73 lines
2.4 KiB
JavaScript
73 lines
2.4 KiB
JavaScript
function checkCSyntax(code) {
|
|
let errors = [];
|
|
let lines = code.split("\n");
|
|
let openBraces = 0;
|
|
|
|
if (!code.match(/^\s*#include\s+<stdio\.h>\s*$/m)) {
|
|
errors.push("Error: Missing or incorrect #include directive.");
|
|
}
|
|
|
|
if (!code.match(/int\s+main\s*\(.*\)\s*\{/)) {
|
|
errors.push("Error: Missing main() function.");
|
|
}
|
|
|
|
if (!code.match(/return\s+0\s*;/)) {
|
|
errors.push("Error: Missing 'return 0;' in main().");
|
|
}
|
|
|
|
let keywords = ["if", "else", "while", "for", "return", "int", "char", "float", "double", "void"];
|
|
let variableDeclarationRegex = /^\s*(int|char|float|double)\s+[a-zA-Z_][a-zA-Z0-9_]*\s*(=\s*[^;]+)?\s*;/;
|
|
let functionCallRegex = /^\s*[a-zA-Z_][a-zA-Z0-9_]*\s*\(.*\)\s*;/;
|
|
let operatorRegex = /^\s*[a-zA-Z_][a-zA-Z0-9_]*\s*(\+\+|--|\+=|-=|\*=|\/=|%=)?\s*;/;
|
|
let controlFlowRegex = /^\s*(if|while|for)\s*\(.*\)\s*\{/;
|
|
|
|
for (let i = 0; i < lines.length; i++) {
|
|
let line = lines[i].trim();
|
|
if (!line) continue;
|
|
|
|
if (line.includes("{")) openBraces++;
|
|
if (line.includes("}")) openBraces--;
|
|
|
|
let words = line.split(/\s+/);
|
|
for (let word of words) {
|
|
if (keywords.includes(word)) continue;
|
|
if (word.match(/^(if|else|while|for|return)$/i)) {
|
|
errors.push(`Error on line ${i + 1}: Misspelled keyword '${word}'. Did you mean '${word.toLowerCase()}'?`);
|
|
}
|
|
}
|
|
|
|
if (variableDeclarationRegex.test(line)) {
|
|
continue;
|
|
}
|
|
|
|
if (functionCallRegex.test(line)) {
|
|
continue;
|
|
}
|
|
|
|
if (line.match(/[a-zA-Z_][a-zA-Z0-9_]*\s*-+\s*;/)) {
|
|
let incorrectOperator = line.match(/[a-zA-Z_][a-zA-Z0-9_]*\s*(-+)\s*;/)[1];
|
|
if (incorrectOperator !== "--") {
|
|
errors.push(`Error on line ${i + 1}: Incorrect operator '${line.trim()}'. Did you mean '${line.trim().replace(/-+;/, "--;")}'?`);
|
|
}
|
|
}
|
|
|
|
if (operatorRegex.test(line)) {
|
|
continue;
|
|
}
|
|
|
|
if (controlFlowRegex.test(line)) {
|
|
continue;
|
|
}
|
|
|
|
if (!line.endsWith(";") && !line.includes("{") && !line.includes("}") && !line.startsWith("#")) {
|
|
errors.push(`Error on line ${i + 1}: Missing semicolon.`);
|
|
}
|
|
}
|
|
|
|
if (openBraces !== 0) {
|
|
errors.push("Error: Mismatched braces `{}`.");
|
|
}
|
|
|
|
return errors.length ? errors : ["Syntax is correct!"];
|
|
}
|