using CodePlay.Core.Interfaces;
using CodePlay.Core.Common;
namespace CodePlay.Core.Parsers;
///
/// Python 解析器
///
public class PythonParser : BaseParser
{
public override LanguageType SupportedLanguage => LanguageType.None; // Python 暂不加入枚举
public override Task ParseAsync(string sourceCode, CancellationToken cancellationToken = default)
{
var tree = CreateSyntaxTree();
tree.SourceCode = sourceCode;
tree.Root = ParseRoot(sourceCode);
tree.Comments = ExtractComments(sourceCode);
return Task.FromResult(tree);
}
private SyntaxNode ParseRoot(string sourceCode)
{
var root = new SyntaxNode { Type = SyntaxNodeType.CompilationUnit, Text = sourceCode };
ExtractClasses(sourceCode, root);
ExtractFunctions(sourceCode, root);
ExtractImports(sourceCode, root);
return root;
}
private void ExtractClasses(string code, SyntaxNode root)
{
var pattern = @"class\s+(\w+)\s*(?:\(([^)]*)\))?";
var matches = System.Text.RegularExpressions.Regex.Matches(code, pattern);
foreach (System.Text.RegularExpressions.Match match in matches)
{
var classNode = new SyntaxNode
{
Type = SyntaxNodeType.Class,
Text = match.Value,
Metadata = new Dictionary
{
["Name"] = match.Groups[1].Value,
["BaseClasses"] = match.Groups[2].Success ? match.Groups[2].Value : null
}
};
root.Children.Add(classNode);
}
}
private void ExtractFunctions(string code, SyntaxNode root)
{
var pattern = @"def\s+(\w+)\s*\(([^)]*)\)";
var matches = System.Text.RegularExpressions.Regex.Matches(code, pattern);
foreach (System.Text.RegularExpressions.Match match in matches)
{
var funcNode = new SyntaxNode
{
Type = SyntaxNodeType.Method,
Text = match.Value,
Metadata = new Dictionary
{
["Name"] = match.Groups[1].Value,
["Parameters"] = match.Groups[2].Value
}
};
root.Children.Add(funcNode);
}
}
private void ExtractImports(string code, SyntaxNode root)
{
var lines = code.Split('\n');
foreach (var line in lines)
{
var trimmed = line.Trim();
if (trimmed.StartsWith("import ") || trimmed.StartsWith("from "))
{
root.Children.Add(new SyntaxNode
{
Type = SyntaxNodeType.Type,
Text = trimmed,
Metadata = { ["Kind"] = "import" }
});
}
}
}
private List ExtractComments(string sourceCode)
{
var comments = new List();
var lines = sourceCode.Split('\n');
for (int i = 0; i < lines.Length; i++)
{
var line = lines[i].Trim();
if (line.StartsWith("#"))
{
comments.Add(new SyntaxComment
{
Type = CommentType.SingleLine,
Text = line.TrimStart('#').Trim(),
LineNumber = i + 1
});
}
}
return comments;
}
}