using Antlr4.Runtime; using MycroForge.Parsing; namespace MycroForge.CLI.CodeGen; public abstract class PythonSourceModifier : PythonParserBaseVisitor { protected CommonTokenStream Stream { get; } protected PythonParser Parser { get; } protected TokenStreamRewriter Rewriter { get; } protected PythonSourceModifier(string source) { var input = new AntlrInputStream(source); var lexer = new PythonLexer(input); Stream = new CommonTokenStream(lexer); Parser = new PythonParser(Stream); Rewriter = new TokenStreamRewriter(Stream); } public abstract string Rewrite(); protected string GetOriginalText(ParserRuleContext context) { // The parser does not necessarily return the original source, // so we return the text from Rewriter.TokenStream, since this is unmodified. return Rewriter.TokenStream.GetText(context); } protected void Rewrite(ParserRuleContext context, params string[] text) { Rewriter.Replace(from: context.start, to: context.Stop, text: string.Join('\n', text)); } }