Antlr4 Javascript Visitor

前端 未结 1 1289
眼角桃花
眼角桃花 2021-01-17 22:51

I\'m currently trying to develope a JavaScript Compiler with the help of an Antlr4 Visitor. I\'ve got this already implemented with Java but cannot figure out how to do this

相关标签:
1条回答
  • 2021-01-17 23:29

    The basic idea behind the visitor is that you have to handle all the logic by yourself. To do this I generated the visitor using antlr. My own visitor overrides all functions that I need to implement my logic.

    1. create lexer, tokens, ...

      var antlr4 = require('antlr4/index');
      var SimpleJavaLexer = require('generated/GrammarLexer');
      var SimpleJavaParser = require('generated/GrammarParser');
      var SimpleJavaVisitor = require('generated/GrammarVisitor');
      var Visitor = require('./Visitor');
      
      var input = "TestInput";
      var chars = new antlr4.InputStream(input);
      var lexer = new GrammarLexer.GrammarLexer(chars);
      var tokens = new antlr4.CommonTokenStream(lexer);
      var parser = new GrammarParser.GrammarParser(tokens);
      var visitor = new Visitor.Visitor();
      parser.buildParseTrees = true;
      var tree = parser.parse();
      
    2. and call your entry function

      visitor.visitTest(tree);
      
    3. inside your new visitor you need to implement your new logic to determine which function to call next (the right context as argument is important)

      var GrammarVisitor =     require('generated/GrammarVisitor').GrammarVisitor;
      
      function Visitor () {
        SimpleJavaVisitor.call(this);
        return this;
      };
      
      Visitor.prototype = Object.create(GrammarVisitor.prototype);
      Visitor.prototype.constructor = Visitor;
      Visitor.prototype.visitTest = function(ctx) {
          // implement logic to determine which function to visit
          // then call next function and with the right context
          this.visitBlock(ctx.block());
      };
      

    I hope you can understand my basic idea. If anybody got any questions just comment.

    0 讨论(0)
提交回复
热议问题