2015年12月29日星期二

Parser Generators: ANTLR vs JavaCC

Parser Generators: ANTLR vs JavaCC

A performance review of two parser generators: Java CC and ANTLR. One of them is a clear winner according to the measurements.

  · Java Zone
 
 Comment (5)
 
Save
 
 9,387 Views
ANTLR (ANother Tool for Language Recognition) is a parser generator developed by Terence Parr, it is extremely versatile and is capable of generating parsers in multiple programming languages, but requires a runtime library.

ANTLR Features:

  • ALL(*) or ALL(k) Parser Generator (an adaptive top down parser with arbitrary token lookahead, ie there is no need to specify the lookahead k)
  • Capable of generate parsers in a number of different programming languages including Java, C#, Python and JavaScript
  • A runtime library is required.
  • A good level of support in the most popular IDEs
  • Version 4 JIT Compiles the parser
  • The lexer, parser and abstract syntax tree can all be generated from a single grammar file.
  • Parse tree is built automatically.
  • Supports parsing modes for mixed language documents.
  • Support for semantic and syntactic predicates.
  • Grammar Definition is EBNF like.
  • A book is available about ANTLR here

Example Syntax

A JSON parser written in ANTLR.
grammar JSONParser;
/*
 * ==============================================
 * ==============================================
 * Parser Rules and AST generation are defined/
 * handled in this section
 * ==============================================
 * ==============================================
 */ 
jsonObject : LBRACE nameValuePairList RBRACE ;
array : LSQR valueList RSQR ;
nameValuePairList : nameValuePair (COMMA nameValuePairList)* ;
nameValuePair : name COLON value ;
name : STRING;
valueList : value (COMMA valueList)* ;
value : (jsonObject | array | STRING | NUMBER | booleanValue) ;
booleanValue : TRUE | FALSE ;
/*
 * ==============================================
 * ==============================================
 * Lexer token deinifitions are defined in this section.
 * ==============================================
 * ==============================================
 */
STRING : '"' STRING_CONTENT '"' ;
TRUE : 'true' ;
FALSE : 'false' ;
NULL : 'null' ;
NUMBER : NUM (EXPONENT)? ;
EXPONENT : ([Ee] ([-+])? ([0-9])+) ;
COLON : ':' ;
COMMA : ',' ;
LBRACE : '{' ;
RBRACE : '}' ;
LSQR : '[' ;
RSQR : ']' ;
NUM : (([-+])? ([0-9])+ | ([-+])? ([0-9])* '.' ([0-9])+) ;
fragment
STRING_CONTENT : (~[\n\r\f\\\"] | '\\' NL | ESCAPE)* ;
fragment
HEX : ([0-9a-fA-F]) ;
fragment
UNICODE: 'u' HEX (HEX (HEX (HEX)?)?)? ;
fragment
ESCAPE : UNICODE | '\\\\' ~[\r\n\f0-9a-f] ;
WS : [ \t]+ -> skip ;
NL : ([\n\r\f])+ -> skip ;

JavaCC

JavaCC (Java Compiler Compiler) was written originally by Dr. Sriram Sankar and Sreenivasa Viswanadha. It is only capable of generating parsers in Java but doesn’t require a runtime library and the parsers it generates are very performant for an LL(k) parsers.

JavaCC Features:

  • LL(k) Parser Generator (a top down parser with arbitrary token lookahead)
  • Can only generate parsers in Java or C/C++.
  • No runtime is required, the generated parser is completely autonomous.
  • The lexer, parser, abstract syntax tree and documentation can all be generated from a single grammar file.
  • Supports parsing modes for mixed language documents.
  • Supports ranges for example a colour in CSS could be defined as “#”(([“0”-“9”,“a”-“f”,“A”-“F”]){3}){1,2}
  • Grammar Definition is Java like.
  • A book is available about JAVACC here

Example Syntax

A JSON Parser written in JavaCC
/**
 * JavaCC JSON Parser
 */
options {
   JDK_VERSION = "1.6";
   STATIC = false;
   UNICODE_INPUT = true;
   MULTI = true;
   VISITOR = true;
   TRACK_TOKENS = true;
   LOOKAHEAD=3;
   NODE_USES_PARSER=true;
   NODE_FACTORY = true;
}
/*
    Class definition begins here:
    Code added in this section is included as part of the generated parser.
*/
PARSER_BEGIN(JSONParser)
package com.brett.jsonparser.javacc;
import java.io.Reader;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;
public class JSONParser {
private static final Logger logger = Logger.getLogger(JSONParser.class);
public static void main(String[] args) {
try {
String filename = System.getProperty("TEST_FILE_NAME");
Reader reader = new InputStreamReader(new FileInputStream(filename), "utf-8");
JSONParser p = new JSONParser(reader);
try {
SimpleNode node = p.value();
                node.dump(">");
} catch (ParseException e) {
    e.printStackTrace();
logger.error("Failed to parse because:", e);
}
 } catch (IOException e) {
     e.printStackTrace();
logger.error("An IOException occurred while trying to parse the file", e);
 }
}
}
PARSER_END(JSONParser)
/*
    ==============================================================================================
    Lexer token deinifitions are defined in this section.
    ==============================================================================================
*/
SKIP : 
{
< WS : ([" ","\t"]) > |
< NL : (["\n","\r","\f"])+ >
}
TOKEN :
{
< #HEX: (["0"-"9","a"-"f","A"-"F"]) > |
    < #UNICODE: "u" ((<HEX>)){4} > |
    < #ESCAPE: <UNICODE> | "\\\\" ~["\r","\n","\f","0"-"9","a"-"f"] > |
< STRING: "\"" <STRING_CONTENT> "\"" > |
< #STRING_CONTENT: (~["\n","\r","\f","\\","\""] | "\\" <NL>|<ESCAPE>)* > |
< TRUE: "true" > |
< FALSE: "false" > |
< NULL: "null" > |
< NUMBER: <NUM>(<EXPONENT>)? > |
< EXPONENT: (["E","e"] (["-","+"])? (["0"-"9"])+) > |
< COLON: ":" > |
< COMMA: "," > |
< LBRACE: "{" > |
< RBRACE: "}" > |
< LSQR: "[" > |
< RSQR: "]" > |
< NUM: ((["-","+"])? (["0"-"9"])+ | (["-","+"])? (["0"-"9"])* "." (["0"-"9"])+) >
}
/*
    ==============================================================================================
    Parser Rules and AST generation are defined/handled in this section
    ==============================================================================================
*/
void jsonObject() #JSONObject : {}
{
<LBRACE> nameValuePairList() <RBRACE>
}
void array() #Array : {}
{
<LSQR> valueList() <RSQR>
}
void nameValuePairList() #NameValuePairList : {}
{
nameValuePair() (<COMMA> nameValuePairList())*
}
void nameValuePair() #NameValuePair : {}
{
name() <COLON> value()
}
void name() #Name : {}
{
<STRING> 
}
void valueList() #ValueList : {}
{
value() ((<COMMA>) valueList())*
}
SimpleNode value() #Value : {}
{
(jsonObject() | array() | <STRING> | <NUMBER> | booleanValue())
{ return jjtThis; }
}
void booleanValue() #BooleanValue : {}
{
<TRUE> | <FALSE>
}

Benchmarks

The JSON file being parsed during the benchmark is a free example from https://adobe.github.io/Spry/samples/ and is shown here below:
[
  {
    "id": "0001",
    "type": "donut",
    "name": "Cake",
    "ppu": 0.55,
    "batters": {
      "batter": [
        {
          "id": "1001",
          "type": "Regular"
        },
        {
          "id": "1002",
          "type": "Chocolate"
        },
        {
          "id": "1003",
          "type": "Blueberry"
        },
        {
          "id": "1004",
          "type": "Devil's Food"
        }
      ]
    },
    "topping": [
      {
        "id": "5001",
        "type": "None"
      },
      {
        "id": "5002",
        "type": "Glazed"
      },
      {
        "id": "5005",
        "type": "Sugar"
      },
      {
        "id": "5007",
        "type": "Powdered Sugar"
      },
      {
        "id": "5006",
        "type": "Chocolate with Sprinkles"
      },
      {
        "id": "5003",
        "type": "Chocolate"
      },
      {
        "id": "5004",
        "type": "Maple"
      }
    ]
  }
]

Both parsers where launched and profiled using the same machine, the same profiler and JVM. The results are displayed below:
Parser Generator
Time (ms)
Avg. Time (ms)
Invocations
ANTLR
179,105
1,791
100
JAVACC
3,312
33
100
Image title

Summary
JavaCC is clearly more performant than ANTLR however if performance is not an issue, both parser generators are valid tools. The syntax is very similar, both have books available to bring you up to speed. Each have pros and cons, your decision which one to use depends on your needs and on your personal preference. Obviously it also depends on what your target programming language will be for the project where you intend to use the parser.

2015年11月25日星期三

hive 1.2.1中的子查询嵌套使用相同别名引起的问题的解决

背景:在升级社区的hive 1.2.1过程中发现,如果使用子查询嵌套,里外别名相同时,会出现结果错误的情况。
如:

select
                s.*
            from
            (
                select
                1000 as qq_no               
            )s  join
            (
                select
                    a.qq_no
                from
                (
                    select qq_no from t_om_qqbook_ykklcy_qqno where ds=201510  and qq_no>0
                )a left outer join
                (
                    select qq_no from t_mm_qqbook_b1_blacklist where ds=201510
                )b on a.qq_no=b.qq_no
                where b.qq_no is null
            )b on s.qq_no=b.qq_no
            limit 10;



定位问题:修改外层别名,结果正确;

select
                s.*
            from
            (
                select
                1000 as qq_no               
            )s  join
            (
                select
                    a.qq_no
                from
                (
                    select qq_no from t_om_qqbook_ykklcy_qqno where ds=201510  and qq_no>0
                )a left outer join
                (
                    select qq_no from t_mm_qqbook_b1_blacklist where ds=201510
                )b on a.qq_no=b.qq_no
                where b.qq_no is null
            )t on s.qq_no=t.qq_no
            limit 10;

且修改内存列别名结果依然正确


select
                s.*
            from
            (
                select
                1000 as qq_no               
            )s  join
            (
                select
                    a.qq_no as qq_nox
                from
                (
                    select qq_no from t_om_qqbook_ykklcy_qqno where ds=201510  and qq_no>0
                )a left outer join
                (
                    select qq_no from t_mm_qqbook_b1_blacklist where ds=201510
                )b on a.qq_no=b.qq_no
                where b.qq_no is null
            )b on s.qq_no=b.qq_nox
            limit 10;
 跟踪explain extended 解析步骤发现
正常结果的步骤里有predicate

  Stage: Stage-2
    Map Reduce
      Map Operator Tree:
          TableScan
            alias: t_om_qqbook_ykklcy_qqno
            Statistics: Num rows: 1611465 Data size: 15052568 Basic stats: COMPLETE Column stats: NONE
            GatherStats: false
            Filter Operator
              isSamplingPred: false
              predicate: ((qq_no > 0) and qq_no is not null) (type: boolean)
              Statistics: Num rows: 268578 Data size: 2508766 Basic stats: COMPLETE Column stats: NONE
              Select Operator
                expressions: qq_no (type: bigint)
                outputColumnNames: _col0
                Statistics: Num rows: 268578 Data size: 2508766 Basic stats: COMPLETE Column stats: NONE
                Reduce Output Operator
                  key expressions: _col0 (type: bigint)
                  sort order: +
                  Map-reduce partition columns: _col0 (type: bigint)
                  Statistics: Num rows: 268578 Data size: 2508766 Basic stats: COMPLETE Column stats: NONE
                  tag: 0
                  auto parallelism: false
          TableScan
            alias: t_mm_qqbook_b1_blacklist
            Statistics: Num rows: 3311453 Data size: 33021350 Basic stats: COMPLETE Column stats: NONE
            GatherStats: false
            Filter Operator
              isSamplingPred: false
              predicate: qq_no is not null (type: boolean)
              Statistics: Num rows: 1655727 Data size: 16510679 Basic stats: COMPLETE Column stats: NONE
              Select Operator
                expressions: qq_no (type: bigint)
                outputColumnNames: _col0
                Statistics: Num rows: 1655727 Data size: 16510679 Basic stats: COMPLETE Column stats: NONE
                Reduce Output Operator
                  key expressions: _col0 (type: bigint)
                  sort order: +
                  Map-reduce partition columns: _col0 (type: bigint)
                  Statistics: Num rows: 1655727 Data size: 16510679 Basic stats: COMPLETE Column stats: NONE
                  tag: 1
                  auto parallelism: false
      Path -> Alias:
        hdfs://10.179.18.50:9000/user/hive/warehouse/u_wsd.db/t_mm_qqbook_b1_blacklist/ds=201510 [t:b:t_mm_qqbook_b1_blacklist]
        hdfs://10.179.18.50:9000/user/hive/warehouse/u_wsd.db/t_om_qqbook_ykklcy_qqno/ds=201510 [t:a:t_om_qqbook_



错误结果步骤里没有


  Stage: Stage-2
    Map Reduce
      Map Operator Tree:
          TableScan
            alias: t_om_qqbook_ykklcy_qqno
            Statistics: Num rows: 1 Data size: 0 Basic stats: PARTIAL Column stats: NONE
            GatherStats: false
            Filter Operator
              isSamplingPred: false
              predicate: false (type: boolean)
              Statistics: Num rows: 1 Data size: 0 Basic stats: PARTIAL Column stats: NONE
              Select Operator
                expressions: qq_no (type: bigint)
                outputColumnNames: _col0
                Statistics: Num rows: 1 Data size: 0 Basic stats: PARTIAL Column stats: NONE
                Reduce Output Operator
                  key expressions: _col0 (type: bigint)
                  sort order: +
                  Map-reduce partition columns: _col0 (type: bigint)
                  Statistics: Num rows: 1 Data size: 0 Basic stats: PARTIAL Column stats: NONE
                  tag: 0
                  auto parallelism: false
          TableScan
            alias: t_mm_qqbook_b1_blacklist
            Statistics: Num rows: 1 Data size: 0 Basic stats: PARTIAL Column stats: NONE
            GatherStats: false
            Filter Operator
              isSamplingPred: false
              predicate: false (type: boolean)
              Statistics: Num rows: 1 Data size: 0 Basic stats: PARTIAL Column stats: NONE
              Select Operator
                expressions: qq_no (type: bigint)
                outputColumnNames: _col0
                Statistics: Num rows: 1 Data size: 0 Basic stats: PARTIAL Column stats: NONE
                Reduce Output Operator
                  key expressions: _col0 (type: bigint)
                  sort order: +
                  Map-reduce partition columns: _col0 (type: bigint)
                  Statistics: Num rows: 1 Data size: 0 Basic stats: PARTIAL Column stats: NONE
                  tag: 1
                  auto parallelism: false

断定是predicate过程发生错误。
跟踪日志:
打开调试日志

发现正常的不同别名日志里没有替换b.qq_no:
同别名的有发生替换:
所有在后续的替换中发生不同转换:
不同别名:
同别名:

再定位到相应代码,找到原因:
       发生的原因是当嵌套的子查询别名一样时,而且输出的列名一样时,当里层的子查询产生Constant predicate替换时
外层的子查询在查找相应的表+列时能找到里层子查询的表+列;
可但是,外层的b.qq_no并不是里层的b.qq_no生成的,而是a.qq_no生成的,所以需要检查以下columnExprMap,
且需要确认如果里层子查询是select 1001 as qq_no ...时同样需要检测constant的值是否一样。
总之:是由于外面的子查询别名在比对上层的Filter Operater的opToConstantExprs时发现了相同的表+列;但实际上外层取的列已经是一个新的ExprNode
修改代码


打完收工。