使用antlr4, 用ts/js还原protobuf生成的jav

2017-03-22  本文已影响0人  ThirstyZebra

目录:

现在开始解释java代码, 首先下载最新的java grammar文件

https://github.com/antlr/grammars-v4/blob/master/java/Java.g4

直接拿过来用就行了, 我们仍然使用visitor来解释.

命令如下

//在./src/antlr/目录执行
antlr4ts ./Java.g4 -o Java -visitor 

目录中文件大致如下:

./src/antlr
├── Java
│   ├── Java.tokens
│   ├── JavaLexer.tokens
│   ├── JavaLexer.ts
│   ├── JavaListener.ts
│   ├── JavaParser.ts
│   └── JavaVisitor.ts
├── Java.g4

test002.ts代码如下

import {ANTLRInputStream, CommonTokenStream} from "antlr4ts";
import {JavaLexer} from "./antlr/Java/JavaLexer";
import {CompilationUnitContext, JavaParser} from "./antlr/Java/JavaParser";
import {fs} from "mz";


// Create the lexer and parser

//get java file

async function myReadfile() {
    try {
        return await fs.readFile('./../src/ref/hello.java', "utf-8");
    }
    catch (err) {
        console.error(err)
    }
}


myReadfile().then((data) => {
    beginParse(data);
});


function beginParse(data) {

    let inputStream = new ANTLRInputStream(data);
    let lexer = new JavaLexer(inputStream);
    let tokenStream = new CommonTokenStream(lexer);
    let parser = new JavaParser(tokenStream);

    // Parse the input, where `compilationUnit` is whatever entry point you defined
    let result: CompilationUnitContext = parser.compilationUnit();

    console.log(result);

    // console.log(value);
}

先读出utf-8 的java代码, 然后还是按照之前的套路来解析

按照操作, 打印出CompilationUnitContext如下

CompilationUnitContext {
  _parent: undefined,
  invokingState: -1,
  _start: 
   CommonToken {
     _line: 1,
     _charPositionInLine: 0,
     _channel: 0,
     index: 0,
     _text: undefined,
     _type: 35,
     source: { source: [Object], stream: [Object] },
     start: 0,
     stop: 5 },
  children: 
   [ TypeDeclarationContext {
       _parent: [Circular],
       invokingState: 211,
       _start: [Object],
       children: [Object],
       _stop: [Object] },
     TerminalNode { _symbol: [Object], _parent: [Circular] } ],
  _stop: 
   CommonToken {
     _line: 5,
     _charPositionInLine: 1,
     _channel: 0,
     index: 26,
     _text: undefined,
     _type: -1,
     source: { source: [Object], stream: [Object] },
     start: 118,
     stop: 117 } }

测试用的hello.java如下, 放在这里方便查看

public class HelloWorld {
   public static void main(String[] args) {
      System.out.println("Hello, World");
   }
}

打印一下ast的图形显示如下:

这个必须翻译成java 运行时, 才可以运行, 具体查询antlr新手教程

hello.java AST

好了, antlr非常完美的自动解析出了ast. 试一试要解析的java

msg_svc$PbGetMsgResp.png
上一篇下一篇

猜你喜欢

热点阅读