Search in sources :

Example 1 with AntlrProgramBuilder

use of org.beetl.core.AntlrProgramBuilder in project beetl2.0 by javamonkey.

the class DefaultTemplateEngine method createProgram.

@Override
public Program createProgram(Resource resource, Reader reader, Map<Integer, String> textMap, String cr, GroupTemplate gt) {
    ANTLRInputStream input;
    try {
        input = new ANTLRInputStream(reader);
    } catch (IOException e) {
        // 不可能发生
        throw new RuntimeException(e);
    }
    BeetlLexer lexer = new BeetlLexer(input);
    lexer.removeErrorListeners();
    lexer.addErrorListener(syntaxError);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    BeetlParser parser = new BeetlParser(tokens);
    // 测试代码
    parser.setErrorHandler(antlrErrorStrategy);
    // 
    ProgContext tree = parser.prog();
    // begin parsing at init rule
    AntlrProgramBuilder pb = getAntlrBuilder(gt);
    ProgramMetaData data = pb.build(tree);
    Program program = new Program();
    program.metaData = data;
    program.res = resource;
    program.rs = resource;
    program.gt = gt;
    program.metaData.staticTextArray = new Object[textMap.size()];
    program.metaData.lineSeparator = cr;
    int i = 0;
    Configuration conf = gt.getConf();
    String charset = conf.getCharset();
    boolean byteOut = conf.isDirectByteOutput();
    for (Entry<Integer, String> entry : textMap.entrySet()) {
        if (byteOut) {
            try {
                program.metaData.staticTextArray[i++] = entry.getValue().getBytes(charset);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        } else {
            program.metaData.staticTextArray[i++] = entry.getValue().toCharArray();
        }
    }
    return program;
}
Also used : CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) Program(org.beetl.core.statement.Program) Configuration(org.beetl.core.Configuration) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) BeetlLexer(org.beetl.core.parser.BeetlLexer) BeetlParser(org.beetl.core.parser.BeetlParser) ProgContext(org.beetl.core.parser.BeetlParser.ProgContext) ProgramMetaData(org.beetl.core.statement.ProgramMetaData) ANTLRInputStream(org.antlr.v4.runtime.ANTLRInputStream) AntlrProgramBuilder(org.beetl.core.AntlrProgramBuilder)

Aggregations

IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 ANTLRInputStream (org.antlr.v4.runtime.ANTLRInputStream)1 CommonTokenStream (org.antlr.v4.runtime.CommonTokenStream)1 AntlrProgramBuilder (org.beetl.core.AntlrProgramBuilder)1 Configuration (org.beetl.core.Configuration)1 BeetlLexer (org.beetl.core.parser.BeetlLexer)1 BeetlParser (org.beetl.core.parser.BeetlParser)1 ProgContext (org.beetl.core.parser.BeetlParser.ProgContext)1 Program (org.beetl.core.statement.Program)1 ProgramMetaData (org.beetl.core.statement.ProgramMetaData)1