-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonSyntaxChecker.cs
More file actions
42 lines (36 loc) · 1.1 KB
/
Copy pathPythonSyntaxChecker.cs
File metadata and controls
42 lines (36 loc) · 1.1 KB
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
using IronPython.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using System.Collections.Generic;
namespace RYCBEditorX.Utils;
public static class PythonSyntaxChecker
{
private static readonly ScriptEngine Engine = Python.CreateEngine();
public static List<PyCodeErr> CheckSyntax(string code)
{
var errors = new List<PyCodeErr>();
try
{
var source = Engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements);
source.Compile();
}
catch (SyntaxErrorException ex)
{
errors.Add(new PyCodeErr
{
Type = PyCodeErr.ErrorType.SyntaxError,
Message = ex.Message,
LineNumber = ex.Line,
CodeSnippet = GetLine(code, ex.Line)
});
}
return errors;
}
private static string GetLine(string code, int lineNumber)
{
var lines = code.Split('\n');
return lineNumber > 0 && lineNumber <= lines.Length
? lines[lineNumber - 1].Trim()
: string.Empty;
}
}