使用Antlr4的TokenStreamRewriter修改內容

schizobulia發表於2022-07-10

需求:在css中使用變數控制部分屬性的值

  • 專案中配置antlr版本
<dependency>

    <groupId>org.antlr</groupId>

    <artifactId>antlr4-runtime</artifactId>

    <version>4.9.3</version>

</dependency>
  • 使用官方css.g4 demo生成api
$ antlr4 -no-listener -visitor css.g4
  • 使用TokenStreamRewriter修改
package css;

import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.TokenStreamRewriter;
import org.antlr.v4.runtime.tree.ParseTree;

public class Css {
    public static void main(String[] args) {
        CssLexer lexer = new CssLexer(CharStreams.fromString(".b { color: red; } .c { color: blue; }"));
        CommonTokenStream stream = new CommonTokenStream(lexer);
        CssParser parser = new CssParser(stream);
        ParseTree tree = parser.stylesheet();
        EvalVisitor evalVisitor = new EvalVisitor(stream);
        evalVisitor.visit(tree);
        System.out.println(evalVisitor.rewriter.getText());
    }
}

class EvalVisitor extends CssBaseVisitor<String> {
    TokenStreamRewriter rewriter;
    public EvalVisitor(CommonTokenStream tokenStream) {
        rewriter = new TokenStreamRewriter(tokenStream);
    }

    @Override
    public String visitExpr(CssParser.ExprContext ctx) {
        String text = ctx.getText();
        if (text.equals("red")) {
            rewriter.replace(ctx.getStart(), ctx.getStop(), "#ff0000");
        }
        return super.visitExpr(ctx);
    }
}

}

```

完整程式碼:github.com/schizobulia/antlr4_demo...

目前我司在招高階前端、ios、android開發(完全遠端)。大佬們有興趣的發簡歷

郵箱:MjgzMzMyNDUyOEBxcS5jb20=

如果你喜歡我的作品,請考慮贊助,以保持它們的可持續性。

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章