File size: 5,973 Bytes
d6a8383
 
ca2360f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3713433
 
 
 
ca2360f
 
 
3713433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6a8383
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Immediate, conservative editing hint, not a C parser. A newline alone is
// legal in C: incomplete expressions/control headers must not trigger a quack.
const STANDARD_FUNCTIONS = ["printf", "scanf", "puts", "getchar", "fgets", "malloc", "free", "strlen"];
const TYPE = "(?:const\\s+)?(?:unsigned\\s+|signed\\s+)?(?:long\\s+long\\s+|long\\s+|short\\s+)?(?:void|char|int|float|double|size_t)";

function editDistance(left, right) {
  const row = Array.from({ length: right.length + 1 }, (_, index) => index);
  for (let i = 1; i <= left.length; i++) {
    let diagonal = row[0]; row[0] = i;
    for (let j = 1; j <= right.length; j++) {
      const previous = row[j];
      row[j] = Math.min(row[j] + 1, row[j - 1] + 1, diagonal + (left[i - 1] === right[j - 1] ? 0 : 1));
      diagonal = previous;
    }
  }
  return row[right.length];
}

function functionHint(line, lineNumber, rawLine = line) {
  // A function declaration has a stricter grammar than a call. Detect an
  // invalid name or parameter as soon as the offending character is typed.
  const declaration = line.match(new RegExp(`^\\s*${TYPE}\\s+([^\\s(]*)\\s*\\((.*)$`));
  if (declaration) {
    const [, name, parameters] = declaration;
    if (name && !/^[A-Za-z_]\w*$/.test(name)) return { line: lineNumber, message: "A function name must start with a letter or underscore." };
    const badParameter = parameters.match(new RegExp(`(?:^|,)\\s*${TYPE}\\s+(\\d\\w*)$`));
    if (badParameter) return { line: lineNumber, message: `Parameter '${badParameter[1]}' cannot start with a number.` };
    if (/;\s*$/.test(parameters)) return { line: lineNumber, message: "Use a comma between function parameters." };
  }
  // Do not flag user-defined functions. For familiar C library calls, a close
  // misspelling is almost always a typo (for example scnaf instead of scanf).
  const calls = [...line.matchAll(/\b([A-Za-z_]\w*)\s*\(/g)];
  const call = calls.at(-1)?.[1];
  if (call && !STANDARD_FUNCTIONS.includes(call) && call.length >= 3) {
    const intended = STANDARD_FUNCTIONS.find((name) => editDistance(call, name) <= 2);
    if (intended) return { line: lineNumber, message: `Unknown function '${call}'. Did you mean '${intended}'?` };
  }
  // scanf is easy to mistype: a format string followed immediately by an
  // address needs a comma. This is safe to flag before the closing parenthesis.
  if (line.trim() && /\bscanf\s*\([^)]*"(?:\\.|[^"\\])*"\s*&/.test(rawLine)) return { line: lineNumber, message: "Add a comma between the scanf format and its parameter." };
  return null;
}

export function syntaxHintWhileEditing(source, caret) {
  const prefix = source.slice(0, caret).replace(/"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|\/\/[^\n]*|\/\*[\s\S]*?(?:\*\/|$)/g,
    (part) => part.replace(/[^\n]/g, " "));
  const lines = prefix.split("\n"), current = lines.at(-1);
  const rawCurrent = source.slice(0, caret).split("\n").at(-1);
  const immediateFunctionHint = functionHint(current, lines.length, rawCurrent);
  if (immediateFunctionHint) return immediateFunctionHint;
  if (!/^\s*[A-Za-z_]\w*/.test(current) || /^\s*#/.test(current)) return null;
  const indentation = (line) => line.match(/^\s*/)[0].replace(/\t/g, "    ").length;
  const stack = [];
  for (let n = 0; n < lines.length - 1; n++) {
    if (/^\s*#/.test(lines[n])) continue;
    for (const char of lines[n]) {
      if (char === "{") stack.push({ line: n, indent: indentation(lines[n]), initializer: /=\s*\{/.test(lines[n]) });
      if (char === "}") stack.pop();
    }
  }
  const open = stack.at(-1);
  if (!open || stack.length < 2 || open.initializer) return null;
  const previous = lines.slice(open.line + 1, -1).filter((line) => line.trim()).at(-1);
  // Outdenting after a completed, indented block statement strongly suggests
  // a missing }. Do not complain while the user is still typing indentation,
  // a closing brace, a comment, or a multiline expression.
  if (!previous || !/[;}]\s*$/.test(previous) || indentation(previous) <= open.indent || indentation(current) > open.indent) return null;
  return { line: lines.length, message: "Possible missing closing brace before this line." };
}

export function syntaxHintAtNewline(source, caret) {
  const tail = source.slice(caret).split("\n", 1)[0];
  if (tail.trim()) return null; // Enter in the middle of an existing line.
  const prefix = source.slice(0, caret);
  const lineNumber = prefix.split("\n").length;
  const rawLine = prefix.split("\n").at(-1);
  if (!rawLine.trim() || /^\s*#/.test(rawLine)) return null;
  const clean = prefix.replace(/"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|\/\/[^\n]*|\/\*[\s\S]*?(?:\*\/|$)/g,
    (part) => /^["']/.test(part) ? "0" + part.slice(1).replace(/[^\n]/g, " ") : part.replace(/[^\n]/g, " "));
  // Ignore complete and continued preprocessor directives.
  let directive = false;
  const code = clean.split("\n").map((line) => {
    if (directive || /^\s*#/.test(line)) { directive = /\\\s*$/.test(line); return " ".repeat(line.length); }
    return line;
  }).join("\n");
  const line = code.split("\n").at(-1).trim();
  if (!line) return null;
  const stack = [];
  for (let i = 0; i < code.length; i++) {
    const c = code[i];
    if ("([{".includes(c)) {
      stack.push({ char: c, initializer: c === "{" && /(?:=|(?:=|return)\s*\([^()]*\))\s*$/.test(code.slice(0, i)) });
    } else if (")]}".includes(c)) {
      const expected = { ")": "(", "]": "[", "}": "{" }[c];
      if (stack.at(-1)?.char !== expected) return { line: lineNumber, message: "Check this closing bracket." };
      stack.pop();
    }
  }
  if (/[;{}:,\\+\-*/%=<>!&|?.]$/.test(line) && !/(?:\+\+|--)$/.test(line)) return null;
  if (!stack.length || stack.some((entry) => entry.char !== "{" || entry.initializer)) return null;
  if (/^(?:if|for|while|switch)\s*\(/.test(line) || /^(?:else|do)\s*$/.test(line)) return null;
  return { line: lineNumber, message: "Possible missing semicolon at the end of this statement." };
}