zkt25/sk1/app/pythonSyntaxChecker.js
2025-04-29 19:12:53 +02:00

41 lines
1.4 KiB
JavaScript

function checkPythonSyntax(code) {
let errors = [];
let lines = code.split("\n");
let keywords = ["if", "else", "while", "for", "def", "return", "print"];
for (let i = 0; i < lines.length; i++) {
let line = lines[i].trim();
if (!line) continue;
let words = line.split(/\s+/);
for (let word of words) {
if (keywords.includes(word)) continue;
if (word.match(/^(if|else|while|for|def|return|print)$/i)) {
errors.push(`Error on line ${i + 1}: Misspelled keyword '${word}'. Did you mean '${word.toLowerCase()}'?`);
}
}
if (line.startsWith("if ") && !line.includes(":")) {
errors.push(`Error on line ${i + 1}: Missing ':' after 'if'.`);
}
if (line.startsWith("while ") && !line.includes(":")) {
errors.push(`Error on line ${i + 1}: Missing ':' after 'while'.`);
}
if (line.startsWith("for ") && !line.includes(":")) {
errors.push(`Error on line ${i + 1}: Missing ':' after 'for'.`);
}
if (line.startsWith("def ") && !line.includes(":")) {
errors.push(`Error on line ${i + 1}: Missing ':' after 'def'.`);
}
if (line.startsWith("print(") && !line.match(/print\(["'].*["']\)/)) {
errors.push(`Error on line ${i + 1}: Strings in print() must be enclosed in quotes.`);
}
}
return errors.length ? errors : ["Syntax is correct!"];
}