使用Antlr實現運算式引擎

來源:互聯網
上載者:User

上周末嘗試使用Antlr產生C#語言的運算式引擎,目前已經可以支援基本運算.主要思路是把運算式解析成運算元和函數(操作符也作為函數看待)兩種類型節點,主要部分類圖如下:

GrandExpr.g檔案內容如下:

grammar GrandExpr;options {  output=AST;  ASTLabelType=CommonTree; // language=CSharp;}tokens{INDEX;MEMBERACCESS;CALL;}expr:logicalOrExpr;logicalOrExpr :logicalAndExpr (OR logicalAndExpr)* ;                        logicalAndExpr:equalityExpr (AND equalityExpr)*  ;                        equalityExpr:relationalExpr ((EQUALS|NOTEQUALS)^ relationalExpr)*;relationalExpr:additiveExpr ((LT|LTEQ|GT|GTEQ)^ additiveExpr)? ;  additiveExpr:multiplyExpr ((PLUS|MINUS)^ multiplyExpr)*  ;multiplyExpr  :powExpr ((a=MUL| a=DIV | a=MOD) powExpr)*    ;   powExpr   :unaryExpr (POWER unaryExpr)?    ;   unaryExpr:  (PLUS | MINUS | NOT) unaryExpr  |  memberExpr ;       memberExpr   :basicExpr (memberAccessExpr)*  (indexerExpr)?   ;basicExpr: parenExpr | literal |  memberFunctionExpr;          parenExpr    :LPAREN! expr  RPAREN!   ;    literal   : numbericLiteral  | stringLiteral   ;       numbericLiteral  :  INTEGER_LITERAL   | DECIMAL_LITERAL    | DATETIME_LITERAL   ;   stringLiteral  : STRING_LITERAL     ;      memberAccessExpr:'.' memberFunctionExpr -> ^(MEMBERACCESS memberFunctionExpr);memberFunctionExpr:fieldPropertyExpr | methodExpr;fieldPropertyExpr:IDENTIFIER;   methodExpr:IDENTIFIER LPAREN (argument (COMMA argument)*)? RPAREN -> ^(CALL IDENTIFIER argument*);    indexerExpr:LBRACKET argument (COMMA argument)* RBRACKET -> ^(INDEX argument+);argument   : expr   ;      AND:'and';OR: 'or';NOT: 'not';COMMA : ','  ;PLUS: '+'  ;MINUS: '-';MUL: '*'  ;DIV: '/'  ;MOD: '%';POWER: '^';EQUALS:'=';NOTEQUALS :'!=' | '<>';LT:'<';LTEQ:'<=';GT:'>';GTEQ:'>=';LPAREN:'(';RPAREN:')';LBRACKET:'[';RBRACKET:']';DATETIME_LITERAL: '\'' STRING_LITERAL '\'';STRING_LITERAL:'"' (~'"')* '"';IDENTIFIER:LETTER (LETTER|Digit)*;fragmentLETTER:'A'..'Z'|'a'..'z'|'_';DECIMAL_LITERAL:   (INTEGER_LITERAL)? '.' Digit* Exponent? ;fragmentExponent : ('e'|'E') INTEGER_LITERAL;INTEGER_LITERAL : Digit+ ;fragmentDigit:'0'..'9';/* Ignore white spaces */WS:  (' '|'\r'|'\t'|'\u000C'|'\n') {$channel=HIDDEN;};

 

 

歡迎轉載,轉載請註明:轉載自周金根 [ http://zhoujg.cnblogs.com/ ]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.