commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
8e9a1a2ea72e87e2f2a74b366cf830818c122d49
emailaddress/emailaddress.g4
emailaddress/emailaddress.g4
/* BSD License Copyright (c) 2013, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar emailaddress; emailaddress : mailbox | group ; group : phrase ':' mailbox* ';'; mailbox : addrspec | (phrase routeaddr ); routeaddr : '<' route* addrspec '>'; route : '@' domain ':'; addrspec : localpart '@' domain; localpart : word ('.' word)*; domain : subdomain ('.' subdomain)*; subdomain : domainref | domainliteral; domainref : atom; phrase : word+; word : atom | quotedstring; lwspchar : SPACE | TAB; lwsp : (CRLF? lwspchar)+; delimeters : SPECIALS | lwsp | comment; //text // : CHAR+; atom : CHAR+; quotedpair : '\\' CHAR; domainliteral : '[' (DTEXT | quotedpair)* ']'; quotedstring : '\'' (QTEXT | quotedpair)* '\''; comment : '(' (CTEXT | quotedpair | comment)* ')'; CHAR : [\u0000-\u0127]; ALPHA : [\u0065-\u0090]; DIGIT : [\u0048-\u0057]; CTL : [\u0000-\u0031]; CR : '\n'; LF : '\r'; SPACE : ' '; HTAB : '\t'; CRLF : '\r\n'; SPECIALS : '(' | ')' | '<' | '>' | '@' | ',' | ';' | ':' | '\\' | '\''| '.' | '[' | ']' ; QUOTE : '"'; QTEXT : ~[\r\n]; DTEXT : ~[[\]\n\\]; CTEXT : ~[()\n\\];
/* BSD License Copyright (c) 2013, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar emailaddress; emailaddress : mailbox | group ; group : phrase ':' mailbox* ';'; mailbox : addrspec | (phrase routeaddr ); routeaddr : '<' route* addrspec '>'; route : '@' domain ':'; addrspec : localpart '@' domain; localpart : word ('.' word)*; domain : subdomain ('.' subdomain)*; subdomain : domainref | domainliteral; domainref : atom; phrase : word+; word : atom | quotedstring; lwspchar : SPACE | HTAB; lwsp : (CRLF? lwspchar)+; delimeters : SPECIALS | lwsp | comment; //text // : CHAR+; atom : CHAR+; quotedpair : '\\' CHAR; domainliteral : '[' (DTEXT | quotedpair)* ']'; quotedstring : '\'' (QTEXT | quotedpair)* '\''; comment : '(' (CTEXT | quotedpair | comment)* ')'; CHAR : [\u0000-\u0127]; ALPHA : [\u0065-\u0090]; DIGIT : [\u0048-\u0057]; CTL : [\u0000-\u0031]; CR : '\n'; LF : '\r'; SPACE : ' '; HTAB : '\t'; CRLF : '\r\n'; SPECIALS : '(' | ')' | '<' | '>' | '@' | ',' | ';' | ':' | '\\' | '\''| '.' | '[' | ']' ; QUOTE : '"'; QTEXT : ~[\r\n]; DTEXT : ~[[\]\n\\]; CTEXT : ~[()\n\\];
fix the lwsp-char rule.
emailaddress: fix the lwsp-char rule. According to the RFC 822 standard, a linear whitespace character should either be a space or a horizontal tab. However, the current grammar tries to match on the TAB lexer rule (which is not even defined). The patch fixes this.
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
28ed148b4f74b304ec81e110cff2e565b7239ec2
src/antlr/symLexer.g4
src/antlr/symLexer.g4
lexer grammar symLexer; @lexer::members { // add members to generated symParser String stops = " \t\n"; } // standard namespaces NS_CLJ_CORE : 'clojure.core' ; NS_CLJ_LANG : 'clojure.lang' ; // ...etc... // specials SPECIAL : DEF | DEFN | OR ; DEF : 'def' ; DEFN : 'defn' ; OR : 'or' ; // ...etc... // kernel/prelude functions PREDEF : LIST | MAP | CONJ ; LIST : 'list' ; MAP : 'map' ; CONJ : 'conj' ; OP : ADD | SUB | MUL | DIV | EQ ; ADD : '+' {stops.contains(Character.toString((char)_input.LA(1)))}? ; SUB : '-' {stops.contains(Character.toString((char)_input.LA(1)))}? ; MUL : '*' {stops.contains(Character.toString((char)_input.LA(1)))}? ; DIV : '/' {stops.contains(Character.toString((char)_input.LA(1)))}? ; EQ : '=' {stops.contains(Character.toString((char)_input.LA(1)))}? ; ID_NS : CHAR_START (LETTER | DIGIT | HARF)* ; ID_NM : CHAR_START (LETTER | DIGIT | HARF)* {' '==(char)_input.LA(1)}? ; fragment CHAR_START : LETTER | HARF | ':' ; fragment LETTER : [a-zA-Z] ; NUMERAL : DIGIT+ ; fragment DIGIT : [0-9] ; // HURUF (sg. HARF) = printable ascii except macro chars, ',' // all: ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~ // legal: ! # $ % & ' * + - . : < = > ? \ _ ` | fragment HARF : [!#$%&'*+-.\<=>?_|] ; SLASH : '/' ; LPAREN : '(' ; RPAREN : ')' ; LBRACK : '[' ; RBRACK : ']' ; // SP : ' '; WS : [ \t\r\n\u000C\u2028]+ -> skip ; COMMENT : ';' ~[\r\n]* -> skip ;
lexer grammar symLexer; @lexer::members { // add members to generated symParser String stops = " \t\n"; } // standard namespaces NS_CLJ_CORE : 'clojure.core' ; NS_CLJ_LANG : 'clojure.lang' ; // ...etc... // specials SPECIAL : DEF | DEFN | OR ; DEF : 'def' ; DEFN : 'defn' ; OR : 'or' ; // ...etc... // kernel/prelude functions PREDEF : LIST | MAP | CONJ ; LIST : 'list' ; MAP : 'map' ; CONJ : 'conj' ; OP : ADD | SUB | MUL | DIV | EQ ; // trailing {...}? is an antlr 4 "semantic predicate"; it must be true // for the match to work. in this case, the predicate means that // these ops must be followed by whitespace if they are not part of a // symbol; otherwise, something like (+1 2) would be parsed as (+ 1 2) // but +1 is a valid clojure (symbol) name part try this: // (def user/-1/ 0) // (+ user/-1 1) => 1 ADD : '+' {stops.contains(Character.toString((char)_input.LA(1)))}? ; SUB : '-' {stops.contains(Character.toString((char)_input.LA(1)))}? ; MUL : '*' {stops.contains(Character.toString((char)_input.LA(1)))}? ; DIV : '/' {stops.contains(Character.toString((char)_input.LA(1)))}? ; EQ : '=' {stops.contains(Character.toString((char)_input.LA(1)))}? ; // symbol = (<namespace-id> '/')? <name> // this structure is recognized by the parser - see rule // id_symbol. the lexer recognizes <namespace-id> and <name> tokens, // (as ID_NS and IS_NM, respectively) but not symbols // the informal clojure spec (http://clojure.org/reader) does not // match the operational semantics defined by the code itself. for // example, the spec says "'/' has special meaning, it can be used // once in the middle of a symbol to separate the namespace from the // name, e.g. my-namespace/foo." But the code // (https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/LispReader.java) // says the symbol regex is [:]?([\\D&&[^/]].*/)?(/|[\\D&&[^/]][^/]*) // which allows any number of '/' in the namespace part. // how does this work? the first parse matches the regex, which puts // all the '/' in the ns part. but when (eventually) the symbol gets // interned (clojure.lang.Symbol$intern), the code just looks for the // first '/' and interns the rest. that's why we get: // user=> (namespace 'a/b/c/d) => "a" // user=> (name 'a/b/c/d) => "b/c/d" // so for the moment we punt and reject '/' from both namespace and name parts of symbols ID_NS : CHAR_START (LETTER | DIGIT | HARF)* ; // here the semantic predicate prevents matching e.g. abc/def/ghi ID_NM : CHAR_START (LETTER | DIGIT | HARF)* {' '==(char)_input.LA(1)}? ; fragment CHAR_START : LETTER | HARF | ':' ; fragment LETTER : [a-zA-Z] ; NUMERAL : DIGIT+ ; fragment DIGIT : [0-9] ; // HURUF (sg. HARF) = printable ascii except macro chars, ',' // all: ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~ // legal: ! # $ % & ' * + - . : < = > ? \ _ ` | fragment HARF : [!#$%&'*+-.\<=>?_|] ; SLASH : '/' ; LPAREN : '(' ; RPAREN : ')' ; LBRACK : '[' ; RBRACK : ']' ; // SP : ' '; WS : [ \t\r\n\u000C\u2028]+ -> skip ; COMMENT : ';' ~[\r\n]* -> skip ;
add some doc to symLexer
add some doc to symLexer
ANTLR
epl-1.0
mobileink/lab.antlr,mobileink/lab.clj.antlr
f4b1b9a98348f5ec0dc525854a9ad7aee2a47f64
Solidity.g4
Solidity.g4
// Copyright 2016-2017 Federico Bond <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. grammar Solidity; sourceUnit : (pragmaDirective | importDirective | contractDefinition)* EOF ; pragmaDirective : 'pragma' pragmaName pragmaValue ';' ; pragmaName : identifier ; pragmaValue : version | expression ; version : versionConstraint versionConstraint? ; versionOperator : '^' | '~' | '>=' | '>' | '<' | '<=' | '=' ; versionConstraint : versionOperator? VersionLiteral ; importDeclaration : identifier ('as' identifier)? ; importDirective : 'import' StringLiteral ('as' identifier)? ';' | 'import' ('*' | identifier) ('as' identifier)? 'from' StringLiteral ';' | 'import' '{' importDeclaration ( ',' importDeclaration )* '}' 'from' StringLiteral ';' ; contractDefinition : ( 'contract' | 'interface' | 'library' ) identifier ( 'is' inheritanceSpecifier (',' inheritanceSpecifier )* )? '{' contractPart* '}' ; inheritanceSpecifier : userDefinedTypeName ( '(' expression ( ',' expression )* ')' )? ; contractPart : stateVariableDeclaration | usingForDeclaration | structDefinition | constructorDefinition | modifierDefinition | functionDefinition | eventDefinition | enumDefinition ; stateVariableDeclaration : typeName ( PublicKeyword | InternalKeyword | PrivateKeyword | ConstantKeyword )* identifier ('=' expression)? ';' ; usingForDeclaration : 'using' identifier 'for' ('*' | typeName) ';' ; structDefinition : 'struct' identifier '{' ( variableDeclaration ';' (variableDeclaration ';')* )? '}' ; constructorDefinition : 'constructor' parameterList modifierList block ; modifierDefinition : 'modifier' identifier parameterList? block ; modifierInvocation : identifier ( '(' expressionList? ')' )? ; functionDefinition : 'function' identifier? parameterList modifierList returnParameters? ( ';' | block ) ; returnParameters : 'returns' parameterList ; modifierList : ( modifierInvocation | stateMutability | ExternalKeyword | PublicKeyword | InternalKeyword | PrivateKeyword )* ; eventDefinition : 'event' identifier eventParameterList AnonymousKeyword? ';' ; enumValue : identifier ; enumDefinition : 'enum' identifier '{' enumValue? (',' enumValue)* '}' ; parameterList : '(' ( parameter (',' parameter)* )? ')' ; parameter : typeName storageLocation? identifier? ; eventParameterList : '(' ( eventParameter (',' eventParameter)* )? ')' ; eventParameter : typeName IndexedKeyword? identifier? ; functionTypeParameterList : '(' ( functionTypeParameter (',' functionTypeParameter)* )? ')' ; functionTypeParameter : typeName storageLocation? ; variableDeclaration : typeName storageLocation? identifier ; typeName : elementaryTypeName | userDefinedTypeName | mapping | typeName '[' expression? ']' | functionTypeName ; userDefinedTypeName : identifier ( '.' identifier )* ; mapping : 'mapping' '(' elementaryTypeName '=>' typeName ')' ; functionTypeName : 'function' functionTypeParameterList ( InternalKeyword | ExternalKeyword | stateMutability )* ( 'returns' functionTypeParameterList )? ; storageLocation : 'memory' | 'storage' | 'calldata'; stateMutability : PureKeyword | ConstantKeyword | ViewKeyword | PayableKeyword ; block : '{' statement* '}' ; statement : ifStatement | whileStatement | forStatement | block | inlineAssemblyStatement | doWhileStatement | continueStatement | breakStatement | returnStatement | throwStatement | emitStatement | simpleStatement ; expressionStatement : expression ';' ; ifStatement : 'if' '(' expression ')' statement ( 'else' statement )? ; whileStatement : 'while' '(' expression ')' statement ; simpleStatement : ( variableDeclarationStatement | expressionStatement ) ; forStatement : 'for' '(' ( simpleStatement | ';' ) expression? ';' expression? ')' statement ; inlineAssemblyStatement : 'assembly' StringLiteral? assemblyBlock ; doWhileStatement : 'do' statement 'while' '(' expression ')' ';' ; continueStatement : 'continue' ';' ; breakStatement : 'break' ';' ; returnStatement : 'return' expression? ';' ; throwStatement : 'throw' ';' ; emitStatement : 'emit' functionCall ';' ; variableDeclarationStatement : ( 'var' identifierList | variableDeclaration | '(' variableDeclarationList ')' ) ( '=' expression )? ';'; variableDeclarationList : variableDeclaration? (',' variableDeclaration? )* ; identifierList : '(' ( identifier? ',' )* identifier? ')' ; elementaryTypeName : 'address' | 'bool' | 'string' | 'var' | Int | Uint | 'byte' | Byte | Fixed | Ufixed ; Int : 'int' | 'int8' | 'int16' | 'int24' | 'int32' | 'int40' | 'int48' | 'int56' | 'int64' | 'int72' | 'int80' | 'int88' | 'int96' | 'int104' | 'int112' | 'int120' | 'int128' | 'int136' | 'int144' | 'int152' | 'int160' | 'int168' | 'int176' | 'int184' | 'int192' | 'int200' | 'int208' | 'int216' | 'int224' | 'int232' | 'int240' | 'int248' | 'int256' ; Uint : 'uint' | 'uint8' | 'uint16' | 'uint24' | 'uint32' | 'uint40' | 'uint48' | 'uint56' | 'uint64' | 'uint72' | 'uint80' | 'uint88' | 'uint96' | 'uint104' | 'uint112' | 'uint120' | 'uint128' | 'uint136' | 'uint144' | 'uint152' | 'uint160' | 'uint168' | 'uint176' | 'uint184' | 'uint192' | 'uint200' | 'uint208' | 'uint216' | 'uint224' | 'uint232' | 'uint240' | 'uint248' | 'uint256' ; Byte : 'bytes' | 'bytes1' | 'bytes2' | 'bytes3' | 'bytes4' | 'bytes5' | 'bytes6' | 'bytes7' | 'bytes8' | 'bytes9' | 'bytes10' | 'bytes11' | 'bytes12' | 'bytes13' | 'bytes14' | 'bytes15' | 'bytes16' | 'bytes17' | 'bytes18' | 'bytes19' | 'bytes20' | 'bytes21' | 'bytes22' | 'bytes23' | 'bytes24' | 'bytes25' | 'bytes26' | 'bytes27' | 'bytes28' | 'bytes29' | 'bytes30' | 'bytes31' | 'bytes32' ; Fixed : 'fixed' | ( 'fixed' [0-9]+ 'x' [0-9]+ ) ; Ufixed : 'ufixed' | ( 'ufixed' [0-9]+ 'x' [0-9]+ ) ; expression : expression ('++' | '--') | 'new' typeName | expression '[' expression ']' | expression '(' functionCallArguments ')' | expression '.' identifier | '(' expression ')' | ('++' | '--') expression | ('+' | '-') expression | ('after' | 'delete') expression | '!' expression | '~' expression | expression '**' expression | expression ('*' | '/' | '%') expression | expression ('+' | '-') expression | expression ('<<' | '>>') expression | expression '&' expression | expression '^' expression | expression '|' expression | expression ('<' | '>' | '<=' | '>=') expression | expression ('==' | '!=') expression | expression '&&' expression | expression '||' expression | expression '?' expression ':' expression | expression ('=' | '|=' | '^=' | '&=' | '<<=' | '>>=' | '+=' | '-=' | '*=' | '/=' | '%=') expression | primaryExpression ; primaryExpression : BooleanLiteral | numberLiteral | HexLiteral | StringLiteral | identifier | tupleExpression | elementaryTypeNameExpression ; expressionList : expression (',' expression)* ; nameValueList : nameValue (',' nameValue)* ','? ; nameValue : identifier ':' expression ; functionCallArguments : '{' nameValueList? '}' | expressionList? ; functionCall : expression '(' functionCallArguments ')' ; assemblyBlock : '{' assemblyItem* '}' ; assemblyItem : identifier | assemblyBlock | assemblyExpression | assemblyLocalDefinition | assemblyAssignment | assemblyStackAssignment | labelDefinition | assemblySwitch | assemblyFunctionDefinition | assemblyFor | assemblyIf | BreakKeyword | ContinueKeyword | subAssembly | numberLiteral | StringLiteral | HexLiteral ; assemblyExpression : assemblyCall | assemblyLiteral ; assemblyCall : ( 'return' | 'address' | 'byte' | identifier ) ( '(' assemblyExpression? ( ',' assemblyExpression )* ')' )? ; assemblyLocalDefinition : 'let' assemblyIdentifierOrList ( ':=' assemblyExpression )? ; assemblyAssignment : assemblyIdentifierOrList ':=' assemblyExpression ; assemblyIdentifierOrList : identifier | '(' assemblyIdentifierList ')' ; assemblyIdentifierList : identifier ( ',' identifier )* ; assemblyStackAssignment : '=:' identifier ; labelDefinition : identifier ':' ; assemblySwitch : 'switch' assemblyExpression assemblyCase* ; assemblyCase : 'case' assemblyLiteral assemblyBlock | 'default' assemblyBlock ; assemblyFunctionDefinition : 'function' identifier '(' assemblyIdentifierList? ')' assemblyFunctionReturns? assemblyBlock ; assemblyFunctionReturns : ( '->' assemblyIdentifierList ) ; assemblyFor : 'for' ( assemblyBlock | assemblyExpression ) assemblyExpression ( assemblyBlock | assemblyExpression ) assemblyBlock ; assemblyIf : 'if' assemblyExpression assemblyBlock ; assemblyLiteral : StringLiteral | DecimalNumber | HexNumber | HexLiteral ; subAssembly : 'assembly' identifier assemblyBlock ; tupleExpression : '(' ( expression? ( ',' expression? )* ) ')' | '[' ( expression ( ',' expression )* )? ']' ; elementaryTypeNameExpression : elementaryTypeName ; numberLiteral : (DecimalNumber | HexNumber) NumberUnit? ; identifier : ('from' | Identifier) ; VersionLiteral : [0-9]+ '.' [0-9]+ '.' [0-9]+ ; BooleanLiteral : 'true' | 'false' ; DecimalNumber : ([0-9]+ | ([0-9]* '.' [0-9]+) ) ( [eE] [0-9]+ )? ; HexNumber : '0' [xX] HexCharacter+ ; NumberUnit : 'wei' | 'szabo' | 'finney' | 'ether' | 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'years' ; HexLiteral : 'hex' ('"' HexPair* '"' | '\'' HexPair* '\'') ; fragment HexPair : HexCharacter HexCharacter ; fragment HexCharacter : [0-9A-Fa-f] ; ReservedKeyword : 'abstract' | 'after' | 'case' | 'catch' | 'default' | 'final' | 'in' | 'inline' | 'let' | 'match' | 'null' | 'of' | 'relocatable' | 'static' | 'switch' | 'try' | 'type' | 'typeof' ; AnonymousKeyword : 'anonymous' ; BreakKeyword : 'break' ; ConstantKeyword : 'constant' ; ContinueKeyword : 'continue' ; ExternalKeyword : 'external' ; IndexedKeyword : 'indexed' ; InternalKeyword : 'internal' ; PayableKeyword : 'payable' ; PrivateKeyword : 'private' ; PublicKeyword : 'public' ; PureKeyword : 'pure' ; ViewKeyword : 'view' ; Identifier : IdentifierStart IdentifierPart* ; fragment IdentifierStart : [a-zA-Z$_] ; fragment IdentifierPart : [a-zA-Z0-9$_] ; StringLiteral : '"' DoubleQuotedStringCharacter* '"' | '\'' SingleQuotedStringCharacter* '\'' ; fragment DoubleQuotedStringCharacter : ~["\r\n\\] | ('\\' .) ; fragment SingleQuotedStringCharacter : ~['\r\n\\] | ('\\' .) ; WS : [ \t\r\n\u000C]+ -> skip ; COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ;
// Copyright 2016-2017 Federico Bond <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. grammar Solidity; sourceUnit : (pragmaDirective | importDirective | contractDefinition)* EOF ; pragmaDirective : 'pragma' pragmaName pragmaValue ';' ; pragmaName : identifier ; pragmaValue : version | expression ; version : versionConstraint versionConstraint? ; versionOperator : '^' | '~' | '>=' | '>' | '<' | '<=' | '=' ; versionConstraint : versionOperator? VersionLiteral ; importDeclaration : identifier ('as' identifier)? ; importDirective : 'import' StringLiteral ('as' identifier)? ';' | 'import' ('*' | identifier) ('as' identifier)? 'from' StringLiteral ';' | 'import' '{' importDeclaration ( ',' importDeclaration )* '}' 'from' StringLiteral ';' ; contractDefinition : ( 'contract' | 'interface' | 'library' ) identifier ( 'is' inheritanceSpecifier (',' inheritanceSpecifier )* )? '{' contractPart* '}' ; inheritanceSpecifier : userDefinedTypeName ( '(' expression ( ',' expression )* ')' )? ; contractPart : stateVariableDeclaration | usingForDeclaration | structDefinition | constructorDefinition | modifierDefinition | functionDefinition | eventDefinition | enumDefinition ; stateVariableDeclaration : typeName ( PublicKeyword | InternalKeyword | PrivateKeyword | ConstantKeyword )* identifier ('=' expression)? ';' ; usingForDeclaration : 'using' identifier 'for' ('*' | typeName) ';' ; structDefinition : 'struct' identifier '{' ( variableDeclaration ';' (variableDeclaration ';')* )? '}' ; constructorDefinition : 'constructor' parameterList modifierList block ; modifierDefinition : 'modifier' identifier parameterList? block ; modifierInvocation : identifier ( '(' expressionList? ')' )? ; functionDefinition : 'function' identifier? parameterList modifierList returnParameters? ( ';' | block ) ; returnParameters : 'returns' parameterList ; modifierList : ( modifierInvocation | stateMutability | ExternalKeyword | PublicKeyword | InternalKeyword | PrivateKeyword )* ; eventDefinition : 'event' identifier eventParameterList AnonymousKeyword? ';' ; enumValue : identifier ; enumDefinition : 'enum' identifier '{' enumValue? (',' enumValue)* '}' ; parameterList : '(' ( parameter (',' parameter)* )? ')' ; parameter : typeName storageLocation? identifier? ; eventParameterList : '(' ( eventParameter (',' eventParameter)* )? ')' ; eventParameter : typeName IndexedKeyword? identifier? ; functionTypeParameterList : '(' ( functionTypeParameter (',' functionTypeParameter)* )? ')' ; functionTypeParameter : typeName storageLocation? ; variableDeclaration : typeName storageLocation? identifier ; typeName : elementaryTypeName | userDefinedTypeName | mapping | typeName '[' expression? ']' | functionTypeName | 'address' 'payable' ; userDefinedTypeName : identifier ( '.' identifier )* ; mapping : 'mapping' '(' elementaryTypeName '=>' typeName ')' ; functionTypeName : 'function' functionTypeParameterList ( InternalKeyword | ExternalKeyword | stateMutability )* ( 'returns' functionTypeParameterList )? ; storageLocation : 'memory' | 'storage' | 'calldata'; stateMutability : PureKeyword | ConstantKeyword | ViewKeyword | PayableKeyword ; block : '{' statement* '}' ; statement : ifStatement | whileStatement | forStatement | block | inlineAssemblyStatement | doWhileStatement | continueStatement | breakStatement | returnStatement | throwStatement | emitStatement | simpleStatement ; expressionStatement : expression ';' ; ifStatement : 'if' '(' expression ')' statement ( 'else' statement )? ; whileStatement : 'while' '(' expression ')' statement ; simpleStatement : ( variableDeclarationStatement | expressionStatement ) ; forStatement : 'for' '(' ( simpleStatement | ';' ) expression? ';' expression? ')' statement ; inlineAssemblyStatement : 'assembly' StringLiteral? assemblyBlock ; doWhileStatement : 'do' statement 'while' '(' expression ')' ';' ; continueStatement : 'continue' ';' ; breakStatement : 'break' ';' ; returnStatement : 'return' expression? ';' ; throwStatement : 'throw' ';' ; emitStatement : 'emit' functionCall ';' ; variableDeclarationStatement : ( 'var' identifierList | variableDeclaration | '(' variableDeclarationList ')' ) ( '=' expression )? ';'; variableDeclarationList : variableDeclaration? (',' variableDeclaration? )* ; identifierList : '(' ( identifier? ',' )* identifier? ')' ; elementaryTypeName : 'address' | 'bool' | 'string' | 'var' | Int | Uint | 'byte' | Byte | Fixed | Ufixed ; Int : 'int' | 'int8' | 'int16' | 'int24' | 'int32' | 'int40' | 'int48' | 'int56' | 'int64' | 'int72' | 'int80' | 'int88' | 'int96' | 'int104' | 'int112' | 'int120' | 'int128' | 'int136' | 'int144' | 'int152' | 'int160' | 'int168' | 'int176' | 'int184' | 'int192' | 'int200' | 'int208' | 'int216' | 'int224' | 'int232' | 'int240' | 'int248' | 'int256' ; Uint : 'uint' | 'uint8' | 'uint16' | 'uint24' | 'uint32' | 'uint40' | 'uint48' | 'uint56' | 'uint64' | 'uint72' | 'uint80' | 'uint88' | 'uint96' | 'uint104' | 'uint112' | 'uint120' | 'uint128' | 'uint136' | 'uint144' | 'uint152' | 'uint160' | 'uint168' | 'uint176' | 'uint184' | 'uint192' | 'uint200' | 'uint208' | 'uint216' | 'uint224' | 'uint232' | 'uint240' | 'uint248' | 'uint256' ; Byte : 'bytes' | 'bytes1' | 'bytes2' | 'bytes3' | 'bytes4' | 'bytes5' | 'bytes6' | 'bytes7' | 'bytes8' | 'bytes9' | 'bytes10' | 'bytes11' | 'bytes12' | 'bytes13' | 'bytes14' | 'bytes15' | 'bytes16' | 'bytes17' | 'bytes18' | 'bytes19' | 'bytes20' | 'bytes21' | 'bytes22' | 'bytes23' | 'bytes24' | 'bytes25' | 'bytes26' | 'bytes27' | 'bytes28' | 'bytes29' | 'bytes30' | 'bytes31' | 'bytes32' ; Fixed : 'fixed' | ( 'fixed' [0-9]+ 'x' [0-9]+ ) ; Ufixed : 'ufixed' | ( 'ufixed' [0-9]+ 'x' [0-9]+ ) ; expression : expression ('++' | '--') | 'new' typeName | expression '[' expression ']' | expression '(' functionCallArguments ')' | expression '.' identifier | '(' expression ')' | ('++' | '--') expression | ('+' | '-') expression | ('after' | 'delete') expression | '!' expression | '~' expression | expression '**' expression | expression ('*' | '/' | '%') expression | expression ('+' | '-') expression | expression ('<<' | '>>') expression | expression '&' expression | expression '^' expression | expression '|' expression | expression ('<' | '>' | '<=' | '>=') expression | expression ('==' | '!=') expression | expression '&&' expression | expression '||' expression | expression '?' expression ':' expression | expression ('=' | '|=' | '^=' | '&=' | '<<=' | '>>=' | '+=' | '-=' | '*=' | '/=' | '%=') expression | primaryExpression ; primaryExpression : BooleanLiteral | numberLiteral | HexLiteral | StringLiteral | identifier | tupleExpression | elementaryTypeNameExpression ; expressionList : expression (',' expression)* ; nameValueList : nameValue (',' nameValue)* ','? ; nameValue : identifier ':' expression ; functionCallArguments : '{' nameValueList? '}' | expressionList? ; functionCall : expression '(' functionCallArguments ')' ; assemblyBlock : '{' assemblyItem* '}' ; assemblyItem : identifier | assemblyBlock | assemblyExpression | assemblyLocalDefinition | assemblyAssignment | assemblyStackAssignment | labelDefinition | assemblySwitch | assemblyFunctionDefinition | assemblyFor | assemblyIf | BreakKeyword | ContinueKeyword | subAssembly | numberLiteral | StringLiteral | HexLiteral ; assemblyExpression : assemblyCall | assemblyLiteral ; assemblyCall : ( 'return' | 'address' | 'byte' | identifier ) ( '(' assemblyExpression? ( ',' assemblyExpression )* ')' )? ; assemblyLocalDefinition : 'let' assemblyIdentifierOrList ( ':=' assemblyExpression )? ; assemblyAssignment : assemblyIdentifierOrList ':=' assemblyExpression ; assemblyIdentifierOrList : identifier | '(' assemblyIdentifierList ')' ; assemblyIdentifierList : identifier ( ',' identifier )* ; assemblyStackAssignment : '=:' identifier ; labelDefinition : identifier ':' ; assemblySwitch : 'switch' assemblyExpression assemblyCase* ; assemblyCase : 'case' assemblyLiteral assemblyBlock | 'default' assemblyBlock ; assemblyFunctionDefinition : 'function' identifier '(' assemblyIdentifierList? ')' assemblyFunctionReturns? assemblyBlock ; assemblyFunctionReturns : ( '->' assemblyIdentifierList ) ; assemblyFor : 'for' ( assemblyBlock | assemblyExpression ) assemblyExpression ( assemblyBlock | assemblyExpression ) assemblyBlock ; assemblyIf : 'if' assemblyExpression assemblyBlock ; assemblyLiteral : StringLiteral | DecimalNumber | HexNumber | HexLiteral ; subAssembly : 'assembly' identifier assemblyBlock ; tupleExpression : '(' ( expression? ( ',' expression? )* ) ')' | '[' ( expression ( ',' expression )* )? ']' ; elementaryTypeNameExpression : elementaryTypeName ; numberLiteral : (DecimalNumber | HexNumber) NumberUnit? ; identifier : ('from' | Identifier) ; VersionLiteral : [0-9]+ '.' [0-9]+ '.' [0-9]+ ; BooleanLiteral : 'true' | 'false' ; DecimalNumber : ([0-9]+ | ([0-9]* '.' [0-9]+) ) ( [eE] [0-9]+ )? ; HexNumber : '0' [xX] HexCharacter+ ; NumberUnit : 'wei' | 'szabo' | 'finney' | 'ether' | 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'years' ; HexLiteral : 'hex' ('"' HexPair* '"' | '\'' HexPair* '\'') ; fragment HexPair : HexCharacter HexCharacter ; fragment HexCharacter : [0-9A-Fa-f] ; ReservedKeyword : 'abstract' | 'after' | 'case' | 'catch' | 'default' | 'final' | 'in' | 'inline' | 'let' | 'match' | 'null' | 'of' | 'relocatable' | 'static' | 'switch' | 'try' | 'type' | 'typeof' ; AnonymousKeyword : 'anonymous' ; BreakKeyword : 'break' ; ConstantKeyword : 'constant' ; ContinueKeyword : 'continue' ; ExternalKeyword : 'external' ; IndexedKeyword : 'indexed' ; InternalKeyword : 'internal' ; PayableKeyword : 'payable' ; PrivateKeyword : 'private' ; PublicKeyword : 'public' ; PureKeyword : 'pure' ; ViewKeyword : 'view' ; Identifier : IdentifierStart IdentifierPart* ; fragment IdentifierStart : [a-zA-Z$_] ; fragment IdentifierPart : [a-zA-Z0-9$_] ; StringLiteral : '"' DoubleQuotedStringCharacter* '"' | '\'' SingleQuotedStringCharacter* '\'' ; fragment DoubleQuotedStringCharacter : ~["\r\n\\] | ('\\' .) ; fragment SingleQuotedStringCharacter : ~['\r\n\\] | ('\\' .) ; WS : [ \t\r\n\u000C]+ -> skip ; COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ;
Add address payable to possible typenames
Add address payable to possible typenames
ANTLR
mit
solidityj/solidity-antlr4,federicobond/solidity-antlr4
a6208d9fba87c6beb8cc83177b92ec8e3f1a9baf
src/main/scala/org/interestinglab/waterdrop/configparser/Config.g4
src/main/scala/org/interestinglab/waterdrop/configparser/Config.g4
grammar Config; config : value ; obj : '{' pair (',' pair)* '}' | '{' '}' ; pair : STRING '=' value ; array : '[' value (',' value)* ']' | '[' ']' ; value : STRING | NUMBER | obj | array | 'true' | 'false' | 'null' ; STRING : '"' (ESC | ~ ["\\])* '"' ; fragment ESC : '\\' (["\\/bfnrt] | UNICODE) ; fragment UNICODE : 'u' HEX HEX HEX HEX ; fragment HEX : [0-9a-fA-F] ; NUMBER : '-'? INT '.' [0-9] + EXP? | '-'? INT EXP | '-'? INT ; fragment INT : '0' | [1-9] [0-9]* ; // no leading zeros fragment EXP : [Ee] [+\-]? INT ; // \- since - means "range" inside [...] WS : [ \t\n\r] + -> skip ;
grammar Config; // Filter, Output 允许if else // STRING lexer rule定义过于简单,不满足需求,包括包含引号的字符串. // 允许comment // [done]允许key不包含双引号 // [done] 允许多行配置没有","分割 // [done] 允许plugin中不包含任何配置 config : input filter output ; input : 'input' '{' (STRING obj)* '}' ; filter : 'filter' '{' (STRING obj)* '}' ; output : 'output' '{' (STRING obj)* '}' ; obj : '{' pair (','? pair)* '}' | '{' '}' ; pair : STRING '=' value ; array : '[' value (',' value)* ']' | '[' ']' ; value : STRING | NUMBER // | obj | array | 'true' | 'false' | 'null' ; STRING : UNQUOTE_STRING | SINGLE_QUOTE_STRING | DOUBLE_QUOTE_STRING ; fragment UNQUOTE_STRING : [a-zA-Z]+ ; fragment SINGLE_QUOTE_STRING : '\'' UNQUOTE_STRING '\'' ; fragment DOUBLE_QUOTE_STRING : '"' UNQUOTE_STRING '"' ; NUMBER : '-'? INT '.' [0-9] + EXP? | '-'? INT EXP | '-'? INT ; fragment INT : '0' | [1-9] [0-9]* ; // no leading zeros fragment EXP : [Ee] [+\-]? INT ; WS : [ \t\n\r]+ -> skip ;
update grammer file
update grammer file
ANTLR
apache-2.0
InterestingLab/waterdrop,InterestingLab/waterdrop
e4a4dfafff0482fbbbdc0a35f0a3a0575ff3bbbd
omni-cx2x/src/cx2x/translator/language/Claw.g4
omni-cx2x/src/cx2x/translator/language/Claw.g4
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import java.util.List; import java.util.ArrayList; import cx2x.translator.common.Constant; import cx2x.translator.pragma.ClawRange; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage language] @init{ $language = new ClawLanguage(); } : CLAW directive[$language] ; ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; directive[ClawLanguage language]: LFUSION { $language.setDirective(ClawDirective.LOOP_FUSION); } group_option[$language] EOF | LINTERCHANGE { $language.setDirective(ClawDirective.LOOP_INTERCHANGE); } indexes_option[$language] EOF | LEXTRACT range_option EOF { $language.setDirective(ClawDirective.LOOP_EXTRACT); $language.setRange($range_option.r); } | REMOVE { $language.setDirective(ClawDirective.REMOVE); } EOF | END REMOVE { $language.setDirective(ClawDirective.END_REMOVE); } EOF ; group_option[ClawLanguage language]: GROUP '(' group_name=IDENTIFIER ')' { $language.setGroupOption($group_name.text); } | /* empty */ ; indexes_option[ClawLanguage language] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $language.setIndexes(indexes); } | /* empty */ ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(Constant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ',' step=IDENTIFIER ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; /* mapping_option: MAP '(' ids_list ':' ids_list ')' ; map_list: mapping_option | mapping_option map_list ; */ /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // Directives LFUSION : 'loop-fusion'; LINTERCHANGE : 'loop-interchange'; LEXTRACT : 'loop-extract'; REMOVE : 'remove'; END : 'end'; // Options GROUP : 'group'; RANGE : 'range'; MAP : 'map'; // Special elements IDENTIFIER : [a-zA-Z_$0-9] [a-zA-Z_$0-9]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : '0'..'9' ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import java.util.List; import java.util.ArrayList; import cx2x.translator.common.Constant; import cx2x.translator.pragma.ClawRange; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage language] @init{ $language = new ClawLanguage(); } : CLAW directive[$language] ; ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; directive[ClawLanguage language]: LFUSION { $language.setDirective(ClawDirective.LOOP_FUSION); } group_option[$language] EOF | LINTERCHANGE { $language.setDirective(ClawDirective.LOOP_INTERCHANGE); } indexes_option[$language] EOF | LEXTRACT range_option EOF { $language.setDirective(ClawDirective.LOOP_EXTRACT); $language.setRange($range_option.r); } | REMOVE { $language.setDirective(ClawDirective.REMOVE); } EOF | END REMOVE { $language.setDirective(ClawDirective.END_REMOVE); } EOF ; group_option[ClawLanguage language]: GROUP '(' group_name=IDENTIFIER ')' { $language.setGroupOption($group_name.text); } | /* empty */ ; indexes_option[ClawLanguage language] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $language.setIndexes(indexes); } | /* empty */ ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(Constant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ',' step=IDENTIFIER ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; /* mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); } : MAP '(' ids_list ':' ids_list ')' ; map_list: mapping_option | mapping_option map_list ; */ /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // Directives LFUSION : 'loop-fusion'; LINTERCHANGE : 'loop-interchange'; LEXTRACT : 'loop-extract'; REMOVE : 'remove'; END : 'end'; // Options GROUP : 'group'; RANGE : 'range'; MAP : 'map'; // Special elements IDENTIFIER : [a-zA-Z_$0-9] [a-zA-Z_$0-9]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : '0'..'9' ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
Add mapping_var parser rule
Add mapping_var parser rule
ANTLR
bsd-2-clause
clementval/claw-compiler,clementval/claw-compiler
76bc8afd728213f6f96edac6490e81ef189f1f4d
omni-cx2x/src/cx2x/translator/language/Claw.g4
omni-cx2x/src/cx2x/translator/language/Claw.g4
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import java.util.List; import java.util.ArrayList; import cx2x.translator.common.Constant; import cx2x.translator.misc.Utility; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage l] @init{ $l = new ClawLanguage(); } : CLAW directive[$l] ; ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; ids_or_colon_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | ':' { $ids.add(":"); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] | ':' { $ids.add(":"); } ',' ids_list[$ids] ; directive[ClawLanguage l] @init{ List<ClawMapping> m = new ArrayList<>(); List<String> o = new ArrayList<>(); List<String> s = new ArrayList<>(); List<Integer> i = new ArrayList<>(); } : // loop-fusion directive LFUSION group_option[$l] collapse_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_FUSION); } // loop-interchange directive | LINTERCHANGE indexes_option[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } // loop-extract directive | LEXTRACT range_option mapping_option_list[m] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_EXTRACT); $l.setRange($range_option.r); $l.setMappings(m); } // remove directive | REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); } | END REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); $l.setEndPragma(); } // Kcache directive | KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); } | KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); $l.setInitClause(); } // Array notation transformation directive | ARRAY_TRANS induction_optional[$l] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); } | END ARRAY_TRANS { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); $l.setEndPragma(); } // loop-hoist directive | LHOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF { $l.setHoistInductionVars(o); $l.setDirective(ClawDirective.LOOP_HOIST); } | END LHOIST EOF { $l.setDirective(ClawDirective.LOOP_HOIST); $l.setEndPragma(); } // on the fly directive | ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')' { $l.setDirective(ClawDirective.ARRAY_TO_CALL); $l.setFctParams(o); $l.setFctName($fct_name.text); $l.setArrayName($array_name.text); } // | DEFINE DIMENSION id=IDENTIFIER '(' lower=range_id ',' upper=range_id ')' { $l.setDirective(ClawDirective.DEFINE); ClawDimension cd = new ClawDimension($id.text, $lower.text, $upper.text); $l.setDimensionClauseValue(cd); } | PARALLELIZE DATA '(' ids_list[o] ')' OVER '(' ids_or_colon_list[s] ')' { $l.setDirective(ClawDirective.PARALLELIZE); $l.setDataClause(o); $l.setOverClause(s); } ; group_option[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupClause($group_name.text); } | /* empty */ ; collapse_optional[ClawLanguage l]: COLLAPSE '(' n=NUMBER ')' { $l.setCollapseClause($n.text); } | /* empty */ ; fusion_optional[ClawLanguage l]: FUSION group_option[$l] { $l.setFusionClause(); } | /* empty */ ; parallel_optional[ClawLanguage l]: PARALLEL { $l.setParallelClause(); } | /* empty */ ; acc_optional[ClawLanguage l] @init{ List<String> tempAcc = new ArrayList<>(); } : ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); } | /* empty */ ; interchange_optional[ClawLanguage l]: INTERCHANGE indexes_option[$l] { $l.setInterchangeClause(); } | /* empty */ ; induction_optional[ClawLanguage l] @init{ List<String> temp = new ArrayList<>(); } : INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); } | /* empty */ ; data_clause[ClawLanguage l] @init { List<String> temp = new ArrayList<>(); } : DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); } ; private_optional[ClawLanguage l]: PRIVATE { $l.setPrivateClause(); } | /* empty */ ; reshape_optional[ClawLanguage l] @init{ List<ClawReshapeInfo> r = new ArrayList(); } : RESHAPE '(' reshape_list[r] ')' { $l.setReshapeClauseValues(r); } | /* empty */ ; reshape_element returns [ClawReshapeInfo i] @init{ List<Integer> temp = new ArrayList(); } : array_name=IDENTIFIER '(' target_dim=NUMBER ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } | array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } ; reshape_list[List<ClawReshapeInfo> r]: info=reshape_element { $r.add($info.i); } ',' reshape_list[$r] | info=reshape_element { $r.add($info.i); } ; identifiers[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids] ; identifiers_list[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids] ; integers[List<Integer> ints]: ; integers_list[List<Integer> ints]: i=NUMBER { $ints.add(Integer.parseInt($i.text)); } | i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints] ; indexes_option[ClawLanguage l] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $l.setIndexes(indexes); } | /* empty */ ; offset_list_optional[List<Integer> offsets]: OFFSET '(' offset_list[$offsets] ')' | /* empty */ ; offset_list[List<Integer> offsets]: offset[$offsets] | offset[$offsets] ',' offset_list[$offsets] ; offset[List<Integer> offsets]: n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } | '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); } | '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(Constant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; range_id returns [String text]: n=NUMBER { $text = $n.text; } | i=IDENTIFIER { $text = $i.text; } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; mapping_var_list[List<ClawMappingVar> vars]: mv=mapping_var { $vars.add($mv.mappingVar); } | mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars] ; mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>(); List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>(); $mapping.setMappedVariables(listMapped); $mapping.setMappingVariables(listMapping); } : MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')' ; mapping_option_list[List<ClawMapping> mappings]: m=mapping_option { $mappings.add($m.mapping); } | m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings] ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // Directives ARRAY_TRANS : 'array-transform'; ARRAY_TO_CALL: 'call'; DEFINE : 'define'; END : 'end'; KCACHE : 'kcache'; LEXTRACT : 'loop-extract'; LFUSION : 'loop-fusion'; LHOIST : 'loop-hoist'; LINTERCHANGE : 'loop-interchange'; PARALLELIZE : 'parallelize'; REMOVE : 'remove'; // Clauses ACC : 'acc'; COLLAPSE : 'collapse'; DATA : 'data'; DIMENSION : 'dimension'; FUSION : 'fusion'; GROUP : 'group'; INDUCTION : 'induction'; INIT : 'init'; INTERCHANGE : 'interchange'; MAP : 'map'; OFFSET : 'offset'; OVER : 'over'; PARALLEL : 'parallel'; PRIVATE : 'private'; RANGE : 'range'; RESHAPE : 'reshape'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : [0-9] ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import java.util.List; import java.util.ArrayList; import cx2x.translator.common.Constant; import cx2x.translator.misc.Utility; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage l] @init{ $l = new ClawLanguage(); } : CLAW directive[$l] ; ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; ids_or_colon_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | ':' { $ids.add(":"); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_or_colon_list[$ids] | ':' { $ids.add(":"); } ',' ids_or_colon_list[$ids] ; directive[ClawLanguage l] @init{ List<ClawMapping> m = new ArrayList<>(); List<String> o = new ArrayList<>(); List<String> s = new ArrayList<>(); List<Integer> i = new ArrayList<>(); } : // loop-fusion directive LFUSION group_option[$l] collapse_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_FUSION); } // loop-interchange directive | LINTERCHANGE indexes_option[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } // loop-extract directive | LEXTRACT range_option mapping_option_list[m] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_EXTRACT); $l.setRange($range_option.r); $l.setMappings(m); } // remove directive | REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); } | END REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); $l.setEndPragma(); } // Kcache directive | KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); } | KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); $l.setInitClause(); } // Array notation transformation directive | ARRAY_TRANS induction_optional[$l] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); } | END ARRAY_TRANS { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); $l.setEndPragma(); } // loop-hoist directive | LHOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF { $l.setHoistInductionVars(o); $l.setDirective(ClawDirective.LOOP_HOIST); } | END LHOIST EOF { $l.setDirective(ClawDirective.LOOP_HOIST); $l.setEndPragma(); } // on the fly directive | ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')' { $l.setDirective(ClawDirective.ARRAY_TO_CALL); $l.setFctParams(o); $l.setFctName($fct_name.text); $l.setArrayName($array_name.text); } // | DEFINE DIMENSION id=IDENTIFIER '(' lower=range_id ',' upper=range_id ')' { $l.setDirective(ClawDirective.DEFINE); ClawDimension cd = new ClawDimension($id.text, $lower.text, $upper.text); $l.setDimensionClauseValue(cd); } | PARALLELIZE DATA '(' ids_list[o] ')' OVER '(' ids_or_colon_list[s] ')' { $l.setDirective(ClawDirective.PARALLELIZE); $l.setDataClause(o); $l.setOverClause(s); } ; group_option[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupClause($group_name.text); } | /* empty */ ; collapse_optional[ClawLanguage l]: COLLAPSE '(' n=NUMBER ')' { $l.setCollapseClause($n.text); } | /* empty */ ; fusion_optional[ClawLanguage l]: FUSION group_option[$l] { $l.setFusionClause(); } | /* empty */ ; parallel_optional[ClawLanguage l]: PARALLEL { $l.setParallelClause(); } | /* empty */ ; acc_optional[ClawLanguage l] @init{ List<String> tempAcc = new ArrayList<>(); } : ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); } | /* empty */ ; interchange_optional[ClawLanguage l]: INTERCHANGE indexes_option[$l] { $l.setInterchangeClause(); } | /* empty */ ; induction_optional[ClawLanguage l] @init{ List<String> temp = new ArrayList<>(); } : INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); } | /* empty */ ; data_clause[ClawLanguage l] @init { List<String> temp = new ArrayList<>(); } : DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); } ; private_optional[ClawLanguage l]: PRIVATE { $l.setPrivateClause(); } | /* empty */ ; reshape_optional[ClawLanguage l] @init{ List<ClawReshapeInfo> r = new ArrayList(); } : RESHAPE '(' reshape_list[r] ')' { $l.setReshapeClauseValues(r); } | /* empty */ ; reshape_element returns [ClawReshapeInfo i] @init{ List<Integer> temp = new ArrayList(); } : array_name=IDENTIFIER '(' target_dim=NUMBER ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } | array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } ; reshape_list[List<ClawReshapeInfo> r]: info=reshape_element { $r.add($info.i); } ',' reshape_list[$r] | info=reshape_element { $r.add($info.i); } ; identifiers[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids] ; identifiers_list[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids] ; integers[List<Integer> ints]: ; integers_list[List<Integer> ints]: i=NUMBER { $ints.add(Integer.parseInt($i.text)); } | i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints] ; indexes_option[ClawLanguage l] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $l.setIndexes(indexes); } | /* empty */ ; offset_list_optional[List<Integer> offsets]: OFFSET '(' offset_list[$offsets] ')' | /* empty */ ; offset_list[List<Integer> offsets]: offset[$offsets] | offset[$offsets] ',' offset_list[$offsets] ; offset[List<Integer> offsets]: n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } | '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); } | '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(Constant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; range_id returns [String text]: n=NUMBER { $text = $n.text; } | i=IDENTIFIER { $text = $i.text; } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; mapping_var_list[List<ClawMappingVar> vars]: mv=mapping_var { $vars.add($mv.mappingVar); } | mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars] ; mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>(); List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>(); $mapping.setMappedVariables(listMapped); $mapping.setMappingVariables(listMapping); } : MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')' ; mapping_option_list[List<ClawMapping> mappings]: m=mapping_option { $mappings.add($m.mapping); } | m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings] ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // Directives ARRAY_TRANS : 'array-transform'; ARRAY_TO_CALL: 'call'; DEFINE : 'define'; END : 'end'; KCACHE : 'kcache'; LEXTRACT : 'loop-extract'; LFUSION : 'loop-fusion'; LHOIST : 'loop-hoist'; LINTERCHANGE : 'loop-interchange'; PARALLELIZE : 'parallelize'; REMOVE : 'remove'; // Clauses ACC : 'acc'; COLLAPSE : 'collapse'; DATA : 'data'; DIMENSION : 'dimension'; FUSION : 'fusion'; GROUP : 'group'; INDUCTION : 'induction'; INIT : 'init'; INTERCHANGE : 'interchange'; MAP : 'map'; OFFSET : 'offset'; OVER : 'over'; PARALLEL : 'parallel'; PRIVATE : 'private'; RANGE : 'range'; RESHAPE : 'reshape'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : [0-9] ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
Fix ids_or_colon_list
Fix ids_or_colon_list
ANTLR
bsd-2-clause
clementval/claw-compiler,clementval/claw-compiler
2620459a5b3d7a577474c7d0d68d60d724c5d24a
projects/batfish/src/org/batfish/grammar/cisco/Cisco_isis.g4
projects/batfish/src/org/batfish/grammar/cisco/Cisco_isis.g4
parser grammar Cisco_isis; import Cisco_common; options { tokenVocab = CiscoLexer; } address_family_iis_stanza : ADDRESS_FAMILY ( IPV4 | IPV6 ) ( UNICAST | MULTICAST ) NEWLINE common_iis_stanza* ; address_family_is_stanza : ADDRESS_FAMILY ( IPV4 | IPV6 ) ( UNICAST | MULTICAST )? NEWLINE isaf_stanza* address_family_footer ; advertise_is_stanza : ADVERTISE PASSIVE_ONLY NEWLINE ; circuit_type_iis_stanza : CIRCUIT_TYPE ( LEVEL_2_ONLY | LEVEL_2 ) NEWLINE ; common_iis_stanza : circuit_type_iis_stanza | metric_iis_stanza | null_iis_stanza | passive_iis_stanza ; common_is_stanza : advertise_is_stanza | is_type_is_stanza | metric_is_stanza | metric_style_is_stanza | net_is_stanza | null_is_stanza | redistribute_connected_is_stanza | redistribute_eigrp_is_stanza_null | redistribute_static_is_stanza | passive_interface_is_stanza | summary_address_is_stanza ; iis_stanza : address_family_iis_stanza | common_iis_stanza ; interface_is_stanza : INTERFACE iname = interface_name NEWLINE iis_stanza* ; is_stanza : address_family_is_stanza | common_is_stanza | interface_is_stanza | unrecognized_line ; is_type_is_stanza : IS_TYPE ( LEVEL_1 | LEVEL_2 | LEVEL_2_ONLY ) NEWLINE ; isaf_stanza : common_is_stanza ; metric_iis_stanza : METRIC DEC NEWLINE ; metric_is_stanza : METRIC DEC ( LEVEL DEC )? NEWLINE ; metric_style_is_stanza : METRIC_STYLE ( WIDE | LEVEL_2 )* NEWLINE ; net_is_stanza : NET ISO_ADDRESS NEWLINE ; null_iis_stanza : NO? ( BFD | HELLO_INTERVAL | HELLO_PADDING | HELLO_PASSWORD | POINT_TO_POINT ) ~NEWLINE* NEWLINE ; null_is_stanza : NO? ( ADJACENCY_CHECK | AUTHENTICATION | BFD | FAST_FLOOD | HELLO | ISPF | LOG | LOG_ADJACENCY_CHANGES | LSP_GEN_INTERVAL | LSP_PASSWORD | LSP_REFRESH_INTERVAL | MAX_LSP_LIFETIME | MAXIMUM_PATHS | MPLS | MULTI_TOPOLOGY | NSF | NSR | PRC_INTERVAL | ( REDISTRIBUTE MAXIMUM_PREFIX ) | SET_OVERLOAD_BIT | SINGLE_TOPOLOGY | SPF_INTERVAL ) ~NEWLINE* NEWLINE ; passive_iis_stanza : PASSIVE NEWLINE ; passive_interface_default_is_stanza : NO? PASSIVE_INTERFACE DEFAULT NEWLINE ; passive_interface_is_stanza : NO? PASSIVE_INTERFACE name = interface_name NEWLINE ; redistribute_connected_is_stanza : REDISTRIBUTE CONNECTED ( IP | LEVEL_1 | LEVEL_1_2 | LEVEL_2 | ( METRIC metric = DEC ) | ( ROUTE_MAP map = VARIABLE ) | ( ROUTE_POLICY policy = VARIABLE ) )* NEWLINE ; redistribute_eigrp_is_stanza_null : REDISTRIBUTE EIGRP ( DEC | IP | LEVEL_1 | LEVEL_1_2 | LEVEL_2 | ( METRIC metric = DEC ) | ( ROUTE_MAP map = VARIABLE ) | ( ROUTE_POLICY policy = VARIABLE ) )* NEWLINE ; redistribute_static_is_stanza : REDISTRIBUTE STATIC ( CLNS | IP | LEVEL_1 | LEVEL_1_2 | LEVEL_2 | ( METRIC metric = DEC ) | ( ROUTE_MAP map = VARIABLE ) | ( ROUTE_POLICY policy = VARIABLE ) )* NEWLINE ; router_isis_stanza : ROUTER ISIS ( name = variable )? NEWLINE is_stanza* ; summary_address_is_stanza : SUMMARY_ADDRESS ip = IP_ADDRESS mask = IP_ADDRESS ( LEVEL_1 | LEVEL_1_2 | LEVEL_2 | ( METRIC metric = DEC ) | ( TAG tag = DEC ) )* NEWLINE ;
parser grammar Cisco_isis; import Cisco_common; options { tokenVocab = CiscoLexer; } address_family_iis_stanza : ADDRESS_FAMILY ( IPV4 | IPV6 ) ( UNICAST | MULTICAST ) NEWLINE common_iis_stanza* ; address_family_is_stanza : ADDRESS_FAMILY ( IPV4 | IPV6 ) ( UNICAST | MULTICAST )? NEWLINE isaf_stanza* address_family_footer ; advertise_is_stanza : ADVERTISE PASSIVE_ONLY NEWLINE ; circuit_type_iis_stanza : CIRCUIT_TYPE ( LEVEL_2_ONLY | LEVEL_2 ) NEWLINE ; common_iis_stanza : circuit_type_iis_stanza | metric_iis_stanza | null_iis_stanza | passive_iis_stanza ; common_is_stanza : advertise_is_stanza | is_type_is_stanza | metric_is_stanza | metric_style_is_stanza | net_is_stanza | null_is_stanza | redistribute_connected_is_stanza | redistribute_eigrp_is_stanza_null | redistribute_static_is_stanza | passive_interface_default_is_stanza | passive_interface_is_stanza | summary_address_is_stanza ; iis_stanza : address_family_iis_stanza | common_iis_stanza ; interface_is_stanza : INTERFACE iname = interface_name NEWLINE iis_stanza* ; is_stanza : address_family_is_stanza | common_is_stanza | interface_is_stanza | unrecognized_line ; is_type_is_stanza : IS_TYPE ( LEVEL_1 | LEVEL_2 | LEVEL_2_ONLY ) NEWLINE ; isaf_stanza : common_is_stanza ; metric_iis_stanza : METRIC DEC NEWLINE ; metric_is_stanza : METRIC DEC ( LEVEL DEC )? NEWLINE ; metric_style_is_stanza : METRIC_STYLE ( WIDE | LEVEL_2 )* NEWLINE ; net_is_stanza : NET ISO_ADDRESS NEWLINE ; null_iis_stanza : NO? ( BFD | HELLO_INTERVAL | HELLO_PADDING | HELLO_PASSWORD | POINT_TO_POINT ) ~NEWLINE* NEWLINE ; null_is_stanza : NO? ( ADJACENCY_CHECK | AUTHENTICATION | BFD | FAST_FLOOD | HELLO | ISPF | LOG | LOG_ADJACENCY_CHANGES | LSP_GEN_INTERVAL | LSP_PASSWORD | LSP_REFRESH_INTERVAL | MAX_LSP_LIFETIME | MAXIMUM_PATHS | MPLS | MULTI_TOPOLOGY | NSF | NSR | PRC_INTERVAL | ( REDISTRIBUTE MAXIMUM_PREFIX ) | SET_OVERLOAD_BIT | SINGLE_TOPOLOGY | SPF_INTERVAL ) ~NEWLINE* NEWLINE ; passive_iis_stanza : PASSIVE NEWLINE ; passive_interface_default_is_stanza : NO? PASSIVE_INTERFACE DEFAULT NEWLINE ; passive_interface_is_stanza : NO? PASSIVE_INTERFACE name = interface_name NEWLINE ; redistribute_connected_is_stanza : REDISTRIBUTE CONNECTED ( IP | LEVEL_1 | LEVEL_1_2 | LEVEL_2 | ( METRIC metric = DEC ) | ( ROUTE_MAP map = VARIABLE ) | ( ROUTE_POLICY policy = VARIABLE ) )* NEWLINE ; redistribute_eigrp_is_stanza_null : REDISTRIBUTE EIGRP ( DEC | IP | LEVEL_1 | LEVEL_1_2 | LEVEL_2 | ( METRIC metric = DEC ) | ( ROUTE_MAP map = VARIABLE ) | ( ROUTE_POLICY policy = VARIABLE ) )* NEWLINE ; redistribute_static_is_stanza : REDISTRIBUTE STATIC ( CLNS | IP | LEVEL_1 | LEVEL_1_2 | LEVEL_2 | ( METRIC metric = DEC ) | ( ROUTE_MAP map = VARIABLE ) | ( ROUTE_POLICY policy = VARIABLE ) )* NEWLINE ; router_isis_stanza : ROUTER ISIS ( name = variable )? NEWLINE is_stanza* ; summary_address_is_stanza : SUMMARY_ADDRESS ip = IP_ADDRESS mask = IP_ADDRESS ( LEVEL_1 | LEVEL_1_2 | LEVEL_2 | ( METRIC metric = DEC ) | ( TAG tag = DEC ) )* NEWLINE ;
fix missing reference to passive_interface_default_is_stanza
fix missing reference to passive_interface_default_is_stanza
ANTLR
apache-2.0
arifogel/batfish,intentionet/batfish,arifogel/batfish,intentionet/batfish,dhalperi/batfish,batfish/batfish,intentionet/batfish,intentionet/batfish,batfish/batfish,batfish/batfish,dhalperi/batfish,dhalperi/batfish,intentionet/batfish,arifogel/batfish
94abd1d6ed04a23151ff8ef7f6e5a96c0c85b353
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
/* Todo: * - Comments justifying and explaining every rule. */ lexer grammar CreoleTokens; options { superClass=ContextSensitiveLexer; } @members { Formatting bold; Formatting italic; Formatting strike; public void setupFormatting() { bold = new Formatting("**"); italic = new Formatting("//"); strike = new Formatting("--"); inlineFormatting.add(bold); inlineFormatting.add(italic); inlineFormatting.add(strike); } public boolean inHeader = false; public boolean start = false; public int listLevel = 0; boolean nowiki = false; boolean cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = false; boolean intr = false; public void doHdr() { String prefix = getText().trim(); boolean seekback = false; if(!prefix.substring(prefix.length() - 1).equals("=")) { prefix = prefix.substring(0, prefix.length() - 1); seekback = true; } if(prefix.length() <= 6) { if(seekback) { seek(-1); } setText(prefix); inHeader = true; } else { setType(Any); } } public void setStart() { String next1 = next(); String next2 = get(1); start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#")); } public void doList(int level) { listLevel = level; seek(-1); setStart(); resetFormatting(); } public void doUrl() { String url = getText(); String last = url.substring(url.length()-1); String next = next(); if((last + next).equals("//") || last.equals(".") || last.equals(",") || last.equals(")")) { seek(-1); setText(url.substring(0, url.length() - 1)); } } public void breakOut() { resetFormatting(); listLevel = 0; inHeader = false; intr = false; nowiki = false; cpp = false; html = false; java = false; xhtml = false; xml = false; } public String[] thisKillsTheFormatting() { String[] ends = new String[4]; if(inHeader || intr || listLevel > 0) { ends[0] = "\n"; } else { ends[0] = null; } if(intr) { ends[1] = "|"; } else { ends[1] = null; } ends[2] = "\n\n"; ends[3] = "\r\n\r\n"; return ends; } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' WS? {doHdr();} ; HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ; /* ***** Lists ***** */ U1 : START '*' ~'*' {doList(1);} ; U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ; U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ; U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ; U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ; O1 : START '#' ~'#' {doList(1);} ; O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ; O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ; O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ; O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+? {breakOut();} ; /* ***** Tables ***** */ TdStartLn : LINE '|' {intr=true; setType(TdStart);} ; ThStartLn : LINE '|=' {intr=true; setType(ThStart);} ; RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ; TdStart : '|' {intr}? {breakOut(); intr=true;} ; ThStart : '|=' {intr}? {breakOut(); intr=true;} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active}? {setFormatting(italic, Any);} ; SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ; BEnd : '**' {bold.active}? {unsetFormatting(bold);} ; IEnd : '//' {italic.active}? {unsetFormatting(italic);} ; SEnd : '--' {strike.active}? {unsetFormatting(strike);} ; NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ; StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ; StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ; StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ; StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ; StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ; /* ***** Links ***** */ LiSt : '[[' -> mode(LINK) ; ImSt : '{{' -> mode(LINK) ; /* ***** Breaks ***** */ InlineBrk : '\\\\' ; ParBreak : LineBreak LineBreak+ {breakOut();} ; LineBreak : '\r'? '\n' ; /* ***** Links ***** */ RawUrl : (URL {doUrl();} | ATTACHMENT {checkBounds("[a-zA-Z0-9@\\./]", "[a-zA-Z0-9@/]")}?) ; fragment URL : (('http' 's'? | 'ftp') '://' | 'mailto:') (~(' '|'\t'|'\r'|'\n'|'/'|'|'|'['|']')+ '/'?)+ ; fragment ATTACHMENT : UPPER ALNUM* ALPHA ALNUM+ '.' LOWER LOWNUM+ ; WikiWords : ((INTERWIKI UPNUM | UPPER) (ABBR | CAMEL) | INTERWIKI UPNUM+) {checkBounds("[\\.\\w]", "\\w")}? ; fragment INTERWIKI : ALPHA+ ':' ; fragment ABBR : UPPER UPPER+ ; fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ; /* ***** Macros ***** */ MacroSt : '<<' -> mode(MACRO) ; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t')+ ; fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ; fragment START : {start}? | LINE ; fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*; fragment LOWNUM : (LOWER | DIGIT) ; fragment UPNUM : (UPPER | DIGIT) ; fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ; ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ; Sep : ' '* '|' ' '*; InLink : ~(']'|'}'|'|'|'\r'|'\n')+ {setText(getText().trim());}; mode MACRO; MacroName : ~(':'|'>')+ ; MacroSep : ':' -> mode(MACRO_ARGS) ; mode MACRO_ARGS; MacroArgs : . -> more ; MacroEnd : '>>' -> mode(DEFAULT_MODE) ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' (~'}' {seek(-1);} | EOF) {nowiki}? -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
/* Todo: * - Comments justifying and explaining every rule. */ lexer grammar CreoleTokens; options { superClass=ContextSensitiveLexer; } @members { Formatting bold; Formatting italic; Formatting strike; public void setupFormatting() { bold = new Formatting("**"); italic = new Formatting("//"); strike = new Formatting("--"); inlineFormatting.add(bold); inlineFormatting.add(italic); inlineFormatting.add(strike); } public boolean inHeader = false; public boolean start = false; public int listLevel = 0; boolean nowiki = false; boolean cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = false; boolean intr = false; public void doHdr() { String prefix = getText().trim(); boolean seekback = false; if(!prefix.substring(prefix.length() - 1).equals("=")) { prefix = prefix.substring(0, prefix.length() - 1); seekback = true; } if(prefix.length() <= 6) { if(seekback) { seek(-1); } setText(prefix); inHeader = true; } else { setType(Any); } } public void setStart() { String next1 = next(); String next2 = get(1); start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#")); } public void doList(int level) { listLevel = level; seek(-1); setStart(); resetFormatting(); } public void doUrl() { String url = getText(); String last = url.substring(url.length()-1); String next = next(); if((last + next).equals("//") || last.equals(".") || last.equals(",") || last.equals(")")) { seek(-1); setText(url.substring(0, url.length() - 1)); } } public void breakOut() { resetFormatting(); listLevel = 0; inHeader = false; intr = false; nowiki = false; cpp = false; html = false; java = false; xhtml = false; xml = false; } public String[] thisKillsTheFormatting() { String[] ends = new String[4]; if(inHeader || intr || listLevel > 0) { ends[0] = "\n"; } else { ends[0] = null; } if(intr) { ends[1] = "|"; } else { ends[1] = null; } ends[2] = "\n\n"; ends[3] = "\r\n\r\n"; return ends; } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' WS? {doHdr();} ; HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ; /* ***** Lists ***** */ U1 : START '*' ~'*' {doList(1);} ; U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ; U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ; U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ; U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ; O1 : START '#' ~'#' {doList(1);} ; O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ; O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ; O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ; O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+? {breakOut();} ; /* ***** Tables ***** */ TdStartLn : LINE '|' {intr=true; setType(TdStart);} ; ThStartLn : LINE '|=' {intr=true; setType(ThStart);} ; RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ; TdStart : '|' {intr}? {breakOut(); intr=true;} ; ThStart : '|=' {intr}? {breakOut(); intr=true;} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active}? {setFormatting(italic, Any);} ; SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ; BEnd : '**' {bold.active}? {unsetFormatting(bold);} ; IEnd : '//' {italic.active}? {unsetFormatting(italic);} ; SEnd : '--' {strike.active}? {unsetFormatting(strike);} ; NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ; StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ; StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ; StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ; StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ; StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ; /* ***** Links ***** */ LiSt : '[[' -> mode(LINK) ; ImSt : '{{' -> mode(LINK) ; /* ***** Breaks ***** */ InlineBrk : '\\\\' ; ParBreak : LineBreak LineBreak+ {breakOut();} ; LineBreak : '\r'? '\n' ; /* ***** Links ***** */ RawUrl : (URL {doUrl();} | ATTACHMENT {checkBounds("[a-zA-Z0-9@\\./]", "[a-zA-Z0-9@/]")}?) ; fragment URL : (('http' 's'? | 'ftp') '://' | 'mailto:') (~(' '|'\t'|'\r'|'\n'|'/'|'|'|'['|']')+ '/'?)+ ; fragment ATTACHMENT : UPPER ALNUM* ALPHA ALNUM+ '.' LOWER LOWNUM+ ; WikiWords : ((INTERWIKI UPNUM | UPPER) (ABBR | CAMEL) | INTERWIKI UPNUM+) {checkBounds("[\\.\\w]", "\\w")}? ; fragment INTERWIKI : ALPHA ALNUM+ ':' ; fragment ABBR : UPPER UPPER+ ; fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ; /* ***** Macros ***** */ MacroSt : '<<' -> mode(MACRO) ; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t')+ ; fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ; fragment START : {start}? | LINE ; fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*; fragment LOWNUM : (LOWER | DIGIT) ; fragment UPNUM : (UPPER | DIGIT) ; fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ; ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ; Sep : ' '* '|' ' '*; InLink : ~(']'|'}'|'|'|'\r'|'\n')+ {setText(getText().trim());}; mode MACRO; MacroName : ~(':'|'>')+ ; MacroSep : ':' -> mode(MACRO_ARGS) ; mode MACRO_ARGS; MacroArgs : . -> more ; MacroEnd : '>>' -> mode(DEFAULT_MODE) ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' (~'}' {seek(-1);} | EOF) {nowiki}? -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
Allow digits in interwiki link prefixes
Allow digits in interwiki link prefixes
ANTLR
apache-2.0
CoreFiling/reviki,strr/reviki,CoreFiling/reviki,CoreFiling/reviki,ashirley/reviki,ashirley/reviki,CoreFiling/reviki,ashirley/reviki,ashirley/reviki,ashirley/reviki,strr/reviki,strr/reviki,CoreFiling/reviki,strr/reviki,strr/reviki
7191703f91c6985037e698b81a6b1af28b5de9c0
sql/hive/grammar/FromClauseParser.g4
sql/hive/grammar/FromClauseParser.g4
/** Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @author Canwei He */ parser grammar FromClauseParser; //----------------------------------------------------------------------------------- tableAllColumns : STAR | tableName DOT STAR ; // (table|column) tableOrColumn : identifier ; expressionList : expression (COMMA expression)* ; aliasList : identifier (COMMA identifier)* ; //----------------------- Rules for parsing fromClause ------------------------------ // from [col1, col2, col3] table1, [col4, col5] table2 fromClause : KW_FROM fromSource ; fromSource : uniqueJoinToken uniqueJoinSource (COMMA uniqueJoinSource)+ | joinSource ; atomjoinSource : tableSource lateralView* | virtualTableSource lateralView* | subQuerySource lateralView* | partitionedTableFunction lateralView* | LPAREN joinSource RPAREN ; joinSource : atomjoinSource (joinToken joinSourcePart (KW_ON expression {$joinToken.start.getType() != COMMA}? | KW_USING columnParenthesesList {$joinToken.start.getType() != COMMA}?)?)* ; joinSourcePart : (tableSource | virtualTableSource | subQuerySource | partitionedTableFunction) lateralView ; uniqueJoinSource : KW_PRESERVE? uniqueJoinTableSource uniqueJoinExpr ; uniqueJoinExpr : LPAREN expressionList RPAREN ; uniqueJoinToken : KW_UNIQUEJOIN ; joinToken : KW_JOIN | KW_INNER KW_JOIN | COMMA | KW_CROSS KW_JOIN | KW_LEFT KW_OUTER? KW_JOIN | KW_RIGHT KW_OUTER? KW_JOIN | KW_FULL KW_OUTER? KW_JOIN | KW_LEFT KW_SEMI KW_JOIN ; lateralView : KW_LATERAL KW_VIEW KW_OUTER function tableAlias (KW_AS identifier (COMMA identifier)*)? | COMMA? KW_LATERAL KW_VIEW function tableAlias (KW_AS identifier (COMMA identifier)*)? | COMMA? KW_LATERAL KW_TABLE LPAREN valuesClause RPAREN KW_AS? tableAlias (LPAREN identifier (COMMA identifier)* RPAREN)? ; tableAlias : identifier ; tableBucketSample : KW_TABLESAMPLE LPAREN KW_BUCKET Number KW_OUT KW_OF Number (KW_ON expression (COMMA expression)*)? RPAREN ; splitSample : KW_TABLESAMPLE LPAREN Number (KW_PERCENT|KW_ROWS) RPAREN | KW_TABLESAMPLE LPAREN ByteLengthLiteral RPAREN ; tableSample : tableBucketSample | splitSample ; tableSource : tableName tableProperties? tableSample? (KW_AS? identifier)? ; uniqueJoinTableSource : tableName tableSample? (KW_AS? identifier)? ; tableName : identifier DOT identifier | identifier ; viewName : (identifier DOT)? identifier ; subQuerySource : LPAREN queryStatementExpression RPAREN KW_AS? identifier ; //---------------------- Rules for parsing PTF clauses ----------------------------- partitioningSpec : partitionByClause orderByClause? | orderByClause | distributeByClause sortByClause? | sortByClause | clusterByClause ; partitionTableFunctionSource : subQuerySource | tableSource | partitionedTableFunction ; partitionedTableFunction : identifier LPAREN KW_ON partitionTableFunctionSource partitioningSpec? (Identifier LPAREN expression RPAREN ( COMMA Identifier LPAREN expression RPAREN)*)? RPAREN identifier? ; //----------------------- Rules for parsing whereClause ----------------------------- // where a=b and ... whereClause : KW_WHERE searchCondition ; searchCondition : expression ; //----------------------------------------------------------------------------------- //-------- Row Constructor ---------------------------------------------------------- //in support of SELECT * FROM (VALUES(1,2,3),(4,5,6),...) as FOO(a,b,c) and // INSERT INTO <table> (col1,col2,...) VALUES(...),(...),... // INSERT INTO <table> (col1,col2,...) SELECT * FROM (VALUES(1,2,3),(4,5,6),...) as Foo(a,b,c) /* VALUES(1),(2) means 2 rows, 1 column each. VALUES(1,2),(3,4) means 2 rows, 2 columns each. VALUES(1,2,3) means 1 row, 3 columns */ valuesClause : KW_VALUES valuesTableConstructor ; valuesTableConstructor : valueRowConstructor (COMMA valueRowConstructor)* ; valueRowConstructor : expressionsInParenthesis ; /* This represents a clause like this: TABLE(VALUES(1,2),(2,3)) as VirtTable(col1,col2) */ virtualTableSource : KW_TABLE LPAREN valuesClause RPAREN KW_AS? tableAlias (LPAREN identifier (COMMA identifier)*)? RPAREN ; //-----------------------------------------------------------------------------------
/** Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @author Canwei He */ parser grammar FromClauseParser; //----------------------------------------------------------------------------------- tableAllColumns : STAR | tableName DOT STAR ; // (table|column) tableOrColumn : identifier ; expressionList : expression (COMMA expression)* ; aliasList : identifier (COMMA identifier)* ; //----------------------- Rules for parsing fromClause ------------------------------ // from [col1, col2, col3] table1, [col4, col5] table2 fromClause : KW_FROM fromSource ; fromSource : uniqueJoinToken uniqueJoinSource (COMMA uniqueJoinSource)+ | joinSource ; atomjoinSource : tableSource lateralView* | virtualTableSource lateralView* | subQuerySource lateralView* | partitionedTableFunction lateralView* | LPAREN joinSource RPAREN ; joinSource : atomjoinSource (joinToken joinSourcePart (KW_ON expression {$joinToken.start.getType() != COMMA}? | KW_USING columnParenthesesList {$joinToken.start.getType() != COMMA}?)?)* ; joinSourcePart : (tableSource | virtualTableSource | subQuerySource | partitionedTableFunction) lateralView* ; uniqueJoinSource : KW_PRESERVE? uniqueJoinTableSource uniqueJoinExpr ; uniqueJoinExpr : LPAREN expressionList RPAREN ; uniqueJoinToken : KW_UNIQUEJOIN ; joinToken : KW_JOIN | KW_INNER KW_JOIN | COMMA | KW_CROSS KW_JOIN | KW_LEFT KW_OUTER? KW_JOIN | KW_RIGHT KW_OUTER? KW_JOIN | KW_FULL KW_OUTER? KW_JOIN | KW_LEFT KW_SEMI KW_JOIN ; lateralView : KW_LATERAL KW_VIEW KW_OUTER function tableAlias (KW_AS identifier (COMMA identifier)*)? | COMMA? KW_LATERAL KW_VIEW function tableAlias (KW_AS identifier (COMMA identifier)*)? | COMMA? KW_LATERAL KW_TABLE LPAREN valuesClause RPAREN KW_AS? tableAlias (LPAREN identifier (COMMA identifier)* RPAREN)? ; tableAlias : identifier ; tableBucketSample : KW_TABLESAMPLE LPAREN KW_BUCKET Number KW_OUT KW_OF Number (KW_ON expression (COMMA expression)*)? RPAREN ; splitSample : KW_TABLESAMPLE LPAREN Number (KW_PERCENT|KW_ROWS) RPAREN | KW_TABLESAMPLE LPAREN ByteLengthLiteral RPAREN ; tableSample : tableBucketSample | splitSample ; tableSource : tableName tableProperties? tableSample? (KW_AS? identifier)? ; uniqueJoinTableSource : tableName tableSample? (KW_AS? identifier)? ; tableName : identifier DOT identifier | identifier ; viewName : (identifier DOT)? identifier ; subQuerySource : LPAREN queryStatementExpression RPAREN KW_AS? identifier ; //---------------------- Rules for parsing PTF clauses ----------------------------- partitioningSpec : partitionByClause orderByClause? | orderByClause | distributeByClause sortByClause? | sortByClause | clusterByClause ; partitionTableFunctionSource : subQuerySource | tableSource | partitionedTableFunction ; partitionedTableFunction : identifier LPAREN KW_ON partitionTableFunctionSource partitioningSpec? (Identifier LPAREN expression RPAREN ( COMMA Identifier LPAREN expression RPAREN)*)? RPAREN identifier? ; //----------------------- Rules for parsing whereClause ----------------------------- // where a=b and ... whereClause : KW_WHERE searchCondition ; searchCondition : expression ; //----------------------------------------------------------------------------------- //-------- Row Constructor ---------------------------------------------------------- //in support of SELECT * FROM (VALUES(1,2,3),(4,5,6),...) as FOO(a,b,c) and // INSERT INTO <table> (col1,col2,...) VALUES(...),(...),... // INSERT INTO <table> (col1,col2,...) SELECT * FROM (VALUES(1,2,3),(4,5,6),...) as Foo(a,b,c) /* VALUES(1),(2) means 2 rows, 1 column each. VALUES(1,2),(3,4) means 2 rows, 2 columns each. VALUES(1,2,3) means 1 row, 3 columns */ valuesClause : KW_VALUES valuesTableConstructor ; valuesTableConstructor : valueRowConstructor (COMMA valueRowConstructor)* ; valueRowConstructor : expressionsInParenthesis ; /* This represents a clause like this: TABLE(VALUES(1,2),(2,3)) as VirtTable(col1,col2) */ virtualTableSource : KW_TABLE LPAREN valuesClause RPAREN KW_AS? tableAlias (LPAREN identifier (COMMA identifier)*)? RPAREN ; //-----------------------------------------------------------------------------------
fix join condition clause parsing
fix join condition clause parsing
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
9112118a4369f0d027afea23df390fa832ad74eb
omni-cx2x/src/cx2x/translator/language/Claw.g4
omni-cx2x/src/cx2x/translator/language/Claw.g4
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import java.util.List; import java.util.ArrayList; import cx2x.translator.common.Constant; import cx2x.translator.misc.Utility; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage l] @init{ $l = new ClawLanguage(); } : CLAW directive[$l] ; ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; directive[ClawLanguage l] @init{ List<ClawMapping> m = new ArrayList<>(); List<String> o = new ArrayList<>(); } : // loop-fusion directive LFUSION { $l.setDirective(ClawDirective.LOOP_FUSION); } group_option[$l] EOF // loop-interchange directive | LINTERCHANGE { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } indexes_option[$l] EOF // loop-extract directive | LEXTRACT range_option mapping_option_list[m] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_EXTRACT); $l.setRange($range_option.r); $l.setMappings(m); } // remove directive | REMOVE { $l.setDirective(ClawDirective.REMOVE); } EOF | END REMOVE { $l.setDirective(ClawDirective.END_REMOVE); } EOF // Kcache directive | KCACHE offset_list_optional[o] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(o); } // Array notation transformation directive | ARRAY_TRANS fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); } ; group_option[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupOption($group_name.text); } | /* empty */ ; fusion_optional[ClawLanguage l]: FUSION group_option[$l] { $l.setFusionOption(); } | /* empty */ ; parallel_optional[ClawLanguage l]: PARALLEL { $l.setParallelOption(); } | /* empty */ ; acc_optional[ClawLanguage l] @init{ List<String> tempAcc = new ArrayList<>(); } : ACC '(' identifiers[tempAcc] ')' { $l.setAccClauses(Utility.join(" ", tempAcc)); } | /* empty */ ; identifiers[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids] ; indexes_option[ClawLanguage l] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $l.setIndexes(indexes); } | /* empty */ ; offset_list_optional[List<String> offsets]: offset_list[$offsets] | /* empty */ ; offset_list[List<String> offsets]: offset[$offsets] | offset[$offsets] offset_list[$offsets] ; offset[List<String> offsets]: n=NUMBER { $offsets.add($n.text); } | '-' n=NUMBER { $offsets.add("-" + $n.text); } | '+' n=NUMBER { $offsets.add($n.text); } ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(Constant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; range_id returns [String text]: n=NUMBER { $text = $n.text; } | i=IDENTIFIER { $text = $i.text; } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; mapping_var_list[List<ClawMappingVar> vars]: mv=mapping_var { $vars.add($mv.mappingVar); } | mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars] ; mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>(); List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>(); $mapping.setMappedVariables(listMapped); $mapping.setMappingVariables(listMapping); } : MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')' ; mapping_option_list[List<ClawMapping> mappings]: m=mapping_option { $mappings.add($m.mapping); } | m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings] ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // Directives ARRAY_TRANS : 'array-transform'; END : 'end'; KCACHE : 'kcache'; LFUSION : 'loop-fusion'; LINTERCHANGE : 'loop-interchange'; LEXTRACT : 'loop-extract'; REMOVE : 'remove'; // Options ACC : 'acc'; FUSION : 'fusion'; GROUP : 'group'; MAP : 'map'; PARALLEL : 'parallel'; RANGE : 'range'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : [0-9] ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import java.util.List; import java.util.ArrayList; import cx2x.translator.common.Constant; import cx2x.translator.misc.Utility; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage l] @init{ $l = new ClawLanguage(); } : CLAW directive[$l] ; ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; directive[ClawLanguage l] @init{ List<ClawMapping> m = new ArrayList<>(); List<String> o = new ArrayList<>(); } : // loop-fusion directive LFUSION { $l.setDirective(ClawDirective.LOOP_FUSION); } group_option[$l] EOF // loop-interchange directive | LINTERCHANGE { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } indexes_option[$l] EOF // loop-extract directive | LEXTRACT range_option mapping_option_list[m] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_EXTRACT); $l.setRange($range_option.r); $l.setMappings(m); } // remove directive | REMOVE { $l.setDirective(ClawDirective.REMOVE); } EOF | END REMOVE { $l.setDirective(ClawDirective.END_REMOVE); } EOF // Kcache directive | KCACHE offset_list_optional[o] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(o); } // Array notation transformation directive | ARRAY_TRANS fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); } ; group_option[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupOption($group_name.text); } | /* empty */ ; fusion_optional[ClawLanguage l]: FUSION group_option[$l] { $l.setFusionOption(); } | /* empty */ ; parallel_optional[ClawLanguage l]: PARALLEL { $l.setParallelOption(); } | /* empty */ ; acc_optional[ClawLanguage l] @init{ List<String> tempAcc = new ArrayList<>(); } : ACC '(' identifiers[tempAcc] ')' { $l.setAccClauses(Utility.join(" ", tempAcc)); } | /* empty */ ; identifiers[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids] ; indexes_option[ClawLanguage l] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $l.setIndexes(indexes); } | /* empty */ ; offset_list_optional[List<String> offsets]: offset_list[$offsets] | /* empty */ ; offset_list[List<String> offsets]: offset[$offsets] | offset[$offsets] offset_list[$offsets] ; offset[List<String> offsets]: n=NUMBER { $offsets.add($n.text); } | '-' n=NUMBER { $offsets.add("-" + $n.text); } | '+' n=NUMBER { $offsets.add($n.text); } ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(Constant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; range_id returns [String text]: n=NUMBER { $text = $n.text; } | i=IDENTIFIER { $text = $i.text; } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; mapping_var_list[List<ClawMappingVar> vars]: mv=mapping_var { $vars.add($mv.mappingVar); } | mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars] ; mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>(); List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>(); $mapping.setMappedVariables(listMapped); $mapping.setMappingVariables(listMapping); } : MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')' ; mapping_option_list[List<ClawMapping> mappings]: m=mapping_option { $mappings.add($m.mapping); } | m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings] ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // Directives ARRAY_TRANS : 'array-transform'; END : 'end'; KCACHE : 'kcache'; LFUSION : 'loop-fusion'; LINTERCHANGE : 'loop-interchange'; LEXTRACT : 'loop-extract'; REMOVE : 'remove'; // Options ACC : 'acc'; FUSION : 'fusion'; GROUP : 'group'; MAP : 'map'; PARALLEL : 'parallel'; RANGE : 'range'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : [0-9] ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
Allow dash to be in an IDENTIFIER
Allow dash to be in an IDENTIFIER
ANTLR
bsd-2-clause
clementval/claw-compiler,clementval/claw-compiler
2d40954d73e00f698cdac8b2a520d626b987c318
refal/refal.g4
refal/refal.g4
/* BSD License Copyright (c) 2021, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar refal; program : f_definition (';'? program)? | external_decl ';' program | program external_decl ';' ; f_definition : f_name '{' block_ '}' | '$ENTRY' f_name '{' block_ '}' ; external_decl : ('$EXTERNAL' | '$EXTERN' | '$EXTRN') f_name_list ; f_name_list : f_name (',' f_name_list ';')? ; f_name : identifier ; block_ : sentence (';' block_?)? ; sentence : left_side conditions ('=' right_side | ',' block_ending) ; left_side : pattern ; conditions : (',' arg_ ':' pattern conditions)? ; pattern : expression_ ; arg_ : expression_ ; right_side : expression_ ; expression_ : (term_ expression_)? ; term_ : symbol | variable | '<' expression_ '>' ; block_ending : arg_ ':' '{' block_ '}' ; symbol : identifier | DIGITS | STRING | STRING2 | CHAR ; identifier : IDENTIFER | STRING ; variable : svar | tvar | evar ; svar : 's' '.' index ; tvar : 't' '.' index ; evar : 'e' '.' index ; index : identifier | DIGITS ; DIGITS : [0-9]+ ; IDENTIFER : [a-zA-Z] [a-zA-Z0-9_-]* ; STRING : '"' ~ '"'* '"' ; STRING2 : '\'' ~ '\''* '\'' ; CHAR : '\\\'' | '\\"' | '\\\\' | '\\n' | '\\r' | '\\t' | '\\x' [0-9] [0-9] ; WS : [ \r\n\t]+ -> skip ;
/* BSD License Copyright (c) 2021, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar refal; program : f_definition (';'? program)? | external_decl ';' program | program external_decl ';' ; f_definition : '$ENTRY'? f_name '{' block_ '}' ; external_decl : ('$EXTERNAL' | '$EXTERN' | '$EXTRN') f_name_list ; f_name_list : f_name (',' f_name_list ';')? ; f_name : identifier ; block_ : sentence (';' block_?)? ; sentence : left_side conditions ('=' right_side | ',' block_ending) ; left_side : pattern ; conditions : (',' arg_ ':' pattern conditions)? ; pattern : expression_ ; arg_ : expression_ ; right_side : expression_ ; expression_ : (term_ expression_)? ; term_ : symbol | variable | '<' expression_ '>' ; block_ending : arg_ ':' '{' block_ '}' ; symbol : identifier | DIGITS | STRING | STRING2 | CHAR ; identifier : IDENTIFER | STRING ; variable : svar | tvar | evar ; svar : 's' '.' index ; tvar : 't' '.' index ; evar : 'e' '.' index ; index : identifier | DIGITS ; DIGITS : [0-9]+ ; IDENTIFER : [a-zA-Z] [a-zA-Z0-9_-]* ; STRING : '"' ~ '"'* '"' ; STRING2 : '\'' ~ '\''* '\'' ; CHAR : '\\\'' | '\\"' | '\\\\' | '\\n' | '\\r' | '\\t' | '\\x' [0-9] [0-9] ; WS : [ \r\n\t]+ -> skip ;
Update refal/refal.g4
Update refal/refal.g4 Co-authored-by: Ivan Kochurkin <[email protected]>
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
b20533b5e4bfda5db867a944d16fd12bfc1621a7
src/main/java/org/apache/sysml/parser/dml/Dml.g4
src/main/java/org/apache/sysml/parser/dml/Dml.g4
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ grammar Dml; @header { /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ } // DML Program is a list of expression // For now, we only allow global function definitions (not nested or inside a while block) programroot: (blocks+=statement | functionBlocks+=functionStatement)* EOF; statement returns [ org.apache.sysml.parser.common.StatementInfo info ] @init { // This actions occurs regardless of how many alternatives in this rule $info = new org.apache.sysml.parser.common.StatementInfo(); } : // ------------------------------------------ // ImportStatement 'source' '(' filePath = STRING ')' 'as' namespace=ID ';'* # ImportStatement | 'setwd' '(' pathValue = STRING ')' ';'* # PathStatement // ------------------------------------------ // Treat function call as AssignmentStatement or MultiAssignmentStatement // For backward compatibility and also since the behavior of foo() * A + foo() ... where foo returns A // Convert FunctionCallIdentifier(paramExprs, ..) -> source | // TODO: Throw an informative error if user doesnot provide the optional assignment ( targetList=dataIdentifier ('='|'<-') )? name=ID '(' (paramExprs+=parameterizedExpression (',' paramExprs+=parameterizedExpression)* )? ')' ';'* # FunctionCallAssignmentStatement | '[' targetList+=dataIdentifier (',' targetList+=dataIdentifier)* ']' ('='|'<-') name=ID '(' (paramExprs+=parameterizedExpression (',' paramExprs+=parameterizedExpression)* )? ')' ';'* # FunctionCallMultiAssignmentStatement // {notifyErrorListeners("Too many parentheses");} // ------------------------------------------ // AssignmentStatement | targetList=dataIdentifier op=('<-'|'=') 'ifdef' '(' commandLineParam=dataIdentifier ',' source=expression ')' ';'* # IfdefAssignmentStatement | targetList=dataIdentifier op=('<-'|'=') source=expression ';'* # AssignmentStatement // ------------------------------------------ // We don't support block statement // | '{' body+=expression ';'* ( body+=expression ';'* )* '}' # BlockStatement // ------------------------------------------ // IfStatement | 'if' '(' predicate=expression ')' (ifBody+=statement ';'* | '{' (ifBody+=statement ';'*)* '}') ('else' (elseBody+=statement ';'* | '{' (elseBody+=statement ';'*)* '}'))? # IfStatement // ------------------------------------------ // ForStatement & ParForStatement | 'for' '(' iterVar=ID 'in' iterPred=iterablePredicate (',' parForParams+=strictParameterizedExpression)* ')' (body+=statement ';'* | '{' (body+=statement ';'* )* '}') # ForStatement // Convert strictParameterizedExpression to HashMap<String, String> for parForParams | 'parfor' '(' iterVar=ID 'in' iterPred=iterablePredicate (',' parForParams+=strictParameterizedExpression)* ')' (body+=statement ';'* | '{' (body+=statement ';'*)* '}') # ParForStatement | 'while' '(' predicate=expression ')' (body+=statement ';'* | '{' (body+=statement ';'*)* '}') # WhileStatement // ------------------------------------------ ; iterablePredicate returns [ org.apache.sysml.parser.common.ExpressionInfo info ] @init { // This actions occurs regardless of how many alternatives in this rule $info = new org.apache.sysml.parser.common.ExpressionInfo(); } : from=expression ':' to=expression #IterablePredicateColonExpression | ID '(' from=expression ',' to=expression ',' increment=expression ')' #IterablePredicateSeqExpression ; functionStatement returns [ org.apache.sysml.parser.common.StatementInfo info ] @init { // This actions occurs regardless of how many alternatives in this rule $info = new org.apache.sysml.parser.common.StatementInfo(); } : // ------------------------------------------ // FunctionStatement & ExternalFunctionStatement // small change: only allow typed arguments here ... instead of data identifier name=ID ('<-'|'=') 'function' '(' ( inputParams+=typedArgNoAssign (',' inputParams+=typedArgNoAssign)* )? ')' ( 'return' '(' ( outputParams+=typedArgNoAssign (',' outputParams+=typedArgNoAssign)* )? ')' )? '{' (body+=statement ';'*)* '}' # InternalFunctionDefExpression | name=ID ('<-'|'=') 'externalFunction' '(' ( inputParams+=typedArgNoAssign (',' inputParams+=typedArgNoAssign)* )? ')' ( 'return' '(' ( outputParams+=typedArgNoAssign (',' outputParams+=typedArgNoAssign)* )? ')' )? 'implemented' 'in' '(' ( otherParams+=strictParameterizedKeyValueString (',' otherParams+=strictParameterizedKeyValueString)* )? ')' ';'* # ExternalFunctionDefExpression // ------------------------------------------ ; // Other data identifiers are typedArgNoAssign, parameterizedExpression and strictParameterizedExpression dataIdentifier returns [ org.apache.sysml.parser.common.ExpressionInfo dataInfo ] @init { // This actions occurs regardless of how many alternatives in this rule $dataInfo = new org.apache.sysml.parser.common.ExpressionInfo(); // $dataInfo.expr = new org.apache.sysml.parser.DataIdentifier(); } : // ------------------------------------------ // IndexedIdentifier name=ID '[' (rowLower=expression (':' rowUpper=expression)?)? ',' (colLower=expression (':' colUpper=expression)?)? ']' # IndexedExpression // ------------------------------------------ | ID # SimpleDataIdentifierExpression | COMMANDLINE_NAMED_ID # CommandlineParamExpression | COMMANDLINE_POSITION_ID # CommandlinePositionExpression ; expression returns [ org.apache.sysml.parser.common.ExpressionInfo info ] @init { // This actions occurs regardless of how many alternatives in this rule $info = new org.apache.sysml.parser.common.ExpressionInfo(); // $info.expr = new org.apache.sysml.parser.BinaryExpression(org.apache.sysml.parser.Expression.BinaryOp.INVALID); } : // ------------------------------------------ // BinaryExpression // power <assoc=right> left=expression op='^' right=expression # PowerExpression // unary plus and minus | op=('-'|'+') left=expression # UnaryExpression // sequence - since we are only using this into for //| left=expression op=':' right=expression # SequenceExpression // matrix multiply | left=expression op='%*%' right=expression # MatrixMulExpression // modulus and integer division | left=expression op=('%/%' | '%%' ) right=expression # ModIntDivExpression // arithmetic multiply and divide | left=expression op=('*'|'/') right=expression # MultDivExpression // arithmetic addition and subtraction | left=expression op=('+'|'-') right=expression # AddSubExpression // ------------------------------------------ // RelationalExpression | left=expression op=('>'|'>='|'<'|'<='|'=='|'!=') right=expression # RelationalExpression // ------------------------------------------ // BooleanExpression // boolean not | op='!' left=expression # BooleanNotExpression // boolean and | left=expression op=('&'|'&&') right=expression # BooleanAndExpression // boolean or | left=expression op=('|'|'||') right=expression # BooleanOrExpression // --------------------------------- // only applicable for builtin function expressions | name=ID '(' (paramExprs+=parameterizedExpression (',' paramExprs+=parameterizedExpression)* )? ')' ';'* # BuiltinFunctionExpression // 4. Atomic | '(' left=expression ')' # AtomicExpression // Should you allow indexed expression here ? | '[' targetList+=expression (',' targetList+=expression)* ']' # MultiIdExpression // | BOOLEAN # ConstBooleanIdExpression | 'TRUE' # ConstTrueExpression | 'FALSE' # ConstFalseExpression | INT # ConstIntIdExpression | DOUBLE # ConstDoubleIdExpression | STRING # ConstStringIdExpression | dataIdentifier # DataIdExpression // Special // | 'NULL' | 'NA' | 'Inf' | 'NaN' ; typedArgNoAssign : paramType=ml_type paramName=ID; parameterizedExpression : (paramName=ID '=')? paramVal=expression; strictParameterizedExpression : paramName=ID '=' paramVal=expression ; strictParameterizedKeyValueString : paramName=ID '=' paramVal=STRING ; ID : (ALPHABET (ALPHABET|DIGIT|'_')* '::')? ALPHABET (ALPHABET|DIGIT|'_')* // Special ID cases: // | 'matrix' // --> This is a special case which causes lot of headache | 'as.scalar' | 'as.matrix' | 'as.frame' | 'as.double' | 'as.integer' | 'as.logical' | 'index.return' | 'lower.tail' ; // Unfortunately, we have datatype name clashing with builtin function name: matrix :( // Therefore, ugly work around for checking datatype ml_type : valueType | dataType '[' valueType ']'; // Note to reduce number of keywords, these are case-sensitive, // To allow case-insenstive, 'int' becomes: ('i' | 'I') ('n' | 'N') ('t' | 'T') valueType: 'int' | 'integer' | 'string' | 'boolean' | 'double' | 'Int' | 'Integer' | 'String' | 'Boolean' | 'Double'; dataType: // 'scalar' # ScalarDataTypeDummyCheck // | ID # MatrixDataTypeCheck //{ if($ID.text.compareTo("matrix") != 0) { notifyErrorListeners("incorrect datatype"); } } //| 'matrix' //---> See ID, this causes lot of headache ; INT : DIGIT+ [Ll]?; // BOOLEAN : 'TRUE' | 'FALSE'; DOUBLE: DIGIT+ '.' DIGIT* EXP? [Ll]? | DIGIT+ EXP? [Ll]? | '.' DIGIT+ EXP? [Ll]? ; DIGIT: '0'..'9'; ALPHABET : [a-zA-Z] ; fragment EXP : ('E' | 'e') ('+' | '-')? INT ; COMMANDLINE_NAMED_ID: '$' ALPHABET (ALPHABET|DIGIT|'_')*; COMMANDLINE_POSITION_ID: '$' DIGIT+; // supports single and double quoted string with escape characters STRING: '"' ( ESC | ~[\\"] )*? '"' | '\'' ( ESC | ~[\\'] )*? '\''; fragment ESC : '\\' [btnfr"'\\] ; // Comments, whitespaces and new line LINE_COMMENT : '#' .*? '\r'? '\n' -> skip ; MULTILINE_BLOCK_COMMENT : '/*' .*? '*/' -> skip ; WHITESPACE : (' ' | '\t' | '\r' | '\n')+ -> skip ;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ grammar Dml; @header { /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ } // DML Program is a list of expression // For now, we only allow global function definitions (not nested or inside a while block) programroot: (blocks+=statement | functionBlocks+=functionStatement)* EOF; statement returns [ org.apache.sysml.parser.common.StatementInfo info ] @init { // This actions occurs regardless of how many alternatives in this rule $info = new org.apache.sysml.parser.common.StatementInfo(); } : // ------------------------------------------ // ImportStatement 'source' '(' filePath = STRING ')' 'as' namespace=ID ';'* # ImportStatement | 'setwd' '(' pathValue = STRING ')' ';'* # PathStatement // ------------------------------------------ // Treat function call as AssignmentStatement or MultiAssignmentStatement // For backward compatibility and also since the behavior of foo() * A + foo() ... where foo returns A // Convert FunctionCallIdentifier(paramExprs, ..) -> source | // TODO: Throw an informative error if user doesnot provide the optional assignment ( targetList=dataIdentifier ('='|'<-') )? name=ID '(' (paramExprs+=parameterizedExpression (',' paramExprs+=parameterizedExpression)* )? ')' ';'* # FunctionCallAssignmentStatement | '[' targetList+=dataIdentifier (',' targetList+=dataIdentifier)* ']' ('='|'<-') name=ID '(' (paramExprs+=parameterizedExpression (',' paramExprs+=parameterizedExpression)* )? ')' ';'* # FunctionCallMultiAssignmentStatement // {notifyErrorListeners("Too many parentheses");} // ------------------------------------------ // AssignmentStatement | targetList=dataIdentifier op=('<-'|'=') 'ifdef' '(' commandLineParam=dataIdentifier ',' source=expression ')' ';'* # IfdefAssignmentStatement | targetList=dataIdentifier op=('<-'|'=') source=expression ';'* # AssignmentStatement // ------------------------------------------ // We don't support block statement // | '{' body+=expression ';'* ( body+=expression ';'* )* '}' # BlockStatement // ------------------------------------------ // IfStatement | 'if' '(' predicate=expression ')' (ifBody+=statement ';'* | '{' (ifBody+=statement ';'*)* '}') ('else' (elseBody+=statement ';'* | '{' (elseBody+=statement ';'*)* '}'))? # IfStatement // ------------------------------------------ // ForStatement & ParForStatement | 'for' '(' iterVar=ID 'in' iterPred=iterablePredicate (',' parForParams+=strictParameterizedExpression)* ')' (body+=statement ';'* | '{' (body+=statement ';'* )* '}') # ForStatement // Convert strictParameterizedExpression to HashMap<String, String> for parForParams | 'parfor' '(' iterVar=ID 'in' iterPred=iterablePredicate (',' parForParams+=strictParameterizedExpression)* ')' (body+=statement ';'* | '{' (body+=statement ';'*)* '}') # ParForStatement | 'while' '(' predicate=expression ')' (body+=statement ';'* | '{' (body+=statement ';'*)* '}') # WhileStatement // ------------------------------------------ ; iterablePredicate returns [ org.apache.sysml.parser.common.ExpressionInfo info ] @init { // This actions occurs regardless of how many alternatives in this rule $info = new org.apache.sysml.parser.common.ExpressionInfo(); } : from=expression ':' to=expression #IterablePredicateColonExpression | ID '(' from=expression ',' to=expression ',' increment=expression ')' #IterablePredicateSeqExpression ; functionStatement returns [ org.apache.sysml.parser.common.StatementInfo info ] @init { // This actions occurs regardless of how many alternatives in this rule $info = new org.apache.sysml.parser.common.StatementInfo(); } : // ------------------------------------------ // FunctionStatement & ExternalFunctionStatement // small change: only allow typed arguments here ... instead of data identifier name=ID ('<-'|'=') 'function' '(' ( inputParams+=typedArgNoAssign (',' inputParams+=typedArgNoAssign)* )? ')' ( 'return' '(' ( outputParams+=typedArgNoAssign (',' outputParams+=typedArgNoAssign)* )? ')' )? '{' (body+=statement ';'*)* '}' ';'* # InternalFunctionDefExpression | name=ID ('<-'|'=') 'externalFunction' '(' ( inputParams+=typedArgNoAssign (',' inputParams+=typedArgNoAssign)* )? ')' ( 'return' '(' ( outputParams+=typedArgNoAssign (',' outputParams+=typedArgNoAssign)* )? ')' )? 'implemented' 'in' '(' ( otherParams+=strictParameterizedKeyValueString (',' otherParams+=strictParameterizedKeyValueString)* )? ')' ';'* # ExternalFunctionDefExpression // ------------------------------------------ ; // Other data identifiers are typedArgNoAssign, parameterizedExpression and strictParameterizedExpression dataIdentifier returns [ org.apache.sysml.parser.common.ExpressionInfo dataInfo ] @init { // This actions occurs regardless of how many alternatives in this rule $dataInfo = new org.apache.sysml.parser.common.ExpressionInfo(); // $dataInfo.expr = new org.apache.sysml.parser.DataIdentifier(); } : // ------------------------------------------ // IndexedIdentifier name=ID '[' (rowLower=expression (':' rowUpper=expression)?)? ',' (colLower=expression (':' colUpper=expression)?)? ']' # IndexedExpression // ------------------------------------------ | ID # SimpleDataIdentifierExpression | COMMANDLINE_NAMED_ID # CommandlineParamExpression | COMMANDLINE_POSITION_ID # CommandlinePositionExpression ; expression returns [ org.apache.sysml.parser.common.ExpressionInfo info ] @init { // This actions occurs regardless of how many alternatives in this rule $info = new org.apache.sysml.parser.common.ExpressionInfo(); // $info.expr = new org.apache.sysml.parser.BinaryExpression(org.apache.sysml.parser.Expression.BinaryOp.INVALID); } : // ------------------------------------------ // BinaryExpression // power <assoc=right> left=expression op='^' right=expression # PowerExpression // unary plus and minus | op=('-'|'+') left=expression # UnaryExpression // sequence - since we are only using this into for //| left=expression op=':' right=expression # SequenceExpression // matrix multiply | left=expression op='%*%' right=expression # MatrixMulExpression // modulus and integer division | left=expression op=('%/%' | '%%' ) right=expression # ModIntDivExpression // arithmetic multiply and divide | left=expression op=('*'|'/') right=expression # MultDivExpression // arithmetic addition and subtraction | left=expression op=('+'|'-') right=expression # AddSubExpression // ------------------------------------------ // RelationalExpression | left=expression op=('>'|'>='|'<'|'<='|'=='|'!=') right=expression # RelationalExpression // ------------------------------------------ // BooleanExpression // boolean not | op='!' left=expression # BooleanNotExpression // boolean and | left=expression op=('&'|'&&') right=expression # BooleanAndExpression // boolean or | left=expression op=('|'|'||') right=expression # BooleanOrExpression // --------------------------------- // only applicable for builtin function expressions | name=ID '(' (paramExprs+=parameterizedExpression (',' paramExprs+=parameterizedExpression)* )? ')' ';'* # BuiltinFunctionExpression // 4. Atomic | '(' left=expression ')' # AtomicExpression // Should you allow indexed expression here ? | '[' targetList+=expression (',' targetList+=expression)* ']' # MultiIdExpression // | BOOLEAN # ConstBooleanIdExpression | 'TRUE' # ConstTrueExpression | 'FALSE' # ConstFalseExpression | INT # ConstIntIdExpression | DOUBLE # ConstDoubleIdExpression | STRING # ConstStringIdExpression | dataIdentifier # DataIdExpression // Special // | 'NULL' | 'NA' | 'Inf' | 'NaN' ; typedArgNoAssign : paramType=ml_type paramName=ID; parameterizedExpression : (paramName=ID '=')? paramVal=expression; strictParameterizedExpression : paramName=ID '=' paramVal=expression ; strictParameterizedKeyValueString : paramName=ID '=' paramVal=STRING ; ID : (ALPHABET (ALPHABET|DIGIT|'_')* '::')? ALPHABET (ALPHABET|DIGIT|'_')* // Special ID cases: // | 'matrix' // --> This is a special case which causes lot of headache | 'as.scalar' | 'as.matrix' | 'as.frame' | 'as.double' | 'as.integer' | 'as.logical' | 'index.return' | 'lower.tail' ; // Unfortunately, we have datatype name clashing with builtin function name: matrix :( // Therefore, ugly work around for checking datatype ml_type : valueType | dataType '[' valueType ']'; // Note to reduce number of keywords, these are case-sensitive, // To allow case-insenstive, 'int' becomes: ('i' | 'I') ('n' | 'N') ('t' | 'T') valueType: 'int' | 'integer' | 'string' | 'boolean' | 'double' | 'Int' | 'Integer' | 'String' | 'Boolean' | 'Double'; dataType: // 'scalar' # ScalarDataTypeDummyCheck // | ID # MatrixDataTypeCheck //{ if($ID.text.compareTo("matrix") != 0) { notifyErrorListeners("incorrect datatype"); } } //| 'matrix' //---> See ID, this causes lot of headache ; INT : DIGIT+ [Ll]?; // BOOLEAN : 'TRUE' | 'FALSE'; DOUBLE: DIGIT+ '.' DIGIT* EXP? [Ll]? | DIGIT+ EXP? [Ll]? | '.' DIGIT+ EXP? [Ll]? ; DIGIT: '0'..'9'; ALPHABET : [a-zA-Z] ; fragment EXP : ('E' | 'e') ('+' | '-')? INT ; COMMANDLINE_NAMED_ID: '$' ALPHABET (ALPHABET|DIGIT|'_')*; COMMANDLINE_POSITION_ID: '$' DIGIT+; // supports single and double quoted string with escape characters STRING: '"' ( ESC | ~[\\"] )*? '"' | '\'' ( ESC | ~[\\'] )*? '\''; fragment ESC : '\\' [btnfr"'\\] ; // Comments, whitespaces and new line LINE_COMMENT : '#' .*? '\r'? '\n' -> skip ; MULTILINE_BLOCK_COMMENT : '/*' .*? '*/' -> skip ; WHITESPACE : (' ' | '\t' | '\r' | '\n')+ -> skip ;
Fix dml.g4 to use semicolon after user-defined function
[SYSTEMML-639] Fix dml.g4 to use semicolon after user-defined function Closes #166.
ANTLR
apache-2.0
iyounus/incubator-systemml,dhutchis/systemml,asurve/incubator-systemml,apache/incubator-systemml,gweidner/incubator-systemml,sandeep-n/incubator-systemml,dhutchis/systemml,asurve/incubator-systemml,gweidner/systemml,dusenberrymw/incubator-systemml,akchinSTC/systemml,asurve/arvind-sysml2,asurve/incubator-systemml,Wenpei/incubator-systemml,nakul02/systemml,apache/incubator-systemml,asurve/systemml,gweidner/incubator-systemml,asurve/systemml,iyounus/incubator-systemml,Wenpei/incubator-systemml,asurve/arvind-sysml2,dhutchis/systemml,dusenberrymw/incubator-systemml,gweidner/incubator-systemml,dhutchis/systemml,deroneriksson/systemml,dusenberrymw/incubator-systemml,niketanpansare/incubator-systemml,nakul02/incubator-systemml,deroneriksson/incubator-systemml,apache/incubator-systemml,dusenberrymw/incubator-systemml,nakul02/incubator-systemml,gweidner/incubator-systemml,apache/incubator-systemml,niketanpansare/incubator-systemml,gweidner/systemml,asurve/systemml,nakul02/incubator-systemml,iyounus/incubator-systemml,deroneriksson/systemml,asurve/arvind-sysml2,dusenberrymw/systemml,asurve/incubator-systemml,deroneriksson/incubator-systemml,gweidner/systemml,fschueler/incubator-systemml,gweidner/incubator-systemml,dhutchis/systemml,fschueler/incubator-systemml,gweidner/systemml,iyounus/incubator-systemml,deroneriksson/systemml,apache/incubator-systemml,fschueler/incubator-systemml,akchinSTC/systemml,nakul02/systemml,dusenberrymw/systemml,asurve/arvind-sysml2,akchinSTC/systemml,dusenberrymw/systemml,nakul02/incubator-systemml,dusenberrymw/incubator-systemml,nakul02/systemml,deroneriksson/incubator-systemml,nakul02/incubator-systemml,dusenberrymw/systemml,sandeep-n/incubator-systemml,nakul02/systemml,akchinSTC/systemml,asurve/systemml,niketanpansare/systemml,asurve/incubator-systemml,dusenberrymw/systemml,Wenpei/incubator-systemml,nakul02/systemml,gweidner/systemml,niketanpansare/incubator-systemml,deroneriksson/systemml,akchinSTC/systemml,deroneriksson/incubator-systemml,dhutchis/systemml,Wenpei/incubator-systemml,deroneriksson/incubator-systemml,niketanpansare/systemml,nakul02/systemml,apache/incubator-systemml,iyounus/incubator-systemml,deroneriksson/systemml,asurve/systemml,asurve/systemml,dusenberrymw/incubator-systemml,deroneriksson/systemml,gweidner/systemml,fschueler/incubator-systemml,niketanpansare/systemml,iyounus/incubator-systemml,niketanpansare/incubator-systemml,gweidner/incubator-systemml,deroneriksson/incubator-systemml,nakul02/incubator-systemml,asurve/incubator-systemml,sandeep-n/incubator-systemml,asurve/arvind-sysml2,asurve/arvind-sysml2,niketanpansare/systemml,niketanpansare/systemml,dusenberrymw/systemml,niketanpansare/systemml,sandeep-n/incubator-systemml,akchinSTC/systemml
1368268a266cf0b21c967fd5a45e4112545a35b7
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE tableNotExistClause_ tableName (createDefinitionClause_ | createLikeClause_) ; createIndex : CREATE createIndexSpecification_ INDEX indexName indexType_? ON tableName ; alterTable : ALTER TABLE tableName alterClause_? ; dropTable : DROP TEMPORARY? TABLE (IF EXISTS)? tableName (COMMA_ tableName)* ; dropIndex : DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName ; truncateTable : TRUNCATE TABLE? tableName ; createTableSpecification_ : TEMPORARY? ; tableNotExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ createDefinitions_ RP_ ; createDefinitions_ : createDefinition_ (COMMA_ createDefinition_)* ; createDefinition_ : columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_ ; columnDefinition : columnName dataType (inlineDataType_* | generatedDataType_*) ; inlineDataType_ : commonDataTypeOption_ | AUTO_INCREMENT | DEFAULT (literals | expr) | COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT) | STORAGE (DISK | MEMORY | DEFAULT) ; commonDataTypeOption_ : primaryKey | UNIQUE KEY? | NOT? NULL | collateClause_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_ ; checkConstraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)? ; referenceDefinition_ : REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)* ; referenceOption_ : RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT ; generatedDataType_ : commonDataTypeOption_ | (GENERATED ALWAYS)? AS expr | (VIRTUAL | STORED) ; indexDefinition_ : (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_* ; indexType_ : USING (BTREE | HASH) ; keyParts_ : LP_ keyPart_ (COMMA_ keyPart_)* RP_ ; keyPart_ : (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)? ; indexOption_ : KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE ; constraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_) ; primaryKeyOption_ : primaryKey indexType_? columnNames indexOption_* ; primaryKey : PRIMARY? KEY ; uniqueOption_ : UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_* ; foreignKeyOption_ : FOREIGN KEY indexName? columnNames referenceDefinition_ ; createLikeClause_ : LP_? LIKE tableName RP_? ; createIndexSpecification_ : (UNIQUE | FULLTEXT | SPATIAL)? ; alterClause_ : alterSpecification_ (COMMA_ alterSpecification_)* ; alterSpecification_ : tableOptions_ | addColumnSpecification | addIndexSpecification | addConstraintSpecification | ADD checkConstraintDefinition_ | DROP CHECK ignoredIdentifier_ | ALTER CHECK ignoredIdentifier_ NOT? ENFORCED | ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY) | ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT) | ALTER INDEX indexName (VISIBLE | INVISIBLE) | changeColumnSpecification | DEFAULT? characterSet_ collateClause_? | CONVERT TO characterSet_ collateClause_? | (DISABLE | ENABLE) KEYS | (DISCARD | IMPORT_) TABLESPACE | dropColumnSpecification | dropIndexSpecification | dropPrimaryKeySpecification | DROP FOREIGN KEY ignoredIdentifier_ | FORCE | LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE) | modifyColumnSpecification // TODO hongjun investigate ORDER BY col_name [, col_name] ... | ORDER BY columnNames | renameColumnSpecification | renameIndexSpecification | renameTableSpecification_ | (WITHOUT | WITH) VALIDATION | ADD PARTITION LP_ partitionDefinition_ RP_ | DROP PARTITION ignoredIdentifiers_ | DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE | IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE | TRUNCATE PARTITION (ignoredIdentifiers_ | ALL) | COALESCE PARTITION NUMBER_ | REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_ | EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)? | ANALYZE PARTITION (ignoredIdentifiers_ | ALL) | CHECK PARTITION (ignoredIdentifiers_ | ALL) | OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL) | REBUILD PARTITION (ignoredIdentifiers_ | ALL) | REPAIR PARTITION (ignoredIdentifiers_ | ALL) | REMOVE PARTITIONING | UPGRADE PARTITIONING ; tableOptions_ : tableOption_ (COMMA_? tableOption_)* ; tableOption_ : AUTO_INCREMENT EQ_? NUMBER_ | AVG_ROW_LENGTH EQ_? NUMBER_ | DEFAULT? (characterSet_ | collateClause_) | CHECKSUM EQ_? NUMBER_ | COMMENT EQ_? STRING_ | COMPRESSION EQ_? STRING_ | CONNECTION EQ_? STRING_ | (DATA | INDEX) DIRECTORY EQ_? STRING_ | DELAY_KEY_WRITE EQ_? NUMBER_ | ENCRYPTION EQ_? STRING_ | ENGINE EQ_? ignoredIdentifier_ | INSERT_METHOD EQ_? (NO | FIRST | LAST) | KEY_BLOCK_SIZE EQ_? NUMBER_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | PACK_KEYS EQ_? (NUMBER_ | DEFAULT) | PASSWORD EQ_? STRING_ | ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT) | STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_) | STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_) | STATS_SAMPLE_PAGES EQ_? NUMBER_ | TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))? | UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_ ; addColumnSpecification : ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_) ; firstOrAfterColumn : FIRST | AFTER columnName ; addIndexSpecification : ADD indexDefinition_ ; addConstraintSpecification : ADD constraintDefinition_ ; changeColumnSpecification : CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn? ; dropColumnSpecification : DROP COLUMN? columnName ; dropIndexSpecification : DROP (INDEX | KEY) indexName ; dropPrimaryKeySpecification : DROP primaryKey ; modifyColumnSpecification : MODIFY COLUMN? columnDefinition firstOrAfterColumn? ; // TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column renameColumnSpecification : RENAME COLUMN columnName TO columnName ; // TODO hongjun: should support renameIndexSpecification on mysql renameIndexSpecification : RENAME (INDEX | KEY) indexName TO indexName ; // TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table renameTableSpecification_ : RENAME (TO | AS)? newTableName ; newTableName : identifier_ ; partitionDefinitions_ : LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_ ; partitionDefinition_ : PARTITION identifier_ (VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))? partitionDefinitionOption_* (LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)? ; partitionLessThanValue_ : LP_ (expr | partitionValueList_) RP_ | MAXVALUE ; partitionValueList_ : literals (COMMA_ literals)* ; partitionDefinitionOption_ : STORAGE? ENGINE EQ_? identifier_ | COMMENT EQ_? STRING_ | DATA DIRECTORY EQ_? STRING_ | INDEX DIRECTORY EQ_? STRING_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | TABLESPACE EQ_? identifier_ ; subpartitionDefinition_ : SUBPARTITION identifier_ partitionDefinitionOption_* ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE tableNotExistClause_ tableName (createDefinitionClause_ | createLikeClause_) ; createIndex : CREATE createIndexSpecification_ INDEX indexName indexType_? ON tableName ; alterTable : ALTER TABLE tableName alterDefinitionClause_? ; dropTable : DROP dropTableSpecification_ TABLE tableExistClause_ tableNames ; dropIndex : DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName ; truncateTable : TRUNCATE TABLE? tableName ; createTableSpecification_ : TEMPORARY? ; tableNotExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ createDefinitions_ RP_ ; createDefinitions_ : createDefinition_ (COMMA_ createDefinition_)* ; createDefinition_ : columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_ ; columnDefinition : columnName dataType (inlineDataType_* | generatedDataType_*) ; inlineDataType_ : commonDataTypeOption_ | AUTO_INCREMENT | DEFAULT (literals | expr) | COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT) | STORAGE (DISK | MEMORY | DEFAULT) ; commonDataTypeOption_ : primaryKey | UNIQUE KEY? | NOT? NULL | collateClause_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_ ; checkConstraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)? ; referenceDefinition_ : REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)* ; referenceOption_ : RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT ; generatedDataType_ : commonDataTypeOption_ | (GENERATED ALWAYS)? AS expr | (VIRTUAL | STORED) ; indexDefinition_ : (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_* ; indexType_ : USING (BTREE | HASH) ; keyParts_ : LP_ keyPart_ (COMMA_ keyPart_)* RP_ ; keyPart_ : (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)? ; indexOption_ : KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE ; constraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_) ; primaryKeyOption_ : primaryKey indexType_? columnNames indexOption_* ; primaryKey : PRIMARY? KEY ; uniqueOption_ : UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_* ; foreignKeyOption_ : FOREIGN KEY indexName? columnNames referenceDefinition_ ; createLikeClause_ : LP_? LIKE tableName RP_? ; createIndexSpecification_ : (UNIQUE | FULLTEXT | SPATIAL)? ; alterDefinitionClause_ : alterSpecification_ (COMMA_ alterSpecification_)* ; alterSpecification_ : tableOptions_ | addColumnSpecification | addIndexSpecification | addConstraintSpecification | ADD checkConstraintDefinition_ | DROP CHECK ignoredIdentifier_ | ALTER CHECK ignoredIdentifier_ NOT? ENFORCED | ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY) | ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT) | ALTER INDEX indexName (VISIBLE | INVISIBLE) | changeColumnSpecification | DEFAULT? characterSet_ collateClause_? | CONVERT TO characterSet_ collateClause_? | (DISABLE | ENABLE) KEYS | (DISCARD | IMPORT_) TABLESPACE | dropColumnSpecification | dropIndexSpecification | dropPrimaryKeySpecification | DROP FOREIGN KEY ignoredIdentifier_ | FORCE | LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE) | modifyColumnSpecification // TODO hongjun investigate ORDER BY col_name [, col_name] ... | ORDER BY columnNames | renameColumnSpecification | renameIndexSpecification | renameTableSpecification_ | (WITHOUT | WITH) VALIDATION | ADD PARTITION LP_ partitionDefinition_ RP_ | DROP PARTITION ignoredIdentifiers_ | DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE | IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE | TRUNCATE PARTITION (ignoredIdentifiers_ | ALL) | COALESCE PARTITION NUMBER_ | REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_ | EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)? | ANALYZE PARTITION (ignoredIdentifiers_ | ALL) | CHECK PARTITION (ignoredIdentifiers_ | ALL) | OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL) | REBUILD PARTITION (ignoredIdentifiers_ | ALL) | REPAIR PARTITION (ignoredIdentifiers_ | ALL) | REMOVE PARTITIONING | UPGRADE PARTITIONING ; tableOptions_ : tableOption_ (COMMA_? tableOption_)* ; tableOption_ : AUTO_INCREMENT EQ_? NUMBER_ | AVG_ROW_LENGTH EQ_? NUMBER_ | DEFAULT? (characterSet_ | collateClause_) | CHECKSUM EQ_? NUMBER_ | COMMENT EQ_? STRING_ | COMPRESSION EQ_? STRING_ | CONNECTION EQ_? STRING_ | (DATA | INDEX) DIRECTORY EQ_? STRING_ | DELAY_KEY_WRITE EQ_? NUMBER_ | ENCRYPTION EQ_? STRING_ | ENGINE EQ_? ignoredIdentifier_ | INSERT_METHOD EQ_? (NO | FIRST | LAST) | KEY_BLOCK_SIZE EQ_? NUMBER_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | PACK_KEYS EQ_? (NUMBER_ | DEFAULT) | PASSWORD EQ_? STRING_ | ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT) | STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_) | STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_) | STATS_SAMPLE_PAGES EQ_? NUMBER_ | TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))? | UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_ ; addColumnSpecification : ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_) ; firstOrAfterColumn : FIRST | AFTER columnName ; addIndexSpecification : ADD indexDefinition_ ; addConstraintSpecification : ADD constraintDefinition_ ; changeColumnSpecification : CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn? ; dropColumnSpecification : DROP COLUMN? columnName ; dropIndexSpecification : DROP (INDEX | KEY) indexName ; dropPrimaryKeySpecification : DROP primaryKey ; modifyColumnSpecification : MODIFY COLUMN? columnDefinition firstOrAfterColumn? ; // TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column renameColumnSpecification : RENAME COLUMN columnName TO columnName ; // TODO hongjun: should support renameIndexSpecification on mysql renameIndexSpecification : RENAME (INDEX | KEY) indexName TO indexName ; // TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table renameTableSpecification_ : RENAME (TO | AS)? newTableName ; newTableName : identifier_ ; partitionDefinitions_ : LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_ ; partitionDefinition_ : PARTITION identifier_ (VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))? partitionDefinitionOption_* (LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)? ; partitionLessThanValue_ : LP_ (expr | partitionValueList_) RP_ | MAXVALUE ; partitionValueList_ : literals (COMMA_ literals)* ; partitionDefinitionOption_ : STORAGE? ENGINE EQ_? identifier_ | COMMENT EQ_? STRING_ | DATA DIRECTORY EQ_? STRING_ | INDEX DIRECTORY EQ_? STRING_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | TABLESPACE EQ_? identifier_ ; subpartitionDefinition_ : SUBPARTITION identifier_ partitionDefinitionOption_* ; dropTableSpecification_ : TEMPORARY? ; tableExistClause_ : (IF EXISTS)? ;
modify dropTable rule
modify dropTable rule
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
215f4c4c5db5c6fea7e4d9668d5587f6ee35a0f1
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/Keyword.g4
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/Keyword.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ lexer grammar Keyword; import Alphabet; WS : [ \t\r\n] + ->skip ; ALL : A L L ; AND : A N D ; ANY : A N Y ; ASC : A S C ; ADMIN : A D M I N ; BETWEEN : B E T W E E N ; BINARY : B I N A R Y ; BY : B Y ; DATE : D A T E ; DESC : D E S C ; DISTINCT : D I S T I N C T ; ESCAPE : E S C A P E ; EXISTS : E X I S T S ; FALSE : F A L S E ; FROM : F R O M ; GROUP : G R O U P ; HAVING : H A V I N G ; IN : I N ; IS : I S ; KEY : K E Y ; LIKE : L I K E ; LIMIT : L I M I T ; MOD : M O D ; NOT : N O T ; NULL : N U L L ; OFFSET : O F F S E T ; OR : O R ; ORDER : O R D E R ; PARTITION : P A R T I T I O N ; PRIMARY : P R I M A R Y ; REGEXP : R E G E X P ; ROW : R O W ; SET : S E T ; SOUNDS : S O U N D S ; TIME : T I M E ; TIMESTAMP : T I M E S T A M P ; TRUE : T R U E ; UNION : U N I O N ; UNKNOWN : U N K N O W N ; WHERE : W H E R E ; WITH : W I T H ; XOR : X O R ; ADD : A D D ; ALTER : A L T E R ; ALWAYS : A L W A Y S ; AS : A S ; CASCADE : C A S C A D E ; CHECK : C H E C K ; COLUMN : C O L U M N ; COMMIT : C O M M I T ; CONSTRAINT : C O N S T R A I N T ; CREATE : C R E A T E ; CURRENT : C U R R E N T ; DAY : D A Y ; DEFAULT : D E F A U L T ; DELETE : D E L E T E ; DISABLE : D I S A B L E ; DROP : D R O P ; ENABLE : E N A B L E ; FOR : F O R ; FOREIGN : F O R E I G N ; FUNCTION : F U N C T I O N ; GENERATED : G E N E R A T E D ; GRANT : G R A N T ; INDEX : I N D E X ; ISOLATION : I S O L A T I O N ; LEVEL : L E V E L ; NO : N O ; ON : O N ; OPTION : O P T I O N ; PRIVILEGES : P R I V I L E G E S ; READ : R E A D ; REFERENCES : R E F E R E N C E S ; REVOKE : R E V O K E ; ROLE : R O L E ; ROLLBACK : R O L L B A C K ; ROWS : R O W S ; START : S T A R T ; TABLE : T A B L E ; TO : T O ; TRANSACTION : T R A N S A C T I O N ; TRUNCATE : T R U N C A T E ; UNIQUE : U N I Q U E ; USER : U S E R ; YEAR : Y E A R ; ACTION : A C T I O N ; ARRAY : A R R A Y ; BEGIN : B E G I N ; BRIN : B R I N ; BTREE : B T R E E ; CACHE : C A C H E ; CAST : C A S T ; CHARACTERISTICS : C H A R A C T E R I S T I C S ; CLUSTER : C L U S T E R ; COLLATE : C O L L A T E ; COMMENTS : C O M M E N T S ; CONCURRENTLY : C O N C U R R E N T L Y ; CONNECT : C O N N E C T ; CONSTRAINTS : C O N S T R A I N T S ; CURRENT_TIMESTAMP : C U R R E N T UL_ T I M E S T A M P ; CURRENT_USER : C U R R E N T UL_ U S E R ; CYCLE : C Y C L E ; DATA : D A T A ; DATABASE : D A T A B A S E ; DEFAULTS : D E F A U L T S ; DEFERRABLE : D E F E R R A B L E ; DEFERRED : D E F E R R E D ; DEPENDS : D E P E N D S ; DOMAIN : D O M A I N ; EXCLUDING : E X C L U D I N G ; EXECUTE : E X E C U T E ; EXTENDED : E X T E N D E D ; EXTENSION : E X T E N S I O N ; EXTERNAL : E X T E R N A L ; EXTRACT : E X T R A C T ; FILTER : F I L T E R ; FIRST : F I R S T ; FOLLOWING : F O L L O W I N G ; FORCE : F O R C E ; FULL : F U L L ; GIN : G I N ; GIST : G I S T ; GLOBAL : G L O B A L ; HASH : H A S H ; HOUR : H O U R ; IDENTITY : I D E N T I T Y ; IF : I F ; IMMEDIATE : I M M E D I A T E ; INCLUDING : I N C L U D I N G ; INCREMENT : I N C R E M E N T ; INDEXES : I N D E X E S ; INHERIT : I N H E R I T ; INHERITS : I N H E R I T S ; INITIALLY : I N I T I A L L Y ; INSERT : I N S E R T ; LANGUAGE : L A N G U A G E ; LARGE : L A R G E ; LAST : L A S T ; LOCAL : L O C A L ; LOGGED : L O G G E D ; MAIN : M A I N ; MATCH : M A T C H ; MAXVALUE : M A X V A L U E ; MINUTE : M I N U T E ; MINVALUE : M I N V A L U E ; MONTH : M O N T H ; NOTHING : N O T H I N G ; NULLS : N U L L S ; OBJECT : O B J E C T ; OF : O F ; OIDS : O I D S ; ONLY : O N L Y ; OVER : O V E R ; OWNED : O W N E D ; OWNER : O W N E R ; PARTIAL : P A R T I A L ; PLAIN : P L A I N ; PRECEDING : P R E C E D I N G ; PROCEDURE : P R O C E D U R E ; RANGE : R A N G E ; RENAME : R E N A M E ; REPLICA : R E P L I C A ; RESET : R E S E T ; RESTART : R E S T A R T ; RESTRICT : R E S T R I C T ; ROUTINE : R O U T I N E ; RULE : R U L E ; SAVEPOINT : S A V E P O I N T ; SCHEMA : S C H E M A ; SECOND : S E C O N D ; SECURITY : S E C U R I T Y ; SELECT : S E L E C T ; SEQUENCE : S E Q U E N C E ; SESSION : S E S S I O N ; SESSION_USER : S E S S I O N UL_ U S E R ; SHOW : S H O W ; SIMPLE : S I M P L E ; SPGIST : S P G I S T ; STATISTICS : S T A T I S T I C S ; STORAGE : S T O R A G E ; TABLESPACE : T A B L E S P A C E ; TEMP : T E M P ; TEMPORARY : T E M P O R A R Y ; TRIGGER : T R I G G E R ; TYPE : T Y P E ; UNBOUNDED : U N B O U N D E D ; UNLOGGED : U N L O G G E D ; UPDATE : U P D A T E ; USAGE : U S A G E ; USING : U S I N G ; VALID : V A L I D ; VALIDATE : V A L I D A T E ; WITHIN : W I T H I N ; WITHOUT : W I T H O U T ; ZONE : Z O N E ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ lexer grammar Keyword; import Alphabet; WS : [ \t\r\n] + ->skip ; ALL : A L L ; AND : A N D ; ANY : A N Y ; ASC : A S C ; ADMIN : A D M I N ; BETWEEN : B E T W E E N ; BINARY : B I N A R Y ; BY : B Y ; DATE : D A T E ; DESC : D E S C ; DISTINCT : D I S T I N C T ; ESCAPE : E S C A P E ; EXISTS : E X I S T S ; EXCLUDE : E X C L U D E ; FALSE : F A L S E ; FROM : F R O M ; GROUP : G R O U P ; HAVING : H A V I N G ; IN : I N ; IS : I S ; KEY : K E Y ; LIKE : L I K E ; LIMIT : L I M I T ; MOD : M O D ; NOT : N O T ; NULL : N U L L ; OFFSET : O F F S E T ; OR : O R ; ORDER : O R D E R ; PARTITION : P A R T I T I O N ; PRIMARY : P R I M A R Y ; REGEXP : R E G E X P ; ROW : R O W ; SET : S E T ; SOUNDS : S O U N D S ; TIME : T I M E ; TIMESTAMP : T I M E S T A M P ; TRUE : T R U E ; UNION : U N I O N ; UNKNOWN : U N K N O W N ; WHERE : W H E R E ; WITH : W I T H ; XOR : X O R ; ADD : A D D ; ALTER : A L T E R ; ALWAYS : A L W A Y S ; AS : A S ; CASCADE : C A S C A D E ; CHECK : C H E C K ; COLUMN : C O L U M N ; COMMIT : C O M M I T ; CONSTRAINT : C O N S T R A I N T ; CREATE : C R E A T E ; CURRENT : C U R R E N T ; DAY : D A Y ; DEFAULT : D E F A U L T ; DELETE : D E L E T E ; DISABLE : D I S A B L E ; DROP : D R O P ; ENABLE : E N A B L E ; FOR : F O R ; FOREIGN : F O R E I G N ; FUNCTION : F U N C T I O N ; GENERATED : G E N E R A T E D ; GRANT : G R A N T ; INDEX : I N D E X ; ISOLATION : I S O L A T I O N ; LEVEL : L E V E L ; NO : N O ; ON : O N ; OPTION : O P T I O N ; PRIVILEGES : P R I V I L E G E S ; READ : R E A D ; REFERENCES : R E F E R E N C E S ; REVOKE : R E V O K E ; ROLE : R O L E ; ROLLBACK : R O L L B A C K ; ROWS : R O W S ; START : S T A R T ; TABLE : T A B L E ; TO : T O ; TRANSACTION : T R A N S A C T I O N ; TRUNCATE : T R U N C A T E ; UNIQUE : U N I Q U E ; USER : U S E R ; YEAR : Y E A R ; ACTION : A C T I O N ; ARRAY : A R R A Y ; BEGIN : B E G I N ; BRIN : B R I N ; BTREE : B T R E E ; CACHE : C A C H E ; CAST : C A S T ; CHARACTERISTICS : C H A R A C T E R I S T I C S ; CLUSTER : C L U S T E R ; COLLATE : C O L L A T E ; COMMENTS : C O M M E N T S ; CONCURRENTLY : C O N C U R R E N T L Y ; CONNECT : C O N N E C T ; CONSTRAINTS : C O N S T R A I N T S ; CURRENT_TIMESTAMP : C U R R E N T UL_ T I M E S T A M P ; CURRENT_USER : C U R R E N T UL_ U S E R ; CYCLE : C Y C L E ; DATA : D A T A ; DATABASE : D A T A B A S E ; DEFAULTS : D E F A U L T S ; DEFERRABLE : D E F E R R A B L E ; DEFERRED : D E F E R R E D ; DEPENDS : D E P E N D S ; DOMAIN : D O M A I N ; EXCLUDING : E X C L U D I N G ; EXECUTE : E X E C U T E ; EXTENDED : E X T E N D E D ; EXTENSION : E X T E N S I O N ; EXTERNAL : E X T E R N A L ; EXTRACT : E X T R A C T ; FILTER : F I L T E R ; FIRST : F I R S T ; FOLLOWING : F O L L O W I N G ; FORCE : F O R C E ; FULL : F U L L ; GIN : G I N ; GIST : G I S T ; GLOBAL : G L O B A L ; HASH : H A S H ; HOUR : H O U R ; IDENTITY : I D E N T I T Y ; IF : I F ; IMMEDIATE : I M M E D I A T E ; INCLUDING : I N C L U D I N G ; INCREMENT : I N C R E M E N T ; INDEXES : I N D E X E S ; INHERIT : I N H E R I T ; INHERITS : I N H E R I T S ; INITIALLY : I N I T I A L L Y ; INCLUDE : I N C L U D E ; INSERT : I N S E R T ; LANGUAGE : L A N G U A G E ; LARGE : L A R G E ; LAST : L A S T ; LOCAL : L O C A L ; LOGGED : L O G G E D ; MAIN : M A I N ; MATCH : M A T C H ; MAXVALUE : M A X V A L U E ; MINUTE : M I N U T E ; MINVALUE : M I N V A L U E ; MONTH : M O N T H ; NOTHING : N O T H I N G ; NULLS : N U L L S ; OBJECT : O B J E C T ; OF : O F ; OIDS : O I D S ; ONLY : O N L Y ; OVER : O V E R ; OWNED : O W N E D ; OWNER : O W N E R ; PARTIAL : P A R T I A L ; PLAIN : P L A I N ; PRECEDING : P R E C E D I N G ; PROCEDURE : P R O C E D U R E ; RANGE : R A N G E ; RENAME : R E N A M E ; REPLICA : R E P L I C A ; RESET : R E S E T ; RESTART : R E S T A R T ; RESTRICT : R E S T R I C T ; ROUTINE : R O U T I N E ; RULE : R U L E ; SAVEPOINT : S A V E P O I N T ; SCHEMA : S C H E M A ; SECOND : S E C O N D ; SECURITY : S E C U R I T Y ; SELECT : S E L E C T ; SEQUENCE : S E Q U E N C E ; SESSION : S E S S I O N ; SESSION_USER : S E S S I O N UL_ U S E R ; SHOW : S H O W ; SIMPLE : S I M P L E ; SPGIST : S P G I S T ; STATISTICS : S T A T I S T I C S ; STORAGE : S T O R A G E ; TABLESPACE : T A B L E S P A C E ; TEMP : T E M P ; TEMPORARY : T E M P O R A R Y ; TRIGGER : T R I G G E R ; TYPE : T Y P E ; UNBOUNDED : U N B O U N D E D ; UNLOGGED : U N L O G G E D ; UPDATE : U P D A T E ; USAGE : U S A G E ; USING : U S I N G ; VALID : V A L I D ; VALIDATE : V A L I D A T E ; WITHIN : W I T H I N ; WITHOUT : W I T H O U T ; ZONE : Z O N E ;
add key words
add key words
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
be06784384d1eba4cbcdffbc0c49673e8a74e47b
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE notExistClause_ tableName createDefinitionClause_ inheritClause_ ; createIndex : CREATE createIndexSpecification_ (indexNotExistClause_ indexName)? ON tableName ; alterTable : alterTableNameWithAsterisk (alterTableActions | renameColumnSpecification | renameConstraint) | alterTableNameExists renameTableSpecification_ ; alterIndex : alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace ; dropTable : DROP TABLE (IF EXISTS)? tableNames ; dropIndex : DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)* ; truncateTable : TRUNCATE TABLE? ONLY? tableNameParts ; createTableSpecification_ : ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? ; notExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ (createDefinition (COMMA_ createDefinition)*)? RP_ ; createDefinition : columnDefinition | tableConstraint | LIKE tableName likeOption* ; columnDefinition : columnName dataType collateClause? columnConstraint* ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT ignoredIdentifier_ ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; checkOption : CHECK expr (NO INHERIT)? ; defaultExpr : CURRENT_TIMESTAMP | expr ; sequenceOptions : sequenceOption+ ; sequenceOption : START WITH? NUMBER_ | INCREMENT BY? NUMBER_ | MAXVALUE NUMBER_ | NO MAXVALUE | MINVALUE NUMBER_ | NO MINVALUE | CYCLE | NO CYCLE | CACHE NUMBER_ | OWNED BY ; indexParameters : (USING INDEX TABLESPACE ignoredIdentifier_)? | INCLUDE columnNames | WITH ; action : NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT) ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))? ; likeOption : (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnNames indexParameters | primaryKey columnNames indexParameters | EXCLUDE (USING ignoredIdentifier_)? | FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; inheritClause_ : (INHERITS tableNames)? ; createIndexSpecification_ : UNIQUE? INDEX CONCURRENTLY? ; indexNotExistClause_ : (IF NOT EXISTS)? ; alterIndexName : ALTER INDEX (IF EXISTS)? indexName ; renameIndexSpecification : RENAME TO indexName ; alterIndexDependsOnExtension : ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_ ; alterIndexSetTableSpace : ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)? ; tableNameParts : tableNamePart (COMMA_ tableNamePart)* ; tableNamePart : tableName ASTERISK_? ; alterTableNameWithAsterisk : ALTER TABLE (IF EXISTS)? ONLY? tableName ASTERISK_? ; alterTableActions : alterTableAction (COMMA_ alterTableAction)* ; alterTableAction : addColumnSpecification | dropColumnSpecification | modifyColumnSpecification | addConstraintSpecification | ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam | VALIDATE CONSTRAINT ignoredIdentifier_ | DROP CONSTRAINT (IF EXISTS)? ignoredIdentifier_ (RESTRICT | CASCADE)? | (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)? | ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_ | (DISABLE | ENABLE) RULE ignoredIdentifier_ | ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_ | (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY | CLUSTER ON indexName | SET WITHOUT CLUSTER | SET (WITH | WITHOUT) OIDS | SET TABLESPACE ignoredIdentifier_ | SET (LOGGED | UNLOGGED) | SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_ | RESET LP_ storageParameter (COMMA_ storageParameter)* RP_ | INHERIT tableName | NO INHERIT tableName | OF dataTypeName_ | NOT OF | OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER) | REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING) ; tableConstraintUsingIndex : (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam ; addColumnSpecification : ADD COLUMN? (IF NOT EXISTS)? columnDefinition ; dropColumnSpecification : DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)? ; modifyColumnSpecification : alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)? | alterColumn SET DEFAULT expr | alterColumn DROP DEFAULT | alterColumn (SET | DROP) NOT NULL | alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)? | alterColumn alterColumnSetOption alterColumnSetOption* | alterColumn DROP IDENTITY (IF EXISTS)? | alterColumn SET STATISTICS NUMBER_ | alterColumn SET LP_ attributeOptions RP_ | alterColumn RESET LP_ attributeOptions RP_ | alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN) ; alterColumn : ALTER COLUMN? columnName ; alterColumnSetOption : SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)? ; attributeOptions : attributeOption (COMMA_ attributeOption)* ; attributeOption : IDENTIFIER_ EQ_ simpleExpr ; addConstraintSpecification : ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex) ; renameColumnSpecification : RENAME COLUMN? columnName TO columnName ; renameConstraint : RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_ ; storageParameterWithValue : storageParameter EQ_ simpleExpr ; storageParameter : IDENTIFIER_ ; alterTableNameExists : ALTER TABLE (IF EXISTS)? tableName ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; usingIndexType : USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN) ; excludeElement : (columnName | expr) ignoredIdentifier_? (ASC | DESC)? (NULLS (FIRST | LAST))? ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE tableNotExistClause_ tableName createDefinitionClause_ inheritClause_ ; createIndex : CREATE createIndexSpecification_ (indexNotExistClause_ indexName)? ON tableName ; alterTable : alterTableNameWithAsterisk (alterTableActions | renameColumnSpecification | renameConstraint) | alterTableNameExists renameTableSpecification_ ; alterIndex : alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace ; dropTable : DROP TABLE (IF EXISTS)? tableNames ; dropIndex : DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)* ; truncateTable : TRUNCATE TABLE? ONLY? tableNameParts ; createTableSpecification_ : ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? ; tableNotExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ (createDefinition (COMMA_ createDefinition)*)? RP_ ; createDefinition : columnDefinition | tableConstraint | LIKE tableName likeOption* ; columnDefinition : columnName dataType collateClause? columnConstraint* ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT ignoredIdentifier_ ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; checkOption : CHECK expr (NO INHERIT)? ; defaultExpr : CURRENT_TIMESTAMP | expr ; sequenceOptions : sequenceOption+ ; sequenceOption : START WITH? NUMBER_ | INCREMENT BY? NUMBER_ | MAXVALUE NUMBER_ | NO MAXVALUE | MINVALUE NUMBER_ | NO MINVALUE | CYCLE | NO CYCLE | CACHE NUMBER_ | OWNED BY ; indexParameters : (USING INDEX TABLESPACE ignoredIdentifier_)? | INCLUDE columnNames | WITH ; action : NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT) ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))? ; likeOption : (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnNames indexParameters | primaryKey columnNames indexParameters | EXCLUDE (USING ignoredIdentifier_)? | FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; inheritClause_ : (INHERITS tableNames)? ; createIndexSpecification_ : UNIQUE? INDEX CONCURRENTLY? ; indexNotExistClause_ : (IF NOT EXISTS)? ; alterIndexName : ALTER INDEX (IF EXISTS)? indexName ; renameIndexSpecification : RENAME TO indexName ; alterIndexDependsOnExtension : ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_ ; alterIndexSetTableSpace : ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)? ; tableNameParts : tableNamePart (COMMA_ tableNamePart)* ; tableNamePart : tableName ASTERISK_? ; alterTableNameWithAsterisk : ALTER TABLE (IF EXISTS)? ONLY? tableName ASTERISK_? ; alterTableActions : alterTableAction (COMMA_ alterTableAction)* ; alterTableAction : addColumnSpecification | dropColumnSpecification | modifyColumnSpecification | addConstraintSpecification | ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam | VALIDATE CONSTRAINT ignoredIdentifier_ | DROP CONSTRAINT (IF EXISTS)? ignoredIdentifier_ (RESTRICT | CASCADE)? | (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)? | ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_ | (DISABLE | ENABLE) RULE ignoredIdentifier_ | ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_ | (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY | CLUSTER ON indexName | SET WITHOUT CLUSTER | SET (WITH | WITHOUT) OIDS | SET TABLESPACE ignoredIdentifier_ | SET (LOGGED | UNLOGGED) | SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_ | RESET LP_ storageParameter (COMMA_ storageParameter)* RP_ | INHERIT tableName | NO INHERIT tableName | OF dataTypeName_ | NOT OF | OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER) | REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING) ; tableConstraintUsingIndex : (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam ; addColumnSpecification : ADD COLUMN? (IF NOT EXISTS)? columnDefinition ; dropColumnSpecification : DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)? ; modifyColumnSpecification : alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)? | alterColumn SET DEFAULT expr | alterColumn DROP DEFAULT | alterColumn (SET | DROP) NOT NULL | alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)? | alterColumn alterColumnSetOption alterColumnSetOption* | alterColumn DROP IDENTITY (IF EXISTS)? | alterColumn SET STATISTICS NUMBER_ | alterColumn SET LP_ attributeOptions RP_ | alterColumn RESET LP_ attributeOptions RP_ | alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN) ; alterColumn : ALTER COLUMN? columnName ; alterColumnSetOption : SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)? ; attributeOptions : attributeOption (COMMA_ attributeOption)* ; attributeOption : IDENTIFIER_ EQ_ simpleExpr ; addConstraintSpecification : ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex) ; renameColumnSpecification : RENAME COLUMN? columnName TO columnName ; renameConstraint : RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_ ; storageParameterWithValue : storageParameter EQ_ simpleExpr ; storageParameter : IDENTIFIER_ ; alterTableNameExists : ALTER TABLE (IF EXISTS)? tableName ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; usingIndexType : USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN) ; excludeElement : (columnName | expr) ignoredIdentifier_? (ASC | DESC)? (NULLS (FIRST | LAST))? ;
rename to tableNotExistClause_
rename to tableNotExistClause_
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
3ea6ca4ddac81fc81575920af88326dbf691195e
antlr-calculator/src/main/java/net/codenest/antlr/calculator/Calculator.g4
antlr-calculator/src/main/java/net/codenest/antlr/calculator/Calculator.g4
grammar Calculator ; INT : [0-9]+ ; DOUBLE : [0-9]+'.'[0-9]+ ; PI : 'pi' ; E : 'e' ; POW : '^' ; NL : '\n' ; WS : [ \t\r]+ -> skip ; ID : [a-zA-Z_][a-zA-Z_0-9]* ; PLUS : '+' ; EQUAL : '=' ; MINUS : '-' ; MULT : '*' ; DIV : '/' ; LPAR : '(' ; RPAR : ')' ; input : setVar NL input # ToSetVar | plusOrMinus NL? EOF # Calculate ; setVar : ID EQUAL plusOrMinus # SetVariable ; plusOrMinus : plusOrMinus PLUS multOrDiv # Plus | plusOrMinus MINUS multOrDiv # Minus | multOrDiv # ToMultOrDiv ; multOrDiv : multOrDiv MULT pow # Multiplication | multOrDiv DIV pow # Division | pow # ToPow ; pow : unaryMinus (POW pow)? # Power ; unaryMinus : MINUS unaryMinus # ChangeSign | atom # ToAtom ; atom : PI # ConstantPI | E # ConstantE | DOUBLE # Double | INT # Int | ID # Variable | LPAR plusOrMinus RPAR # Braces ;
grammar Calculator ; /*********************************************************** * Parser rules: define grammars **********************************************************/ input : setVar NL input # ToSetVar | plusOrMinus NL? EOF # Calculate ; setVar : ID EQUAL plusOrMinus # SetVariable ; plusOrMinus : plusOrMinus PLUS multOrDiv # Plus | plusOrMinus MINUS multOrDiv # Minus | multOrDiv # ToMultOrDiv ; multOrDiv : multOrDiv MULT pow # Multiplication | multOrDiv DIV pow # Division | pow # ToPow ; pow : unaryMinus (POW pow)? # Power ; unaryMinus : MINUS unaryMinus # ChangeSign | atom # ToAtom ; atom : PI # ConstantPI | E # ConstantE | DOUBLE # Double | INT # Int | ID # Variable | LPAR plusOrMinus RPAR # Braces ; /*********************************************************** * Lexer rules: define tokens **********************************************************/ INT : [0-9]+ ; DOUBLE : [0-9]+'.'[0-9]+ ; PI : 'pi' ; E : 'e' ; POW : '^' ; NL : '\n' ; WS : [ \t\r]+ -> skip ; ID : [a-zA-Z_][a-zA-Z_0-9]* ; PLUS : '+' ; EQUAL : '=' ; MINUS : '-' ; MULT : '*' ; DIV : '/' ; LPAR : '(' ; RPAR : ')' ;
update grammar layout
update grammar layout
ANTLR
apache-2.0
sunke/codenest,sunke/codenest
29ce56458c16b0bf89599ca60ce1340b599e05fd
source/src/HML.g4
source/src/HML.g4
grammar HML; hybridModel : signalDeclaration* variableDeclaration* template* program EOF; template : 'Template' ID formalParameters parStatement; formalParameters : '(' formalParameterDecls? ')' ; formalParameterDecls : type formalParameterDeclsRest ; formalParameterDeclsRest : variableDeclaratorId (',' formalParameterDecls)? ; variableDeclaratorId : ID ('[' ']')* ; type : primitiveType ('[' ']')* ; primitiveType : 'boolean' | 'int' | 'float' ; signalDeclaration : 'Signal' ('[' size=INT ']')* ID (',' ID)* ';' ; modifier : 'final' // used for the vars that cannot be modified ; variableDeclaration : modifier? type variableDeclarators ';' ; variableDeclarators : variableDeclarator (',' variableDeclarator)* ; variableDeclarator : variableDeclaratorId ('=' variableInitializer)? ; variableInitializer : arrayInitializer | expr ; arrayInitializer : '{' (variableInitializer (',' variableInitializer)* (',')? )? '}' | 'new' 'Array' ('[' INT ']')+ ; program : 'Main ' '{' signalDeclaration* variableDeclaration* blockStatement* '}'; blockStatement : atom #AtomPro // Atomic | blockStatement '|' blockStatement #NonCh // non-deterministrate choice | blockStatement '||' blockStatement #ParaCom // parallel composition | blockStatement ';' blockStatement #SeqCom // sequential composition | '(' blockStatement '<' expr '>' blockStatement ')' #ConCh // conditional choice | equation 'until' guard #Ode // differential equation | 'when' '(' guardedchoice ')' #WhenPro // when program | 'while' parExpression parStatement #LoopPro // loop | 'if' parExpression parStatement 'else' parStatement #IfPro // if statement | ID '(' exprList? ')' #CallTem // call template | parStatement #ParPro // program with paraentheses outside ; parStatement : '{' blockStatement '}' | '(' blockStatement ')' ; exprList : expr (',' expr)* ; // arg list atom : 'skip' | ID ':=' expr | '!' ID | 'suspend' '(' time=expr ')' ; expr : ID | INT | FLOAT |'true' | 'false' | ('-' | '~') expr // negtive and negation | expr ('*'|'/'|'mod') expr // % is mod | expr ('+'|'-') expr | expr ('>=' | '>' | '==' | '<' | '<=') expr | expr 'and' expr | expr 'or' expr | 'floor' '(' expr ')' | 'ceil' '(' expr ')' ; parExpression : '(' expr ')' ; equation : relation | relation 'init' expr | equation '||' equation ; relation : 'dot' ID '=' expr; guard : 'eps' | signal | expr | 'timeout' '(' expr ')' | guard '<and>' guard | guard '<or>' guard | '(' guard ')' ; signal : ID ('[' expr ']')*; guardedchoice : guard '&' program | guardedchoice '[]' guardedchoice ; COMOP : '>=' | '>' | '==' | '<' | '<=' ; ID : (LETTER | '_') (LETTER|DIGIT|'_')* ; fragment LETTER : [a-zA-Z] ; INT : DIGIT+ ; FLOAT : DIGIT+ '.' DIGIT+ ; fragment DIGIT: '0'..'9' ; COMMENT : '/*' .*? '*/' -> channel(HIDDEN) // match anything between /* and */ ; LINE_COMMENT : '//' ~[\r\n]* '\r'? '\n' -> channel(HIDDEN) ; WS : [ \r\t\u000C\n]+ -> channel(HIDDEN) ;
grammar HML; hybridModel : signalDeclaration* variableDeclaration* template* program EOF ; template : 'Template' ID formalParameters parStatement; formalParameters : '(' formalParameterDecls? ')' ; formalParameterDecls : type formalParameterDeclsRest ; formalParameterDeclsRest : variableDeclaratorId (',' formalParameterDecls)? ; variableDeclaratorId : ID ('[' ']')* ; type : primitiveType ('[' ']')* ; primitiveType : 'boolean' | 'int' | 'float' ; signalDeclaration : 'Signal' ('[' size=INT ']')* ID (',' ID)* ';' ; modifier : 'final' // used for the vars that cannot be modified ; variableDeclaration : modifier? type variableDeclarators ';' ; variableDeclarators : variableDeclarator (',' variableDeclarator)* ; variableDeclarator : variableDeclaratorId ('=' variableInitializer)? ; variableInitializer : arrayInitializer | expr ; arrayInitializer : '{' (variableInitializer (',' variableInitializer)* (',')? )? '}' | 'new' 'Array' ('[' INT ']')+ ; program : 'Main ' '{' signalDeclaration* variableDeclaration* blockStatement* '}'; blockStatement : atom #AtomPro // Atomic | blockStatement '|' blockStatement #NonCh // non-deterministrate choice | blockStatement '||' blockStatement #ParaCom // parallel composition | blockStatement ';' blockStatement #SeqCom // sequential composition | '(' blockStatement '<' expr '>' blockStatement ')' #ConCh // conditional choice | equation 'until' guard #Ode // differential equation | 'when' '(' guardedchoice ')' #WhenPro // when program | 'while' parExpression parStatement #LoopPro // loop | 'if' parExpression parStatement 'else' parStatement #IfPro // if statement | ID '(' exprList? ')' #CallTem // call template | parStatement #ParPro // program with paraentheses outside ; parStatement : '{' blockStatement '}' | '(' blockStatement ')' ; exprList : expr (',' expr)* ; // arg list atom : 'skip' | ID ':=' expr | '!' ID | 'suspend' '(' time=expr ')' ; expr : ID | INT | FLOAT |'true' | 'false' | ('-' | '~') expr // negtive and negation | expr ('*'|'/'|'mod') expr // % is mod | expr ('+'|'-') expr | expr ('>=' | '>' | '==' | '<' | '<=') expr | expr 'and' expr | expr 'or' expr | 'floor' '(' expr ')' | 'ceil' '(' expr ')' ; parExpression : '(' expr ')' ; equation : relation | relation 'init' expr | equation '||' equation ; relation : 'dot' ID '=' expr; guard : 'eps' | signal | expr | 'timeout' '(' expr ')' | guard '<and>' guard | guard '<or>' guard | '(' guard ')' ; signal : ID ('[' expr ']')*; guardedchoice : guard '&' program | guardedchoice '[]' guardedchoice ; COMOP : '>=' | '>' | '==' | '<' | '<=' ; ID : (LETTER | '_') (LETTER|DIGIT|'_')* ; fragment LETTER : [a-zA-Z] ; INT : DIGIT+ ; FLOAT : DIGIT+ '.' DIGIT+ ; fragment DIGIT: '0'..'9' ; COMMENT : '/*' .*? '*/' -> channel(HIDDEN) // match anything between /* and */ ; LINE_COMMENT : '//' ~[\r\n]* '\r'? '\n' -> channel(HIDDEN) ; WS : [ \r\t\u000C\n]+ -> channel(HIDDEN) ;
modify format
modify format
ANTLR
mit
fanghuixing/HML
73f8ec83bcb60009474fa4edaddb3ea6528fae28
datalog/datalog.g4
datalog/datalog.g4
/* BSD License Copyright (c) 2022, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar datalog; program : statement* ; statement : assertion | retraction | query | requirement ; assertion : clause '.' ; retraction : clause '~' ; query : literal '?' ; requirement : '(' IDENTIFIER ')' '.' ; clause : literal ':-' body | literal ; body : literal ',' body | literal ; literal : predicate_sym '(' ')' | predicate_sym '(' terms ')' | predicate_sym | term '=' term | term '!=' term | VARIABLE ':-' external_sym '(' terms ')' ; predicate_sym : IDENTIFIER | STRING ; terms : term | term ',' terms ; term : VARIABLE | constant ; constant : IDENTIFIER | STRING | INTEGER | 'true' | 'false' ; external_sym : IDENTIFIER ; VARIABLE : [A-Z] [a-zA-Z_]* ; IDENTIFIER : [a-z] [a-zA-Z0-9_-]* ; STRING : '"' ~ '"'* '"' ; INTEGER : [0-9]+ ; COMMENT : '#' (~ [\n\r])* -> skip ; WS : [ \r\n\t]+ -> skip ;
/* BSD License Copyright (c) 2022, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar datalog; program : statement* ; statement : assertion | retraction | query | requirement ; assertion : clause '.' ; retraction : clause '~' ; query : literal '?' ; requirement : '(' IDENTIFIER ')' '.' ; clause : literal ':-' body | literal ; body : literal ',' body | literal ; literal : predicate_sym '(' ')' | predicate_sym '(' terms_ ')' | predicate_sym | term_ '=' term_ | term_ '!=' term_ | VARIABLE ':-' external_sym '(' terms_ ')' ; predicate_sym : IDENTIFIER | STRING ; terms_ : term_ | term_ ',' terms_ ; term_ : VARIABLE | constant ; constant : IDENTIFIER | STRING | INTEGER | 'true' | 'false' ; external_sym : IDENTIFIER ; VARIABLE : [A-Z] [a-zA-Z_]* ; IDENTIFIER : [a-z] [a-zA-Z0-9_-]* ; STRING : '"' ~ '"'* '"' ; INTEGER : [0-9]+ ; COMMENT : '#' (~ [\n\r])* -> skip ; WS : [ \r\n\t]+ -> skip ;
update for symbol conflict
update for symbol conflict
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
d679b1d61fbd039da37ac7700b3b0a5543fa047a
projects/batfish/src/main/antlr4/org/batfish/grammar/cisco_nxos/CiscoNxos_static.g4
projects/batfish/src/main/antlr4/org/batfish/grammar/cisco_nxos/CiscoNxos_static.g4
parser grammar CiscoNxos_static; import CiscoNxos_common; options { tokenVocab = CiscoNxosLexer; } ip_route : ROUTE ( ip_route_network | ip_route_static ) ; ip_route_network : network = route_network ( null0 = NULL0 | nhint = interface_name? nhip = ip_address | nhint = interface_name nhip = ip_address? ) ( VRF nhvrf = vrf_name )? ( TRACK track = track_object_number )? ( NAME name = static_route_name )? ( (TAG tag = uint32) pref = protocol_distance? | pref = protocol_distance (TAG tag = uint32)? )? NEWLINE ; static_route_name : // 1-50 characters WORD ; ip_route_static : STATIC BFD name = interface_name ip = ip_address NEWLINE ;
parser grammar CiscoNxos_static; import CiscoNxos_common; options { tokenVocab = CiscoNxosLexer; } ip_route : ROUTE ( ip_route_network | ip_route_static ) ; ip_route_network : network = route_network ( null0 = NULL0 | nhint = interface_name nhip = ip_address? | nhip = ip_address ) ( VRF nhvrf = vrf_name )? ( TRACK track = track_object_number )? ( NAME name = static_route_name )? ( (TAG tag = uint32) pref = protocol_distance? | pref = protocol_distance (TAG tag = uint32)? )? NEWLINE ; static_route_name : // 1-50 characters WORD ; ip_route_static : STATIC BFD name = interface_name ip = ip_address NEWLINE ;
remove unecessary ambiguity (adaptive prediction) in the static route grammar (#4716)
NX-OS: remove unecessary ambiguity (adaptive prediction) in the static route grammar (#4716)
ANTLR
apache-2.0
intentionet/batfish,arifogel/batfish,intentionet/batfish,intentionet/batfish,batfish/batfish,dhalperi/batfish,dhalperi/batfish,arifogel/batfish,batfish/batfish,dhalperi/batfish,arifogel/batfish,intentionet/batfish,batfish/batfish,intentionet/batfish
65a36a173a3e8830e2d37883bc6bc10ab82305b6
sharding-core/src/main/antlr4/imports/BaseRule.g4
sharding-core/src/main/antlr4/imports/BaseRule.g4
//rule in this file does not allow override grammar BaseRule; import DataType,Keyword,Symbol; ID: (BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_? DOT)? (BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_?) |[a-zA-Z_$0-9]+ DOT ASTERISK ; schemaName: ID; tableName: ID; columnName: ID; tablespaceName: ID; collationName: STRING | ID; indexName: ID; alias: ID; cteName:ID; parserName: ID; extensionName: ID; rowName: ID; opclass: ID; fileGroup: ID; groupName: ID; constraintName: ID; keyName: ID; typeName: ID; xmlSchemaCollection:ID; columnSetName: ID; directoryName: ID; triggerName: ID; roleName: ID; partitionName: ID; rewriteRuleName: ID; ownerName: ID; userName: ID; ifExists : IF EXISTS; ifNotExists : IF NOT EXISTS; dataTypeLength : LP_ (NUMBER (COMMA NUMBER)?)? RP_ ; nullNotnull : NULL | NOT NULL ; primaryKey : PRIMARY? KEY ; matchNone : 'Default does not match anything' ; idList : LP_ ID (COMMA ID)* RP_ ; rangeClause : NUMBER (COMMA NUMBER)* | NUMBER OFFSET NUMBER ; tableNamesWithParen : LP_ tableNames RP_ ; tableNames : tableName (COMMA tableName)* ; columnNamesWithParen : LP_ columnNames RP_ ; columnNames : columnName (COMMA columnName)* ; columnList : LP_ columnNames RP_ ; indexNames : indexName (COMMA indexName)* ; rowNames : rowName (COMMA rowName)* ; bitExprs: bitExpr (COMMA bitExpr)* ; exprs : expr (COMMA expr)* ; exprsWithParen : LP_ exprs RP_ ; //https://dev.mysql.com/doc/refman/8.0/en/expressions.html expr : expr OR expr | expr OR_ expr | expr XOR expr | expr AND expr | expr AND_ expr | LP_ expr RP_ | NOT expr | NOT_ expr | booleanPrimary | exprRecursive ; exprRecursive : matchNone ; booleanPrimary : booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL) | booleanPrimary SAFE_EQ predicate | booleanPrimary comparisonOperator predicate | booleanPrimary comparisonOperator (ALL | ANY) subquery | predicate ; comparisonOperator : EQ_ | GTE | GT | LTE | LT | NEQ_ | NEQ ; predicate : bitExpr NOT? IN subquery | bitExpr NOT? IN LP_ simpleExpr ( COMMA simpleExpr)* RP_ | bitExpr NOT? BETWEEN simpleExpr AND predicate | bitExpr SOUNDS LIKE simpleExpr | bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)* | bitExpr NOT? REGEXP simpleExpr | bitExpr ; bitExpr : bitExpr BIT_INCLUSIVE_OR bitExpr | bitExpr BIT_AND bitExpr | bitExpr SIGNED_LEFT_SHIFT bitExpr | bitExpr SIGNED_RIGHT_SHIFT bitExpr | bitExpr PLUS bitExpr | bitExpr MINUS bitExpr | bitExpr ASTERISK bitExpr | bitExpr SLASH bitExpr | bitExpr MOD bitExpr | bitExpr MOD_ bitExpr | bitExpr BIT_EXCLUSIVE_OR bitExpr //| bitExpr '+' interval_expr //| bitExpr '-' interval_expr | simpleExpr ; simpleExpr : functionCall | liter | ID | simpleExpr collateClause //| param_marker //| variable | simpleExpr AND_ simpleExpr | PLUS simpleExpr | MINUS simpleExpr | UNARY_BIT_COMPLEMENT simpleExpr | NOT_ simpleExpr | BINARY simpleExpr | LP_ expr RP_ | ROW LP_ simpleExpr( COMMA simpleExpr)* RP_ | subquery | EXISTS subquery // | (identifier expr) //| match_expr //| case_expr // | interval_expr |privateExprOfDb ; functionCall : ID LP_( bitExprs?) RP_ ; privateExprOfDb : matchNone ; liter : QUESTION | NUMBER | TRUE | FALSE | NULL | LBE_ ID STRING RBE_ | HEX_DIGIT | ID? STRING collateClause? | (DATE | TIME |TIMESTAMP) STRING | ID? BIT_NUM collateClause? ; subquery : matchNone ; collateClause : matchNone ; orderByClause : ORDER BY groupByItem (COMMA groupByItem)* ; groupByItem : (columnName | NUMBER |expr) (ASC|DESC)? ;
//rule in this file does not allow override grammar BaseRule; import DataType,Keyword,Symbol; ID: (BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_? DOT)? (BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_?) |[a-zA-Z_$0-9]+ DOT ASTERISK ; schemaName: ID; tableName: ID; columnName: ID; tablespaceName: ID; collationName: STRING | ID; indexName: ID; alias: ID; cteName:ID; parserName: ID; extensionName: ID; rowName: ID; opclass: ID; fileGroup: ID; groupName: ID; constraintName: ID; keyName: ID; typeName: ID; xmlSchemaCollection:ID; columnSetName: ID; directoryName: ID; triggerName: ID; roleName: ID; partitionName: ID; rewriteRuleName: ID; ownerName: ID; userName: ID; ifExists : IF EXISTS; ifNotExists : IF NOT EXISTS; dataTypeLength : LP_ (NUMBER (COMMA NUMBER)?)? RP_ ; nullNotnull : NULL | NOT NULL ; primaryKey : PRIMARY? KEY ; matchNone : 'Default does not match anything' ; idList : LP_ ID (COMMA ID)* RP_ ; rangeClause : NUMBER (COMMA NUMBER)* | NUMBER OFFSET NUMBER ; tableNamesWithParen : LP_ tableNames RP_ ; tableNames : tableName (COMMA tableName)* ; columnNamesWithParen : LP_ columnNames RP_ ; columnNames : columnName (COMMA columnName)* ; columnList : LP_ columnNames RP_ ; indexNames : indexName (COMMA indexName)* ; rowNames : rowName (COMMA rowName)* ; roleNames : roleName (COMMA roleName)* ; userNames : userName (COMMA userName)* ; bitExprs: bitExpr (COMMA bitExpr)* ; exprs : expr (COMMA expr)* ; exprsWithParen : LP_ exprs RP_ ; //https://dev.mysql.com/doc/refman/8.0/en/expressions.html expr : expr OR expr | expr OR_ expr | expr XOR expr | expr AND expr | expr AND_ expr | LP_ expr RP_ | NOT expr | NOT_ expr | booleanPrimary | exprRecursive ; exprRecursive : matchNone ; booleanPrimary : booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL) | booleanPrimary SAFE_EQ predicate | booleanPrimary comparisonOperator predicate | booleanPrimary comparisonOperator (ALL | ANY) subquery | predicate ; comparisonOperator : EQ_ | GTE | GT | LTE | LT | NEQ_ | NEQ ; predicate : bitExpr NOT? IN subquery | bitExpr NOT? IN LP_ simpleExpr ( COMMA simpleExpr)* RP_ | bitExpr NOT? BETWEEN simpleExpr AND predicate | bitExpr SOUNDS LIKE simpleExpr | bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)* | bitExpr NOT? REGEXP simpleExpr | bitExpr ; bitExpr : bitExpr BIT_INCLUSIVE_OR bitExpr | bitExpr BIT_AND bitExpr | bitExpr SIGNED_LEFT_SHIFT bitExpr | bitExpr SIGNED_RIGHT_SHIFT bitExpr | bitExpr PLUS bitExpr | bitExpr MINUS bitExpr | bitExpr ASTERISK bitExpr | bitExpr SLASH bitExpr | bitExpr MOD bitExpr | bitExpr MOD_ bitExpr | bitExpr BIT_EXCLUSIVE_OR bitExpr //| bitExpr '+' interval_expr //| bitExpr '-' interval_expr | simpleExpr ; simpleExpr : functionCall | liter | ID | simpleExpr collateClause //| param_marker //| variable | simpleExpr AND_ simpleExpr | PLUS simpleExpr | MINUS simpleExpr | UNARY_BIT_COMPLEMENT simpleExpr | NOT_ simpleExpr | BINARY simpleExpr | LP_ expr RP_ | ROW LP_ simpleExpr( COMMA simpleExpr)* RP_ | subquery | EXISTS subquery // | (identifier expr) //| match_expr //| case_expr // | interval_expr |privateExprOfDb ; functionCall : ID LP_( bitExprs?) RP_ ; privateExprOfDb : matchNone ; liter : QUESTION | NUMBER | TRUE | FALSE | NULL | LBE_ ID STRING RBE_ | HEX_DIGIT | ID? STRING collateClause? | (DATE | TIME |TIMESTAMP) STRING | ID? BIT_NUM collateClause? ; subquery : matchNone ; collateClause : matchNone ; orderByClause : ORDER BY groupByItem (COMMA groupByItem)* ; groupByItem : (columnName | NUMBER |expr) (ASC|DESC)? ;
add userNames roleNames
add userNames roleNames
ANTLR
apache-2.0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
be3e175c5974e2f342b5ffb65c54fb2d8f2333c0
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE tableNotExistClause_ tableName (createDefinitionClause_ | createLikeClause_) ; createIndex : CREATE createIndexSpecification_ INDEX indexName indexType_? ON tableName ; alterTable : ALTER TABLE tableName alterSpecifications_? ; dropTable : DROP TEMPORARY? TABLE (IF EXISTS)? tableName (COMMA_ tableName)* ; dropIndex : DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName ; truncateTable : TRUNCATE TABLE? tableName ; createTableSpecification_ : TEMPORARY? ; tableNotExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ createDefinitions_ RP_ ; createDefinitions_ : createDefinition_ (COMMA_ createDefinition_)* ; createDefinition_ : columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_ ; columnDefinition : columnName dataType (inlineDataType_* | generatedDataType_*) ; inlineDataType_ : commonDataTypeOption_ | AUTO_INCREMENT | DEFAULT (literals | expr) | COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT) | STORAGE (DISK | MEMORY | DEFAULT) ; commonDataTypeOption_ : primaryKey | UNIQUE KEY? | NOT? NULL | collateClause_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_ ; checkConstraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)? ; referenceDefinition_ : REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)* ; referenceOption_ : RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT ; generatedDataType_ : commonDataTypeOption_ | (GENERATED ALWAYS)? AS expr | (VIRTUAL | STORED) ; indexDefinition_ : (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_* ; indexType_ : USING (BTREE | HASH) ; keyParts_ : LP_ keyPart_ (COMMA_ keyPart_)* RP_ ; keyPart_ : (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)? ; indexOption_ : KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE ; constraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_) ; primaryKeyOption_ : primaryKey indexType_? columnNames indexOption_* ; primaryKey : PRIMARY? KEY ; uniqueOption_ : UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_* ; foreignKeyOption_ : FOREIGN KEY indexName? columnNames referenceDefinition_ ; createLikeClause_ : LP_? LIKE tableName RP_? ; createIndexSpecification_ : (UNIQUE | FULLTEXT | SPATIAL)? ; alterSpecifications_ : alterSpecification_ (COMMA_ alterSpecification_)* ; alterSpecification_ : tableOptions_ | addColumnSpecification | addIndexSpecification | addConstraintSpecification | ADD checkConstraintDefinition_ | DROP CHECK ignoredIdentifier_ | ALTER CHECK ignoredIdentifier_ NOT? ENFORCED | ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY) | ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT) | ALTER INDEX indexName (VISIBLE | INVISIBLE) | changeColumnSpecification | DEFAULT? characterSet_ collateClause_? | CONVERT TO characterSet_ collateClause_? | (DISABLE | ENABLE) KEYS | (DISCARD | IMPORT_) TABLESPACE | dropColumnSpecification | dropIndexSpecification | dropPrimaryKeySpecification | DROP FOREIGN KEY ignoredIdentifier_ | FORCE | LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE) | modifyColumnSpecification // TODO hongjun investigate ORDER BY col_name [, col_name] ... | ORDER BY columnNames | renameColumnSpecification | renameIndexSpecification | renameTableSpecification_ | (WITHOUT | WITH) VALIDATION | ADD PARTITION LP_ partitionDefinition_ RP_ | DROP PARTITION ignoredIdentifiers_ | DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE | IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE | TRUNCATE PARTITION (ignoredIdentifiers_ | ALL) | COALESCE PARTITION NUMBER_ | REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_ | EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)? | ANALYZE PARTITION (ignoredIdentifiers_ | ALL) | CHECK PARTITION (ignoredIdentifiers_ | ALL) | OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL) | REBUILD PARTITION (ignoredIdentifiers_ | ALL) | REPAIR PARTITION (ignoredIdentifiers_ | ALL) | REMOVE PARTITIONING | UPGRADE PARTITIONING ; tableOptions_ : tableOption_ (COMMA_? tableOption_)* ; tableOption_ : AUTO_INCREMENT EQ_? NUMBER_ | AVG_ROW_LENGTH EQ_? NUMBER_ | DEFAULT? (characterSet_ | collateClause_) | CHECKSUM EQ_? NUMBER_ | COMMENT EQ_? STRING_ | COMPRESSION EQ_? STRING_ | CONNECTION EQ_? STRING_ | (DATA | INDEX) DIRECTORY EQ_? STRING_ | DELAY_KEY_WRITE EQ_? NUMBER_ | ENCRYPTION EQ_? STRING_ | ENGINE EQ_? ignoredIdentifier_ | INSERT_METHOD EQ_? (NO | FIRST | LAST) | KEY_BLOCK_SIZE EQ_? NUMBER_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | PACK_KEYS EQ_? (NUMBER_ | DEFAULT) | PASSWORD EQ_? STRING_ | ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT) | STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_) | STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_) | STATS_SAMPLE_PAGES EQ_? NUMBER_ | TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))? | UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_ ; addColumnSpecification : ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_) ; firstOrAfterColumn : FIRST | AFTER columnName ; addIndexSpecification : ADD indexDefinition_ ; addConstraintSpecification : ADD constraintDefinition_ ; changeColumnSpecification : CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn? ; dropColumnSpecification : DROP COLUMN? columnName ; dropIndexSpecification : DROP (INDEX | KEY) indexName ; dropPrimaryKeySpecification : DROP primaryKey ; modifyColumnSpecification : MODIFY COLUMN? columnDefinition firstOrAfterColumn? ; // TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column renameColumnSpecification : RENAME COLUMN columnName TO columnName ; // TODO hongjun: should support renameIndexSpecification on mysql renameIndexSpecification : RENAME (INDEX | KEY) indexName TO indexName ; // TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table renameTableSpecification_ : RENAME (TO | AS)? newTableName ; newTableName : identifier_ ; partitionDefinitions_ : LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_ ; partitionDefinition_ : PARTITION identifier_ (VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))? partitionDefinitionOption_* (LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)? ; partitionLessThanValue_ : LP_ (expr | partitionValueList_) RP_ | MAXVALUE ; partitionValueList_ : literals (COMMA_ literals)* ; partitionDefinitionOption_ : STORAGE? ENGINE EQ_? identifier_ | COMMENT EQ_? STRING_ | DATA DIRECTORY EQ_? STRING_ | INDEX DIRECTORY EQ_? STRING_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | TABLESPACE EQ_? identifier_ ; subpartitionDefinition_ : SUBPARTITION identifier_ partitionDefinitionOption_* ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE tableNotExistClause_ tableName (createDefinitionClause_ | createLikeClause_) ; createIndex : CREATE createIndexSpecification_ INDEX indexName indexType_? ON tableName ; alterTable : ALTER TABLE tableName alterSpecifications_? ; dropTable : DROP TEMPORARY? TABLE (IF EXISTS)? tableName (COMMA_ tableName)* ; dropIndex : DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName ; truncateTable : TRUNCATE TABLE? tableName ; createTableSpecification_ : TEMPORARY? ; tableNotExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ createDefinitions_ RP_ ; createDefinitions_ : createDefinition_ (COMMA_ createDefinition_)* ; createDefinition_ : columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_ ; columnDefinition : columnName dataType (inlineDataType_* | generatedDataType_*) ; inlineDataType_ : commonDataTypeOption_ | AUTO_INCREMENT | DEFAULT (literals | expr) | COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT) | STORAGE (DISK | MEMORY | DEFAULT) ; commonDataTypeOption_ : primaryKey | UNIQUE KEY? | NOT? NULL | collateClause_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_ ; checkConstraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)? ; referenceDefinition_ : REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)* ; referenceOption_ : RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT ; generatedDataType_ : commonDataTypeOption_ | (GENERATED ALWAYS)? AS expr | (VIRTUAL | STORED) ; indexDefinition_ : (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_* ; indexType_ : USING (BTREE | HASH) ; keyParts_ : LP_ keyPart_ (COMMA_ keyPart_)* RP_ ; keyPart_ : (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)? ; indexOption_ : KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE ; constraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_) ; primaryKeyOption_ : primaryKey indexType_? columnNames indexOption_* ; primaryKey : PRIMARY? KEY ; uniqueOption_ : UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_* ; foreignKeyOption_ : FOREIGN KEY indexName? columnNames referenceDefinition_ ; createLikeClause_ : LP_? LIKE tableName RP_? ; createIndexSpecification_ : (UNIQUE | FULLTEXT | SPATIAL)? ; alterSpecifications_ : alterSpecification_ (COMMA_ alterSpecification_)* ; alterSpecification_ : tableOptions_ | addColumnSpecification | addIndexSpecification | addConstraintSpecification | ADD checkConstraintDefinition_ | DROP CHECK ignoredIdentifier_ | ALTER CHECK ignoredIdentifier_ NOT? ENFORCED | ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY) | ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT) | ALTER INDEX indexName (VISIBLE | INVISIBLE) | changeColumnSpecification | DEFAULT? characterSet_ collateClause_? | CONVERT TO characterSet_ collateClause_? | (DISABLE | ENABLE) KEYS | (DISCARD | IMPORT_) TABLESPACE | dropColumnSpecification | dropIndexSpecification | dropPrimaryKeySpecification | DROP FOREIGN KEY ignoredIdentifier_ | FORCE | LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE) | modifyColumnSpecification // TODO hongjun investigate ORDER BY col_name [, col_name] ... | ORDER BY columnNames | renameColumnSpecification | renameIndexSpecification | renameTableSpecification_ | (WITHOUT | WITH) VALIDATION | ADD PARTITION LP_ partitionDefinition_ RP_ | DROP PARTITION ignoredIdentifiers_ | DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE | IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE | TRUNCATE PARTITION (ignoredIdentifiers_ | ALL) | COALESCE PARTITION NUMBER_ | REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_ | EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)? | ANALYZE PARTITION (ignoredIdentifiers_ | ALL) | CHECK PARTITION (ignoredIdentifiers_ | ALL) | OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL) | REBUILD PARTITION (ignoredIdentifiers_ | ALL) | REPAIR PARTITION (ignoredIdentifiers_ | ALL) | REMOVE PARTITIONING | UPGRADE PARTITIONING ; tableOptions_ : tableOption_ (COMMA_? tableOption_)* ; tableOption_ : AUTO_INCREMENT EQ_? NUMBER_ | AVG_ROW_LENGTH EQ_? NUMBER_ | DEFAULT? (characterSet_ | collateClause_) | CHECKSUM EQ_? NUMBER_ | COMMENT EQ_? STRING_ | COMPRESSION EQ_? STRING_ | CONNECTION EQ_? STRING_ | (DATA | INDEX) DIRECTORY EQ_? STRING_ | DELAY_KEY_WRITE EQ_? NUMBER_ | ENCRYPTION EQ_? STRING_ | ENGINE EQ_? ignoredIdentifier_ | INSERT_METHOD EQ_? (NO | FIRST | LAST) | KEY_BLOCK_SIZE EQ_? NUMBER_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | PACK_KEYS EQ_? (NUMBER_ | DEFAULT) | PASSWORD EQ_? STRING_ | ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT) | STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_) | STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_) | STATS_SAMPLE_PAGES EQ_? NUMBER_ | TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))? | UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_ ; addColumnSpecification : ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_) ; firstOrAfterColumn : FIRST | AFTER columnName ; addIndexSpecification : ADD indexDefinition_ ; addConstraintSpecification : ADD constraintDefinition_ ; changeColumnSpecification : CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn? ; dropColumnSpecification : DROP COLUMN? columnName ; dropIndexSpecification : DROP (INDEX | KEY) indexName ; dropPrimaryKeySpecification : DROP primaryKey ; modifyColumnSpecification : MODIFY COLUMN? columnDefinition firstOrAfterColumn? ; // TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column renameColumnSpecification : RENAME COLUMN columnName TO columnName ; // TODO hongjun: should support renameIndexSpecification on mysql renameIndexSpecification : RENAME (INDEX | KEY) indexName TO indexName ; // TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table renameTableSpecification_ : RENAME (TO | AS)? newTableName ; newTableName : identifier_ ; partitionDefinitions_ : LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_ ; partitionDefinition_ : PARTITION identifier_ (VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))? partitionDefinitionOption_* (LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)? ; partitionLessThanValue_ : LP_ (expr | partitionValueList_) RP_ | MAXVALUE ; partitionValueList_ : literals (COMMA_ literals)* ; partitionDefinitionOption_ : STORAGE? ENGINE EQ_? identifier_ | COMMENT EQ_? STRING_ | DATA DIRECTORY EQ_? STRING_ | INDEX DIRECTORY EQ_? STRING_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | TABLESPACE EQ_? identifier_ ; subpartitionDefinition_ : SUBPARTITION identifier_ partitionDefinitionOption_* ;
check style
check style
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
bdcf81ae0165695a4df0957056d0b88c0a8a4d1c
robozonky-strategy-natural/src/main/antlr4/com/github/robozonky/strategy/natural/NaturalLanguageStrategy.g4
robozonky-strategy-natural/src/main/antlr4/com/github/robozonky/strategy/natural/NaturalLanguageStrategy.g4
grammar NaturalLanguageStrategy; import Defaults, InvestmentSize, PortfolioStructure, MarketplaceFilters; @header { import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.Collections; import org.apache.logging.log4j.LogManager; import com.github.robozonky.api.remote.enums.*; import com.github.robozonky.api.remote.entities.*; import com.github.robozonky.strategy.natural.*; } primaryExpression returns [ParsedStrategy result] : v=minimumVersionExpression? ( ( s=portfolioExpression { final DefaultValues v = new DefaultValues($s.result); // enable primary and secondary marketplaces, disable selling, do not enable reservation system final FilterSupplier f = new FilterSupplier(v, Collections.emptySet(), Collections.emptySet()); $result = new ParsedStrategy(v, f); }) | ( c=complexExpression { $result = $c.result; }) ) { // only set version when the optional expression was actually present if ($ctx.minimumVersionExpression() != null) $result.setMinimumVersion($v.result); } EOF ; minimumVersionExpression returns [RoboZonkyVersion result] : 'Tato strategie vyžaduje RoboZonky ve verzi ' major=intExpr DOT minor=intExpr DOT micro=intExpr ' nebo pozdější.' { $result = new RoboZonkyVersion($major.result, $minor.result, $micro.result); } ; complexExpression returns [ParsedStrategy result] @init { Collection<PortfolioShare> portfolioStructures = Collections.emptyList(); Map<Rating, MoneyRange> investmentSizes = Collections.emptyMap(); Map<Rating, MoneyRange> purchaseSizes = Collections.emptyMap(); Collection<MarketplaceFilter> primaryFilters = Collections.emptyList(); Collection<MarketplaceFilter> secondaryFilters = Collections.emptyList(); Collection<MarketplaceFilter> sellFilters = Collections.emptyList(); }: DELIM 'Obecná nastavení' d=defaultExpression ( DELIM 'Úprava struktury portfolia' p=portfolioStructureExpression { portfolioStructures = $p.result; } )? ( ( DELIM 'Výše investice' i1=legacyInvestmentSizeExpression { investmentSizes = $i1.result; } ) | ( ( DELIM 'Výše investice' i2=investmentSizeExpression { investmentSizes = $i2.result; } ) ( DELIM 'Výše nákupu' i3=purchaseSizeExpression { purchaseSizes = $i3.result; } )? ) )? ( ( ( DELIM 'Filtrování tržiště' m=marketplaceFilterExpression { primaryFilters = $m.primaryEnabled ? $m.primary : null; secondaryFilters = $m.secondaryEnabled ? $m.secondary : null; } ) ) | ( 'Ignorovat všechny půjčky i participace.' { primaryFilters = null; secondaryFilters = null; } ) | ( 'Investovat do všech půjček a participací.' ) ) { DefaultValues v = $d.result; } ( ( DELIM 'Prodej participací' s=sellFilterExpression { v.setSellingMode(SellingMode.SELL_FILTERS); sellFilters = $s.result; } ) | ( 'Prodávat všechny participace bez poplatku a slevy, které odpovídají filtrům tržiště.' { v.setSellingMode(SellingMode.FREE_UNDISCOUNTED_AND_OUTSIDE_STRATEGY); } ) | ( 'Prodávat všechny participace bez poplatku, které odpovídají filtrům tržiště.' { v.setSellingMode(SellingMode.FREE_AND_OUTSIDE_STRATEGY); } ) | ( 'Prodej participací zakázán.' ) ) { $result = new ParsedStrategy(v, portfolioStructures, investmentSizes, purchaseSizes, new FilterSupplier(v, primaryFilters, secondaryFilters, sellFilters)); } ;
grammar NaturalLanguageStrategy; import Defaults, InvestmentSize, PortfolioStructure, MarketplaceFilters; @header { import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.Collections; import org.apache.logging.log4j.LogManager; import com.github.robozonky.api.remote.enums.*; import com.github.robozonky.api.remote.entities.*; import com.github.robozonky.strategy.natural.*; } primaryExpression returns [ParsedStrategy result] : v=minimumVersionExpression? ( ( s=portfolioExpression { final DefaultValues v = new DefaultValues($s.result); // enable primary and secondary marketplaces, disable selling, do not enable reservation system final FilterSupplier f = new FilterSupplier(v, Collections.emptySet(), Collections.emptySet()); $result = new ParsedStrategy(v, f); }) | ( c=complexExpression { $result = $c.result; }) ) { // only set version when the optional expression was actually present if ($ctx.minimumVersionExpression() != null) $result.setMinimumVersion($v.result); } EOF ; minimumVersionExpression returns [RoboZonkyVersion result] : 'Tato strategie vyžaduje RoboZonky ve verzi ' major=intExpr DOT minor=intExpr DOT micro=intExpr ' nebo pozdější.' { $result = new RoboZonkyVersion($major.result, $minor.result, $micro.result); } ; complexExpression returns [ParsedStrategy result] @init { Collection<PortfolioShare> portfolioStructures = Collections.emptyList(); Map<Rating, MoneyRange> investmentSizes = Collections.emptyMap(); Map<Rating, MoneyRange> purchaseSizes = Collections.emptyMap(); Collection<MarketplaceFilter> primaryFilters = Collections.emptyList(); Collection<MarketplaceFilter> secondaryFilters = Collections.emptyList(); Collection<MarketplaceFilter> sellFilters = Collections.emptyList(); }: DELIM 'Obecná nastavení' d=defaultExpression ( DELIM 'Úprava struktury portfolia' p=portfolioStructureExpression { portfolioStructures = $p.result; } )? ( ( DELIM 'Výše investice' i1=legacyInvestmentSizeExpression { investmentSizes = $i1.result; } ) | ( ( DELIM 'Výše investice' i2=investmentSizeExpression { investmentSizes = $i2.result; } )? ( DELIM 'Výše nákupu' i3=purchaseSizeExpression { purchaseSizes = $i3.result; } ) ) )? ( ( ( DELIM 'Filtrování tržiště' m=marketplaceFilterExpression { primaryFilters = $m.primaryEnabled ? $m.primary : null; secondaryFilters = $m.secondaryEnabled ? $m.secondary : null; } ) ) | ( 'Ignorovat všechny půjčky i participace.' { primaryFilters = null; secondaryFilters = null; } ) | ( 'Investovat do všech půjček a participací.' ) ) { DefaultValues v = $d.result; } ( ( DELIM 'Prodej participací' s=sellFilterExpression { v.setSellingMode(SellingMode.SELL_FILTERS); sellFilters = $s.result; } ) | ( 'Prodávat všechny participace bez poplatku a slevy, které odpovídají filtrům tržiště.' { v.setSellingMode(SellingMode.FREE_UNDISCOUNTED_AND_OUTSIDE_STRATEGY); } ) | ( 'Prodávat všechny participace bez poplatku, které odpovídají filtrům tržiště.' { v.setSellingMode(SellingMode.FREE_AND_OUTSIDE_STRATEGY); } ) | ( 'Prodej participací zakázán.' ) ) { $result = new ParsedStrategy(v, portfolioStructures, investmentSizes, purchaseSizes, new FilterSupplier(v, primaryFilters, secondaryFilters, sellFilters)); } ;
Fix investment sizes parser bug
Fix investment sizes parser bug
ANTLR
apache-2.0
triceo/zonkybot,triceo/robozonky,triceo/robozonky,triceo/zonkybot,RoboZonky/robozonky,RoboZonky/robozonky
57d3f465a88c56f9ca16aa43ec0eef52fee7215d
sharding-core/sharding-core-parse/sharding-core-parse-sqlserver/src/main/antlr4/imports/sqlserver/DCLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-sqlserver/src/main/antlr4/imports/sqlserver/DCLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DCLStatement; import Symbol, Keyword, Literals, BaseRule; grant : GRANT (classPrivilegesClause_ | classTypePrivilegesClause_) ; revoke : REVOKE (optionForClause_? classPrivilegesClause_ | classTypePrivilegesClause_) ; deny : DENY (classPrivilegesClause_ | classTypePrivilegesClause_) ; classPrivilegesClause_ : classPrivileges_ (ON onClassClause_)? ; classTypePrivilegesClause_ : classTypePrivileges_ (ON onClassTypeClause_)? ; optionForClause_ : GRANT OPTION FOR ; classPrivileges_ : privilegeType_ columnNames? (COMMA_ privilegeType_ columnNames?)* ; onClassClause_ : class_? tableName ; classTypePrivileges_ : privilegeType_ (COMMA_ privilegeType_)* ; onClassTypeClause_ : classType_? tableName ; privilegeType_ : ALL PRIVILEGES? | IDENTIFIER_+? ; class_ : IDENTIFIER_ COLON_ COLON_ ; classType_ : (LOGIN | DATABASE | OBJECT | ROLE | SCHEMA | USER) COLON_ COLON_ ; createUser : CREATE USER ; dropUser : DROP USER ; alterUser : ALTER USER ; createRole : CREATE ROLE ; dropRole : DROP ROLE ; alterRole : ALTER ROLE ; createLogin : CREATE LOGIN ; dropLogin : DROP LOGIN ; alterLogin : ALTER LOGIN ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DCLStatement; import Symbol, Keyword, Literals, BaseRule; grant : GRANT (classPrivilegesClause_ | classTypePrivilegesClause_) ; revoke : REVOKE (optionForClause_? classPrivilegesClause_ | classTypePrivilegesClause_) ; deny : DENY (classPrivilegesClause_ | classTypePrivilegesClause_) ; classPrivilegesClause_ : classPrivileges_ (ON onClassClause_)? ; classTypePrivilegesClause_ : classTypePrivileges_ (ON onClassTypeClause_)? ; optionForClause_ : GRANT OPTION FOR ; classPrivileges_ : privilegeType_ columnNames? (COMMA_ privilegeType_ columnNames?)* ; onClassClause_ : class_? tableName ; classTypePrivileges_ : privilegeType_ (COMMA_ privilegeType_)* ; onClassTypeClause_ : classType_? tableName ; privilegeType_ : ALL PRIVILEGES? | ignoredIdentifiers_ ; class_ : IDENTIFIER_ COLON_ COLON_ ; classType_ : (LOGIN | DATABASE | OBJECT | ROLE | SCHEMA | USER) COLON_ COLON_ ; createUser : CREATE USER ; dropUser : DROP USER ; alterUser : ALTER USER ; createRole : CREATE ROLE ; dropRole : DROP ROLE ; alterRole : ALTER ROLE ; createLogin : CREATE LOGIN ; dropLogin : DROP LOGIN ; alterLogin : ALTER LOGIN ;
check style
check style
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
c41632f55ca2e4d8da46ea89ad14449ef5c90e39
graphql/GraphQL.g4
graphql/GraphQL.g4
/* The MIT License (MIT) Copyright (c) 2015 Joseph T. McBride Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. GraphQL grammar derived from: GraphQL Draft Specification - July 2015 http://facebook.github.io/graphql/ https://github.com/facebook/graphql AB:10-sep19: replaced type with type_ to resolve conflict for golang generator AB: 13-oct-19: added type system as per June 2018 specs AB: 26-oct-19: added ID type AB: 30-Oct-19: description, boolean, schema & Block string fix. now parses: https://raw.githubusercontent.com/graphql-cats/graphql-cats/master/scenarios/validation/validation.schema.graphql */ grammar GraphQL; //https://spec.graphql.org/June2018/#sec-Language.Document document: definition+; definition: executableDefinition | typeSystemDefinition | typeSystemExtension; //https://spec.graphql.org/June2018/#ExecutableDefinition executableDefinition: operationDefinition | fragmentDefinition; //https://spec.graphql.org/June2018/#sec-Language.Operations operationDefinition: operationType name? variableDefinitions? directives? selectionSet | selectionSet ; operationType: 'query' | 'mutation' | 'subscription'; //https://spec.graphql.org/June2018/#sec-Selection-Sets selectionSet: '{' selection+ '}'; selection: field | fragmentSpread | inlineFragment ; //https://spec.graphql.org/June2018/#sec-Language.Fields field: alias? name arguments? directives? selectionSet?; //https://spec.graphql.org/June2018/#sec-Language.Arguments arguments: '(' argument+ ')'; argument: name ':' value; //https://spec.graphql.org/June2018/#sec-Field-Alias alias: name ':'; //https://spec.graphql.org/June2018/#sec-Language.Fragments fragmentSpread: '...' fragmentName directives?; fragmentDefinition: 'fragment' fragmentName 'on' typeCondition directives? selectionSet; fragmentName: name; // except on //https://spec.graphql.org/June2018/#sec-Type-Conditions typeCondition: 'on' namedType; //https://spec.graphql.org/June2018/#sec-Inline-Fragments inlineFragment: '...' typeCondition? directives? selectionSet; //https://spec.graphql.org/June2018/#sec-Input-Values value: variable | intValue | floatValue | stringValue | booleanValue | nullValue | enumValue | listValue | objectValue ; //https://spec.graphql.org/June2018/#sec-Int-Value intValue: INT; //https://spec.graphql.org/June2018/#sec-Float-Value floatValue: FLOAT; //https://spec.graphql.org/June2018/#sec-Boolean-Value booleanValue : 'true' | 'false' ; //https://spec.graphql.org/June2018/#sec-String-Value stringValue : STRING | BLOCK_STRING; //https://spec.graphql.org/June2018/#sec-Null-Value nullValue: 'null'; //https://spec.graphql.org/June2018/#sec-Enum-Value enumValue: name; //{ not (nullValue | booleanValue) }; //https://spec.graphql.org/June2018/#sec-List-Value listValue: '[' ']' | '[' value+ ']' ; //https://spec.graphql.org/June2018/#sec-Input-Object-Values objectValue: '{' objectField* '}'; objectField: name ':' value; //https://spec.graphql.org/June2018/#sec-Language.Variables variable: '$' name; variableDefinitions: '(' variableDefinition+ ')'; variableDefinition: variable ':' type_ defaultValue?; defaultValue: '=' value; //https://spec.graphql.org/June2018/#sec-Type-References type_: namedType '!'? | listType '!'? ; namedType: name; listType: '[' type_ ']'; //https://spec.graphql.org/June2018/#sec-Language.Directives directives: directive+; directive: '@' name arguments?; // https://graphql.github.io/graphql-spec/June2018/#TypeSystemDefinition typeSystemDefinition: schemaDefinition | typeDefinition | directiveDefinition ; //https://spec.graphql.org/June2018/#TypeSystemExtension typeSystemExtension: schemaExtension | typeExtension ; // https://graphql.github.io/graphql-spec/June2018/#sec-Schema schemaDefinition: 'schema' directives? '{' rootOperationTypeDefinition+ '}'; rootOperationTypeDefinition: operationType ':' namedType; //https://spec.graphql.org/June2018/#sec-Schema-Extension schemaExtension: 'extend' 'schema' directives? '{' operationTypeDefinition+ '}' | 'extend' 'schema' directives ; //https://spec.graphql.org/June2018/#OperationTypeDefinition operationTypeDefinition: operationType ':' namedType; //https://spec.graphql.org/June2018/#sec-Descriptions description: stringValue; //https://spec.graphql.org/June2018/#sec-Types typeDefinition: scalarTypeDefinition | objectTypeDefinition | interfaceTypeDefinition | unionTypeDefinition | enumTypeDefinition | inputObjectTypeDefinition; //https://spec.graphql.org/June2018/#sec-Type-Extensions typeExtension : scalarTypeExtension | objectTypeExtension | interfaceTypeExtension | unionTypeExtension | enumTypeExtension | inputObjectTypeExtension ; //https://spec.graphql.org/June2018/#sec-Scalars scalarTypeDefinition: description? 'scalar' name directives?; //https://spec.graphql.org/June2018/#sec-Scalar-Extensions scalarTypeExtension: 'extends' 'scalar' name directives; // https://graphql.github.io/graphql-spec/June2018/#sec-Objects objectTypeDefinition : description? 'type' name implementsInterfaces? directives? fieldsDefinition?; implementsInterfaces: 'implements' '&'? namedType | implementsInterfaces '&' namedType ; fieldsDefinition: '{' fieldDefinition+ '}'; fieldDefinition: description? name argumentsDefinition? ':' type_ directives? ; //https://spec.graphql.org/June2018/#sec-Field-Arguments argumentsDefinition: '(' inputValueDefinition+ ')'; inputValueDefinition: description? name ':' type_ defaultValue? directives?; //https://spec.graphql.org/June2018/#sec-Object-Extensions objectTypeExtension: 'extend' 'type' name implementsInterfaces? directives? fieldsDefinition | 'extend' 'type' name implementsInterfaces? directives | 'extend' 'type' name implementsInterfaces ; //https://spec.graphql.org/June2018/#sec-Interfaces interfaceTypeDefinition: description? 'interface' name directives? fieldsDefinition?; //https://spec.graphql.org/June2018/#sec-Interface-Extensions interfaceTypeExtension: 'extend' 'interface' name directives? fieldsDefinition | 'extend' 'interface' name directives ; // https://graphql.github.io/graphql-spec/June2018/#sec-Unions unionTypeDefinition: description? 'union' name directives? unionMemberTypes?; unionMemberTypes: '=' '|'? namedType ('|'namedType)* ; //https://spec.graphql.org/June2018/#sec-Union-Extensions unionTypeExtension : 'extend' 'union' name directives? unionMemberTypes | 'extend' 'union' name directives ; //https://spec.graphql.org/June2018/#sec-Enums enumTypeDefinition: description? 'enum' name directives? enumValuesDefinition?; enumValuesDefinition: '{' enumValueDefinition+ '}'; enumValueDefinition: description? enumValue directives?; //https://spec.graphql.org/June2018/#sec-Enum-Extensions enumTypeExtension: 'extend' 'enum' name directives? enumValuesDefinition | 'extend' 'enum' name directives ; //https://spec.graphql.org/June2018/#sec-Input-Objects inputObjectTypeDefinition: description? 'input' name directives? inputFieldsDefinition?; inputFieldsDefinition: '{' inputValueDefinition+ '}'; //https://spec.graphql.org/June2018/#sec-Input-Object-Extensions inputObjectTypeExtension: 'extend' 'input' name directives? inputFieldsDefinition | 'extend' 'input' name directives ; //https://spec.graphql.org/June2018/#sec-Type-System.Directives directiveDefinition: description? 'directive' '@' name argumentsDefinition? 'on' directiveLocations; directiveLocations: directiveLocation ('|' directiveLocation)*; directiveLocation: executableDirectiveLocation | typeSystemDirectiveLocation; executableDirectiveLocation: 'QUERY' | 'MUTATION' | 'SUBSCRIPTION' | 'FIELD' | 'FRAGMENT_DEFINITION' | 'FRAGMENT_SPREAD' | 'INLINE_FRAGMENT' ; typeSystemDirectiveLocation: 'SCHEMA' | 'SCALAR' | 'OBJECT' | 'FIELD_DEFINITION' | 'ARGUMENT_DEFINITION' | 'INTERFACE' | 'UNION' | 'ENUM' | 'ENUM_VALUE' | 'INPUT_OBJECT' | 'INPUT_FIELD_DEFINITION' ; name: NAME; //Start lexer NAME: [_A-Za-z] [_0-9A-Za-z]*; fragment CHARACTER: ( ESC | ~ ["\\]); STRING: '"' CHARACTER* '"'; BLOCK_STRING : '"""' .*? '"""' ; ID: STRING; fragment ESC: '\\' ( ["\\/bfnrt] | UNICODE); fragment UNICODE: 'u' HEX HEX HEX HEX; fragment HEX: [0-9a-fA-F]; fragment NONZERO_DIGIT: [1-9]; fragment DIGIT: [0-9]; fragment FRACTIONAL_PART: '.' DIGIT+; fragment EXPONENTIAL_PART: EXPONENT_INDICATOR SIGN? DIGIT+; fragment EXPONENT_INDICATOR: [eE]; fragment SIGN: [+-]; fragment NEGATIVE_SIGN: '-'; FLOAT: INT FRACTIONAL_PART | INT EXPONENTIAL_PART | INT FRACTIONAL_PART EXPONENTIAL_PART ; INT: NEGATIVE_SIGN? '0' | NEGATIVE_SIGN? NONZERO_DIGIT DIGIT* ; PUNCTUATOR: '!' | '$' | '(' | ')' | '...' | ':' | '=' | '@' | '[' | ']' | '{' | '}' | '|' ; // no leading zeros fragment EXP: [Ee] [+\-]? INT; // \- since - means "range" inside [...] WS: [ \t\n\r]+ -> skip; COMMA: ',' -> skip; LineComment : '#' ~[\r\n]* -> skip ; UNICODE_BOM: (UTF8_BOM | UTF16_BOM | UTF32_BOM ) -> skip ; UTF8_BOM: '\uEFBBBF'; UTF16_BOM: '\uFEFF'; UTF32_BOM: '\u0000FEFF';
/* The MIT License (MIT) Copyright (c) 2015 Joseph T. McBride Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. GraphQL grammar derived from: GraphQL Draft Specification - July 2015 http://facebook.github.io/graphql/ https://github.com/facebook/graphql AB:10-sep19: replaced type with type_ to resolve conflict for golang generator AB: 13-oct-19: added type system as per June 2018 specs AB: 26-oct-19: added ID type AB: 30-Oct-19: description, boolean, schema & Block string fix. now parses: https://raw.githubusercontent.com/graphql-cats/graphql-cats/master/scenarios/validation/validation.schema.graphql */ grammar GraphQL; //https://spec.graphql.org/June2018/#sec-Language.Document document: definition+; definition: executableDefinition | typeSystemDefinition | typeSystemExtension; //https://spec.graphql.org/June2018/#ExecutableDefinition executableDefinition: operationDefinition | fragmentDefinition; //https://spec.graphql.org/June2018/#sec-Language.Operations operationDefinition: operationType name? variableDefinitions? directives? selectionSet | selectionSet ; operationType: 'query' | 'mutation' | 'subscription'; //https://spec.graphql.org/June2018/#sec-Selection-Sets selectionSet: '{' selection+ '}'; selection: field | fragmentSpread | inlineFragment ; //https://spec.graphql.org/June2018/#sec-Language.Fields field: alias? name arguments? directives? selectionSet?; //https://spec.graphql.org/June2018/#sec-Language.Arguments arguments: '(' argument+ ')'; argument: name ':' value; //https://spec.graphql.org/June2018/#sec-Field-Alias alias: name ':'; //https://spec.graphql.org/June2018/#sec-Language.Fragments fragmentSpread: '...' fragmentName directives?; fragmentDefinition: 'fragment' fragmentName typeCondition directives? selectionSet; fragmentName: name; // except on //https://spec.graphql.org/June2018/#sec-Type-Conditions typeCondition: 'on' namedType; //https://spec.graphql.org/June2018/#sec-Inline-Fragments inlineFragment: '...' typeCondition? directives? selectionSet; //https://spec.graphql.org/June2018/#sec-Input-Values value: variable | intValue | floatValue | stringValue | booleanValue | nullValue | enumValue | listValue | objectValue ; //https://spec.graphql.org/June2018/#sec-Int-Value intValue: INT; //https://spec.graphql.org/June2018/#sec-Float-Value floatValue: FLOAT; //https://spec.graphql.org/June2018/#sec-Boolean-Value booleanValue : 'true' | 'false' ; //https://spec.graphql.org/June2018/#sec-String-Value stringValue : STRING | BLOCK_STRING; //https://spec.graphql.org/June2018/#sec-Null-Value nullValue: 'null'; //https://spec.graphql.org/June2018/#sec-Enum-Value enumValue: name; //{ not (nullValue | booleanValue) }; //https://spec.graphql.org/June2018/#sec-List-Value listValue: '[' ']' | '[' value+ ']' ; //https://spec.graphql.org/June2018/#sec-Input-Object-Values objectValue: '{' objectField* '}'; objectField: name ':' value; //https://spec.graphql.org/June2018/#sec-Language.Variables variable: '$' name; variableDefinitions: '(' variableDefinition+ ')'; variableDefinition: variable ':' type_ defaultValue?; defaultValue: '=' value; //https://spec.graphql.org/June2018/#sec-Type-References type_: namedType '!'? | listType '!'? ; namedType: name; listType: '[' type_ ']'; //https://spec.graphql.org/June2018/#sec-Language.Directives directives: directive+; directive: '@' name arguments?; // https://graphql.github.io/graphql-spec/June2018/#TypeSystemDefinition typeSystemDefinition: schemaDefinition | typeDefinition | directiveDefinition ; //https://spec.graphql.org/June2018/#TypeSystemExtension typeSystemExtension: schemaExtension | typeExtension ; // https://graphql.github.io/graphql-spec/June2018/#sec-Schema schemaDefinition: 'schema' directives? '{' rootOperationTypeDefinition+ '}'; rootOperationTypeDefinition: operationType ':' namedType; //https://spec.graphql.org/June2018/#sec-Schema-Extension schemaExtension: 'extend' 'schema' directives? '{' operationTypeDefinition+ '}' | 'extend' 'schema' directives ; //https://spec.graphql.org/June2018/#OperationTypeDefinition operationTypeDefinition: operationType ':' namedType; //https://spec.graphql.org/June2018/#sec-Descriptions description: stringValue; //https://spec.graphql.org/June2018/#sec-Types typeDefinition: scalarTypeDefinition | objectTypeDefinition | interfaceTypeDefinition | unionTypeDefinition | enumTypeDefinition | inputObjectTypeDefinition; //https://spec.graphql.org/June2018/#sec-Type-Extensions typeExtension : scalarTypeExtension | objectTypeExtension | interfaceTypeExtension | unionTypeExtension | enumTypeExtension | inputObjectTypeExtension ; //https://spec.graphql.org/June2018/#sec-Scalars scalarTypeDefinition: description? 'scalar' name directives?; //https://spec.graphql.org/June2018/#sec-Scalar-Extensions scalarTypeExtension: 'extends' 'scalar' name directives; // https://graphql.github.io/graphql-spec/June2018/#sec-Objects objectTypeDefinition : description? 'type' name implementsInterfaces? directives? fieldsDefinition?; implementsInterfaces: 'implements' '&'? namedType | implementsInterfaces '&' namedType ; fieldsDefinition: '{' fieldDefinition+ '}'; fieldDefinition: description? name argumentsDefinition? ':' type_ directives? ; //https://spec.graphql.org/June2018/#sec-Field-Arguments argumentsDefinition: '(' inputValueDefinition+ ')'; inputValueDefinition: description? name ':' type_ defaultValue? directives?; //https://spec.graphql.org/June2018/#sec-Object-Extensions objectTypeExtension: 'extend' 'type' name implementsInterfaces? directives? fieldsDefinition | 'extend' 'type' name implementsInterfaces? directives | 'extend' 'type' name implementsInterfaces ; //https://spec.graphql.org/June2018/#sec-Interfaces interfaceTypeDefinition: description? 'interface' name directives? fieldsDefinition?; //https://spec.graphql.org/June2018/#sec-Interface-Extensions interfaceTypeExtension: 'extend' 'interface' name directives? fieldsDefinition | 'extend' 'interface' name directives ; // https://graphql.github.io/graphql-spec/June2018/#sec-Unions unionTypeDefinition: description? 'union' name directives? unionMemberTypes?; unionMemberTypes: '=' '|'? namedType ('|'namedType)* ; //https://spec.graphql.org/June2018/#sec-Union-Extensions unionTypeExtension : 'extend' 'union' name directives? unionMemberTypes | 'extend' 'union' name directives ; //https://spec.graphql.org/June2018/#sec-Enums enumTypeDefinition: description? 'enum' name directives? enumValuesDefinition?; enumValuesDefinition: '{' enumValueDefinition+ '}'; enumValueDefinition: description? enumValue directives?; //https://spec.graphql.org/June2018/#sec-Enum-Extensions enumTypeExtension: 'extend' 'enum' name directives? enumValuesDefinition | 'extend' 'enum' name directives ; //https://spec.graphql.org/June2018/#sec-Input-Objects inputObjectTypeDefinition: description? 'input' name directives? inputFieldsDefinition?; inputFieldsDefinition: '{' inputValueDefinition+ '}'; //https://spec.graphql.org/June2018/#sec-Input-Object-Extensions inputObjectTypeExtension: 'extend' 'input' name directives? inputFieldsDefinition | 'extend' 'input' name directives ; //https://spec.graphql.org/June2018/#sec-Type-System.Directives directiveDefinition: description? 'directive' '@' name argumentsDefinition? 'on' directiveLocations; directiveLocations: directiveLocation ('|' directiveLocation)*; directiveLocation: executableDirectiveLocation | typeSystemDirectiveLocation; executableDirectiveLocation: 'QUERY' | 'MUTATION' | 'SUBSCRIPTION' | 'FIELD' | 'FRAGMENT_DEFINITION' | 'FRAGMENT_SPREAD' | 'INLINE_FRAGMENT' ; typeSystemDirectiveLocation: 'SCHEMA' | 'SCALAR' | 'OBJECT' | 'FIELD_DEFINITION' | 'ARGUMENT_DEFINITION' | 'INTERFACE' | 'UNION' | 'ENUM' | 'ENUM_VALUE' | 'INPUT_OBJECT' | 'INPUT_FIELD_DEFINITION' ; name: NAME; //Start lexer NAME: [_A-Za-z] [_0-9A-Za-z]*; fragment CHARACTER: ( ESC | ~ ["\\]); STRING: '"' CHARACTER* '"'; BLOCK_STRING : '"""' .*? '"""' ; ID: STRING; fragment ESC: '\\' ( ["\\/bfnrt] | UNICODE); fragment UNICODE: 'u' HEX HEX HEX HEX; fragment HEX: [0-9a-fA-F]; fragment NONZERO_DIGIT: [1-9]; fragment DIGIT: [0-9]; fragment FRACTIONAL_PART: '.' DIGIT+; fragment EXPONENTIAL_PART: EXPONENT_INDICATOR SIGN? DIGIT+; fragment EXPONENT_INDICATOR: [eE]; fragment SIGN: [+-]; fragment NEGATIVE_SIGN: '-'; FLOAT: INT FRACTIONAL_PART | INT EXPONENTIAL_PART | INT FRACTIONAL_PART EXPONENTIAL_PART ; INT: NEGATIVE_SIGN? '0' | NEGATIVE_SIGN? NONZERO_DIGIT DIGIT* ; PUNCTUATOR: '!' | '$' | '(' | ')' | '...' | ':' | '=' | '@' | '[' | ']' | '{' | '}' | '|' ; // no leading zeros fragment EXP: [Ee] [+\-]? INT; // \- since - means "range" inside [...] WS: [ \t\n\r]+ -> skip; COMMA: ',' -> skip; LineComment : '#' ~[\r\n]* -> skip ; UNICODE_BOM: (UTF8_BOM | UTF16_BOM | UTF32_BOM ) -> skip ; UTF8_BOM: '\uEFBBBF'; UTF16_BOM: '\uFEFF'; UTF32_BOM: '\u0000FEFF';
Remove duplicate 'on' from fragment definition
Remove duplicate 'on' from fragment definition The 'on' work is defined on the typeCondition and isn't repeated on the fragment definition. https://spec.graphql.org/June2018/#sec-Language.Fragments
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
eb66cb75504158c1a70f939bd143d3819e2af1e7
sharding-jdbc-ddl-parser/src/main/antlr4/io/shardingsphere/parser/antlr/postgre/PostgreDDL.g4
sharding-jdbc-ddl-parser/src/main/antlr4/io/shardingsphere/parser/antlr/postgre/PostgreDDL.g4
grammar PostgreDDL; import PostgreKeyword, DataType, Keyword,BaseRule,Symbol; createIndex: CREATE UNIQUE? INDEX CONCURRENTLY? ((IF NOT EXISTS)? indexName)? ON tableName indexType? keyParts withStorageParameters? tableSpaceClause? whereClause? ; alterIndex: (alterIndexName(renameIndex | setTableSpace | setStorageParameter | resetStorageParameter)) | alterIndexDependsOnExtension | alterIndexSetTableSpace ; dropIndex: DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA indexName)* (CASCADE | RESTRICT) ; indexType: USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN) ; keyParts: LEFT_PAREN keyPart (COMMA keyPart)* RIGHT_PAREN ; keyPart: (columnName | simpleExpr | LEFT_PAREN simpleExpr RIGHT_PAREN) collateClause? opclass? (ASC | DESC)? (NULLS (FIRST | LAST))? ; simpleExpr: | functionCall | liter | ID ; alterIndexName: ALTER INDEX (IF EXISTS)? indexName ; renameIndex: RENAME TO indexName ; setTableSpace: SET TABLESPACE tablespaceName ; setStorageParameter: SET LEFT_PAREN storageParameters RIGHT_PAREN ; resetStorageParameter: RESET LEFT_PAREN storageParameters RIGHT_PAREN ; alterIndexDependsOnExtension: ALTER INDEX indexName DEPENDS ON EXTENSION extensionName ; alterIndexSetTableSpace: ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY rowNames)? SET TABLESPACE tablespaceName (NOWAIT)? ; rowNames: rowName (COMMA rowName)* ; rowName: ID ; whereClause: WHERE expr ; createTable: createBasicTable |createTypeTable |createTableForPartition ; createBasicTable: createTableHeader createDefinitions inheritClause? partitionClause? tableWithClause? commitClause? tableSpaceClause? ; createTableHeader: CREATE ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? TABLE (IF NOT EXISTS)? tableName ; createDefinitions: LEFT_PAREN (createDefinition (COMMA createDefinition)*)? RIGHT_PAREN ; createDefinition: (columnName dataType collateClause? columnConstraint*) | tableConstraint | LIKE tableName likeOption* ; inheritClause: INHERITS LEFT_PAREN tableName (COMMA tableName)* RIGHT_PAREN ; partitionClause: PARTITION BY (RANGE | LIST) LEFT_PAREN partitionClauseParam (COMMA partitionClauseParam)* RIGHT_PAREN ; partitionClauseParam: (columnName | LEFT_PAREN simpleExpr RIGHT_PAREN) collateClause? opclass? ; tableWithClause: withStorageParameters |(WITH OIDS) |(WITHOUT OIDS) ; commitClause: ON COMMIT (PRESERVE ROWS | DELETE ROWS | DROP) ; tableSpaceClause: TABLESPACE tablespaceName ; createTypeTable: createTableHeader typeNameClause createDefinition1s? partitionClause? tableWithClause? commitClause? tableSpaceClause? ; typeNameClause: OF typeName ; createDefinition1s: LEFT_PAREN createDefinition1 (COMMA createDefinition1)* RIGHT_PAREN ; createDefinition1: (columnName (WITH OPTIONS )? columnConstraint*) | tableConstraint ; createTableForPartition: createTableHeader partitionOfParent createDefinition1s? forValuesParition partitionClause? tableWithClause? commitClause? tableSpaceClause? ; partitionOfParent: PARTITION OF tableName ; forValuesParition: FOR VALUES partitionBoundSpec ; partitionBoundSpec: (IN inValueOption) |(FROM fromValueOption TO fromValueOption) ; inValueOption: LEFT_PAREN inValue (COMMA inValue)* RIGHT_PAREN ; inValue: NUMBER |STRING |TRUE |FALSE |NULL ; fromValue: inValue |MINVALUE |MAXVALUE ; fromValueOption: LEFT_PAREN fromValue (COMMA fromValue)* RIGHT_PAREN ; createTableOptions: ; dataType: basicDataType (LEFT_BRACKET RIGHT_BRACKET)* ; basicDataType: BIGINT |INT8 |BIGSERIAL |SERIAL8 |BIT VARYING? numericPrecision? |VARBIT numericPrecision? |BOOLEAN |BOOL // |BOX |BYTEA |((CHARACTER VARYING?) | CHAR | VARCHAR) numericPrecision? |CIDR |CIRCLE |DATE |DOUBLE PRECISION |FLOAT8 |(INTEGER | INT4 | INT) |intervalType |JSON |JSONB |LINE |LSEG |MACADDR |MACADDR8 |MONEY |NUMERIC numericPrecision |DECIMAL numericPrecision? |PATH |PG_LSN |POINT |POLYGON |REAL |FLOAT4 |SMALLINT |INT2 |SERIAL |SERIAL4 |FLOAT numericPrecision? |TEXT |(TIME | TIMESTAMP) numericPrecision?((WITHOUT TIME ZONE)? | (WITH TIME ZONE)) |TSQUERY |TSVECTOR |TXID_SNAPSHOT |UUID |XML ; intervalType: INTERVAL intervalFields? numericPrecision? ; intervalFields: intervalField (TO intervalField)? ; intervalField: YEAR |MONTH |DAY |HOUR |MINUTE |SECOND ; numericPrecision: LEFT_PAREN NUMBER (COMMA NUMBER)? RIGHT_PAREN ; defaultExpr: CURRENT_TIMESTAMP |expr; collateClause: COLLATE collationName ; columnConstraint: constraintClause? columnConstraintOption constraintOptionalParam ; columnConstraintOption: (NOT NULL) |NULL |checkOption |(DEFAULT defaultExpr) |(GENERATED ( ALWAYS | BY DEFAULT ) AS IDENTITY ( LEFT_PAREN sequenceOptions RIGHT_PAREN )?) |(UNIQUE indexParameters) |(PRIMARY KEY indexParameters) |(REFERENCES tableName (LEFT_PAREN columnName RIGHT_PAREN)? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)?(ON DELETE action )? (ON UPDATE action )?) ; checkOption: CHECK expr (NO INHERIT )? ; action: (NO ACTION) |RESTRICT |CASCADE |(SET NULL) |(SET DEFAULT) ; sequenceOptions: sequenceOption (START WITH? NUMBER)? (CACHE NUMBER)? (NO? CYCLE)? ; sequenceOption: (INCREMENT BY? NUMBER)? (MINVALUE NUMBER | NO MINVALUE)? (MAXVALUE NUMBER | NO MAXVALUE)? ; likeOption: (INCLUDING | EXCLUDING ) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint: constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption: checkOption |(UNIQUE columnList indexParameters) |(PRIMARY KEY columnList indexParameters) |(EXCLUDE (USING extensionName)? LEFT_PAREN excludeParam (COMMA excludeParam)* RIGHT_PAREN indexParameters (WHERE ( predicate ))?) |(FOREIGN KEY columnList REFERENCES tableName columnList (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON DELETE action )? (ON UPDATE action)?) ; indexParameters: withStorageParameters? (USING INDEX TABLESPACE tablespaceName)? ; extensionName: ID ; excludeParam: excludeElement WITH operator ; excludeElement: (columnName | expr) opclass? (ASC | DESC)? (NULLS (FIRST | LAST))? ; operator: SAFE_EQ |EQ_OR_ASSIGN |NEQ |NEQ_SYM |GT |GTE |LT |LTE |AND_SYM |OR_SYM |NOT_SYM ; typeName:ID; constraintName:ID; constraintClause: CONSTRAINT constraintName ; withStorageParameters: WITH LEFT_PAREN storageParameters RIGHT_PAREN ; storageParameters: storageParameterWithValue (COMMA storageParameterWithValue)* ; storageParameterWithValue: storageParameter EQ_OR_ASSIGN simpleExpr ; storageParameter: ID ; opclass: ID ; alterTable: (alterTableNameWithAsterisk(alterTableActions| renameColumn | renameConstraint)) |(alterTableNameExists(renameTable | setSchema |attachTableSpace |detachTableSpace)) |alterTableSetTableSpace ; alterTableOp: ALTER TABLE ; alterTableActions: alterTableAction (COMMA alterTableAction)* ; renameColumn: RENAME COLUMN? columnName TO columnName ; renameConstraint: RENAME CONSTRAINT constraintName TO constraintName ; renameTable: RENAME TO tableName ; setSchema: SET SCHEMA schemaName ; alterTableSetTableSpace: alterTableOp ALL IN TABLESPACE tablespaceName (OWNED BY roleName (COMMA roleName)* )? SET TABLESPACE tablespaceName NOWAIT? ; attachTableSpace: ATTACH PARTITION partitionName forValuesParition ; detachTableSpace: DETACH PARTITION partitionName ; alterTableNameWithAsterisk: alterTableOp (IF EXISTS)? ONLY? tableName ASTERISK? ; alterTableNameExists: alterTableOp (IF EXISTS)? tableName ; alterTableAction: (ADD COLUMN? (IF NOT EXISTS )? columnName dataType collateClause? (columnConstraint columnConstraint*)?) |(DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)?) |(alterColumnOp columnName (SET DATA)? TYPE dataType collateClause? (USING expr)?) |(alterColumnOp columnName SET DEFAULT expr) |(alterColumnOp columnName DROP DEFAULT) |(alterColumnOp columnName (SET | DROP) NOT NULL) |(alterColumnOp columnName ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LEFT_PAREN sequenceOptions RIGHT_PAREN)?) |(alterColumnOp columnName alterColumnSetOption alterColumnSetOption*) |(alterColumnOp columnName DROP IDENTITY (IF EXISTS)?) |(alterColumnOp columnName SET STATISTICS NUMBER) |(alterColumnOp columnName SET LEFT_PAREN attributeOptions RIGHT_PAREN) |(alterColumnOp columnName RESET LEFT_PAREN attributeOptions RIGHT_PAREN) |(alterColumnOp columnName SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN)) |(ADD tableConstraint (NOT VALID)?) |(ADD tableConstraintUsingIndex) |(ALTER CONSTRAINT constraintName constraintOptionalParam) |(VALIDATE CONSTRAINT constraintName) |(DROP CONSTRAINT (IF EXISTS)? constraintName (RESTRICT | CASCADE)?) |((DISABLE |ENABLE) TRIGGER (triggerName | ALL | USER )?) |(ENABLE (REPLICA | ALWAYS) TRIGGER triggerName) |((DISABLE | ENABLE) RULE rewriteRuleName) |(ENABLE (REPLICA | ALWAYS) RULE rewriteRuleName) |((DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY) |(CLUSTER ON indexName) |(SET WITHOUT CLUSTER) |(SET (WITH | WITHOUT) OIDS) |(SET TABLESPACE tablespaceName) |(SET (LOGGED | UNLOGGED)) |(SET LEFT_PAREN storageParameterWithValue (COMMA storageParameterWithValue)* RIGHT_PAREN) |(RESET LEFT_PAREN storageParameter (COMMA storageParameter)* RIGHT_PAREN) |(INHERIT tableName) |(NO INHERIT tableName) |(OF typeName) |(NOT OF) |(OWNER TO (ownerName | CURRENT_USER | SESSION_USER)) |(REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING)) ; alterColumnOp: ALTER COLUMN? ; alterColumnSetOption: (SET GENERATED (ALWAYS | BY DEFAULT)) |SET sequenceOption |(RESTART (WITH? NUMBER)?) ; attributeOptions: attributeOption (COMMA attributeOption)* ; //options:n_distinct and n_distinct_inherited, loosen match attributeOption: ID EQ_OR_ASSIGN simpleExpr ; tableConstraintUsingIndex: (CONSTRAINT constraintName)? (UNIQUE | PRIMARY KEY) USING INDEX indexName constraintOptionalParam ; constraintOptionalParam: (NOT? DEFERRABLE)? (INITIALLY (DEFERRED |IMMEDIATE))? ; privateExprOfDb: aggregateExpression |windowFunction |arrayConstructorWithCast |(TIMESTAMP (WITH TIME ZONE)? STRING) ; pgExpr: |castExpr |collateExpr |expr ; aggregateExpression: ID ( (LEFT_PAREN (ALL | DISTINCT)? exprs orderByClause? RIGHT_PAREN) |asteriskWithParen | (LEFT_PAREN exprs RIGHT_PAREN WITHIN GROUP LEFT_PAREN orderByClause RIGHT_PAREN) ) filterClause ? ; filterClause: FILTER LEFT_PAREN WHERE booleanPrimary RIGHT_PAREN ; asteriskWithParen: LEFT_PAREN ASTERISK RIGHT_PAREN ; windowFunction: ID (exprsWithParen | asteriskWithParen) filterClause? windowFunctionWithClause ; windowFunctionWithClause: OVER (ID | LEFT_PAREN windowDefinition RIGHT_PAREN ) ; windowDefinition: ID? (PARTITION BY exprs)? (orderByExpr (COMMA orderByExpr)*)? frameClause? ; orderByExpr: ORDER BY expr (ASC | DESC | USING operator)? (NULLS (FIRST | LAST ))? ; frameClause: ((RANGE | ROWS) frameStart) |(RANGE | ROWS ) BETWEEN frameStart AND frameEnd ; frameStart: (UNBOUNDED PRECEDING) |(NUMBER PRECEDING) |(CURRENT ROW) |(NUMBER FOLLOWING) |(UNBOUNDED FOLLOWING) ; frameEnd: frameStart ; castExpr: (CAST LEFT_PAREN expr AS dataType RIGHT_PAREN) |(expr COLON COLON dataType) ; castExprWithColon: COLON COLON dataType(LEFT_BRACKET RIGHT_BRACKET)* ; collateExpr: expr COLLATE expr ; arrayConstructorWithCast: arrayConstructor castExprWithColon? |(ARRAY LEFT_BRACKET RIGHT_BRACKET castExprWithColon) ; arrayConstructor: | ARRAY LEFT_BRACKET exprs RIGHT_BRACKET | ARRAY LEFT_BRACKET arrayConstructor (COMMA arrayConstructor)* RIGHT_BRACKET ;
grammar PostgreDDL; import PostgreKeyword, DataType, Keyword,BaseRule,Symbol; createIndex: CREATE UNIQUE? INDEX CONCURRENTLY? ((IF NOT EXISTS)? indexName)? ON tableName indexType? keyParts withStorageParameters? tableSpaceClause? whereClause? ; alterIndex: (alterIndexName(renameIndex | setTableSpace | setStorageParameter | resetStorageParameter)) | alterIndexDependsOnExtension | alterIndexSetTableSpace ; dropIndex: DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA indexName)* (CASCADE | RESTRICT) ; indexType: USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN) ; keyParts: LEFT_PAREN keyPart (COMMA keyPart)* RIGHT_PAREN ; keyPart: (columnName | simpleExpr | LEFT_PAREN simpleExpr RIGHT_PAREN) collateClause? opclass? (ASC | DESC)? (NULLS (FIRST | LAST))? ; simpleExpr: | functionCall | liter | ID ; alterIndexName: ALTER INDEX (IF EXISTS)? indexName ; renameIndex: RENAME TO indexName ; setTableSpace: SET TABLESPACE tablespaceName ; setStorageParameter: SET storageParametersWithParen ; resetStorageParameter: RESET storageParametersWithParen ; storageParametersWithParen: LEFT_PAREN storageParameters RIGHT_PAREN ; alterIndexDependsOnExtension: ALTER INDEX indexName DEPENDS ON EXTENSION extensionName ; alterIndexSetTableSpace: ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY rowNames)? SET TABLESPACE tablespaceName (NOWAIT)? ; rowNames: rowName (COMMA rowName)* ; rowName: ID ; whereClause: WHERE expr ; createTable: createBasicTable |createTypeTable |createTableForPartition ; createBasicTable: createTableHeader createDefinitions inheritClause? partitionClause? tableWithClause? commitClause? tableSpaceClause? ; createTableHeader: CREATE ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? TABLE (IF NOT EXISTS)? tableName ; createDefinitions: LEFT_PAREN (createDefinition (COMMA createDefinition)*)? RIGHT_PAREN ; createDefinition: (columnName dataType collateClause? columnConstraint*) | tableConstraint | LIKE tableName likeOption* ; inheritClause: INHERITS LEFT_PAREN tableName (COMMA tableName)* RIGHT_PAREN ; partitionClause: PARTITION BY (RANGE | LIST) LEFT_PAREN partitionClauseParam (COMMA partitionClauseParam)* RIGHT_PAREN ; partitionClauseParam: (columnName | LEFT_PAREN simpleExpr RIGHT_PAREN) collateClause? opclass? ; tableWithClause: withStorageParameters |(WITH OIDS) |(WITHOUT OIDS) ; commitClause: ON COMMIT (PRESERVE ROWS | DELETE ROWS | DROP) ; tableSpaceClause: TABLESPACE tablespaceName ; createTypeTable: createTableHeader typeNameClause createDefinition1s? partitionClause? tableWithClause? commitClause? tableSpaceClause? ; typeNameClause: OF typeName ; createDefinition1s: LEFT_PAREN createDefinition1 (COMMA createDefinition1)* RIGHT_PAREN ; createDefinition1: (columnName (WITH OPTIONS )? columnConstraint*) | tableConstraint ; createTableForPartition: createTableHeader partitionOfParent createDefinition1s? forValuesParition partitionClause? tableWithClause? commitClause? tableSpaceClause? ; partitionOfParent: PARTITION OF tableName ; forValuesParition: FOR VALUES partitionBoundSpec ; partitionBoundSpec: (IN inValueOption) |(FROM fromValueOption TO fromValueOption) ; inValueOption: LEFT_PAREN inValue (COMMA inValue)* RIGHT_PAREN ; inValue: NUMBER |STRING |TRUE |FALSE |NULL ; fromValue: inValue |MINVALUE |MAXVALUE ; fromValueOption: LEFT_PAREN fromValue (COMMA fromValue)* RIGHT_PAREN ; createTableOptions: ; dataType: basicDataType (LEFT_BRACKET RIGHT_BRACKET)* ; basicDataType: BIGINT |INT8 |BIGSERIAL |SERIAL8 |BIT VARYING? numericPrecision? |VARBIT numericPrecision? |BOOLEAN |BOOL // |BOX |BYTEA |((CHARACTER VARYING?) | CHAR | VARCHAR) numericPrecision? |CIDR |CIRCLE |DATE |DOUBLE PRECISION |FLOAT8 |(INTEGER | INT4 | INT) |intervalType |JSON |JSONB |LINE |LSEG |MACADDR |MACADDR8 |MONEY |NUMERIC numericPrecision |DECIMAL numericPrecision? |PATH |PG_LSN |POINT |POLYGON |REAL |FLOAT4 |SMALLINT |INT2 |SERIAL |SERIAL4 |FLOAT numericPrecision? |TEXT |(TIME | TIMESTAMP) numericPrecision?((WITHOUT TIME ZONE)? | (WITH TIME ZONE)) |TSQUERY |TSVECTOR |TXID_SNAPSHOT |UUID |XML ; intervalType: INTERVAL intervalFields? numericPrecision? ; intervalFields: intervalField (TO intervalField)? ; intervalField: YEAR |MONTH |DAY |HOUR |MINUTE |SECOND ; numericPrecision: LEFT_PAREN NUMBER (COMMA NUMBER)? RIGHT_PAREN ; defaultExpr: CURRENT_TIMESTAMP |expr; collateClause: COLLATE collationName ; columnConstraint: constraintClause? columnConstraintOption constraintOptionalParam ; columnConstraintOption: (NOT NULL) |NULL |checkOption |(DEFAULT defaultExpr) |(GENERATED ( ALWAYS | BY DEFAULT ) AS IDENTITY ( LEFT_PAREN sequenceOptions RIGHT_PAREN )?) |(UNIQUE indexParameters) |(PRIMARY KEY indexParameters) |(REFERENCES tableName (LEFT_PAREN columnName RIGHT_PAREN)? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)?(ON DELETE action )? (ON UPDATE action )?) ; checkOption: CHECK expr (NO INHERIT )? ; action: (NO ACTION) |RESTRICT |CASCADE |(SET NULL) |(SET DEFAULT) ; sequenceOptions: sequenceOption (START WITH? NUMBER)? (CACHE NUMBER)? (NO? CYCLE)? ; sequenceOption: (INCREMENT BY? NUMBER)? (MINVALUE NUMBER | NO MINVALUE)? (MAXVALUE NUMBER | NO MAXVALUE)? ; likeOption: (INCLUDING | EXCLUDING ) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint: constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption: checkOption |(UNIQUE columnList indexParameters) |(PRIMARY KEY columnList indexParameters) |(EXCLUDE (USING extensionName)? LEFT_PAREN excludeParam (COMMA excludeParam)* RIGHT_PAREN indexParameters (WHERE ( predicate ))?) |(FOREIGN KEY columnList REFERENCES tableName columnList (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON DELETE action )? (ON UPDATE action)?) ; indexParameters: withStorageParameters? (USING INDEX TABLESPACE tablespaceName)? ; extensionName: ID ; excludeParam: excludeElement WITH operator ; excludeElement: (columnName | expr) opclass? (ASC | DESC)? (NULLS (FIRST | LAST))? ; operator: SAFE_EQ |EQ_OR_ASSIGN |NEQ |NEQ_SYM |GT |GTE |LT |LTE |AND_SYM |OR_SYM |NOT_SYM ; typeName:ID; constraintName:ID; constraintClause: CONSTRAINT constraintName ; withStorageParameters: WITH storageParametersWithParen ; storageParameters: storageParameterWithValue (COMMA storageParameterWithValue)* ; storageParameterWithValue: storageParameter EQ_OR_ASSIGN simpleExpr ; storageParameter: ID ; opclass: ID ; alterTable: (alterTableNameWithAsterisk(alterTableActions| renameColumn | renameConstraint)) |(alterTableNameExists(renameTable | setSchema |attachTableSpace |detachTableSpace)) |alterTableSetTableSpace ; alterTableOp: ALTER TABLE ; alterTableActions: alterTableAction (COMMA alterTableAction)* ; renameColumn: RENAME COLUMN? columnName TO columnName ; renameConstraint: RENAME CONSTRAINT constraintName TO constraintName ; renameTable: RENAME TO tableName ; setSchema: SET SCHEMA schemaName ; alterTableSetTableSpace: alterTableOp ALL IN TABLESPACE tablespaceName (OWNED BY roleName (COMMA roleName)* )? SET TABLESPACE tablespaceName NOWAIT? ; attachTableSpace: ATTACH PARTITION partitionName forValuesParition ; detachTableSpace: DETACH PARTITION partitionName ; alterTableNameWithAsterisk: alterTableOp (IF EXISTS)? ONLY? tableName ASTERISK? ; alterTableNameExists: alterTableOp (IF EXISTS)? tableName ; alterTableAction: (ADD COLUMN? (IF NOT EXISTS )? columnName dataType collateClause? (columnConstraint columnConstraint*)?) |(DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)?) |(alterColumnOp columnName (SET DATA)? TYPE dataType collateClause? (USING expr)?) |(alterColumnOp columnName SET DEFAULT expr) |(alterColumnOp columnName DROP DEFAULT) |(alterColumnOp columnName (SET | DROP) NOT NULL) |(alterColumnOp columnName ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LEFT_PAREN sequenceOptions RIGHT_PAREN)?) |(alterColumnOp columnName alterColumnSetOption alterColumnSetOption*) |(alterColumnOp columnName DROP IDENTITY (IF EXISTS)?) |(alterColumnOp columnName SET STATISTICS NUMBER) |(alterColumnOp columnName SET LEFT_PAREN attributeOptions RIGHT_PAREN) |(alterColumnOp columnName RESET LEFT_PAREN attributeOptions RIGHT_PAREN) |(alterColumnOp columnName SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN)) |(ADD tableConstraint (NOT VALID)?) |(ADD tableConstraintUsingIndex) |(ALTER CONSTRAINT constraintName constraintOptionalParam) |(VALIDATE CONSTRAINT constraintName) |(DROP CONSTRAINT (IF EXISTS)? constraintName (RESTRICT | CASCADE)?) |((DISABLE |ENABLE) TRIGGER (triggerName | ALL | USER )?) |(ENABLE (REPLICA | ALWAYS) TRIGGER triggerName) |((DISABLE | ENABLE) RULE rewriteRuleName) |(ENABLE (REPLICA | ALWAYS) RULE rewriteRuleName) |((DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY) |(CLUSTER ON indexName) |(SET WITHOUT CLUSTER) |(SET (WITH | WITHOUT) OIDS) |(SET TABLESPACE tablespaceName) |(SET (LOGGED | UNLOGGED)) |(SET LEFT_PAREN storageParameterWithValue (COMMA storageParameterWithValue)* RIGHT_PAREN) |(RESET LEFT_PAREN storageParameter (COMMA storageParameter)* RIGHT_PAREN) |(INHERIT tableName) |(NO INHERIT tableName) |(OF typeName) |(NOT OF) |(OWNER TO (ownerName | CURRENT_USER | SESSION_USER)) |(REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING)) ; alterColumnOp: ALTER COLUMN? ; alterColumnSetOption: (SET GENERATED (ALWAYS | BY DEFAULT)) |SET sequenceOption |(RESTART (WITH? NUMBER)?) ; attributeOptions: attributeOption (COMMA attributeOption)* ; //options:n_distinct and n_distinct_inherited, loosen match attributeOption: ID EQ_OR_ASSIGN simpleExpr ; tableConstraintUsingIndex: (CONSTRAINT constraintName)? (UNIQUE | PRIMARY KEY) USING INDEX indexName constraintOptionalParam ; constraintOptionalParam: (NOT? DEFERRABLE)? (INITIALLY (DEFERRED |IMMEDIATE))? ; privateExprOfDb: aggregateExpression |windowFunction |arrayConstructorWithCast |(TIMESTAMP (WITH TIME ZONE)? STRING) ; pgExpr: |castExpr |collateExpr |expr ; aggregateExpression: ID ( (LEFT_PAREN (ALL | DISTINCT)? exprs orderByClause? RIGHT_PAREN) |asteriskWithParen | (LEFT_PAREN exprs RIGHT_PAREN WITHIN GROUP LEFT_PAREN orderByClause RIGHT_PAREN) ) filterClause ? ; filterClause: FILTER LEFT_PAREN WHERE booleanPrimary RIGHT_PAREN ; asteriskWithParen: LEFT_PAREN ASTERISK RIGHT_PAREN ; windowFunction: ID (exprsWithParen | asteriskWithParen) filterClause? windowFunctionWithClause ; windowFunctionWithClause: OVER (ID | LEFT_PAREN windowDefinition RIGHT_PAREN ) ; windowDefinition: ID? (PARTITION BY exprs)? (orderByExpr (COMMA orderByExpr)*)? frameClause? ; orderByExpr: ORDER BY expr (ASC | DESC | USING operator)? (NULLS (FIRST | LAST ))? ; frameClause: ((RANGE | ROWS) frameStart) |(RANGE | ROWS ) BETWEEN frameStart AND frameEnd ; frameStart: (UNBOUNDED PRECEDING) |(NUMBER PRECEDING) |(CURRENT ROW) |(NUMBER FOLLOWING) |(UNBOUNDED FOLLOWING) ; frameEnd: frameStart ; castExpr: (CAST LEFT_PAREN expr AS dataType RIGHT_PAREN) |(expr COLON COLON dataType) ; castExprWithColon: COLON COLON dataType(LEFT_BRACKET RIGHT_BRACKET)* ; collateExpr: expr COLLATE expr ; arrayConstructorWithCast: arrayConstructor castExprWithColon? |(ARRAY LEFT_BRACKET RIGHT_BRACKET castExprWithColon) ; arrayConstructor: | ARRAY LEFT_BRACKET exprs RIGHT_BRACKET | ARRAY LEFT_BRACKET arrayConstructor (COMMA arrayConstructor)* RIGHT_BRACKET ;
add storageParametersWithParen rule
add storageParametersWithParen rule add storageParametersWithParen rule
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
6f54b4b6228b4eb7d7c39fefae0c273e4f4be1ec
Solidity.g4
Solidity.g4
// Copyright 2016-2017 Federico Bond <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. grammar Solidity; sourceUnit : (pragmaDirective | importDirective | contractDefinition)* EOF ; pragmaDirective : 'pragma' pragmaName pragmaValue ';' ; pragmaName : identifier ; pragmaValue : version | expression ; version : versionConstraint versionConstraint? ; versionOperator : '^' | '~' | '>=' | '>' | '<' | '<=' | '=' ; versionConstraint : versionOperator? VersionLiteral ; importDeclaration : identifier ('as' identifier)? ; importDirective : 'import' StringLiteral ('as' identifier)? ';' | 'import' ('*' | identifier) ('as' identifier)? 'from' StringLiteral ';' | 'import' '{' importDeclaration ( ',' importDeclaration )* '}' 'from' StringLiteral ';' ; contractDefinition : ( 'contract' | 'interface' | 'library' ) identifier ( 'is' inheritanceSpecifier (',' inheritanceSpecifier )* )? '{' contractPart* '}' ; inheritanceSpecifier : userDefinedTypeName ( '(' expression ( ',' expression )* ')' )? ; contractPart : stateVariableDeclaration | usingForDeclaration | structDefinition | constructorDefinition | modifierDefinition | functionDefinition | eventDefinition | enumDefinition ; stateVariableDeclaration : typeName ( PublicKeyword | InternalKeyword | PrivateKeyword | ConstantKeyword )* identifier ('=' expression)? ';' ; usingForDeclaration : 'using' identifier 'for' ('*' | typeName) ';' ; structDefinition : 'struct' identifier '{' ( variableDeclaration ';' (variableDeclaration ';')* )? '}' ; constructorDefinition : 'constructor' parameterList modifierList block ; modifierDefinition : 'modifier' identifier parameterList? block ; modifierInvocation : identifier ( '(' expressionList? ')' )? ; functionDefinition : 'function' identifier? parameterList modifierList returnParameters? ( ';' | block ) ; returnParameters : 'returns' parameterList ; modifierList : ( modifierInvocation | stateMutability | ExternalKeyword | PublicKeyword | InternalKeyword | PrivateKeyword )* ; eventDefinition : 'event' identifier eventParameterList AnonymousKeyword? ';' ; enumValue : identifier ; enumDefinition : 'enum' identifier '{' enumValue? (',' enumValue)* '}' ; parameterList : '(' ( parameter (',' parameter)* )? ')' ; parameter : typeName storageLocation? identifier? ; eventParameterList : '(' ( eventParameter (',' eventParameter)* )? ')' ; eventParameter : typeName IndexedKeyword? identifier? ; functionTypeParameterList : '(' ( functionTypeParameter (',' functionTypeParameter)* )? ')' ; functionTypeParameter : typeName storageLocation? ; variableDeclaration : typeName storageLocation? identifier ; typeName : elementaryTypeName | userDefinedTypeName | mapping | typeName '[' expression? ']' | functionTypeName | 'address' 'payable' ; userDefinedTypeName : identifier ( '.' identifier )* ; mapping : 'mapping' '(' elementaryTypeName '=>' typeName ')' ; functionTypeName : 'function' functionTypeParameterList ( InternalKeyword | ExternalKeyword | stateMutability )* ( 'returns' functionTypeParameterList )? ; storageLocation : 'memory' | 'storage' | 'calldata'; stateMutability : PureKeyword | ConstantKeyword | ViewKeyword | PayableKeyword ; block : '{' statement* '}' ; statement : ifStatement | whileStatement | forStatement | block | inlineAssemblyStatement | doWhileStatement | continueStatement | breakStatement | returnStatement | throwStatement | emitStatement | simpleStatement ; expressionStatement : expression ';' ; ifStatement : 'if' '(' expression ')' statement ( 'else' statement )? ; whileStatement : 'while' '(' expression ')' statement ; simpleStatement : ( variableDeclarationStatement | expressionStatement ) ; forStatement : 'for' '(' ( simpleStatement | ';' ) ( expressionStatement | ';' ) expression? ')' statement ; inlineAssemblyStatement : 'assembly' StringLiteral? assemblyBlock ; doWhileStatement : 'do' statement 'while' '(' expression ')' ';' ; continueStatement : 'continue' ';' ; breakStatement : 'break' ';' ; returnStatement : 'return' expression? ';' ; throwStatement : 'throw' ';' ; emitStatement : 'emit' functionCall ';' ; variableDeclarationStatement : ( 'var' identifierList | variableDeclaration | '(' variableDeclarationList ')' ) ( '=' expression )? ';'; variableDeclarationList : variableDeclaration? (',' variableDeclaration? )* ; identifierList : '(' ( identifier? ',' )* identifier? ')' ; elementaryTypeName : 'address' | 'bool' | 'string' | 'var' | Int | Uint | 'byte' | Byte | Fixed | Ufixed ; Int : 'int' | 'int8' | 'int16' | 'int24' | 'int32' | 'int40' | 'int48' | 'int56' | 'int64' | 'int72' | 'int80' | 'int88' | 'int96' | 'int104' | 'int112' | 'int120' | 'int128' | 'int136' | 'int144' | 'int152' | 'int160' | 'int168' | 'int176' | 'int184' | 'int192' | 'int200' | 'int208' | 'int216' | 'int224' | 'int232' | 'int240' | 'int248' | 'int256' ; Uint : 'uint' | 'uint8' | 'uint16' | 'uint24' | 'uint32' | 'uint40' | 'uint48' | 'uint56' | 'uint64' | 'uint72' | 'uint80' | 'uint88' | 'uint96' | 'uint104' | 'uint112' | 'uint120' | 'uint128' | 'uint136' | 'uint144' | 'uint152' | 'uint160' | 'uint168' | 'uint176' | 'uint184' | 'uint192' | 'uint200' | 'uint208' | 'uint216' | 'uint224' | 'uint232' | 'uint240' | 'uint248' | 'uint256' ; Byte : 'bytes' | 'bytes1' | 'bytes2' | 'bytes3' | 'bytes4' | 'bytes5' | 'bytes6' | 'bytes7' | 'bytes8' | 'bytes9' | 'bytes10' | 'bytes11' | 'bytes12' | 'bytes13' | 'bytes14' | 'bytes15' | 'bytes16' | 'bytes17' | 'bytes18' | 'bytes19' | 'bytes20' | 'bytes21' | 'bytes22' | 'bytes23' | 'bytes24' | 'bytes25' | 'bytes26' | 'bytes27' | 'bytes28' | 'bytes29' | 'bytes30' | 'bytes31' | 'bytes32' ; Fixed : 'fixed' | ( 'fixed' [0-9]+ 'x' [0-9]+ ) ; Ufixed : 'ufixed' | ( 'ufixed' [0-9]+ 'x' [0-9]+ ) ; expression : expression ('++' | '--') | 'new' typeName | expression '[' expression ']' | expression '(' functionCallArguments ')' | expression '.' identifier | '(' expression ')' | ('++' | '--') expression | ('+' | '-') expression | ('after' | 'delete') expression | '!' expression | '~' expression | expression '**' expression | expression ('*' | '/' | '%') expression | expression ('+' | '-') expression | expression ('<<' | '>>') expression | expression '&' expression | expression '^' expression | expression '|' expression | expression ('<' | '>' | '<=' | '>=') expression | expression ('==' | '!=') expression | expression '&&' expression | expression '||' expression | expression '?' expression ':' expression | expression ('=' | '|=' | '^=' | '&=' | '<<=' | '>>=' | '+=' | '-=' | '*=' | '/=' | '%=') expression | primaryExpression ; primaryExpression : BooleanLiteral | numberLiteral | HexLiteral | StringLiteral | identifier | tupleExpression | elementaryTypeNameExpression ; expressionList : expression (',' expression)* ; nameValueList : nameValue (',' nameValue)* ','? ; nameValue : identifier ':' expression ; functionCallArguments : '{' nameValueList? '}' | expressionList? ; functionCall : expression '(' functionCallArguments ')' ; assemblyBlock : '{' assemblyItem* '}' ; assemblyItem : identifier | assemblyBlock | assemblyExpression | assemblyLocalDefinition | assemblyAssignment | assemblyStackAssignment | labelDefinition | assemblySwitch | assemblyFunctionDefinition | assemblyFor | assemblyIf | BreakKeyword | ContinueKeyword | subAssembly | numberLiteral | StringLiteral | HexLiteral ; assemblyExpression : assemblyCall | assemblyLiteral ; assemblyCall : ( 'return' | 'address' | 'byte' | identifier ) ( '(' assemblyExpression? ( ',' assemblyExpression )* ')' )? ; assemblyLocalDefinition : 'let' assemblyIdentifierOrList ( ':=' assemblyExpression )? ; assemblyAssignment : assemblyIdentifierOrList ':=' assemblyExpression ; assemblyIdentifierOrList : identifier | '(' assemblyIdentifierList ')' ; assemblyIdentifierList : identifier ( ',' identifier )* ; assemblyStackAssignment : '=:' identifier ; labelDefinition : identifier ':' ; assemblySwitch : 'switch' assemblyExpression assemblyCase* ; assemblyCase : 'case' assemblyLiteral assemblyBlock | 'default' assemblyBlock ; assemblyFunctionDefinition : 'function' identifier '(' assemblyIdentifierList? ')' assemblyFunctionReturns? assemblyBlock ; assemblyFunctionReturns : ( '->' assemblyIdentifierList ) ; assemblyFor : 'for' ( assemblyBlock | assemblyExpression ) assemblyExpression ( assemblyBlock | assemblyExpression ) assemblyBlock ; assemblyIf : 'if' assemblyExpression assemblyBlock ; assemblyLiteral : StringLiteral | DecimalNumber | HexNumber | HexLiteral ; subAssembly : 'assembly' identifier assemblyBlock ; tupleExpression : '(' ( expression? ( ',' expression? )* ) ')' | '[' ( expression ( ',' expression )* )? ']' ; elementaryTypeNameExpression : elementaryTypeName ; numberLiteral : (DecimalNumber | HexNumber) NumberUnit? ; identifier : ('from' | 'calldata' | Identifier) ; VersionLiteral : [0-9]+ '.' [0-9]+ '.' [0-9]+ ; BooleanLiteral : 'true' | 'false' ; DecimalNumber : ([0-9]+ | ([0-9]* '.' [0-9]+) ) ( [eE] [0-9]+ )? ; HexNumber : '0' [xX] HexCharacter+ ; NumberUnit : 'wei' | 'szabo' | 'finney' | 'ether' | 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'years' ; HexLiteral : 'hex' ('"' HexPair* '"' | '\'' HexPair* '\'') ; fragment HexPair : HexCharacter HexCharacter ; fragment HexCharacter : [0-9A-Fa-f] ; ReservedKeyword : 'abstract' | 'after' | 'case' | 'catch' | 'default' | 'final' | 'in' | 'inline' | 'let' | 'match' | 'null' | 'of' | 'relocatable' | 'static' | 'switch' | 'try' | 'type' | 'typeof' ; AnonymousKeyword : 'anonymous' ; BreakKeyword : 'break' ; ConstantKeyword : 'constant' ; ContinueKeyword : 'continue' ; ExternalKeyword : 'external' ; IndexedKeyword : 'indexed' ; InternalKeyword : 'internal' ; PayableKeyword : 'payable' ; PrivateKeyword : 'private' ; PublicKeyword : 'public' ; PureKeyword : 'pure' ; ViewKeyword : 'view' ; Identifier : IdentifierStart IdentifierPart* ; fragment IdentifierStart : [a-zA-Z$_] ; fragment IdentifierPart : [a-zA-Z0-9$_] ; StringLiteral : '"' DoubleQuotedStringCharacter* '"' | '\'' SingleQuotedStringCharacter* '\'' ; fragment DoubleQuotedStringCharacter : ~["\r\n\\] | ('\\' .) ; fragment SingleQuotedStringCharacter : ~['\r\n\\] | ('\\' .) ; WS : [ \t\r\n\u000C]+ -> skip ; COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ;
// Copyright 2016-2019 Federico Bond <[email protected]> // Licensed under the MIT license. See LICENSE file in the project root for details. grammar Solidity; sourceUnit : (pragmaDirective | importDirective | contractDefinition)* EOF ; pragmaDirective : 'pragma' pragmaName pragmaValue ';' ; pragmaName : identifier ; pragmaValue : version | expression ; version : versionConstraint versionConstraint? ; versionOperator : '^' | '~' | '>=' | '>' | '<' | '<=' | '=' ; versionConstraint : versionOperator? VersionLiteral ; importDeclaration : identifier ('as' identifier)? ; importDirective : 'import' StringLiteral ('as' identifier)? ';' | 'import' ('*' | identifier) ('as' identifier)? 'from' StringLiteral ';' | 'import' '{' importDeclaration ( ',' importDeclaration )* '}' 'from' StringLiteral ';' ; contractDefinition : ( 'contract' | 'interface' | 'library' ) identifier ( 'is' inheritanceSpecifier (',' inheritanceSpecifier )* )? '{' contractPart* '}' ; inheritanceSpecifier : userDefinedTypeName ( '(' expression ( ',' expression )* ')' )? ; contractPart : stateVariableDeclaration | usingForDeclaration | structDefinition | constructorDefinition | modifierDefinition | functionDefinition | eventDefinition | enumDefinition ; stateVariableDeclaration : typeName ( PublicKeyword | InternalKeyword | PrivateKeyword | ConstantKeyword )* identifier ('=' expression)? ';' ; usingForDeclaration : 'using' identifier 'for' ('*' | typeName) ';' ; structDefinition : 'struct' identifier '{' ( variableDeclaration ';' (variableDeclaration ';')* )? '}' ; constructorDefinition : 'constructor' parameterList modifierList block ; modifierDefinition : 'modifier' identifier parameterList? block ; modifierInvocation : identifier ( '(' expressionList? ')' )? ; functionDefinition : 'function' identifier? parameterList modifierList returnParameters? ( ';' | block ) ; returnParameters : 'returns' parameterList ; modifierList : ( modifierInvocation | stateMutability | ExternalKeyword | PublicKeyword | InternalKeyword | PrivateKeyword )* ; eventDefinition : 'event' identifier eventParameterList AnonymousKeyword? ';' ; enumValue : identifier ; enumDefinition : 'enum' identifier '{' enumValue? (',' enumValue)* '}' ; parameterList : '(' ( parameter (',' parameter)* )? ')' ; parameter : typeName storageLocation? identifier? ; eventParameterList : '(' ( eventParameter (',' eventParameter)* )? ')' ; eventParameter : typeName IndexedKeyword? identifier? ; functionTypeParameterList : '(' ( functionTypeParameter (',' functionTypeParameter)* )? ')' ; functionTypeParameter : typeName storageLocation? ; variableDeclaration : typeName storageLocation? identifier ; typeName : elementaryTypeName | userDefinedTypeName | mapping | typeName '[' expression? ']' | functionTypeName | 'address' 'payable' ; userDefinedTypeName : identifier ( '.' identifier )* ; mapping : 'mapping' '(' elementaryTypeName '=>' typeName ')' ; functionTypeName : 'function' functionTypeParameterList ( InternalKeyword | ExternalKeyword | stateMutability )* ( 'returns' functionTypeParameterList )? ; storageLocation : 'memory' | 'storage' | 'calldata'; stateMutability : PureKeyword | ConstantKeyword | ViewKeyword | PayableKeyword ; block : '{' statement* '}' ; statement : ifStatement | whileStatement | forStatement | block | inlineAssemblyStatement | doWhileStatement | continueStatement | breakStatement | returnStatement | throwStatement | emitStatement | simpleStatement ; expressionStatement : expression ';' ; ifStatement : 'if' '(' expression ')' statement ( 'else' statement )? ; whileStatement : 'while' '(' expression ')' statement ; simpleStatement : ( variableDeclarationStatement | expressionStatement ) ; forStatement : 'for' '(' ( simpleStatement | ';' ) ( expressionStatement | ';' ) expression? ')' statement ; inlineAssemblyStatement : 'assembly' StringLiteral? assemblyBlock ; doWhileStatement : 'do' statement 'while' '(' expression ')' ';' ; continueStatement : 'continue' ';' ; breakStatement : 'break' ';' ; returnStatement : 'return' expression? ';' ; throwStatement : 'throw' ';' ; emitStatement : 'emit' functionCall ';' ; variableDeclarationStatement : ( 'var' identifierList | variableDeclaration | '(' variableDeclarationList ')' ) ( '=' expression )? ';'; variableDeclarationList : variableDeclaration? (',' variableDeclaration? )* ; identifierList : '(' ( identifier? ',' )* identifier? ')' ; elementaryTypeName : 'address' | 'bool' | 'string' | 'var' | Int | Uint | 'byte' | Byte | Fixed | Ufixed ; Int : 'int' | 'int8' | 'int16' | 'int24' | 'int32' | 'int40' | 'int48' | 'int56' | 'int64' | 'int72' | 'int80' | 'int88' | 'int96' | 'int104' | 'int112' | 'int120' | 'int128' | 'int136' | 'int144' | 'int152' | 'int160' | 'int168' | 'int176' | 'int184' | 'int192' | 'int200' | 'int208' | 'int216' | 'int224' | 'int232' | 'int240' | 'int248' | 'int256' ; Uint : 'uint' | 'uint8' | 'uint16' | 'uint24' | 'uint32' | 'uint40' | 'uint48' | 'uint56' | 'uint64' | 'uint72' | 'uint80' | 'uint88' | 'uint96' | 'uint104' | 'uint112' | 'uint120' | 'uint128' | 'uint136' | 'uint144' | 'uint152' | 'uint160' | 'uint168' | 'uint176' | 'uint184' | 'uint192' | 'uint200' | 'uint208' | 'uint216' | 'uint224' | 'uint232' | 'uint240' | 'uint248' | 'uint256' ; Byte : 'bytes' | 'bytes1' | 'bytes2' | 'bytes3' | 'bytes4' | 'bytes5' | 'bytes6' | 'bytes7' | 'bytes8' | 'bytes9' | 'bytes10' | 'bytes11' | 'bytes12' | 'bytes13' | 'bytes14' | 'bytes15' | 'bytes16' | 'bytes17' | 'bytes18' | 'bytes19' | 'bytes20' | 'bytes21' | 'bytes22' | 'bytes23' | 'bytes24' | 'bytes25' | 'bytes26' | 'bytes27' | 'bytes28' | 'bytes29' | 'bytes30' | 'bytes31' | 'bytes32' ; Fixed : 'fixed' | ( 'fixed' [0-9]+ 'x' [0-9]+ ) ; Ufixed : 'ufixed' | ( 'ufixed' [0-9]+ 'x' [0-9]+ ) ; expression : expression ('++' | '--') | 'new' typeName | expression '[' expression ']' | expression '(' functionCallArguments ')' | expression '.' identifier | '(' expression ')' | ('++' | '--') expression | ('+' | '-') expression | ('after' | 'delete') expression | '!' expression | '~' expression | expression '**' expression | expression ('*' | '/' | '%') expression | expression ('+' | '-') expression | expression ('<<' | '>>') expression | expression '&' expression | expression '^' expression | expression '|' expression | expression ('<' | '>' | '<=' | '>=') expression | expression ('==' | '!=') expression | expression '&&' expression | expression '||' expression | expression '?' expression ':' expression | expression ('=' | '|=' | '^=' | '&=' | '<<=' | '>>=' | '+=' | '-=' | '*=' | '/=' | '%=') expression | primaryExpression ; primaryExpression : BooleanLiteral | numberLiteral | HexLiteral | StringLiteral | identifier | tupleExpression | elementaryTypeNameExpression ; expressionList : expression (',' expression)* ; nameValueList : nameValue (',' nameValue)* ','? ; nameValue : identifier ':' expression ; functionCallArguments : '{' nameValueList? '}' | expressionList? ; functionCall : expression '(' functionCallArguments ')' ; assemblyBlock : '{' assemblyItem* '}' ; assemblyItem : identifier | assemblyBlock | assemblyExpression | assemblyLocalDefinition | assemblyAssignment | assemblyStackAssignment | labelDefinition | assemblySwitch | assemblyFunctionDefinition | assemblyFor | assemblyIf | BreakKeyword | ContinueKeyword | subAssembly | numberLiteral | StringLiteral | HexLiteral ; assemblyExpression : assemblyCall | assemblyLiteral ; assemblyCall : ( 'return' | 'address' | 'byte' | identifier ) ( '(' assemblyExpression? ( ',' assemblyExpression )* ')' )? ; assemblyLocalDefinition : 'let' assemblyIdentifierOrList ( ':=' assemblyExpression )? ; assemblyAssignment : assemblyIdentifierOrList ':=' assemblyExpression ; assemblyIdentifierOrList : identifier | '(' assemblyIdentifierList ')' ; assemblyIdentifierList : identifier ( ',' identifier )* ; assemblyStackAssignment : '=:' identifier ; labelDefinition : identifier ':' ; assemblySwitch : 'switch' assemblyExpression assemblyCase* ; assemblyCase : 'case' assemblyLiteral assemblyBlock | 'default' assemblyBlock ; assemblyFunctionDefinition : 'function' identifier '(' assemblyIdentifierList? ')' assemblyFunctionReturns? assemblyBlock ; assemblyFunctionReturns : ( '->' assemblyIdentifierList ) ; assemblyFor : 'for' ( assemblyBlock | assemblyExpression ) assemblyExpression ( assemblyBlock | assemblyExpression ) assemblyBlock ; assemblyIf : 'if' assemblyExpression assemblyBlock ; assemblyLiteral : StringLiteral | DecimalNumber | HexNumber | HexLiteral ; subAssembly : 'assembly' identifier assemblyBlock ; tupleExpression : '(' ( expression? ( ',' expression? )* ) ')' | '[' ( expression ( ',' expression )* )? ']' ; elementaryTypeNameExpression : elementaryTypeName ; numberLiteral : (DecimalNumber | HexNumber) NumberUnit? ; identifier : ('from' | 'calldata' | Identifier) ; VersionLiteral : [0-9]+ '.' [0-9]+ '.' [0-9]+ ; BooleanLiteral : 'true' | 'false' ; DecimalNumber : ([0-9]+ | ([0-9]* '.' [0-9]+) ) ( [eE] [0-9]+ )? ; HexNumber : '0' [xX] HexCharacter+ ; NumberUnit : 'wei' | 'szabo' | 'finney' | 'ether' | 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'years' ; HexLiteral : 'hex' ('"' HexPair* '"' | '\'' HexPair* '\'') ; fragment HexPair : HexCharacter HexCharacter ; fragment HexCharacter : [0-9A-Fa-f] ; ReservedKeyword : 'abstract' | 'after' | 'case' | 'catch' | 'default' | 'final' | 'in' | 'inline' | 'let' | 'match' | 'null' | 'of' | 'relocatable' | 'static' | 'switch' | 'try' | 'type' | 'typeof' ; AnonymousKeyword : 'anonymous' ; BreakKeyword : 'break' ; ConstantKeyword : 'constant' ; ContinueKeyword : 'continue' ; ExternalKeyword : 'external' ; IndexedKeyword : 'indexed' ; InternalKeyword : 'internal' ; PayableKeyword : 'payable' ; PrivateKeyword : 'private' ; PublicKeyword : 'public' ; PureKeyword : 'pure' ; ViewKeyword : 'view' ; Identifier : IdentifierStart IdentifierPart* ; fragment IdentifierStart : [a-zA-Z$_] ; fragment IdentifierPart : [a-zA-Z0-9$_] ; StringLiteral : '"' DoubleQuotedStringCharacter* '"' | '\'' SingleQuotedStringCharacter* '\'' ; fragment DoubleQuotedStringCharacter : ~["\r\n\\] | ('\\' .) ; fragment SingleQuotedStringCharacter : ~['\r\n\\] | ('\\' .) ; WS : [ \t\r\n\u000C]+ -> skip ; COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ;
Update license header
Update license header
ANTLR
mit
solidityj/solidity-antlr4,federicobond/solidity-antlr4
329e8a3aebbf8a652cb88be3a9dd07475a1398f5
src/grammar/Clojure.g4
src/grammar/Clojure.g4
/* Converted to ANTLR 4 by Terence Parr. Unsure of provence. I see it commited by matthias.koester for clojure-eclipse project on Oct 5, 2009: https://code.google.com/p/clojure-eclipse/ Seems to me Laurent Petit had a version of this. I also see Jingguo Yao submitting a link to a now-dead github project on Jan 1, 2011. https://github.com/laurentpetit/ccw/tree/master/clojure-antlr-grammar Regardless, there are some issues perhaps related to "sugar"; I've tried to fix them. This parses https://github.com/weavejester/compojure project. I also note this is hardly a grammar; more like "match a bunch of crap in parens" but I guess that is LISP for you ;) */ grammar Clojure; file: form* #ftest; form: kw | literal | let_form | list | vector | map | reader_macro | '#\'' SYMBOL // TJP added (get Var object instead of the value of a symbol) ; let_form: '(' let binding body ')'; let: 'let' ; binding: '[' form* ']' ; body: form*; /* list: '(' form* ')' ; */ list: '(' form* ')' ; kw: 'defn' | 'def' | 'do' ; // etc. vector: '[' form* ']' ; map: '{' (form form)* '}' ; // TJP added '&' (gather a variable number of arguments) special_form: ('\'' | '`' | '~' | '~@' | '^' | '@' | '&') form ; lambda: '#(' form* ')' ; meta_data: '#^' map form ; var_quote: '\'' '#' SYMBOL ; regex: '#' STRING ; reader_macro : lambda | meta_data | special_form | regex | var_quote | SYMBOL '#' // TJP added (auto-gensym) ; literal : STRING # str | NUMBER # nbr | CHARACTER #char | NIL #nil | BOOLEAN #bool | KEYWORD #keyw | SYMBOL #sym | PARAM_NAME #parm ; STRING : '"' ( ~'"' | '\\' '"' )* '"' ; NUMBER : '-'? [0-9]+ ('.' [0-9]+)? ([eE] '-'? [0-9]+)? ; CHARACTER : '\\' . ; NIL : 'nil'; BOOLEAN : 'true' | 'false' ; KEYWORD : ':' SYMBOL ; SYMBOL: '.' | '/' | NAME ('/' NAME)? ; PARAM_NAME: '%' (('1'..'9')('0'..'9')*)? ; fragment NAME: SYMBOL_HEAD SYMBOL_REST* (':' SYMBOL_REST+)* ; fragment SYMBOL_HEAD : 'a'..'z' | 'A'..'Z' | '*' | '+' | '!' | '-' | '_' | '?' | '>' | '<' | '=' | '$' ; fragment SYMBOL_REST : SYMBOL_HEAD | '&' // apparently this is legal in an ID: "(defn- assoc-&-binding ..." TJP | '0'..'9' | '.' ; WS : [ \n\r\t\,] -> channel(HIDDEN) ; COMMENT : ';' ~[\r\n]* -> channel(HIDDEN) ;
// copy before editing! // original: https://github.com/antlr/grammars-v4/blob/master/clojure/Clojure.g4 /* Converted to ANTLR 4 by Terence Parr. Unsure of provence. I see it commited by matthias.koester for clojure-eclipse project on Oct 5, 2009: https://code.google.com/p/clojure-eclipse/ Seems to me Laurent Petit had a version of this. I also see Jingguo Yao submitting a link to a now-dead github project on Jan 1, 2011. https://github.com/laurentpetit/ccw/tree/master/clojure-antlr-grammar Regardless, there are some issues perhaps related to "sugar"; I've tried to fix them. This parses https://github.com/weavejester/compojure project. I also note this is hardly a grammar; more like "match a bunch of crap in parens" but I guess that is LISP for you ;) */ grammar Clojure; file: list*; form: literal | list | vector | map | reader_macro | '#\'' SYMBOL // TJP added (get Var object instead of the value of a symbol) ; list: '(' form* ')' ; vector: '[' form* ']' ; map: '{' (form form)* '}' ; // TJP added '&' (gather a variable number of arguments) special_form: ('\'' | '`' | '~' | '~@' | '^' | '@' | '&') form ; lambda: '#(' form* ')' ; meta_data: '#^' map form ; var_quote: '\'' '#' SYMBOL ; regex: '#' STRING ; reader_macro : lambda | meta_data | special_form | regex | var_quote | SYMBOL '#' // TJP added (auto-gensym) ; literal : STRING | NUMBER | CHARACTER | NIL | BOOLEAN | KEYWORD | SYMBOL | PARAM_NAME ; STRING : '"' ( ~'"' | '\\' '"' )* '"' ; NUMBER : '-'? [0-9]+ ('.' [0-9]+)? ([eE] '-'? [0-9]+)? ; CHARACTER : '\\' . ; NIL : 'nil'; BOOLEAN : 'true' | 'false' ; KEYWORD : ':' SYMBOL ; SYMBOL: '.' | '/' | NAME ('/' NAME)? ; PARAM_NAME: '%' (('1'..'9')('0'..'9')*)? ; fragment NAME: SYMBOL_HEAD SYMBOL_REST* (':' SYMBOL_REST+)* ; fragment SYMBOL_HEAD : 'a'..'z' | 'A'..'Z' | '*' | '+' | '!' | '-' | '_' | '?' | '>' | '<' | '=' | '$' ; fragment SYMBOL_REST : SYMBOL_HEAD | '&' // apparently this is legal in an ID: "(defn- assoc-&-binding ..." TJP | '0'..'9' | '.' ; WS : [ \n\r\t\,] -> channel(HIDDEN) ; COMMENT : ';' ~[\r\n]* -> channel(HIDDEN) ;
install read-only copy of Clojure.g4 from antlr repo
install read-only copy of Clojure.g4 from antlr repo
ANTLR
epl-1.0
mobileink/lab.antlr,mobileink/lab.clj.antlr
bb37c95796c511cb63c72948afb6b3207355ce32
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
grammar SQLServerDCLStatement; import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol; permissionOnColumns : permission columnList? ; permission : ID *? ;
grammar SQLServerDCLStatement; import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol; grantGeneral : GRANT (ALL PRIVILEGES? | permissionOnColumns ( COMMA permissionOnColumns)*) (ON (ID COLONCOLON)? ID )? TO ids (WITH GRANT OPTION)? (AS ID)? ; permissionOnColumns : permission columnList? ; permission : ID *? ;
add grantGeneral
add grantGeneral
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
914d991160751938f9b4840911e1e815f9d9daae
prolog.g4
prolog.g4
/* BSD License Copyright (c) 2013, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar prolog; // Prolog text and data formed from terms (6.2) p_text: (directive | clause) * EOF ; directive: ':-' term '.' ; // also 3.58 clause: term '.' ; // also 3.33 // Abstract Syntax (6.3): terms formed from tokens termlist : term ( ',' term )* ; term : VARIABLE # variable | '(' term ')' # braced_term | '-'? integer # integer_term | '-'? FLOAT # float // structure / compound term | atom '(' termlist ')' # compound_term |<assoc=right> term operator term # binary_operator | operator term # unary_operator | '[' termlist ( '|' term )? ']' # list_term //TODO: find out what [|] list syntax means | '{' termlist '}' # curly_bracketed_term | atom # atom_term ; //TODO: operator priority, associativity, arity. valid priority ranges for e.g. [list] syntax //TODO: modifying operator table operator : ':-' | '-->' | '?-' | 'dynamic' | 'multifile' | 'discontiguous' | 'public' | ';' | '->' | ',' | '\\+' | '=' | '\\=' | '==' | '\\==' | '@<' | '@=<' | '@>' | '@>=' | '=..' | 'is' | '=:=' | '=\\=' | '<' | '=<' | '>' | '>=' | ':' // modules: 5.2.1 | '+' | '-' | '/\\' | '\\/' | '*' | '/' | '//' | 'rem' | 'mod' | '<<' | '>>' //TODO: '/' cannot be used as atom because token here not in GRAPHIC. only works because , is operator too. example: swipl/filesex.pl:177 | '**' | '^' | '\\' ; atom // 6.4.2 and 6.1.2 : '[' ']' # empty_list | '{' '}' # empty_braces | LETTER_DIGIT # name | GRAPHIC_TOKEN # graphic | QUOTED # quoted_string | DOUBLE_QUOTED_LIST# dq_string | BACK_QUOTED_STRING# backq_string | ';' # semicolon | '!' # cut ; integer // 6.4.4 : DECIMAL | CHARACTER_CODE_CONSTANT | BINARY | OCTAL | HEX ; // Lexer (6.4 & 6.5): Tokens formed from Characters LETTER_DIGIT // 6.4.2 : SMALL_LETTER ALPHANUMERIC* ; VARIABLE // 6.4.3 : CAPITAL_LETTER ALPHANUMERIC* | '_' ALPHANUMERIC+ | '_' ; // 6.4.4 DECIMAL: DIGIT+ ; BINARY: '0b' [01]+ ; OCTAL: '0o' [0-7]+ ; HEX: '0x' HEX_DIGIT+ ; CHARACTER_CODE_CONSTANT: '0' '\'' SINGLE_QUOTED_CHARACTER ; FLOAT: DECIMAL '.' [0-9]+ ( [eE] [+-] DECIMAL )? ; GRAPHIC_TOKEN: (GRAPHIC | '\\')+ ; // 6.4.2 fragment GRAPHIC: [#$&*+./:<=>?@^~] | '-' ; // 6.5.1 graphic char // 6.4.2.1 fragment SINGLE_QUOTED_CHARACTER: NON_QUOTE_CHAR | '\'\'' | '"' | '`' ; fragment DOUBLE_QUOTED_CHARACTER: NON_QUOTE_CHAR | '\'' | '""' | '`' ; fragment BACK_QUOTED_CHARACTER: NON_QUOTE_CHAR | '\'' | '"' | '``' ; fragment NON_QUOTE_CHAR : GRAPHIC | ALPHANUMERIC | SOLO | ' ' // space char | META_ESCAPE | CONTROL_ESCAPE | OCTAL_ESCAPE | HEX_ESCAPE ; META_ESCAPE: '\\' [\\'"`] ; // meta char CONTROL_ESCAPE: '\\' [abrftnv] ; OCTAL_ESCAPE: '\\' [0-7]+ '\\' ; HEX_ESCAPE: '\\x' HEX_DIGIT+ '\\' ; QUOTED: '\'' (CONTINUATION_ESCAPE | SINGLE_QUOTED_CHARACTER )*? '\'' ; // 6.4.2 DOUBLE_QUOTED_LIST: '"' (CONTINUATION_ESCAPE | DOUBLE_QUOTED_CHARACTER )*? '"'; // 6.4.6 BACK_QUOTED_STRING: '`' (CONTINUATION_ESCAPE | BACK_QUOTED_CHARACTER )*? '`'; // 6.4.7 fragment CONTINUATION_ESCAPE: '\\\n' ; // 6.5.2 fragment ALPHANUMERIC: ALPHA | DIGIT ; fragment ALPHA: '_' | SMALL_LETTER | CAPITAL_LETTER ; fragment SMALL_LETTER: [a-z_]; fragment CAPITAL_LETTER: [A-Z]; fragment DIGIT: [0-9] ; fragment HEX_DIGIT: [0-9a-fA-F] ; // 6.5.3 fragment SOLO: [!(),;[{}|%] | ']' ; WS : [ \t\r\n]+ -> skip ; COMMENT: '%' ~[\n\r]* ( [\n\r] | EOF) -> channel(HIDDEN) ; MULTILINE_COMMENT: '/*' ( MULTILINE_COMMENT | . )*? ('*/' | EOF) -> channel(HIDDEN);
/* BSD License Copyright (c) 2013, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar prolog; // Prolog text and data formed from terms (6.2) p_text: (directive | clause) * EOF ; directive: ':-' term '.' ; // also 3.58 clause: term '.' ; // also 3.33 // Abstract Syntax (6.3): terms formed from tokens termlist : term ( ',' term )* ; term : VARIABLE # variable | '(' term ')' # braced_term | '-'? integer # integer_term | '-'? FLOAT # float // structure / compound term | atom '(' termlist ')' # compound_term |<assoc=right> term operator term # binary_operator | operator term # unary_operator | '[' termlist ( '|' term )? ']' # list_term | '{' termlist '}' # curly_bracketed_term | atom # atom_term ; //TODO: operator priority, associativity, arity. Filter valid priority ranges for e.g. [list] syntax //TODO: modifying operator table operator : ':-' | '-->' | '?-' | 'dynamic' | 'multifile' | 'discontiguous' | 'public' //TODO: move operators used in directives to "built-in" definition of dialect | ';' | '->' | ',' | '\\+' | '=' | '\\=' | '==' | '\\==' | '@<' | '@=<' | '@>' | '@>=' | '=..' | 'is' | '=:=' | '=\\=' | '<' | '=<' | '>' | '>=' | ':' // modules: 5.2.1 | '+' | '-' | '/\\' | '\\/' | '*' | '/' | '//' | 'rem' | 'mod' | '<<' | '>>' //TODO: '/' cannot be used as atom because token here not in GRAPHIC. only works because , is operator too. example: swipl/filesex.pl:177 | '**' | '^' | '\\' ; atom // 6.4.2 and 6.1.2 : '[' ']' # empty_list //NOTE [] is not atom anymore in swipl 7 and later | '{' '}' # empty_braces | LETTER_DIGIT # name | GRAPHIC_TOKEN # graphic | QUOTED # quoted_string | DOUBLE_QUOTED_LIST# dq_string | BACK_QUOTED_STRING# backq_string | ';' # semicolon | '!' # cut ; integer // 6.4.4 : DECIMAL | CHARACTER_CODE_CONSTANT | BINARY | OCTAL | HEX ; // Lexer (6.4 & 6.5): Tokens formed from Characters LETTER_DIGIT // 6.4.2 : SMALL_LETTER ALPHANUMERIC* ; VARIABLE // 6.4.3 : CAPITAL_LETTER ALPHANUMERIC* | '_' ALPHANUMERIC+ | '_' ; // 6.4.4 DECIMAL: DIGIT+ ; BINARY: '0b' [01]+ ; OCTAL: '0o' [0-7]+ ; HEX: '0x' HEX_DIGIT+ ; CHARACTER_CODE_CONSTANT: '0' '\'' SINGLE_QUOTED_CHARACTER ; FLOAT: DECIMAL '.' [0-9]+ ( [eE] [+-] DECIMAL )? ; GRAPHIC_TOKEN: (GRAPHIC | '\\')+ ; // 6.4.2 fragment GRAPHIC: [#$&*+./:<=>?@^~] | '-' ; // 6.5.1 graphic char // 6.4.2.1 fragment SINGLE_QUOTED_CHARACTER: NON_QUOTE_CHAR | '\'\'' | '"' | '`' ; fragment DOUBLE_QUOTED_CHARACTER: NON_QUOTE_CHAR | '\'' | '""' | '`' ; fragment BACK_QUOTED_CHARACTER: NON_QUOTE_CHAR | '\'' | '"' | '``' ; fragment NON_QUOTE_CHAR : GRAPHIC | ALPHANUMERIC | SOLO | ' ' // space char | META_ESCAPE | CONTROL_ESCAPE | OCTAL_ESCAPE | HEX_ESCAPE ; META_ESCAPE: '\\' [\\'"`] ; // meta char CONTROL_ESCAPE: '\\' [abrftnv] ; OCTAL_ESCAPE: '\\' [0-7]+ '\\' ; HEX_ESCAPE: '\\x' HEX_DIGIT+ '\\' ; QUOTED: '\'' (CONTINUATION_ESCAPE | SINGLE_QUOTED_CHARACTER )*? '\'' ; // 6.4.2 DOUBLE_QUOTED_LIST: '"' (CONTINUATION_ESCAPE | DOUBLE_QUOTED_CHARACTER )*? '"'; // 6.4.6 BACK_QUOTED_STRING: '`' (CONTINUATION_ESCAPE | BACK_QUOTED_CHARACTER )*? '`'; // 6.4.7 fragment CONTINUATION_ESCAPE: '\\\n' ; // 6.5.2 fragment ALPHANUMERIC: ALPHA | DIGIT ; fragment ALPHA: '_' | SMALL_LETTER | CAPITAL_LETTER ; fragment SMALL_LETTER: [a-z_]; fragment CAPITAL_LETTER: [A-Z]; fragment DIGIT: [0-9] ; fragment HEX_DIGIT: [0-9a-fA-F] ; // 6.5.3 fragment SOLO: [!(),;[{}|%] | ']' ; WS : [ \t\r\n]+ -> skip ; COMMENT: '%' ~[\n\r]* ( [\n\r] | EOF) -> channel(HIDDEN) ; MULTILINE_COMMENT: '/*' ( MULTILINE_COMMENT | . )*? ('*/' | EOF) -> channel(HIDDEN);
update TODOs
update TODOs
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
f933a3cd758610a3ba5763009c74dbb1afde7aa6
omni-cx2x/src/cx2x/translator/language/parser/Claw.g4
omni-cx2x/src/cx2x/translator/language/parser/Claw.g4
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import cx2x.translator.common.ClawConstant; import cx2x.translator.language.base.ClawDirective; import cx2x.translator.language.base.ClawLanguage; import cx2x.translator.language.common.*; import cx2x.translator.common.Utility; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage l] @init{ $l = new ClawLanguage(); } : CLAW directive[$l] EOF | CLAW VERBATIM // this directive accept anything after the verbatim { $l.setDirective(ClawDirective.VERBATIM); } | CLAW ACC // this directive accept anything after the acc { $l.setDirective(ClawDirective.PRIMITIVE); } | CLAW OMP // this directive accept anything after the omp { $l.setDirective(ClawDirective.PRIMITIVE); } ; directive[ClawLanguage l] @init{ List<ClawMapping> m = new ArrayList<>(); List<String> o = new ArrayList<>(); List<String> s = new ArrayList<>(); List<Integer> i = new ArrayList<>(); } : // loop-fusion directive LOOPFUSION group_clause_optional[$l] collapse_clause_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_FUSION); } // loop-interchange directive | LOOPINTERCHANGE indexes_option[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } // loop-extract directive | LOOPEXTRACT range_option mapping_option_list[m] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_EXTRACT); $l.setRange($range_option.r); $l.setMappings(m); } // remove directive | REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); } | END REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); $l.setEndPragma(); } // Kcache directive | KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); } | KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); $l.setInitClause(); } // Array notation transformation directive | ARRAY_TRANS induction_optional[$l] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); } | END ARRAY_TRANS { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); $l.setEndPragma(); } // loop-hoist directive | LOOPHOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF { $l.setHoistInductionVars(o); $l.setDirective(ClawDirective.LOOP_HOIST); } | END LOOPHOIST EOF { $l.setDirective(ClawDirective.LOOP_HOIST); $l.setEndPragma(); } // on the fly directive | ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')' { $l.setDirective(ClawDirective.ARRAY_TO_CALL); $l.setFctParams(o); $l.setFctName($fct_name.text); $l.setArrayName($array_name.text); } // parallelize directive | define_option[$l]* PARALLELIZE data_over_clause[$l]* { $l.setDirective(ClawDirective.PARALLELIZE); } | PARALLELIZE FORWARD { $l.setDirective(ClawDirective.PARALLELIZE); $l.setForwardClause(); } | END PARALLELIZE { $l.setDirective(ClawDirective.PARALLELIZE); $l.setEndPragma(); } // ignore directive | IGNORE { $l.setDirective(ClawDirective.IGNORE); } | END IGNORE { $l.setDirective(ClawDirective.IGNORE); $l.setEndPragma(); } ; // Comma-separated identifiers list ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; // Comma-separated identifiers or colon symbol list ids_or_colon_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | ':' { $ids.add(":"); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_or_colon_list[$ids] | ':' { $ids.add(":"); } ',' ids_or_colon_list[$ids] ; // data over clause used in parallelize directive data_over_clause[ClawLanguage l] @init{ List<String> overLst = new ArrayList<>(); List<String> dataLst = new ArrayList<>(); } : DATA '(' ids_list[dataLst] ')' OVER '(' ids_or_colon_list[overLst] ')' { $l.setOverDataClause(dataLst); $l.setOverClause(overLst); } ; // group clause group_clause_optional[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupClause($group_name.text); } | /* empty */ ; // collapse clause collapse_clause_optional[ClawLanguage l]: COLLAPSE '(' n=NUMBER ')' { $l.setCollapseClause($n.text); } | /* empty */ ; // fusion clause fusion_clause_optional[ClawLanguage l]: FUSION group_clause_optional[$l] { $l.setFusionClause(); } | /* empty */ ; // parallel clause parallel_clause_optional[ClawLanguage l]: PARALLEL { $l.setParallelClause(); } | /* empty */ ; // acc clause acc_optional[ClawLanguage l] @init{ List<String> tempAcc = new ArrayList<>(); } : ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); } | /* empty */ ; // interchange clause interchange_optional[ClawLanguage l]: INTERCHANGE indexes_option[$l] { $l.setInterchangeClause(); } | /* empty */ ; // induction clause induction_optional[ClawLanguage l] @init{ List<String> temp = new ArrayList<>(); } : INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); } | /* empty */ ; // data clause data_clause[ClawLanguage l] @init { List<String> temp = new ArrayList<>(); } : DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); } ; // private clause private_optional[ClawLanguage l]: PRIVATE { $l.setPrivateClause(); } | /* empty */ ; // reshape clause reshape_optional[ClawLanguage l] @init{ List<ClawReshapeInfo> r = new ArrayList(); } : RESHAPE '(' reshape_list[r] ')' { $l.setReshapeClauseValues(r); } | /* empty */ ; // reshape clause reshape_element returns [ClawReshapeInfo i] @init{ List<Integer> temp = new ArrayList(); } : array_name=IDENTIFIER '(' target_dim=NUMBER ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } | array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } ; reshape_list[List<ClawReshapeInfo> r]: info=reshape_element { $r.add($info.i); } ',' reshape_list[$r] | info=reshape_element { $r.add($info.i); } ; identifiers[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids] ; identifiers_list[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids] ; integers[List<Integer> ints]: ; integers_list[List<Integer> ints]: i=NUMBER { $ints.add(Integer.parseInt($i.text)); } | i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints] ; indexes_option[ClawLanguage l] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $l.setIndexes(indexes); } | /* empty */ ; offset_list_optional[List<Integer> offsets]: OFFSET '(' offset_list[$offsets] ')' | /* empty */ ; offset_list[List<Integer> offsets]: offset[$offsets] | offset[$offsets] ',' offset_list[$offsets] ; offset[List<Integer> offsets]: n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } | '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); } | '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(ClawConstant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; range_id returns [String text]: n=NUMBER { $text = $n.text; } | i=IDENTIFIER { $text = $i.text; } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; mapping_var_list[List<ClawMappingVar> vars]: mv=mapping_var { $vars.add($mv.mappingVar); } | mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars] ; mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>(); List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>(); $mapping.setMappedVariables(listMapped); $mapping.setMappingVariables(listMapping); } : MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')' ; mapping_option_list[List<ClawMapping> mappings]: m=mapping_option { $mappings.add($m.mapping); } | m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings] ; define_option[ClawLanguage l]: DEFINE DIMENSION id=IDENTIFIER '(' lower=range_id ':' upper=range_id ')' { ClawDimension cd = new ClawDimension($id.text, $lower.text, $upper.text); $l.addDimension(cd); } ; copy_clause_optional[ClawLanguage l]: /* empty */ | COPY //{ $l.setCopyClause(BOTH); } | COPY '(' IN ')' //{ $l.setCopyClause(IN); } | COPY '(' OUT ')' //{ $l.setCopyClause(OUT); } ; update_clause_optional[ClawLanguage l]: /* empty */ | UPDATE //{ $l.setUpdateClause(BOTH); } | UPDATE '(' IN ')' //{ $l.setUpdateClause(IN); } | UPDATE '(' OUT ')' //{ $l.setUpdateClause(OUT); } ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // CLAW Directives ARRAY_TRANS : 'array-transform'; ARRAY_TO_CALL : 'call'; DEFINE : 'define'; END : 'end'; KCACHE : 'kcache'; LOOPEXTRACT : 'loop-extract'; LOOPFUSION : 'loop-fusion'; LOOPHOIST : 'loop-hoist'; LOOPINTERCHANGE : 'loop-interchange'; PARALLELIZE : 'parallelize'; REMOVE : 'remove'; IGNORE : 'ignore'; VERBATIM : 'verbatim'; // CLAW Clauses COLLAPSE : 'collapse'; COPY : 'copy'; DATA : 'data'; DIMENSION : 'dimension'; FORWARD : 'forward'; FUSION : 'fusion'; GROUP : 'group'; INDUCTION : 'induction'; INIT : 'init'; INTERCHANGE : 'interchange'; MAP : 'map'; OFFSET : 'offset'; OVER : 'over'; PARALLEL : 'parallel'; PRIVATE : 'private'; RANGE : 'range'; RESHAPE : 'reshape'; UPDATE : 'update'; // data copy/update clause keywords IN : 'in'; OUT : 'out'; // Directive primitive clause ACC : 'acc'; OMP : 'omp'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : [0-9] ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import cx2x.translator.common.ClawConstant; import cx2x.translator.language.base.*; import cx2x.translator.language.common.*; import cx2x.translator.common.Utility; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage l] @init{ $l = new ClawLanguage(); } : CLAW directive[$l] EOF | CLAW VERBATIM // this directive accept anything after the verbatim { $l.setDirective(ClawDirective.VERBATIM); } | CLAW ACC // this directive accept anything after the acc { $l.setDirective(ClawDirective.PRIMITIVE); } | CLAW OMP // this directive accept anything after the omp { $l.setDirective(ClawDirective.PRIMITIVE); } ; directive[ClawLanguage l] @init{ List<ClawMapping> m = new ArrayList<>(); List<String> o = new ArrayList<>(); List<String> s = new ArrayList<>(); List<Integer> i = new ArrayList<>(); } : // loop-fusion directive LOOPFUSION group_clause_optional[$l] collapse_clause_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_FUSION); } // loop-interchange directive | LOOPINTERCHANGE indexes_option[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } // loop-extract directive | LOOPEXTRACT range_option mapping_option_list[m] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_EXTRACT); $l.setRange($range_option.r); $l.setMappings(m); } // remove directive | REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); } | END REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); $l.setEndPragma(); } // Kcache directive | KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); } | KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); $l.setInitClause(); } // Array notation transformation directive | ARRAY_TRANS induction_optional[$l] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); } | END ARRAY_TRANS { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); $l.setEndPragma(); } // loop-hoist directive | LOOPHOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF { $l.setHoistInductionVars(o); $l.setDirective(ClawDirective.LOOP_HOIST); } | END LOOPHOIST EOF { $l.setDirective(ClawDirective.LOOP_HOIST); $l.setEndPragma(); } // on the fly directive | ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')' { $l.setDirective(ClawDirective.ARRAY_TO_CALL); $l.setFctParams(o); $l.setFctName($fct_name.text); $l.setArrayName($array_name.text); } // parallelize directive | define_option[$l]* PARALLELIZE data_over_clause[$l]* { $l.setDirective(ClawDirective.PARALLELIZE); } | PARALLELIZE FORWARD { $l.setDirective(ClawDirective.PARALLELIZE); $l.setForwardClause(); } | END PARALLELIZE { $l.setDirective(ClawDirective.PARALLELIZE); $l.setEndPragma(); } // ignore directive | IGNORE { $l.setDirective(ClawDirective.IGNORE); } | END IGNORE { $l.setDirective(ClawDirective.IGNORE); $l.setEndPragma(); } ; // Comma-separated identifiers list ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; // Comma-separated identifiers or colon symbol list ids_or_colon_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | ':' { $ids.add(":"); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_or_colon_list[$ids] | ':' { $ids.add(":"); } ',' ids_or_colon_list[$ids] ; // data over clause used in parallelize directive data_over_clause[ClawLanguage l] @init{ List<String> overLst = new ArrayList<>(); List<String> dataLst = new ArrayList<>(); } : DATA '(' ids_list[dataLst] ')' OVER '(' ids_or_colon_list[overLst] ')' { $l.setOverDataClause(dataLst); $l.setOverClause(overLst); } ; // group clause group_clause_optional[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupClause($group_name.text); } | /* empty */ ; // collapse clause collapse_clause_optional[ClawLanguage l]: COLLAPSE '(' n=NUMBER ')' { $l.setCollapseClause($n.text); } | /* empty */ ; // fusion clause fusion_clause_optional[ClawLanguage l]: FUSION group_clause_optional[$l] { $l.setFusionClause(); } | /* empty */ ; // parallel clause parallel_clause_optional[ClawLanguage l]: PARALLEL { $l.setParallelClause(); } | /* empty */ ; // acc clause acc_optional[ClawLanguage l] @init{ List<String> tempAcc = new ArrayList<>(); } : ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); } | /* empty */ ; // interchange clause interchange_optional[ClawLanguage l]: INTERCHANGE indexes_option[$l] { $l.setInterchangeClause(); } | /* empty */ ; // induction clause induction_optional[ClawLanguage l] @init{ List<String> temp = new ArrayList<>(); } : INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); } | /* empty */ ; // data clause data_clause[ClawLanguage l] @init { List<String> temp = new ArrayList<>(); } : DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); } ; // private clause private_optional[ClawLanguage l]: PRIVATE { $l.setPrivateClause(); } | /* empty */ ; // reshape clause reshape_optional[ClawLanguage l] @init{ List<ClawReshapeInfo> r = new ArrayList(); } : RESHAPE '(' reshape_list[r] ')' { $l.setReshapeClauseValues(r); } | /* empty */ ; // reshape clause reshape_element returns [ClawReshapeInfo i] @init{ List<Integer> temp = new ArrayList(); } : array_name=IDENTIFIER '(' target_dim=NUMBER ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } | array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } ; reshape_list[List<ClawReshapeInfo> r]: info=reshape_element { $r.add($info.i); } ',' reshape_list[$r] | info=reshape_element { $r.add($info.i); } ; identifiers[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids] ; identifiers_list[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids] ; integers[List<Integer> ints]: ; integers_list[List<Integer> ints]: i=NUMBER { $ints.add(Integer.parseInt($i.text)); } | i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints] ; indexes_option[ClawLanguage l] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $l.setIndexes(indexes); } | /* empty */ ; offset_list_optional[List<Integer> offsets]: OFFSET '(' offset_list[$offsets] ')' | /* empty */ ; offset_list[List<Integer> offsets]: offset[$offsets] | offset[$offsets] ',' offset_list[$offsets] ; offset[List<Integer> offsets]: n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } | '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); } | '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(ClawConstant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; range_id returns [String text]: n=NUMBER { $text = $n.text; } | i=IDENTIFIER { $text = $i.text; } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; mapping_var_list[List<ClawMappingVar> vars]: mv=mapping_var { $vars.add($mv.mappingVar); } | mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars] ; mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>(); List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>(); $mapping.setMappedVariables(listMapped); $mapping.setMappingVariables(listMapping); } : MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')' ; mapping_option_list[List<ClawMapping> mappings]: m=mapping_option { $mappings.add($m.mapping); } | m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings] ; define_option[ClawLanguage l]: DEFINE DIMENSION id=IDENTIFIER '(' lower=range_id ':' upper=range_id ')' { ClawDimension cd = new ClawDimension($id.text, $lower.text, $upper.text); $l.addDimension(cd); } ; copy_clause_optional[ClawLanguage l]: /* empty */ | COPY { $l.setCopyClauseValue(ClawDMD.BOTH); } | COPY '(' IN ')' { $l.setCopyClauseValue(ClawDMD.IN); } | COPY '(' OUT ')' { $l.setCopyClauseValue(ClawDMD.OUT); } ; update_clause_optional[ClawLanguage l]: /* empty */ | UPDATE { $l.setUpdateClauseValue(ClawDMD.BOTH); } | UPDATE '(' IN ')' { $l.setUpdateClauseValue(ClawDMD.IN); } | UPDATE '(' OUT ')' { $l.setUpdateClauseValue(ClawDMD.OUT); } ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // CLAW Directives ARRAY_TRANS : 'array-transform'; ARRAY_TO_CALL : 'call'; DEFINE : 'define'; END : 'end'; KCACHE : 'kcache'; LOOPEXTRACT : 'loop-extract'; LOOPFUSION : 'loop-fusion'; LOOPHOIST : 'loop-hoist'; LOOPINTERCHANGE : 'loop-interchange'; PARALLELIZE : 'parallelize'; REMOVE : 'remove'; IGNORE : 'ignore'; VERBATIM : 'verbatim'; // CLAW Clauses COLLAPSE : 'collapse'; COPY : 'copy'; DATA : 'data'; DIMENSION : 'dimension'; FORWARD : 'forward'; FUSION : 'fusion'; GROUP : 'group'; INDUCTION : 'induction'; INIT : 'init'; INTERCHANGE : 'interchange'; MAP : 'map'; OFFSET : 'offset'; OVER : 'over'; PARALLEL : 'parallel'; PRIVATE : 'private'; RANGE : 'range'; RESHAPE : 'reshape'; UPDATE : 'update'; // data copy/update clause keywords IN : 'in'; OUT : 'out'; // Directive primitive clause ACC : 'acc'; OMP : 'omp'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : [0-9] ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
Update the language object during parsing for copy/update clause
Update the language object during parsing for copy/update clause
ANTLR
bsd-2-clause
clementval/claw-compiler,clementval/claw-compiler
72c25638ce95d5d2ec1a150a5b6b51dbec7cb3e8
sharding-core/src/main/antlr4/imports/PostgreBase.g4
sharding-core/src/main/antlr4/imports/PostgreBase.g4
grammar PostgreBase; import PostgreKeyword, DataType, Keyword, Symbol, BaseRule; columnDefinition : columnName dataType collateClause? columnConstraint* ; dataType : typeName intervalFields? dataTypeLength? (WITHOUT TIME ZONE | WITH TIME ZONE)? (LEFT_BRACKET RIGHT_BRACKET)* | ID ; typeName : DOUBLE PRECISION | CHARACTER VARYING? | BIT VARYING? | ID ; intervalFields : intervalField (TO intervalField)? ; intervalField : YEAR | MONTH | DAY | HOUR | MINUTE | SECOND ; collateClause : COLLATE collationName ; usingIndexType: USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN) ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT constraintName ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LEFT_PAREN sequenceOptions RIGHT_PAREN)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName (LEFT_PAREN columnName RIGHT_PAREN)? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)?(ON DELETE action)? (ON UPDATE action)? ; checkOption : CHECK expr (NO INHERIT )? ; defaultExpr : CURRENT_TIMESTAMP | expr; sequenceOptions: sequenceOption+ ; sequenceOption : START WITH? NUMBER | INCREMENT BY? NUMBER | MAXVALUE NUMBER | NO MAXVALUE | MINVALUE NUMBER | NO MINVALUE | CYCLE | NO CYCLE | CACHE NUMBER ; indexParameters : (USING INDEX TABLESPACE tablespaceName)? ; action : NO ACTION | RESTRICT | CASCADE | SET NULL | SET DEFAULT ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED |IMMEDIATE))? ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnList indexParameters | primaryKey columnList indexParameters | FOREIGN KEY columnList REFERENCES tableName columnList (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? foreignKeyOnAction* ; foreignKeyOnAction : ON UPDATE foreignKeyOn | ON DELETE foreignKeyOn ; foreignKeyOn : RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT ; excludeElement : (columnName | expr) opclass? (ASC | DESC)? (NULLS (FIRST | LAST))? ; privateExprOfDb: aggregateExpression |windowFunction |arrayConstructorWithCast |(TIMESTAMP (WITH TIME ZONE)? STRING) |extractFromFunction ; pgExpr : castExpr | collateExpr | expr ; aggregateExpression : ID (LEFT_PAREN (ALL | DISTINCT)? exprs orderByClause? RIGHT_PAREN) asteriskWithParen (LEFT_PAREN exprs RIGHT_PAREN WITHIN GROUP LEFT_PAREN orderByClause RIGHT_PAREN) filterClause? ; filterClause : FILTER LEFT_PAREN WHERE booleanPrimary RIGHT_PAREN ; asteriskWithParen : LEFT_PAREN ASTERISK RIGHT_PAREN ; windowFunction : ID (exprsWithParen | asteriskWithParen) filterClause? windowFunctionWithClause ; windowFunctionWithClause : OVER (ID | LEFT_PAREN windowDefinition RIGHT_PAREN ) ; windowDefinition : ID? (PARTITION BY exprs)? (orderByExpr (COMMA orderByExpr)*)? frameClause? ; orderByExpr : ORDER BY expr (ASC | DESC | USING operator)? (NULLS (FIRST | LAST ))? ; operator : SAFE_EQ | EQ_OR_ASSIGN | NEQ | NEQ_SYM | GT | GTE | LT | LTE | AND_SYM | OR_SYM | NOT_SYM ; frameClause : (RANGE | ROWS) frameStart | (RANGE | ROWS ) BETWEEN frameStart AND frameEnd ; frameStart : UNBOUNDED PRECEDING | NUMBER PRECEDING | CURRENT ROW | NUMBER FOLLOWING | UNBOUNDED FOLLOWING ; frameEnd : frameStart ; castExpr : CAST LEFT_PAREN expr AS dataType RIGHT_PAREN | expr COLON COLON dataType ; castExprWithColon : COLON COLON dataType(LEFT_BRACKET RIGHT_BRACKET)* ; collateExpr : expr COLLATE expr ; arrayConstructorWithCast : arrayConstructor castExprWithColon? | ARRAY LEFT_BRACKET RIGHT_BRACKET castExprWithColon ; arrayConstructor : ARRAY LEFT_BRACKET exprs RIGHT_BRACKET | ARRAY LEFT_BRACKET arrayConstructor (COMMA arrayConstructor)* RIGHT_BRACKET ; extractFromFunction : EXTRACT LEFT_PAREN ID FROM ID RIGHT_PAREN ;
grammar PostgreBase; import PostgreKeyword, DataType, Keyword, Symbol, BaseRule; columnDefinition : columnName dataType collateClause? columnConstraint* ; dataType : typeName intervalFields? dataTypeLength? (WITHOUT TIME ZONE | WITH TIME ZONE)? (LEFT_BRACKET RIGHT_BRACKET)* | ID ; typeName : DOUBLE PRECISION | CHARACTER VARYING? | BIT VARYING? | ID ; intervalFields : intervalField (TO intervalField)? ; intervalField : YEAR | MONTH | DAY | HOUR | MINUTE | SECOND ; collateClause : COLLATE collationName ; usingIndexType: USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN) ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT constraintName ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LEFT_PAREN sequenceOptions RIGHT_PAREN)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName (LEFT_PAREN columnName RIGHT_PAREN)? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)?(ON DELETE action)? foreignKeyOnAction* ; checkOption : CHECK expr (NO INHERIT )? ; defaultExpr : CURRENT_TIMESTAMP | expr; sequenceOptions: sequenceOption+ ; sequenceOption : START WITH? NUMBER | INCREMENT BY? NUMBER | MAXVALUE NUMBER | NO MAXVALUE | MINVALUE NUMBER | NO MINVALUE | CYCLE | NO CYCLE | CACHE NUMBER ; indexParameters : (USING INDEX TABLESPACE tablespaceName)? ; action : NO ACTION | RESTRICT | CASCADE | SET NULL | SET DEFAULT ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED |IMMEDIATE))? ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnList indexParameters | primaryKey columnList indexParameters | FOREIGN KEY columnList REFERENCES tableName columnList (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? foreignKeyOnAction* ; foreignKeyOnAction : ON UPDATE foreignKeyOn | ON DELETE foreignKeyOn ; foreignKeyOn : RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT ; excludeElement : (columnName | expr) opclass? (ASC | DESC)? (NULLS (FIRST | LAST))? ; privateExprOfDb: aggregateExpression |windowFunction |arrayConstructorWithCast |(TIMESTAMP (WITH TIME ZONE)? STRING) |extractFromFunction ; pgExpr : castExpr | collateExpr | expr ; aggregateExpression : ID (LEFT_PAREN (ALL | DISTINCT)? exprs orderByClause? RIGHT_PAREN) asteriskWithParen (LEFT_PAREN exprs RIGHT_PAREN WITHIN GROUP LEFT_PAREN orderByClause RIGHT_PAREN) filterClause? ; filterClause : FILTER LEFT_PAREN WHERE booleanPrimary RIGHT_PAREN ; asteriskWithParen : LEFT_PAREN ASTERISK RIGHT_PAREN ; windowFunction : ID (exprsWithParen | asteriskWithParen) filterClause? windowFunctionWithClause ; windowFunctionWithClause : OVER (ID | LEFT_PAREN windowDefinition RIGHT_PAREN ) ; windowDefinition : ID? (PARTITION BY exprs)? (orderByExpr (COMMA orderByExpr)*)? frameClause? ; orderByExpr : ORDER BY expr (ASC | DESC | USING operator)? (NULLS (FIRST | LAST ))? ; operator : SAFE_EQ | EQ_OR_ASSIGN | NEQ | NEQ_SYM | GT | GTE | LT | LTE | AND_SYM | OR_SYM | NOT_SYM ; frameClause : (RANGE | ROWS) frameStart | (RANGE | ROWS ) BETWEEN frameStart AND frameEnd ; frameStart : UNBOUNDED PRECEDING | NUMBER PRECEDING | CURRENT ROW | NUMBER FOLLOWING | UNBOUNDED FOLLOWING ; frameEnd : frameStart ; castExpr : CAST LEFT_PAREN expr AS dataType RIGHT_PAREN | expr COLON COLON dataType ; castExprWithColon : COLON COLON dataType(LEFT_BRACKET RIGHT_BRACKET)* ; collateExpr : expr COLLATE expr ; arrayConstructorWithCast : arrayConstructor castExprWithColon? | ARRAY LEFT_BRACKET RIGHT_BRACKET castExprWithColon ; arrayConstructor : ARRAY LEFT_BRACKET exprs RIGHT_BRACKET | ARRAY LEFT_BRACKET arrayConstructor (COMMA arrayConstructor)* RIGHT_BRACKET ; extractFromFunction : EXTRACT LEFT_PAREN ID FROM ID RIGHT_PAREN ;
fix postgre foreign key option
fix postgre foreign key option
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
7cbe4d3a8866779bffe63af7d2f110335d19db39
src/main/resources/grammar/Goo.g4
src/main/resources/grammar/Goo.g4
/* generic object-oriented programming language a sample procedure: rtn = foo.bar() a.b.c().d().e.f() a a.b a.b() callback = foo:bar() */ grammar Goo; @lexer::members { public static final int WHITESPACE = 1; public static final int COMMENTS = 2; } //this language don't support class procedure : header block; header : PROCEDURE ID? '(' paramDeclareList? ')'; paramDeclareList : ID (',' ID)*; block : '{' statement* '}'; statement : assignmentStatement | expressionStatement | ifStatement | whileStatement | forStatement | returnStatement | breakStatement | continueStatement | comment | emptyStatement ; emptyStatement : ';'; //varDeclare : 'var' varList; //varList : ID (',' ID)*; expressionStatement : expr ';'; assignmentStatement : assignment ';'; assignment : assignee assignOperator expr; assignOperator : REF_ASSIGN #RefAssignOperator | OWN_ASSIGN #OwnAssignOperator | AUTO_ASSIGN #AutoAssignOperator ; assignee : ID #AssigneeVariable | expr DOT field #AssigneeField ; expr: constant #ConstantExpr | variable #VariableExpr | expr DOT field #AccessField | expr (DOT|DOTDOT) messgeSubject('#'replySubject)? '(' fieldList? ')' #SendMessage ; constant : NUMBER #Number | STRING #String | BOOLEAN #Boolean | NULL #NullValue | link #ObjectLink | procedure #ProcedureConst | object #ObjectConst ; //messageOperator : SYNC_MESSAGE #SyncMessageOperator // | ASYNC_MESSAGE #AsyncMessageOperator // ; link : LINK_PROTOCOL LINK_ADDRESS; object : '{' fieldList? '}'; variable : ID; field : ID #IdField | '$' ID #VarField | STRING #StringField ; messgeSubject : ID #IdMessageSubject | '$' ID #VarMessageSubject | STRING #StringMessageSubject ; replySubject : ID; fieldList : expr (',' expr)* #orderedParamList | nameValue (',' nameValue)* #namedParamList ; nameValue : ID ':' expr; ifStatement : IF '(' expr ')' trueBranch (ELSE falseBranch)?; trueBranch : blockOrStatment; falseBranch: blockOrStatment; whileStatement : WHILE '(' expr ')' blockOrStatment; forStatement : FOR '(' forInit? ';' forCondition ';' forAfterthought? ')' blockOrStatment; forInit: assignment|expr; forCondition : expr; forAfterthought : assignment | expr; blockOrStatment : block | statement; returnStatement : RETURN expr? ';'; breakStatement : BREAK ';'; continueStatement : CONTINUE ';'; comment : LINE_COMMENT | BLOCK_COMMENT; PROCEDURE : 'procedure'; IF : 'if'; ELSE:'else'; WHILE : 'while'; FOR : 'for'; RETURN : 'return'; BOOLEAN : 'true' | 'false'; BREAK: 'break'; CONTINUE : 'continue'; DOT : '.'; DOTDOT : '..'; LINE_COMMENT : '//' .*? '\r'? '\n'; BLOCK_COMMENT : '/*' .*? '*/'; REF_ASSIGN : '->'; OWN_ASSIGN : '=>'; AUTO_ASSIGN: '='| '~>'; //SYNC_MESSAGE : '.'; //ASYNC_MESSAGE : ':'; //LINK : [a-zA-Z0-9]+ '://' [a-zA-Z0-9.]+ '@' [a-zA-Z0-9]+ ('.' [a-zA-Z0-9]+)*; LINK_PROTOCOL : [a-zA-Z0-9]+ '://'; LINK_ADDRESS : ([a-zA-Z0-9._]+)? '@' [a-zA-Z0-9]+ ('.' [a-zA-Z0-9]+)*; //LINK_ID : [a-zA-Z0-9.]+; //LINK_DOMAIN : [a-zA-Z0-9]+ ('.' [a-zA-Z0-9]+)*; NUMBER : [0-9]+ | [0-9]+ '.' [0-9]+; STRING : '"' ('\\"'|~["])* '"'; NULL : 'null'; ID : [_a-zA-Z][_a-zA-Z0-9]*; //WS : [ \t\n\r]+ -> skip ; WS : [ \t\n\r]+ -> channel(WHITESPACE);
/* generic object-oriented programming language a sample procedure: rtn = foo.bar() a.b.c().d().e.f() a a.b a.b() callback = foo:bar() */ grammar Goo; @lexer::members { public static final int WHITESPACE = 1; public static final int COMMENTS = 2; } //this language don't support class procedure : header block; header : PROCEDURE ID? '(' paramDeclareList? ')'; paramDeclareList : ID (',' ID)*; block : '{' statement* '}'; statement : assignmentStatement | expressionStatement | ifStatement | whileStatement | forStatement | returnStatement | breakStatement | continueStatement | comment | emptyStatement ; emptyStatement : ';'; //varDeclare : 'var' varList; //varList : ID (',' ID)*; expressionStatement : expr ';'; assignmentStatement : assignment ';'; assignment : assignee assignOperator expr; assignOperator : REF_ASSIGN #RefAssignOperator | OWN_ASSIGN #OwnAssignOperator | AUTO_ASSIGN #AutoAssignOperator ; assignee : ID #AssigneeVariable | expr DOT field #AssigneeField ; expr: constant #ConstantExpr | variable #VariableExpr | expr DOT field #AccessField | expr (DOT|DOTDOT) messgeSubject('#'replySubject)? '(' fieldList? ')' #SendMessage ; constant : NUMBER #Number | STRING #String | BOOLEAN #Boolean | NULL #NullValue | link #ObjectLink | procedure #ProcedureConst | object #ObjectConst ; //messageOperator : SYNC_MESSAGE #SyncMessageOperator // | ASYNC_MESSAGE #AsyncMessageOperator // ; link : LINK_PROTOCOL LINK_ADDRESS; object : '{' fieldList? '}'; variable : ID; field : ID #IdField | '$' ID #VarField | STRING #StringField ; messgeSubject : ID #IdMessageSubject | '$' ID #VarMessageSubject | STRING #StringMessageSubject ; replySubject : ID; fieldList : expr (',' expr)* #orderedParamList | nameValue (',' nameValue)* #namedParamList ; nameValue : ID ':' expr; ifStatement : IF '(' expr ')' trueBranch (ELSE falseBranch)?; trueBranch : blockOrStatment; falseBranch: blockOrStatment; whileStatement : WHILE '(' expr ')' blockOrStatment; forStatement : FOR '(' forInit? ';' forCondition ';' forAfterthought? ')' blockOrStatment; forInit: assignment|expr; forCondition : expr; forAfterthought : assignment | expr; blockOrStatment : block | statement; returnStatement : RETURN expr? ';'; breakStatement : BREAK ';'; continueStatement : CONTINUE ';'; comment : LINE_COMMENT | BLOCK_COMMENT; PROCEDURE : 'procedure'; IF : 'if'; ELSE:'else'; WHILE : 'while'; FOR : 'for'; RETURN : 'return'; BOOLEAN : 'true' | 'false'; BREAK: 'break'; CONTINUE : 'continue'; DOT : '.'; DOTDOT : '..'; LINE_COMMENT : '//' .*? '\r'? '\n'; BLOCK_COMMENT : '/*' .*? '*/'; REF_ASSIGN : '->'; OWN_ASSIGN : '=>'; AUTO_ASSIGN: '='| '~>'; //SYNC_MESSAGE : '.'; //ASYNC_MESSAGE : ':'; //LINK : [a-zA-Z0-9]+ '://' [a-zA-Z0-9.]+ '@' [a-zA-Z0-9]+ ('.' [a-zA-Z0-9]+)*; LINK_PROTOCOL : [a-zA-Z0-9]+ '://'; LINK_ADDRESS : ([a-zA-Z0-9._-]+)? '@' [a-zA-Z0-9-]+ ('.' [a-zA-Z0-9-]+)*; //LINK_ID : [a-zA-Z0-9.]+; //LINK_DOMAIN : [a-zA-Z0-9]+ ('.' [a-zA-Z0-9]+)*; NUMBER : [0-9]+ | [0-9]+ '.' [0-9]+; STRING : '"' ('\\"'|~["])* '"'; NULL : 'null'; ID : [_a-zA-Z][_a-zA-Z0-9]*; //WS : [ \t\n\r]+ -> skip ; WS : [ \t\n\r]+ -> channel(WHITESPACE);
change link grammar to support special characters
change link grammar to support special characters
ANTLR
apache-2.0
jackhatedance/visual-programming,jackhatedance/visual-programming
cdb6e1e15f691599b15a4d474952f38c7381a964
src/grammar/RustLexer.g4
src/grammar/RustLexer.g4
lexer grammar RustLexer; @lexer::members { public boolean is_at(int pos) { return _input.index() == pos; } } tokens { EQ, LT, LE, EQEQ, NE, GE, GT, ANDAND, OROR, NOT, TILDE, PLUT, MINUS, STAR, SLASH, PERCENT, CARET, AND, OR, SHL, SHR, BINOP, BINOPEQ, AT, DOT, DOTDOT, DOTDOTDOT, COMMA, SEMI, COLON, MOD_SEP, RARROW, FAT_ARROW, LPAREN, RPAREN, LBRACKET, RBRACKET, LBRACE, RBRACE, POUND, DOLLAR, UNDERSCORE, LIT_CHAR, LIT_INTEGER, LIT_FLOAT, LIT_STR, LIT_STR_RAW, LIT_BINARY, LIT_BINARY_RAW, IDENT, LIFETIME, WHITESPACE, DOC_COMMENT, COMMENT, SHEBANG } import xidstart , xidcontinue; /* Expression-operator symbols */ EQ : '=' ; LT : '<' ; LE : '<=' ; EQEQ : '==' ; NE : '!=' ; GE : '>=' ; GT : '>' ; ANDAND : '&&' ; OROR : '||' ; NOT : '!' ; TILDE : '~' ; PLUS : '+' ; MINUS : '-' ; STAR : '*' ; SLASH : '/' ; PERCENT : '%' ; CARET : '^' ; AND : '&' ; OR : '|' ; SHL : '<<' ; SHR : '>>' ; BINOP : PLUS | SLASH | MINUS | STAR | PERCENT | CARET | AND | OR | SHL | SHR ; BINOPEQ : BINOP EQ ; /* "Structural symbols" */ AT : '@' ; DOT : '.' ; DOTDOT : '..' ; DOTDOTDOT : '...' ; COMMA : ',' ; SEMI : ';' ; COLON : ':' ; MOD_SEP : '::' ; RARROW : '->' ; FAT_ARROW : '=>' ; LPAREN : '(' ; RPAREN : ')' ; LBRACKET : '[' ; RBRACKET : ']' ; LBRACE : '{' ; RBRACE : '}' ; POUND : '#'; DOLLAR : '$' ; UNDERSCORE : '_' ; // Literals fragment HEXIT : [0-9a-fA-F] ; fragment CHAR_ESCAPE : [nrt\\'"0] | [xX] HEXIT HEXIT | 'u' HEXIT HEXIT HEXIT HEXIT | 'U' HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT | 'u{' HEXIT '}' | 'u{' HEXIT HEXIT '}' | 'u{' HEXIT HEXIT HEXIT '}' | 'u{' HEXIT HEXIT HEXIT HEXIT '}' | 'u{' HEXIT HEXIT HEXIT HEXIT HEXIT '}' | 'u{' HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT '}' ; fragment SUFFIX : IDENT ; fragment INTEGER_SUFFIX : { _input.LA(1) != 'e' && _input.LA(1) != 'E' }? SUFFIX ; LIT_CHAR : '\'' ( '\\' CHAR_ESCAPE | ~[\\'\n\t\r] | '\ud800' .. '\udbff' '\udc00' .. '\udfff' ) '\'' SUFFIX? ; LIT_BYTE : 'b\'' ( '\\' ( [xX] HEXIT HEXIT | [nrt\\'"0] ) | ~[\\'\n\t\r] '\udc00'..'\udfff'? ) '\'' SUFFIX? ; LIT_INTEGER : [0-9][0-9_]* INTEGER_SUFFIX? | '0b' [01_]+ INTEGER_SUFFIX? | '0o' [0-7_]+ INTEGER_SUFFIX? | '0x' [0-9a-fA-F_]+ INTEGER_SUFFIX? ; LIT_FLOAT : [0-9][0-9_]* ('.' { /* dot followed by another dot is a range, not a float */ _input.LA(1) != '.' && /* dot followed by an identifier is an integer with a function call, not a float */ _input.LA(1) != '_' && !(_input.LA(1) >= 'a' && _input.LA(1) <= 'z') && !(_input.LA(1) >= 'A' && _input.LA(1) <= 'Z') }? | ('.' [0-9][0-9_]*)? ([eE] [-+]? [0-9][0-9_]*)? SUFFIX?) ; LIT_STR : '"' ('\\\n' | '\\\r\n' | '\\' CHAR_ESCAPE | .)*? '"' SUFFIX? ; LIT_BINARY : 'b' LIT_STR ; LIT_BINARY_RAW : 'b' LIT_STR_RAW ; /* this is a bit messy */ fragment LIT_STR_RAW_INNER : '"' .*? '"' | LIT_STR_RAW_INNER2 ; fragment LIT_STR_RAW_INNER2 : POUND LIT_STR_RAW_INNER POUND ; LIT_STR_RAW : 'r' LIT_STR_RAW_INNER SUFFIX? ; QUESTION : '?'; IDENT : XID_Start XID_Continue* ; fragment QUESTION_IDENTIFIER : QUESTION? IDENT; LIFETIME : '\'' IDENT ; WHITESPACE : [ \r\n\t]+ ; UNDOC_COMMENT : '////' ~[\n]* -> type(COMMENT) ; YESDOC_COMMENT : '///' ~[\r\n]* -> type(DOC_COMMENT) ; OUTER_DOC_COMMENT : '//!' ~[\r\n]* -> type(DOC_COMMENT) ; LINE_COMMENT : '//' ( ~[/\n] ~[\n]* )? -> type(COMMENT) ; DOC_BLOCK_COMMENT : ('/**' ~[*] | '/*!') (DOC_BLOCK_COMMENT | .)*? '*/' -> type(DOC_COMMENT) ; BLOCK_COMMENT : '/*' (BLOCK_COMMENT | .)*? '*/' -> type(COMMENT) ; /* these appear at the beginning of a file */ SHEBANG : '#!' { is_at(2) && _input.LA(1) != '[' }? ~[\r\n]* -> type(SHEBANG) ; UTF8_BOM : '\ufeff' { is_at(1) }? -> skip ;
lexer grammar RustLexer; @lexer::members { public boolean is_at(int pos) { return _input.index() == pos; } } tokens { EQ, LT, LE, EQEQ, NE, GE, GT, ANDAND, OROR, NOT, TILDE, PLUS, MINUS, STAR, SLASH, PERCENT, CARET, AND, OR, SHL, SHR, BINOP, BINOPEQ, AT, DOT, DOTDOT, DOTDOTDOT, COMMA, SEMI, COLON, MOD_SEP, RARROW, FAT_ARROW, LPAREN, RPAREN, LBRACKET, RBRACKET, LBRACE, RBRACE, POUND, DOLLAR, UNDERSCORE, LIT_CHAR, LIT_INTEGER, LIT_FLOAT, LIT_STR, LIT_STR_RAW, LIT_BINARY, LIT_BINARY_RAW, IDENT, LIFETIME, WHITESPACE, DOC_COMMENT, COMMENT, SHEBANG } import xidstart , xidcontinue; /* Expression-operator symbols */ EQ : '=' ; LT : '<' ; LE : '<=' ; EQEQ : '==' ; NE : '!=' ; GE : '>=' ; GT : '>' ; ANDAND : '&&' ; OROR : '||' ; NOT : '!' ; TILDE : '~' ; PLUS : '+' ; MINUS : '-' ; STAR : '*' ; SLASH : '/' ; PERCENT : '%' ; CARET : '^' ; AND : '&' ; OR : '|' ; SHL : '<<' ; SHR : '>>' ; BINOP : PLUS | SLASH | MINUS | STAR | PERCENT | CARET | AND | OR | SHL | SHR ; BINOPEQ : BINOP EQ ; /* "Structural symbols" */ AT : '@' ; DOT : '.' ; DOTDOT : '..' ; DOTDOTDOT : '...' ; COMMA : ',' ; SEMI : ';' ; COLON : ':' ; MOD_SEP : '::' ; RARROW : '->' ; FAT_ARROW : '=>' ; LPAREN : '(' ; RPAREN : ')' ; LBRACKET : '[' ; RBRACKET : ']' ; LBRACE : '{' ; RBRACE : '}' ; POUND : '#'; DOLLAR : '$' ; UNDERSCORE : '_' ; // Literals fragment HEXIT : [0-9a-fA-F] ; fragment CHAR_ESCAPE : [nrt\\'"0] | [xX] HEXIT HEXIT | 'u' HEXIT HEXIT HEXIT HEXIT | 'U' HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT | 'u{' HEXIT '}' | 'u{' HEXIT HEXIT '}' | 'u{' HEXIT HEXIT HEXIT '}' | 'u{' HEXIT HEXIT HEXIT HEXIT '}' | 'u{' HEXIT HEXIT HEXIT HEXIT HEXIT '}' | 'u{' HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT '}' ; fragment SUFFIX : IDENT ; fragment INTEGER_SUFFIX : { _input.LA(1) != 'e' && _input.LA(1) != 'E' }? SUFFIX ; LIT_CHAR : '\'' ( '\\' CHAR_ESCAPE | ~[\\'\n\t\r] | '\ud800' .. '\udbff' '\udc00' .. '\udfff' ) '\'' SUFFIX? ; LIT_BYTE : 'b\'' ( '\\' ( [xX] HEXIT HEXIT | [nrt\\'"0] ) | ~[\\'\n\t\r] '\udc00'..'\udfff'? ) '\'' SUFFIX? ; LIT_INTEGER : [0-9][0-9_]* INTEGER_SUFFIX? | '0b' [01_]+ INTEGER_SUFFIX? | '0o' [0-7_]+ INTEGER_SUFFIX? | '0x' [0-9a-fA-F_]+ INTEGER_SUFFIX? ; LIT_FLOAT : [0-9][0-9_]* ('.' { /* dot followed by another dot is a range, not a float */ _input.LA(1) != '.' && /* dot followed by an identifier is an integer with a function call, not a float */ _input.LA(1) != '_' && !(_input.LA(1) >= 'a' && _input.LA(1) <= 'z') && !(_input.LA(1) >= 'A' && _input.LA(1) <= 'Z') }? | ('.' [0-9][0-9_]*)? ([eE] [-+]? [0-9][0-9_]*)? SUFFIX?) ; LIT_STR : '"' ('\\\n' | '\\\r\n' | '\\' CHAR_ESCAPE | .)*? '"' SUFFIX? ; LIT_BINARY : 'b' LIT_STR ; LIT_BINARY_RAW : 'b' LIT_STR_RAW ; /* this is a bit messy */ fragment LIT_STR_RAW_INNER : '"' .*? '"' | LIT_STR_RAW_INNER2 ; fragment LIT_STR_RAW_INNER2 : POUND LIT_STR_RAW_INNER POUND ; LIT_STR_RAW : 'r' LIT_STR_RAW_INNER SUFFIX? ; QUESTION : '?'; IDENT : XID_Start XID_Continue* ; fragment QUESTION_IDENTIFIER : QUESTION? IDENT; LIFETIME : '\'' IDENT ; WHITESPACE : [ \r\n\t]+ ; UNDOC_COMMENT : '////' ~[\n]* -> type(COMMENT) ; YESDOC_COMMENT : '///' ~[\r\n]* -> type(DOC_COMMENT) ; OUTER_DOC_COMMENT : '//!' ~[\r\n]* -> type(DOC_COMMENT) ; LINE_COMMENT : '//' ( ~[/\n] ~[\n]* )? -> type(COMMENT) ; DOC_BLOCK_COMMENT : ('/**' ~[*] | '/*!') (DOC_BLOCK_COMMENT | .)*? '*/' -> type(DOC_COMMENT) ; BLOCK_COMMENT : '/*' (BLOCK_COMMENT | .)*? '*/' -> type(COMMENT) ; /* these appear at the beginning of a file */ SHEBANG : '#!' { is_at(2) && _input.LA(1) != '[' }? ~[\r\n]* -> type(SHEBANG) ; UTF8_BOM : '\ufeff' { is_at(1) }? -> skip ;
Correct a typo in a declared token in the reference grammar
Correct a typo in a declared token in the reference grammar This appears to not have too much of a detrimental effect, but it doesn't seem to be what is intended either. antlr doesn't mind that `PLUS` isn't declared in `tokens` and happily uses the `PLUS` that appears later in the file, but the generated RustLexer.tokens had PLUS at the end rather than where it was intended: NOT=10 TILDE=11 PLUT=12 MINUS=13 ... PLUS=56
ANTLR
apache-2.0
rohitjoshi/rust,aidancully/rust,aepsil0n/rust,carols10cents/rust,dwillmer/rust,pshc/rust,vhbit/rust,zubron/rust,pshc/rust,kwantam/rust,aidancully/rust,dwillmer/rust,krzysz00/rust,krzysz00/rust,KokaKiwi/rust,ejjeong/rust,pelmers/rust,mihneadb/rust,vhbit/rust,rohitjoshi/rust,mdinger/rust,graydon/rust,aneeshusa/rust,andars/rust,robertg/rust,dwillmer/rust,nwin/rust,TheNeikos/rust,zubron/rust,zachwick/rust,omasanori/rust,vhbit/rust,graydon/rust,jashank/rust,zubron/rust,sae-bom/rust,ejjeong/rust,cllns/rust,jashank/rust,pshc/rust,krzysz00/rust,kwantam/rust,zubron/rust,reem/rust,TheNeikos/rust,GBGamer/rust,jroesch/rust,philyoon/rust,jashank/rust,l0kod/rust,l0kod/rust,jashank/rust,gifnksm/rust,reem/rust,graydon/rust,GBGamer/rust,zachwick/rust,jroesch/rust,gifnksm/rust,cllns/rust,victorvde/rust,philyoon/rust,reem/rust,victorvde/rust,omasanori/rust,kwantam/rust,TheNeikos/rust,mvdnes/rust,pshc/rust,rohitjoshi/rust,rohitjoshi/rust,vhbit/rust,ejjeong/rust,nwin/rust,sae-bom/rust,l0kod/rust,ejjeong/rust,krzysz00/rust,mihneadb/rust,zachwick/rust,mihneadb/rust,zubron/rust,aneeshusa/rust,mdinger/rust,mvdnes/rust,jroesch/rust,mihneadb/rust,jroesch/rust,rohitjoshi/rust,nwin/rust,aneeshusa/rust,reem/rust,XMPPwocky/rust,philyoon/rust,l0kod/rust,vhbit/rust,XMPPwocky/rust,andars/rust,pshc/rust,seanrivera/rust,rohitjoshi/rust,kwantam/rust,philyoon/rust,aepsil0n/rust,victorvde/rust,victorvde/rust,pelmers/rust,KokaKiwi/rust,aneeshusa/rust,andars/rust,mdinger/rust,nwin/rust,vhbit/rust,cllns/rust,seanrivera/rust,zubron/rust,philyoon/rust,pshc/rust,andars/rust,gifnksm/rust,l0kod/rust,omasanori/rust,dwillmer/rust,KokaKiwi/rust,XMPPwocky/rust,jroesch/rust,omasanori/rust,GBGamer/rust,robertg/rust,robertg/rust,robertg/rust,pelmers/rust,victorvde/rust,sae-bom/rust,aidancully/rust,sae-bom/rust,jroesch/rust,nwin/rust,GBGamer/rust,robertg/rust,vhbit/rust,seanrivera/rust,jashank/rust,cllns/rust,GBGamer/rust,pelmers/rust,graydon/rust,aidancully/rust,GBGamer/rust,kwantam/rust,l0kod/rust,kwantam/rust,ejjeong/rust,GBGamer/rust,mvdnes/rust,victorvde/rust,seanrivera/rust,aepsil0n/rust,carols10cents/rust,XMPPwocky/rust,jroesch/rust,mihneadb/rust,aidancully/rust,pshc/rust,XMPPwocky/rust,zachwick/rust,gifnksm/rust,aneeshusa/rust,pshc/rust,jashank/rust,carols10cents/rust,mdinger/rust,krzysz00/rust,nwin/rust,aepsil0n/rust,aidancully/rust,KokaKiwi/rust,graydon/rust,mvdnes/rust,TheNeikos/rust,philyoon/rust,gifnksm/rust,jashank/rust,carols10cents/rust,carols10cents/rust,cllns/rust,zachwick/rust,l0kod/rust,sae-bom/rust,pelmers/rust,KokaKiwi/rust,dwillmer/rust,mvdnes/rust,aepsil0n/rust,aepsil0n/rust,dwillmer/rust,robertg/rust,mihneadb/rust,GBGamer/rust,dwillmer/rust,TheNeikos/rust,reem/rust,l0kod/rust,mvdnes/rust,seanrivera/rust,krzysz00/rust,omasanori/rust,mdinger/rust,cllns/rust,zubron/rust,TheNeikos/rust,omasanori/rust,nwin/rust,gifnksm/rust,dwillmer/rust,andars/rust,carols10cents/rust,nwin/rust,vhbit/rust,andars/rust,reem/rust,ejjeong/rust,sae-bom/rust,pelmers/rust,seanrivera/rust,jashank/rust,graydon/rust,XMPPwocky/rust,zachwick/rust,aneeshusa/rust,KokaKiwi/rust,mdinger/rust,jroesch/rust,zubron/rust
527fa93f5a6e11a5218201d13dc329853df8c83a
terraform/terraform.g4
terraform/terraform.g4
/* BSD License Copyright (c) 2020, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar terraform; file : (local | module | output | provider | variable | data | resource | terraform)+ ; terraform : 'terraform' blockbody ; resource : 'resource' resourcetype name blockbody ; data : 'data' resourcetype name blockbody ; provider : 'provider' resourcetype blockbody ; output : 'output' name blockbody ; local : 'locals' blockbody ; module : 'module' name blockbody ; variable : VARIABLE name blockbody ; block : blocktype label* blockbody ; blocktype : IDENTIFIER ; resourcetype : STRING ; name : STRING ; label : STRING ; blockbody : LCURL (argument | block)* RCURL ; argument : identifier '=' expression ; identifier : (('local' | 'data' | 'var' | 'module') DOT)? identifierchain ; identifierchain : (IDENTIFIER | IN | VARIABLE) index? (DOT identifierchain)* | STAR (DOT identifierchain)* | inline_index (DOT identifierchain)* ; inline_index : NATURAL_NUMBER ; expression : section | expression operator expression | LPAREN expression RPAREN | expression '?' expression ':' expression | forloop ; forloop : 'for' identifier IN expression ':' expression ; section : list | map | val ; val : NULL | signed_number | string | identifier | BOOL | DESCRIPTION | filedecl | functioncall | EOF_ ; functioncall : functionname LPAREN functionarguments RPAREN ; functionname : IDENTIFIER ; functionarguments : //no arguments | expression (',' expression)* ; index : '[' expression ']' ; filedecl : 'file' '(' expression ')' ; list : '[' (expression (',' expression)* ','?)? ']' ; map : LCURL (argument ','?)* RCURL ; string : STRING | MULTILINESTRING ; fragment DIGIT : [0-9] ; signed_number : '+' number | '-' number | number ; VARIABLE : 'variable' ; IN : 'in' ; STAR : '*' ; DOT : '.' ; operator : '/' | STAR | '%' | '+' | '-' | '>' | '>=' | '<' | '<=' | '==' | '!=' | '&&' | '||' ; LCURL : '{' ; RCURL : '}' ; LPAREN : '(' ; RPAREN : ')' ; EOF_ : '<<EOF' .*? 'EOF' ; NULL : 'nul' ; NATURAL_NUMBER : DIGIT+ ; number : NATURAL_NUMBER (DOT NATURAL_NUMBER)? ; BOOL : 'true' | 'false' ; DESCRIPTION : '<<DESCRIPTION' .*? 'DESCRIPTION' ; MULTILINESTRING : '<<-EOF' .*? 'EOF' ; STRING : '"' (~ [\r\n"] | '""' | '\\"')* '"' ; IDENTIFIER : [a-zA-Z] ([a-zA-Z0-9_-])* ; COMMENT : ('#' | '//') ~ [\r\n]* -> channel(HIDDEN) ; BLOCKCOMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; WS : [ \r\n\t]+ -> skip ;
/* BSD License Copyright (c) 2020, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar terraform; file : (local | module | output | provider | variable | data | resource | terraform)+ ; terraform : 'terraform' blockbody ; resource : 'resource' resourcetype name blockbody ; data : 'data' resourcetype name blockbody ; provider : 'provider' resourcetype blockbody ; output : 'output' name blockbody ; local : 'locals' blockbody ; module : 'module' name blockbody ; variable : VARIABLE name blockbody ; block : blocktype label* blockbody ; blocktype : IDENTIFIER ; resourcetype : STRING ; name : STRING ; label : STRING ; blockbody : LCURL (argument | block)* RCURL ; argument : identifier '=' expression ; identifier : (('local' | 'data' | 'var' | 'module') DOT)? identifierchain ; identifierchain : (IDENTIFIER | IN | VARIABLE) index? (DOT identifierchain)* | STAR (DOT identifierchain)* | inline_index (DOT identifierchain)* ; inline_index : NATURAL_NUMBER ; expression : section | expression operator expression | LPAREN expression RPAREN | expression '?' expression ':' expression | forloop ; forloop : 'for' identifier IN expression ':' expression ; section : list | map | val ; val : NULL | signed_number | string | identifier | BOOL | DESCRIPTION | filedecl | functioncall | EOF_ ; functioncall : functionname LPAREN functionarguments RPAREN ; functionname : IDENTIFIER ; functionarguments : //no arguments | expression (',' expression)* ; index : '[' expression ']' ; filedecl : 'file' '(' expression ')' ; list : '[' (expression (',' expression)* ','?)? ']' ; map : LCURL (argument ','?)* RCURL ; string : STRING | MULTILINESTRING ; fragment DIGIT : [0-9] ; signed_number : ('+' | '-')? number ; VARIABLE : 'variable' ; IN : 'in' ; STAR : '*' ; DOT : '.' ; operator : '/' | STAR | '%' | '+' | '-' | '>' | '>=' | '<' | '<=' | '==' | '!=' | '&&' | '||' ; LCURL : '{' ; RCURL : '}' ; LPAREN : '(' ; RPAREN : ')' ; EOF_ : '<<EOF' .*? 'EOF' ; NULL : 'nul' ; NATURAL_NUMBER : DIGIT+ ; number : NATURAL_NUMBER (DOT NATURAL_NUMBER)? ; BOOL : 'true' | 'false' ; DESCRIPTION : '<<DESCRIPTION' .*? 'DESCRIPTION' ; MULTILINESTRING : '<<-EOF' .*? 'EOF' ; STRING : '"' (~ [\r\n"] | '""' | '\\"')* '"' ; IDENTIFIER : [a-zA-Z] ([a-zA-Z0-9_-])* ; COMMENT : ('#' | '//') ~ [\r\n]* -> channel(HIDDEN) ; BLOCKCOMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; WS : [ \r\n\t]+ -> skip ;
Improve readability
Improve readability
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
f3d8ed1bea614dd2756d047bcc8e6bc57fc53275
src/main/antlr4/com/kodcu/lang/Query.g4
src/main/antlr4/com/kodcu/lang/Query.g4
grammar Query; /** * Created by HAKAN on 26/06/2015. */ query : queryDeclaration EOF ; queryDeclaration : queryTag dataLocation dataset ; queryTag : tag=(EXPORT|TRANSFER|COPY) ; dataLocation : databaseName '/' collectionName ; databaseName : IDENTIFIER ; collectionName : IDENTIFIER ; dataset : fromDeclaration toDeclaration (andDeclaration)? ; fromDeclaration : FROM declarations ; toDeclaration : TO declarations ; andDeclaration : AND declarations ; declarations : mongoDeclaration | fileDeclaration | esDeclaration ; mongoDeclaration : MONGO '=' configuration ; fileDeclaration : FILE '=' fileConfiguration ; esDeclaration : ES '=' configuration ; fileConfiguration : '{' NAME ':' STRINGLITERAL '}' ; configuration : '{' property (',' property)* '}' ; property : key ':' value ; key : HOST | PORT ; value : IDENTIFIER | STRINGLITERAL | NUMBER ; // LEXER // KEYWORDS TO : 'to'|'TO'; ES : 'es'|'ES'; AND : 'and'|'AND'; FROM : 'from'|'FROM'; HOST : 'host'|'HOST'; PORT : 'port'|'PORT'; NAME : 'name'|'NAME'; FILE : 'file'|'FILE'; COPY : 'copy'|'COPY'; MONGO : 'mongo'|'MONGO'; EXPORT : 'export'|'EXPORT'; TRANSFER : 'transfer'|'TRANSPORT'; STRINGLITERAL : '"' .*? '"' ; NUMBER : [0-9]+ ; IDENTIFIER : [a-zA-Z_] [a-zA-Z_0-9]* ; LINE_COMMENT : '//' ~[\r\n]* -> skip ; SPACES : [ \t\r\n]+ -> skip ;
grammar Query; /** * Created by HAKAN on 26/06/2015. */ query : queryDeclaration EOF ; queryDeclaration : queryTag dataLocation dataset ; queryTag : tag=(EXPORT|TRANSFER|COPY) ; dataLocation : databaseName '/' collectionName ; databaseName : IDENTIFIER ; collectionName : IDENTIFIER ; dataset : fromDeclaration toDeclaration (andDeclaration)? ; fromDeclaration : FROM declarations ; toDeclaration : TO fileDeclaration ; andDeclaration : AND declarations ; declarations : mongoDeclaration | esDeclaration ; mongoDeclaration : MONGO '=' configuration ; fileDeclaration : FILE '=' fileConfiguration ; esDeclaration : ES '=' configuration ; fileConfiguration : '{' NAME ':' STRINGLITERAL '}' ; configuration : '{' property (',' property)* '}' ; property : key ':' value ; key : HOST | PORT ; value : IDENTIFIER | STRINGLITERAL | NUMBER ; // LEXER // KEYWORDS TO : 'to'|'TO'; ES : 'es'|'ES'; AND : 'and'|'AND'; FROM : 'from'|'FROM'; HOST : 'host'|'HOST'; PORT : 'port'|'PORT'; NAME : 'name'|'NAME'; FILE : 'file'|'FILE'; COPY : 'copy'|'COPY'; MONGO : 'mongo'|'MONGO'; EXPORT : 'export'|'EXPORT'; TRANSFER : 'transfer'|'TRANSPORT'; STRINGLITERAL : '"' .*? '"' ; NUMBER : [0-9]+ ; IDENTIFIER : [a-zA-Z_] [a-zA-Z_0-9]* ; LINE_COMMENT : '//' ~[\r\n]* -> skip ; SPACES : [ \t\r\n]+ -> skip ;
Update query grammar
Update query grammar
ANTLR
mit
ozlerhakan/mongolastic
25b1539060bfddef979b7f12106f04e0c23a2606
mapping/core/src/main/antlr4/it/unibz/inf/ontop/spec/mapping/parser/impl/TurtleOBDA.g4
mapping/core/src/main/antlr4/it/unibz/inf/ontop/spec/mapping/parser/impl/TurtleOBDA.g4
/* * #%L * ontop-obdalib-core * %% * Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /* This grammar is adapted from https://github.com/antlr/grammars-v4/tree/master/turtle, derived in turn from http://www.w3.org/TR/turtle/#sec-grammar-grammar, with the following copywright: [The "BSD licence"] Copyright (c) 2014, Alejandro Medrano (@ Universidad Politecnica de Madrid, http://www.upm.es/) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES */ grammar TurtleOBDA; /* Source files (Parser, Visitor, ...) are generated by the ANTLR4 Maven Plugin, during the Maven generate-sources phase. If src/main/<subPath>/TurtleOBDA.g4 is the path to this file, then the source files are generated in target/generated-sources/antlr4/<subPath> */ /*------------------------------------------------------------------ * PARSER RULES *------------------------------------------------------------------*/ parse : directiveStatement* triplesStatement+ EOF ; directiveStatement : directive '.' ; triplesStatement : triples '.' | quads '.' ; directive : base | prefixID ; prefixID : ('@prefix' | '@PREFIX') PNAME_NS IRIREF ; base : ('@base' | '@BASE') IRIREF ; quads : 'GRAPH' graph '{' triples+ '}' triples : subject predicateObjectList ; predicateObjectList : predicateObject (';' predicateObject)* ; predicateObject : verb objectList ; objectList : object (',' object)* ; verb : resource | 'a' ; graph : resource | variable | blank ; subject : resource | variable | blank ; object : resource | blank | literal | variableLiteral | variable ; resource : iri | iriExt ; iriExt : IRIREF_EXT | PREFIXED_NAME_EXT ; blank : BLANK_NODE_FUNCTION | BLANK_NODE_LABEL | ANON ; variable : STRING_WITH_CURLY_BRACKET ; variableLiteral : variable languageTag # variableLiteral_1 | variable '^^' iri # variableLiteral_2 ; languageTag : LANGTAG | '@' variable ; iri : IRIREF | PREFIXED_NAME ; literal : typedLiteral | untypedStringLiteral | untypedNumericLiteral | untypedBooleanLiteral ; untypedStringLiteral : litString (languageTag)? ; typedLiteral : litString '^^' iri ; litString : STRING_LITERAL_QUOTE // : STRING_WITH_QUOTE_DOUBLE ; untypedNumericLiteral : numericUnsigned | numericPositive | numericNegative ; untypedBooleanLiteral : BOOLEAN_LITERAL ; numericUnsigned : INTEGER | DOUBLE | DECIMAL ; numericPositive : INTEGER_POSITIVE | DOUBLE_POSITIVE | DECIMAL_POSITIVE ; numericNegative : INTEGER_NEGATIVE | DOUBLE_NEGATIVE | DECIMAL_NEGATIVE ; WS : ([\t\r\n\u000C] | ' ') + -> skip ; /*------------------------------------------------------------------ * LEXER RULES Applied for tokenization (before parsing), regardless of parser rules, as follows: - The rule matching the longest substring is applied - If there are several of them, the first one is applied *------------------------------------------------------------------*/ STRING_WITH_CURLY_BRACKET : '{' VARIABLE_CHAR+ '}' ; BOOLEAN_LITERAL : 'true' | 'TRUE' | 'True' | 'false'| 'FALSE'| 'False' ; // extends IRIREF to allow curly brackets, and forces one curly bracket IRIREF_EXT : '<' IRIREF_INNER_CHAR_EXT* '{' IRIREF_INNER_CHAR_EXT+ '>' ; IRIREF : '<' IRIREF_INNER_CHAR* '>' ; PNAME_NS : PN_PREFIX? ':' ; PN_PREFIX : PN_CHARS_BASE ((PN_CHARS | '.')* PN_CHARS)? ; PREFIXED_NAME : PNAME_NS PN_LOCAL ; // extends PREFIXED_NAME to allow right-hand side curly brackets, and force one right-hand side opening curly bracket PREFIXED_NAME_EXT : PNAME_NS PN_LOCAL_EXT ; // specific syntax for blank nodes with variables BLANK_NODE_FUNCTION : '_:' PN_LOCAL_EXT ; BLANK_NODE_LABEL : '_:' (PN_CHARS_U | [0-9]) ((PN_CHARS | '.')* PN_CHARS )? ; LANGTAG : '@' [a-zA-Z] + ('-' [a-zA-Z0-9] +)* ; INTEGER : [0-9] + ; DECIMAL : [0-9]* '.' [0-9] + ; DOUBLE : ([0-9] + '.' [0-9]* EXPONENT | '.' [0-9] + EXPONENT | [0-9] + EXPONENT) ; EXPONENT : [eE] [+-]? [0-9] + ; INTEGER_POSITIVE : '+' INTEGER ; INTEGER_NEGATIVE : '-' INTEGER ; DOUBLE_POSITIVE : '+' DOUBLE ; DOUBLE_NEGATIVE : '-' DOUBLE ; DECIMAL_POSITIVE : '+' DECIMAL ; DECIMAL_NEGATIVE : '-' DECIMAL ; // not used STRING_LITERAL_LONG_SINGLE_QUOTE : '\'\'\'' (('\'' | '\'\'')? ([^'\\] | ECHAR | UCHAR | '"'))* '\'\'\'' ; // not used STRING_LITERAL_LONG_QUOTE : '"""' (('"' | '""')? (~ ["\\] | ECHAR | UCHAR | '\''))* '"""' ; // extends STRING_LITERAL_QUOTE in the original grammar to allow curly brackets, space and escaped characters STRING_LITERAL_QUOTE : '"' (~ ["\\\r\n] | '\'' | '\\"' | '{' | '}' | ' ' | ECHAR)* '"' ; /* orginal version: STRING_LITERAL_QUOTE : '"' (~ ["\\\r\n] | '\'' | '\\"')* '"' ; */ // not used STRING_LITERAL_SINGLE_QUOTE : '\'' (~ [\u0027\u005C\u000A\u000D] | ECHAR | UCHAR | '"')* '\'' ; UCHAR : '\\u' HEX HEX HEX HEX | '\\U' HEX HEX HEX HEX HEX HEX HEX HEX ; ECHAR : '\\' [tbnrf"'\\] ; ANON_WS : ' ' | '\t' | '\r' | '\n' ; ANON : '[' ANON_WS* ']' ; PN_CHARS_BASE : 'A' .. 'Z' | 'a' .. 'z' | '\u00C0' .. '\u00D6' | '\u00D8' .. '\u00F6' | '\u00F8' .. '\u02FF' | '\u0370' .. '\u037D' | '\u037F' .. '\u1FFF' | '\u200C' .. '\u200D' | '\u2070' .. '\u218F' | '\u2C00' .. '\u2FEF' | '\u3001' .. '\uD7FF' | '\uF900' .. '\uFDCF' | '\uFDF0' .. '\uFFFD' // Limitation: Unicode Characters beyond \uFFFF are not (yet?) supported by ANTLR // | '\u10000' .. '\u1FFFD' | '\u20000' .. '\u2FFFD' | // '\u30000' .. '\u3FFFD' | '\u40000' .. '\u4FFFD' | '\u50000' .. '\u5FFFD' | '\u60000' .. '\u6FFFD' | // '\u70000' .. '\u7FFFD' | '\u80000' .. '\u8FFFD' | '\u90000' .. '\u9FFFD' | '\uA0000' .. '\uAFFFD' | // '\uB0000' .. '\uBFFFD' | '\uC0000' .. '\uCFFFD' | '\uD0000' .. '\uDFFFD' | '\uE1000' .. '\uEFFFD' ; PN_CHARS_U : PN_CHARS_BASE | '_' ; PN_CHARS : PN_CHARS_U | '-' | [0-9] | '\u00B7' | [\u0300-\u036F] | [\u203F-\u2040] | '?' | '=' ; // extends PN_LOCAL to allow curly brackets, and force at least one (opening) curly bracket PN_LOCAL_EXT : '{' RIGHT_PART_TAIL_EXT + | RIGHT_PART_FIRST_CHAR RIGHT_PART_TAIL_EXT_MAND ; // extends PN_LOCAL in the original grammar to allow '/' and '#' PN_LOCAL : RIGHT_PART_FIRST_CHAR RIGHT_PART_TAIL? ; PLX : PERCENT | PN_LOCAL_ESC ; PERCENT : '%' HEX HEX ; HEX : [0-9] | [A-F] | [a-f] ; // RDF-specific: the backslash (first character) is ignored when parsing the IRI PN_LOCAL_ESC : '\\' ('_' | '~' | '.' | '-' | '!' | '$' | '&' | '\'' | '(' | ')' | '*' | '+' | ',' | ';' | '=' | '/' | '?' | '#' | '@' | '%') ; fragment RIGHT_PART_FIRST_CHAR : (PN_CHARS_U | ':' | '#' | [0-9] | PLX) ; fragment RIGHT_PART_FIRST_CHAR_EXT : (RIGHT_PART_FIRST_CHAR | '{') ; fragment RIGHT_PART_CHAR : (PN_CHARS | '.' | ':' | '/' | '#' | ';' | PLX) ; fragment RIGHT_PART_CHAR_EXT : (RIGHT_PART_CHAR | '{' | '}') ; fragment RIGHT_PART_END_CHAR : (PN_CHARS | ':' | '/'| PLX) ; fragment RIGHT_PART_END_CHAR_EXT : (RIGHT_PART_END_CHAR | '}') ; fragment RIGHT_PART_TAIL : RIGHT_PART_CHAR* RIGHT_PART_END_CHAR ; fragment RIGHT_PART_TAIL_EXT : RIGHT_PART_CHAR_EXT* RIGHT_PART_END_CHAR_EXT ; fragment RIGHT_PART_TAIL_EXT_MAND : RIGHT_PART_CHAR_EXT* '{' RIGHT_PART_CHAR_EXT* RIGHT_PART_END_CHAR_EXT ; fragment IRIREF_INNER_CHAR : (PN_CHARS | '.' | ':' | '/' | '\\' | '#' | '@' | '%' | '&' | ';' | UCHAR) ; fragment IRIREF_INNER_CHAR_EXT : (IRIREF_INNER_CHAR | '{' | '}') ; fragment VARIABLE_CHAR : (PN_CHARS | '.' | ':' | '/' | '\\' | '#' | '%' | '&' | '$' | UCHAR) ;
/* * #%L * ontop-obdalib-core * %% * Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /* This grammar is adapted from https://github.com/antlr/grammars-v4/tree/master/turtle, derived in turn from http://www.w3.org/TR/turtle/#sec-grammar-grammar, with the following copywright: [The "BSD licence"] Copyright (c) 2014, Alejandro Medrano (@ Universidad Politecnica de Madrid, http://www.upm.es/) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES */ grammar TurtleOBDA; /* Source files (Parser, Visitor, ...) are generated by the ANTLR4 Maven Plugin, during the Maven generate-sources phase. If src/main/<subPath>/TurtleOBDA.g4 is the path to this file, then the source files are generated in target/generated-sources/antlr4/<subPath> */ /*------------------------------------------------------------------ * PARSER RULES *------------------------------------------------------------------*/ parse : directiveStatement* triplesStatement+ EOF ; directiveStatement : directive '.' ; triplesStatement : triples '.' | quads '.' ; directive : base | prefixID ; prefixID : ('@prefix' | '@PREFIX') PNAME_NS IRIREF ; base : ('@base' | '@BASE') IRIREF ; quads : 'GRAPH' graph '{' triples+ '}' ; triples : subject predicateObjectList ; predicateObjectList : predicateObject (';' predicateObject)* ; predicateObject : verb objectList ; objectList : object (',' object)* ; verb : resource | 'a' ; graph : resource | variable | blank ; subject : resource | variable | blank ; object : resource | blank | literal | variableLiteral | variable ; resource : iri | iriExt ; iriExt : IRIREF_EXT | PREFIXED_NAME_EXT ; blank : BLANK_NODE_FUNCTION | BLANK_NODE_LABEL | ANON ; variable : STRING_WITH_CURLY_BRACKET ; variableLiteral : variable languageTag # variableLiteral_1 | variable '^^' iri # variableLiteral_2 ; languageTag : LANGTAG | '@' variable ; iri : IRIREF | PREFIXED_NAME ; literal : typedLiteral | untypedStringLiteral | untypedNumericLiteral | untypedBooleanLiteral ; untypedStringLiteral : litString (languageTag)? ; typedLiteral : litString '^^' iri ; litString : STRING_LITERAL_QUOTE // : STRING_WITH_QUOTE_DOUBLE ; untypedNumericLiteral : numericUnsigned | numericPositive | numericNegative ; untypedBooleanLiteral : BOOLEAN_LITERAL ; numericUnsigned : INTEGER | DOUBLE | DECIMAL ; numericPositive : INTEGER_POSITIVE | DOUBLE_POSITIVE | DECIMAL_POSITIVE ; numericNegative : INTEGER_NEGATIVE | DOUBLE_NEGATIVE | DECIMAL_NEGATIVE ; WS : ([\t\r\n\u000C] | ' ') + -> skip ; /*------------------------------------------------------------------ * LEXER RULES Applied for tokenization (before parsing), regardless of parser rules, as follows: - The rule matching the longest substring is applied - If there are several of them, the first one is applied *------------------------------------------------------------------*/ STRING_WITH_CURLY_BRACKET : '{' VARIABLE_CHAR+ '}' ; BOOLEAN_LITERAL : 'true' | 'TRUE' | 'True' | 'false'| 'FALSE'| 'False' ; // extends IRIREF to allow curly brackets, and forces one curly bracket IRIREF_EXT : '<' IRIREF_INNER_CHAR_EXT* '{' IRIREF_INNER_CHAR_EXT+ '>' ; IRIREF : '<' IRIREF_INNER_CHAR* '>' ; PNAME_NS : PN_PREFIX? ':' ; PN_PREFIX : PN_CHARS_BASE ((PN_CHARS | '.')* PN_CHARS)? ; PREFIXED_NAME : PNAME_NS PN_LOCAL ; // extends PREFIXED_NAME to allow right-hand side curly brackets, and force one right-hand side opening curly bracket PREFIXED_NAME_EXT : PNAME_NS PN_LOCAL_EXT ; // specific syntax for blank nodes with variables BLANK_NODE_FUNCTION : '_:' PN_LOCAL_EXT ; BLANK_NODE_LABEL : '_:' (PN_CHARS_U | [0-9]) ((PN_CHARS | '.')* PN_CHARS )? ; LANGTAG : '@' [a-zA-Z] + ('-' [a-zA-Z0-9] +)* ; INTEGER : [0-9] + ; DECIMAL : [0-9]* '.' [0-9] + ; DOUBLE : ([0-9] + '.' [0-9]* EXPONENT | '.' [0-9] + EXPONENT | [0-9] + EXPONENT) ; EXPONENT : [eE] [+-]? [0-9] + ; INTEGER_POSITIVE : '+' INTEGER ; INTEGER_NEGATIVE : '-' INTEGER ; DOUBLE_POSITIVE : '+' DOUBLE ; DOUBLE_NEGATIVE : '-' DOUBLE ; DECIMAL_POSITIVE : '+' DECIMAL ; DECIMAL_NEGATIVE : '-' DECIMAL ; // not used STRING_LITERAL_LONG_SINGLE_QUOTE : '\'\'\'' (('\'' | '\'\'')? ([^'\\] | ECHAR | UCHAR | '"'))* '\'\'\'' ; // not used STRING_LITERAL_LONG_QUOTE : '"""' (('"' | '""')? (~ ["\\] | ECHAR | UCHAR | '\''))* '"""' ; // extends STRING_LITERAL_QUOTE in the original grammar to allow curly brackets, space and escaped characters STRING_LITERAL_QUOTE : '"' (~ ["\\\r\n] | '\'' | '\\"' | '{' | '}' | ' ' | ECHAR)* '"' ; /* orginal version: STRING_LITERAL_QUOTE : '"' (~ ["\\\r\n] | '\'' | '\\"')* '"' ; */ // not used STRING_LITERAL_SINGLE_QUOTE : '\'' (~ [\u0027\u005C\u000A\u000D] | ECHAR | UCHAR | '"')* '\'' ; UCHAR : '\\u' HEX HEX HEX HEX | '\\U' HEX HEX HEX HEX HEX HEX HEX HEX ; ECHAR : '\\' [tbnrf"'\\] ; ANON_WS : ' ' | '\t' | '\r' | '\n' ; ANON : '[' ANON_WS* ']' ; PN_CHARS_BASE : 'A' .. 'Z' | 'a' .. 'z' | '\u00C0' .. '\u00D6' | '\u00D8' .. '\u00F6' | '\u00F8' .. '\u02FF' | '\u0370' .. '\u037D' | '\u037F' .. '\u1FFF' | '\u200C' .. '\u200D' | '\u2070' .. '\u218F' | '\u2C00' .. '\u2FEF' | '\u3001' .. '\uD7FF' | '\uF900' .. '\uFDCF' | '\uFDF0' .. '\uFFFD' // Limitation: Unicode Characters beyond \uFFFF are not (yet?) supported by ANTLR // | '\u10000' .. '\u1FFFD' | '\u20000' .. '\u2FFFD' | // '\u30000' .. '\u3FFFD' | '\u40000' .. '\u4FFFD' | '\u50000' .. '\u5FFFD' | '\u60000' .. '\u6FFFD' | // '\u70000' .. '\u7FFFD' | '\u80000' .. '\u8FFFD' | '\u90000' .. '\u9FFFD' | '\uA0000' .. '\uAFFFD' | // '\uB0000' .. '\uBFFFD' | '\uC0000' .. '\uCFFFD' | '\uD0000' .. '\uDFFFD' | '\uE1000' .. '\uEFFFD' ; PN_CHARS_U : PN_CHARS_BASE | '_' ; PN_CHARS : PN_CHARS_U | '-' | [0-9] | '\u00B7' | [\u0300-\u036F] | [\u203F-\u2040] | '?' | '=' ; // extends PN_LOCAL to allow curly brackets, and force at least one (opening) curly bracket PN_LOCAL_EXT : '{' RIGHT_PART_TAIL_EXT + | RIGHT_PART_FIRST_CHAR RIGHT_PART_TAIL_EXT_MAND ; // extends PN_LOCAL in the original grammar to allow '/' and '#' PN_LOCAL : RIGHT_PART_FIRST_CHAR RIGHT_PART_TAIL? ; PLX : PERCENT | PN_LOCAL_ESC ; PERCENT : '%' HEX HEX ; HEX : [0-9] | [A-F] | [a-f] ; // RDF-specific: the backslash (first character) is ignored when parsing the IRI PN_LOCAL_ESC : '\\' ('_' | '~' | '.' | '-' | '!' | '$' | '&' | '\'' | '(' | ')' | '*' | '+' | ',' | ';' | '=' | '/' | '?' | '#' | '@' | '%') ; fragment RIGHT_PART_FIRST_CHAR : (PN_CHARS_U | ':' | '#' | [0-9] | PLX) ; fragment RIGHT_PART_FIRST_CHAR_EXT : (RIGHT_PART_FIRST_CHAR | '{') ; fragment RIGHT_PART_CHAR : (PN_CHARS | '.' | ':' | '/' | '#' | ';' | PLX) ; fragment RIGHT_PART_CHAR_EXT : (RIGHT_PART_CHAR | '{' | '}') ; fragment RIGHT_PART_END_CHAR : (PN_CHARS | ':' | '/'| PLX) ; fragment RIGHT_PART_END_CHAR_EXT : (RIGHT_PART_END_CHAR | '}') ; fragment RIGHT_PART_TAIL : RIGHT_PART_CHAR* RIGHT_PART_END_CHAR ; fragment RIGHT_PART_TAIL_EXT : RIGHT_PART_CHAR_EXT* RIGHT_PART_END_CHAR_EXT ; fragment RIGHT_PART_TAIL_EXT_MAND : RIGHT_PART_CHAR_EXT* '{' RIGHT_PART_CHAR_EXT* RIGHT_PART_END_CHAR_EXT ; fragment IRIREF_INNER_CHAR : (PN_CHARS | '.' | ':' | '/' | '\\' | '#' | '@' | '%' | '&' | ';' | UCHAR) ; fragment IRIREF_INNER_CHAR_EXT : (IRIREF_INNER_CHAR | '{' | '}') ; fragment VARIABLE_CHAR : (PN_CHARS | '.' | ':' | '/' | '\\' | '#' | '%' | '&' | '$' | UCHAR) ;
fix antlr grammar
fix antlr grammar
ANTLR
apache-2.0
ontop/ontop,ontop/ontop,ontop/ontop,ontop/ontop,ontop/ontop
a20218ebce88610ff4dd1f5a7d2f96ee5ac0edf5
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
/* Todo: * - Comments justifying and explaining every rule. */ lexer grammar CreoleTokens; options { superClass=ContextSensitiveLexer; } @members { Formatting bold; Formatting italic; Formatting strike; public void setupFormatting() { bold = new Formatting("**"); italic = new Formatting("//"); strike = new Formatting("--"); inlineFormatting.add(bold); inlineFormatting.add(italic); inlineFormatting.add(strike); } public boolean inHeader = false; public boolean start = false; public int olistLevel = 0; public int ulistLevel = 0; boolean nowiki = false; boolean cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = false; boolean intr = false; public void doHdr() { String prefix = getText().trim(); boolean seekback = false; if(!prefix.substring(prefix.length() - 1).equals("=")) { prefix = prefix.substring(0, prefix.length() - 1); seekback = true; } if(prefix.length() <= 6) { if(seekback) { seek(-1); } setText(prefix); inHeader = true; } else { setType(Any); } } public void setStart() { String next1 = next(); String next2 = get(1); start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#")); } public void doUlist(int level) { ulistLevel = level; seek(-1); setStart(); } public void doOlist(int level) { olistLevel = level; seek(-1); setStart(); } public void doUrl() { String url = getText(); String last = url.substring(url.length()-1); String next = next(); if((last + next).equals("//") || (last+next).equals(". ") || (last+next).equals(", ")) { seek(-1); setText(url.substring(0, url.length() - 1)); } } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' WS? {doHdr();} ; HEnd : ' '* '='* ('\r'? '\n' {seek(-1);} | EOF) {inHeader}? {inHeader = false; resetFormatting();} ; /* ***** Lists ***** */ U1 : START '*' ~'*' {doUlist(1); resetFormatting();} ; U2 : START '**' ~'*' {ulistLevel >= 1}? {doUlist(2); resetFormatting();} ; U3 : START '***' ~'*' {ulistLevel >= 2}? {doUlist(3); resetFormatting();} ; U4 : START '****' ~'*' {ulistLevel >= 3}? {doUlist(4); resetFormatting();} ; U5 : START '*****' ~'*' {ulistLevel >= 4}? {doUlist(5); resetFormatting();} ; O1 : START '#' ~'#' {doOlist(1); resetFormatting();} ; O2 : START '##' ~'#' {olistLevel >= 1}? {doOlist(2); resetFormatting();} ; O3 : START '###' ~'#' {olistLevel >= 2}? {doOlist(3); resetFormatting();} ; O4 : START '####' ~'#' {olistLevel >= 3}? {doOlist(4); resetFormatting();} ; O5 : START '#####' ~'#' {olistLevel >= 4}? {doOlist(5); resetFormatting();} ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+? {resetFormatting();} ; /* ***** Tables ***** */ RowEnd : '|' LineBreak {intr}? {intr=false;} ; TdStart : '|' {resetFormatting(); intr=true;} ; ThStart : '|=' {resetFormatting(); intr=true;} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active}? {setFormatting(italic, Any);} ; SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ; BEnd : '**' {bold.active}? {unsetFormatting(bold);} ; IEnd : '//' {italic.active}? {unsetFormatting(italic);} ; SEnd : '--' {strike.active}? {unsetFormatting(strike);} ; NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ; StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ; StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ; StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ; StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ; StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ; /* ***** Links ***** */ LiSt : '[[' -> mode(LINK) ; ImSt : '{{' -> mode(LINK) ; /* ***** Breaks ***** */ InlineBrk : '\\\\' ; ParBreak : LineBreak LineBreak+ {resetFormatting();} ; LineBreak : '\r'? '\n' ; /* ***** Links ***** */ RawUrl : ('http://' | 'ftp://' | 'mailto:') (~(' '|'\t'|'\r'|'\n'|'/'|'|')+ '/'?)+ {doUrl();}; WikiWords : (ALNUM+ ':')? (UPPER ((ALNUM|'.')* ALNUM)*) (UPPER ((ALNUM|'.')* ALNUM)*)+; /* ***** Macros ***** */ MacroSt : '<<' -> mode(MACRO) ; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t'|'\r'|'\n')+ ; fragment START : {start}? | LINE ; fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*; fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : ']]' -> mode(DEFAULT_MODE) ; ImEnd : '}}' -> mode(DEFAULT_MODE) ; Sep : '|' ; InLink : ~(']'|'}'|'|')+ ; mode MACRO; MacroName : ~(':'|'>')+ ; MacroSep : ':' -> mode(MACRO_ARGS) ; mode MACRO_ARGS; MacroArgs : . -> more ; MacroEnd : '>>' -> mode(DEFAULT_MODE) ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' (~'}' {seek(-1);} | EOF) {nowiki}? -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
/* Todo: * - Comments justifying and explaining every rule. */ lexer grammar CreoleTokens; options { superClass=ContextSensitiveLexer; } @members { Formatting bold; Formatting italic; Formatting strike; public void setupFormatting() { bold = new Formatting("**"); italic = new Formatting("//"); strike = new Formatting("--"); inlineFormatting.add(bold); inlineFormatting.add(italic); inlineFormatting.add(strike); } public boolean inHeader = false; public boolean start = false; public int olistLevel = 0; public int ulistLevel = 0; boolean nowiki = false; boolean cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = false; boolean intr = false; public void doHdr() { String prefix = getText().trim(); boolean seekback = false; if(!prefix.substring(prefix.length() - 1).equals("=")) { prefix = prefix.substring(0, prefix.length() - 1); seekback = true; } if(prefix.length() <= 6) { if(seekback) { seek(-1); } setText(prefix); inHeader = true; } else { setType(Any); } } public void setStart() { String next1 = next(); String next2 = get(1); start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#")); } public void doUlist(int level) { ulistLevel = level; seek(-1); setStart(); } public void doOlist(int level) { olistLevel = level; seek(-1); setStart(); } public void doUrl() { String url = getText(); String last = url.substring(url.length()-1); String next = next(); if((last + next).equals("//") || (last+next).equals(". ") || (last+next).equals(", ")) { seek(-1); setText(url.substring(0, url.length() - 1)); } } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' WS? {doHdr();} ; HEnd : ' '* '='* ('\r'? '\n' {seek(-1);} | EOF) {inHeader}? {inHeader = false; resetFormatting();} ; /* ***** Lists ***** */ U1 : START '*' ~'*' {doUlist(1); resetFormatting();} ; U2 : START '**' ~'*' {ulistLevel >= 1}? {doUlist(2); resetFormatting();} ; U3 : START '***' ~'*' {ulistLevel >= 2}? {doUlist(3); resetFormatting();} ; U4 : START '****' ~'*' {ulistLevel >= 3}? {doUlist(4); resetFormatting();} ; U5 : START '*****' ~'*' {ulistLevel >= 4}? {doUlist(5); resetFormatting();} ; O1 : START '#' ~'#' {doOlist(1); resetFormatting();} ; O2 : START '##' ~'#' {olistLevel >= 1}? {doOlist(2); resetFormatting();} ; O3 : START '###' ~'#' {olistLevel >= 2}? {doOlist(3); resetFormatting();} ; O4 : START '####' ~'#' {olistLevel >= 3}? {doOlist(4); resetFormatting();} ; O5 : START '#####' ~'#' {olistLevel >= 4}? {doOlist(5); resetFormatting();} ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+? {resetFormatting();} ; /* ***** Tables ***** */ RowEnd : '|' LineBreak {intr}? {intr=false;} ; TdStart : '|' {resetFormatting(); intr=true;} ; ThStart : '|=' {resetFormatting(); intr=true;} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active}? {setFormatting(italic, Any);} ; SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ; BEnd : '**' {bold.active}? {unsetFormatting(bold);} ; IEnd : '//' {italic.active}? {unsetFormatting(italic);} ; SEnd : '--' {strike.active}? {unsetFormatting(strike);} ; NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ; StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ; StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ; StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ; StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ; StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ; /* ***** Links ***** */ LiSt : '[[' -> mode(LINK) ; ImSt : '{{' -> mode(LINK) ; /* ***** Breaks ***** */ InlineBrk : '\\\\' ; ParBreak : LineBreak LineBreak+ {resetFormatting();} ; LineBreak : '\r'? '\n' ; /* ***** Links ***** */ RawUrl : (('http' 's'? | 'ftp') '://' | 'mailto:') (~(' '|'\t'|'\r'|'\n'|'/'|'|')+ '/'?)+ {doUrl();}; WikiWords : (ALNUM+ ':')? (UPPER ((ALNUM|'.')* ALNUM)*) (UPPER ((ALNUM|'.')* ALNUM)*)+; /* ***** Macros ***** */ MacroSt : '<<' -> mode(MACRO) ; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t'|'\r'|'\n')+ ; fragment START : {start}? | LINE ; fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*; fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : ']]' -> mode(DEFAULT_MODE) ; ImEnd : '}}' -> mode(DEFAULT_MODE) ; Sep : '|' ; InLink : ~(']'|'}'|'|')+ ; mode MACRO; MacroName : ~(':'|'>')+ ; MacroSep : ':' -> mode(MACRO_ARGS) ; mode MACRO_ARGS; MacroArgs : . -> more ; MacroEnd : '>>' -> mode(DEFAULT_MODE) ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' (~'}' {seek(-1);} | EOF) {nowiki}? -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
Allow https raw urls
Allow https raw urls
ANTLR
apache-2.0
ashirley/reviki,CoreFiling/reviki,strr/reviki,strr/reviki,ashirley/reviki,CoreFiling/reviki,CoreFiling/reviki,CoreFiling/reviki,strr/reviki,CoreFiling/reviki,ashirley/reviki,ashirley/reviki,ashirley/reviki,strr/reviki,strr/reviki
43c4cdaf9e916d630fcf7bde4025af66bae2852b
src/main/antlr4/YokohamaUnitLexer.g4
src/main/antlr4/YokohamaUnitLexer.g4
lexer grammar YokohamaUnitLexer; HASH1: '#' ; HASH2: '##' ; HASH3: '###' ; HASH4: '####' ; HASH5: '#####' ; HASH6: '######' ; TEST: 'Test:' -> mode(TEST_LEADING); TABLE: 'Table:' -> mode(TABLE_LEADING); SETUP: 'Setup' -> mode(PHASE_LEADING); EXERCISE: 'Exercise' -> mode(PHASE_LEADING); VERIFY: 'Verify' -> mode(PHASE_LEADING); TEARDOWN: 'Teardown' -> mode(PHASE_LEADING); BAR: '|' -> mode(IN_TABLE_HEADER) ; ASSERT: 'Assert' -> mode(IN_THE_MIDDLE_OF_LINE) ; THAT: 'that' -> mode(IN_THE_MIDDLE_OF_LINE) ; STOP: '.' -> mode(IN_THE_MIDDLE_OF_LINE) ; AND: 'and' -> mode(IN_THE_MIDDLE_OF_LINE) ; IS: 'is' -> mode(IN_THE_MIDDLE_OF_LINE) ; NOT: 'not' -> mode(IN_THE_MIDDLE_OF_LINE) ; THROWS: 'throws' -> mode(IN_THE_MIDDLE_OF_LINE) ; ACCORDING: 'according' -> mode(IN_THE_MIDDLE_OF_LINE) ; TO: 'to' -> mode(IN_THE_MIDDLE_OF_LINE) ; FOR: 'for' -> mode(IN_THE_MIDDLE_OF_LINE) ; ALL: 'all' -> mode(IN_THE_MIDDLE_OF_LINE) ; RULES: 'rules' -> mode(IN_THE_MIDDLE_OF_LINE) ; IN: 'in' -> mode(IN_THE_MIDDLE_OF_LINE) ; UTABLE: 'Table' -> mode(IN_THE_MIDDLE_OF_LINE) ; CSV: 'CSV' -> mode(IN_THE_MIDDLE_OF_LINE) ; TSV: 'TSV' -> mode(IN_THE_MIDDLE_OF_LINE) ; EXCEL: 'Excel' -> mode(IN_THE_MIDDLE_OF_LINE) ; WHERE: 'where' -> mode(IN_THE_MIDDLE_OF_LINE) ; EQ: '=' -> mode(IN_THE_MIDDLE_OF_LINE) ; LET: 'Let' -> mode(IN_THE_MIDDLE_OF_LINE) ; BE: 'be' -> mode(IN_THE_MIDDLE_OF_LINE) ; DO: 'Do' -> mode(IN_THE_MIDDLE_OF_LINE) ; A: 'a' -> mode(IN_THE_MIDDLE_OF_LINE) ; STUB: 'stub' -> mode(IN_THE_MIDDLE_OF_LINE) ; OF: 'of' -> mode(IN_THE_MIDDLE_OF_LINE) ; SUCHTHAT: 'such' [ \t\r\n]+ 'that' -> mode(AFTER_SUCHTHAT) ; RETURNS: 'returns' -> mode(IN_THE_MIDDLE_OF_LINE) ; Identifier: IdentStart IdentPart* ; OPENBACKTICK: '`' -> skip, mode(IN_BACKTICK) ; OPENDOUBLEQUOTE: '"' -> skip, mode(IN_DOUBLEQUOTE) ; NEW_LINE : ('\r'? '\n')+ -> skip ; WS : [ \t]+ -> skip ; mode IN_THE_MIDDLE_OF_LINE; ASSERT2: 'Assert' -> type(ASSERT) ; THAT2: 'that' -> type(THAT) ; STOP2: '.' -> type(STOP) ; AND2: 'and' -> type(AND) ; IS2: 'is' -> type(IS) ; NOT2: 'not' -> type(NOT) ; THROWS2: 'throws' -> type(THROWS) ; ACCORDING2: 'according' -> type(ACCORDING) ; TO2: 'to' -> type(TO) ; FOR2: 'for' -> type(FOR) ; ALL2: 'all' -> type(ALL) ; RULES2: 'rules' -> type(RULES) ; IN2: 'in' -> type(IN) ; UTABLE2: 'Table' -> type(UTABLE) ; CSV2: 'CSV' -> type(CSV) ; TSV2: 'TSV' -> type(TSV) ; EXCEL2: 'Excel' -> type(EXCEL) ; WHERE2: 'where' -> type(WHERE) ; EQ2: '=' -> type(EQ) ; LET2: 'Let' -> type(LET) ; BE2: 'be' -> type(BE) ; DO2: 'Do' -> type(DO) ; A2: 'a' -> type(A) ; STUB2: 'stub' -> type(STUB) ; OF2: 'of' -> type(OF) ; SUCHTHAT2: 'such' [ \t\r\n]+ 'that' -> type(SUCHTHAT), mode(AFTER_SUCHTHAT) ; RETURNS2: 'returns' -> type(RETURNS) ; Identifier2 : IdentStart IdentPart* -> type(Identifier); OPENBACKTICK2: '`' -> skip, mode(IN_BACKTICK) ; OPENDOUBLEQUOTE2: '"' -> skip, mode(IN_DOUBLEQUOTE) ; NEW_LINE2 : ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; WS2 : [ \t]+ -> skip ; mode TEST_LEADING; WS3: [ \t]+ -> skip, mode(TEST_NAME); mode TEST_NAME; TestName: ~[\r\n]+ ; NEW_LINE_TESTNAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode TABLE_LEADING; WS4: [ \t]+ -> skip, mode(TABLE_NAME); mode TABLE_NAME; TableName: ~[\r\n]+ ; NEW_LINE_TABLENAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode PHASE_LEADING; COLON: ':' [ \t]* -> skip, mode(PHASE_DESCRIPTION) ; WS5: [ \t]* '\r'? '\n' -> skip, mode(DEFAULT_MODE) ; mode PHASE_DESCRIPTION; PhaseDescription: ~[\r\n]+ ; NEW_LINE_PHASE: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode IN_DOUBLEQUOTE; Quoted: ~["]+ ; CLOSEDOUBLEQUOTE: '"' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode IN_BACKTICK; Expr: ~[`]+ /*-> type(Expr)*/ ; CLOSEBACKTICK: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode IN_TABLE_HEADER; IDENTHEADER: IdentStart IdentPart* -> type(Identifier) ; BARH: '|' -> type(BAR) ; NEWLINE: '\r'? '\n' -> mode(IN_TABLE_ONSET) ; SPACETAB: [ \t]+ -> skip ; mode IN_TABLE_CELL; ExprCell: ~[|\r\n]+ -> type(Expr) ; BARCELL: '|' -> type(BAR) ; NEWLINECELL: '\r'? '\n' -> type(NEWLINE), mode(IN_TABLE_ONSET) ; SPACETABCELL: [ \t]+ -> skip ; mode IN_TABLE_ONSET; BARONSET: '|' -> type(BAR), mode(IN_TABLE_CELL) ; HBAR: '-'+ '\r'? '\n' ; SPACETAB2: [ \t]+ -> skip ; NEWLINEONSET: '\r'?'\n' -> skip, mode(DEFAULT_MODE) ; mode AFTER_SUCHTHAT; OPENBACKTICK3: '`' -> skip, mode(METHOD_PATTERN) ; SPACETABNEWLINE: [ \t\r\n]+ -> skip ; mode METHOD_PATTERN; BOOLEAN: 'boolean' ; BYTE: 'byte' ; SHORT: 'short' ; INT: 'int' ; LONG: 'long' ; FLOAT: 'float' ; DOUBLE: 'double' ; COMMA: ',' ; THREEDOTS: '...' ; DOT: '.' ; LPAREN: '(' ; RPAREN: ')' ; LBRACKET: '[' ; RBRACKET: ']' ; Identifier3 : IdentStart IdentPart* -> type(Identifier); SPACETABNEWLINE2: [ \t\r\n]+ -> skip ; CLOSEBACKTICK2: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; fragment IdentStart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierStart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IdentPart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierPart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ;
lexer grammar YokohamaUnitLexer; HASH1: '#' ; HASH2: '##' ; HASH3: '###' ; HASH4: '####' ; HASH5: '#####' ; HASH6: '######' ; TEST: 'Test:' -> mode(TEST_LEADING); TABLE: 'Table:' -> mode(TABLE_LEADING); SETUP: 'Setup' -> mode(PHASE_LEADING); EXERCISE: 'Exercise' -> mode(PHASE_LEADING); VERIFY: 'Verify' -> mode(PHASE_LEADING); TEARDOWN: 'Teardown' -> mode(PHASE_LEADING); BAR: '|' -> mode(IN_TABLE_HEADER) ; ASSERT: 'Assert' -> mode(IN_THE_MIDDLE_OF_LINE) ; THAT: 'that' -> mode(IN_THE_MIDDLE_OF_LINE) ; STOP: '.' -> mode(IN_THE_MIDDLE_OF_LINE) ; AND: 'and' -> mode(IN_THE_MIDDLE_OF_LINE) ; IS: 'is' -> mode(IN_THE_MIDDLE_OF_LINE) ; NOT: 'not' -> mode(IN_THE_MIDDLE_OF_LINE) ; THROWS: 'throws' -> mode(IN_THE_MIDDLE_OF_LINE) ; ACCORDING: 'according' -> mode(IN_THE_MIDDLE_OF_LINE) ; TO: 'to' -> mode(IN_THE_MIDDLE_OF_LINE) ; FOR: 'for' -> mode(IN_THE_MIDDLE_OF_LINE) ; ALL: 'all' -> mode(IN_THE_MIDDLE_OF_LINE) ; RULES: 'rules' -> mode(IN_THE_MIDDLE_OF_LINE) ; IN: 'in' -> mode(IN_THE_MIDDLE_OF_LINE) ; UTABLE: 'Table' -> mode(IN_THE_MIDDLE_OF_LINE) ; CSV: 'CSV' -> mode(IN_THE_MIDDLE_OF_LINE) ; TSV: 'TSV' -> mode(IN_THE_MIDDLE_OF_LINE) ; EXCEL: 'Excel' -> mode(IN_THE_MIDDLE_OF_LINE) ; WHERE: 'where' -> mode(IN_THE_MIDDLE_OF_LINE) ; EQ: '=' -> mode(IN_THE_MIDDLE_OF_LINE) ; LET: 'Let' -> mode(IN_THE_MIDDLE_OF_LINE) ; BE: 'be' -> mode(IN_THE_MIDDLE_OF_LINE) ; DO: 'Do' -> mode(IN_THE_MIDDLE_OF_LINE) ; A: 'a' -> mode(IN_THE_MIDDLE_OF_LINE) ; STUB: 'stub' -> mode(IN_THE_MIDDLE_OF_LINE) ; OF: 'of' -> mode(IN_THE_MIDDLE_OF_LINE) ; SUCHTHAT: 'such' [ \t\r\n]+ 'that' -> mode(AFTER_SUCHTHAT) ; RETURNS: 'returns' -> mode(IN_THE_MIDDLE_OF_LINE) ; Identifier: IdentStart IdentPart* ; OPENBACKTICK: '`' -> skip, mode(IN_BACKTICK) ; OPENDOUBLEQUOTE: '"' -> skip, mode(IN_DOUBLEQUOTE) ; NEW_LINE : ('\r'? '\n')+ -> skip ; WS : [ \t]+ -> skip ; mode IN_THE_MIDDLE_OF_LINE; ASSERT2: 'Assert' -> type(ASSERT) ; THAT2: 'that' -> type(THAT) ; STOP2: '.' -> type(STOP) ; AND2: 'and' -> type(AND) ; IS2: 'is' -> type(IS) ; NOT2: 'not' -> type(NOT) ; THROWS2: 'throws' -> type(THROWS) ; ACCORDING2: 'according' -> type(ACCORDING) ; TO2: 'to' -> type(TO) ; FOR2: 'for' -> type(FOR) ; ALL2: 'all' -> type(ALL) ; RULES2: 'rules' -> type(RULES) ; IN2: 'in' -> type(IN) ; UTABLE2: 'Table' -> type(UTABLE) ; CSV2: 'CSV' -> type(CSV) ; TSV2: 'TSV' -> type(TSV) ; EXCEL2: 'Excel' -> type(EXCEL) ; WHERE2: 'where' -> type(WHERE) ; EQ2: '=' -> type(EQ) ; LET2: 'Let' -> type(LET) ; BE2: 'be' -> type(BE) ; DO2: 'Do' -> type(DO) ; A2: 'a' -> type(A) ; STUB2: 'stub' -> type(STUB) ; OF2: 'of' -> type(OF) ; SUCHTHAT2: 'such' [ \t\r\n]+ 'that' -> type(SUCHTHAT), mode(AFTER_SUCHTHAT) ; RETURNS2: 'returns' -> type(RETURNS) ; Identifier2 : IdentStart IdentPart* -> type(Identifier); OPENBACKTICK2: '`' -> skip, mode(IN_BACKTICK) ; OPENDOUBLEQUOTE2: '"' -> skip, mode(IN_DOUBLEQUOTE) ; NEW_LINE2 : ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; WS2 : [ \t]+ -> skip ; mode TEST_LEADING; WS3: [ \t]+ -> skip, mode(TEST_NAME); mode TEST_NAME; TestName: ~[\r\n]+ ; NEW_LINE_TESTNAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode TABLE_LEADING; WS4: [ \t]+ -> skip, mode(TABLE_NAME); mode TABLE_NAME; TableName: ~[\r\n]+ ; NEW_LINE_TABLENAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode PHASE_LEADING; COLON: ':' [ \t]* -> skip, mode(PHASE_DESCRIPTION) ; WS5: [ \t]* '\r'? '\n' -> skip, mode(DEFAULT_MODE) ; mode PHASE_DESCRIPTION; PhaseDescription: ~[\r\n]+ ; NEW_LINE_PHASE: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode IN_DOUBLEQUOTE; Quoted: ~["]+ ; CLOSEDOUBLEQUOTE: '"' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode IN_BACKTICK; Expr: ~[`]+ /*-> type(Expr)*/ ; CLOSEBACKTICK: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode IN_TABLE_HEADER; IDENTHEADER: IdentStart IdentPart* -> type(Identifier) ; BARH: '|' -> type(BAR) ; NEWLINE: '\r'? '\n' -> mode(IN_TABLE_ONSET) ; SPACETAB: [ \t]+ -> skip ; mode IN_TABLE_CELL; ExprCell: ~[|\r\n]+ -> type(Expr) ; BARCELL: '|' -> type(BAR) ; NEWLINECELL: '\r'? '\n' -> type(NEWLINE), mode(IN_TABLE_ONSET) ; SPACETABCELL: [ \t]+ -> skip ; mode IN_TABLE_ONSET; BARONSET: '|' -> type(BAR), mode(IN_TABLE_CELL) ; HBAR: '-'+ '\r'? '\n' ; SPACETAB2: [ \t]+ -> skip ; NEWLINEONSET: '\r'?'\n' -> skip, mode(DEFAULT_MODE) ; mode AFTER_SUCHTHAT; OPENBACKTICK3: '`' -> skip, mode(METHOD_PATTERN) ; SPACETABNEWLINE: [ \t\r\n]+ -> skip ; mode METHOD_PATTERN; BOOLEAN: 'boolean' ; BYTE: 'byte' ; SHORT: 'short' ; INT: 'int' ; LONG: 'long' ; CHAR: 'char' ; FLOAT: 'float' ; DOUBLE: 'double' ; COMMA: ',' ; THREEDOTS: '...' ; DOT: '.' ; LPAREN: '(' ; RPAREN: ')' ; LBRACKET: '[' ; RBRACKET: ']' ; Identifier3 : IdentStart IdentPart* -> type(Identifier); SPACETABNEWLINE2: [ \t\r\n]+ -> skip ; CLOSEBACKTICK2: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; fragment IdentStart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierStart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IdentPart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierPart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ;
Add `char` token
Add `char` token
ANTLR
mit
tkob/yokohamaunit,tkob/yokohamaunit
f117d4549deb7549b4564542d53016b5231adea4
src/main/antlr/com/github/oreissig/footran1/parser/Footran.g4
src/main/antlr/com/github/oreissig/footran1/parser/Footran.g4
/* * A grammar for the original version of FORTRAN as described * by IBM's programmer's reference manual from 1956: * http://www.fortran.com/FortranForTheIBM704.pdf * * This grammar tries to keep its wording close to the original * language reference, e.g. an array is called subscripted * variable. */ grammar Footran; @header { package com.github.oreissig.footran1.parser; } @lexer::members { /** * FORTRAN-I encapsulates type information in its identifiers, but * unfortunately there are cases that require context to be certain: * IDs with 4 or more characters ending with 'F' may either denote a * non-subscripted variable or a function. * * @param text the ID to analyze * @return true if we know for sure, that text is a variable ID */ private boolean isVariable(String text) { return text.length() < 4 || !text.endsWith("F"); } } // parser rules program : card*; card : STMTNUM? statement NEWCARD?; statement : arithmeticFormula // GO TO family | uncondGoto | assignedGoto | assign | computedGoto // IF family | ifStatement | senseLight | ifSenseLight | ifSenseSwitch | ifAccumulatorOverflow | ifQuotientOverflow | ifDivideCheck // DO loop & misc control flow | doLoop | continueStmt | pause | stop // TODO more to come ; arithmeticFormula : (VAR_ID | FUNC_CANDIDATE | subscript) '=' expression; uncondGoto : 'GO' 'TO' ufixedConst; assignedGoto : 'GO' 'TO' variable ',' '(' ufixedConst (',' ufixedConst)* ')'; assign : 'ASSIGN' ufixedConst 'TO' variable; computedGoto : 'GO' 'TO' '(' ufixedConst (',' ufixedConst)* ')' ',' variable; ifStatement : 'IF' '(' condition=expression ')' lessThan=ufixedConst ',' equal=ufixedConst ',' greaterThan=ufixedConst; senseLight : 'SENSE' 'LIGHT' light=ufixedConst; ifSenseLight : 'IF' '(' 'SENSE' 'LIGHT' light=ufixedConst ')' on=ufixedConst ',' off=ufixedConst; ifSenseSwitch : 'IF' '(' 'SENSE' 'SWITCH' senseSwitch=ufixedConst ')' down=ufixedConst ',' up=ufixedConst; ifAccumulatorOverflow : 'IF' 'ACCUMULATOR' 'OVERFLOW' on=ufixedConst ',' off=ufixedConst; ifQuotientOverflow : 'IF' 'QUOTIENT' 'OVERFLOW' on=ufixedConst ',' off=ufixedConst; ifDivideCheck : 'IF' 'DIVIDE' 'CHECK' on=ufixedConst ',' off=ufixedConst; doLoop : 'DO' range=ufixedConst index=variable '=' first=loopBoundary ',' last=loopBoundary (',' step=loopBoundary)?; loopBoundary : ufixedConst|variable; continueStmt : 'CONTINUE'; pause : 'PAUSE' consoleOutput=ufixedConst?; stop : 'STOP' consoleOutput=ufixedConst?; variable : VAR_ID | FUNC_CANDIDATE; subscript : var=VAR_ID '(' subscriptExpression (',' subscriptExpression (',' subscriptExpression )? )? ')'; subscriptExpression : constant=ufixedConst | (factor=ufixedConst '*')? index=variable (sign summand=ufixedConst)?; expression : sign? unsigned=unsignedExpression; unsignedExpression : '(' expression ')' | variable | subscript | functionCall | ufixedConst | ufloatConst; functionCall : function=FUNC_CANDIDATE '(' expression (',' expression)* ')'; ufixedConst : NUMBER ; fixedConst : sign? unsigned=ufixedConst ; ufloatConst : integer=NUMBER? '.' (fraction=NUMBER | fractionE=FLOAT_FRAC exponent=fixedConst)? ; floatConst : sign? unsigned=ufloatConst ; sign : (PLUS|MINUS); mulOp : (MUL|DIV); // lexer rules // prefix area processing COMMENT : {getCharPositionInLine() == 0}? 'C' ~('\n')* '\n'? -> skip ; STMTNUM : {getCharPositionInLine() < 5}? [1-9][0-9]* ; CONTINUE : NEWCARD . . . . . ~[' '|'0'] -> skip ; // body processing fragment DIGIT : {getCharPositionInLine() > 5}? [0-9]; fragment LETTER : {getCharPositionInLine() > 5}? [A-Z]; fragment ALFNUM : {getCharPositionInLine() > 5}? [A-Z0-9]; NUMBER : DIGIT+ ; // use a separate token to avoid recognizing the float exponential E as ID FLOAT_FRAC : NUMBER 'E'; VAR_ID : LETTER ALFNUM* {isVariable(getText())}? ; // function candidate refers to either a function or a non-subscripted variable FUNC_CANDIDATE : LETTER ALFNUM+ {!isVariable(getText())}? ; PLUS : '+'; MINUS : '-'; MUL : '*'; DIV : '/'; POWER : '**'; // return newlines to parser NEWCARD : '\r'? '\n' ; // skip spaces and tabs WS : ' '+ -> skip ;
/* * A grammar for the original version of FORTRAN as described * by IBM's programmer's reference manual from 1956: * http://www.fortran.com/FortranForTheIBM704.pdf * * This grammar tries to keep its wording close to the original * language reference, e.g. an array is called subscripted * variable. */ grammar Footran; @header { package com.github.oreissig.footran1.parser; } @lexer::members { /** * FORTRAN-I encapsulates type information in its identifiers, but * unfortunately there are cases that require context to be certain: * IDs with 4 or more characters ending with 'F' may either denote a * non-subscripted variable or a function. * * @param text the ID to analyze * @return true if we know for sure, that text is a variable ID */ private boolean isVariable(String text) { return text.length() < 4 || !text.endsWith("F"); } } // parser rules program : card*; card : STMTNUM? statement NEWCARD?; statement : arithmeticFormula // GO TO family | uncondGoto | assignedGoto | assign | computedGoto // IF family | ifStatement | senseLight | ifSenseLight | ifSenseSwitch | ifAccumulatorOverflow | ifQuotientOverflow | ifDivideCheck // DO loop & misc control flow | doLoop | continueStmt | pause | stop // TODO I/O // TODO specifications ; arithmeticFormula : (VAR_ID | FUNC_CANDIDATE | subscript) '=' expression; uncondGoto : 'GO' 'TO' ufixedConst; assignedGoto : 'GO' 'TO' variable ',' '(' ufixedConst (',' ufixedConst)* ')'; assign : 'ASSIGN' ufixedConst 'TO' variable; computedGoto : 'GO' 'TO' '(' ufixedConst (',' ufixedConst)* ')' ',' variable; ifStatement : 'IF' '(' condition=expression ')' lessThan=ufixedConst ',' equal=ufixedConst ',' greaterThan=ufixedConst; senseLight : 'SENSE' 'LIGHT' light=ufixedConst; ifSenseLight : 'IF' '(' 'SENSE' 'LIGHT' light=ufixedConst ')' on=ufixedConst ',' off=ufixedConst; ifSenseSwitch : 'IF' '(' 'SENSE' 'SWITCH' senseSwitch=ufixedConst ')' down=ufixedConst ',' up=ufixedConst; ifAccumulatorOverflow : 'IF' 'ACCUMULATOR' 'OVERFLOW' on=ufixedConst ',' off=ufixedConst; ifQuotientOverflow : 'IF' 'QUOTIENT' 'OVERFLOW' on=ufixedConst ',' off=ufixedConst; ifDivideCheck : 'IF' 'DIVIDE' 'CHECK' on=ufixedConst ',' off=ufixedConst; doLoop : 'DO' range=ufixedConst index=variable '=' first=loopBoundary ',' last=loopBoundary (',' step=loopBoundary)?; loopBoundary : ufixedConst|variable; continueStmt : 'CONTINUE'; pause : 'PAUSE' consoleOutput=ufixedConst?; stop : 'STOP' consoleOutput=ufixedConst?; variable : VAR_ID | FUNC_CANDIDATE; subscript : var=VAR_ID '(' subscriptExpression (',' subscriptExpression (',' subscriptExpression )? )? ')'; subscriptExpression : constant=ufixedConst | (factor=ufixedConst '*')? index=variable (sign summand=ufixedConst)?; expression : sign? unsigned=unsignedExpression; unsignedExpression : '(' expression ')' | variable | subscript | functionCall | ufixedConst | ufloatConst; functionCall : function=FUNC_CANDIDATE '(' expression (',' expression)* ')'; ufixedConst : NUMBER ; fixedConst : sign? unsigned=ufixedConst ; ufloatConst : integer=NUMBER? '.' (fraction=NUMBER | fractionE=FLOAT_FRAC exponent=fixedConst)? ; floatConst : sign? unsigned=ufloatConst ; sign : (PLUS|MINUS); mulOp : (MUL|DIV); // lexer rules // prefix area processing COMMENT : {getCharPositionInLine() == 0}? 'C' ~('\n')* '\n'? -> skip ; STMTNUM : {getCharPositionInLine() < 5}? [1-9][0-9]* ; CONTINUE : NEWCARD . . . . . ~[' '|'0'] -> skip ; // body processing fragment DIGIT : {getCharPositionInLine() > 5}? [0-9]; fragment LETTER : {getCharPositionInLine() > 5}? [A-Z]; fragment ALFNUM : {getCharPositionInLine() > 5}? [A-Z0-9]; NUMBER : DIGIT+ ; // use a separate token to avoid recognizing the float exponential E as ID FLOAT_FRAC : NUMBER 'E'; VAR_ID : LETTER ALFNUM* {isVariable(getText())}? ; // function candidate refers to either a function or a non-subscripted variable FUNC_CANDIDATE : LETTER ALFNUM+ {!isVariable(getText())}? ; PLUS : '+'; MINUS : '-'; MUL : '*'; DIV : '/'; POWER : '**'; // return newlines to parser NEWCARD : '\r'? '\n' ; // skip spaces and tabs WS : ' '+ -> skip ;
make TODO more concrete
make TODO more concrete
ANTLR
isc
oreissig/FOOTRAN-I
be4c86a182e78b30b337f0c8d8194469247422aa
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE temporaryClause_ TABLE existClause_ tableName createDefinitionClause_ inheritClause_ ; createIndex : CREATE UNIQUE? INDEX CONCURRENTLY? ((IF NOT EXISTS)? indexName)? ON tableName ; alterTable : alterTableNameWithAsterisk (alterTableActions | renameColumnSpecification | renameConstraint) | alterTableNameExists renameTableSpecification_ ; alterIndex : alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace ; dropTable : DROP TABLE (IF EXISTS)? tableNames ; dropIndex : DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)* ; truncateTable : TRUNCATE TABLE? ONLY? tableNameParts ; temporaryClause_ : ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? ; existClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ (createDefinition (COMMA_ createDefinition)*)? RP_ ; createDefinition : columnDefinition | tableConstraint | LIKE tableName likeOption* ; columnDefinition : columnName dataType collateClause? columnConstraint* ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT ignoredIdentifier_ ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; checkOption : CHECK expr (NO INHERIT)? ; defaultExpr : CURRENT_TIMESTAMP | expr ; sequenceOptions : sequenceOption+ ; sequenceOption : START WITH? NUMBER_ | INCREMENT BY? NUMBER_ | MAXVALUE NUMBER_ | NO MAXVALUE | MINVALUE NUMBER_ | NO MINVALUE | CYCLE | NO CYCLE | CACHE NUMBER_ | OWNED BY ; indexParameters : (USING INDEX TABLESPACE ignoredIdentifier_)? | INCLUDE columnNames | WITH ; action : NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT) ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))? ; likeOption : (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnNames indexParameters | primaryKey columnNames indexParameters | EXCLUDE (USING ignoredIdentifier_)? | FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; inheritClause_ : (INHERITS tableNames)? ; alterIndexName : ALTER INDEX (IF EXISTS)? indexName ; renameIndexSpecification : RENAME TO indexName ; alterIndexDependsOnExtension : ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_ ; alterIndexSetTableSpace : ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)? ; tableNameParts : tableNamePart (COMMA_ tableNamePart)* ; tableNamePart : tableName ASTERISK_? ; alterTableNameWithAsterisk : ALTER TABLE (IF EXISTS)? ONLY? tableName ASTERISK_? ; alterTableActions : alterTableAction (COMMA_ alterTableAction)* ; alterTableAction : addColumnSpecification | dropColumnSpecification | modifyColumnSpecification | addConstraintSpecification | ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam | VALIDATE CONSTRAINT ignoredIdentifier_ | DROP CONSTRAINT (IF EXISTS)? ignoredIdentifier_ (RESTRICT | CASCADE)? | (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)? | ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_ | (DISABLE | ENABLE) RULE ignoredIdentifier_ | ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_ | (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY | CLUSTER ON indexName | SET WITHOUT CLUSTER | SET (WITH | WITHOUT) OIDS | SET TABLESPACE ignoredIdentifier_ | SET (LOGGED | UNLOGGED) | SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_ | RESET LP_ storageParameter (COMMA_ storageParameter)* RP_ | INHERIT tableName | NO INHERIT tableName | OF dataTypeName_ | NOT OF | OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER) | REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING) ; tableConstraintUsingIndex : (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam ; addColumnSpecification : ADD COLUMN? (IF NOT EXISTS)? columnDefinition ; dropColumnSpecification : DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)? ; modifyColumnSpecification : alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)? | alterColumn SET DEFAULT expr | alterColumn DROP DEFAULT | alterColumn (SET | DROP) NOT NULL | alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)? | alterColumn alterColumnSetOption alterColumnSetOption* | alterColumn DROP IDENTITY (IF EXISTS)? | alterColumn SET STATISTICS NUMBER_ | alterColumn SET LP_ attributeOptions RP_ | alterColumn RESET LP_ attributeOptions RP_ | alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN) ; alterColumn : ALTER COLUMN? columnName ; alterColumnSetOption : SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)? ; attributeOptions : attributeOption (COMMA_ attributeOption)* ; attributeOption : IDENTIFIER_ EQ_ simpleExpr ; addConstraintSpecification : ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex) ; renameColumnSpecification : RENAME COLUMN? columnName TO columnName ; renameConstraint : RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_ ; storageParameterWithValue : storageParameter EQ_ simpleExpr ; storageParameter : IDENTIFIER_ ; alterTableNameExists : ALTER TABLE (IF EXISTS)? tableName ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; usingIndexType : USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN) ; excludeElement : (columnName | expr) ignoredIdentifier_? (ASC | DESC)? (NULLS (FIRST | LAST))? ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createSpecification_ TABLE notExistClause_ tableName createDefinitionClause_ inheritClause_ ; createIndex : CREATE UNIQUE? INDEX CONCURRENTLY? ((IF NOT EXISTS)? indexName)? ON tableName ; alterTable : alterTableNameWithAsterisk (alterTableActions | renameColumnSpecification | renameConstraint) | alterTableNameExists renameTableSpecification_ ; alterIndex : alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace ; dropTable : DROP TABLE (IF EXISTS)? tableNames ; dropIndex : DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)* ; truncateTable : TRUNCATE TABLE? ONLY? tableNameParts ; createSpecification_ : ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? ; notExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ (createDefinition (COMMA_ createDefinition)*)? RP_ ; createDefinition : columnDefinition | tableConstraint | LIKE tableName likeOption* ; columnDefinition : columnName dataType collateClause? columnConstraint* ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT ignoredIdentifier_ ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; checkOption : CHECK expr (NO INHERIT)? ; defaultExpr : CURRENT_TIMESTAMP | expr ; sequenceOptions : sequenceOption+ ; sequenceOption : START WITH? NUMBER_ | INCREMENT BY? NUMBER_ | MAXVALUE NUMBER_ | NO MAXVALUE | MINVALUE NUMBER_ | NO MINVALUE | CYCLE | NO CYCLE | CACHE NUMBER_ | OWNED BY ; indexParameters : (USING INDEX TABLESPACE ignoredIdentifier_)? | INCLUDE columnNames | WITH ; action : NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT) ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))? ; likeOption : (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnNames indexParameters | primaryKey columnNames indexParameters | EXCLUDE (USING ignoredIdentifier_)? | FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; inheritClause_ : (INHERITS tableNames)? ; alterIndexName : ALTER INDEX (IF EXISTS)? indexName ; renameIndexSpecification : RENAME TO indexName ; alterIndexDependsOnExtension : ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_ ; alterIndexSetTableSpace : ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)? ; tableNameParts : tableNamePart (COMMA_ tableNamePart)* ; tableNamePart : tableName ASTERISK_? ; alterTableNameWithAsterisk : ALTER TABLE (IF EXISTS)? ONLY? tableName ASTERISK_? ; alterTableActions : alterTableAction (COMMA_ alterTableAction)* ; alterTableAction : addColumnSpecification | dropColumnSpecification | modifyColumnSpecification | addConstraintSpecification | ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam | VALIDATE CONSTRAINT ignoredIdentifier_ | DROP CONSTRAINT (IF EXISTS)? ignoredIdentifier_ (RESTRICT | CASCADE)? | (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)? | ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_ | (DISABLE | ENABLE) RULE ignoredIdentifier_ | ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_ | (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY | CLUSTER ON indexName | SET WITHOUT CLUSTER | SET (WITH | WITHOUT) OIDS | SET TABLESPACE ignoredIdentifier_ | SET (LOGGED | UNLOGGED) | SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_ | RESET LP_ storageParameter (COMMA_ storageParameter)* RP_ | INHERIT tableName | NO INHERIT tableName | OF dataTypeName_ | NOT OF | OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER) | REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING) ; tableConstraintUsingIndex : (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam ; addColumnSpecification : ADD COLUMN? (IF NOT EXISTS)? columnDefinition ; dropColumnSpecification : DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)? ; modifyColumnSpecification : alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)? | alterColumn SET DEFAULT expr | alterColumn DROP DEFAULT | alterColumn (SET | DROP) NOT NULL | alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)? | alterColumn alterColumnSetOption alterColumnSetOption* | alterColumn DROP IDENTITY (IF EXISTS)? | alterColumn SET STATISTICS NUMBER_ | alterColumn SET LP_ attributeOptions RP_ | alterColumn RESET LP_ attributeOptions RP_ | alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN) ; alterColumn : ALTER COLUMN? columnName ; alterColumnSetOption : SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)? ; attributeOptions : attributeOption (COMMA_ attributeOption)* ; attributeOption : IDENTIFIER_ EQ_ simpleExpr ; addConstraintSpecification : ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex) ; renameColumnSpecification : RENAME COLUMN? columnName TO columnName ; renameConstraint : RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_ ; storageParameterWithValue : storageParameter EQ_ simpleExpr ; storageParameter : IDENTIFIER_ ; alterTableNameExists : ALTER TABLE (IF EXISTS)? tableName ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; usingIndexType : USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN) ; excludeElement : (columnName | expr) ignoredIdentifier_? (ASC | DESC)? (NULLS (FIRST | LAST))? ;
rename to createSpecification_
rename to createSpecification_
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
05f1cc30edf8c524c55b9fcc2db3d6a180f02946
sharding-core/sharding-core-parse/sharding-core-parse-oracle/src/main/antlr4/imports/oracle/DDLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-oracle/src/main/antlr4/imports/oracle/DDLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE temporaryClause_ TABLE tableName relationalTable ; createIndex : CREATE (UNIQUE | BITMAP)? INDEX indexName ON (tableIndexClause_ | bitmapJoinIndexClause_) ; alterTable : ALTER TABLE tableName (alterTableProperties | columnClauses | constraintClauses | alterExternalTable)? ; // TODO hongjun throw exeption when alter index on oracle alterIndex : ALTER INDEX indexName (RENAME TO indexName)? ; dropTable : DROP TABLE tableName ; dropIndex : DROP INDEX indexName ; truncateTable : TRUNCATE TABLE tableName ; temporaryClause_ : (GLOBAL TEMPORARY)? ; tablespaceClauseWithParen : LP_ tablespaceClause RP_ ; tablespaceClause : TABLESPACE ignoredIdentifier_ ; domainIndexClause : indexTypeName ; relationalTable : (LP_ relationalProperties RP_)? (ON COMMIT (DELETE | PRESERVE) ROWS)? ; relationalProperties : relationalProperty (COMMA_ relationalProperty)* ; relationalProperty : columnDefinition | virtualColumnDefinition | outOfLineConstraint | outOfLineRefConstraint ; tableProperties : columnProperties? (AS unionSelect)? ; unionSelect : matchNone ; alterTableProperties : renameTableSpecification_ | REKEY encryptionSpec ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; columnClauses : opColumnClause+ | renameColumnSpecification ; opColumnClause : addColumnSpecification | modifyColumnSpecification | dropColumnClause ; addColumnSpecification : ADD columnOrVirtualDefinitions columnProperties? ; columnOrVirtualDefinitions : LP_ columnOrVirtualDefinition (COMMA_ columnOrVirtualDefinition)* RP_ | columnOrVirtualDefinition ; columnOrVirtualDefinition : columnDefinition | virtualColumnDefinition ; modifyColumnSpecification : MODIFY (LP_? modifyColProperties (COMMA_ modifyColProperties)* RP_? | modifyColSubstitutable) ; modifyColProperties : columnName dataType? (DEFAULT expr)? (ENCRYPT encryptionSpec | DECRYPT)? inlineConstraint* ; modifyColSubstitutable : COLUMN columnName NOT? SUBSTITUTABLE AT ALL LEVELS FORCE? ; dropColumnClause : SET UNUSED columnOrColumnList cascadeOrInvalidate* | dropColumnSpecification ; dropColumnSpecification : DROP columnOrColumnList cascadeOrInvalidate* checkpointNumber? ; columnOrColumnList : COLUMN columnName | LP_ columnName (COMMA_ columnName)* RP_ ; cascadeOrInvalidate : CASCADE CONSTRAINTS | INVALIDATE ; checkpointNumber : CHECKPOINT NUMBER_ ; renameColumnSpecification : RENAME COLUMN columnName TO columnName ; constraintClauses : addConstraintSpecification | modifyConstraintClause | renameConstraintClause | dropConstraintClause+ ; addConstraintSpecification : ADD (outOfLineConstraint+ | outOfLineRefConstraint) ; modifyConstraintClause : MODIFY constraintOption constraintState+ CASCADE? ; constraintWithName : CONSTRAINT ignoredIdentifier_ ; constraintOption : constraintWithName | constraintPrimaryOrUnique ; constraintPrimaryOrUnique : primaryKey | UNIQUE columnNames ; renameConstraintClause : RENAME constraintWithName TO ignoredIdentifier_ ; dropConstraintClause : DROP ( constraintPrimaryOrUnique CASCADE? ((KEEP | DROP) INDEX)? | (CONSTRAINT ignoredIdentifier_ CASCADE?) ) ; alterExternalTable : (addColumnSpecification | modifyColumnSpecification | dropColumnSpecification)+ ; columnDefinition : columnName dataType SORT? (VISIBLE | INVISIBLE)? (DEFAULT (ON NULL)? expr | identityClause)? (ENCRYPT encryptionSpec)? (inlineConstraint+ | inlineRefConstraint)? ; identityClause : GENERATED (ALWAYS | BY DEFAULT (ON NULL)?) AS IDENTITY LP_? (identityOptions+)? RP_? ; identityOptions : START WITH (NUMBER_ | LIMIT VALUE) | INCREMENT BY NUMBER_ | MAXVALUE NUMBER_ | NOMAXVALUE | MINVALUE NUMBER_ | NOMINVALUE | CYCLE | NOCYCLE | CACHE NUMBER_ | NOCACHE | ORDER | NOORDER ; virtualColumnDefinition : columnName dataType? (GENERATED ALWAYS)? AS LP_ expr RP_ VIRTUAL? inlineConstraint* ; inlineConstraint : (CONSTRAINT ignoredIdentifier_)? (NOT? NULL | UNIQUE | primaryKey | referencesClause | CHECK LP_ expr RP_) constraintState* ; referencesClause : REFERENCES tableName columnNames? (ON DELETE (CASCADE | SET NULL))? ; constraintState : notDeferrable | initiallyClause | RELY | NORELY | usingIndexClause | ENABLE | DISABLE | VALIDATE | NOVALIDATE | exceptionsClause ; notDeferrable : NOT? DEFERRABLE ; initiallyClause : INITIALLY (IMMEDIATE | DEFERRED) ; exceptionsClause : EXCEPTIONS INTO ; usingIndexClause : USING INDEX (indexName | LP_ createIndex RP_)? ; inlineRefConstraint : SCOPE IS tableName | WITH ROWID | (CONSTRAINT ignoredIdentifier_)? referencesClause constraintState* ; outOfLineConstraint : (CONSTRAINT ignoredIdentifier_)? ( UNIQUE columnNames | primaryKey columnNames | FOREIGN KEY columnNames referencesClause | CHECK LP_ expr RP_ ) constraintState* ; outOfLineRefConstraint : SCOPE FOR LP_ lobItem RP_ IS tableName | REF LP_ lobItem RP_ WITH ROWID | (CONSTRAINT ignoredIdentifier_)? FOREIGN KEY lobItemList referencesClause constraintState* ; encryptionSpec : (USING STRING_)? (IDENTIFIED BY STRING_)? STRING_? (NO? SALT)? ; objectProperties : objectProperty (COMMA_ objectProperty)* ; objectProperty : (columnName | attributeName) (DEFAULT expr)? (inlineConstraint* | inlineRefConstraint?) | outOfLineConstraint | outOfLineRefConstraint ; columnProperties : columnProperty+ ; columnProperty : objectTypeColProperties ; objectTypeColProperties : COLUMN columnName substitutableColumnClause ; substitutableColumnClause : ELEMENT? IS OF TYPE? LP_ ONLY? dataTypeName_ RP_ | NOT? SUBSTITUTABLE AT ALL LEVELS ; tableIndexClause_ : tableName alias? LP_ indexExpr_ (COMMA_ indexExpr_)* RP_ ; indexExpr_ : (columnName | expr) (ASC | DESC)? ; bitmapJoinIndexClause_ : tableName LP_ columnSortClause_ (COMMA_ columnSortClause_)* RP_ FROM tableName alias? (COMMA_ tableName alias?)* WHERE expr ; columnSortClause_ : tableName alias? columnName (ASC | DESC)? ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE temporaryClause_ TABLE tableName relationalTable ; createIndex : CREATE (UNIQUE | BITMAP)? INDEX indexName ON (tableIndexClause_ | bitmapJoinIndexClause_) ; alterTable : ALTER TABLE tableName (alterTableProperties | columnClauses | constraintClauses | alterExternalTable)? ; // TODO hongjun throw exeption when alter index on oracle alterIndex : ALTER INDEX indexName (RENAME TO indexName)? ; dropTable : DROP TABLE tableName ; dropIndex : DROP INDEX indexName ; truncateTable : TRUNCATE TABLE tableName ; temporaryClause_ : (GLOBAL TEMPORARY)? ; tablespaceClauseWithParen : LP_ tablespaceClause RP_ ; tablespaceClause : TABLESPACE ignoredIdentifier_ ; domainIndexClause : indexTypeName ; relationalTable : (LP_ relationalProperties RP_)? (ON COMMIT (DELETE | PRESERVE) ROWS)? ; relationalProperties : relationalProperty (COMMA_ relationalProperty)* ; relationalProperty : columnDefinition | virtualColumnDefinition | outOfLineConstraint | outOfLineRefConstraint ; tableProperties : columnProperties? (AS unionSelect)? ; unionSelect : matchNone ; alterTableProperties : renameTableSpecification_ | REKEY encryptionSpec ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; columnClauses : opColumnClause+ | renameColumnSpecification ; opColumnClause : addColumnSpecification | modifyColumnSpecification | dropColumnClause ; addColumnSpecification : ADD columnOrVirtualDefinitions columnProperties? ; columnOrVirtualDefinitions : LP_ columnOrVirtualDefinition (COMMA_ columnOrVirtualDefinition)* RP_ | columnOrVirtualDefinition ; columnOrVirtualDefinition : columnDefinition | virtualColumnDefinition ; modifyColumnSpecification : MODIFY (LP_? modifyColProperties (COMMA_ modifyColProperties)* RP_? | modifyColSubstitutable) ; modifyColProperties : columnName dataType? (DEFAULT expr)? (ENCRYPT encryptionSpec | DECRYPT)? inlineConstraint* ; modifyColSubstitutable : COLUMN columnName NOT? SUBSTITUTABLE AT ALL LEVELS FORCE? ; dropColumnClause : SET UNUSED columnOrColumnList cascadeOrInvalidate* | dropColumnSpecification ; dropColumnSpecification : DROP columnOrColumnList cascadeOrInvalidate* checkpointNumber? ; columnOrColumnList : COLUMN columnName | LP_ columnName (COMMA_ columnName)* RP_ ; cascadeOrInvalidate : CASCADE CONSTRAINTS | INVALIDATE ; checkpointNumber : CHECKPOINT NUMBER_ ; renameColumnSpecification : RENAME COLUMN columnName TO columnName ; constraintClauses : addConstraintSpecification | modifyConstraintClause | renameConstraintClause | dropConstraintClause+ ; addConstraintSpecification : ADD (outOfLineConstraint+ | outOfLineRefConstraint) ; modifyConstraintClause : MODIFY constraintOption constraintState+ CASCADE? ; constraintWithName : CONSTRAINT ignoredIdentifier_ ; constraintOption : constraintWithName | constraintPrimaryOrUnique ; constraintPrimaryOrUnique : primaryKey | UNIQUE columnNames ; renameConstraintClause : RENAME constraintWithName TO ignoredIdentifier_ ; dropConstraintClause : DROP ( constraintPrimaryOrUnique CASCADE? ((KEEP | DROP) INDEX)? | (CONSTRAINT ignoredIdentifier_ CASCADE?) ) ; alterExternalTable : (addColumnSpecification | modifyColumnSpecification | dropColumnSpecification)+ ; columnDefinition : columnName dataType SORT? (VISIBLE | INVISIBLE)? (DEFAULT (ON NULL)? expr | identityClause)? (ENCRYPT encryptionSpec)? (inlineConstraint+ | inlineRefConstraint)? ; identityClause : GENERATED (ALWAYS | BY DEFAULT (ON NULL)?) AS IDENTITY LP_? (identityOptions+)? RP_? ; identityOptions : START WITH (NUMBER_ | LIMIT VALUE) | INCREMENT BY NUMBER_ | MAXVALUE NUMBER_ | NOMAXVALUE | MINVALUE NUMBER_ | NOMINVALUE | CYCLE | NOCYCLE | CACHE NUMBER_ | NOCACHE | ORDER | NOORDER ; virtualColumnDefinition : columnName dataType? (GENERATED ALWAYS)? AS LP_ expr RP_ VIRTUAL? inlineConstraint* ; inlineConstraint : (CONSTRAINT ignoredIdentifier_)? (NOT? NULL | UNIQUE | primaryKey | referencesClause | CHECK LP_ expr RP_) constraintState* ; referencesClause : REFERENCES tableName columnNames? (ON DELETE (CASCADE | SET NULL))? ; constraintState : notDeferrable | initiallyClause | RELY | NORELY | usingIndexClause | ENABLE | DISABLE | VALIDATE | NOVALIDATE | exceptionsClause ; notDeferrable : NOT? DEFERRABLE ; initiallyClause : INITIALLY (IMMEDIATE | DEFERRED) ; exceptionsClause : EXCEPTIONS INTO tableName ; usingIndexClause : USING INDEX (indexName | LP_ createIndex RP_)? ; inlineRefConstraint : SCOPE IS tableName | WITH ROWID | (CONSTRAINT ignoredIdentifier_)? referencesClause constraintState* ; outOfLineConstraint : (CONSTRAINT ignoredIdentifier_)? (UNIQUE columnNames | primaryKey columnNames | FOREIGN KEY columnNames referencesClause | CHECK LP_ expr RP_ ) constraintState* ; outOfLineRefConstraint : SCOPE FOR LP_ lobItem RP_ IS tableName | REF LP_ lobItem RP_ WITH ROWID | (CONSTRAINT ignoredIdentifier_)? FOREIGN KEY lobItemList referencesClause constraintState* ; encryptionSpec : (USING STRING_)? (IDENTIFIED BY STRING_)? STRING_? (NO? SALT)? ; objectProperties : objectProperty (COMMA_ objectProperty)* ; objectProperty : (columnName | attributeName) (DEFAULT expr)? (inlineConstraint* | inlineRefConstraint?) | outOfLineConstraint | outOfLineRefConstraint ; columnProperties : columnProperty+ ; columnProperty : objectTypeColProperties ; objectTypeColProperties : COLUMN columnName substitutableColumnClause ; substitutableColumnClause : ELEMENT? IS OF TYPE? LP_ ONLY? dataTypeName_ RP_ | NOT? SUBSTITUTABLE AT ALL LEVELS ; tableIndexClause_ : tableName alias? LP_ indexExpr_ (COMMA_ indexExpr_)* RP_ ; indexExpr_ : (columnName | expr) (ASC | DESC)? ; bitmapJoinIndexClause_ : tableName LP_ columnSortClause_ (COMMA_ columnSortClause_)* RP_ FROM tableName alias? (COMMA_ tableName alias?)* WHERE expr ; columnSortClause_ : tableName alias? columnName (ASC | DESC)? ;
modify constraintState
modify constraintState
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
8bd4cdad2f524339dd5f0376dce03c90572a5164
PS.g4
PS.g4
grammar PS; options { language=Python2; } WS: [ \t\r\n]+ -> skip; ADD: '+'; SUB: '-'; MUL: '*'; DIV: '/'; L_PAREN: '('; R_PAREN: ')'; L_BRACE: '{'; R_BRACE: '}'; L_BRACKET: '['; R_BRACKET: ']'; BAR: '|'; FUNC_LIM: '\\lim'; LIM_APPROACH_SYM: '\\to' | '\\rightarrow' | '\\Rightarrow'; FUNC_INT: '\\int'; FUNC_SUM: '\\sum'; FUNC_PROD: '\\prod'; FUNC_LOG: '\\log'; FUNC_LN: '\\ln'; FUNC_SIN: '\\sin'; FUNC_COS: '\\cos'; FUNC_TAN: '\\tan'; FUNC_CSC: '\\csc'; FUNC_SEC: '\\sec'; FUNC_COT: '\\cot'; FUNC_ARCSIN: '\\arcsin'; FUNC_ARCCOS: '\\arccos'; FUNC_ARCTAN: '\\arctan'; FUNC_ARCCSC: '\\arccsc'; FUNC_ARCSEC: '\\arcsec'; FUNC_ARCCOT: '\\arccot'; FUNC_SQRT: '\\sqrt'; CMD_TIMES: '\\times'; CMD_CDOT: '\\cdot'; CMD_DIV: '\\div'; CMD_FRAC: '\\frac'; UNDERSCORE: '_'; CARET: '^'; DIFFERENTIAL: 'd' ([a-zA-Z] | '\\' [a-zA-Z]+); LETTER: [a-zA-Z]; fragment DIGIT: [0-9]; NUMBER: DIGIT+ (',' DIGIT DIGIT DIGIT)* | DIGIT* (',' DIGIT DIGIT DIGIT)* '.' DIGIT+; EQUAL: '='; LT: '<'; LTE: '\\leq'; GT: '>'; GTE: '\\geq'; BANG: '!'; SYMBOL: '\\' [a-zA-Z]+; math: relation; relation: relation (EQUAL | LT | LTE | GT | GTE) relation | expr; equality: expr EQUAL expr; expr: additive; additive: additive ADD additive | additive SUB additive | mp; // mult part mp: mp (MUL | CMD_TIMES | CMD_CDOT) mp | mp (DIV | CMD_DIV) mp | unary; unary: (ADD | SUB) unary | postfix+; postfix: exp postfix_op*; postfix_op: BANG | eval_at; eval_at: BAR (eval_at_sup | eval_at_sub | eval_at_sup eval_at_sub); eval_at_sub: UNDERSCORE L_BRACE (expr | equality) R_BRACE; eval_at_sup: CARET L_BRACE (expr | equality) R_BRACE; exp: exp CARET (atom | L_BRACE expr R_BRACE) subexpr? | comp; comp: group | abs_group | atom | frac | func; group: L_PAREN expr R_PAREN | L_BRACKET expr R_BRACKET; abs_group: BAR expr BAR; atom: (LETTER | SYMBOL) subexpr? | NUMBER | DIFFERENTIAL; frac: CMD_FRAC L_BRACE (letter1=LETTER | (letter1=LETTER? upper=expr)) R_BRACE L_BRACE (DIFFERENTIAL | lower=expr) R_BRACE; func_normal: FUNC_LOG | FUNC_LN | FUNC_SIN | FUNC_COS | FUNC_TAN | FUNC_CSC | FUNC_SEC | FUNC_COT | FUNC_ARCSIN | FUNC_ARCCOS | FUNC_ARCTAN | FUNC_ARCCSC | FUNC_ARCSEC | FUNC_ARCCOT; func: func_normal (subexpr? supexpr? | supexpr? subexpr?) func_arg | FUNC_INT (subexpr supexpr | supexpr subexpr)? (additive? DIFFERENTIAL | frac | additive) | FUNC_SQRT L_BRACE expr R_BRACE | (FUNC_SUM | FUNC_PROD) (subeq supexpr | supexpr subeq) mp | FUNC_LIM limit_sub mp; limit_sub: UNDERSCORE L_BRACE (LETTER | SYMBOL) LIM_APPROACH_SYM expr (CARET L_BRACE (ADD | SUB) R_BRACE)? R_BRACE; func_arg: atom+ | comp; subexpr: UNDERSCORE L_BRACE expr R_BRACE; supexpr: CARET L_BRACE expr R_BRACE; subeq: UNDERSCORE L_BRACE equality R_BRACE; supeq: UNDERSCORE L_BRACE equality R_BRACE;
grammar PS; options { language=Python2; } WS: [ \t\r\n]+ -> skip; ADD: '+'; SUB: '-'; MUL: '*'; DIV: '/'; L_PAREN: '('; R_PAREN: ')'; L_BRACE: '{'; R_BRACE: '}'; L_BRACKET: '['; R_BRACKET: ']'; BAR: '|'; FUNC_LIM: '\\lim'; LIM_APPROACH_SYM: '\\to' | '\\rightarrow' | '\\Rightarrow'; FUNC_INT: '\\int'; FUNC_SUM: '\\sum'; FUNC_PROD: '\\prod'; FUNC_LOG: '\\log'; FUNC_LN: '\\ln'; FUNC_SIN: '\\sin'; FUNC_COS: '\\cos'; FUNC_TAN: '\\tan'; FUNC_CSC: '\\csc'; FUNC_SEC: '\\sec'; FUNC_COT: '\\cot'; FUNC_ARCSIN: '\\arcsin'; FUNC_ARCCOS: '\\arccos'; FUNC_ARCTAN: '\\arctan'; FUNC_ARCCSC: '\\arccsc'; FUNC_ARCSEC: '\\arcsec'; FUNC_ARCCOT: '\\arccot'; FUNC_SQRT: '\\sqrt'; CMD_TIMES: '\\times'; CMD_CDOT: '\\cdot'; CMD_DIV: '\\div'; CMD_FRAC: '\\frac'; UNDERSCORE: '_'; CARET: '^'; DIFFERENTIAL: 'd' ([a-zA-Z] | '\\' [a-zA-Z]+); LETTER: [a-zA-Z]; fragment DIGIT: [0-9]; NUMBER: DIGIT+ (',' DIGIT DIGIT DIGIT)* | DIGIT* (',' DIGIT DIGIT DIGIT)* '.' DIGIT+; EQUAL: '='; LT: '<'; LTE: '\\leq'; GT: '>'; GTE: '\\geq'; BANG: '!'; SYMBOL: '\\' [a-zA-Z]+; math: relation; relation: relation (EQUAL | LT | LTE | GT | GTE) relation | expr; equality: expr EQUAL expr; expr: additive; additive: additive (ADD | SUB) additive | mp; // mult part mp: mp (MUL | CMD_TIMES | CMD_CDOT | DIV | CMD_DIV) mp | unary; unary: (ADD | SUB) unary | postfix+; postfix: exp postfix_op*; postfix_op: BANG | eval_at; eval_at: BAR (eval_at_sup | eval_at_sub | eval_at_sup eval_at_sub); eval_at_sub: UNDERSCORE L_BRACE (expr | equality) R_BRACE; eval_at_sup: CARET L_BRACE (expr | equality) R_BRACE; exp: exp CARET (atom | L_BRACE expr R_BRACE) subexpr? | comp; comp: group | abs_group | atom | frac | func; group: L_PAREN expr R_PAREN | L_BRACKET expr R_BRACKET; abs_group: BAR expr BAR; atom: (LETTER | SYMBOL) subexpr? | NUMBER | DIFFERENTIAL; frac: CMD_FRAC L_BRACE (letter1=LETTER | (letter1=LETTER? upper=expr)) R_BRACE L_BRACE (DIFFERENTIAL | lower=expr) R_BRACE; func_normal: FUNC_LOG | FUNC_LN | FUNC_SIN | FUNC_COS | FUNC_TAN | FUNC_CSC | FUNC_SEC | FUNC_COT | FUNC_ARCSIN | FUNC_ARCCOS | FUNC_ARCTAN | FUNC_ARCCSC | FUNC_ARCSEC | FUNC_ARCCOT; func: func_normal (subexpr? supexpr? | supexpr? subexpr?) func_arg | FUNC_INT (subexpr supexpr | supexpr subexpr)? (additive? DIFFERENTIAL | frac | additive) | FUNC_SQRT L_BRACE expr R_BRACE | (FUNC_SUM | FUNC_PROD) (subeq supexpr | supexpr subeq) mp | FUNC_LIM limit_sub mp; limit_sub: UNDERSCORE L_BRACE (LETTER | SYMBOL) LIM_APPROACH_SYM expr (CARET L_BRACE (ADD | SUB) R_BRACE)? R_BRACE; func_arg: atom+ | comp; subexpr: UNDERSCORE L_BRACE expr R_BRACE; supexpr: CARET L_BRACE expr R_BRACE; subeq: UNDERSCORE L_BRACE equality R_BRACE; supeq: UNDERSCORE L_BRACE equality R_BRACE;
Fix weird behavior
Fix weird behavior
ANTLR
mit
augustt198/latex2sympy
32cbd1599029ca66a709fdd13a41625e162b1caa
java-vtl-parser/src/main/antlr4/no/ssb/vtl/parser/VTL.g4
java-vtl-parser/src/main/antlr4/no/ssb/vtl/parser/VTL.g4
/*- * #%L * Java VTL * %% * Copyright (C) 2016 Hadrien Kohl * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ grammar VTL; start : statement+ EOF; /* Assignment */ statement : variableID ':=' datasetExpression; /* Expressions */ datasetExpression : <assoc=right>datasetExpression clauseExpression #withClause | relationalExpression #withRelational | getExpression #withGet | putExpression #withPut | exprAtom #withAtom ; getExpression : 'get' '(' datasetId ')'; putExpression : 'put(todo)'; datasetId : STRING_CONSTANT ; /* Atom */ exprAtom : variableRef; datasetRef: variableRef ; componentRef : ( datasetRef '.')? variableRef ; variableRef : identifier; identifier : '\'' STRING_CONSTANT '\'' | IDENTIFIER ; variableID : IDENTIFIER ; constant : INTEGER_CONSTANT | FLOAT_CONSTANT | BOOLEAN_CONSTANT | STRING_CONSTANT | NULL_CONSTANT; clauseExpression : '[' clause ']' ; clause : 'rename' renameParam (',' renameParam)* #renameClause | filter #filterClause | keep #keepClause | calc #calcClause | attrcalc #attrcalcClause | aggregate #aggregateClause ; // [ rename component as string, // component as string role = IDENTIFIER, // component as string role = MEASURE, // component as string role = ATTRIBUTE // ] renameParam : from=componentRef 'as' to=componentRef ( 'role' '=' role )? ; role : ( 'IDENTIFIER' | 'MEASURE' | 'ATTRIBUTE' ) ; filter : 'filter' booleanExpression ; keep : 'keep' booleanExpression ( ',' booleanExpression )* ; calc : 'calc' ; attrcalc : 'attrcalc' ; aggregate : 'aggregate' ; //booleanExpression : 'booleanExpression' ; //varID : 'varId'; //WS : [ \t\n\t] -> skip ; booleanExpression : booleanExpression AND booleanExpression | booleanExpression ( OR booleanExpression | XOR booleanExpression ) | booleanEquallity | BOOLEAN_CONSTANT ; booleanEquallity : booleanEquallity ( ( EQ | NE | LE | GE ) booleanEquallity ) | datasetExpression // typed constant? ; //datasetExpression // : 'dsTest' // ; EQ : '=' ; NE : '<>' ; LE : '<=' ; GE : '>=' ; AND : 'and' ; OR : 'or' ; XOR : 'xor' ; //WS : [ \r\t\u000C] -> skip ; relationalExpression : unionExpression | joinExpression ; unionExpression : 'union' '(' datasetExpression (',' datasetExpression )* ')' ; joinExpression : '[' joinDefinition ']' '{' joinBody '}'; joinDefinition : INNER? joinParam #joinDefinitionInner | OUTER joinParam #joinDefinitionOuter | CROSS joinParam #joinDefinitionCross ; joinParam : datasetRef (',' datasetRef )* ( 'on' dimensionExpression (',' dimensionExpression )* )? ; dimensionExpression : IDENTIFIER; //unimplemented joinBody : joinClause (',' joinClause)* ; joinClause : role? variableID '=' joinCalcExpression # joinCalcClause | joinDropExpression # joinDropClause | joinKeepExpression # joinKeepClause | joinRenameExpression # joinRenameClause | joinFilterExpression # joinFilterClause | joinFoldExpression # joinFoldClause | joinUnfoldExpression # joinUnfoldClause ; joinFoldExpression : 'fold' elements=foldUnfoldElements 'to' dimension=identifier ',' measure=identifier ; joinUnfoldExpression : 'unfold' dimension=componentRef ',' measure=componentRef 'to' elements=foldUnfoldElements ; // TODO: The spec writes examples with parentheses, but it seems unecessary to me. // TODO: The spec is unclear regarding types of the elements, we support strings only for now. // TODO: Reuse component references foldUnfoldElements : STRING_CONSTANT (',' STRING_CONSTANT)* ; // Left recursive joinCalcExpression : leftOperand=joinCalcExpression sign=( '*' | '/' ) rightOperand=joinCalcExpression #joinCalcProduct | leftOperand=joinCalcExpression sign=( '+' | '-' ) rightOperand=joinCalcExpression #joinCalcSummation | '(' joinCalcExpression ')' #joinCalcPrecedence | componentRef #joinCalcReference | constant #joinCalcAtom ; // Drop clause joinDropExpression : 'drop' componentRef (',' componentRef)* ; // Keep clause joinKeepExpression : 'keep' componentRef (',' componentRef)* ; // TODO: Use in keep, drop and calc. // TODO: Make this the membership operator. // TODO: Revise this when the final version of the specification precisely define if the rename needs ' or not. // Rename clause joinRenameExpression : 'rename' joinRenameParameter (',' joinRenameParameter)* ; joinRenameParameter : from=componentRef 'to' to=identifier ; // Filter clause joinFilterExpression : 'filter' booleanExpression ; //role : ( 'IDENTIFIER' | 'MEASURE' | 'ATTRIBUTE' ) ; INNER : 'inner' ; OUTER : 'outer' ; CROSS : 'cross' ; INTEGER_CONSTANT : DIGIT+; BOOLEAN_CONSTANT : 'true' | 'false' ; STRING_CONSTANT :'"' (~'"')* '"'; FLOAT_CONSTANT : (DIGIT)+ '.' (DIGIT)* FLOATEXP? | (DIGIT)+ FLOATEXP ; NULL_CONSTANT : 'null'; IDENTIFIER : REG_IDENTIFIER | ESCAPED_IDENTIFIER ; //regular identifiers start with a (lowercase or uppercase) English alphabet letter, followed by zero or more letters, decimal digits, or underscores fragment REG_IDENTIFIER: LETTER(LETTER|'_'|DIGIT)* ; //TODO: Case insensitive?? //VTL 1.1 allows us to escape the limitations imposed on regular identifiers by enclosing them in single quotes (apostrophes). fragment ESCAPED_IDENTIFIER: QUOTE (~'\'' | '\'\'')+ QUOTE; fragment QUOTE : '\''; PLUS : '+'; MINUS : '-'; fragment DIGIT : '0'..'9' ; fragment FLOATEXP : ('e'|'E')(PLUS|MINUS)?('0'..'9')+; fragment LETTER : 'A'..'Z' | 'a'..'z'; WS : [ \n\r\t\u000C] -> skip ; COMMENT : '/*' .*? '*/' -> skip;
/*- * #%L * Java VTL * %% * Copyright (C) 2016 Hadrien Kohl * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ grammar VTL; start : statement+ EOF; /* Assignment */ statement : variableID ':=' datasetExpression | variableID ':=' block ; block : '{' statement+ '}' ; /* Expressions */ datasetExpression : <assoc=right>datasetExpression clauseExpression #withClause | relationalExpression #withRelational | getExpression #withGet | putExpression #withPut | exprAtom #withAtom ; getExpression : 'get' '(' datasetId ')'; putExpression : 'put(todo)'; datasetId : STRING_CONSTANT ; /* Atom */ exprAtom : variableRef; datasetRef: variableRef ; componentRef : ( datasetRef '.')? variableRef ; variableRef : identifier; identifier : '\'' STRING_CONSTANT '\'' | IDENTIFIER ; variableID : IDENTIFIER ; constant : INTEGER_CONSTANT | FLOAT_CONSTANT | BOOLEAN_CONSTANT | STRING_CONSTANT | NULL_CONSTANT; clauseExpression : '[' clause ']' ; clause : 'rename' renameParam (',' renameParam)* #renameClause | filter #filterClause | keep #keepClause | calc #calcClause | attrcalc #attrcalcClause | aggregate #aggregateClause ; // [ rename component as string, // component as string role = IDENTIFIER, // component as string role = MEASURE, // component as string role = ATTRIBUTE // ] renameParam : from=componentRef 'as' to=componentRef ( 'role' '=' role )? ; role : ( 'IDENTIFIER' | 'MEASURE' | 'ATTRIBUTE' ) ; filter : 'filter' booleanExpression ; keep : 'keep' booleanExpression ( ',' booleanExpression )* ; calc : 'calc' ; attrcalc : 'attrcalc' ; aggregate : 'aggregate' ; //booleanExpression : 'booleanExpression' ; //varID : 'varId'; //WS : [ \t\n\t] -> skip ; booleanExpression : booleanExpression AND booleanExpression | booleanExpression ( OR booleanExpression | XOR booleanExpression ) | booleanEquallity | BOOLEAN_CONSTANT ; booleanEquallity : booleanEquallity ( ( EQ | NE | LE | GE ) booleanEquallity ) | datasetExpression // typed constant? ; //datasetExpression // : 'dsTest' // ; EQ : '=' ; NE : '<>' ; LE : '<=' ; GE : '>=' ; AND : 'and' ; OR : 'or' ; XOR : 'xor' ; //WS : [ \r\t\u000C] -> skip ; relationalExpression : unionExpression | joinExpression ; unionExpression : 'union' '(' datasetExpression (',' datasetExpression )* ')' ; joinExpression : '[' joinDefinition ']' '{' joinBody '}'; joinDefinition : INNER? joinParam #joinDefinitionInner | OUTER joinParam #joinDefinitionOuter | CROSS joinParam #joinDefinitionCross ; joinParam : datasetRef (',' datasetRef )* ( 'on' dimensionExpression (',' dimensionExpression )* )? ; dimensionExpression : IDENTIFIER; //unimplemented joinBody : joinClause (',' joinClause)* ; joinClause : role? variableID '=' joinCalcExpression # joinCalcClause | joinDropExpression # joinDropClause | joinKeepExpression # joinKeepClause | joinRenameExpression # joinRenameClause | joinFilterExpression # joinFilterClause | joinFoldExpression # joinFoldClause | joinUnfoldExpression # joinUnfoldClause ; joinFoldExpression : 'fold' elements=foldUnfoldElements 'to' dimension=identifier ',' measure=identifier ; joinUnfoldExpression : 'unfold' dimension=componentRef ',' measure=componentRef 'to' elements=foldUnfoldElements ; // TODO: The spec writes examples with parentheses, but it seems unecessary to me. // TODO: The spec is unclear regarding types of the elements, we support strings only for now. // TODO: Reuse component references foldUnfoldElements : STRING_CONSTANT (',' STRING_CONSTANT)* ; // Left recursive joinCalcExpression : leftOperand=joinCalcExpression sign=( '*' | '/' ) rightOperand=joinCalcExpression #joinCalcProduct | leftOperand=joinCalcExpression sign=( '+' | '-' ) rightOperand=joinCalcExpression #joinCalcSummation | '(' joinCalcExpression ')' #joinCalcPrecedence | componentRef #joinCalcReference | constant #joinCalcAtom ; // Drop clause joinDropExpression : 'drop' componentRef (',' componentRef)* ; // Keep clause joinKeepExpression : 'keep' componentRef (',' componentRef)* ; // TODO: Use in keep, drop and calc. // TODO: Make this the membership operator. // TODO: Revise this when the final version of the specification precisely define if the rename needs ' or not. // Rename clause joinRenameExpression : 'rename' joinRenameParameter (',' joinRenameParameter)* ; joinRenameParameter : from=componentRef 'to' to=identifier ; // Filter clause joinFilterExpression : 'filter' booleanExpression ; //role : ( 'IDENTIFIER' | 'MEASURE' | 'ATTRIBUTE' ) ; INNER : 'inner' ; OUTER : 'outer' ; CROSS : 'cross' ; INTEGER_CONSTANT : DIGIT+; BOOLEAN_CONSTANT : 'true' | 'false' ; STRING_CONSTANT :'"' (~'"')* '"'; FLOAT_CONSTANT : (DIGIT)+ '.' (DIGIT)* FLOATEXP? | (DIGIT)+ FLOATEXP ; NULL_CONSTANT : 'null'; IDENTIFIER : REG_IDENTIFIER | ESCAPED_IDENTIFIER ; //regular identifiers start with a (lowercase or uppercase) English alphabet letter, followed by zero or more letters, decimal digits, or underscores fragment REG_IDENTIFIER: LETTER(LETTER|'_'|DIGIT)* ; //TODO: Case insensitive?? //VTL 1.1 allows us to escape the limitations imposed on regular identifiers by enclosing them in single quotes (apostrophes). fragment ESCAPED_IDENTIFIER: QUOTE (~'\'' | '\'\'')+ QUOTE; fragment QUOTE : '\''; PLUS : '+'; MINUS : '-'; fragment DIGIT : '0'..'9' ; fragment FLOATEXP : ('e'|'E')(PLUS|MINUS)?('0'..'9')+; fragment LETTER : 'A'..'Z' | 'a'..'z'; WS : [ \n\r\t\u000C] -> skip ; COMMENT : '/*' .*? '*/' -> skip;
Introduce bloc
Introduce bloc
ANTLR
apache-2.0
statisticsnorway/java-vtl,statisticsnorway/java-vtl,statisticsnorway/java-vtl,hadrienk/java-vtl,hadrienk/java-vtl,statisticsnorway/java-vtl,hadrienk/java-vtl
53cbc9fb885846107254ed34406898bb6d2b38df
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
grammar OracleDCLStatement; import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol; /** * each statement has a url, * each base url : https://docs.oracle.com/database/121/SQLRF/. * no begin statement in oracle */ //statements_9014.htm#SQLRF01603 grant : GRANT ( (grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))? | grantRolesToPrograms ) ; grantSystemPrivileges : systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)? ; systemObjects : systemObject(COMMA systemObject)* ; systemObject : ALL PRIVILEGES | roleName | ID *? ; grantees : grantee (COMMA grantee)* ; grantee : userName | roleName | PUBLIC ; granteeIdentifiedBy : userNames IDENTIFIED BY STRING (COMMA STRING)* ; grantObjectPrivilegeClause : grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause TO grantees (WITH HIERARCHY OPTION)?(WITH GRANT OPTION)? ; grantObjectPrivilege : objectPrivilege columnList? ; objectPrivilege : ID *? | ALL PRIVILEGES? ; onObjectClause : ON ( schemaName? ID | USER userName ( COMMA userName)* | (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID ) ; grantRolesToPrograms : roleNames TO programUnits ; programUnits : programUnit (COMMA programUnit)* ; programUnit : (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID ; revoke : REVOKE ( (revokeSystemPrivileges | revokeObjectPrivileges) (CONTAINER EQ_ (CURRENT | ALL))? | revokeRolesFromPrograms ) ; revokeSystemPrivileges : systemObjects FROM ; revokeObjectPrivileges : objectPrivilege (COMMA objectPrivilege)* onObjectClause FROM grantees (CASCADE CONSTRAINTS | FORCE)? ; revokeRolesFromPrograms : (roleNames | ALL) FROM programUnits ; createUser : CREATE USER userName IDENTIFIED (BY STRING | (EXTERNALLY | GLOBALLY) ( AS STRING)?) ( DEFAULT TABLESPACE ID | TEMPORARY TABLESPACE ID | (QUOTA (sizeClause | UNLIMITED) ON ID) | PROFILE ID | PASSWORD EXPIRE | ACCOUNT (LOCK | UNLOCK) | ENABLE EDITIONS | CONTAINER EQ_ (CURRENT | ALL) )* ; sizeClause : NUMBER ID? ; dbUserProxyClauses : (WITH ( ROLE (ALL EXCEPT)? roleNames | NO ROLES ) )? (AUTHENTICATION REQUIRED )? ;
grammar OracleDCLStatement; import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol; /** * each statement has a url, * each base url : https://docs.oracle.com/database/121/SQLRF/. * no begin statement in oracle */ //statements_9014.htm#SQLRF01603 grant : GRANT ( (grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))? | grantRolesToPrograms ) ; grantSystemPrivileges : systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)? ; systemObjects : systemObject(COMMA systemObject)* ; systemObject : ALL PRIVILEGES | roleName | ID *? ; grantees : grantee (COMMA grantee)* ; grantee : userName | roleName | PUBLIC ; granteeIdentifiedBy : userNames IDENTIFIED BY STRING (COMMA STRING)* ; grantObjectPrivilegeClause : grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause TO grantees (WITH HIERARCHY OPTION)?(WITH GRANT OPTION)? ; grantObjectPrivilege : objectPrivilege columnList? ; objectPrivilege : ID *? | ALL PRIVILEGES? ; onObjectClause : ON ( schemaName? ID | USER userName ( COMMA userName)* | (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID ) ; grantRolesToPrograms : roleNames TO programUnits ; programUnits : programUnit (COMMA programUnit)* ; programUnit : (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID ; revoke : REVOKE ( (revokeSystemPrivileges | revokeObjectPrivileges) (CONTAINER EQ_ (CURRENT | ALL))? | revokeRolesFromPrograms ) ; revokeSystemPrivileges : systemObjects FROM ; revokeObjectPrivileges : objectPrivilege (COMMA objectPrivilege)* onObjectClause FROM grantees (CASCADE CONSTRAINTS | FORCE)? ; revokeRolesFromPrograms : (roleNames | ALL) FROM programUnits ; createUser : CREATE USER userName IDENTIFIED (BY STRING | (EXTERNALLY | GLOBALLY) ( AS STRING)?) ( DEFAULT TABLESPACE ID | TEMPORARY TABLESPACE ID | (QUOTA (sizeClause | UNLIMITED) ON ID) | PROFILE ID | PASSWORD EXPIRE | ACCOUNT (LOCK | UNLOCK) | ENABLE EDITIONS | CONTAINER EQ_ (CURRENT | ALL) )* ; sizeClause : NUMBER ID? ; proxyClause : (GRANT | REVOKE) CONNECT THROUGH ( ENTERPRISE USERS | userName dbUserProxyClauses?) ; dbUserProxyClauses : (WITH ( ROLE (ALL EXCEPT)? roleNames | NO ROLES ) )? (AUTHENTICATION REQUIRED )? ;
add proxyClause
add proxyClause
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
2037acfa8be56f6ab1a55c686cdca2ea0b3fa713
turin-parser/src/main/antlr4/me/tomassetti/parser/antlr/TurinParser.g4
turin-parser/src/main/antlr4/me/tomassetti/parser/antlr/TurinParser.g4
grammar TurinParser; @header { } turinFile: namespace=namespaceDecl nls (imports+=importDeclaration)* (members+=fileMember)+ EOF; // Base nls: NL+; qualifiedId: (parts+=ID POINT)* parts+=ID; // Namespace namespaceDecl: NAMESPACE_KW name=qualifiedId; // Imports importDeclaration: typeImportDeclaration | singleFieldImportDeclaration | allFieldsImportDeclaration; typeImportDeclaration: packagePart=qualifiedId POINT typeName=ID nls; singleFieldImportDeclaration: packagePart=qualifiedId POINT typeName=ID POINT fieldName=ID nls; allFieldsImportDeclaration: packagePart=qualifiedId POINT typeName=ID POINT ASTERISK nls; // typeUsage: ref=TID | arrayBase=typeUsage LSQUARE RSQUARE; // topLevelPropertyDeclaration: PROPERTY_KW type=typeUsage COLON name=ID nls; inTypePropertyDeclaration: HAS_KW type=typeUsage COLON name=ID nls; propertyReference: HAS_KW name=ID nls; typeMember: inTypePropertyDeclaration | propertyReference; typeDeclaration: TYPE_KW name=TID LBRACKET nls (typeMembers += typeMember)* RBRACKET nls; // actualParam: expression | name=ID ASSIGNMENT expression; functionCall: name=ID LPAREN params+=actualParam (COMMA params+=actualParam)* RPAREN ; expression: functionCall | creation | stringLiteral | intLiteral; stringLiteral: STRING; intLiteral: INT; fragment StringCharacters : StringCharacter+ ; fragment StringCharacter : ~["] ; creation: name=TID LPAREN params+=actualParam (COMMA params+=actualParam)* RPAREN ; varDecl : VAL_KW (type=typeUsage COLON)? name=ID ASSIGNMENT value=expression nls; expressionStmt: expression nls; statement : varDecl | expressionStmt ; // formalParam : type=typeUsage name=ID; // program: PROGRAM_KW name=TID LPAREN params+=formalParam (COMMA params+=formalParam)* RPAREN LBRACKET nls (statements += statement)* RBRACKET nls; // fileMember: topLevelPropertyDeclaration | typeDeclaration | program; NAMESPACE_KW: 'namespace'; PROGRAM_KW: 'program'; PROPERTY_KW: 'property'; TYPE_KW: 'type'; VAL_KW: 'val'; HAS_KW: 'has'; ABSTRACT_KW: 'abstract'; SHARED_KW: 'shared'; LPAREN: '('; RPAREN: ')'; LBRACKET: '{'; RBRACKET: '}'; LSQUARE: '['; RSQUARE: ']'; COMMA: ','; POINT: '.'; COLON: ':'; EQUAL: '=='; ASSIGNMENT: '='; ID: 'a'..'z' ('A'..'Z' | 'a'..'z' | '_')*; // Only for types TID: 'A'..'Z' ('A'..'Z' | 'a'..'z' | '_')*; INT: '0'|('1'..'9')('0'..'9')*; STRING: '"' ~["]* '"'; STRING_START: '"'; WS: (' ' | '\t')+ -> skip; NL: '\r'? '\n'; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '//' ~[\r\n]* -> skip ;
grammar TurinParser; @header { } turinFile: namespace=namespaceDecl nls (imports+=importDeclaration)* (members+=fileMember)+ EOF; // Base nls: NL+; qualifiedId: (parts+=ID POINT)* parts+=ID; // Namespace namespaceDecl: NAMESPACE_KW name=qualifiedId; // Imports importDeclaration: typeImportDeclaration | singleFieldImportDeclaration | allFieldsImportDeclaration; typeImportDeclaration: packagePart=qualifiedId POINT typeName=ID (AS alternativeName=ID)? nls ; singleFieldImportDeclaration: packagePart=qualifiedId POINT typeName=ID POINT fieldName=qualifiedId (AS alternativeName=ID)? nls; allFieldsImportDeclaration: packagePart=qualifiedId POINT typeName=ID POINT ASTERISK nls; // typeUsage: ref=TID | arrayBase=typeUsage LSQUARE RSQUARE; // topLevelPropertyDeclaration: PROPERTY_KW type=typeUsage COLON name=ID nls; inTypePropertyDeclaration: HAS_KW type=typeUsage COLON name=ID nls; propertyReference: HAS_KW name=ID nls; typeMember: inTypePropertyDeclaration | propertyReference; typeDeclaration: TYPE_KW name=TID LBRACKET nls (typeMembers += typeMember)* RBRACKET nls; // actualParam: expression | name=ID ASSIGNMENT expression; functionCall: name=ID LPAREN params+=actualParam (COMMA params+=actualParam)* RPAREN ; expression: functionCall | creation | stringLiteral | intLiteral; stringLiteral: STRING; intLiteral: INT; fragment StringCharacters : StringCharacter+ ; fragment StringCharacter : ~["] ; creation: name=TID LPAREN params+=actualParam (COMMA params+=actualParam)* RPAREN ; varDecl : VAL_KW (type=typeUsage COLON)? name=ID ASSIGNMENT value=expression nls; expressionStmt: expression nls; statement : varDecl | expressionStmt ; // formalParam : type=typeUsage name=ID; // program: PROGRAM_KW name=TID LPAREN params+=formalParam (COMMA params+=formalParam)* RPAREN LBRACKET nls (statements += statement)* RBRACKET nls; // fileMember: topLevelPropertyDeclaration | typeDeclaration | program; NAMESPACE_KW: 'namespace'; PROGRAM_KW: 'program'; PROPERTY_KW: 'property'; TYPE_KW: 'type'; VAL_KW: 'val'; HAS_KW: 'has'; ABSTRACT_KW: 'abstract'; SHARED_KW: 'shared'; LPAREN: '('; RPAREN: ')'; LBRACKET: '{'; RBRACKET: '}'; LSQUARE: '['; RSQUARE: ']'; COMMA: ','; POINT: '.'; COLON: ':'; EQUAL: '=='; ASSIGNMENT: '='; ID: 'a'..'z' ('A'..'Z' | 'a'..'z' | '_')*; // Only for types TID: 'A'..'Z' ('A'..'Z' | 'a'..'z' | '_')*; INT: '0'|('1'..'9')('0'..'9')*; STRING: '"' ~["]* '"'; STRING_START: '"'; WS: (' ' | '\t')+ -> skip; NL: '\r'? '\n'; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '//' ~[\r\n]* -> skip ;
add clause "as xyz" to import declarations
add clause "as xyz" to import declarations
ANTLR
apache-2.0
ftomassetti/turin-programming-language,ftomassetti/turin-programming-language
43d37089f68d0364c056dcf8131c2a8c10b13e7c
src/main/resources/syntax/LPMLN.g4
src/main/resources/syntax/LPMLN.g4
/** * LPMLN 词法语法定义 * 王彬 * 2016-08-30 **/ grammar LPMLN; /** * 词法定义 **/ //缺省否定关键字 NAF_NOT : 'not '; //字符串 STRING : '"' ('\\"'|~('"'))* '"'; //规则终结符 FULLSTOP : '.'; //正整数 POSITIVE_INT : [1-9][0-9]*; //小数(点表示法) DECIMAL : MINUS? (POSITIVE_INT* | ZERO ) FULLSTOP [0-9] ZERO* [1-9]*; //0 ZERO : '0'; //常量 CONSTANT : [_]*[a-z][a-zA-Z0-9_']* | BOOL_CONSTANTS; //变量 VAR : [_]*[A-Z][a-zA-Z0-9_']*; //指数运算 EXPONENITIATION : '**'; //位运算 BITWISE_AND : '&'; BITWISE_OR : '?'; BITWISE_EXCLUSIVE_OR : '^'; BITWISE_COMPLEMENT : '~'; //加号 PLUS : '+'; //减号、经典否定关键字 MINUS : '-'; //乘号、 星号 STAR : '*'; //除号、斜线 SLASH : '/'; //左圆括号 LPAREN : '('; //右圆括号 RPAREN : ')'; //左方括号 LSBRACK : '['; //右方括号 RSBRACK : ']'; //左花括号 LCBRACK : '{'; //右花括号 RCBRACK : '}'; //范围运算 RANGE : '..'; //逗号 COMMA : ','; //认知析取符 DISJUNCTION : '|'; //条件限制符 CONDITION : ':'; //推导符号 ASSIGN : ':-'; //弱约束推导符号 WEAK_ASSIGN : ':~'; //分号 SEMICOLON : ';'; //关系运算符 LESS_THAN : '<'; LEQ : '<='; GREATER_THAN : '>'; GEQ : '>='; EQUAL : '='; DOUBLE_EQUAL : '=='; NEQ : '!='; AGGREGATE_OP : '#count' | '#sum' | '#max' | '#min'; // META_OP : '#show '; //单行注释 LINE_COMMENT : ('%' ~('\r' | '\n')* '\r'? '\n') -> skip; //空白字符或换行符 WS : ( ' ' | '\t' | '\n' | '\r')+ -> skip ; //布尔常量 BOOL_CONSTANTS : '#true' | '#false'; /** * 语法规则定义 **/ //负整数 negative_int : MINUS POSITIVE_INT ; //整数 integer : POSITIVE_INT | negative_int | ZERO; //自然数 natural_number : POSITIVE_INT | ZERO; //四则运算符 arithmetic_op : PLUS | MINUS | STAR | SLASH; //二元位运算 bitwise_op : BITWISE_AND | BITWISE_OR | BITWISE_EXCLUSIVE_OR; //二元运算符 binary_op : arithmetic_op | bitwise_op | EXPONENITIATION; //一元运算符 unary_op : BITWISE_COMPLEMENT; //数字 bit_number : unary_op? natural_number; //关系运算符(comparison predicates) relation_op : LESS_THAN | LEQ | GREATER_THAN | GEQ | EQUAL | NEQ; //简单四则运算算术表达式,不加括号 simple_arithmetic_expr : integer | (MINUS)? VAR | (integer | (MINUS)? VAR) (binary_op (bit_number | VAR))* ; //四则运算算术表达式,加括号 simple_arithmetic_expr2 : simple_arithmetic_expr | (LPAREN simple_arithmetic_expr2 RPAREN) | simple_arithmetic_expr2 arithmetic_op simple_arithmetic_expr2; //四则运算表达式 arithmethic_expr: simple_arithmetic_expr2 | MINUS LPAREN simple_arithmetic_expr2 RPAREN; //函数 function : CONSTANT LPAREN term (COMMA term)* RPAREN; //简单项,缺_,#sup,#inf simpleterm : integer | CONSTANT | STRING | VAR; //元组 tuple : LPAREN ( | term ( | COMMA | (COMMA term)* )) RPAREN; //范围枚举 interval : (integer | VAR) RANGE (integer | VAR); //逐个枚举 pooling : LPAREN ((integer | VAR) (SEMICOLON (integer | VAR))* ) RPAREN; //项 //term : VAR | CONSTANT | integer | arithmethic_expr | function | STRING; term : simpleterm | function | tuple | arithmethic_expr | interval | pooling; //原子 atom : CONSTANT | CONSTANT LPAREN term (COMMA term)* RPAREN; //文字 literal : atom | MINUS atom | NAF_NOT literal | comparison_literal; //缺省文字 //default_literal : NAF_NOT literal; //扩展文字,包含查询原子 //extended_literal : literal | default_literal; //项元组 term_tuple : term (COMMA term)*; //文字元组 literal_tuple : literal (COMMA literal)*; //聚合元素 aggregate_elements : (term_tuple CONDITION)? literal_tuple (SEMICOLON (term_tuple CONDITION)? literal_tuple)*; //带条件的聚合元素 aggregate_elements_condition : (term_tuple CONDITION)? literal_tuple CONDITION literal_tuple (SEMICOLON (term_tuple CONDITION)? literal_tuple CONDITION literal_tuple)*; //体部聚合原子 body_aggregate : (term relation_op?)? AGGREGATE_OP? LCBRACK aggregate_elements RCBRACK (relation_op? term)?; //aggregate_atom : AGGREGATE_OP LCBRACK (literal | VAR) CONDITION literal RCBRACK ; //头部聚合原子 head_aggregate : (term relation_op?)? AGGREGATE_OP? LCBRACK aggregate_elements_condition RCBRACK (relation_op? term)?; //聚合运算表达式 //aggregate_expr: (VAR | aggregate_atom | integer) relation_op aggregate_atom | // aggregate_atom relation_op (VAR | integer) | // VAR EQUAL aggregate_atom; //关系运算表达式 //relation_expr : ((MINUS)? term) relation_op ((MINUS)? term); comparison_literal : ((MINUS)? term) relation_op ((MINUS)? term); //规则头部 head : (head_literal DISJUNCTION)* head_literal; //头部文字 head_literal : literal | head_aggregate | NAF_NOT head_literal | condition_literal; //条件文字 condition_literal : literal CONDITION literal (COMMA literal)*; //规则体部 body : (body_literal COMMA | condition_literal SEMICOLON)* (body_literal | condition_literal) ; //体部文字 body_literal : literal | body_aggregate | NAF_NOT body_literal; //事实 fact : head FULLSTOP; //约束 constraint : ASSIGN body FULLSTOP; //基本规则 full_rule : head ASSIGN body FULLSTOP; //ASP 规则 (hard rule) hard_rule : fact | constraint | full_rule; //弱规则 (soft rule) soft_rule : (DECIMAL | integer ) CONDITION hard_rule; // meta_rule : META_OP (MINUS)? CONSTANT SLASH natural_number FULLSTOP; //ASP4QA程序 lpmln_rule : (hard_rule | soft_rule | meta_rule)*;
/** * LPMLN 词法语法定义 * 王彬 * 2016-08-30 **/ grammar LPMLN; /** * 词法定义 **/ //缺省否定关键字 NAF_NOT : 'not '; //字符串 STRING : '"' ('\\"'|~('"'))* '"'; //规则终结符 FULLSTOP : '.'; //正整数 POSITIVE_INT : [1-9][0-9]*; //小数(点表示法) DECIMAL : MINUS? (POSITIVE_INT* | ZERO ) FULLSTOP [0-9] ZERO* [1-9]*; //0 ZERO : '0'; //identifier IDENTIFIER : [_]*[a-z][a-zA-Z0-9_']*; //常量 CONSTANT : IDENTIFIER | BOOL_CONSTANTS; //变量 VAR : [_]*[A-Z][a-zA-Z0-9_']*; //指数运算 EXPONENITIATION : '**'; //位运算 BITWISE_AND : '&'; BITWISE_OR : '?'; BITWISE_EXCLUSIVE_OR : '^'; BITWISE_COMPLEMENT : '~'; //加号 PLUS : '+'; //减号、经典否定关键字 MINUS : '-'; //乘号、 星号 STAR : '*'; //除号、斜线 SLASH : '/'; //左圆括号 LPAREN : '('; //右圆括号 RPAREN : ')'; //左方括号 LSBRACK : '['; //右方括号 RSBRACK : ']'; //左花括号 LCBRACK : '{'; //右花括号 RCBRACK : '}'; //范围运算 RANGE : '..'; //逗号 COMMA : ','; //认知析取符 DISJUNCTION : '|'; //条件限制符 CONDITION : ':'; //推导符号 ASSIGN : ':-'; //弱约束推导符号 WEAK_ASSIGN : ':~'; //分号 SEMICOLON : ';'; //关系运算符 LESS_THAN : '<'; LEQ : '<='; GREATER_THAN : '>'; GEQ : '>='; EQUAL : '='; DOUBLE_EQUAL : '=='; NEQ : '!='; AGGREGATE_OP : '#count' | '#sum' | '#max' | '#min'; // META_OP : '#show '; //单行注释 LINE_COMMENT : ('%' ~('\r' | '\n')* '\r'? '\n') -> skip; //空白字符或换行符 WS : ( ' ' | '\t' | '\n' | '\r')+ -> skip ; //布尔常量 BOOL_CONSTANTS : '#true' | '#false'; /** * 语法规则定义 **/ //负整数 negative_int : MINUS POSITIVE_INT ; //整数 integer : POSITIVE_INT | negative_int | ZERO; //自然数 natural_number : POSITIVE_INT | ZERO; //四则运算符 arithmetic_op : PLUS | MINUS | STAR | SLASH; //二元位运算 bitwise_op : BITWISE_AND | BITWISE_OR | BITWISE_EXCLUSIVE_OR; //二元运算符 binary_op : arithmetic_op | bitwise_op | EXPONENITIATION | RANGE; //一元运算符 unary_op : BITWISE_COMPLEMENT; //数字 bit_number : unary_op? natural_number; //关系运算符(comparison predicates) relation_op : LESS_THAN | LEQ | GREATER_THAN | GEQ | EQUAL | NEQ; //简单四则运算算术表达式,不加括号 simple_arithmetic_expr : integer | (MINUS)? VAR | (integer | (MINUS)? VAR) (binary_op (bit_number | VAR))* ; //四则运算算术表达式,加括号 simple_arithmetic_expr2 : simple_arithmetic_expr | (LPAREN simple_arithmetic_expr2 RPAREN) | simple_arithmetic_expr2 arithmetic_op simple_arithmetic_expr2; //四则运算表达式 arithmethic_expr: simple_arithmetic_expr2 | MINUS LPAREN simple_arithmetic_expr2 RPAREN; //函数 function : IDENTIFIER term; //简单项,缺_,#sup,#inf simpleterm : integer | CONSTANT | STRING | VAR; //元组 tuple : | COMMA | ( COMMA term )+ ; //范围枚举 //interval : (integer | VAR) RANGE (integer | VAR); //逐个枚举 pooling : (SEMICOLON term)+; //项 //term : VAR | CONSTANT | integer | arithmethic_expr | function | STRING; term : (simpleterm | function | arithmethic_expr | LPAREN term RPAREN) (tuple | pooling); //原子 atom : CONSTANT | IDENTIFIER LPAREN term (COMMA term)* RPAREN; //文字 literal : atom | MINUS atom | NAF_NOT literal | comparison_literal; //缺省文字 //default_literal : NAF_NOT literal; //扩展文字,包含查询原子 //extended_literal : literal | default_literal; //项元组 term_tuple : term (COMMA term)*; //文字元组 literal_tuple : literal (COMMA literal)*; //聚合元素 aggregate_elements : (term_tuple CONDITION)? literal_tuple (SEMICOLON (term_tuple CONDITION)? literal_tuple)*; //带条件的聚合元素 aggregate_elements_condition : (term_tuple CONDITION)? literal_tuple CONDITION literal_tuple (SEMICOLON (term_tuple CONDITION)? literal_tuple CONDITION literal_tuple)*; //体部聚合原子 body_aggregate : (term relation_op?)? AGGREGATE_OP? LCBRACK aggregate_elements RCBRACK (relation_op? term)?; //aggregate_atom : AGGREGATE_OP LCBRACK (literal | VAR) CONDITION literal RCBRACK ; //头部聚合原子 head_aggregate : (term relation_op?)? AGGREGATE_OP? LCBRACK aggregate_elements_condition RCBRACK (relation_op? term)?; //聚合运算表达式 //aggregate_expr: (VAR | aggregate_atom | integer) relation_op aggregate_atom | // aggregate_atom relation_op (VAR | integer) | // VAR EQUAL aggregate_atom; //关系运算表达式 //relation_expr : ((MINUS)? term) relation_op ((MINUS)? term); comparison_literal : ((MINUS)? term) relation_op ((MINUS)? term); //规则头部 head : (head_literal DISJUNCTION)* head_literal; //头部文字 head_literal : literal | head_aggregate | NAF_NOT head_literal | condition_literal; //条件文字 condition_literal : literal CONDITION literal (COMMA literal)*; //规则体部 body : (body_literal COMMA | condition_literal SEMICOLON)* (body_literal | condition_literal) ; //体部文字 body_literal : literal | body_aggregate | NAF_NOT body_literal; //事实 fact : head FULLSTOP; //约束 constraint : ASSIGN body FULLSTOP; //基本规则 full_rule : head ASSIGN body FULLSTOP; //ASP 规则 (hard rule) hard_rule : fact | constraint | full_rule; //弱规则 (soft rule) soft_rule : (DECIMAL | integer ) CONDITION hard_rule; // meta_rule : META_OP (MINUS)? IDENTIFIER SLASH natural_number FULLSTOP; //ASP4QA程序 lpmln_rule : (hard_rule | soft_rule | meta_rule)*;
重构tuple,pooling,分离constant和identifier
重构tuple,pooling,分离constant和identifier Signed-off-by: 许鸿翔 <[email protected]>
ANTLR
agpl-3.0
wangbiu/lpmlnmodels
c9d3d8ec8a990850dcac609a02734400790c3527
src/main/antlr/SHRParser.g4
src/main/antlr/SHRParser.g4
parser grammar SHRParser; options { tokenVocab=SHRLexer; } shr: dataDefsDoc | valuesetDefsDoc /* | contentProfiles*/; // DATA DEFINITIONS (Vocabularies, Entries, Elements) dataDefsDoc: dataDefsHeader usesStatement? pathDefs? vocabularyDefs? dataDefs; dataDefsHeader: KW_DATA_DEFINITIONS namespace; usesStatement: KW_USES namespace (COMMA namespace)*; pathDefs: (defaultPathDef pathDef*) | (defaultPathDef? pathDef+); defaultPathDef: KW_PATH URL; pathDef: KW_PATH ALL_CAPS EQUAL URL; vocabularyDefs: vocabularyDef+; vocabularyDef: KW_VOCABULARY ALL_CAPS EQUAL (URL | URN_OID); dataDefs: dataDef*; dataDef: elementDef | entryDef; elementDef: elementHeader elementProps? values; elementHeader: KW_ELEMENT simpleName; entryDef: entryHeader elementProps? values; entryHeader: KW_ENTRY_ELEMENT simpleName; elementProps: elementProp+; elementProp: basedOnProp | conceptProp | descriptionProp; values: (value supportingValue*) | (value? supportingValue+); value: KW_VALUE (uncountedValue | countedValue); uncountedValue: (valueType (KW_OR valueType)*) | (OPEN_PAREN valueType (KW_OR valueType)* CLOSE_PAREN); countedValue: count valueType | count OPEN_PAREN valueType (KW_OR valueType)* CLOSE_PAREN; valueType: simpleOrFQName | ref | primitive | codeFromVS | elementWithConstraint | tbd; supportingValue: countedSupportingValue (KW_OR countedSupportingValue)*; countedSupportingValue: count (supportingValueType | OPEN_PAREN supportingValueType (KW_OR supportingValueType)* CLOSE_PAREN); supportingValueType: simpleOrFQName | ref | elementWithConstraint | tbd; basedOnProp: KW_BASED_ON simpleOrFQName; conceptProp: KW_CONCEPT (tbd | concepts); concepts: fullyQualifiedCode (COMMA fullyQualifiedCode)*; descriptionProp: KW_DESCRIPTION STRING; // VALUESET DEFINITIONS valuesetDefsDoc: valuesetDefsHeader usesStatement? pathDefs? vocabularyDefs? valuesetDefs; valuesetDefsHeader: KW_VALUESET_DEFINITIONS namespace; valuesetDefs: valuesetDef*; valuesetDef: valuesetHeader valuesetProps? valuesetValues?; valuesetHeader: KW_VALUESET (URL | URN_OID| simpleName); valuesetValues: valuesetValue+; valuesetValue: fullyQualifiedCode | valuesetInlineValue | valuesetDescendingFrom | valuesetFrom; valuesetInlineValue: CODE STRING?; valuesetDescendingFrom: KW_INCLUDES_CODES_DESCENDING_FROM fullyQualifiedCode (KW_AND_NOT_DESCENDING_FROM fullyQualifiedCode)*; valuesetFrom: KW_INCLUDES_CODES_FROM fullyQualifiedCode; valuesetProps: valuesetProp+; valuesetProp: conceptProp | descriptionProp; // CONTENT PROFILES: TODO -- May Be a Separate Grammar // COMMON BITS namespace: LOWER_WORD | DOT_SEPARATED_LW; simpleName: UPPER_WORD | ALL_CAPS; fullyQualifiedName: DOT_SEPARATED_UW; simpleOrFQName: simpleName | fullyQualifiedName; ref: KW_REF OPEN_PAREN simpleOrFQName CLOSE_PAREN; code: CODE STRING?; fullyQualifiedCode: ALL_CAPS code; codeFromVS: (KW_CODE_FROM | KW_CODING_FROM) valueset; elementWithConstraint: simpleOrFQName (DOT simpleName)* elementConstraint; elementConstraint: elementCodeVSConstraint | elementCodeValueConstraint | elementTypeConstraint | elementWithUnitsConstraint; elementCodeVSConstraint: KW_WITH codeFromVS; elementCodeValueConstraint: KW_IS fullyQualifiedCode; elementTypeConstraint: KW_IS simpleOrFQName; elementWithUnitsConstraint: KW_WITH KW_UNITS fullyQualifiedCode; valueset: URL | PATH_URL | URN_OID | simpleName; primitive: KW_BOOLEAN | KW_INTEGER | KW_STRING | KW_DECIMAL | KW_URI | KW_BASE64_BINARY | KW_INSTANT | KW_DATE | KW_DATE_TIME | KW_TIME | KW_CODE | KW_OID | KW_ID | KW_MARKDOWN | KW_UNSIGNED_INT | KW_POSITIVE_INT; count: WHOLE_NUMBER RANGE (WHOLE_NUMBER | STAR); tbd: KW_TBD STRING?;
parser grammar SHRParser; options { tokenVocab=SHRLexer; } shr: dataDefsDoc | valuesetDefsDoc /* | contentProfiles*/; // DATA DEFINITIONS (Vocabularies, Entries, Elements) dataDefsDoc: dataDefsHeader usesStatement? pathDefs? vocabularyDefs? dataDefs; dataDefsHeader: KW_DATA_DEFINITIONS namespace; usesStatement: KW_USES namespace (COMMA namespace)*; pathDefs: (defaultPathDef pathDef*) | (defaultPathDef? pathDef+); defaultPathDef: KW_PATH URL; pathDef: KW_PATH ALL_CAPS EQUAL URL; vocabularyDefs: vocabularyDef+; vocabularyDef: KW_VOCABULARY ALL_CAPS EQUAL (URL | URN_OID); dataDefs: dataDef*; dataDef: elementDef | entryDef; elementDef: elementHeader elementProps? values; elementHeader: KW_ELEMENT simpleName; entryDef: entryHeader elementProps? values; entryHeader: KW_ENTRY_ELEMENT simpleName; elementProps: elementProp+; elementProp: basedOnProp | conceptProp | descriptionProp; values: (value field*) | (value? field+); value: KW_VALUE (uncountedValue | countedValue); uncountedValue: (valueType (KW_OR valueType)*) | (OPEN_PAREN valueType (KW_OR valueType)* CLOSE_PAREN); countedValue: count valueType | count OPEN_PAREN valueType (KW_OR valueType)* CLOSE_PAREN; valueType: simpleOrFQName | ref | primitive | codeFromVS | elementWithConstraint | tbd; field: countedField (KW_OR countedField)*; countedField: count (fieldType | OPEN_PAREN fieldType (KW_OR fieldType)* CLOSE_PAREN); fieldType: simpleOrFQName | ref | elementWithConstraint | tbd; basedOnProp: KW_BASED_ON simpleOrFQName; conceptProp: KW_CONCEPT (tbd | concepts); concepts: fullyQualifiedCode (COMMA fullyQualifiedCode)*; descriptionProp: KW_DESCRIPTION STRING; // VALUESET DEFINITIONS valuesetDefsDoc: valuesetDefsHeader usesStatement? pathDefs? vocabularyDefs? valuesetDefs; valuesetDefsHeader: KW_VALUESET_DEFINITIONS namespace; valuesetDefs: valuesetDef*; valuesetDef: valuesetHeader valuesetProps? valuesetValues?; valuesetHeader: KW_VALUESET (URL | URN_OID| simpleName); valuesetValues: valuesetValue+; valuesetValue: fullyQualifiedCode | valuesetInlineValue | valuesetDescendingFrom | valuesetFrom; valuesetInlineValue: CODE STRING?; valuesetDescendingFrom: KW_INCLUDES_CODES_DESCENDING_FROM fullyQualifiedCode (KW_AND_NOT_DESCENDING_FROM fullyQualifiedCode)*; valuesetFrom: KW_INCLUDES_CODES_FROM fullyQualifiedCode; valuesetProps: valuesetProp+; valuesetProp: conceptProp | descriptionProp; // CONTENT PROFILES: TODO -- May Be a Separate Grammar // COMMON BITS namespace: LOWER_WORD | DOT_SEPARATED_LW; simpleName: UPPER_WORD | ALL_CAPS; fullyQualifiedName: DOT_SEPARATED_UW; simpleOrFQName: simpleName | fullyQualifiedName; ref: KW_REF OPEN_PAREN simpleOrFQName CLOSE_PAREN; code: CODE STRING?; fullyQualifiedCode: ALL_CAPS code; codeFromVS: (KW_CODE_FROM | KW_CODING_FROM) valueset; elementWithConstraint: simpleOrFQName (DOT simpleName)* elementConstraint; elementConstraint: elementCodeVSConstraint | elementCodeValueConstraint | elementTypeConstraint | elementWithUnitsConstraint; elementCodeVSConstraint: KW_WITH codeFromVS; elementCodeValueConstraint: KW_IS fullyQualifiedCode; elementTypeConstraint: KW_IS simpleOrFQName; elementWithUnitsConstraint: KW_WITH KW_UNITS fullyQualifiedCode; valueset: URL | PATH_URL | URN_OID | simpleName; primitive: KW_BOOLEAN | KW_INTEGER | KW_STRING | KW_DECIMAL | KW_URI | KW_BASE64_BINARY | KW_INSTANT | KW_DATE | KW_DATE_TIME | KW_TIME | KW_CODE | KW_OID | KW_ID | KW_MARKDOWN | KW_UNSIGNED_INT | KW_POSITIVE_INT; count: WHOLE_NUMBER RANGE (WHOLE_NUMBER | STAR); tbd: KW_TBD STRING?;
Rename SupportingValue to Field
ANTLR4: Rename SupportingValue to Field
ANTLR
apache-2.0
standardhealth/shr_spec
d5427a899dc04d2d3150461496da95a9c0563069
src/main/antlr4/Gherkins.g4
src/main/antlr4/Gherkins.g4
grammar Gherkins; @header { package nl.eernie.jmoribus; } feature : NEWLINE* comment? NEWLINE* SPACE* tags? NEWLINE* SPACE* feature_keyword SPACE* line_to_eol NEWLINE+ (feature_elements .)* feature_elements ; feature_elements : (scenario_outline | scenario | background)* ; background : comment? tags? background_keyword SPACE* line_to_eol NEWLINE+ steps ; scenario : comment? tags? scenario_keyword SPACE* line_to_eol NEWLINE+ steps ; scenario_outline : comment? tags? scenario_outline_keyword SPACE* line_to_eol NEWLINE+ steps examples_sections ; steps : step* ; step : step_keyword SPACE* line_to_eol NEWLINE+ multiline_arg? ; examples_sections : examples+ ; examples : examples_keyword SPACE* line_to_eol NEWLINE+ table ; multiline_arg : table ; table : table_row+ ; table_row : SPACE* '|' (cell '|')+ SPACE* (NEWLINE+) ; cell : (~('|' | NEWLINE) .)* ; tags : tag (SPACE tag)* NEWLINE+ ; tag : '@' tag_name=ID ; comment : (comment_line NEWLINE)* ; comment_line : '#' line_to_eol; line_to_eol : (~NEWLINE)* ; feature_keyword : 'Feature' ':'? ; background_keyword : 'Background' ':'?; scenario_keyword : 'Scenario' ':'? ; scenario_outline_keyword : 'Scenario Outline' ':'? ; step_keyword : 'Given' | 'When' | 'Then' | 'And' | 'Prologue'; examples_keyword : 'Examples' ':'? ; ID : ('a'..'z'|'A'..'Z'|'_')+ ; NEWLINE : (('\r')? '\n' )+ ; SPACE : (' '|'\t')+ {skip();};
grammar Gherkins; @header { package nl.eernie.jmoribus; } feature : NEWLINE* comment? NEWLINE* SPACE* tags? NEWLINE* SPACE* feature_keyword SPACE* line_to_eol NEWLINE+ (feature_elements .)* feature_elements ; feature_elements : (scenario | background)* ; background : comment? tags? background_keyword SPACE* line_to_eol NEWLINE+ steps ; scenario : comment? tags? scenario_keyword SPACE* line_to_eol NEWLINE+ steps examples_sections? ; steps : step* ; step : step_keyword SPACE* line_to_eol NEWLINE+ multiline_arg? ; examples_sections : examples+ ; examples : examples_keyword SPACE* line_to_eol NEWLINE+ table ; multiline_arg : table ; table : table_row+ ; table_row : SPACE* '|' (cell '|')+ SPACE* (NEWLINE+) ; cell : (~('|' | NEWLINE) .)* ; tags : tag (SPACE tag)* NEWLINE+ ; tag : '@' tag_name=ID ; comment : (comment_line NEWLINE)+ ; comment_line : '#' line_to_eol; line_to_eol : (~NEWLINE)* ; feature_keyword : 'Feature:'; background_keyword : 'Background:'; scenario_keyword : 'Scenario:'; step_keyword : 'Given' | 'When' | 'Then' | 'And' | 'Prologue'; examples_keyword : 'Examples' ':'? ; ID : ('a'..'z'|'A'..'Z'|'_')+ ; NEWLINE : (('\r')? '\n' )+ ; SPACE : (' '|'\t')+ {skip();};
Remove scenario outline keyword Fix comment repetition warning resulting in Antlr warning during compile time
Remove scenario outline keyword Fix comment repetition warning resulting in Antlr warning during compile time
ANTLR
mit
Eernie/JMoribus
3ed95d70e990c91a3edf431be3bd56e1fd66f9d6
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
grammar SQLServerDCLStatement; import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol; grant : grantGeneral | grantDW ; grantGeneral : GRANT generalPrisOn TO ids (WITH GRANT OPTION)? (AS ID)? ; generalPrisOn : (ALL PRIVILEGES? | permissionOnColumns (COMMA permissionOnColumns)*) (ON (ID COLON COLON)? ID)? ; permissionOnColumns : permission columnList? ; permission : ID *? ; grantDW : GRANT permission (COMMA permission)* (ON (classType COLON COLON)? ID)? TO ids (WITH GRANT OPTION)? ; classType : LOGIN | DATABASE | OBJECT | ROLE | SCHEMA | USER ; revoke : revokeGeneral | revokeDW ; revokeGeneral : REVOKE (GRANT OPTION FOR)? ((ALL PRIVILEGES?)? | permissionOnColumns) (ON (ID COLON COLON)? ID)? (TO | FROM) ids (CASCADE)? (AS ID)? ; revokeDW : REVOKE permissionWithClass (FROM | TO)? ids CASCADE? ; permissionWithClass : permission (COMMA permission)* (ON (classType COLON COLON)? ID)? ; deny : DENY generalPrisOn TO ids CASCADE? (AS ID)? ; createUser : CREATE USER ( userName (createUserBody1 | createUserBody4) | createUserBody2 | createUserBody3 )? ; createUserBody1 : ((FOR | FROM) LOGIN ID)? (WITH optionsLists)? ; createUserBody2 : windowsPrincipal (WITH optionsLists)? | userName WITH PASSWORD EQ_ STRING (COMMA optionsList)* | ID FROM EXTERNAL PROVIDER ; windowsPrincipal : ID BACKSLASH ID ; createUserBody3 : windowsPrincipal ((FOR | FROM) LOGIN ID)? | userName (FOR | FROM) LOGIN ID ; createUserBody4 : WITHOUT LOGIN (WITH optionsLists)? | (FOR | FROM) (CERTIFICATE ID | ASYMMETRIC KEY ID) ; optionsLists : optionsList (COMMA optionsList)* ; optionsList : ID EQ_ ID? ; alterUser : ALTER USER userName optionsLists ; dropUser : DROP USER (IF EXISTS)? userName ;
grammar SQLServerDCLStatement; import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol; grant : grantGeneral | grantDW ; grantGeneral : GRANT generalPrisOn TO ids (WITH GRANT OPTION)? (AS ID)? ; generalPrisOn : (ALL PRIVILEGES? | permissionOnColumns (COMMA permissionOnColumns)*) (ON (ID COLON COLON)? ID)? ; permissionOnColumns : permission columnList? ; permission : ID *? ; grantDW : GRANT permission (COMMA permission)* (ON (classType COLON COLON)? ID)? TO ids (WITH GRANT OPTION)? ; classType : LOGIN | DATABASE | OBJECT | ROLE | SCHEMA | USER ; revoke : revokeGeneral | revokeDW ; revokeGeneral : REVOKE (GRANT OPTION FOR)? ((ALL PRIVILEGES?)? | permissionOnColumns) (ON (ID COLON COLON)? ID)? (TO | FROM) ids (CASCADE)? (AS ID)? ; revokeDW : REVOKE permissionWithClass (FROM | TO)? ids CASCADE? ; permissionWithClass : permission (COMMA permission)* (ON (classType COLON COLON)? ID)? ; deny : DENY generalPrisOn TO ids CASCADE? (AS ID)? ; createUser : CREATE USER ( userName (createUserBody1 | createUserBody4) | createUserBody2 | createUserBody3 )? ; createUserBody1 : ((FOR | FROM) LOGIN ID)? (WITH optionsLists)? ; createUserBody2 : windowsPrincipal (WITH optionsLists)? | userName WITH PASSWORD EQ_ STRING (COMMA optionsList)* | ID FROM EXTERNAL PROVIDER ; windowsPrincipal : ID BACKSLASH ID ; createUserBody3 : windowsPrincipal ((FOR | FROM) LOGIN ID)? | userName (FOR | FROM) LOGIN ID ; createUserBody4 : WITHOUT LOGIN (WITH optionsLists)? | (FOR | FROM) (CERTIFICATE ID | ASYMMETRIC KEY ID) ; optionsLists : optionsList (COMMA optionsList)* ; optionsList : ID EQ_ ID? ; alterUser : ALTER USER userName optionsLists ; dropUser : DROP USER (IF EXISTS)? userName ; sources : WINDOWS (WITH optionsList (COMMA optionsList)?)? | CERTIFICATE ID | ASYMMETRIC KEY ID ;
add sources
add sources
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
e68db088920f4f82963641c8baf1ccd0775cc8db
sharding-core/src/main/antlr4/io/shardingsphere/core/parsing/antlr/autogen/OracleStatement.g4
sharding-core/src/main/antlr4/io/shardingsphere/core/parsing/antlr/autogen/OracleStatement.g4
grammar OracleStatement; import OracleKeyword, Keyword, OracleBase, OracleCreateIndex, OracleAlterIndex , OracleDropIndex, OracleCreateTable, OracleAlterTable, OracleDropTable, OracleTruncateTable , OracleTCLStatement, OracleDCLStatement ; execute : createIndex | alterIndex | dropIndex | createTable | alterTable | dropTable | truncateTable | setTransaction | commit | rollback | savepoint | grant | revoke | createUser | alterUser ;
grammar OracleStatement; import OracleKeyword, Keyword, OracleBase, OracleCreateIndex, OracleAlterIndex , OracleDropIndex, OracleCreateTable, OracleAlterTable, OracleDropTable, OracleTruncateTable , OracleTCLStatement, OracleDCLStatement ; execute : createIndex | alterIndex | dropIndex | createTable | alterTable | dropTable | truncateTable | setTransaction | commit | rollback | savepoint | grant | revoke | createUser | alterUser | dropUser ;
add drop user statement
add drop user statement
ANTLR
apache-2.0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
b55a6dd4ecea759e454a2bf13b45e022a69675fd
src/main/antlr4/nl/eernie/jmoribus/Gherkins.g4
src/main/antlr4/nl/eernie/jmoribus/Gherkins.g4
grammar Gherkins; story : prologue? scenario*; prologue : NEWLINE? prologue_keyword (NEWLINE step)+; scenario : NEWLINE? scenario_keyword title (NEWLINE step)+; title : line; step : step_keyword line; line : (SPACE|TEXT)*; feature_keyword : 'Feature:'; prologue_keyword : 'Prologue:'; scenario_keyword : 'Scenario:'; step_keyword : 'Given' | 'When' | 'Then' | 'And' | 'Revering:'; SPACE : ' ' | '\t'; NEWLINE : '\r'? '\n'; TEXT : (UPPERCASE_LETTER | LOWERCASE_LETTER | DIGIT| SYMBOL ) ; fragment UPPERCASE_LETTER : 'A'..'Z' ; fragment LOWERCASE_LETTER : 'a'..'z' ; fragment DIGIT : '0'..'9' ; fragment SYMBOL : '\u0021'..'\u0027' | '\u002a'..'\u002f' | '\u003a'..'\u0040' | '\u005e'..'\u0060' | '\u00a1'..'\u00FF' | '\u0152'..'\u0192' | '\u2013'..'\u2122' | '\u2190'..'\u21FF' | '\u2200'..'\u22FF' | '('..')' ; WS : [ \t\n\r]+ -> skip ;
grammar Gherkins; story : prologue? scenario*; prologue : NEWLINE? prologue_keyword (NEWLINE step)+; scenario : NEWLINE? scenario_keyword title (NEWLINE step)+; title : line; step : step_keyword line (NEWLINE SPACE SPACE line)*; line : (SPACE|TEXT)*; feature_keyword : 'Feature:'; prologue_keyword : 'Prologue:'; scenario_keyword : 'Scenario:'; step_keyword : 'Given' | 'When' | 'Then' | 'And' | 'Revering:'; SPACE : ' ' | '\t'; NEWLINE : '\r'? '\n'; TEXT : (UPPERCASE_LETTER | LOWERCASE_LETTER | DIGIT| SYMBOL ) ; fragment UPPERCASE_LETTER : 'A'..'Z' ; fragment LOWERCASE_LETTER : 'a'..'z' ; fragment DIGIT : '0'..'9' ; fragment SYMBOL : '\u0021'..'\u0027' | '\u002a'..'\u002f' | '\u003a'..'\u0040' | '\u005e'..'\u0060' | '\u00a1'..'\u00FF' | '\u0152'..'\u0192' | '\u2013'..'\u2122' | '\u2190'..'\u21FF' | '\u2200'..'\u22FF' | '('..')' ; WS : [ \t\n\r]+ -> skip ;
Support multiline steps
Support multiline steps
ANTLR
mit
Eernie/JMoribus
0f1e66f9b6ca813ed39a2f3e321be0e50bedcc8d
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE temporaryClause_ TABLE existClause_ tableName createDefinitions inheritClause? ; createIndex : CREATE UNIQUE? INDEX CONCURRENTLY? ((IF NOT EXISTS)? indexName)? ON tableName ; alterTable : alterTableNameWithAsterisk (alterTableActions | renameColumnSpecification | renameConstraint) | alterTableNameExists renameTableSpecification_ ; alterIndex : alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace ; dropTable : DROP TABLE (IF EXISTS)? tableNames ; dropIndex : DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)* ; truncateTable : TRUNCATE TABLE? ONLY? tableNameParts ; temporaryClause_ : ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? ; existClause_ : (IF NOT EXISTS)? ; createDefinitions : LP_ (createDefinition (COMMA_ createDefinition)*)? RP_ ; createDefinition : columnDefinition | tableConstraint | LIKE tableName likeOption* ; columnDefinition : columnName dataType collateClause? columnConstraint* ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT ignoredIdentifier_ ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; checkOption : CHECK expr (NO INHERIT)? ; defaultExpr : CURRENT_TIMESTAMP | expr ; sequenceOptions : sequenceOption+ ; sequenceOption : START WITH? NUMBER_ | INCREMENT BY? NUMBER_ | MAXVALUE NUMBER_ | NO MAXVALUE | MINVALUE NUMBER_ | NO MINVALUE | CYCLE | NO CYCLE | CACHE NUMBER_ | OWNED BY ; indexParameters : (USING INDEX TABLESPACE ignoredIdentifier_)? | INCLUDE columnNames | WITH ; action : NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT) ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))? ; likeOption : (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnNames indexParameters | primaryKey columnNames indexParameters | EXCLUDE (USING ignoredIdentifier_)? | FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; inheritClause : INHERITS tableNames ; alterIndexName : ALTER INDEX (IF EXISTS)? indexName ; renameIndexSpecification : RENAME TO indexName ; alterIndexDependsOnExtension : ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_ ; alterIndexSetTableSpace : ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)? ; tableNameParts : tableNamePart (COMMA_ tableNamePart)* ; tableNamePart : tableName ASTERISK_? ; alterTableNameWithAsterisk : ALTER TABLE (IF EXISTS)? ONLY? tableName ASTERISK_? ; alterTableActions : alterTableAction (COMMA_ alterTableAction)* ; alterTableAction : addColumnSpecification | dropColumnSpecification | modifyColumnSpecification | addConstraintSpecification | ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam | VALIDATE CONSTRAINT ignoredIdentifier_ | DROP CONSTRAINT (IF EXISTS)? ignoredIdentifier_ (RESTRICT | CASCADE)? | (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)? | ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_ | (DISABLE | ENABLE) RULE ignoredIdentifier_ | ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_ | (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY | CLUSTER ON indexName | SET WITHOUT CLUSTER | SET (WITH | WITHOUT) OIDS | SET TABLESPACE ignoredIdentifier_ | SET (LOGGED | UNLOGGED) | SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_ | RESET LP_ storageParameter (COMMA_ storageParameter)* RP_ | INHERIT tableName | NO INHERIT tableName | OF dataTypeName_ | NOT OF | OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER) | REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING) ; tableConstraintUsingIndex : (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam ; addColumnSpecification : ADD COLUMN? (IF NOT EXISTS)? columnDefinition ; dropColumnSpecification : DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)? ; modifyColumnSpecification : alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)? | alterColumn SET DEFAULT expr | alterColumn DROP DEFAULT | alterColumn (SET | DROP) NOT NULL | alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)? | alterColumn alterColumnSetOption alterColumnSetOption* | alterColumn DROP IDENTITY (IF EXISTS)? | alterColumn SET STATISTICS NUMBER_ | alterColumn SET LP_ attributeOptions RP_ | alterColumn RESET LP_ attributeOptions RP_ | alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN) ; alterColumn : ALTER COLUMN? columnName ; alterColumnSetOption : SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)? ; attributeOptions : attributeOption (COMMA_ attributeOption)* ; attributeOption : IDENTIFIER_ EQ_ simpleExpr ; addConstraintSpecification : ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex) ; renameColumnSpecification : RENAME COLUMN? columnName TO columnName ; renameConstraint : RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_ ; storageParameterWithValue : storageParameter EQ_ simpleExpr ; storageParameter : IDENTIFIER_ ; alterTableNameExists : ALTER TABLE (IF EXISTS)? tableName ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; usingIndexType : USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN) ; excludeElement : (columnName | expr) ignoredIdentifier_? (ASC | DESC)? (NULLS (FIRST | LAST))? ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE temporaryClause_ TABLE existClause_ tableName createDefinitionClause_ inheritClause ; createIndex : CREATE UNIQUE? INDEX CONCURRENTLY? ((IF NOT EXISTS)? indexName)? ON tableName ; alterTable : alterTableNameWithAsterisk (alterTableActions | renameColumnSpecification | renameConstraint) | alterTableNameExists renameTableSpecification_ ; alterIndex : alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace ; dropTable : DROP TABLE (IF EXISTS)? tableNames ; dropIndex : DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)* ; truncateTable : TRUNCATE TABLE? ONLY? tableNameParts ; temporaryClause_ : ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? ; existClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ (createDefinition (COMMA_ createDefinition)*)? RP_ ; createDefinition : columnDefinition | tableConstraint | LIKE tableName likeOption* ; columnDefinition : columnName dataType collateClause? columnConstraint* ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT ignoredIdentifier_ ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; checkOption : CHECK expr (NO INHERIT)? ; defaultExpr : CURRENT_TIMESTAMP | expr ; sequenceOptions : sequenceOption+ ; sequenceOption : START WITH? NUMBER_ | INCREMENT BY? NUMBER_ | MAXVALUE NUMBER_ | NO MAXVALUE | MINVALUE NUMBER_ | NO MINVALUE | CYCLE | NO CYCLE | CACHE NUMBER_ | OWNED BY ; indexParameters : (USING INDEX TABLESPACE ignoredIdentifier_)? | INCLUDE columnNames | WITH ; action : NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT) ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))? ; likeOption : (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnNames indexParameters | primaryKey columnNames indexParameters | EXCLUDE (USING ignoredIdentifier_)? | FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; inheritClause : (INHERITS tableNames)? ; alterIndexName : ALTER INDEX (IF EXISTS)? indexName ; renameIndexSpecification : RENAME TO indexName ; alterIndexDependsOnExtension : ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_ ; alterIndexSetTableSpace : ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)? ; tableNameParts : tableNamePart (COMMA_ tableNamePart)* ; tableNamePart : tableName ASTERISK_? ; alterTableNameWithAsterisk : ALTER TABLE (IF EXISTS)? ONLY? tableName ASTERISK_? ; alterTableActions : alterTableAction (COMMA_ alterTableAction)* ; alterTableAction : addColumnSpecification | dropColumnSpecification | modifyColumnSpecification | addConstraintSpecification | ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam | VALIDATE CONSTRAINT ignoredIdentifier_ | DROP CONSTRAINT (IF EXISTS)? ignoredIdentifier_ (RESTRICT | CASCADE)? | (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)? | ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_ | (DISABLE | ENABLE) RULE ignoredIdentifier_ | ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_ | (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY | CLUSTER ON indexName | SET WITHOUT CLUSTER | SET (WITH | WITHOUT) OIDS | SET TABLESPACE ignoredIdentifier_ | SET (LOGGED | UNLOGGED) | SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_ | RESET LP_ storageParameter (COMMA_ storageParameter)* RP_ | INHERIT tableName | NO INHERIT tableName | OF dataTypeName_ | NOT OF | OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER) | REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING) ; tableConstraintUsingIndex : (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam ; addColumnSpecification : ADD COLUMN? (IF NOT EXISTS)? columnDefinition ; dropColumnSpecification : DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)? ; modifyColumnSpecification : alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)? | alterColumn SET DEFAULT expr | alterColumn DROP DEFAULT | alterColumn (SET | DROP) NOT NULL | alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)? | alterColumn alterColumnSetOption alterColumnSetOption* | alterColumn DROP IDENTITY (IF EXISTS)? | alterColumn SET STATISTICS NUMBER_ | alterColumn SET LP_ attributeOptions RP_ | alterColumn RESET LP_ attributeOptions RP_ | alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN) ; alterColumn : ALTER COLUMN? columnName ; alterColumnSetOption : SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)? ; attributeOptions : attributeOption (COMMA_ attributeOption)* ; attributeOption : IDENTIFIER_ EQ_ simpleExpr ; addConstraintSpecification : ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex) ; renameColumnSpecification : RENAME COLUMN? columnName TO columnName ; renameConstraint : RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_ ; storageParameterWithValue : storageParameter EQ_ simpleExpr ; storageParameter : IDENTIFIER_ ; alterTableNameExists : ALTER TABLE (IF EXISTS)? tableName ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; usingIndexType : USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN) ; excludeElement : (columnName | expr) ignoredIdentifier_? (ASC | DESC)? (NULLS (FIRST | LAST))? ;
rename to createDefinitionClause_
rename to createDefinitionClause_
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
d64e29583a3e9aef7dd585b02028f2998ee891ec
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE tableNotExistClause_ tableName createDefinitionClause_ inheritClause_ ; createIndex : CREATE createIndexSpecification_ INDEX concurrentlyClause_ (indexNotExistClause_ indexName)? ON onlyClause_ tableName ; alterTable : ALTER TABLE existClause_ onlyClause_ tableName asteriskClause_ alterDefinitionClause_ ; alterIndex : ALTER INDEX existClause_ indexName alterIndexDefinitionClause_ ; dropTable : DROP TABLE existClause_ tableNames ; dropIndex : DROP INDEX (CONCURRENTLY)? existClause_ indexName (COMMA_ indexName)* ; truncateTable : TRUNCATE TABLE? ONLY? tableNameParts ; createTableSpecification_ : ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? ; tableNotExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ (createDefinition (COMMA_ createDefinition)*)? RP_ ; createDefinition : columnDefinition | tableConstraint | LIKE tableName likeOption* ; columnDefinition : columnName dataType collateClause? columnConstraint* ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT ignoredIdentifier_ ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; checkOption : CHECK expr (NO INHERIT)? ; defaultExpr : CURRENT_TIMESTAMP | expr ; sequenceOptions : sequenceOption+ ; sequenceOption : START WITH? NUMBER_ | INCREMENT BY? NUMBER_ | MAXVALUE NUMBER_ | NO MAXVALUE | MINVALUE NUMBER_ | NO MINVALUE | CYCLE | NO CYCLE | CACHE NUMBER_ | OWNED BY ; indexParameters : (USING INDEX TABLESPACE ignoredIdentifier_)? | INCLUDE columnNames | WITH ; action : NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT) ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))? ; likeOption : (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnNames indexParameters | primaryKey columnNames indexParameters | EXCLUDE (USING ignoredIdentifier_)? | FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; inheritClause_ : (INHERITS tableNames)? ; createIndexSpecification_ : UNIQUE? ; concurrentlyClause_ : CONCURRENTLY? ; indexNotExistClause_ : (IF NOT EXISTS)? ; onlyClause_ : ONLY? ; existClause_ : (IF EXISTS)? ; asteriskClause_ : ASTERISK_? ; alterDefinitionClause_ : alterTableActions | renameColumnSpecification | renameConstraint | renameTableSpecification_ ; alterIndexDefinitionClause_ : renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace ; renameIndexSpecification : RENAME TO indexName ; alterIndexDependsOnExtension : ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_ ; alterIndexSetTableSpace : ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)? ; tableNameParts : tableNamePart (COMMA_ tableNamePart)* ; tableNamePart : tableName ASTERISK_? ; alterTableActions : alterTableAction (COMMA_ alterTableAction)* ; alterTableAction : addColumnSpecification | dropColumnSpecification | modifyColumnSpecification | addConstraintSpecification | ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam | VALIDATE CONSTRAINT ignoredIdentifier_ | DROP CONSTRAINT existClause_ ignoredIdentifier_ (RESTRICT | CASCADE)? | (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)? | ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_ | (DISABLE | ENABLE) RULE ignoredIdentifier_ | ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_ | (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY | CLUSTER ON indexName | SET WITHOUT CLUSTER | SET (WITH | WITHOUT) OIDS | SET TABLESPACE ignoredIdentifier_ | SET (LOGGED | UNLOGGED) | SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_ | RESET LP_ storageParameter (COMMA_ storageParameter)* RP_ | INHERIT tableName | NO INHERIT tableName | OF dataTypeName_ | NOT OF | OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER) | REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING) ; addColumnSpecification : ADD COLUMN? (IF NOT EXISTS)? columnDefinition ; dropColumnSpecification : DROP COLUMN? existClause_ columnName (RESTRICT | CASCADE)? ; modifyColumnSpecification : alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)? | alterColumn SET DEFAULT expr | alterColumn DROP DEFAULT | alterColumn (SET | DROP) NOT NULL | alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)? | alterColumn alterColumnSetOption alterColumnSetOption* | alterColumn DROP IDENTITY existClause_ | alterColumn SET STATISTICS NUMBER_ | alterColumn SET LP_ attributeOptions RP_ | alterColumn RESET LP_ attributeOptions RP_ | alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN) ; alterColumn : ALTER COLUMN? columnName ; alterColumnSetOption : SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)? ; attributeOptions : attributeOption (COMMA_ attributeOption)* ; attributeOption : IDENTIFIER_ EQ_ simpleExpr ; addConstraintSpecification : ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex) ; tableConstraintUsingIndex : (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam ; storageParameterWithValue : storageParameter EQ_ simpleExpr ; storageParameter : IDENTIFIER_ ; renameColumnSpecification : RENAME COLUMN? columnName TO columnName ; renameConstraint : RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_ ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE tableNotExistClause_ tableName createDefinitionClause_ inheritClause_ ; createIndex : CREATE createIndexSpecification_ INDEX concurrentlyClause_ (indexNotExistClause_ indexName)? ON onlyClause_ tableName ; alterTable : ALTER TABLE tableExistClause_ onlyClause_ tableName asteriskClause_ alterDefinitionClause_ ; alterIndex : ALTER INDEX indexExistClause_ indexName alterIndexDefinitionClause_ ; dropTable : DROP TABLE tableExistClause_ tableNames ; dropIndex : DROP INDEX concurrentlyClause_ indexExistClause_ indexNames ; truncateTable : TRUNCATE TABLE? onlyClause_ tableNamesClause ; createTableSpecification_ : ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? ; tableNotExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ (createDefinition (COMMA_ createDefinition)*)? RP_ ; createDefinition : columnDefinition | tableConstraint | LIKE tableName likeOption* ; columnDefinition : columnName dataType collateClause? columnConstraint* ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT ignoredIdentifier_ ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; checkOption : CHECK expr (NO INHERIT)? ; defaultExpr : CURRENT_TIMESTAMP | expr ; sequenceOptions : sequenceOption+ ; sequenceOption : START WITH? NUMBER_ | INCREMENT BY? NUMBER_ | MAXVALUE NUMBER_ | NO MAXVALUE | MINVALUE NUMBER_ | NO MINVALUE | CYCLE | NO CYCLE | CACHE NUMBER_ | OWNED BY ; indexParameters : (USING INDEX TABLESPACE ignoredIdentifier_)? | INCLUDE columnNames | WITH ; action : NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT) ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))? ; likeOption : (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnNames indexParameters | primaryKey columnNames indexParameters | EXCLUDE (USING ignoredIdentifier_)? | FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; inheritClause_ : (INHERITS tableNames)? ; createIndexSpecification_ : UNIQUE? ; concurrentlyClause_ : CONCURRENTLY? ; indexNotExistClause_ : (IF NOT EXISTS)? ; onlyClause_ : ONLY? ; tableExistClause_ : (IF EXISTS)? ; asteriskClause_ : ASTERISK_? ; alterDefinitionClause_ : alterTableActions | renameColumnSpecification | renameConstraint | renameTableSpecification_ ; alterIndexDefinitionClause_ : renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace ; renameIndexSpecification : RENAME TO indexName ; alterIndexDependsOnExtension : ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_ ; alterIndexSetTableSpace : ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)? ; tableNamesClause : tableNameClause (COMMA_ tableNameClause)* ; tableNameClause : tableName ASTERISK_? ; alterTableActions : alterTableAction (COMMA_ alterTableAction)* ; alterTableAction : addColumnSpecification | dropColumnSpecification | modifyColumnSpecification | addConstraintSpecification | ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam | VALIDATE CONSTRAINT ignoredIdentifier_ | DROP CONSTRAINT indexExistClause_ ignoredIdentifier_ (RESTRICT | CASCADE)? | (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)? | ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_ | (DISABLE | ENABLE) RULE ignoredIdentifier_ | ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_ | (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY | CLUSTER ON indexName | SET WITHOUT CLUSTER | SET (WITH | WITHOUT) OIDS | SET TABLESPACE ignoredIdentifier_ | SET (LOGGED | UNLOGGED) | SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_ | RESET LP_ storageParameter (COMMA_ storageParameter)* RP_ | INHERIT tableName | NO INHERIT tableName | OF dataTypeName_ | NOT OF | OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER) | REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING) ; addColumnSpecification : ADD COLUMN? (IF NOT EXISTS)? columnDefinition ; dropColumnSpecification : DROP COLUMN? columnExistClause_ columnName (RESTRICT | CASCADE)? ; columnExistClause_ : (IF EXISTS)? ; modifyColumnSpecification : alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)? | alterColumn SET DEFAULT expr | alterColumn DROP DEFAULT | alterColumn (SET | DROP) NOT NULL | alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)? | alterColumn alterColumnSetOption alterColumnSetOption* | alterColumn DROP IDENTITY columnExistClause_ | alterColumn SET STATISTICS NUMBER_ | alterColumn SET LP_ attributeOptions RP_ | alterColumn RESET LP_ attributeOptions RP_ | alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN) ; alterColumn : ALTER COLUMN? columnName ; alterColumnSetOption : SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)? ; attributeOptions : attributeOption (COMMA_ attributeOption)* ; attributeOption : IDENTIFIER_ EQ_ simpleExpr ; addConstraintSpecification : ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex) ; tableConstraintUsingIndex : (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam ; storageParameterWithValue : storageParameter EQ_ simpleExpr ; storageParameter : IDENTIFIER_ ; renameColumnSpecification : RENAME COLUMN? columnName TO columnName ; renameConstraint : RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_ ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; indexExistClause_ : (IF EXISTS)? ; indexNames : indexName (COMMA_ indexName)* ;
add tableNamesClause
add tableNamesClause
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
bc543795cef8e02e8469aeaa8f38fff79aa0a163
terraform/terraform.g4
terraform/terraform.g4
/* BSD License Copyright (c) 2020, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar terraform; file : (local | module | output | provider | variable | data | resource | terraform)+ ; terraform : 'terraform' blockbody ; resource : 'resource' resourcetype name blockbody ; data : 'data' resourcetype name blockbody ; provider : 'provider' resourcetype blockbody ; output : 'output' name blockbody ; local : 'locals' blockbody ; module : 'module' name blockbody ; variable : 'variable' name blockbody ; block : blocktype label* blockbody ; blocktype : IDENTIFIER ; resourcetype : STRING ; name : STRING ; label : STRING ; blockbody : LCURL (argument | block)* RCURL ; argument : identifier '=' expression ; identifier : (('local' | 'data' | 'var' | 'module') DOT)? identifierchain ; identifierchain : (IDENTIFIER | IN) index? (DOT identifierchain)* | STAR (DOT identifierchain)* ; expression : section | expression operator expression | LPAREN expression RPAREN | expression '?' expression ':' expression | forloop ; forloop : 'for' identifier IN expression ':' expression ; section : list | map | val ; val : NULL | SIGNED_NUMBER | string | identifier | BOOL | DESCRIPTION | filedecl | functioncall | EOF_ ; functioncall : functionname LPAREN functionarguments RPAREN ; functionname : IDENTIFIER ; functionarguments : //no arguments | expression (',' expression)* ; index : '[' expression ']' ; filedecl : 'file' '(' expression ')' ; list : '[' (expression (',' expression)* ','?)? ']' ; map : LCURL (argument ','?)* RCURL ; string : STRING | MULTILINESTRING ; identifier : IDENTIFIER | 'variable' ; fragment DIGIT : [0-9] ; SIGNED_NUMBER : '+' NUMBER | '-' NUMBER | NUMBER ; IN : 'in' ; STAR : '*' ; DOT : '.' ; operator : '/' | STAR | '%' | '+' | '-' | '>' | '>=' | '<' | '<=' | '==' | '!=' | '&&' | '||' ; LCURL : '{' ; RCURL : '}' ; LPAREN : '(' ; RPAREN : ')' ; EOF_ : '<<EOF' .*? 'EOF' ; NULL : 'nul' ; NUMBER : DIGIT+ (DOT DIGIT+)? ; BOOL : 'true' | 'false' ; DESCRIPTION : '<<DESCRIPTION' .*? 'DESCRIPTION' ; MULTILINESTRING : '<<-EOF' .*? 'EOF' ; STRING : '"' (~ [\r\n"] | '""' | '\\"')* '"' ; IDENTIFIER : [a-zA-Z] ([a-zA-Z0-9_-])* ; COMMENT : ('#' | '//') ~ [\r\n]* -> channel(HIDDEN) ; BLOCKCOMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; WS : [ \r\n\t]+ -> skip ;
/* BSD License Copyright (c) 2020, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar terraform; file : (local | module | output | provider | variable | data | resource | terraform)+ ; terraform : 'terraform' blockbody ; resource : 'resource' resourcetype name blockbody ; data : 'data' resourcetype name blockbody ; provider : 'provider' resourcetype blockbody ; output : 'output' name blockbody ; local : 'locals' blockbody ; module : 'module' name blockbody ; variable : VARIABLE name blockbody ; block : blocktype label* blockbody ; blocktype : IDENTIFIER ; resourcetype : STRING ; name : STRING ; label : STRING ; blockbody : LCURL (argument | block)* RCURL ; argument : identifier '=' expression ; identifier : (('local' | 'data' | 'var' | 'module') DOT)? identifierchain ; identifierchain : (IDENTIFIER | IN | VARIABLE) index? (DOT identifierchain)* | STAR (DOT identifierchain)* ; expression : section | expression operator expression | LPAREN expression RPAREN | expression '?' expression ':' expression | forloop ; forloop : 'for' identifier IN expression ':' expression ; section : list | map | val ; val : NULL | SIGNED_NUMBER | string | identifier | BOOL | DESCRIPTION | filedecl | functioncall | EOF_ ; functioncall : functionname LPAREN functionarguments RPAREN ; functionname : IDENTIFIER ; functionarguments : //no arguments | expression (',' expression)* ; index : '[' expression ']' ; filedecl : 'file' '(' expression ')' ; list : '[' (expression (',' expression)* ','?)? ']' ; map : LCURL (argument ','?)* RCURL ; string : STRING | MULTILINESTRING ; fragment DIGIT : [0-9] ; SIGNED_NUMBER : '+' NUMBER | '-' NUMBER | NUMBER ; VARIABLE : 'variable' ; IN : 'in' ; STAR : '*' ; DOT : '.' ; operator : '/' | STAR | '%' | '+' | '-' | '>' | '>=' | '<' | '<=' | '==' | '!=' | '&&' | '||' ; LCURL : '{' ; RCURL : '}' ; LPAREN : '(' ; RPAREN : ')' ; EOF_ : '<<EOF' .*? 'EOF' ; NULL : 'nul' ; NUMBER : DIGIT+ (DOT DIGIT+)? ; BOOL : 'true' | 'false' ; DESCRIPTION : '<<DESCRIPTION' .*? 'DESCRIPTION' ; MULTILINESTRING : '<<-EOF' .*? 'EOF' ; STRING : '"' (~ [\r\n"] | '""' | '\\"')* '"' ; IDENTIFIER : [a-zA-Z] ([a-zA-Z0-9_-])* ; COMMENT : ('#' | '//') ~ [\r\n]* -> channel(HIDDEN) ; BLOCKCOMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; WS : [ \r\n\t]+ -> skip ;
Fix merge error
Fix merge error
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
656b506fd618ef7a90e7a7d4838180a3605a8dc7
src/main/antlr/YokohamaUnitLexer.g4
src/main/antlr/YokohamaUnitLexer.g4
lexer grammar YokohamaUnitLexer; STAR_LBRACKET: '*[' [ \t]* -> mode(ABBREVIATION); HASHES: Hashes [ \t]* -> mode(UNTIL_EOL) ; TEST: Hashes [ \t]* 'Test:' [ \t]* -> mode(UNTIL_EOL); SETUP: Hashes [ \t]* 'Setup:' [ \t]* -> mode(UNTIL_EOL); EXERCISE: Hashes [ \t]* 'Exercise:' [ \t]* -> mode(UNTIL_EOL); VERIFY: Hashes [ \t]* 'Verify:' [ \t]* -> mode(UNTIL_EOL); TEARDOWN: Hashes [ \t]* 'Teardown:' [ \t]* -> mode(UNTIL_EOL); SETUP_NO_DESC: Hashes [ \t]* 'Setup' -> type(SETUP) ; EXERCISE_NO_DESC: Hashes [ \t]* 'Exercise' -> type(EXERCISE) ; VERIFY_NO_DESC: Hashes [ \t]* 'Verify' -> type(VERIFY) ; TEARDOWN_NO_DESC: Hashes [ \t]* 'Teardown' -> type(TEARDOWN) ; LBRACKET_DEFAULT_MODE: '[' -> type(LBRACKET), mode(ANCHOR); AS_BACK_TICK: 'as' Spaces? '`' -> mode(CLASS) ; BAR: '|' ; BAR_EOL: '|' [ \t]* '\r'? '\n' ; HBAR: '|' [|\-=\:\.\+ \t]* '|' [ \t]* '\r'? '\n' ; ASSERT: 'Assert' ; THAT: 'that' ; STOP: '.' ; AND: 'and' ; IS: 'is' ; NOT: 'not' ; THROWS: 'throws' ; FOR: 'for' ; ALL: 'all' ; COMMA: ',' ; IN: 'in' ; UTABLE: 'Table' ; CSV_SINGLE_QUOTE: 'CSV' Spaces? '\'' -> mode(IN_FILE_NAME) ; TSV_SINGLE_QUOTE: 'TSV' Spaces? '\''-> mode(IN_FILE_NAME) ; EXCEL_SINGLE_QUOTE: 'Excel' Spaces? '\'' -> mode(IN_BOOK_NAME) ; WHERE: 'where' ; EQ: '=' ; LET: 'Let' ; BE: 'be' ; ANY_OF: 'any' Spaces 'of' ; ANY_DEFINED_BY: 'any' Spaces ('value' 's'? Spaces)? 'defined' Spaces 'by' ; OR: 'or' ; DO: 'Do' ; A_STUB_OF_BACK_TICK: 'a' Spaces 'stub' Spaces 'of' Spaces? '`' -> mode(CLASS) ; SUCH: 'such' ; METHOD_BACK_TICK: 'method' Spaces? '`' -> mode(METHOD_PATTERN) ; RETURNS: 'returns' ; AN_INSTANCE_OF_BACK_TICK: 'an' Spaces 'instance' Spaces 'of' Spaces? '`' -> mode(CLASS) ; AN_INSTANCE: 'an' Spaces 'instance' -> mode(AFTER_AN_INSTANCE) ; AN_INVOCATION_OF_BACK_TICK: 'an' Spaces 'invocation' Spaces 'of' Spaces? '`' -> mode(METHOD_PATTERN) ; ON: 'on' ; WITH: 'with' ; INVOKE_TICK: 'Invoke' Spaces? '`' -> mode (METHOD_PATTERN) ; MATCHES: 'matches' ; DOES: 'does' ; MATCH: 'match' ; RE_TICK: 're' Spaces? '`' -> mode(REGEXP) ; RE_TICK2: 're' Spaces? '``' -> type(RE_TICK), mode(REGEXP2) ; REGEX_TICK: 'regex' Spaces? '`' -> mode(REGEXP) ; REGEX_TICK2: 'regex' Spaces? '``' -> type(RE_TICK), mode(REGEXP2) ; REGEXP_TICK: 'regexp' Spaces? '`' -> mode(REGEXP) ; REGEXP_TICK2: 'regexp' Spaces? '``' -> type(RE_TICK), mode(REGEXP2) ; RESOURCE: 'resource' ; A_TEMPORARY_FILE: 'a' Spaces 'temporary' Spaces 'file' ; A_TEMP_FILE: 'a' Spaces 'temp' Spaces 'file' ; NULL: 'null' ; NOTHING: 'nothing' ; TRUE: 'true' ; FALSE: 'false' ; Identifier: IdentStart IdentPart* ; Integer: IntegerLiteral ; FloatingPoint: FloatingPointLiteral ; MINUS: '-' ; EMPTY_STRING: '""' ; BACK_TICK: '`' -> mode(IN_BACK_TICK) ; DOUBLE_QUOTE: '"' -> mode(IN_DOUBLE_QUOTE) ; SINGLE_QUOTE: '\'' -> mode(IN_SINGLE_QUOTE) ; BACK_TICKS: '```' -> mode(IN_FENCE_3) ; BACK_TICKS4: '````' -> mode(IN_FENCE_4), type(BACK_TICKS) ; BACK_TICKS5: '`````' -> mode(IN_FENCE_5), type(BACK_TICKS) ; COMMENT : '{>>' .*? '<<}' -> skip ; WS : Spaces -> skip ; mode ABBREVIATION; ShortName: ~[\]\r\n]+ ; RBRACKET_COLON: ']:' [ \t]* -> mode(UNTIL_EOL) ; mode UNTIL_EOL; Line: ~[ \t\r\n]+ ([ \t]+ ~[ \t\r\n]+)* ; //exclude trailing spaces NEW_LINE: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode ANCHOR; Anchor: ~[\]\r\n]+ ; RBRACKET_ANCHOR: ']' -> type(RBRACKET), mode(DEFAULT_MODE) ; mode AFTER_AN_INSTANCE; OF: 'of' ; Identifier_AFTER_AN_INSTANCE : IdentStart IdentPart* -> type(Identifier) ; BACK_TICK_AFTER_AN_INSTANCE: '`' -> type(BACK_TICK), mode(CLASS) ; COMMENT_AFTER_AN_INSTANCE : '{>>' .*? '<<}' -> skip ; WS_AFTER_AN_INSTANCE: Spaces -> skip ; mode IN_DOUBLE_QUOTE; Str: (~["\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_DOUBLE_QUOTE: '"' -> type(DOUBLE_QUOTE), mode(DEFAULT_MODE) ; mode IN_SINGLE_QUOTE; Char: (~['\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_SINGLE_QUOTE: '\'' -> type(SINGLE_QUOTE), mode(DEFAULT_MODE) ; mode IN_BACK_TICK; Expr: ~[`]+ ; CLOSE_BACK_TICK: '`' -> type(BACK_TICK), mode(DEFAULT_MODE) ; mode IN_FENCE_3; CLOSE_BACK_TICKS_3: '```' [ \t]* ('\r'? '\n' | EOF) -> type(BACK_TICKS), mode(DEFAULT_MODE) ; CodeLine: ~[\r\n]* '\r'? '\n' ; mode IN_FENCE_4; CLOSE_BACK_TICKS_4: '````' [ \t]* ('\r'? '\n' | EOF) -> type(BACK_TICKS), mode(DEFAULT_MODE) ; CodeLine4: ~[\r\n]* '\r'? '\n' -> type(CodeLine) ; mode IN_FENCE_5; CLOSE_BACK_TICKS_5: '`````' [ \t]* ('\r'? '\n' | EOF) -> type(BACK_TICKS), mode(DEFAULT_MODE) ; CodeLine5: ~[\r\n]* '\r'? '\n' -> type(CodeLine) ; mode METHOD_PATTERN; BOOLEAN: 'boolean' ; BYTE: 'byte' ; SHORT: 'short' ; INT: 'int' ; LONG: 'long' ; CHAR: 'char' ; FLOAT: 'float' ; DOUBLE: 'double' ; COMMA_METHOD_PATTERN: ',' -> type(COMMA); THREEDOTS: '...' ; DOT: '.' ; LPAREN: '(' ; RPAREN: ')' ; LBRACKET: '[' ; RBRACKET: ']' ; HASH: '#' ; Identifier_METHOD_PATTERN : IdentStart IdentPart* -> type(Identifier); WS_METHOD_PATTERN: Spaces -> skip ; BACK_TICK_METHOD_PATTERN: '`' -> type(BACK_TICK), mode(DEFAULT_MODE) ; mode CLASS; DOT_CLASS: '.' -> type(DOT) ; Identifier_CLASS : IdentStart IdentPart* -> type(Identifier) ; WS_CLASS: Spaces -> skip ; BACK_TICK_CLASS: '`' -> type(BACK_TICK), mode(DEFAULT_MODE) ; mode IN_FILE_NAME; FileName: (~['\r\n]|'\'\'')+ ; CLOSE_SINGLE_QUOTE_IN_FILE_NAME: '\'' -> type(SINGLE_QUOTE), mode(DEFAULT_MODE) ; mode IN_BOOK_NAME; BookName: (~['\r\n]|'\'\'')+ ; CLOSE_SINGLE_QUOTE_IN_BOOK_NAME: '\'' -> type(SINGLE_QUOTE), mode(DEFAULT_MODE) ; mode REGEXP; Regexp: (~[`])+ ; BACK_TICK_REGEXP: '`' -> type(BACK_TICK), mode(DEFAULT_MODE) ; mode REGEXP2; Regexp2: (~[`] | '`' ~[`])+ -> type(Regexp) ; BACK_TICK_REGEXP2: '``' -> type(BACK_TICK), mode(DEFAULT_MODE) ; fragment Hashes: '#' | '##' | '###' | '####' | '#####' | '######' ; fragment Spaces: [ \t\r\n]+ ; fragment IdentStart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierStart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IdentPart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierPart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IntegerLiteral: DecimalIntegerLiteral | HexIntegerLiteral | OctalIntegerLiteral | BinaryIntegerLiteral ; fragment DecimalIntegerLiteral: DecimalNumeral IntegerTypeSuffix? ; fragment HexIntegerLiteral: HexNumeral IntegerTypeSuffix? ; fragment OctalIntegerLiteral: OctalNumeral IntegerTypeSuffix? ; fragment BinaryIntegerLiteral: BinaryNumeral IntegerTypeSuffix? ; fragment IntegerTypeSuffix: [lL] ; fragment DecimalNumeral: '0' | [1-9] ([_0-9]* [0-9])? ; fragment HexNumeral: '0' [xX] HexDigits ; fragment HexDigits: [0-9a-fA-F] ([_0-9a-fA-F]* [0-9a-fA-F])? ; fragment OctalNumeral: '0' [_0-7]* [0-7] ; fragment BinaryNumeral: '0' [bB] [01] ([_01]* [01])? ; fragment FloatingPointLiteral: DecimalFloatingPointLiteral | HexadecimalFloatingPointLiteral ; fragment DecimalFloatingPointLiteral: Digits '.' Digits ExponentPart? FloatTypeSuffix? | Digits '.' ExponentPart FloatTypeSuffix? | Digits '.' ExponentPart? FloatTypeSuffix /* the above rules differ from the Java spec: fp literals which end with dot are not allowd */ | '.' Digits ExponentPart? FloatTypeSuffix? | Digits ExponentPart FloatTypeSuffix? | Digits ExponentPart? FloatTypeSuffix ; fragment Digits: [0-9] ([_0-9]* [0-9])? ; fragment ExponentPart: [eE] SignedInteger ; fragment SignedInteger: ('+' | '-')? Digits ; fragment FloatTypeSuffix: [fFdD] ; fragment HexadecimalFloatingPointLiteral: HexSignificand BinaryExponent FloatTypeSuffix? ; fragment HexSignificand: HexNumeral '.'? | '0' [xX] HexDigits? . HexDigits ; fragment BinaryExponent: [pP] SignedInteger ; fragment UnicodeEscape: '\\' 'u'+ [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] ; fragment EscapeSequence: '\\b' // (backspace BS, Unicode \u0008) | '\\t' // (horizontal tab HT, Unicode \u0009) | '\\n' // (linefeed LF, Unicode \u000a) | '\\f' // (form feed FF, Unicode \u000c) | '\\r' // (carriage return CR, Unicode \u000d) | '\\"' // (double quote ", Unicode \u0022) | '\\\'' // (single quote ', Unicode \u0027) | '\\\\' // (backslash \, Unicode \u005c) | OctalEscape // (octal value, Unicode \u0000 to \u00ff) ; fragment OctalEscape: '\\' [0-7] | '\\' [0-7] [0-7] | '\\' [0-3] [0-7] [0-7] ;
lexer grammar YokohamaUnitLexer; STAR_LBRACKET: '*[' [ \t]* -> mode(ABBREVIATION); HASHES: Hashes [ \t]* -> mode(UNTIL_EOL) ; TEST: Hashes [ \t]* 'Test:' [ \t]* -> mode(UNTIL_EOL); SETUP: Hashes [ \t]* 'Setup:' [ \t]* -> mode(UNTIL_EOL); EXERCISE: Hashes [ \t]* 'Exercise:' [ \t]* -> mode(UNTIL_EOL); VERIFY: Hashes [ \t]* 'Verify:' [ \t]* -> mode(UNTIL_EOL); TEARDOWN: Hashes [ \t]* 'Teardown:' [ \t]* -> mode(UNTIL_EOL); SETUP_NO_DESC: Hashes [ \t]* 'Setup' -> type(SETUP) ; EXERCISE_NO_DESC: Hashes [ \t]* 'Exercise' -> type(EXERCISE) ; VERIFY_NO_DESC: Hashes [ \t]* 'Verify' -> type(VERIFY) ; TEARDOWN_NO_DESC: Hashes [ \t]* 'Teardown' -> type(TEARDOWN) ; LBRACKET_DEFAULT_MODE: '[' -> type(LBRACKET), mode(ANCHOR); AS_BACK_TICK: 'as' SpacesOrComments? '`' -> mode(CLASS) ; BAR: '|' ; BAR_EOL: '|' [ \t]* '\r'? '\n' ; HBAR: '|' [|\-=\:\.\+ \t]* '|' [ \t]* '\r'? '\n' ; ASSERT: 'Assert' ; THAT: 'that' ; STOP: '.' ; AND: 'and' ; IS: 'is' ; NOT: 'not' ; THROWS: 'throws' ; FOR: 'for' ; ALL: 'all' ; COMMA: ',' ; IN: 'in' ; UTABLE: 'Table' ; CSV_SINGLE_QUOTE: 'CSV' SpacesOrComments? '\'' -> mode(IN_FILE_NAME) ; TSV_SINGLE_QUOTE: 'TSV' SpacesOrComments? '\''-> mode(IN_FILE_NAME) ; EXCEL_SINGLE_QUOTE: 'Excel' SpacesOrComments? '\'' -> mode(IN_BOOK_NAME) ; WHERE: 'where' ; EQ: '=' ; LET: 'Let' ; BE: 'be' ; ANY_OF: 'any' SpacesOrComments 'of' ; ANY_DEFINED_BY: 'any' SpacesOrComments ('value' 's'? SpacesOrComments)? 'defined' SpacesOrComments 'by' ; OR: 'or' ; DO: 'Do' ; A_STUB_OF_BACK_TICK: 'a' SpacesOrComments 'stub' SpacesOrComments 'of' SpacesOrComments? '`' -> mode(CLASS) ; SUCH: 'such' ; METHOD_BACK_TICK: 'method' SpacesOrComments? '`' -> mode(METHOD_PATTERN) ; RETURNS: 'returns' ; AN_INSTANCE_OF_BACK_TICK: 'an' SpacesOrComments 'instance' Spaces 'of' SpacesOrComments? '`' -> mode(CLASS) ; AN_INSTANCE: 'an' SpacesOrComments 'instance' -> mode(AFTER_AN_INSTANCE) ; AN_INVOCATION_OF_BACK_TICK: 'an' SpacesOrComments 'invocation' SpacesOrComments 'of' SpacesOrComments? '`' -> mode(METHOD_PATTERN) ; ON: 'on' ; WITH: 'with' ; INVOKE_TICK: 'Invoke' SpacesOrComments? '`' -> mode (METHOD_PATTERN) ; MATCHES: 'matches' ; DOES: 'does' ; MATCH: 'match' ; RE_TICK: 're' SpacesOrComments? '`' -> mode(REGEXP) ; RE_TICK2: 're' SpacesOrComments? '``' -> type(RE_TICK), mode(REGEXP2) ; REGEX_TICK: 'regex' SpacesOrComments? '`' -> mode(REGEXP) ; REGEX_TICK2: 'regex' SpacesOrComments? '``' -> type(RE_TICK), mode(REGEXP2) ; REGEXP_TICK: 'regexp' SpacesOrComments? '`' -> mode(REGEXP) ; REGEXP_TICK2: 'regexp' SpacesOrComments? '``' -> type(RE_TICK), mode(REGEXP2) ; RESOURCE: 'resource' ; A_TEMPORARY_FILE: 'a' SpacesOrComments 'temporary' SpacesOrComments 'file' ; A_TEMP_FILE: 'a' SpacesOrComments 'temp' SpacesOrComments 'file' ; NULL: 'null' ; NOTHING: 'nothing' ; TRUE: 'true' ; FALSE: 'false' ; Identifier: IdentStart IdentPart* ; Integer: IntegerLiteral ; FloatingPoint: FloatingPointLiteral ; MINUS: '-' ; EMPTY_STRING: '""' ; BACK_TICK: '`' -> mode(IN_BACK_TICK) ; DOUBLE_QUOTE: '"' -> mode(IN_DOUBLE_QUOTE) ; SINGLE_QUOTE: '\'' -> mode(IN_SINGLE_QUOTE) ; BACK_TICKS: '```' -> mode(IN_FENCE_3) ; BACK_TICKS4: '````' -> mode(IN_FENCE_4), type(BACK_TICKS) ; BACK_TICKS5: '`````' -> mode(IN_FENCE_5), type(BACK_TICKS) ; COMMENT : '{>>' .*? '<<}' -> skip ; WS : Spaces -> skip ; mode ABBREVIATION; ShortName: ~[\]\r\n]+ ; RBRACKET_COLON: ']:' [ \t]* -> mode(UNTIL_EOL) ; mode UNTIL_EOL; Line: ~[ \t\r\n]+ ([ \t]+ ~[ \t\r\n]+)* ; //exclude trailing spaces NEW_LINE: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode ANCHOR; Anchor: ~[\]\r\n]+ ; RBRACKET_ANCHOR: ']' -> type(RBRACKET), mode(DEFAULT_MODE) ; mode AFTER_AN_INSTANCE; OF: 'of' ; Identifier_AFTER_AN_INSTANCE : IdentStart IdentPart* -> type(Identifier) ; BACK_TICK_AFTER_AN_INSTANCE: '`' -> type(BACK_TICK), mode(CLASS) ; COMMENT_AFTER_AN_INSTANCE : '{>>' .*? '<<}' -> skip ; WS_AFTER_AN_INSTANCE: Spaces -> skip ; mode IN_DOUBLE_QUOTE; Str: (~["\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_DOUBLE_QUOTE: '"' -> type(DOUBLE_QUOTE), mode(DEFAULT_MODE) ; mode IN_SINGLE_QUOTE; Char: (~['\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_SINGLE_QUOTE: '\'' -> type(SINGLE_QUOTE), mode(DEFAULT_MODE) ; mode IN_BACK_TICK; Expr: ~[`]+ ; CLOSE_BACK_TICK: '`' -> type(BACK_TICK), mode(DEFAULT_MODE) ; mode IN_FENCE_3; CLOSE_BACK_TICKS_3: '```' [ \t]* ('\r'? '\n' | EOF) -> type(BACK_TICKS), mode(DEFAULT_MODE) ; CodeLine: ~[\r\n]* '\r'? '\n' ; mode IN_FENCE_4; CLOSE_BACK_TICKS_4: '````' [ \t]* ('\r'? '\n' | EOF) -> type(BACK_TICKS), mode(DEFAULT_MODE) ; CodeLine4: ~[\r\n]* '\r'? '\n' -> type(CodeLine) ; mode IN_FENCE_5; CLOSE_BACK_TICKS_5: '`````' [ \t]* ('\r'? '\n' | EOF) -> type(BACK_TICKS), mode(DEFAULT_MODE) ; CodeLine5: ~[\r\n]* '\r'? '\n' -> type(CodeLine) ; mode METHOD_PATTERN; BOOLEAN: 'boolean' ; BYTE: 'byte' ; SHORT: 'short' ; INT: 'int' ; LONG: 'long' ; CHAR: 'char' ; FLOAT: 'float' ; DOUBLE: 'double' ; COMMA_METHOD_PATTERN: ',' -> type(COMMA); THREEDOTS: '...' ; DOT: '.' ; LPAREN: '(' ; RPAREN: ')' ; LBRACKET: '[' ; RBRACKET: ']' ; HASH: '#' ; Identifier_METHOD_PATTERN : IdentStart IdentPart* -> type(Identifier); WS_METHOD_PATTERN: Spaces -> skip ; BACK_TICK_METHOD_PATTERN: '`' -> type(BACK_TICK), mode(DEFAULT_MODE) ; mode CLASS; DOT_CLASS: '.' -> type(DOT) ; Identifier_CLASS : IdentStart IdentPart* -> type(Identifier) ; WS_CLASS: Spaces -> skip ; BACK_TICK_CLASS: '`' -> type(BACK_TICK), mode(DEFAULT_MODE) ; mode IN_FILE_NAME; FileName: (~['\r\n]|'\'\'')+ ; CLOSE_SINGLE_QUOTE_IN_FILE_NAME: '\'' -> type(SINGLE_QUOTE), mode(DEFAULT_MODE) ; mode IN_BOOK_NAME; BookName: (~['\r\n]|'\'\'')+ ; CLOSE_SINGLE_QUOTE_IN_BOOK_NAME: '\'' -> type(SINGLE_QUOTE), mode(DEFAULT_MODE) ; mode REGEXP; Regexp: (~[`])+ ; BACK_TICK_REGEXP: '`' -> type(BACK_TICK), mode(DEFAULT_MODE) ; mode REGEXP2; Regexp2: (~[`] | '`' ~[`])+ -> type(Regexp) ; BACK_TICK_REGEXP2: '``' -> type(BACK_TICK), mode(DEFAULT_MODE) ; fragment Hashes: '#' | '##' | '###' | '####' | '#####' | '######' ; fragment Spaces: [ \t\r\n]+ ; fragment SpacesOrComments: ([ \t\r\n] | ('{>>' .*? '<<}') )+ ; fragment IdentStart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierStart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IdentPart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierPart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IntegerLiteral: DecimalIntegerLiteral | HexIntegerLiteral | OctalIntegerLiteral | BinaryIntegerLiteral ; fragment DecimalIntegerLiteral: DecimalNumeral IntegerTypeSuffix? ; fragment HexIntegerLiteral: HexNumeral IntegerTypeSuffix? ; fragment OctalIntegerLiteral: OctalNumeral IntegerTypeSuffix? ; fragment BinaryIntegerLiteral: BinaryNumeral IntegerTypeSuffix? ; fragment IntegerTypeSuffix: [lL] ; fragment DecimalNumeral: '0' | [1-9] ([_0-9]* [0-9])? ; fragment HexNumeral: '0' [xX] HexDigits ; fragment HexDigits: [0-9a-fA-F] ([_0-9a-fA-F]* [0-9a-fA-F])? ; fragment OctalNumeral: '0' [_0-7]* [0-7] ; fragment BinaryNumeral: '0' [bB] [01] ([_01]* [01])? ; fragment FloatingPointLiteral: DecimalFloatingPointLiteral | HexadecimalFloatingPointLiteral ; fragment DecimalFloatingPointLiteral: Digits '.' Digits ExponentPart? FloatTypeSuffix? | Digits '.' ExponentPart FloatTypeSuffix? | Digits '.' ExponentPart? FloatTypeSuffix /* the above rules differ from the Java spec: fp literals which end with dot are not allowd */ | '.' Digits ExponentPart? FloatTypeSuffix? | Digits ExponentPart FloatTypeSuffix? | Digits ExponentPart? FloatTypeSuffix ; fragment Digits: [0-9] ([_0-9]* [0-9])? ; fragment ExponentPart: [eE] SignedInteger ; fragment SignedInteger: ('+' | '-')? Digits ; fragment FloatTypeSuffix: [fFdD] ; fragment HexadecimalFloatingPointLiteral: HexSignificand BinaryExponent FloatTypeSuffix? ; fragment HexSignificand: HexNumeral '.'? | '0' [xX] HexDigits? . HexDigits ; fragment BinaryExponent: [pP] SignedInteger ; fragment UnicodeEscape: '\\' 'u'+ [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] ; fragment EscapeSequence: '\\b' // (backspace BS, Unicode \u0008) | '\\t' // (horizontal tab HT, Unicode \u0009) | '\\n' // (linefeed LF, Unicode \u000a) | '\\f' // (form feed FF, Unicode \u000c) | '\\r' // (carriage return CR, Unicode \u000d) | '\\"' // (double quote ", Unicode \u0022) | '\\\'' // (single quote ', Unicode \u0027) | '\\\\' // (backslash \, Unicode \u005c) | OctalEscape // (octal value, Unicode \u0000 to \u00ff) ; fragment OctalEscape: '\\' [0-7] | '\\' [0-7] [0-7] | '\\' [0-3] [0-7] [0-7] ;
Introduce SpacesOrComments fragment
Introduce SpacesOrComments fragment
ANTLR
mit
tkob/yokohamaunit,tkob/yokohamaunit
294cb6e39b744139fa3841ed2276fd763c6351b3
src/br/com/wfcreations/annms/core/sqlann/SQLANN.g4
src/br/com/wfcreations/annms/core/sqlann/SQLANN.g4
/* * ANNDL - Artificial Neural Networks Definition Language * ANNML - Artificial Neural Network Manipulation Language * ANNQL - Artificial Neural Networks Query Language */ grammar SQLANN; @header { /* * Copyright (c) 2013, Welsiton Ferreira ([email protected]) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of the WFCreation nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package br.com.wfcreations.annms.core.sqlann; } options { language = Java; } /* * Lexer */ fragment A_ : ('a'|'A'); fragment B_ : ('b'|'B'); fragment C_ : ('c'|'C'); fragment D_ : ('d'|'D'); fragment E_ : ('e'|'E'); fragment F_ : ('f'|'F'); fragment G_ : ('g'|'G'); fragment H_ : ('h'|'H'); fragment I_ : ('i'|'I'); fragment J_ : ('j'|'J'); fragment K_ : ('k'|'K'); fragment L_ : ('l'|'L'); fragment M_ : ('m'|'M'); fragment N_ : ('n'|'N'); fragment O_ : ('o'|'O'); fragment P_ : ('p'|'P'); fragment Q_ : ('q'|'Q'); fragment R_ : ('r'|'R'); fragment S_ : ('s'|'S'); fragment T_ : ('t'|'T'); fragment U_ : ('u'|'U'); fragment V_ : ('v'|'V'); fragment W_ : ('w'|'W'); fragment X_ : ('x'|'X'); fragment Y_ : ('y'|'Y'); fragment Z_ : ('z'|'Z'); fragment DIGIT : [0-9]; fragment EscapeSequence : '\\' ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\'); OPEN_PARENTHESIS : '('; CLOSE_PARENTHESIS : ')'; OPEN_BRACKETS : '{'; CLOSE_BRACKETS : '}'; COMMA : ','; CLAUSE_END : ';'; EQUALS : '='; INTEGER : I_ N_ T_ E_ G_ E_ R_; REAL : R_ E_ A_ L_; BOOLEAN : B_ O_ O_ L_ E_ A_ N_; STRING : S_ T_ R_ I_ N_ G_; DATE : D_ A_ T_ E_; CREATE : C_ R_ E_ A_ T_ E_; DATA : D_ A_ T_ A_; DROP : D_ R_ O_ P_; TYPE : T_ Y_ P_ E_; INSERT : I_ N_ S_ E_ R_ T_; INTO : I_ N_ T_ O_; NEURALNETWORK : N_ E_ U_ R_ A_ L_ N_ E_ T_ W_ O_ R_ K_; NEURALNETWORKS : N_ E_ U_ R_ A_ L_ N_ E_ T_ W_ O_ R_ K_ S_; RUN : R_ U_ N_; SHOW : S_ H_ O_ W_; STATUS : S_ T_ A_ T_ U_ S_; TRAIN : T_ R_ A_ I_ N_; VALUES : V_ A_ L_ U_ E_ S_; TRUE : T_ R_ U_ E_; FALSE : F_ A_ L_ S_ E_; NOT : N_ O_ T_; NULL : N_ U_ L_ L_; EXISTS : E_ X_ I_ S_ T_ S_; IF : I_ F_; LIKE : L_ I_ K_ E_; LEARNRULE : L_ E_ A_ R_ N_ R_ U_ L_ E_; INPUT : I_ N_ P_ U_ T_; OUTPUT : O_ U_ T_ P_ U_ T_; Integer : [+-]? DIGIT+; Real : [+-]? DIGIT+ '.' DIGIT* | [+-]? '.' DIGIT+ ; ID : [a-zA-Z$][a-zA-Z0-9$_[\-\]]*; String : '"' ( EscapeSequence | ~('\\'|'"') )* '"'; COMMENT : '/*' .*? '*/' -> channel(HIDDEN); LINE_COMMENT : '//' ~[\r\n]* '\r'? '\n' -> channel(HIDDEN); WS : [ \r\t\u000C\n]+ -> skip; /* * Parser */ statements : statement (';' statement)* ';'?; statement : CREATE DATA (IF NOT EXISTS)? ID ('(' dataAttributes ')' | LIKE ID)? #createDataStatement | CREATE NEURALNETWORK (IF NOT EXISTS)? ID ('(' params ')' TYPE ('=')? ID | LIKE ID)? #createNeuralNetworkStatement | DROP DATA (IF EXISTS)? ID (',' ID)* #dropDataStatement | DROP NEURALNETWORK ID #dropNeuralNetworkStatement | INSERT INTO ID VALUES '(' values ')' #insertIntoStatement | RUN ID VALUES '(' values ')' #runStatement | SHOW DATA #showDataStatemen | SHOW DATA STATUS ID #showDataStatusStatement | SHOW NEURALNETWORKS #showNeuralNetworksStatement | SHOW NEURALNETWORK STATUS ID #showNeuralNetworkStatusStatement | SHOW STATUS #showStatusStatement | TRAIN ID ('(' params ')')? trainConfigs? #trainStatement ; dataAttributes : dataAttribute (',' dataAttribute)* ','?; dataAttribute : ID dataType ; dataType : BOOLEAN #booleanDataType | INTEGER #integerDataType | REAL #realDataType | STRING #stringDataType | DATE String #dateDataType | list #listDataType ; list : '{' ID (',' ID)* '}'; params : param (',' param)* ','? ; param : ID paramValue* ; paramValue : value | complexList ; value : (TRUE | FALSE) #booleanValue | NULL #nullValue | Integer #integerValue | Real #realValue | String #stringValue ; values : value (',' value)* ; complexList : '{' paramValue (',' paramValue)* '}' ; trainConfigs : trainConfig (',' trainConfig)*; trainConfig : LEARNRULE ('=')? ID | DATA ('=')? ID | INPUT ('=')? list | OUTPUT ('=') list;
/* * ANNDL - Artificial Neural Networks Definition Language * ANNML - Artificial Neural Network Manipulation Language * ANNQL - Artificial Neural Networks Query Language */ grammar SQLANN; @header { /* * Copyright (c) 2013, Welsiton Ferreira ([email protected]) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of the WFCreation nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package br.com.wfcreations.annms.core.sqlann; } options { language = Java; } /* * Lexer */ fragment A_ : ('a'|'A'); fragment B_ : ('b'|'B'); fragment C_ : ('c'|'C'); fragment D_ : ('d'|'D'); fragment E_ : ('e'|'E'); fragment F_ : ('f'|'F'); fragment G_ : ('g'|'G'); fragment H_ : ('h'|'H'); fragment I_ : ('i'|'I'); fragment J_ : ('j'|'J'); fragment K_ : ('k'|'K'); fragment L_ : ('l'|'L'); fragment M_ : ('m'|'M'); fragment N_ : ('n'|'N'); fragment O_ : ('o'|'O'); fragment P_ : ('p'|'P'); fragment Q_ : ('q'|'Q'); fragment R_ : ('r'|'R'); fragment S_ : ('s'|'S'); fragment T_ : ('t'|'T'); fragment U_ : ('u'|'U'); fragment V_ : ('v'|'V'); fragment W_ : ('w'|'W'); fragment X_ : ('x'|'X'); fragment Y_ : ('y'|'Y'); fragment Z_ : ('z'|'Z'); fragment DIGIT : [0-9]; fragment EscapeSequence : '\\' ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\'); OPEN_PARENTHESIS : '('; CLOSE_PARENTHESIS : ')'; OPEN_BRACKETS : '{'; CLOSE_BRACKETS : '}'; COMMA : ','; CLAUSE_END : ';'; EQUALS : '='; INTEGER : I_ N_ T_ E_ G_ E_ R_; REAL : R_ E_ A_ L_; BOOLEAN : B_ O_ O_ L_ E_ A_ N_; STRING : S_ T_ R_ I_ N_ G_; DATE : D_ A_ T_ E_; CREATE : C_ R_ E_ A_ T_ E_; DATA : D_ A_ T_ A_; DROP : D_ R_ O_ P_; MODEL : M_ O_ D_ E_ L_; INSERT : I_ N_ S_ E_ R_ T_; INTO : I_ N_ T_ O_; NEURALNETWORK : N_ E_ U_ R_ A_ L_ N_ E_ T_ W_ O_ R_ K_; NEURALNETWORKS : N_ E_ U_ R_ A_ L_ N_ E_ T_ W_ O_ R_ K_ S_; RUN : R_ U_ N_; SHOW : S_ H_ O_ W_; STATUS : S_ T_ A_ T_ U_ S_; TRAIN : T_ R_ A_ I_ N_; VALUES : V_ A_ L_ U_ E_ S_; TRUE : T_ R_ U_ E_; FALSE : F_ A_ L_ S_ E_; NOT : N_ O_ T_; NULL : N_ U_ L_ L_; EXISTS : E_ X_ I_ S_ T_ S_; IF : I_ F_; LIKE : L_ I_ K_ E_; LEARNRULE : L_ E_ A_ R_ N_ R_ U_ L_ E_; INPUT : I_ N_ P_ U_ T_; OUTPUT : O_ U_ T_ P_ U_ T_; Integer : [+-]? DIGIT+; Real : [+-]? DIGIT+ '.' DIGIT* | [+-]? '.' DIGIT+ ; ID : [a-zA-Z$][a-zA-Z0-9$_[\-\]]*; String : '"' ( EscapeSequence | ~('\\'|'"') )* '"'; COMMENT : '/*' .*? '*/' -> channel(HIDDEN); LINE_COMMENT : '//' ~[\r\n]* '\r'? '\n' -> channel(HIDDEN); WS : [ \r\t\u000C\n]+ -> skip; /* * Parser */ statements : statement (';' statement)* ';'?; statement : CREATE DATA (IF NOT EXISTS)? ID ('(' dataAttributes ')' | LIKE ID)? #createDataStatement | CREATE NEURALNETWORK (IF NOT EXISTS)? ID (('(' params ')')? MODEL ('=')? ID | LIKE ID)? #createNeuralNetworkStatement | DROP DATA (IF EXISTS)? ID (',' ID)* #dropDataStatement | DROP NEURALNETWORKS (IF EXISTS)? ID (',' ID)* #dropNeuralNetworkStatement | INSERT INTO ID VALUES '(' values ')' #insertIntoStatement | RUN ID VALUES '(' values ')' #runStatement | SHOW DATA #showDataStatemen | SHOW DATA STATUS ID #showDataStatusStatement | SHOW NEURALNETWORKS #showNeuralNetworksStatement | SHOW NEURALNETWORK STATUS ID #showNeuralNetworkStatusStatement | SHOW STATUS #showStatusStatement | TRAIN ID ('(' params ')')? LEARNRULE ('=')? ID ',' DATA ('=')? ID ',' INPUT ('=')? list (',' OUTPUT ('=') list)? #trainStatement ; dataAttributes : dataAttribute (',' dataAttribute)* ','?; dataAttribute : ID dataType ; dataType : BOOLEAN #booleanDataType | INTEGER #integerDataType | REAL #realDataType | STRING #stringDataType | DATE String #dateDataType | list #listDataType ; list : '{' ID (',' ID)* '}'; params : param (',' param)* ','? ; param : ID paramValue* ; paramValue : value | complexList ; value : (TRUE | FALSE) #booleanValue | NULL #nullValue | Integer #integerValue | Real #realValue | String #stringValue | ID #idValue ; values : value (',' value)* ; complexList : '{' paramValue (',' paramValue)* '}' ;
Update grammar
Update grammar
ANTLR
bsd-3-clause
wfcreations/ANNMS
8c88178939989907bd83b65badd620511531b08a
python/PythonParser.g4
python/PythonParser.g4
// Header included from Python site: /* * Grammar for Python * * Note: Changing the grammar specified in this file will most likely * require corresponding changes in the parser module * (../Modules/parsermodule.c). If you can't make the changes to * that module yourself, please co-ordinate the required changes * with someone who can; ask around on python-dev for help. Fred * Drake <[email protected]> will probably be listening there. * * NOTE WELL: You should also follow all the steps listed in PEP 306, * "How to Change Python's Grammar" * * Start symbols for the grammar: * single_input is a single interactive statement; * file_input is a module or sequence of commands read from an input file; * eval_input is the input for the eval() and input() functions. * NB: compound_stmt in single_input is followed by extra NEWLINE! */ parser grammar PythonParser; options { tokenVocab=PythonLexer; } root : single_input | file_input | eval_input ; single_input : NEWLINE | simple_stmt | compound_stmt NEWLINE ; file_input : (NEWLINE | stmt)* EOF ; eval_input : testlist NEWLINE* EOF ; decorator : AT dotted_name (OPEN_PAREN arglist? CLOSE_PAREN)? NEWLINE ; decorated : decorator+ (classdef | funcdef) ; funcdef : ASYNC? DEF name parameters (ARROW test)? COLON suite ; parameters : OPEN_PAREN typedargslist? CLOSE_PAREN ; //python 3 paramters typedargslist : (def_parameters COMMA)? (args (COMMA def_parameters)? (COMMA kwargs)? | kwargs) | def_parameters ; args : STAR named_parameter ; kwargs : POWER named_parameter ; def_parameters : def_parameter (COMMA def_parameter)* ; def_parameter : named_parameter (ASSIGN test)? | STAR ; vardef_parameters : vardef_parameter (COMMA vardef_parameter)* ; vardef_parameter : name (ASSIGN test)? ; named_parameter : name (COLON test)? ; //python 2 paramteters varargslist : (vardef_parameters COMMA)? varargs (COMMA vardef_parameters)? (COMMA varkwargs) | vardef_parameters ; varargs : STAR name ; varkwargs : POWER name ; stmt : simple_stmt | compound_stmt ; simple_stmt : small_stmt (SEMI_COLON small_stmt)* SEMI_COLON? (NEWLINE | EOF) ; small_stmt : expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | exec_stmt | assert_stmt | nonlocal_stmt ; //Python 3 nonlocal_stmt : NONLOCAL name (COMMA name)* ; expr_stmt : testlist_star_expr | annassign | augassign | assign ; // if left expression in assign is bool literal, it's mean that is Python 2 here assign : testlist_star_expr (ASSIGN (yield_expr | testlist_star_expr))* ; // Python3 rule annassign : testlist_star_expr COLON test (ASSIGN (yield_expr | testlist))? ; testlist_star_expr : (test | star_expr) (COMMA (test | star_expr))* COMMA? ; augassign : testlist_star_expr op=( ADD_ASSIGN | SUB_ASSIGN | MULT_ASSIGN | AT_ASSIGN | DIV_ASSIGN | MOD_ASSIGN | AND_ASSIGN | OR_ASSIGN | XOR_ASSIGN | LEFT_SHIFT_ASSIGN | RIGHT_SHIFT_ASSIGN | POWER_ASSIGN | IDIV_ASSIGN ) (yield_expr | testlist) ; // python 2 print_stmt : PRINT ((test (COMMA test)* COMMA?) | RIGHT_SHIFT test ((COMMA test)+ COMMA?)) ; del_stmt : DEL exprlist ; pass_stmt : PASS ; flow_stmt : break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt ; break_stmt : BREAK ; continue_stmt : CONTINUE ; return_stmt : RETURN testlist? ; yield_stmt : yield_expr ; raise_stmt : RAISE (test (COMMA test (COMMA test)?)?)? (FROM test)? ; import_stmt : import_name | import_from ; import_name : IMPORT dotted_as_names ; import_from : (FROM ((DOT | ELLIPSIS)* dotted_name | (DOT | ELLIPSIS)+) IMPORT (STAR | OPEN_PAREN import_as_names CLOSE_PAREN | import_as_names)) ; import_as_name : name (AS name)? ; dotted_as_name : dotted_name (AS name)? ; import_as_names : import_as_name (COMMA import_as_name)* COMMA? ; dotted_as_names : dotted_as_name (COMMA dotted_as_name)* ; dotted_name : dotted_name DOT name | name ; global_stmt : GLOBAL name (COMMA name)* ; exec_stmt : EXEC expr (IN test (COMMA test)?)? ; assert_stmt : ASSERT test (COMMA test)? ; compound_stmt : if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated | async_stmt ; async_stmt : ASYNC (funcdef | with_stmt | for_stmt) ; if_stmt : IF test COLON suite elif_clause* else_clause? ; elif_clause : ELIF test COLON suite ; else_clause : ELSE COLON suite ; while_stmt : WHILE test COLON suite else_clause? ; for_stmt : FOR exprlist IN testlist COLON suite else_clause? ; try_stmt : TRY COLON suite (except_clause+ else_clause? finaly_clause? | finaly_clause) ; finaly_clause : FINALLY COLON suite ; with_stmt : WITH with_item (COMMA with_item)* COLON suite ; with_item // NB compile.c makes sure that the default except clause is last : test (AS expr)? ; // Python 2 : EXCEPT test COMMA name, Python 3 : EXCEPT test AS name except_clause : EXCEPT (test (COMMA name | AS name)?)? COLON suite ; suite : simple_stmt | NEWLINE INDENT stmt+ DEDENT ; // Backward compatibility cruft to support: // [ x for x in lambda: True, lambda: False if x() ] // even while also allowing: // lambda x: 5 if x else 2 // (But not a mix of the two) testlist_safe : old_test ((COMMA old_test)+ COMMA?)? ; old_test : logical_test | old_lambdef ; old_lambdef : LAMBDA varargslist? COLON old_test ; test : logical_test (IF logical_test ELSE test)? | lambdef ; test_nocond : logical_test | lambdef_nocond ; lambdef_nocond : LAMBDA varargslist? COLON test_nocond ; logical_test : logical_test op=OR logical_test | logical_test op=AND logical_test | NOT logical_test | comparison ; // <> isn't actually a valid comparison operator in Python. It's here for the // sake of a __future__ import described in PEP 401 (which really works :-) comparison : comparison op=(LESS_THAN | GREATER_THAN | EQUALS | GT_EQ | LT_EQ | NOT_EQ_1 | NOT_EQ_2 | IN | IS | NOT) comparison | comparison (NOT IN | IS NOT) comparison | expr ; star_expr : STAR expr ; expr : expr op=OR_OP expr | expr op=XOR expr | expr op=AND_OP expr | expr op=(LEFT_SHIFT | RIGHT_SHIFT) expr | expr op=(ADD | MINUS) expr | expr op=(STAR | DIV | MOD | IDIV) expr | expr op=(ADD | MINUS) expr | expr op=POWER expr | op=(ADD | MINUS | NOT_OP) expr | AWAIT? atom trailer* ; atom : dotted_name | OPEN_PAREN (yield_expr | testlist_comp)? CLOSE_PAREN | OPEN_BRACKET testlist_comp? CLOSE_BRACKET | OPEN_BRACE dictorsetmaker? CLOSE_BRACE | REVERSE_QUOTE testlist COMMA? REVERSE_QUOTE | ELLIPSIS | name | PRINT | EXEC | MINUS? number | NONE | STRING+ ; name : NAME | TRUE | FALSE ; number : integer | IMAG_NUMBER | FLOAT_NUMBER ; integer : DECIMAL_INTEGER | OCT_INTEGER | HEX_INTEGER | BIN_INTEGER ; testlist_comp : (test | star_expr) (comp_for | (COMMA (test | star_expr))* COMMA?) ; lambdef : LAMBDA varargslist? COLON test ; trailer : OPEN_PAREN arglist? CLOSE_PAREN | OPEN_BRACKET subscriptlist CLOSE_BRACKET | DOT name ; subscriptlist : subscript (COMMA subscript)* COMMA? ; subscript : ELLIPSIS | test | test? COLON test? sliceop? ; sliceop : COLON test? ; exprlist : expr (COMMA expr)* COMMA? ; testlist : test (COMMA test)* COMMA? ; dictorsetmaker : (test COLON test | POWER expr) (comp_for | (COMMA (test COLON test | POWER expr))* COMMA?) | (test | star_expr) (comp_for | (COMMA (test | star_expr))* COMMA?) ; classdef : CLASS name (OPEN_PAREN arglist? CLOSE_PAREN)? COLON suite ; arglist // The reason that keywords are test nodes instead of name is that using name // results in an ambiguity. ast.c makes sure it's a name. : argument (COMMA argument)* COMMA? ; argument : test comp_for? | test ASSIGN test | POWER test | STAR test ; list_iter : list_for | list_if ; list_for : FOR exprlist IN testlist_safe list_iter? ; list_if : IF old_test list_iter? ; comp_iter : comp_for | comp_if ; comp_for : FOR exprlist IN logical_test comp_iter? ; comp_if : IF old_test comp_iter? ; // not used in grammar, but may appear in "node" passed from Parser to Compiler encoding_decl : name ; yield_expr : YIELD yield_arg? ; yield_arg : FROM test | testlist ;
// Header included from Python site: /* * Grammar for Python * * Note: Changing the grammar specified in this file will most likely * require corresponding changes in the parser module * (../Modules/parsermodule.c). If you can't make the changes to * that module yourself, please co-ordinate the required changes * with someone who can; ask around on python-dev for help. Fred * Drake <[email protected]> will probably be listening there. * * NOTE WELL: You should also follow all the steps listed in PEP 306, * "How to Change Python's Grammar" * * Start symbols for the grammar: * single_input is a single interactive statement; * file_input is a module or sequence of commands read from an input file; * eval_input is the input for the eval() and input() functions. * NB: compound_stmt in single_input is followed by extra NEWLINE! */ parser grammar PythonParser; options { tokenVocab=PythonLexer; } root : (single_input | file_input | eval_input)? EOF ; single_input : NEWLINE | simple_stmt | compound_stmt NEWLINE ; file_input : (NEWLINE | stmt)+ ; eval_input : testlist NEWLINE* ; decorator : AT dotted_name (OPEN_PAREN arglist? CLOSE_PAREN)? NEWLINE ; decorated : decorator+ (classdef | funcdef) ; funcdef : ASYNC? DEF name parameters (ARROW test)? COLON suite ; parameters : OPEN_PAREN typedargslist? CLOSE_PAREN ; //python 3 paramters typedargslist : (def_parameters COMMA)? (args (COMMA def_parameters)? (COMMA kwargs)? | kwargs) | def_parameters ; args : STAR named_parameter ; kwargs : POWER named_parameter ; def_parameters : def_parameter (COMMA def_parameter)* ; def_parameter : named_parameter (ASSIGN test)? | STAR ; vardef_parameters : vardef_parameter (COMMA vardef_parameter)* ; vardef_parameter : name (ASSIGN test)? ; named_parameter : name (COLON test)? ; //python 2 paramteters varargslist : (vardef_parameters COMMA)? varargs (COMMA vardef_parameters)? (COMMA varkwargs) | vardef_parameters ; varargs : STAR name ; varkwargs : POWER name ; stmt : simple_stmt | compound_stmt ; simple_stmt : small_stmt (SEMI_COLON small_stmt)* SEMI_COLON? (NEWLINE | EOF) ; small_stmt : expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | exec_stmt | assert_stmt | nonlocal_stmt ; //Python 3 nonlocal_stmt : NONLOCAL name (COMMA name)* ; expr_stmt : testlist_star_expr | annassign | augassign | assign ; // if left expression in assign is bool literal, it's mean that is Python 2 here assign : testlist_star_expr (ASSIGN (yield_expr | testlist_star_expr))* ; // Python3 rule annassign : testlist_star_expr COLON test (ASSIGN (yield_expr | testlist))? ; testlist_star_expr : (test | star_expr) (COMMA (test | star_expr))* COMMA? ; augassign : testlist_star_expr op=( ADD_ASSIGN | SUB_ASSIGN | MULT_ASSIGN | AT_ASSIGN | DIV_ASSIGN | MOD_ASSIGN | AND_ASSIGN | OR_ASSIGN | XOR_ASSIGN | LEFT_SHIFT_ASSIGN | RIGHT_SHIFT_ASSIGN | POWER_ASSIGN | IDIV_ASSIGN ) (yield_expr | testlist) ; // python 2 print_stmt : PRINT ((test (COMMA test)* COMMA?) | RIGHT_SHIFT test ((COMMA test)+ COMMA?)) ; del_stmt : DEL exprlist ; pass_stmt : PASS ; flow_stmt : break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt ; break_stmt : BREAK ; continue_stmt : CONTINUE ; return_stmt : RETURN testlist? ; yield_stmt : yield_expr ; raise_stmt : RAISE (test (COMMA test (COMMA test)?)?)? (FROM test)? ; import_stmt : import_name | import_from ; import_name : IMPORT dotted_as_names ; import_from : (FROM ((DOT | ELLIPSIS)* dotted_name | (DOT | ELLIPSIS)+) IMPORT (STAR | OPEN_PAREN import_as_names CLOSE_PAREN | import_as_names)) ; import_as_name : name (AS name)? ; dotted_as_name : dotted_name (AS name)? ; import_as_names : import_as_name (COMMA import_as_name)* COMMA? ; dotted_as_names : dotted_as_name (COMMA dotted_as_name)* ; dotted_name : dotted_name DOT name | name ; global_stmt : GLOBAL name (COMMA name)* ; exec_stmt : EXEC expr (IN test (COMMA test)?)? ; assert_stmt : ASSERT test (COMMA test)? ; compound_stmt : if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated | async_stmt ; async_stmt : ASYNC (funcdef | with_stmt | for_stmt) ; if_stmt : IF test COLON suite elif_clause* else_clause? ; elif_clause : ELIF test COLON suite ; else_clause : ELSE COLON suite ; while_stmt : WHILE test COLON suite else_clause? ; for_stmt : FOR exprlist IN testlist COLON suite else_clause? ; try_stmt : TRY COLON suite (except_clause+ else_clause? finaly_clause? | finaly_clause) ; finaly_clause : FINALLY COLON suite ; with_stmt : WITH with_item (COMMA with_item)* COLON suite ; with_item // NB compile.c makes sure that the default except clause is last : test (AS expr)? ; // Python 2 : EXCEPT test COMMA name, Python 3 : EXCEPT test AS name except_clause : EXCEPT (test (COMMA name | AS name)?)? COLON suite ; suite : simple_stmt | NEWLINE INDENT stmt+ DEDENT ; // Backward compatibility cruft to support: // [ x for x in lambda: True, lambda: False if x() ] // even while also allowing: // lambda x: 5 if x else 2 // (But not a mix of the two) testlist_safe : old_test ((COMMA old_test)+ COMMA?)? ; old_test : logical_test | old_lambdef ; old_lambdef : LAMBDA varargslist? COLON old_test ; test : logical_test (IF logical_test ELSE test)? | lambdef ; test_nocond : logical_test | lambdef_nocond ; lambdef_nocond : LAMBDA varargslist? COLON test_nocond ; logical_test : logical_test op=OR logical_test | logical_test op=AND logical_test | NOT logical_test | comparison ; // <> isn't actually a valid comparison operator in Python. It's here for the // sake of a __future__ import described in PEP 401 (which really works :-) comparison : comparison op=(LESS_THAN | GREATER_THAN | EQUALS | GT_EQ | LT_EQ | NOT_EQ_1 | NOT_EQ_2 | IN | IS | NOT) comparison | comparison (NOT IN | IS NOT) comparison | expr ; star_expr : STAR expr ; expr : expr op=OR_OP expr | expr op=XOR expr | expr op=AND_OP expr | expr op=(LEFT_SHIFT | RIGHT_SHIFT) expr | expr op=(ADD | MINUS) expr | expr op=(STAR | DIV | MOD | IDIV) expr | expr op=(ADD | MINUS) expr | expr op=POWER expr | op=(ADD | MINUS | NOT_OP) expr | AWAIT? atom trailer* ; atom : dotted_name | OPEN_PAREN (yield_expr | testlist_comp)? CLOSE_PAREN | OPEN_BRACKET testlist_comp? CLOSE_BRACKET | OPEN_BRACE dictorsetmaker? CLOSE_BRACE | REVERSE_QUOTE testlist COMMA? REVERSE_QUOTE | ELLIPSIS | name | PRINT | EXEC | MINUS? number | NONE | STRING+ ; name : NAME | TRUE | FALSE ; number : integer | IMAG_NUMBER | FLOAT_NUMBER ; integer : DECIMAL_INTEGER | OCT_INTEGER | HEX_INTEGER | BIN_INTEGER ; testlist_comp : (test | star_expr) (comp_for | (COMMA (test | star_expr))* COMMA?) ; lambdef : LAMBDA varargslist? COLON test ; trailer : OPEN_PAREN arglist? CLOSE_PAREN | OPEN_BRACKET subscriptlist CLOSE_BRACKET | DOT name ; subscriptlist : subscript (COMMA subscript)* COMMA? ; subscript : ELLIPSIS | test | test? COLON test? sliceop? ; sliceop : COLON test? ; exprlist : expr (COMMA expr)* COMMA? ; testlist : test (COMMA test)* COMMA? ; dictorsetmaker : (test COLON test | POWER expr) (comp_for | (COMMA (test COLON test | POWER expr))* COMMA?) | (test | star_expr) (comp_for | (COMMA (test | star_expr))* COMMA?) ; classdef : CLASS name (OPEN_PAREN arglist? CLOSE_PAREN)? COLON suite ; arglist // The reason that keywords are test nodes instead of name is that using name // results in an ambiguity. ast.c makes sure it's a name. : argument (COMMA argument)* COMMA? ; argument : test comp_for? | test ASSIGN test | POWER test | STAR test ; list_iter : list_for | list_if ; list_for : FOR exprlist IN testlist_safe list_iter? ; list_if : IF old_test list_iter? ; comp_iter : comp_for | comp_if ; comp_for : FOR exprlist IN logical_test comp_iter? ; comp_if : IF old_test comp_iter? ; // not used in grammar, but may appear in "node" passed from Parser to Compiler encoding_decl : name ; yield_expr : YIELD yield_arg? ; yield_arg : FROM test | testlist ;
Add EOF token to all roots
Add EOF token to all roots
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
77e2e8320312b1a2a0345cc7837176f5b6fcbba3
pdn/pdn.g4
pdn/pdn.g4
/* BSD License Copyright (c) 2017, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar pdn; game : tags moves ; tags : tag* ; tag : '[' text string ']' ; moves : move+ (result | '*') ; move : movenum movespec+ ; movespec : (MOVE1 | MOVE2) (result | '*')? ; movenum : number '.' ; result : '1/2-1/2' | '1-0' | '0-1' ; text : TEXT ; string : STRING ; number : NUMBER ; MOVE1 : ('0' .. '9') + 'x' ('0' .. '9') + ; MOVE2 : ('0' .. '9') + '-' ('0' .. '9') + ; NUMBER : ('0' .. '9') + ; TEXT : [a-zA-Z] [a-zA-Z0-9_] + ; STRING : '"' ('""' | ~ '"')* '"' ; COMMENT : '{' .*? '}' -> skip ; WS : [ \t\r\n] + -> skip ;
/* BSD License Copyright (c) 2017, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar pdn; game : tags moves EOF ; tags : tag* ; tag : '[' text string ']' ; moves : move+ (result | '*')+ ; move : movenum movespec+ ; movespec : (MOVE1 | MOVE2) (result | '*')? ; movenum : number '.' ; result : '1/2-1/2' | '1-0' | '0-1' ; text : TEXT ; string : STRING ; number : NUMBER ; MOVE1 : ('0' .. '9') + 'x' ('0' .. '9') + ; MOVE2 : ('0' .. '9') + '-' ('0' .. '9') + ; NUMBER : ('0' .. '9') + ; TEXT : [a-zA-Z] [a-zA-Z0-9_] + ; STRING : '"' ('""' | ~ '"')* '"' ; COMMENT : '{' .*? '}' -> skip ; WS : [ \t\r\n] + -> skip ;
Add EOF start rule to pdf/, fix parse with duplicate final result--apparently acceptable.
Add EOF start rule to pdf/, fix parse with duplicate final result--apparently acceptable.
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
ce7cd542c77add5fd0949f36a250d35b14e61ac9
java/JavaParser.g4
java/JavaParser.g4
/* [The "BSD licence"] Copyright (c) 2013 Terence Parr, Sam Harwell Copyright (c) 2017 Ivan Kochurkin (upgrade to Java 8) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ parser grammar JavaParser; options { tokenVocab=JavaLexer; } compilationUnit : packageDeclaration? importDeclaration* typeDeclaration* EOF ; packageDeclaration : annotation* PACKAGE qualifiedName ';' ; importDeclaration : IMPORT STATIC? qualifiedName ('.' '*')? ';' ; typeDeclaration : classOrInterfaceModifier* (classDeclaration | enumDeclaration | interfaceDeclaration | annotationTypeDeclaration) | ';' ; modifier : classOrInterfaceModifier | NATIVE | SYNCHRONIZED | TRANSIENT | VOLATILE ; classOrInterfaceModifier : annotation | PUBLIC | PROTECTED | PRIVATE | STATIC | ABSTRACT | FINAL // FINAL for class only -- does not apply to interfaces | STRICTFP ; variableModifier : FINAL | annotation ; classDeclaration : CLASS IDENTIFIER typeParameters? (EXTENDS typeType)? (IMPLEMENTS typeList)? classBody ; typeParameters : '<' typeParameter (',' typeParameter)* '>' ; typeParameter : annotation* IDENTIFIER (EXTENDS typeBound)? ; typeBound : typeType ('&' typeType)* ; enumDeclaration : ENUM IDENTIFIER (IMPLEMENTS typeList)? '{' enumConstants? ','? enumBodyDeclarations? '}' ; enumConstants : enumConstant (',' enumConstant)* ; enumConstant : annotation* IDENTIFIER arguments? classBody? ; enumBodyDeclarations : ';' classBodyDeclaration* ; interfaceDeclaration : INTERFACE IDENTIFIER typeParameters? (EXTENDS typeList)? interfaceBody ; classBody : '{' classBodyDeclaration* '}' ; interfaceBody : '{' interfaceBodyDeclaration* '}' ; classBodyDeclaration : ';' | STATIC? block | modifier* memberDeclaration ; memberDeclaration : methodDeclaration | genericMethodDeclaration | fieldDeclaration | constructorDeclaration | genericConstructorDeclaration | interfaceDeclaration | annotationTypeDeclaration | classDeclaration | enumDeclaration ; /* We use rule this even for void methods which cannot have [] after parameters. This simplifies grammar and we can consider void to be a type, which renders the [] matching as a context-sensitive issue or a semantic check for invalid return type after parsing. */ methodDeclaration : typeTypeOrVoid IDENTIFIER formalParameters ('[' ']')* (THROWS qualifiedNameList)? methodBody ; methodBody : block | ';' ; typeTypeOrVoid : typeType | VOID ; genericMethodDeclaration : typeParameters methodDeclaration ; genericConstructorDeclaration : typeParameters constructorDeclaration ; constructorDeclaration : IDENTIFIER formalParameters (THROWS qualifiedNameList)? constructorBody=block ; fieldDeclaration : typeType variableDeclarators ';' ; interfaceBodyDeclaration : modifier* interfaceMemberDeclaration | ';' ; interfaceMemberDeclaration : constDeclaration | interfaceMethodDeclaration | genericInterfaceMethodDeclaration | interfaceDeclaration | annotationTypeDeclaration | classDeclaration | enumDeclaration ; constDeclaration : typeType constantDeclarator (',' constantDeclarator)* ';' ; constantDeclarator : IDENTIFIER ('[' ']')* '=' variableInitializer ; // see matching of [] comment in methodDeclaratorRest // methodBody from Java8 interfaceMethodDeclaration : interfaceMethodModifier* (typeTypeOrVoid | typeParameters annotation* typeTypeOrVoid) IDENTIFIER formalParameters ('[' ']')* (THROWS qualifiedNameList)? methodBody ; // Java8 interfaceMethodModifier : annotation | PUBLIC | ABSTRACT | DEFAULT | STATIC | STRICTFP ; genericInterfaceMethodDeclaration : typeParameters interfaceMethodDeclaration ; variableDeclarators : variableDeclarator (',' variableDeclarator)* ; variableDeclarator : variableDeclaratorId ('=' variableInitializer)? ; variableDeclaratorId : IDENTIFIER ('[' ']')* ; variableInitializer : arrayInitializer | expression ; arrayInitializer : '{' (variableInitializer (',' variableInitializer)* (',')? )? '}' ; classOrInterfaceType : IDENTIFIER typeArguments? ('.' IDENTIFIER typeArguments?)* ; typeArgument : typeType | '?' ((EXTENDS | SUPER) typeType)? ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; formalParameters : '(' formalParameterList? ')' ; formalParameterList : formalParameter (',' formalParameter)* (',' lastFormalParameter)? | lastFormalParameter ; formalParameter : variableModifier* typeType variableDeclaratorId ; lastFormalParameter : variableModifier* typeType '...' variableDeclaratorId ; qualifiedName : IDENTIFIER ('.' IDENTIFIER)* ; literal : integerLiteral | floatLiteral | CHAR_LITERAL | STRING_LITERAL | BOOL_LITERAL | NULL_LITERAL ; integerLiteral : DECIMAL_LITERAL | HEX_LITERAL | OCT_LITERAL | BINARY_LITERAL ; floatLiteral : FLOAT_LITERAL | HEX_FLOAT_LITERAL ; // ANNOTATIONS annotation : '@' qualifiedName ('(' ( elementValuePairs | elementValue )? ')')? ; elementValuePairs : elementValuePair (',' elementValuePair)* ; elementValuePair : IDENTIFIER '=' elementValue ; elementValue : expression | annotation | elementValueArrayInitializer ; elementValueArrayInitializer : '{' (elementValue (',' elementValue)*)? (',')? '}' ; annotationTypeDeclaration : '@' INTERFACE IDENTIFIER annotationTypeBody ; annotationTypeBody : '{' (annotationTypeElementDeclaration)* '}' ; annotationTypeElementDeclaration : modifier* annotationTypeElementRest | ';' // this is not allowed by the grammar, but apparently allowed by the actual compiler ; annotationTypeElementRest : typeType annotationMethodOrConstantRest ';' | classDeclaration ';'? | interfaceDeclaration ';'? | enumDeclaration ';'? | annotationTypeDeclaration ';'? ; annotationMethodOrConstantRest : annotationMethodRest | annotationConstantRest ; annotationMethodRest : IDENTIFIER '(' ')' defaultValue? ; annotationConstantRest : variableDeclarators ; defaultValue : DEFAULT elementValue ; // STATEMENTS / BLOCKS block : '{' blockStatement* '}' ; blockStatement : localVariableDeclaration ';' | statement | localTypeDeclaration ; localVariableDeclaration : variableModifier* typeType variableDeclarators ; localTypeDeclaration : classOrInterfaceModifier* (classDeclaration | interfaceDeclaration) | ';' ; statement : blockLabel=block | ASSERT expression (':' expression)? ';' | IF parExpression statement (ELSE statement)? | FOR '(' forControl ')' statement | WHILE parExpression statement | DO statement WHILE parExpression ';' | TRY block (catchClause+ finallyBlock? | finallyBlock) | TRY resourceSpecification block catchClause* finallyBlock? | SWITCH parExpression '{' switchBlockStatementGroup* switchLabel* '}' | SYNCHRONIZED parExpression block | RETURN expression? ';' | THROW expression ';' | BREAK IDENTIFIER? ';' | CONTINUE IDENTIFIER? ';' | SEMI | statementExpression=expression ';' | identifierLabel=IDENTIFIER ':' statement ; catchClause : CATCH '(' variableModifier* catchType IDENTIFIER ')' block ; catchType : qualifiedName ('|' qualifiedName)* ; finallyBlock : FINALLY block ; resourceSpecification : '(' resources ';'? ')' ; resources : resource (';' resource)* ; resource : variableModifier* classOrInterfaceType variableDeclaratorId '=' expression ; /** Matches cases then statements, both of which are mandatory. * To handle empty cases at the end, we add switchLabel* to statement. */ switchBlockStatementGroup : switchLabel+ blockStatement+ ; switchLabel : CASE (constantExpression=expression | enumConstantName=IDENTIFIER) ':' | DEFAULT ':' ; forControl : enhancedForControl | forInit? ';' expression? ';' forUpdate=expressionList? ; forInit : localVariableDeclaration | expressionList ; enhancedForControl : variableModifier* typeType variableDeclaratorId ':' expression ; // EXPRESSIONS parExpression : '(' expression ')' ; expressionList : expression (',' expression)* ; methodCall : IDENTIFIER '(' expressionList? ')' ; expression : primary | expression bop='.' ( IDENTIFIER | methodCall | THIS | NEW nonWildcardTypeArguments? innerCreator | SUPER superSuffix | explicitGenericInvocation ) | expression '[' expression ']' | methodCall | NEW creator | '(' typeType ')' expression | expression postfix=('++' | '--') | prefix=('+'|'-'|'++'|'--') expression | prefix=('~'|'!') expression | expression bop=('*'|'/'|'%') expression | expression bop=('+'|'-') expression | expression ('<' '<' | '>' '>' '>' | '>' '>') expression | expression bop=('<=' | '>=' | '>' | '<') expression | expression bop=INSTANCEOF typeType | expression bop=('==' | '!=') expression | expression bop='&' expression | expression bop='^' expression | expression bop='|' expression | expression bop='&&' expression | expression bop='||' expression | expression bop='?' expression ':' expression | <assoc=right> expression bop=('=' | '+=' | '-=' | '*=' | '/=' | '&=' | '|=' | '^=' | '>>=' | '>>>=' | '<<=' | '%=') expression | lambdaExpression // Java8 // Java 8 methodReference | expression '::' typeArguments? IDENTIFIER | typeType '::' (typeArguments? IDENTIFIER | NEW) | classType '::' typeArguments? NEW ; // Java8 lambdaExpression : lambdaParameters '->' lambdaBody ; // Java8 lambdaParameters : IDENTIFIER | '(' formalParameterList? ')' | '(' IDENTIFIER (',' IDENTIFIER)* ')' ; // Java8 lambdaBody : expression | block ; primary : '(' expression ')' | THIS | SUPER | literal | IDENTIFIER | typeTypeOrVoid '.' CLASS | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) ; classType : (classOrInterfaceType '.')? annotation* IDENTIFIER typeArguments? ; creator : nonWildcardTypeArguments createdName classCreatorRest | createdName (arrayCreatorRest | classCreatorRest) ; createdName : IDENTIFIER typeArgumentsOrDiamond? ('.' IDENTIFIER typeArgumentsOrDiamond?)* | primitiveType ; innerCreator : IDENTIFIER nonWildcardTypeArgumentsOrDiamond? classCreatorRest ; arrayCreatorRest : '[' (']' ('[' ']')* arrayInitializer | expression ']' ('[' expression ']')* ('[' ']')*) ; classCreatorRest : arguments classBody? ; explicitGenericInvocation : nonWildcardTypeArguments explicitGenericInvocationSuffix ; typeArgumentsOrDiamond : '<' '>' | typeArguments ; nonWildcardTypeArgumentsOrDiamond : '<' '>' | nonWildcardTypeArguments ; nonWildcardTypeArguments : '<' typeList '>' ; typeList : typeType (',' typeType)* ; typeType : annotation? (classOrInterfaceType | primitiveType) ('[' ']')* ; primitiveType : BOOLEAN | CHAR | BYTE | SHORT | INT | LONG | FLOAT | DOUBLE ; typeArguments : '<' typeArgument (',' typeArgument)* '>' ; superSuffix : arguments | '.' IDENTIFIER arguments? ; explicitGenericInvocationSuffix : SUPER superSuffix | IDENTIFIER arguments ; arguments : '(' expressionList? ')' ;
/* [The "BSD licence"] Copyright (c) 2013 Terence Parr, Sam Harwell Copyright (c) 2017 Ivan Kochurkin (upgrade to Java 8) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ parser grammar JavaParser; options { tokenVocab=JavaLexer; } compilationUnit : packageDeclaration? importDeclaration* typeDeclaration* EOF ; packageDeclaration : annotation* PACKAGE qualifiedName ';' ; importDeclaration : IMPORT STATIC? qualifiedName ('.' '*')? ';' ; typeDeclaration : classOrInterfaceModifier* (classDeclaration | enumDeclaration | interfaceDeclaration | annotationTypeDeclaration) | ';' ; modifier : classOrInterfaceModifier | NATIVE | SYNCHRONIZED | TRANSIENT | VOLATILE ; classOrInterfaceModifier : annotation | PUBLIC | PROTECTED | PRIVATE | STATIC | ABSTRACT | FINAL // FINAL for class only -- does not apply to interfaces | STRICTFP ; variableModifier : FINAL | annotation ; classDeclaration : CLASS IDENTIFIER typeParameters? (EXTENDS typeType)? (IMPLEMENTS typeList)? classBody ; typeParameters : '<' typeParameter (',' typeParameter)* '>' ; typeParameter : annotation* IDENTIFIER (EXTENDS typeBound)? ; typeBound : typeType ('&' typeType)* ; enumDeclaration : ENUM IDENTIFIER (IMPLEMENTS typeList)? '{' enumConstants? ','? enumBodyDeclarations? '}' ; enumConstants : enumConstant (',' enumConstant)* ; enumConstant : annotation* IDENTIFIER arguments? classBody? ; enumBodyDeclarations : ';' classBodyDeclaration* ; interfaceDeclaration : INTERFACE IDENTIFIER typeParameters? (EXTENDS typeList)? interfaceBody ; classBody : '{' classBodyDeclaration* '}' ; interfaceBody : '{' interfaceBodyDeclaration* '}' ; classBodyDeclaration : ';' | STATIC? block | modifier* memberDeclaration ; memberDeclaration : methodDeclaration | genericMethodDeclaration | fieldDeclaration | constructorDeclaration | genericConstructorDeclaration | interfaceDeclaration | annotationTypeDeclaration | classDeclaration | enumDeclaration ; /* We use rule this even for void methods which cannot have [] after parameters. This simplifies grammar and we can consider void to be a type, which renders the [] matching as a context-sensitive issue or a semantic check for invalid return type after parsing. */ methodDeclaration : typeTypeOrVoid IDENTIFIER formalParameters ('[' ']')* (THROWS qualifiedNameList)? methodBody ; methodBody : block | ';' ; typeTypeOrVoid : typeType | VOID ; genericMethodDeclaration : typeParameters methodDeclaration ; genericConstructorDeclaration : typeParameters constructorDeclaration ; constructorDeclaration : IDENTIFIER formalParameters (THROWS qualifiedNameList)? constructorBody=block ; fieldDeclaration : typeType variableDeclarators ';' ; interfaceBodyDeclaration : modifier* interfaceMemberDeclaration | ';' ; interfaceMemberDeclaration : constDeclaration | interfaceMethodDeclaration | genericInterfaceMethodDeclaration | interfaceDeclaration | annotationTypeDeclaration | classDeclaration | enumDeclaration ; constDeclaration : typeType constantDeclarator (',' constantDeclarator)* ';' ; constantDeclarator : IDENTIFIER ('[' ']')* '=' variableInitializer ; // see matching of [] comment in methodDeclaratorRest // methodBody from Java8 interfaceMethodDeclaration : interfaceMethodModifier* (typeTypeOrVoid | typeParameters annotation* typeTypeOrVoid) IDENTIFIER formalParameters ('[' ']')* (THROWS qualifiedNameList)? methodBody ; // Java8 interfaceMethodModifier : annotation | PUBLIC | ABSTRACT | DEFAULT | STATIC | STRICTFP ; genericInterfaceMethodDeclaration : typeParameters interfaceMethodDeclaration ; variableDeclarators : variableDeclarator (',' variableDeclarator)* ; variableDeclarator : variableDeclaratorId ('=' variableInitializer)? ; variableDeclaratorId : IDENTIFIER ('[' ']')* ; variableInitializer : arrayInitializer | expression ; arrayInitializer : '{' (variableInitializer (',' variableInitializer)* (',')? )? '}' ; classOrInterfaceType : IDENTIFIER typeArguments? ('.' IDENTIFIER typeArguments?)* ; typeArgument : typeType | '?' ((EXTENDS | SUPER) typeType)? ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; formalParameters : '(' formalParameterList? ')' ; formalParameterList : formalParameter (',' formalParameter)* (',' lastFormalParameter)? | lastFormalParameter ; formalParameter : variableModifier* typeType variableDeclaratorId ; lastFormalParameter : variableModifier* typeType '...' variableDeclaratorId ; qualifiedName : IDENTIFIER ('.' IDENTIFIER)* ; literal : integerLiteral | floatLiteral | CHAR_LITERAL | STRING_LITERAL | BOOL_LITERAL | NULL_LITERAL ; integerLiteral : DECIMAL_LITERAL | HEX_LITERAL | OCT_LITERAL | BINARY_LITERAL ; floatLiteral : FLOAT_LITERAL | HEX_FLOAT_LITERAL ; // ANNOTATIONS annotation : '@' qualifiedName ('(' ( elementValuePairs | elementValue )? ')')? ; elementValuePairs : elementValuePair (',' elementValuePair)* ; elementValuePair : IDENTIFIER '=' elementValue ; elementValue : expression | annotation | elementValueArrayInitializer ; elementValueArrayInitializer : '{' (elementValue (',' elementValue)*)? (',')? '}' ; annotationTypeDeclaration : '@' INTERFACE IDENTIFIER annotationTypeBody ; annotationTypeBody : '{' (annotationTypeElementDeclaration)* '}' ; annotationTypeElementDeclaration : modifier* annotationTypeElementRest | ';' // this is not allowed by the grammar, but apparently allowed by the actual compiler ; annotationTypeElementRest : typeType annotationMethodOrConstantRest ';' | classDeclaration ';'? | interfaceDeclaration ';'? | enumDeclaration ';'? | annotationTypeDeclaration ';'? ; annotationMethodOrConstantRest : annotationMethodRest | annotationConstantRest ; annotationMethodRest : IDENTIFIER '(' ')' defaultValue? ; annotationConstantRest : variableDeclarators ; defaultValue : DEFAULT elementValue ; // STATEMENTS / BLOCKS block : '{' blockStatement* '}' ; blockStatement : localVariableDeclaration ';' | statement | localTypeDeclaration ; localVariableDeclaration : variableModifier* typeType variableDeclarators ; localTypeDeclaration : classOrInterfaceModifier* (classDeclaration | interfaceDeclaration) | ';' ; statement : blockLabel=block | ASSERT expression (':' expression)? ';' | IF parExpression statement (ELSE statement)? | FOR '(' forControl ')' statement | WHILE parExpression statement | DO statement WHILE parExpression ';' | TRY block (catchClause+ finallyBlock? | finallyBlock) | TRY resourceSpecification block catchClause* finallyBlock? | SWITCH parExpression '{' switchBlockStatementGroup* switchLabel* '}' | SYNCHRONIZED parExpression block | RETURN expression? ';' | THROW expression ';' | BREAK IDENTIFIER? ';' | CONTINUE IDENTIFIER? ';' | SEMI | statementExpression=expression ';' | identifierLabel=IDENTIFIER ':' statement ; catchClause : CATCH '(' variableModifier* catchType IDENTIFIER ')' block ; catchType : qualifiedName ('|' qualifiedName)* ; finallyBlock : FINALLY block ; resourceSpecification : '(' resources ';'? ')' ; resources : resource (';' resource)* ; resource : variableModifier* classOrInterfaceType variableDeclaratorId '=' expression ; /** Matches cases then statements, both of which are mandatory. * To handle empty cases at the end, we add switchLabel* to statement. */ switchBlockStatementGroup : switchLabel+ blockStatement+ ; switchLabel : CASE (constantExpression=expression | enumConstantName=IDENTIFIER) ':' | DEFAULT ':' ; forControl : enhancedForControl | forInit? ';' expression? ';' forUpdate=expressionList? ; forInit : localVariableDeclaration | expressionList ; enhancedForControl : variableModifier* typeType variableDeclaratorId ':' expression ; // EXPRESSIONS parExpression : '(' expression ')' ; expressionList : expression (',' expression)* ; methodCall : IDENTIFIER '(' expressionList? ')' | THIS '(' expressionList? ')' | SUPER '(' expressionList? ')' ; expression : primary | expression bop='.' ( IDENTIFIER | methodCall | THIS | NEW nonWildcardTypeArguments? innerCreator | SUPER superSuffix | explicitGenericInvocation ) | expression '[' expression ']' | methodCall | NEW creator | '(' typeType ')' expression | expression postfix=('++' | '--') | prefix=('+'|'-'|'++'|'--') expression | prefix=('~'|'!') expression | expression bop=('*'|'/'|'%') expression | expression bop=('+'|'-') expression | expression ('<' '<' | '>' '>' '>' | '>' '>') expression | expression bop=('<=' | '>=' | '>' | '<') expression | expression bop=INSTANCEOF typeType | expression bop=('==' | '!=') expression | expression bop='&' expression | expression bop='^' expression | expression bop='|' expression | expression bop='&&' expression | expression bop='||' expression | expression bop='?' expression ':' expression | <assoc=right> expression bop=('=' | '+=' | '-=' | '*=' | '/=' | '&=' | '|=' | '^=' | '>>=' | '>>>=' | '<<=' | '%=') expression | lambdaExpression // Java8 // Java 8 methodReference | expression '::' typeArguments? IDENTIFIER | typeType '::' (typeArguments? IDENTIFIER | NEW) | classType '::' typeArguments? NEW ; // Java8 lambdaExpression : lambdaParameters '->' lambdaBody ; // Java8 lambdaParameters : IDENTIFIER | '(' formalParameterList? ')' | '(' IDENTIFIER (',' IDENTIFIER)* ')' ; // Java8 lambdaBody : expression | block ; primary : '(' expression ')' | THIS | SUPER | literal | IDENTIFIER | typeTypeOrVoid '.' CLASS | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) ; classType : (classOrInterfaceType '.')? annotation* IDENTIFIER typeArguments? ; creator : nonWildcardTypeArguments createdName classCreatorRest | createdName (arrayCreatorRest | classCreatorRest) ; createdName : IDENTIFIER typeArgumentsOrDiamond? ('.' IDENTIFIER typeArgumentsOrDiamond?)* | primitiveType ; innerCreator : IDENTIFIER nonWildcardTypeArgumentsOrDiamond? classCreatorRest ; arrayCreatorRest : '[' (']' ('[' ']')* arrayInitializer | expression ']' ('[' expression ']')* ('[' ']')*) ; classCreatorRest : arguments classBody? ; explicitGenericInvocation : nonWildcardTypeArguments explicitGenericInvocationSuffix ; typeArgumentsOrDiamond : '<' '>' | typeArguments ; nonWildcardTypeArgumentsOrDiamond : '<' '>' | nonWildcardTypeArguments ; nonWildcardTypeArguments : '<' typeList '>' ; typeList : typeType (',' typeType)* ; typeType : annotation? (classOrInterfaceType | primitiveType) ('[' ']')* ; primitiveType : BOOLEAN | CHAR | BYTE | SHORT | INT | LONG | FLOAT | DOUBLE ; typeArguments : '<' typeArgument (',' typeArgument)* '>' ; superSuffix : arguments | '.' IDENTIFIER arguments? ; explicitGenericInvocationSuffix : SUPER superSuffix | IDENTIFIER arguments ; arguments : '(' expressionList? ')' ;
Fix #1069 #1097 #1208
Fix #1069 #1097 #1208 In constructor body: - Fix calling parent constructor - Fix calling overloaded constructor
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
db9c9b38b8f8a702a578e37e94ce52a29fcdf665
src/main/antlr/mrtim/sasscompiler/grammar/Sass.g4
src/main/antlr/mrtim/sasscompiler/grammar/Sass.g4
grammar Sass; NL : '\r'? '\n' -> skip; WS : (' ' | '\t' | NL) -> skip; COMMENT: '/*' .*? '*/' -> skip; LINE_COMMENT : '//' ~[\r\n]* NL? -> skip; DSTRING : '"' ('\\"' | ~'"')* '"'; SSTRING : '\'' ('\\\'' | ~'\'')* '\''; URL : 'url(' ~[)]* ')'; COMMA : ','; SEMICOLON: ';'; LPAREN: '('; RPAREN: ')'; LBRACE: '{'; RBRACE: '}'; LSQBRACKET: '['; RSQBRACKET: ']'; DOLLAR: '$'; EQUALS: '='; COLON: ':'; STAR: '*'; BAR: '|'; DOT: '.'; IMPORT_KW : '@import'; MIXIN_KW: '@mixin'; FUNCTION_KW: '@function'; INCLUDE_KW: '@include'; //CSS constants EVEN_KW: 'even'; ODD_KW: 'odd'; PSEUDO_NOT_KW: ':not'; DIMENSION : 'px'; DIGITS: [0-9]+; PLUS: '+'; MINUS: '-'; IDENTIFIER: [a-zA-Z][a-zA-Z0-9_-]*; VARIABLE: '$' IDENTIFIER; TILDE: '~'; RARROW: '>'; PIPE: '|'; CARET: '^'; HASH: '#'; PERCENT: '%'; ID_NAME: HASH IDENTIFIER; CLASS_NAME: DOT IDENTIFIER; string: DSTRING | SSTRING; import_target: URL | string; import_statement : IMPORT_KW import_target ( ',' import_target )* SEMICOLON; definition : ( MIXIN_KW | FUNCTION_KW) IDENTIFIER parameter_def_list block_body ; include_statement : INCLUDE_KW IDENTIFIER parameter_list? SEMICOLON; parameter_def_list: LPAREN ( variable_def (COMMA variable_def)* )? RPAREN; parameter_list: LPAREN ( parameter (COMMA parameter)* )? RPAREN; parameter: (IDENTIFIER | variable_def | value); variable_def: VARIABLE (COLON value_list)?; //selectors: L309-532 //selector_schema: parser.cpp:309 //selector_group: parser.cpp:336 selector_list: selector_combination (COMMA selector_combination)*; //selector_combination: parser.cpp:362 selector_combination: (simple_selector+)? ((PLUS | TILDE | RARROW) selector_combination)?; //simple_selector_sequence: parser.cpp:399 //simple_selector_sequence: simple_selector+; //simple_selector: parser.cpp:426 simple_selector: (ID_NAME | CLASS_NAME | string ) // or number | type_selector // don't think this is right... | negated_selector | pseudo_selector | attribute_selector | placeholder_selector ; placeholder_selector: PERCENT IDENTIFIER; //negated_selector: parser.cpp:453 negated_selector: PSEUDO_NOT_KW LPAREN selector_list RPAREN; //pseudo_selector: parser.cpp:464 pseudo_selector: ((pseudo_prefix)? functional ((EVEN_KW | ODD_KW) | binomial | IDENTIFIER | string )? RPAREN ) | pseudo_prefix IDENTIFIER; pseudo_prefix: COLON COLON?; functional: IDENTIFIER LPAREN; binomial: integer IDENTIFIER (PLUS DIGITS)?; //attribute_selector: parser.cpp:517 attribute_selector: LSQBRACKET type_selector ((TILDE | PIPE | STAR | CARET | DOLLAR)? EQUALS (string | IDENTIFIER))? RSQBRACKET; type_selector: namespace_prefix? IDENTIFIER; namespace_prefix: (IDENTIFIER | STAR) BAR; variable: variable_def SEMICOLON; //parser.cpp:534 block_body: LBRACE ( import_statement // not allowed inside mixins and functions | assignment | ruleset | include_statement | variable )* RBRACE; variable_assignment: VARIABLE COLON value_list SEMICOLON; css_identifier: MINUS? IDENTIFIER; assignment: css_identifier COLON value_list SEMICOLON; value_list: value ( value )*; value : (VARIABLE | IDENTIFIER | string | integer ( DIMENSION | PERCENT)? ); integer: (PLUS | MINUS)? DIGITS; ruleset: selector_list block_body; sass_file : ( import_statement | definition | ruleset | variable | include_statement )*;
grammar Sass; NL : '\r'? '\n' -> skip; WS : (' ' | '\t' | NL) -> skip; COMMENT: '/*' .*? '*/' -> skip; LINE_COMMENT : '//' ~[\r\n]* NL? -> skip; DSTRING : '"' ('\\"' | ~'"')* '"'; SSTRING : '\'' ('\\\'' | ~'\'')* '\''; URL : 'url(' ~[)]* ')'; COMMA : ','; SEMICOLON: ';'; LPAREN: '('; RPAREN: ')'; LBRACE: '{'; RBRACE: '}'; LSQBRACKET: '['; RSQBRACKET: ']'; DOLLAR: '$'; EQUALS: '='; COLON: ':'; STAR: '*'; BAR: '|'; DOT: '.'; IMPORT_KW : '@import'; MIXIN_KW: '@mixin'; FUNCTION_KW: '@function'; INCLUDE_KW: '@include'; //CSS constants EVEN_KW: 'even'; ODD_KW: 'odd'; PSEUDO_NOT_KW: ':not'; DIMENSION : 'px'; DIGITS: [0-9]+; PLUS: '+'; MINUS: '-'; IDENTIFIER: [a-zA-Z#.][a-zA-Z0-9_#.-]*; VARIABLE: '$' IDENTIFIER; TILDE: '~'; RARROW: '>'; PIPE: '|'; CARET: '^'; HASH: '#'; PERCENT: '%'; ID_NAME: HASH IDENTIFIER; CLASS_NAME: DOT IDENTIFIER; string: DSTRING | SSTRING; import_target: URL | string; import_statement : IMPORT_KW import_target ( ',' import_target )* SEMICOLON; definition : ( MIXIN_KW | FUNCTION_KW) IDENTIFIER parameter_def_list block_body ; include_statement : INCLUDE_KW IDENTIFIER parameter_list? SEMICOLON; parameter_def_list: LPAREN ( variable_def (COMMA variable_def)* )? RPAREN; parameter_list: LPAREN ( parameter (COMMA parameter)* )? RPAREN; parameter: (IDENTIFIER | variable_def | value); variable_def: VARIABLE (COLON value_list)?; //selectors: L309-532 //selector_schema: parser.cpp:309 //selector_group: parser.cpp:336 selector_list: selector_combination (COMMA selector_combination)*; //selector_combination: parser.cpp:362 selector_combination: (simple_selector+)? ((PLUS | TILDE | RARROW) selector_combination)?; //simple_selector_sequence: parser.cpp:399 //simple_selector_sequence: simple_selector+; //simple_selector: parser.cpp:426 simple_selector: (ID_NAME | CLASS_NAME | string ) // or number | type_selector // don't think this is right... | negated_selector | pseudo_selector | attribute_selector | placeholder_selector ; placeholder_selector: PERCENT IDENTIFIER; //negated_selector: parser.cpp:453 negated_selector: PSEUDO_NOT_KW LPAREN selector_list RPAREN; //pseudo_selector: parser.cpp:464 pseudo_selector: ((pseudo_prefix)? functional ((EVEN_KW | ODD_KW) | binomial | IDENTIFIER | string )? RPAREN ) | pseudo_prefix IDENTIFIER; pseudo_prefix: COLON COLON?; functional: IDENTIFIER LPAREN; binomial: integer IDENTIFIER (PLUS DIGITS)?; //attribute_selector: parser.cpp:517 attribute_selector: LSQBRACKET type_selector ((TILDE | PIPE | STAR | CARET | DOLLAR)? EQUALS (string | IDENTIFIER))? RSQBRACKET; type_selector: namespace_prefix? IDENTIFIER; namespace_prefix: (IDENTIFIER | STAR) BAR; variable: variable_def SEMICOLON; //parser.cpp:534 block_body: LBRACE ( import_statement // not allowed inside mixins and functions | assignment | ruleset | include_statement | variable )* RBRACE; variable_assignment: VARIABLE COLON value_list SEMICOLON; css_identifier: MINUS? IDENTIFIER; assignment: css_identifier COLON value_list SEMICOLON; value_list: value ( value )*; value : (VARIABLE | IDENTIFIER | string | integer ( DIMENSION | PERCENT)? ); integer: (PLUS | MINUS)? DIGITS; ruleset: selector_list block_body; sass_file : ( import_statement | definition | ruleset | variable | include_statement )*;
Expand IDENTIFIER to include css classes and ids
Expand IDENTIFIER to include css classes and ids
ANTLR
mit
mr-tim/sass-compiler,mr-tim/sass-compiler
6460d991df9285af115ec5624a55e7403888e9da
terraform/terraform.g4
terraform/terraform.g4
/* BSD License Copyright (c) 2020, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar terraform; file : (local | module | output | provider | variable | data | resource)+ ; resource : 'resource' label* blockbody ; data : 'data' label* blockbody ; provider : 'provider' STRING blockbody ; output : 'output' STRING blockbody ; local : 'locals' blockbody ; module : 'module' STRING blockbody ; variable : 'variable' STRING blockbody ; block : blocktype label* blockbody ; blocktype : IDENTIFIER ; label : STRING ; blockbody : '{' (argument | block)* '}' ; argument : identifier '=' expression ; identifier : IDENTIFIER ; expression : section ('.' section)* ; section : list | map | val ; val : NULL | NUMBER | string | BOOL | IDENTIFIER index? | DESCRIPTION | filedecl | functioncall | EOF_ ; functioncall : functionname '(' functionarguments ')' ; functionname : IDENTIFIER ; functionarguments : //no arguments | expression (',' expression)* ; index : '[' expression ']' ; filedecl : 'file' '(' expression ')' ; list : '[' expression (',' expression)* ','? ']' ; map : '{' argument* '}' ; string : STRING | MULTILINESTRING ; fragment DIGIT : [0-9] ; EOF_ : '<<EOF' .*? 'EOF' ; NULL : 'nul' ; NUMBER : DIGIT+ ('.' DIGIT+)? ; BOOL : 'true' | 'false' ; DESCRIPTION : '<<DESCRIPTION' .*? 'DESCRIPTION' ; MULTILINESTRING : '<<-EOF' .*? 'EOF' ; STRING : '"' (~ [\r\n"] | '""')* '"' ; IDENTIFIER : [a-zA-Z]([a-zA-Z0-9_-])* ; COMMENT : ('#' | '//') ~ [\r\n]* -> channel(HIDDEN) ; BLOCKCOMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; WS : [ \r\n\t]+ -> skip ;
/* BSD License Copyright (c) 2020, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar terraform; file : (local | module | output | provider | variable | data | resource)+ ; resource : 'resource' label* blockbody ; data : 'data' label* blockbody ; provider : 'provider' STRING blockbody ; output : 'output' STRING blockbody ; local : 'locals' blockbody ; module : 'module' STRING blockbody ; variable : 'variable' STRING blockbody ; block : blocktype label* blockbody ; blocktype : IDENTIFIER ; label : STRING ; blockbody : '{' (argument | block)* '}' ; argument : identifier '=' expression ; identifier : IDENTIFIER ; expression : section ('.' section)* ; section : list | map | val ; val : NULL | NUMBER | string | BOOL | IDENTIFIER index? | DESCRIPTION | filedecl | functioncall | EOF_ ; functioncall : functionname '(' functionarguments ')' ; functionname : IDENTIFIER ; functionarguments : //no arguments | expression (',' expression)* ; index : '[' expression ']' ; filedecl : 'file' '(' expression ')' ; list : '[' expression (',' expression)* ','? ']' ; map : '{' argument* '}' ; string : STRING | MULTILINESTRING ; fragment DIGIT : [0-9] ; EOF_ : '<<EOF' .*? 'EOF' ; NULL : 'nul' ; NUMBER : DIGIT+ ('.' DIGIT+)? ; BOOL : 'true' | 'false' ; DESCRIPTION : '<<DESCRIPTION' .*? 'DESCRIPTION' ; MULTILINESTRING : '<<-EOF' .*? 'EOF' ; STRING : '"' (~ [\r\n"] | '""')* '"' ; IDENTIFIER : [a-zA-Z] ([a-zA-Z0-9_-])* ; COMMENT : ('#' | '//') ~ [\r\n]* -> channel(HIDDEN) ; BLOCKCOMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; WS : [ \r\n\t]+ -> skip ;
Reformat IDENTIFIER
Reformat IDENTIFIER
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
6fbbf9ff55344cbc144c7be391da85dc6ffbf3ca
Owl.g4
Owl.g4
/* * Copyright 2016 Igor Demura * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar Owl; @header { // This file is a part of the Owl Programming Language. package owl.compiler; } // Parser Rules module : 'module' NAME ';' ( function | variable )* ; qualifiedName : NAME ('::' NAME)* ; variable : 'var' NAME '=' expression ';' ; function : NAME? '(' (argument (',' argument)*)? ')' (':' type)? block ; argument : NAME (':' type)? ; block : '{' statement* '}' ; // Expression exprPrime : NAME | BOOL | INT | STRING | '(' expression ')' ; exprApply : exprPrime | exprApply op = '.' NAME | exprApply op = '(' (expression (',' expression)*)? ')' | exprApply op = '[' expression ']' ; exprCoerce : exprApply (':' type)? ; exprUnary : (op = ('~' | '+' | '-'))? t = exprCoerce ; exprMulDiv : t = exprUnary | l = exprMulDiv op = '*' r = exprUnary | l = exprMulDiv op = '/' r = exprUnary | l = exprMulDiv op = '%' r = exprUnary | l = exprMulDiv op = '//' r = exprUnary ; exprAddSub : t = exprMulDiv | l = exprAddSub op = '+' r = exprMulDiv | l = exprAddSub op = '-' r = exprMulDiv ; exprShift : t = exprAddSub | l = exprShift op = '<<' r = exprAddSub | l = exprShift op = '>>' r = exprAddSub | l = exprShift op = '>>>' r = exprAddSub ; exprBitAnd : t = exprShift | l = exprBitAnd op = '&' r = exprShift ; exprBitXor : t = exprBitAnd | l = exprBitXor op = '^' r = exprBitAnd ; exprBitOr : t = exprBitXor | l = exprBitOr op = '|' r = exprBitXor ; exprCmp : t = exprBitOr | l = exprCmp op = '<' r = exprBitOr | l = exprCmp op = '<=' r = exprBitOr | l = exprCmp op = '>' r = exprBitOr | l = exprCmp op = '>=' r = exprBitOr ; exprEq : t = exprCmp | l = exprEq op = '==' r = exprCmp | l = exprEq op = '!=' r = exprCmp ; exprNot : t = exprEq | op = '!' l = exprNot ; exprAnd : t = exprNot | l = exprAnd op = '&&' r = exprNot ; // Compared to == has different priority exprXor : t = exprAnd | l = exprXor op = '^^' r = exprAnd ; exprOr : t = exprXor | l = exprOr op = '||' r = exprXor ; expression : t = exprOr ; // TODO: // - Comma assignment x, y = 10 + 12, 10 * 12; // - Lambda expression assignment : l = expression ( op = ('=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '>>>=' | '&=' | '^=' | '|=') r = expression )? ; stmtIf : 'if' expression block ( 'elif' expression block )* ( 'else' block )? ; stmtReturn : 'return' expression? ';' ; stmtFor : 'for' expression block ; // Another would be stmtForKey // TODO: // - While // - For // - Yield (add to return) statement : assignment ';' | stmtIf | stmtReturn | variable | stmtFor ; arrayTypeSuffix : '[' ']' ; typeSimple : '(' type ')' | qualifiedName ('(' type (',' type)* ')')? arrayTypeSuffix* ; type : typeSimple ('=>' typeSimple)* ; BOOL: 'true' | 'false'; NAME: [a-zA-Z] [a-zA-Z0-9_]*; INT: '0o' [0-7]+ | [0-9]+ | '0x' [0-9a-fA-F]+; STRING: '"' ~[\t\r\n\f"]* '"'; COMMENT: '#' ~[\n]* -> channel(HIDDEN); WS: [ \t\r\n\f]+ -> skip;
/* * Copyright 2016 Igor Demura * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar Owl; @header { // This file is a part of the Owl Programming Language. package owl.compiler; } // Parser Rules module : 'module' NAME ';' ( function | variable )* ; qualifiedName : NAME ('::' NAME)* ; variable : 'var' NAME '=' expression ';' ; function : NAME? '(' (argument (',' argument)*)? ')' (':' type)? block ; argument : NAME (':' type)? ; block : '{' statement* '}' ; // Expression exprPrime : NAME | BOOL | INT | STRING | '(' expression ')' ; exprApply : exprPrime | exprApply op = '.' NAME | exprApply op = '(' (expression (',' expression)*)? ')' | exprApply op = '[' expression ']' ; exprCoerce : exprApply (':' type)? ; exprUnary : (op = ('~' | '+' | '-'))? t = exprCoerce ; exprMulDiv : t = exprUnary | l = exprMulDiv op = '*' r = exprUnary | l = exprMulDiv op = '/' r = exprUnary | l = exprMulDiv op = '%' r = exprUnary | l = exprMulDiv op = '//' r = exprUnary ; exprAddSub : t = exprMulDiv | l = exprAddSub op = '+' r = exprMulDiv | l = exprAddSub op = '-' r = exprMulDiv ; exprShift : t = exprAddSub | l = exprShift op = '<<' r = exprAddSub | l = exprShift op = '>>' r = exprAddSub | l = exprShift op = '>>>' r = exprAddSub ; exprBitAnd : t = exprShift | l = exprBitAnd op = '&' r = exprShift ; exprBitXor : t = exprBitAnd | l = exprBitXor op = '^' r = exprBitAnd ; exprBitOr : t = exprBitXor | l = exprBitOr op = '|' r = exprBitXor ; exprCmp : t = exprBitOr | l = exprCmp op = '<' r = exprBitOr | l = exprCmp op = '<=' r = exprBitOr | l = exprCmp op = '>' r = exprBitOr | l = exprCmp op = '>=' r = exprBitOr ; exprEq : t = exprCmp | l = exprEq op = '==' r = exprCmp | l = exprEq op = '!=' r = exprCmp ; exprNot : t = exprEq | op = '!' l = exprNot ; exprAnd : t = exprNot | l = exprAnd op = '&&' r = exprNot ; // Compared to == has different priority exprXor : t = exprAnd | l = exprXor op = '^^' r = exprAnd ; exprOr : t = exprXor | l = exprOr op = '||' r = exprXor ; expression : t = exprOr ; // TODO: // - Comma assignment x, y = 10 + 12, 10 * 12; // - Lambda expression assignment : l = expression ( op = ('=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '>>>=' | '&=' | '^=' | '|=') r = expression )? ; stmtIf : 'if' expression block ( 'elif' expression block )* ( 'else' block )? ; stmtReturn : 'return' expression? ';' ; stmtFor : 'for' expression block ; // Another would be stmtForKey // TODO: // - Range for // - Yield (add to return) statement : assignment ';' | stmtIf | stmtReturn | variable | stmtFor ; arrayTypeSuffix : '[' ']' ; typeSimple : '(' type ')' | qualifiedName ('(' type (',' type)* ')')? arrayTypeSuffix* ; type : typeSimple ('=>' typeSimple)* ; BOOL: 'true' | 'false'; NAME: [a-zA-Z] [a-zA-Z0-9_]*; INT: '0o' [0-7]+ | [0-9]+ | '0x' [0-9a-fA-F]+; STRING: '"' ~[\t\r\n\f"]* '"'; COMMENT: '#' ~[\n]* -> channel(HIDDEN); WS: [ \t\r\n\f]+ -> skip;
Range for comment
Range for comment
ANTLR
apache-2.0
idemura/owl_lang,idemura/owl_lang,idemura/owl_lang,idemura/owl_lang
1736de4054b09c1d2b947ec1c48eee93d3e0ccfb
lua/Lua.g4
lua/Lua.g4
/* BSD License Copyright (c) 2013, Kazunori Sakamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the NAME of Rainer Schuster nor the NAMEs of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This grammar file derived from: Lua 5.2 Reference Manual http://www.lua.org/manual/5.2/manual.html Lua 5.1 grammar written by Nicolai Mainiero http://www.antlr3.org/grammar/1178608849736/Lua.g */ grammar Lua; chunk : block ; block : stat* retstat? ; stat : ';' | varlist '=' explist | functioncall | label | 'break' | 'goto' NAME | 'do' block 'end' | 'while' exp 'do' block 'end' | 'repeat' block 'until' exp | 'if' exp 'then' block ('elseif' exp 'then' block)* ('else' block)? 'end' | 'for' NAME '=' exp ',' exp (',' exp)? 'do' block 'end' | 'for' namelist 'in' explist 'do' block 'end' | 'function' funcname funcbody | 'local' 'function' NAME funcbody | 'local' namelist ('=' explist)? ; retstat : 'return' explist? ';'? ; label : '::' NAME '::' ; funcname : NAME ('.' NAME)* (':' NAME)? ; varlist : var (',' var)* ; namelist : NAME (',' NAME)* ; explist : exp (',' exp)* ; exp : 'nil' | 'false' | 'true' | number | string | '...' | functiondef | prefixexp | tableconstructor | exp binop exp | unop exp ; var : (NAME | '(' exp ')' varSuffix) varSuffix* ; prefixexp : varOrExp nameAndArgs* ; functioncall : varOrExp nameAndArgs+ ; varOrExp : var | '(' exp ')' ; nameAndArgs : (':' NAME)? args ; varSuffix : nameAndArgs* ('[' exp ']' | '.' NAME) ; /* var : NAME | prefixexp '[' exp ']' | prefixexp '.' NAME ; prefixexp : var | functioncall | '(' exp ')' ; functioncall : prefixexp args | prefixexp ':' NAME args ; */ args : '(' explist? ')' | tableconstructor | string ; functiondef : 'function' funcbody ; funcbody : '(' parlist? ')' block 'end' ; parlist : namelist (',' '...')? | '...' ; tableconstructor : '{' fieldlist? '}' ; fieldlist : field (fieldsep field)* fieldsep? ; field : '[' exp ']' '=' exp | NAME '=' exp | exp ; fieldsep : ',' | ';' ; binop : '+' | '-' | '*' | '/' | '^' | '%' | '..' | '<' | '<=' | '>' | '>=' | '==' | '~=' | 'and' | 'or' ; unop : '-' | 'not' | '#' ; number : INT | HEX | FLOAT | HEX_FLOAT ; string : NORMALSTRING | CHARSTRING | LONGSTRING ; // LEXER NAME : [a-zA-Z_][a-zA-Z_0-9]* ; NORMALSTRING : '"' ( EscapeSequence | ~('\\'|'"') )* '"' ; CHARSTRING : '\'' ( EscapeSequence | ~('\''|'\\') )* '\'' ; LONGSTRING : '[' '='* '[' .*? ']' '='* ']' // TODO: the numbers of '=' should be same ; INT : Digit+ ; HEX : '0' [xX] HexDigit+ ; FLOAT : Digit+ '.' Digit* ExponentPart? | '.' Digit+ ExponentPart? | Digit+ ExponentPart ; HEX_FLOAT : '0' [xX] HexDigit+ '.' HexDigit* HexExponentPart? | '0' [xX] '.' HexDigit+ HexExponentPart? | '0' [xX] HexDigit+ HexExponentPart ; fragment ExponentPart : [eE] [+-]? Digit+ ; fragment HexExponentPart : [pP] [+-]? Digit+ ; fragment EscapeSequence : '\\' [abfnrtvz"'\\] | DecimalEscape | HexEscape ; fragment DecimalEscape : '\\' Digit | '\\' Digit Digit | '\\' [0-2] Digit Digit ; fragment HexEscape : '\\' 'x' HexDigit HexDigit ; fragment Digit : [0-9] ; fragment HexDigit : [0-9a-fA-F] ; COMMENT : '--[[' .*? ']]'-> channel(HIDDEN) ; LINE_COMMENT : '--' ~('\n'|'\r')* '\r'? '\n'-> channel(HIDDEN) ; WS : [ \t\u000C]+ -> skip ; NEWLINE : '\r'? '\n' -> skip ;
/* BSD License Copyright (c) 2013, Kazunori Sakamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the NAME of Rainer Schuster nor the NAMEs of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This grammar file derived from: Lua 5.2 Reference Manual http://www.lua.org/manual/5.2/manual.html Lua 5.1 grammar written by Nicolai Mainiero http://www.antlr3.org/grammar/1178608849736/Lua.g I tested my grammar with Test suite for Lua 5.2 (http://www.lua.org/tests/5.2/) */ grammar Lua; chunk : block EOF ; block : stat* retstat? ; stat : ';' | varlist '=' explist | functioncall | label | 'break' | 'goto' NAME | 'do' block 'end' | 'while' exp 'do' block 'end' | 'repeat' block 'until' exp | 'if' exp 'then' block ('elseif' exp 'then' block)* ('else' block)? 'end' | 'for' NAME '=' exp ',' exp (',' exp)? 'do' block 'end' | 'for' namelist 'in' explist 'do' block 'end' | 'function' funcname funcbody | 'local' 'function' NAME funcbody | 'local' namelist ('=' explist)? ; retstat : 'return' explist? ';'? ; label : '::' NAME '::' ; funcname : NAME ('.' NAME)* (':' NAME)? ; varlist : var (',' var)* ; namelist : NAME (',' NAME)* ; explist : exp (',' exp)* ; exp : 'nil' | 'false' | 'true' | number | string | '...' | functiondef | prefixexp | tableconstructor | exp binop exp | unop exp ; var : (NAME | '(' exp ')' varSuffix) varSuffix* ; prefixexp : varOrExp nameAndArgs* ; functioncall : varOrExp nameAndArgs+ ; varOrExp : var | '(' exp ')' ; nameAndArgs : (':' NAME)? args ; varSuffix : nameAndArgs* ('[' exp ']' | '.' NAME) ; /* var : NAME | prefixexp '[' exp ']' | prefixexp '.' NAME ; prefixexp : var | functioncall | '(' exp ')' ; functioncall : prefixexp args | prefixexp ':' NAME args ; */ args : '(' explist? ')' | tableconstructor | string ; functiondef : 'function' funcbody ; funcbody : '(' parlist? ')' block 'end' ; parlist : namelist (',' '...')? | '...' ; tableconstructor : '{' fieldlist? '}' ; fieldlist : field (fieldsep field)* fieldsep? ; field : '[' exp ']' '=' exp | NAME '=' exp | exp ; fieldsep : ',' | ';' ; binop : '+' | '-' | '*' | '/' | '^' | '%' | '..' | '<' | '<=' | '>' | '>=' | '==' | '~=' | 'and' | 'or' ; unop : '-' | 'not' | '#' ; number : INT | HEX | FLOAT | HEX_FLOAT ; string : NORMALSTRING | CHARSTRING | LONGSTRING ; // LEXER NAME : [a-zA-Z_][a-zA-Z_0-9]* ; NORMALSTRING : '"' ( EscapeSequence | ~('\\'|'"') )* '"' ; CHARSTRING : '\'' ( EscapeSequence | ~('\''|'\\') )* '\'' ; LONGSTRING : '[' NESTED_STR ']' ; fragment NESTED_STR : '=' NESTED_STR '=' | '[' .*? ']' ; INT : Digit+ ; HEX : '0' [xX] HexDigit+ ; FLOAT : Digit+ '.' Digit* ExponentPart? | '.' Digit+ ExponentPart? | Digit+ ExponentPart ; HEX_FLOAT : '0' [xX] HexDigit+ '.' HexDigit* HexExponentPart? | '0' [xX] '.' HexDigit+ HexExponentPart? | '0' [xX] HexDigit+ HexExponentPart ; fragment ExponentPart : [eE] [+-]? Digit+ ; fragment HexExponentPart : [pP] [+-]? Digit+ ; fragment EscapeSequence : '\\' [abfnrtvz"'\\] | DecimalEscape | HexEscape ; fragment DecimalEscape : '\\' Digit | '\\' Digit Digit | '\\' [0-2] Digit Digit ; fragment HexEscape : '\\' 'x' HexDigit HexDigit ; fragment Digit : [0-9] ; fragment HexDigit : [0-9a-fA-F] ; COMMENT : '--[[' .*? ']]'-> channel(HIDDEN) ; LINE_COMMENT : '--' '['? (~('['|'\n'|'\r') ~('\n'|'\r')*)? ('\n'|'\r')* -> channel(HIDDEN) ; WS : [ \t\u000C]+ -> skip ; NEWLINE : '\r'? '\n' -> skip ;
Fix parser rules for comments.
Fix parser rules for comments.
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
c165a3010f155afb5a0dcf8890d4b10800dffbd6
trans/src/wich/parser/Wich.g4
trans/src/wich/parser/Wich.g4
/* The MIT License (MIT) Copyright (c) 2015 Terence Parr, Hanzhou Shi, Shuai Yuan, Yuanyuan Zhang Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ grammar Wich; @header {package wich.parser; } file : script ; script : (statement | function)+ EOF ; function : 'func' ID '(' formal_args ')' (':' type)? '{' statement* '}' ; formal_args : formal_arg (',' formal_arg)* ; formal_arg : ID ':' type ; type: 'int' | 'float' | 'string' | '[' ']' ; statement : 'if' '(' expr ')' statement ('else' statement)? # If | 'while' '(' expr ')' statement # While | 'var' ID ('=' expr)? # VarDef | ID '=' expr # Assign | ID '[' expr ']' '=' expr # ElementAssign | call_expr # CallStatement | 'return' expr # Return | '{' statement+ '}' # Block ; expr: expr operator expr # Op | '-' expr # Negate | '!' expr # Not | call_expr # Call | ID '[' expr ']' # Index | '(' expr ')' # Parens | primary # Atom ; operator : '*'|'/'|'+'|'-'|'<'|'<='|'=='|'!='|'>'|'>='|'||'|'&&'|' . ' ; // no precedence call_expr : ID '(' expr_list ')' ; expr_list : expr (',' expr)* ; primary : ID | INT | FLOAT | STRING | '[' expr_list ']' ; LINE_COMMENT : '//' .*? ('\n'|EOF) -> channel(HIDDEN) ; COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; ID : [a-zA-Z_] [a-zA-Z0-9_]* ; INT : [0-9]+ ; FLOAT : '-'? INT '.' INT EXP? // 1.35, 1.35E-9, 0.3, -4.5 | '-'? INT EXP // 1e10 -3e4 ; fragment EXP : [Ee] [+\-]? INT ; STRING : '"' (ESC | ~["\\])* '"' ; fragment ESC : '\\' ["\bfnrt] ; WS : [ \t\n\r]+ -> channel(HIDDEN) ;
/* The MIT License (MIT) Copyright (c) 2015 Terence Parr, Hanzhou Shi, Shuai Yuan, Yuanyuan Zhang Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ grammar Wich; @header {package wich.parser; } file : script ; script : (statement | function)+ EOF ; function : 'func' ID '(' formal_args ')' (':' type)? '{' statement* '}' ; formal_args : formal_arg (',' formal_arg)* ; formal_arg : ID ':' type ; type: 'int' | 'float' | 'string' | '[' ']' ; statement : 'if' '(' expr ')' statement ('else' statement)? # If | 'while' '(' expr ')' statement # While | 'var' ID ('=' expr)? # VarDef | ID '=' expr # Assign | ID '[' expr ']' '=' expr # ElementAssign | call_expr # CallStatement | 'return' expr # Return | '{' statement* '}' # Block ; expr: expr operator expr # Op | '-' expr # Negate | '!' expr # Not | call_expr # Call | ID '[' expr ']' # Index | '(' expr ')' # Parens | primary # Atom ; operator : '*'|'/'|'+'|'-'|'<'|'<='|'=='|'!='|'>'|'>='|'||'|'&&'|' . ' ; // no precedence call_expr : ID '(' expr_list ')' ; expr_list : expr (',' expr)* ; primary : ID | INT | FLOAT | STRING | '[' expr_list ']' ; LINE_COMMENT : '//' .*? ('\n'|EOF) -> channel(HIDDEN) ; COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; ID : [a-zA-Z_] [a-zA-Z0-9_]* ; INT : [0-9]+ ; FLOAT : '-'? INT '.' INT EXP? // 1.35, 1.35E-9, 0.3, -4.5 | '-'? INT EXP // 1e10 -3e4 ; fragment EXP : [Ee] [+\-]? INT ; STRING : '"' (ESC | ~["\\])* '"' ; fragment ESC : '\\' ["\bfnrt] ; WS : [ \t\n\r]+ -> channel(HIDDEN) ;
allow empty {...} code blocks per Shuai
allow empty {...} code blocks per Shuai
ANTLR
mit
hanjoes/wich-c,YuanyuanZh/wich-c,YuanyuanZh/wich-c,syuanivy/wich-c,syuanivy/wich-c,hanjoes/wich-c,langwich/wich-c,langwich/wich-c
9cc366311dbdeaf0d5e22648352c9ceed7e315e4
src/grammar/RustLexer.g4
src/grammar/RustLexer.g4
lexer grammar RustLexer; tokens { EQ, LT, LE, EQEQ, NE, GE, GT, ANDAND, OROR, NOT, TILDE, PLUT, MINUS, STAR, SLASH, PERCENT, CARET, AND, OR, SHL, SHR, BINOP, BINOPEQ, AT, DOT, DOTDOT, DOTDOTDOT, COMMA, SEMI, COLON, MOD_SEP, RARROW, FAT_ARROW, LPAREN, RPAREN, LBRACKET, RBRACKET, LBRACE, RBRACE, POUND, DOLLAR, UNDERSCORE, LIT_CHAR, LIT_INTEGER, LIT_FLOAT, LIT_STR, LIT_STR_RAW, LIT_BINARY, LIT_BINARY_RAW, IDENT, LIFETIME, WHITESPACE, DOC_COMMENT, COMMENT } /* Note: due to antlr limitations, we can't represent XID_start and * XID_continue properly. ASCII-only substitute. */ fragment XID_start : [_a-zA-Z] ; fragment XID_continue : [_a-zA-Z0-9] ; /* Expression-operator symbols */ EQ : '=' ; LT : '<' ; LE : '<=' ; EQEQ : '==' ; NE : '!=' ; GE : '>=' ; GT : '>' ; ANDAND : '&&' ; OROR : '||' ; NOT : '!' ; TILDE : '~' ; PLUS : '+' ; MINUS : '-' ; STAR : '*' ; SLASH : '/' ; PERCENT : '%' ; CARET : '^' ; AND : '&' ; OR : '|' ; SHL : '<<' ; SHR : '>>' ; BINOP : PLUS | SLASH | MINUS | STAR | PERCENT | CARET | AND | OR | SHL | SHR ; BINOPEQ : BINOP EQ ; /* "Structural symbols" */ AT : '@' ; DOT : '.' ; DOTDOT : '..' ; DOTDOTDOT : '...' ; COMMA : ',' ; SEMI : ';' ; COLON : ':' ; MOD_SEP : '::' ; RARROW : '->' ; FAT_ARROW : '=>' ; LPAREN : '(' ; RPAREN : ')' ; LBRACKET : '[' ; RBRACKET : ']' ; LBRACE : '{' ; RBRACE : '}' ; POUND : '#'; DOLLAR : '$' ; UNDERSCORE : '_' ; // Literals fragment HEXIT : [0-9a-fA-F] ; fragment CHAR_ESCAPE : [nrt\\'"0] | [xX] HEXIT HEXIT | 'u' HEXIT HEXIT HEXIT HEXIT | 'U' HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT ; LIT_CHAR : '\'' ( '\\' CHAR_ESCAPE | ~[\\'\n\t\r] ) '\'' ; LIT_BYTE : 'b\'' ( '\\' ( [xX] HEXIT HEXIT | [nrt\\'"0] ) | ~[\\'\n\t\r] ) '\'' ; fragment INT_SUFFIX : 'i' | 'i8' | 'i16' | 'i32' | 'i64' | 'u' | 'u8' | 'u16' | 'u32' | 'u64' ; LIT_INTEGER : [0-9][0-9_]* INT_SUFFIX? | '0b' [01][01_]* INT_SUFFIX? | '0o' [0-7][0-7_]* INT_SUFFIX? | '0x' [0-9a-fA-F][0-9a-fA-F_]* INT_SUFFIX? ; FLOAT_SUFFIX : 'f32' | 'f64' | 'f128' ; LIT_FLOAT : [0-9][0-9_]* ('.' | ('.' [0-9][0-9_]*)? ([eE] [-+]? [0-9][0-9_]*)? FLOAT_SUFFIX?) ; LIT_STR : '"' ('\\\n' | '\\\r\n' | '\\' CHAR_ESCAPE | .)*? '"' ; LIT_BINARY : 'b' LIT_STR ; LIT_BINARY_RAW : 'rb' LIT_STR_RAW ; /* this is a bit messy */ fragment LIT_STR_RAW_INNER : '"' .*? '"' | LIT_STR_RAW_INNER2 ; fragment LIT_STR_RAW_INNER2 : POUND LIT_STR_RAW_INNER POUND ; LIT_STR_RAW : 'r' LIT_STR_RAW_INNER ; IDENT : XID_start XID_continue* ; LIFETIME : '\'' IDENT ; WHITESPACE : [ \r\n\t]+ ; UNDOC_COMMENT : '////' ~[\r\n]* -> type(COMMENT) ; YESDOC_COMMENT : '///' ~[\r\n]* -> type(DOC_COMMENT) ; OUTER_DOC_COMMENT : '//!' ~[\r\n]* -> type(DOC_COMMENT) ; LINE_COMMENT : '//' ~[\r\n]* -> type(COMMENT) ; DOC_BLOCK_COMMENT : ('/**' ~[*] | '/*!') (DOC_BLOCK_COMMENT | .)*? '*/' -> type(DOC_COMMENT) ; BLOCK_COMMENT : '/*' (BLOCK_COMMENT | .)*? '*/' -> type(COMMENT) ;
lexer grammar RustLexer; tokens { EQ, LT, LE, EQEQ, NE, GE, GT, ANDAND, OROR, NOT, TILDE, PLUT, MINUS, STAR, SLASH, PERCENT, CARET, AND, OR, SHL, SHR, BINOP, BINOPEQ, AT, DOT, DOTDOT, DOTDOTDOT, COMMA, SEMI, COLON, MOD_SEP, RARROW, FAT_ARROW, LPAREN, RPAREN, LBRACKET, RBRACKET, LBRACE, RBRACE, POUND, DOLLAR, UNDERSCORE, LIT_CHAR, LIT_INTEGER, LIT_FLOAT, LIT_STR, LIT_STR_RAW, LIT_BINARY, LIT_BINARY_RAW, IDENT, LIFETIME, WHITESPACE, DOC_COMMENT, COMMENT } /* Note: due to antlr limitations, we can't represent XID_start and * XID_continue properly. ASCII-only substitute. */ fragment XID_start : [_a-zA-Z] ; fragment XID_continue : [_a-zA-Z0-9] ; /* Expression-operator symbols */ EQ : '=' ; LT : '<' ; LE : '<=' ; EQEQ : '==' ; NE : '!=' ; GE : '>=' ; GT : '>' ; ANDAND : '&&' ; OROR : '||' ; NOT : '!' ; TILDE : '~' ; PLUS : '+' ; MINUS : '-' ; STAR : '*' ; SLASH : '/' ; PERCENT : '%' ; CARET : '^' ; AND : '&' ; OR : '|' ; SHL : '<<' ; SHR : '>>' ; BINOP : PLUS | SLASH | MINUS | STAR | PERCENT | CARET | AND | OR | SHL | SHR ; BINOPEQ : BINOP EQ ; /* "Structural symbols" */ AT : '@' ; DOT : '.' ; DOTDOT : '..' ; DOTDOTDOT : '...' ; COMMA : ',' ; SEMI : ';' ; COLON : ':' ; MOD_SEP : '::' ; RARROW : '->' ; FAT_ARROW : '=>' ; LPAREN : '(' ; RPAREN : ')' ; LBRACKET : '[' ; RBRACKET : ']' ; LBRACE : '{' ; RBRACE : '}' ; POUND : '#'; DOLLAR : '$' ; UNDERSCORE : '_' ; // Literals fragment HEXIT : [0-9a-fA-F] ; fragment CHAR_ESCAPE : [nrt\\'"0] | [xX] HEXIT HEXIT | 'u' HEXIT HEXIT HEXIT HEXIT | 'U' HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT ; LIT_CHAR : '\'' ( '\\' CHAR_ESCAPE | ~[\\'\n\t\r] ) '\'' ; LIT_BYTE : 'b\'' ( '\\' ( [xX] HEXIT HEXIT | [nrt\\'"0] ) | ~[\\'\n\t\r] ) '\'' ; fragment INT_SUFFIX : 'i' | 'i8' | 'i16' | 'i32' | 'i64' | 'u' | 'u8' | 'u16' | 'u32' | 'u64' ; LIT_INTEGER : [0-9][0-9_]* INT_SUFFIX? | '0b' [01][01_]* INT_SUFFIX? | '0o' [0-7][0-7_]* INT_SUFFIX? | '0x' [0-9a-fA-F][0-9a-fA-F_]* INT_SUFFIX? ; fragment FLOAT_SUFFIX : 'f32' | 'f64' ; LIT_FLOAT : [0-9][0-9_]* ('.' | ('.' [0-9][0-9_]*)? ([eE] [-+]? [0-9][0-9_]*)? FLOAT_SUFFIX?) ; LIT_STR : '"' ('\\\n' | '\\\r\n' | '\\' CHAR_ESCAPE | .)*? '"' ; LIT_BINARY : 'b' LIT_STR ; LIT_BINARY_RAW : 'rb' LIT_STR_RAW ; /* this is a bit messy */ fragment LIT_STR_RAW_INNER : '"' .*? '"' | LIT_STR_RAW_INNER2 ; fragment LIT_STR_RAW_INNER2 : POUND LIT_STR_RAW_INNER POUND ; LIT_STR_RAW : 'r' LIT_STR_RAW_INNER ; IDENT : XID_start XID_continue* ; LIFETIME : '\'' IDENT ; WHITESPACE : [ \r\n\t]+ ; UNDOC_COMMENT : '////' ~[\r\n]* -> type(COMMENT) ; YESDOC_COMMENT : '///' ~[\r\n]* -> type(DOC_COMMENT) ; OUTER_DOC_COMMENT : '//!' ~[\r\n]* -> type(DOC_COMMENT) ; LINE_COMMENT : '//' ~[\r\n]* -> type(COMMENT) ; DOC_BLOCK_COMMENT : ('/**' ~[*] | '/*!') (DOC_BLOCK_COMMENT | .)*? '*/' -> type(DOC_COMMENT) ; BLOCK_COMMENT : '/*' (BLOCK_COMMENT | .)*? '*/' -> type(COMMENT) ;
Update ANTLR float suffix grammar
Update ANTLR float suffix grammar - Removes f128 from the grammar, which is no longer support in rustc - The fragment modifier is added so it won't parse float suffix as a separate token
ANTLR
apache-2.0
vhbit/rust,emk/rust,0x73/rust,hauleth/rust,rohitjoshi/rust,rohitjoshi/rust,KokaKiwi/rust,carols10cents/rust,ejjeong/rust,untitaker/rust,omasanori/rust,aepsil0n/rust,nwin/rust,rohitjoshi/rust,0x73/rust,defuz/rust,vhbit/rust,pshc/rust,philyoon/rust,ebfull/rust,kwantam/rust,untitaker/rust,jroesch/rust,ejjeong/rust,avdi/rust,nwin/rust,quornian/rust,bombless/rust-docs-chinese,emk/rust,sae-bom/rust,XMPPwocky/rust,philyoon/rust,graydon/rust,robertg/rust,jashank/rust,l0kod/rust,miniupnp/rust,zaeleus/rust,aidancully/rust,reem/rust,jroesch/rust,KokaKiwi/rust,victorvde/rust,pelmers/rust,hauleth/rust,nwin/rust,quornian/rust,aneeshusa/rust,rohitjoshi/rust,XMPPwocky/rust,omasanori/rust,pshc/rust,pelmers/rust,avdi/rust,cllns/rust,sae-bom/rust,richo/rust,victorvde/rust,carols10cents/rust,ruud-v-a/rust,AerialX/rust,vhbit/rust,AerialX/rust,ktossell/rust,robertg/rust,graydon/rust,robertg/rust,0x73/rust,richo/rust,dinfuehr/rust,vhbit/rust,mihneadb/rust,defuz/rust,andars/rust,barosl/rust,victorvde/rust,mahkoh/rust,gifnksm/rust,philyoon/rust,aneeshusa/rust,kimroen/rust,mdinger/rust,XMPPwocky/rust,jashank/rust,cllns/rust,vhbit/rust,dinfuehr/rust,cllns/rust,mahkoh/rust,0x73/rust,untitaker/rust,TheNeikos/rust,pshc/rust,defuz/rust,pshc/rust,kwantam/rust,rprichard/rust,vhbit/rust,KokaKiwi/rust,aidancully/rust,defuz/rust,rprichard/rust,dwillmer/rust,dwillmer/rust,avdi/rust,jroesch/rust,jashank/rust,ktossell/rust,seanrivera/rust,TheNeikos/rust,0x73/rust,mdinger/rust,ktossell/rust,victorvde/rust,defuz/rust,l0kod/rust,aepsil0n/rust,hauleth/rust,zaeleus/rust,mvdnes/rust,omasanori/rust,kwantam/rust,gifnksm/rust,TheNeikos/rust,bombless/rust,aidancully/rust,hauleth/rust,krzysz00/rust,seanrivera/rust,bombless/rust,dinfuehr/rust,untitaker/rust,GBGamer/rust,quornian/rust,aneeshusa/rust,zachwick/rust,AerialX/rust-rt-minimal,kimroen/rust,hauleth/rust,rprichard/rust,quornian/rust,jashank/rust,dinfuehr/rust,ktossell/rust,nwin/rust,GBGamer/rust,ejjeong/rust,reem/rust,aidancully/rust,mvdnes/rust,ejjeong/rust,aepsil0n/rust,andars/rust,ejjeong/rust,dinfuehr/rust,AerialX/rust,avdi/rust,zubron/rust,mdinger/rust,gifnksm/rust,graydon/rust,barosl/rust,AerialX/rust,omasanori/rust,ejjeong/rust,mihneadb/rust,rohitjoshi/rust,rprichard/rust,omasanori/rust,zachwick/rust,ebfull/rust,seanrivera/rust,AerialX/rust-rt-minimal,ebfull/rust,rohitjoshi/rust,andars/rust,krzysz00/rust,kimroen/rust,GBGamer/rust,krzysz00/rust,miniupnp/rust,l0kod/rust,pelmers/rust,aneeshusa/rust,barosl/rust,XMPPwocky/rust,emk/rust,gifnksm/rust,mahkoh/rust,miniupnp/rust,graydon/rust,aneeshusa/rust,philyoon/rust,0x73/rust,jroesch/rust,mvdnes/rust,zachwick/rust,l0kod/rust,mihneadb/rust,quornian/rust,kwantam/rust,rprichard/rust,robertg/rust,seanrivera/rust,cllns/rust,zubron/rust,ktossell/rust,ruud-v-a/rust,omasanori/rust,zubron/rust,kwantam/rust,hauleth/rust,ktossell/rust,richo/rust,kimroen/rust,l0kod/rust,reem/rust,l0kod/rust,zachwick/rust,pelmers/rust,TheNeikos/rust,miniupnp/rust,GBGamer/rust,zubron/rust,sae-bom/rust,barosl/rust,philyoon/rust,mihneadb/rust,kwantam/rust,l0kod/rust,dwillmer/rust,zaeleus/rust,KokaKiwi/rust,mdinger/rust,zubron/rust,miniupnp/rust,sae-bom/rust,AerialX/rust-rt-minimal,bombless/rust,nwin/rust,dinfuehr/rust,nwin/rust,dwillmer/rust,jashank/rust,mahkoh/rust,aidancully/rust,krzysz00/rust,aneeshusa/rust,nwin/rust,TheNeikos/rust,jashank/rust,mahkoh/rust,robertg/rust,kimroen/rust,richo/rust,zubron/rust,cllns/rust,emk/rust,graydon/rust,ebfull/rust,bombless/rust,jroesch/rust,rprichard/rust,pshc/rust,carols10cents/rust,carols10cents/rust,seanrivera/rust,miniupnp/rust,mahkoh/rust,richo/rust,bombless/rust,pshc/rust,ruud-v-a/rust,mvdnes/rust,zubron/rust,GBGamer/rust,ruud-v-a/rust,dwillmer/rust,aidancully/rust,robertg/rust,GBGamer/rust,cllns/rust,reem/rust,mdinger/rust,jroesch/rust,bombless/rust,AerialX/rust-rt-minimal,barosl/rust,mvdnes/rust,ktossell/rust,emk/rust,seanrivera/rust,untitaker/rust,barosl/rust,jroesch/rust,KokaKiwi/rust,GBGamer/rust,0x73/rust,miniupnp/rust,victorvde/rust,andars/rust,nwin/rust,quornian/rust,XMPPwocky/rust,zaeleus/rust,quornian/rust,zaeleus/rust,richo/rust,avdi/rust,avdi/rust,sae-bom/rust,emk/rust,graydon/rust,jashank/rust,miniupnp/rust,gifnksm/rust,l0kod/rust,zachwick/rust,zachwick/rust,philyoon/rust,aepsil0n/rust,andars/rust,AerialX/rust,zubron/rust,krzysz00/rust,reem/rust,mihneadb/rust,untitaker/rust,GBGamer/rust,ruud-v-a/rust,ebfull/rust,pelmers/rust,defuz/rust,mihneadb/rust,jashank/rust,TheNeikos/rust,mvdnes/rust,reem/rust,KokaKiwi/rust,mdinger/rust,andars/rust,ebfull/rust,pshc/rust,pshc/rust,ruud-v-a/rust,AerialX/rust-rt-minimal,vhbit/rust,krzysz00/rust,sae-bom/rust,carols10cents/rust,carols10cents/rust,aepsil0n/rust,dwillmer/rust,kimroen/rust,barosl/rust,aepsil0n/rust,AerialX/rust,emk/rust,jroesch/rust,gifnksm/rust,pelmers/rust,kimroen/rust,victorvde/rust,vhbit/rust,AerialX/rust-rt-minimal,dwillmer/rust,dwillmer/rust,zaeleus/rust,XMPPwocky/rust
cff71fbcbd3d9523c4e09d40adc1558646fcd063
src/main/antlr/BMoThParser.g4
src/main/antlr/BMoThParser.g4
parser grammar BMoThParser; options { tokenVocab=BMoThLexer; } @header { package de.bmoth.antlr; } start : parse_unit EOF # ParseUnit ; parse_unit : MACHINE IDENTIFIER (clauses+=machine_clause)* END # MachineParseUnit ; machine_clause : clauseName=(PROPERTIES|INVARIANT) pred=predicate # PredicateClause | clauseName=(CONSTANTS|VARIABLES) identifier_list # DeclarationClause | INITIALISATION substitution # InitialisationClause | OPERATIONS ops+=single_operation (SEMICOLON ops+=single_operation)* # OperationsClause | SETS set_definition (';' set_definition)* # SetsClause | definition_clause # DefinitionClauseIndirection // used to reuse definition_clause for definition files ; set_definition : IDENTIFIER # DeferredSet | IDENTIFIER EQUAL LEFT_BRACE identifier_list RIGHT_BRACE # EnumeratedSet ; definition_clause : DEFINITIONS defs+=single_definition (SEMICOLON defs+=single_definition)* SEMICOLON? # DefinitionClause ; single_definition : name=IDENTIFIER (LEFT_PAR identifier_list RIGHT_PAR)? DOUBLE_EQUAL definition_body # OrdinaryDefinition | StringLiteral # DefinitionFile ; definition_body : IDENTIFIER (LEFT_PAR expression_list RIGHT_PAR)? # DefinitionAmbiguousCall | expression # DefinitionExpression | predicate # DefinitionPredicate | substitution # DefinitionSubstitution ; single_operation : IDENTIFIER EQUAL substitution # Operation ; quantified_variables_list : identifier_list | LEFT_PAR identifier_list RIGHT_PAR ; identifier_list : identifiers+=IDENTIFIER (',' identifiers+=IDENTIFIER)* ; substitution : BEGIN substitution END # BlockSubstitution | SKIP_SUB # SkipSubstitution | SELECT preds+=predicate THEN subs+=substitution (WHEN preds+=predicate THEN subs+=substitution)* (ELSE elseSub=substitution)? END # SelectSubstitution | CASE expr=expression OF EITHER either=expression_list THEN sub=substitution (SUBSTITUTION_OR or_exprs+=expression_list THEN or_subs+=substitution)+ (ELSE else_sub=substitution)? END END # CaseSubstitution | keyword=(PRE|ASSERT) predicate THEN substitution END # ConditionSubstitution | ANY identifier_list WHERE predicate THEN substitution END # AnySubstitution | identifier_list ':=' expression_list # AssignSubstitution | substitution DOUBLE_VERTICAL_BAR substitution # ParallelSubstitution | identifier_list DOUBLE_COLON expression # BecomesElementOfSubstitution | identifier_list (ELEMENT_OF|COLON) LEFT_PAR predicate RIGHT_PAR # BecomesSuchThatSubstitution | IF preds+=predicate THEN subs+=substitution (ELSIF preds+=predicate THEN subs+=substitution)* (ELSE elseSub=substitution)? END # IfSubstitution | WHILE condition=predicate DO substitution INVARIANT invariant=predicate VARIANT variant=expression END # WhileSubstitution ; expression_list : exprs+=expression (',' exprs+=expression)* ; formula : predicate EOF | expression EOF ; predicate : LEFT_PAR predicate RIGHT_PAR # ParenthesesPredicate | IDENTIFIER # PredicateIdentifier | IDENTIFIER LEFT_PAR exprs+=expression (',' exprs+=expression)* RIGHT_PAR # PredicateDefinitionCall | operator=(FOR_ANY|EXITS) quantified_variables_list DOT LEFT_PAR predicate RIGHT_PAR # QuantifiedPredicate | operator=(TRUE|FALSE) # PredicateOperator | operator=NOT LEFT_PAR predicate RIGHT_PAR # PredicateOperator | expression operator=(EQUAL|NOT_EQUAL|COLON|ELEMENT_OF|NOT_BELONGING |INCLUSION|STRICT_INCLUSION|NON_INCLUSION|STRICT_NON_INCLUSION |LESS_EQUAL|LESS|GREATER_EQUAL|GREATER) expression # PredicateOperatorWithExprArgs | predicate operator=EQUIVALENCE predicate # PredicateOperator //p60 | predicate operator=(AND|OR) predicate # PredicateOperator //p40 | predicate operator=IMPLIES predicate # PredicateOperator //p30 ; expression : Number # NumberExpression | LEFT_PAR expression RIGHT_PAR # ParenthesesExpression | BOOL_CAST LEFT_PAR predicate RIGHT_PAR # CastPredicateExpression | IDENTIFIER # IdentifierExpression | LEFT_BRACE RIGHT_BRACE # EmptySetExpression | LEFT_BRACE expression_list RIGHT_BRACE # SetEnumerationExpression | LEFT_BRACE identifier_list '|' predicate RIGHT_BRACE # SetComprehensionExpression | LEFT_PAR exprs+=expression COMMA exprs+=expression (COMMA exprs+=expression)* RIGHT_PAR # NestedCoupleAsTupleExpression | '[' expression_list? ']' # SequenceEnumerationExpression | operator=(NATURAL|NATURAL1|INTEGER|INT|NAT |MININT|MAXINT|BOOL|TRUE|FALSE) # ExpressionOperator | exprs+=expression LEFT_PAR exprs+=expression (',' exprs+=expression)* RIGHT_PAR # FunctionCallExpression | operator=(DOM|RAN|CARD|CONC|FIRST|FRONT|ID|ISEQ|ISEQ1 |LAST|MAX|MIN|POW|REV|SEQ|SEQ1|TAIL |GENERALIZED_UNION|GENERALIZED_INTER) LEFT_PAR expression RIGHT_PAR # ExpressionOperator | operator=(QUANTIFIED_UNION|QUANTIFIED_INTER|SIGMA|PI) quantified_variables_list DOT LEFT_PAR predicate VERTICAL_BAR expression RIGHT_PAR # QuantifiedExpression // operators with precedences | expression operator=TILDE # ExpressionOperator //p230 | operator=MINUS expression # ExpressionOperator //P210 | <assoc=right> expression operator=POWER_OF expression # ExpressionOperator //p200 | expression operator=(MULT|DIVIDE|MOD) expression # ExpressionOperator //p190 | expression operator=(PLUS|MINUS|SET_SUBTRACTION) expression # ExpressionOperator //p180 | expression operator=INTERVAL expression # ExpressionOperator //p170 | expression operator=(OVERWRITE_RELATION|DIRECT_PRODUCT|CONCAT |DOMAIN_RESTRICTION|DOMAIN_SUBTRACTION|RANGE_RESTRICTION |RANGE_SUBTRACTION|INSERT_FRONT|INSERT_TAIL|UNION|INTERSECTION |RESTRICT_FRONT|RESTRICT_TAIL|MAPLET) expression # ExpressionOperator //p160 ; ltlStart : ltlFormula EOF ; ltlFormula : LTL_LEFT_PAR ltlFormula LTL_RIGHT_PAR # LTLParentheses | keyword=(LTL_TRUE|LTL_FALSE) # LTLKeyword | operator=(LTL_GLOBALLY|LTL_FINALLY|LTL_NEXT|LTL_NOT) ltlFormula # LTLPrefixOperator | LTL_B_START predicate B_END # LTLBPredicate | ltlFormula operator=LTL_IMPLIES ltlFormula # LTLInfixOperator | ltlFormula operator=(LTL_UNTIL|LTL_RELEASE) ltlFormula # LTLInfixOperator | ltlFormula operator=(LTL_AND|LTL_OR) ltlFormula # LTLInfixOperator ;
parser grammar BMoThParser; options { tokenVocab=BMoThLexer; } @header { package de.bmoth.antlr; } start : parse_unit EOF # ParseUnit ; parse_unit : MACHINE IDENTIFIER (clauses+=machine_clause)* END # MachineParseUnit ; machine_clause : clauseName=(PROPERTIES|INVARIANT) pred=predicate # PredicateClause | clauseName=(CONSTANTS|VARIABLES) identifier_list # DeclarationClause | INITIALISATION substitution # InitialisationClause | OPERATIONS ops+=single_operation (SEMICOLON ops+=single_operation)* # OperationsClause | SETS set_definition (';' set_definition)* # SetsClause | definition_clause # DefinitionClauseIndirection // used to reuse definition_clause for definition files ; set_definition : IDENTIFIER # DeferredSet | IDENTIFIER EQUAL LEFT_BRACE identifier_list RIGHT_BRACE # EnumeratedSet ; definition_clause : DEFINITIONS defs+=single_definition (SEMICOLON defs+=single_definition)* SEMICOLON? # DefinitionClause ; single_definition : name=IDENTIFIER (LEFT_PAR identifier_list RIGHT_PAR)? DOUBLE_EQUAL definition_body # OrdinaryDefinition | StringLiteral # DefinitionFile ; definition_body : IDENTIFIER (LEFT_PAR expression_list RIGHT_PAR)? # DefinitionAmbiguousCall | expression # DefinitionExpression | predicate # DefinitionPredicate | substitution # DefinitionSubstitution ; single_operation : IDENTIFIER EQUAL substitution # Operation ; quantified_variables_list : identifier_list | LEFT_PAR identifier_list RIGHT_PAR ; identifier_list : identifiers+=IDENTIFIER (',' identifiers+=IDENTIFIER)* ; substitution : BEGIN substitution END # BlockSubstitution | SKIP_SUB # SkipSubstitution | SELECT preds+=predicate THEN subs+=substitution (WHEN preds+=predicate THEN subs+=substitution)* (ELSE elseSub=substitution)? END # SelectSubstitution | CASE expr=expression OF EITHER either=expression_list THEN sub=substitution (SUBSTITUTION_OR or_exprs+=expression_list THEN or_subs+=substitution)+ (ELSE else_sub=substitution)? END END # CaseSubstitution | keyword=(PRE|ASSERT) predicate THEN substitution END # ConditionSubstitution | ANY identifier_list WHERE predicate THEN substitution END # AnySubstitution | identifier_list ':=' expression_list # AssignSubstitution | substitution DOUBLE_VERTICAL_BAR substitution # ParallelSubstitution | identifier_list DOUBLE_COLON expression # BecomesElementOfSubstitution | identifier_list (ELEMENT_OF|COLON) LEFT_PAR predicate RIGHT_PAR # BecomesSuchThatSubstitution | IF preds+=predicate THEN subs+=substitution (ELSIF preds+=predicate THEN subs+=substitution)* (ELSE elseSub=substitution)? END # IfSubstitution | WHILE condition=predicate DO substitution INVARIANT invariant=predicate VARIANT variant=expression END # WhileSubstitution ; expression_list : exprs+=expression (',' exprs+=expression)* ; formula : predicate EOF | expression EOF ; predicate : LEFT_PAR predicate RIGHT_PAR # ParenthesesPredicate | IDENTIFIER # PredicateIdentifier | IDENTIFIER LEFT_PAR exprs+=expression (',' exprs+=expression)* RIGHT_PAR # PredicateDefinitionCall | operator=(FOR_ANY|EXITS) quantified_variables_list DOT LEFT_PAR predicate RIGHT_PAR # QuantifiedPredicate | operator=(TRUE|FALSE) # PredicateOperator | operator=NOT LEFT_PAR predicate RIGHT_PAR # PredicateOperator | expression operator=(EQUAL|NOT_EQUAL|COLON|ELEMENT_OF|NOT_BELONGING |INCLUSION|STRICT_INCLUSION|NON_INCLUSION|STRICT_NON_INCLUSION |LESS_EQUAL|LESS|GREATER_EQUAL|GREATER) expression # PredicateOperatorWithExprArgs | predicate operator=EQUIVALENCE predicate # PredicateOperator //p60 | predicate operator=(AND|OR) predicate # PredicateOperator //p40 | predicate operator=IMPLIES predicate # PredicateOperator //p30 ; expression : Number # NumberExpression | LEFT_PAR expression RIGHT_PAR # ParenthesesExpression | BOOL_CAST LEFT_PAR predicate RIGHT_PAR # CastPredicateExpression | IDENTIFIER # IdentifierExpression | LEFT_BRACE RIGHT_BRACE # EmptySetExpression | LEFT_BRACE expression_list RIGHT_BRACE # SetEnumerationExpression | LEFT_BRACE identifier_list '|' predicate RIGHT_BRACE # SetComprehensionExpression | LEFT_PAR exprs+=expression COMMA exprs+=expression (COMMA exprs+=expression)* RIGHT_PAR # NestedCoupleAsTupleExpression | '[' expression_list? ']' # SequenceEnumerationExpression | operator=(NATURAL|NATURAL1|INTEGER|INT|NAT |MININT|MAXINT|BOOL|TRUE|FALSE) # ExpressionOperator | exprs+=expression LEFT_PAR exprs+=expression (',' exprs+=expression)* RIGHT_PAR # FunctionCallExpression | operator=(DOM|RAN|CARD|CONC|FIRST|FRONT|ID|ISEQ|ISEQ1 |LAST|MAX|MIN|POW|REV|SEQ|SEQ1|TAIL |GENERALIZED_UNION|GENERALIZED_INTER) LEFT_PAR expression RIGHT_PAR # ExpressionOperator | operator=(QUANTIFIED_UNION|QUANTIFIED_INTER|SIGMA|PI) quantified_variables_list DOT LEFT_PAR predicate VERTICAL_BAR expression RIGHT_PAR # QuantifiedExpression // operators with precedences | expression operator=TILDE # ExpressionOperator //p230 | operator=MINUS expression # ExpressionOperator //P210 | <assoc=right> expression operator=POWER_OF expression # ExpressionOperator //p200 | expression operator=(MULT|DIVIDE|MOD) expression # ExpressionOperator //p190 | expression operator=(PLUS|MINUS|SET_SUBTRACTION) expression # ExpressionOperator //p180 | expression operator=INTERVAL expression # ExpressionOperator //p170 | expression operator=(OVERWRITE_RELATION|DIRECT_PRODUCT|CONCAT |DOMAIN_RESTRICTION|DOMAIN_SUBTRACTION|RANGE_RESTRICTION |RANGE_SUBTRACTION|INSERT_FRONT|INSERT_TAIL|UNION|INTERSECTION |RESTRICT_FRONT|RESTRICT_TAIL|MAPLET) expression # ExpressionOperator //p160 ; ltlStart : ltlFormula EOF ; ltlFormula : LTL_LEFT_PAR ltlFormula LTL_RIGHT_PAR # LTLParentheses | keyword=(LTL_TRUE|LTL_FALSE) # LTLKeyword | operator=(LTL_GLOBALLY|LTL_FINALLY|LTL_NEXT|LTL_NOT) ltlFormula # LTLPrefixOperator | LTL_B_START predicate B_END # LTLBPredicate | ltlFormula operator=LTL_IMPLIES ltlFormula # LTLInfixOperator | ltlFormula operator=(LTL_UNTIL|LTL_RELEASE) ltlFormula # LTLInfixOperator | ltlFormula operator=(LTL_AND|LTL_OR) ltlFormula # LTLInfixOperator ;
format grammar
format grammar
ANTLR
mit
hhu-stups/bmoth
967f6db83574560e0bba50f0507e9611203b1afc
src/main/antlr4/YokohamaUnitLexer.g4
src/main/antlr4/YokohamaUnitLexer.g4
lexer grammar YokohamaUnitLexer; HASH1: '#' ; HASH2: '##' ; HASH3: '###' ; HASH4: '####' ; HASH5: '#####' ; HASH6: '######' ; TEST: 'Test:' -> mode(TEST_LEADING); TABLECAPTION: '[' -> skip, mode(TABLE_NAME); SETUP: 'Setup' -> mode(PHASE_LEADING); EXERCISE: 'Exercise' -> mode(PHASE_LEADING); VERIFY: 'Verify' -> mode(PHASE_LEADING); TEARDOWN: 'Teardown' -> mode(PHASE_LEADING); BAR: '|' -> mode(IN_TABLE_HEADER) ; STARLBRACKET: '*[' -> skip, mode(ABBREVIATION); ASSERT: 'Assert' -> mode(IN_THE_MIDDLE_OF_LINE) ; THAT: 'that' -> mode(IN_THE_MIDDLE_OF_LINE) ; STOP: '.' -> mode(IN_THE_MIDDLE_OF_LINE) ; AND: 'and' -> mode(IN_THE_MIDDLE_OF_LINE) ; IS: 'is' -> mode(IN_THE_MIDDLE_OF_LINE) ; NOT: 'not' -> mode(IN_THE_MIDDLE_OF_LINE) ; THROWS: 'throws' -> mode(IN_THE_MIDDLE_OF_LINE) ; FOR: 'for' -> mode(IN_THE_MIDDLE_OF_LINE) ; ALL: 'all' -> mode(IN_THE_MIDDLE_OF_LINE) ; COMMA: ',' -> mode(IN_THE_MIDDLE_OF_LINE) ; RULES: 'rules' -> mode(IN_THE_MIDDLE_OF_LINE) ; IN: 'in' -> mode(IN_THE_MIDDLE_OF_LINE) ; UTABLE: 'Table' -> mode(AFTER_TABLE) ; CSV: 'CSV' -> mode(AFTER_CSV) ; TSV: 'TSV' -> mode(AFTER_CSV) ; EXCEL: 'Excel' -> mode(AFTER_EXCEL) ; WHERE: 'where' -> mode(IN_THE_MIDDLE_OF_LINE) ; EQ: '=' -> mode(IN_THE_MIDDLE_OF_LINE) ; LET: 'Let' -> mode(IN_THE_MIDDLE_OF_LINE) ; BE: 'be' -> mode(IN_THE_MIDDLE_OF_LINE) ; DO: 'Do' -> mode(IN_THE_MIDDLE_OF_LINE) ; A_STUB_OF: 'a' [ \t\r\n]+ 'stub' [ \t\r\n]+ 'of' -> mode(EXPECT_CLASS) ; SUCH: 'such' -> mode(IN_THE_MIDDLE_OF_LINE) ; METHOD: 'method' -> mode(AFTER_METHOD) ; RETURNS: 'returns' -> mode(IN_THE_MIDDLE_OF_LINE) ; AN_INSTANCE_OF: 'an' [ \t\r\n]+ 'instance' [ \t\r\n] 'of' -> mode(EXPECT_CLASS) ; AN_INSTANCE: 'an' [ \t\r\n]+ 'instance' -> mode(AFTER_AN_INSTANCE) ; AN_INVOCATION_OF: 'an' [ \t\r\n]+ 'invocation' [ \t\r\n] 'of' -> mode(AFTER_METHOD) ; NULL: 'null' -> mode(IN_THE_MIDDLE_OF_LINE) ; NOTHING: 'nothing' -> mode(IN_THE_MIDDLE_OF_LINE) ; Identifier: IdentStart IdentPart* ; Integer: IntegerLiteral ; FloatingPoint: FloatingPointLiteral ; MINUS: '-' ; OPENBACKTICK: '`' -> skip, mode(IN_BACKTICK) ; OPENDOUBLEQUOTE: '"' -> skip, mode(IN_DOUBLEQUOTE) ; NEW_LINE : ('\r'? '\n')+ -> skip ; WS : [ \t]+ -> skip ; mode IN_THE_MIDDLE_OF_LINE; ASSERT2: 'Assert' -> type(ASSERT) ; THAT2: 'that' -> type(THAT) ; STOP2: '.' -> type(STOP) ; AND2: 'and' -> type(AND) ; IS2: 'is' -> type(IS) ; NOT2: 'not' -> type(NOT) ; THROWS2: 'throws' -> type(THROWS) ; FOR2: 'for' -> type(FOR) ; ALL2: 'all' -> type(ALL) ; RULES2: 'rules' -> type(RULES) ; COMMA2: ',' -> type(COMMA); IN2: 'in' -> type(IN) ; UTABLE2: 'Table' -> type(UTABLE), mode(AFTER_TABLE) ; CSV2: 'CSV' -> type(CSV), mode(AFTER_CSV) ; TSV2: 'TSV' -> type(TSV), mode(AFTER_CSV) ; EXCEL2: 'Excel' -> type(EXCEL), mode(AFTER_EXCEL) ; WHERE2: 'where' -> type(WHERE) ; EQ2: '=' -> type(EQ) ; LET2: 'Let' -> type(LET) ; BE2: 'be' -> type(BE) ; DO2: 'Do' -> type(DO) ; A_STUB_OF2: 'a' [ \t\r\n]+ 'stub' [ \t\r\n]+ 'of' -> type(A_STUB_OF), mode(EXPECT_CLASS) ; SUCH2: 'such' -> type(SUCH) ; METHOD2: 'method' -> type(METHOD), mode(AFTER_METHOD) ; RETURNS2: 'returns' -> type(RETURNS) ; AN_INSTANCE_OF2: 'an' [ \t\r\n]+ 'instance' [ \t\r\n] 'of' -> type(AN_INSTANCE_OF), mode(EXPECT_CLASS) ; AN_INSTANCE2: 'an' [ \t\r\n]+ 'instance' -> type(AN_INSTANCE), mode(AFTER_AN_INSTANCE) ; AN_INVOCATION_OF2: 'an' [ \t\r\n]+ 'invocation' [ \t\r\n] 'of' -> type(AN_INVOCATION_OF), mode(AFTER_METHOD) ; NULL2: 'null' -> type(NULL) ; NOTHING2: 'nothing' -> type(NOTHING) ; Identifier2 : IdentStart IdentPart* -> type(Identifier); Integer2: IntegerLiteral -> type(Integer); FloatingPoint2: FloatingPointLiteral -> type(FloatingPoint); MINUS2: '-' -> type(MINUS) ; OPENBACKTICK2: '`' -> skip, mode(IN_BACKTICK) ; OPENDOUBLEQUOTE2: '"' -> skip, mode(IN_DOUBLEQUOTE) ; NEW_LINE2 : ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; WS2 : [ \t]+ -> skip ; mode TEST_LEADING; WS3: [ \t]+ -> skip, mode(TEST_NAME); mode TEST_NAME; TestName: ~[\r\n]+ ; NEW_LINE_TESTNAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode TABLE_NAME; TableName: ~[\]\r\n]+ ; EXIT_TABLENAME: ']' [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode PHASE_LEADING; COLON: ':' [ \t]* -> skip, mode(PHASE_DESCRIPTION) ; WS5: [ \t]* '\r'? '\n' -> skip, mode(DEFAULT_MODE) ; mode PHASE_DESCRIPTION; PhaseDescription: ~[\r\n]+ ; NEW_LINE_PHASE: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode IN_DOUBLEQUOTE; Quoted: ~["]+ ; CLOSEDOUBLEQUOTE: '"' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode IN_BACKTICK; Expr: ~[`]+ /*-> type(Expr)*/ ; CLOSEBACKTICK: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode IN_TABLE_HEADER; IDENTHEADER: IdentStart IdentPart* -> type(Identifier) ; BARH: '|' -> type(BAR) ; NEWLINE: '\r'? '\n' -> mode(IN_TABLE_ONSET) ; SPACETAB: [ \t]+ -> skip ; mode IN_TABLE_CELL; ExprCell: ~[|\r\n]+ -> type(Expr) ; BARCELL: '|' -> type(BAR) ; NEWLINECELL: '\r'? '\n' -> type(NEWLINE), mode(IN_TABLE_ONSET) ; SPACETABCELL: [ \t]+ -> skip ; mode IN_TABLE_ONSET; HBAR: [|\-=\:\.\+ \t]+ '\r'? '\n' ; BARONSET: '|' -> type(BAR), mode(IN_TABLE_CELL) ; TABLECAPTION2: '[' -> skip, mode(TABLE_NAME); SPACETAB2: [ \t]+ -> skip ; NEWLINEONSET: '\r'?'\n' -> skip, mode(DEFAULT_MODE) ; mode AFTER_METHOD; OPENBACKTICK3: '`' -> skip, mode(METHOD_PATTERN) ; SPACETABNEWLINE: [ \t\r\n]+ -> skip ; mode METHOD_PATTERN; BOOLEAN: 'boolean' ; BYTE: 'byte' ; SHORT: 'short' ; INT: 'int' ; LONG: 'long' ; CHAR: 'char' ; FLOAT: 'float' ; DOUBLE: 'double' ; COMMA3: ',' -> type(COMMA); THREEDOTS: '...' ; DOT: '.' ; LPAREN: '(' ; RPAREN: ')' ; LBRACKET: '[' ; RBRACKET: ']' ; Identifier3 : IdentStart IdentPart* -> type(Identifier); SPACETABNEWLINE2: [ \t\r\n]+ -> skip ; CLOSEBACKTICK2: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode EXPECT_CLASS; OPENBACKTICK4: '`' -> skip, mode(CLASS) ; SPACETABNEWLINE3: [ \t\r\n]+ -> skip ; mode CLASS; DOT2: '.' -> type(DOT) ; Identifier4 : IdentStart IdentPart* -> type(Identifier) ; SPACETABNEWLINE4: [ \t\r\n]+ -> skip ; CLOSEBACKTICK3: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode AFTER_AN_INSTANCE; OF: 'of' ; Identifier5 : IdentStart IdentPart* -> type(Identifier) ; OPENBACKTICK5: '`' -> skip, mode(CLASS) ; SPACETABNEWLINE5: [ \t\r\n]+ -> skip ; mode AFTER_TABLE; LBRACKET2: '[' -> skip, mode(IN_TABLE_NAME) ; SPACETABNEWLINE6: [ \t\r\n]+ -> skip ; mode AFTER_CSV; OPENSINGLEQUOTE2: '\'' -> skip, mode(IN_FILE_NAME) ; SPACETABNEWLINE7: [ \t\r\n]+ -> skip ; mode AFTER_EXCEL; OPENSINGLEQUOTE3: '\'' -> skip, mode(IN_BOOK_NAME) ; SPACETABNEWLINE8: [ \t\r\n]+ -> skip ; mode IN_TABLE_NAME; SingleQuoteName: ~[\]\r\n]* ; RBRACKET2: ']' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode IN_FILE_NAME; SingleQuoteName2: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ; CLOSESINGLEQUOTE2: '\'' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode IN_BOOK_NAME; SingleQuoteName3: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ; CLOSESINGLEQUOTE3: '\'' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode ABBREVIATION; ShortName: ~[\]\r\n]* ; RBRACKETCOLON: ']:' [ \t\r\n]* -> skip, mode(LONG_NAME) ; mode LONG_NAME; LongName: ~[\r\n]* ; EXIT_LONG_NAME: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; fragment IdentStart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierStart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IdentPart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierPart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IntegerLiteral: DecimalIntegerLiteral | HexIntegerLiteral | OctalIntegerLiteral | BinaryIntegerLiteral ; fragment DecimalIntegerLiteral: DecimalNumeral IntegerTypeSuffix? ; fragment HexIntegerLiteral: HexNumeral IntegerTypeSuffix? ; fragment OctalIntegerLiteral: OctalNumeral IntegerTypeSuffix? ; fragment BinaryIntegerLiteral: BinaryNumeral IntegerTypeSuffix? ; fragment IntegerTypeSuffix: [lL] ; fragment DecimalNumeral: '0' | [1-9] ([_0-9]* [0-9])? ; fragment HexNumeral: '0' [xX] HexDigits ; fragment HexDigits: [0-9a-fA-F] ([_0-9a-fA-F]* [0-9a-fA-F])? ; fragment OctalNumeral: '0' [_0-7]* [0-7] ; fragment BinaryNumeral: '0' [bB] [01] ([_01]* [01])? ; fragment FloatingPointLiteral: DecimalFloatingPointLiteral | HexadecimalFloatingPointLiteral ; fragment DecimalFloatingPointLiteral: Digits '.' Digits ExponentPart? FloatTypeSuffix? | Digits '.' ExponentPart FloatTypeSuffix? | Digits '.' ExponentPart? FloatTypeSuffix /* the above rules differ from the Java spec: fp literals which end with dot are not allowd */ | '.' Digits ExponentPart? FloatTypeSuffix? | Digits ExponentPart FloatTypeSuffix? | Digits ExponentPart? FloatTypeSuffix ; fragment Digits: [0-9] ([_0-9]* [0-9])? ; fragment ExponentPart: [eE] SignedInteger ; fragment SignedInteger: ('+' | '-')? Digits ; fragment FloatTypeSuffix: [fFdD] ; fragment HexadecimalFloatingPointLiteral: HexSignificand BinaryExponent FloatTypeSuffix? ; fragment HexSignificand: HexNumeral '.'? | '0' [xX] HexDigits? . HexDigits ; fragment BinaryExponent: [pP] SignedInteger ;
lexer grammar YokohamaUnitLexer; HASH1: '#' ; HASH2: '##' ; HASH3: '###' ; HASH4: '####' ; HASH5: '#####' ; HASH6: '######' ; TEST: 'Test:' -> mode(TEST_LEADING); TABLECAPTION: '[' -> skip, mode(TABLE_NAME); SETUP: 'Setup' -> mode(PHASE_LEADING); EXERCISE: 'Exercise' -> mode(PHASE_LEADING); VERIFY: 'Verify' -> mode(PHASE_LEADING); TEARDOWN: 'Teardown' -> mode(PHASE_LEADING); BAR: '|' -> mode(IN_TABLE_HEADER) ; STARLBRACKET: '*[' -> skip, mode(ABBREVIATION); ASSERT: 'Assert' -> mode(IN_THE_MIDDLE_OF_LINE) ; THAT: 'that' -> mode(IN_THE_MIDDLE_OF_LINE) ; STOP: '.' -> mode(IN_THE_MIDDLE_OF_LINE) ; AND: 'and' -> mode(IN_THE_MIDDLE_OF_LINE) ; IS: 'is' -> mode(IN_THE_MIDDLE_OF_LINE) ; NOT: 'not' -> mode(IN_THE_MIDDLE_OF_LINE) ; THROWS: 'throws' -> mode(IN_THE_MIDDLE_OF_LINE) ; FOR: 'for' -> mode(IN_THE_MIDDLE_OF_LINE) ; ALL: 'all' -> mode(IN_THE_MIDDLE_OF_LINE) ; COMMA: ',' -> mode(IN_THE_MIDDLE_OF_LINE) ; RULES: 'rules' -> mode(IN_THE_MIDDLE_OF_LINE) ; IN: 'in' -> mode(IN_THE_MIDDLE_OF_LINE) ; UTABLE: 'Table' -> mode(AFTER_TABLE) ; CSV: 'CSV' -> mode(AFTER_CSV) ; TSV: 'TSV' -> mode(AFTER_CSV) ; EXCEL: 'Excel' -> mode(AFTER_EXCEL) ; WHERE: 'where' -> mode(IN_THE_MIDDLE_OF_LINE) ; EQ: '=' -> mode(IN_THE_MIDDLE_OF_LINE) ; LET: 'Let' -> mode(IN_THE_MIDDLE_OF_LINE) ; BE: 'be' -> mode(IN_THE_MIDDLE_OF_LINE) ; DO: 'Do' -> mode(IN_THE_MIDDLE_OF_LINE) ; A_STUB_OF: 'a' [ \t\r\n]+ 'stub' [ \t\r\n]+ 'of' -> mode(EXPECT_CLASS) ; SUCH: 'such' -> mode(IN_THE_MIDDLE_OF_LINE) ; METHOD: 'method' -> mode(AFTER_METHOD) ; RETURNS: 'returns' -> mode(IN_THE_MIDDLE_OF_LINE) ; AN_INSTANCE_OF: 'an' [ \t\r\n]+ 'instance' [ \t\r\n] 'of' -> mode(EXPECT_CLASS) ; AN_INSTANCE: 'an' [ \t\r\n]+ 'instance' -> mode(AFTER_AN_INSTANCE) ; AN_INVOCATION_OF: 'an' [ \t\r\n]+ 'invocation' [ \t\r\n] 'of' -> mode(AFTER_METHOD) ; NULL: 'null' -> mode(IN_THE_MIDDLE_OF_LINE) ; NOTHING: 'nothing' -> mode(IN_THE_MIDDLE_OF_LINE) ; Identifier: IdentStart IdentPart* -> mode(IN_THE_MIDDLE_OF_LINE) ; Integer: IntegerLiteral -> mode(IN_THE_MIDDLE_OF_LINE) ; FloatingPoint: FloatingPointLiteral -> mode(IN_THE_MIDDLE_OF_LINE) ; MINUS: '-' -> mode(IN_THE_MIDDLE_OF_LINE) ; OPENBACKTICK: '`' -> skip, mode(IN_BACKTICK) ; OPENDOUBLEQUOTE: '"' -> skip, mode(IN_DOUBLEQUOTE) ; NEW_LINE : ('\r'? '\n')+ -> skip ; WS : [ \t]+ -> skip ; mode IN_THE_MIDDLE_OF_LINE; ASSERT2: 'Assert' -> type(ASSERT) ; THAT2: 'that' -> type(THAT) ; STOP2: '.' -> type(STOP) ; AND2: 'and' -> type(AND) ; IS2: 'is' -> type(IS) ; NOT2: 'not' -> type(NOT) ; THROWS2: 'throws' -> type(THROWS) ; FOR2: 'for' -> type(FOR) ; ALL2: 'all' -> type(ALL) ; RULES2: 'rules' -> type(RULES) ; COMMA2: ',' -> type(COMMA); IN2: 'in' -> type(IN) ; UTABLE2: 'Table' -> type(UTABLE), mode(AFTER_TABLE) ; CSV2: 'CSV' -> type(CSV), mode(AFTER_CSV) ; TSV2: 'TSV' -> type(TSV), mode(AFTER_CSV) ; EXCEL2: 'Excel' -> type(EXCEL), mode(AFTER_EXCEL) ; WHERE2: 'where' -> type(WHERE) ; EQ2: '=' -> type(EQ) ; LET2: 'Let' -> type(LET) ; BE2: 'be' -> type(BE) ; DO2: 'Do' -> type(DO) ; A_STUB_OF2: 'a' [ \t\r\n]+ 'stub' [ \t\r\n]+ 'of' -> type(A_STUB_OF), mode(EXPECT_CLASS) ; SUCH2: 'such' -> type(SUCH) ; METHOD2: 'method' -> type(METHOD), mode(AFTER_METHOD) ; RETURNS2: 'returns' -> type(RETURNS) ; AN_INSTANCE_OF2: 'an' [ \t\r\n]+ 'instance' [ \t\r\n] 'of' -> type(AN_INSTANCE_OF), mode(EXPECT_CLASS) ; AN_INSTANCE2: 'an' [ \t\r\n]+ 'instance' -> type(AN_INSTANCE), mode(AFTER_AN_INSTANCE) ; AN_INVOCATION_OF2: 'an' [ \t\r\n]+ 'invocation' [ \t\r\n] 'of' -> type(AN_INVOCATION_OF), mode(AFTER_METHOD) ; NULL2: 'null' -> type(NULL) ; NOTHING2: 'nothing' -> type(NOTHING) ; Identifier2 : IdentStart IdentPart* -> type(Identifier); Integer2: IntegerLiteral -> type(Integer); FloatingPoint2: FloatingPointLiteral -> type(FloatingPoint); MINUS2: '-' -> type(MINUS) ; OPENBACKTICK2: '`' -> skip, mode(IN_BACKTICK) ; OPENDOUBLEQUOTE2: '"' -> skip, mode(IN_DOUBLEQUOTE) ; NEW_LINE2 : ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; WS2 : [ \t]+ -> skip ; mode TEST_LEADING; WS3: [ \t]+ -> skip, mode(TEST_NAME); mode TEST_NAME; TestName: ~[\r\n]+ ; NEW_LINE_TESTNAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode TABLE_NAME; TableName: ~[\]\r\n]+ ; EXIT_TABLENAME: ']' [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode PHASE_LEADING; COLON: ':' [ \t]* -> skip, mode(PHASE_DESCRIPTION) ; WS5: [ \t]* '\r'? '\n' -> skip, mode(DEFAULT_MODE) ; mode PHASE_DESCRIPTION; PhaseDescription: ~[\r\n]+ ; NEW_LINE_PHASE: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode IN_DOUBLEQUOTE; Quoted: ~["]+ ; CLOSEDOUBLEQUOTE: '"' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode IN_BACKTICK; Expr: ~[`]+ /*-> type(Expr)*/ ; CLOSEBACKTICK: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode IN_TABLE_HEADER; IDENTHEADER: IdentStart IdentPart* -> type(Identifier) ; BARH: '|' -> type(BAR) ; NEWLINE: '\r'? '\n' -> mode(IN_TABLE_ONSET) ; SPACETAB: [ \t]+ -> skip ; mode IN_TABLE_CELL; ExprCell: ~[|\r\n]+ -> type(Expr) ; BARCELL: '|' -> type(BAR) ; NEWLINECELL: '\r'? '\n' -> type(NEWLINE), mode(IN_TABLE_ONSET) ; SPACETABCELL: [ \t]+ -> skip ; mode IN_TABLE_ONSET; HBAR: [|\-=\:\.\+ \t]+ '\r'? '\n' ; BARONSET: '|' -> type(BAR), mode(IN_TABLE_CELL) ; TABLECAPTION2: '[' -> skip, mode(TABLE_NAME); SPACETAB2: [ \t]+ -> skip ; NEWLINEONSET: '\r'?'\n' -> skip, mode(DEFAULT_MODE) ; mode AFTER_METHOD; OPENBACKTICK3: '`' -> skip, mode(METHOD_PATTERN) ; SPACETABNEWLINE: [ \t\r\n]+ -> skip ; mode METHOD_PATTERN; BOOLEAN: 'boolean' ; BYTE: 'byte' ; SHORT: 'short' ; INT: 'int' ; LONG: 'long' ; CHAR: 'char' ; FLOAT: 'float' ; DOUBLE: 'double' ; COMMA3: ',' -> type(COMMA); THREEDOTS: '...' ; DOT: '.' ; LPAREN: '(' ; RPAREN: ')' ; LBRACKET: '[' ; RBRACKET: ']' ; Identifier3 : IdentStart IdentPart* -> type(Identifier); SPACETABNEWLINE2: [ \t\r\n]+ -> skip ; CLOSEBACKTICK2: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode EXPECT_CLASS; OPENBACKTICK4: '`' -> skip, mode(CLASS) ; SPACETABNEWLINE3: [ \t\r\n]+ -> skip ; mode CLASS; DOT2: '.' -> type(DOT) ; Identifier4 : IdentStart IdentPart* -> type(Identifier) ; SPACETABNEWLINE4: [ \t\r\n]+ -> skip ; CLOSEBACKTICK3: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode AFTER_AN_INSTANCE; OF: 'of' ; Identifier5 : IdentStart IdentPart* -> type(Identifier) ; OPENBACKTICK5: '`' -> skip, mode(CLASS) ; SPACETABNEWLINE5: [ \t\r\n]+ -> skip ; mode AFTER_TABLE; LBRACKET2: '[' -> skip, mode(IN_TABLE_NAME) ; SPACETABNEWLINE6: [ \t\r\n]+ -> skip ; mode AFTER_CSV; OPENSINGLEQUOTE2: '\'' -> skip, mode(IN_FILE_NAME) ; SPACETABNEWLINE7: [ \t\r\n]+ -> skip ; mode AFTER_EXCEL; OPENSINGLEQUOTE3: '\'' -> skip, mode(IN_BOOK_NAME) ; SPACETABNEWLINE8: [ \t\r\n]+ -> skip ; mode IN_TABLE_NAME; SingleQuoteName: ~[\]\r\n]* ; RBRACKET2: ']' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode IN_FILE_NAME; SingleQuoteName2: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ; CLOSESINGLEQUOTE2: '\'' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode IN_BOOK_NAME; SingleQuoteName3: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ; CLOSESINGLEQUOTE3: '\'' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ; mode ABBREVIATION; ShortName: ~[\]\r\n]* ; RBRACKETCOLON: ']:' [ \t\r\n]* -> skip, mode(LONG_NAME) ; mode LONG_NAME; LongName: ~[\r\n]* ; EXIT_LONG_NAME: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; fragment IdentStart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierStart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IdentPart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierPart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IntegerLiteral: DecimalIntegerLiteral | HexIntegerLiteral | OctalIntegerLiteral | BinaryIntegerLiteral ; fragment DecimalIntegerLiteral: DecimalNumeral IntegerTypeSuffix? ; fragment HexIntegerLiteral: HexNumeral IntegerTypeSuffix? ; fragment OctalIntegerLiteral: OctalNumeral IntegerTypeSuffix? ; fragment BinaryIntegerLiteral: BinaryNumeral IntegerTypeSuffix? ; fragment IntegerTypeSuffix: [lL] ; fragment DecimalNumeral: '0' | [1-9] ([_0-9]* [0-9])? ; fragment HexNumeral: '0' [xX] HexDigits ; fragment HexDigits: [0-9a-fA-F] ([_0-9a-fA-F]* [0-9a-fA-F])? ; fragment OctalNumeral: '0' [_0-7]* [0-7] ; fragment BinaryNumeral: '0' [bB] [01] ([_01]* [01])? ; fragment FloatingPointLiteral: DecimalFloatingPointLiteral | HexadecimalFloatingPointLiteral ; fragment DecimalFloatingPointLiteral: Digits '.' Digits ExponentPart? FloatTypeSuffix? | Digits '.' ExponentPart FloatTypeSuffix? | Digits '.' ExponentPart? FloatTypeSuffix /* the above rules differ from the Java spec: fp literals which end with dot are not allowd */ | '.' Digits ExponentPart? FloatTypeSuffix? | Digits ExponentPart FloatTypeSuffix? | Digits ExponentPart? FloatTypeSuffix ; fragment Digits: [0-9] ([_0-9]* [0-9])? ; fragment ExponentPart: [eE] SignedInteger ; fragment SignedInteger: ('+' | '-')? Digits ; fragment FloatTypeSuffix: [fFdD] ; fragment HexadecimalFloatingPointLiteral: HexSignificand BinaryExponent FloatTypeSuffix? ; fragment HexSignificand: HexNumeral '.'? | '0' [xX] HexDigits? . HexDigits ; fragment BinaryExponent: [pP] SignedInteger ;
Change mode to IN_THE_MIDDLE_OF_LINE if identifiers or literals are recognized
Change mode to IN_THE_MIDDLE_OF_LINE if identifiers or literals are recognized
ANTLR
mit
tkob/yokohamaunit,tkob/yokohamaunit
35e624ec1f37afdf5d25716509a7d76f4e2c93ad
source/src/HML.g4
source/src/HML.g4
grammar HML; hybridModel : signalDeclaration* variableDeclaration* template* program EOF ; template : 'Template' ID formalParameters parStatement; formalParameters : '(' formalParameterDecls? ')' ; formalParameterDecls : type formalParameterDeclsRest ; formalParameterDeclsRest : variableDeclaratorId (',' formalParameterDecls)? ; variableDeclaratorId : ID ('[' ']')* ; type : primitiveType ('[' ']')* ; primitiveType : 'boolean' | 'int' | 'float' ; signalDeclaration : 'Signal' ('[' size=INT ']')* ID (',' ID)* ';' ; modifier : 'final' // used for the vars that cannot be modified ; variableDeclaration : modifier? type variableDeclarators ';' ; variableDeclarators : variableDeclarator (',' variableDeclarator)* ; variableDeclarator : variableDeclaratorId ('=' variableInitializer)? ; variableInitializer : arrayInitializer | expr ; arrayInitializer : '{' (variableInitializer (',' variableInitializer)* (',')? )? '}' | 'new' 'Array' ('[' INT ']')+ ; program : 'Main ' '{' signalDeclaration* variableDeclaration* blockStatement* '}'; blockStatement : atom #AtomPro // Atomic | blockStatement '|' blockStatement #NonCh // non-deterministrate choice | blockStatement '||' blockStatement #ParaCom // parallel composition | blockStatement ';' blockStatement #SeqCom // sequential composition | '(' blockStatement '<' expr '>' blockStatement ')' #ConCh // conditional choice | equation 'until' guard #Ode // differential equation | 'when' '(' guardedchoice ')' #WhenPro // when program | 'while' parExpression parStatement #LoopPro // loop | 'if' parExpression parStatement 'else' parStatement #IfPro // if statement | ID '(' exprList? ')' #CallTem // call template | parStatement #ParPro // program with paraentheses outside ; parStatement : '{' blockStatement '}' | '(' blockStatement ')' ; exprList : expr (',' expr)* ; // arg list atom : 'skip' | ID ':=' expr | '!' ID | 'suspend' '(' time=expr ')' ; expr : ID | INT | FLOAT |'true' | 'false' | ('-' | '~') expr // negtive and negation | expr ('*'|'/'|'mod') expr // % is mod | expr ('+'|'-') expr | expr ('>=' | '>' | '==' | '<' | '<=') expr | expr 'and' expr | expr 'or' expr | 'floor' '(' expr ')' | 'ceil' '(' expr ')' ; parExpression : '(' expr ')' ; equation : relation | relation 'init' expr | equation '||' equation ; relation : 'dot' ID '=' expr; guard : 'eps' | signal | expr | 'timeout' '(' expr ')' | guard '<and>' guard | guard '<or>' guard | '(' guard ')' ; signal : ID ('[' expr ']')*; guardedchoice : guard '&' program | guardedchoice '[]' guardedchoice ; COMOP : '>=' | '>' | '==' | '<' | '<=' ; ID : (LETTER | '_') (LETTER|DIGIT|'_')* ; fragment LETTER : [a-zA-Z] ; INT : DIGIT+ ; FLOAT : DIGIT+ '.' DIGIT+ ; fragment DIGIT: '0'..'9' ; COMMENT : '/*' .*? '*/' -> channel(HIDDEN) // match anything between /* and */ ; LINE_COMMENT : '//' ~[\r\n]* '\r'? '\n' -> channel(HIDDEN) ; WS : [ \r\t\u000C\n]+ -> channel(HIDDEN) ;
grammar HML; hybridModel : signalDeclaration* variableDeclaration* template* program EOF ; template : 'Template' ID formalParameters parStatement; formalParameters : '(' formalParameterDecls? ')' ; formalParameterDecls : type formalParameterDeclsRest ; formalParameterDeclsRest : variableDeclaratorId (',' formalParameterDecls)? ; variableDeclaratorId : ID ('[' ']')* ; type : primitiveType ('[' ']')* ; primitiveType : 'boolean' | 'int' | 'float' ; signalDeclaration : 'Signal' ('[' size=INT ']')* ID (',' ID)* ';' ; modifier : 'final' // used for the vars that cannot be modified ; variableDeclaration : modifier? type variableDeclarators ';' ; variableDeclarators : variableDeclarator (',' variableDeclarator)* ; variableDeclarator : variableDeclaratorId ('=' variableInitializer)? ; variableInitializer : arrayInitializer | expr ; arrayInitializer : '{' (variableInitializer (',' variableInitializer)* (',')? )? '}' | 'new' 'Array' ('[' INT ']')+ ; program : 'Main ' '{' signalDeclaration* variableDeclaration* blockStatement* '}'; blockStatement : atom #AtomPro // Atomic | blockStatement '|' blockStatement #NonCh // non-deterministrate choice | blockStatement '||' blockStatement #ParaCom // parallel composition | blockStatement ';' blockStatement #SeqCom // sequential composition | '(' blockStatement '<' expr '>' blockStatement ')' #ConCh // conditional choice | equation 'until' guard #Ode // differential equation | 'when' '(' guardedchoice ')' #WhenPro // when program | 'while' parExpression parStatement #LoopPro // loop | 'if' parExpression parStatement 'else' parStatement #IfPro // if statement | ID '(' exprList? ')' #CallTem // call template | parStatement #ParPro // program with paraentheses outside ; parStatement : '{' blockStatement '}' | '(' blockStatement ')' ; exprList : expr (',' expr)* ; // arg list atom : 'skip' | ID ':=' expr | '!' ID | 'suspend' '(' time=expr ')' ; expr : ID | INT | FLOAT |'true' | 'false' | ('-' | '~') expr // negtive and negation | expr ('*'|'/'|'mod') expr // % is mod | expr ('+'|'-') expr | expr ('>=' | '>' | '==' | '<' | '<=') expr | expr 'and' expr | expr 'or' expr | 'floor' '(' expr ')' | 'ceil' '(' expr ')' | parExpression ; parExpression : '(' expr ')' ; equation : relation | relation 'init' expr | equation '||' equation ; relation : 'dot' ID '=' expr; guard : 'eps' | signal | expr | 'timeout' '(' expr ')' | guard '<and>' guard | guard '<or>' guard | '(' guard ')' ; signal : ID ('[' expr ']')*; guardedchoice : guard '&' program | guardedchoice '[]' guardedchoice ; COMOP : '>=' | '>' | '==' | '<' | '<=' ; ID : (LETTER | '_') (LETTER|DIGIT|'_')* ; fragment LETTER : [a-zA-Z] ; INT : DIGIT+ ; FLOAT : DIGIT+ '.' DIGIT+ ; fragment DIGIT: '0'..'9' ; COMMENT : '/*' .*? '*/' -> channel(HIDDEN) // match anything between /* and */ ; LINE_COMMENT : '//' ~[\r\n]* '\r'? '\n' -> channel(HIDDEN) ; WS : [ \r\t\u000C\n]+ -> channel(HIDDEN) ;
add parExpression as a sub-rule of expr
add parExpression as a sub-rule of expr
ANTLR
mit
fanghuixing/HML
2663a35a2111ef6cd832987816cc8aa4d40fbb67
sharding-jdbc-ddl-parser/src/main/antlr4/imports/BaseRule.g4
sharding-jdbc-ddl-parser/src/main/antlr4/imports/BaseRule.g4
//rule in this file does not allow override grammar BaseRule; import DataType,Keyword,Symbol; ID: (BACK_QUOTA?[a-zA-Z_$][a-zA-Z0-9_$]* BACK_QUOTA? DOT)? (BACK_QUOTA?[a-zA-Z_$][a-zA-Z0-9_$]* BACK_QUOTA?) |[a-zA-Z_$0-9]+ DOT ASTERISK ; schemaName: ID; tableName: ID; tableOrViewName: ID; columnName: ID; tablespaceName: ID; collationName: STRING | ID; indexName: ID; alias: ID; cteName:ID; parserName: ID; extensionName: ID; rowName: ID; storageParameter: ID; opclass: ID; fileGroup: ID; groupName: ID; constraintName: ID; keyName: ID; typeName: ID; xmlSchemaCollection:ID; columnSetName: ID; directoryName: ID; triggerName: ID; roleName: ID; partitionName: ID; rewriteRuleName: ID; ownerName: ID; matchNone: 'Default does not match anything' ; idList: LEFT_PAREN ID (COMMA ID)* RIGHT_PAREN ; rangeClause: NUMBER (COMMA NUMBER)* | NUMBER OFFSET NUMBER ; tableNames: tableName (COMMA tableName)* ; columnNames: columnName (COMMA columnName)* ; columnList: LEFT_PAREN columnNames RIGHT_PAREN ; indexNames: indexName (COMMA indexName)* ; rowNames: rowName (COMMA rowName)* ; exprs: expr (COMMA expr)* ; exprsWithParen: LEFT_PAREN exprs RIGHT_PAREN ; //https://dev.mysql.com/doc/refman/8.0/en/expressions.html expr: expr OR expr | expr OR_SYM expr | expr XOR expr | expr AND expr | expr AND_SYM expr | LEFT_PAREN expr RIGHT_PAREN | NOT expr | NOT_SYM expr | booleanPrimary | exprRecursive ; exprRecursive: matchNone ; booleanPrimary: booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL) | booleanPrimary SAFE_EQ predicate | booleanPrimary comparisonOperator predicate | booleanPrimary comparisonOperator (ALL | ANY) subquery | predicate ; comparisonOperator: EQ_OR_ASSIGN | GTE | GT | LTE | LT | NEQ_SYM | NEQ ; predicate: bitExpr NOT? IN subquery | bitExpr NOT? IN LEFT_PAREN simpleExpr ( COMMA simpleExpr)* RIGHT_PAREN | bitExpr NOT? BETWEEN simpleExpr AND predicate | bitExpr SOUNDS LIKE simpleExpr | bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)* | bitExpr NOT? REGEXP simpleExpr | bitExpr ; bitExpr: bitExpr BIT_INCLUSIVE_OR bitExpr | bitExpr BIT_AND bitExpr | bitExpr SIGNED_LEFT_SHIFT bitExpr | bitExpr SIGNED_RIGHT_SHIFT bitExpr | bitExpr PLUS bitExpr | bitExpr MINUS bitExpr | bitExpr ASTERISK bitExpr | bitExpr SLASH bitExpr | bitExpr DIV bitExpr | bitExpr MOD bitExpr | bitExpr MOD_SYM bitExpr | bitExpr BIT_EXCLUSIVE_OR bitExpr //| bitExpr '+' interval_expr //| bitExpr '-' interval_expr | simpleExpr ; simpleExpr: functionCall | liter | ID | simpleExpr collateClause //| param_marker //| variable | simpleExpr AND_SYM simpleExpr | PLUS simpleExpr | MINUS simpleExpr | UNARY_BIT_COMPLEMENT simpleExpr | NOT_SYM simpleExpr | BINARY simpleExpr | LEFT_PAREN expr RIGHT_PAREN | ROW LEFT_PAREN simpleExpr( COMMA simpleExpr)* RIGHT_PAREN | subquery | EXISTS subquery // | (identifier expr) //| match_expr //| case_expr // | interval_expr |privateExprOfDb ; functionCall: ID LEFT_PAREN(| simpleExpr ( COMMA simpleExpr)*) RIGHT_PAREN ; privateExprOfDb: matchNone ; liter: QUESTION |NUMBER |TRUE |FALSE |NULL |LEFT_BRACE ID STRING RIGHT_BRACE // |HEX_DIGIT |ID? STRING collateClause? |(DATE | TIME |TIMESTAMP)STRING |ID? BIT_NUM collateClause? ; subquery: matchNone ; collateClause: matchNone ; orderByClause: ORDER BY groupByItem (COMMA groupByItem)* ; groupByItem: (columnName | NUMBER |expr) (ASC|DESC)? ;
//rule in this file does not allow override grammar BaseRule; import DataType,Keyword,Symbol; ID: (BACK_QUOTA?[a-zA-Z_$][a-zA-Z0-9_$]* BACK_QUOTA? DOT)? (BACK_QUOTA?[a-zA-Z_$][a-zA-Z0-9_$]* BACK_QUOTA?) |[a-zA-Z_$0-9]+ DOT ASTERISK ; schemaName: ID; tableName: ID; tableOrViewName: ID; columnName: ID; tablespaceName: ID; collationName: STRING | ID; indexName: ID; alias: ID; cteName:ID; parserName: ID; extensionName: ID; rowName: ID; storageParameter: ID; opclass: ID; fileGroup: ID; groupName: ID; constraintName: ID; keyName: ID; typeName: ID; xmlSchemaCollection:ID; columnSetName: ID; directoryName: ID; triggerName: ID; roleName: ID; partitionName: ID; rewriteRuleName: ID; ownerName: ID; matchNone: 'Default does not match anything' ; idList: LEFT_PAREN ID (COMMA ID)* RIGHT_PAREN ; rangeClause: NUMBER (COMMA NUMBER)* | NUMBER OFFSET NUMBER ; tableNames: tableName (COMMA tableName)* ; columnNames: columnName (COMMA columnName)* ; columnList: LEFT_PAREN columnNames RIGHT_PAREN ; indexNames: indexName (COMMA indexName)* ; rowNames: rowName (COMMA rowName)* ; bitExprs: bitExpr (COMMA bitExpr)* ; exprs: expr (COMMA expr)* ; exprsWithParen: LEFT_PAREN exprs RIGHT_PAREN ; //https://dev.mysql.com/doc/refman/8.0/en/expressions.html expr: expr OR expr | expr OR_SYM expr | expr XOR expr | expr AND expr | expr AND_SYM expr | LEFT_PAREN expr RIGHT_PAREN | NOT expr | NOT_SYM expr | booleanPrimary | exprRecursive ; exprRecursive: matchNone ; booleanPrimary: booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL) | booleanPrimary SAFE_EQ predicate | booleanPrimary comparisonOperator predicate | booleanPrimary comparisonOperator (ALL | ANY) subquery | predicate ; comparisonOperator: EQ_OR_ASSIGN | GTE | GT | LTE | LT | NEQ_SYM | NEQ ; predicate: bitExpr NOT? IN subquery | bitExpr NOT? IN LEFT_PAREN simpleExpr ( COMMA simpleExpr)* RIGHT_PAREN | bitExpr NOT? BETWEEN simpleExpr AND predicate | bitExpr SOUNDS LIKE simpleExpr | bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)* | bitExpr NOT? REGEXP simpleExpr | bitExpr ; bitExpr: bitExpr BIT_INCLUSIVE_OR bitExpr | bitExpr BIT_AND bitExpr | bitExpr SIGNED_LEFT_SHIFT bitExpr | bitExpr SIGNED_RIGHT_SHIFT bitExpr | bitExpr PLUS bitExpr | bitExpr MINUS bitExpr | bitExpr ASTERISK bitExpr | bitExpr SLASH bitExpr | bitExpr DIV bitExpr | bitExpr MOD bitExpr | bitExpr MOD_SYM bitExpr | bitExpr BIT_EXCLUSIVE_OR bitExpr //| bitExpr '+' interval_expr //| bitExpr '-' interval_expr | simpleExpr ; simpleExpr: functionCall | liter | ID | simpleExpr collateClause //| param_marker //| variable | simpleExpr AND_SYM simpleExpr | PLUS simpleExpr | MINUS simpleExpr | UNARY_BIT_COMPLEMENT simpleExpr | NOT_SYM simpleExpr | BINARY simpleExpr | LEFT_PAREN expr RIGHT_PAREN | ROW LEFT_PAREN simpleExpr( COMMA simpleExpr)* RIGHT_PAREN | subquery | EXISTS subquery // | (identifier expr) //| match_expr //| case_expr // | interval_expr |privateExprOfDb ; functionCall: ID LEFT_PAREN(bitExprs?) RIGHT_PAREN ; privateExprOfDb: matchNone ; liter: QUESTION |NUMBER |TRUE |FALSE |NULL |LEFT_BRACE ID STRING RIGHT_BRACE // |HEX_DIGIT |ID? STRING collateClause? |(DATE | TIME |TIMESTAMP)STRING |ID? BIT_NUM collateClause? ; subquery: matchNone ; collateClause: matchNone ; orderByClause: ORDER BY groupByItem (COMMA groupByItem)* ; groupByItem: (columnName | NUMBER |expr) (ASC|DESC)? ;
Modify functionCall support arithmetic operation
Modify functionCall support arithmetic operation
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
f85aa15aaa09d313c658c3a5e3b942d981ffaa2f
dsl-parser/src/main/antlr4/com/mattunderscore/specky/parser/Specky.g4
dsl-parser/src/main/antlr4/com/mattunderscore/specky/parser/Specky.g4
/* Copyright © 2016 Matthew Champion All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of mattunderscore.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHEW CHAMPION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ parser grammar Specky; options { tokenVocab=SpeckyLexer; } construction : CONSTRUCTOR | MUTABLE_BUILDER | IMMUTABLE_BUILDER ; default_value : DEFAULT ANYTHING ; typeParameters : OPEN_TYPE_PARAMETERS Identifier+ CLOSE_TYPE_PARAMETERS ; property : OPTIONAL? Identifier typeParameters? Identifier default_value? ; qualifiedName : Identifier (PACKAGE_SEPARATOR Identifier)* ; package_name : PACKAGE qualifiedName ; imports : IMPORT OPEN_BLOCK qualifiedName + CLOSE_BLOCK ; opts : OPTIONS OPEN_BLOCK construction? CLOSE_BLOCK ; implementationSpec : (VALUE | BEAN ) Identifier (EXTENDS Identifier)? OPEN_BLOCK (property)+ opts? CLOSE_BLOCK ; typeSpec : TYPE Identifier OPEN_BLOCK (property)* CLOSE_BLOCK ; spec : package_name imports? (typeSpec | implementationSpec)+ ;
/* Copyright © 2016 Matthew Champion All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of mattunderscore.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHEW CHAMPION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ parser grammar Specky; options { tokenVocab=SpeckyLexer; } construction : CONSTRUCTOR | MUTABLE_BUILDER | IMMUTABLE_BUILDER ; default_value : DEFAULT ANYTHING ; typeParameters : OPEN_TYPE_PARAMETERS Identifier+ CLOSE_TYPE_PARAMETERS ; property : OPTIONAL? Identifier typeParameters? Identifier default_value? ; qualifiedName : Identifier (PACKAGE_SEPARATOR Identifier)* ; package_name : PACKAGE qualifiedName ; imports : IMPORT OPEN_BLOCK qualifiedName + CLOSE_BLOCK ; opts : OPTIONS OPEN_BLOCK construction? CLOSE_BLOCK ; implementationSpec : (VALUE | BEAN ) Identifier (EXTENDS Identifier)? OPEN_BLOCK (property)* opts? CLOSE_BLOCK ; typeSpec : TYPE Identifier OPEN_BLOCK (property)* CLOSE_BLOCK ; spec : package_name imports? (typeSpec | implementationSpec)+ ;
Support empty bean and value specs.
Support empty bean and value specs.
ANTLR
bsd-3-clause
mattunderscorechampion/specky,mattunderscorechampion/specky,mattunderscorechampion/specky
44a997ac3c20378fd1cfe13393d602fbf08e5dec
algol60/algol60.g4
algol60/algol60.g4
grammar algol60; // Derived from the authoratitive source ISO 1538 // You can download a free copy at: // http://www.softwarepreservation.org/projects/ALGOL/report/ISO1538.pdf // The spec, typical for most grammars at the time, do not distinguish // BNF between the lexer and parser. The rules are divided here as: // // TBD // 1.1 empty : ; fragment Basic_symbol : Letter | Digit | Logical_value_f | Delimiter ; // The alphabet can be extended in any way. // If memory serves me, I recall no case sensitivity. Array_ : [aA] [rR] [rR] [aA] [yY] ; Begin_ : [bB] [eE] [gG] [iI] [nN] ; Boolean_ : [bB] [oO] [oO] [lL] [eE] [aA] [nN] ; Comment_ : [cC] [oO] [mM] [mM] [eE] [nN] [tT] ; Do_ : [dD] [oO] ; Else_ : [eE] [lL] [sS] [eE] ; End_ : [eE] [nN] [dD] ; False_ : [fF] [aA] [lL] [sS] [eE] ; For_ : [fF] [oO] [rR] ; Goto_ : [gG] [oO] Ws* [tT] [oO] ; If_ : [iI] [fF] ; Integer_ : [iI] [nN] [tT] [eE] [gG] [eE] [rR] ; Label_ : [lL] [aA] [bB] [eE] [lL] ; Own_ : [oO] [wW] [nN] ; Procedure_ : [pP] [rR] [oO] [cC] [eE] [dD] [uU] [rR] [eE] ; Real_ : [rR] [eE] [aA] [lL] ; Step_ : [sS] [tT] [eE] [pP] ; String_ : [sS] [tT] [rR] [iI] [nN] [gG] ; Switch_ : [sS] [wW] [iI] [tT] [cC] [hH] ; Then_ : [tT] [hH] [eE] [nN] ; True_ : [tT] [rR] [uU] [eE] ; Until_ : [uU] [nN] [tT] [iI] [lL] ; Value_ : [vV] [aA] [lL] [uU] [eE] ; While_ : [wW] [hH] [iI] [lL] [eE] ; And_ : '⋀' | '&' ; // '⊃' | ∧ | '⋀' Assign_ : ':=' ; Colon_ : ':' ; Comma_ : ',' ; Dot_ : '.' ; Divide_ : '/' | '÷' ; Eor_ : '^=' ; Eq_ : '=' ; Equiv_ : '≡' ; Exp_ : '↑' | '^' ; Gt_ : '>' ; Ge_ : '≥' | '>=' ; Includes_ : '⊃' ; Lb_ : '[' ; Le_ : '<=' | '≤' ; LP_ : '(' ; Lt_ : '<' ; Minus_ : '-' | '–'; Mult_ : '×' | '*' ; Ne_ : '≠' | '!=' ; Not_ : '¬' | '!' ; Or_ : '⋁' | '|' ; Plus_ : '+' ; Rb_ : ']' ; Rp_ : ')' ; Semi_ : ';' ; Times_ : '×' | '*' ; Underscore_ : '_' ; // 2.1 fragment Letter : 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z' | '_' // an extension. ; // 2.2.1 fragment Digit : '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' ; fragment ULCorner_f : '\u231C' ; ULCorner : ULCorner_f ; fragment URCorner_f : '\u231D' ; URCorner : URCorner_f ; // 2.2.2 fragment Logical_value_f : True_ | False_ ; Logical_value : Logical_value_f ; // 2.3 fragment Delimiter : Operator | Separator | Bracket | Declarator | Specificator ; fragment Operator : Arithmetic_operator | Relational_operator_f | Logical_operator | Sequential_operator ; fragment Arithmetic_operator : Plus_ | Minus_ | Times_ | Divide_ | Exp_ ; fragment Relational_operator_f : Lt_ | Le_ | Eq_ | Ne_ | Gt_ | Ge_ ; Relational_operator : Relational_operator_f ; fragment Logical_operator : Equiv_ | Includes_ | Or_ | And_ | Not_ ; fragment Sequential_operator : Goto_ | If_ | Then_ | Else_ | For_ | Do_ ; fragment Separator : Comma_ | Dot_ | '10' | Colon_ | Semi_ | Assign_ | Underscore_ | Step_ | Until_ | While_ | Comment_ ; fragment Bracket : LP_ | Rp_ | Lb_ | Rb_ | '⌈' | '⌝' | Begin_ | End_ ; fragment Declarator : Own_ | Boolean_ | Integer_ | Real_ | Array_ | Switch_ | Procedure_ ; fragment Specificator : String_ | Label_ | Value_ ; // Antlr restriction cannot use ~Semi_. Comment : Comment_ (~';')+ Semi_ -> channel(HIDDEN) ; // 2.4.1 // rewritten to avoid MLR. Identifier : (Letter | Digit)+ ; // 2.5.1 // rewritten to avoid MLR. Unsigned_integer : Digit+ ; integer : Unsigned_integer | Plus_ Unsigned_integer | Minus_ Unsigned_integer ; Decimal_fraction : Dot_ Unsigned_integer ; // unfold Exponential_part : '10' (Unsigned_integer | Plus_ Unsigned_integer | Minus_ Unsigned_integer) ; Decimal_number : Unsigned_integer | Decimal_fraction | Unsigned_integer Decimal_fraction ; Unsigned_number : Decimal_number | Exponential_part | Decimal_number Exponential_part ; number : Unsigned_number | Plus_ Unsigned_number | Minus_ Unsigned_number ; // 2.6.1 fragment Proper_string : (~('\u231C' | '\u231D'))+ ; // rewritten to avoid MLR. fragment Open_string : Proper_string? (ULCorner Open_string URCorner)+ ; fragment Closed_string : ULCorner Open_string URCorner ; String : Closed_string+ | '"' ~'"'* '"' | '`' ~'\''* '\'' ; // 3 expression : arithmetic_expression | boolean_expression | designational_expression ; // 3.1 variable_identifier : Identifier ; simple_variable : variable_identifier ; subscript_expression : arithmetic_expression ; subscript_list : subscript_expression | subscript_list Comma_ subscript_expression ; array_identifier : Identifier ; subscripted_variable : array_identifier Lb_ subscript_list Rb_ ; variable : simple_variable | subscripted_variable ; // 3.2.1 procedure_identifier : Identifier ; // The following rules replaced because there is no context sensitive lexing. //letter_string : letter | letter_string letter ; //parameter_delimiter : Comma_ | Rp_ letter_string Colon_ LP_ ; parameter_delimiter : Comma_ | Rp_ Identifier Colon_ LP_ ; actual_parameter : String | expression | array_identifier | switch_identifier | procedure_identifier ; actual_parameter_list : actual_parameter | actual_parameter_list parameter_delimiter actual_parameter ; function_designator : procedure_identifier actual_parameter_part ; // 3.3.1 adding_operator : Plus_ | Minus_ ; multiplying_operator : Mult_ | Divide_ ; primary : Unsigned_number | variable | function_designator | LP_ arithmetic_expression Rp_ ; factor : primary | factor Exp_ primary ; term : factor | term multiplying_operator factor ; simple_arithmetic_expression : term | adding_operator term | simple_arithmetic_expression adding_operator term ; if_clause : If_ boolean_expression Then_ ; arithmetic_expression : simple_arithmetic_expression | if_clause simple_arithmetic_expression Else_ arithmetic_expression ; // 3.4.1 // dup relational_operator. relation : simple_arithmetic_expression Relational_operator simple_arithmetic_expression ; boolean_primary : Logical_value | variable | function_designator | relation | LP_ boolean_expression Rp_ ; boolean_secondary : boolean_primary | Not_ boolean_primary ; boolean_factor : boolean_secondary | boolean_factor And_ boolean_secondary ; boolean_term : boolean_factor | boolean_term Or_ boolean_factor ; implication : boolean_term | implication Includes_ boolean_term ; simple_boolean : implication | simple_boolean Equiv_ implication ; boolean_expression : simple_boolean | if_clause simple_boolean Else_ boolean_expression ; // 3.5.1 label : Identifier | Unsigned_integer ; switch_identifier : Identifier ; switch_designator : switch_identifier Lb_ subscript_expression Rb_ ; simple_designational_expression : label | switch_designator | LP_ designational_expression Rp_ ; designational_expression : simple_designational_expression | if_clause simple_designational_expression Else_ designational_expression ; // 4.1.1 unlabelled_basic_statement : assignment_statement | go_to_statement | dummy_statement | procedure_statement ; basic_statement : unlabelled_basic_statement | label Colon_ basic_statement ; unconditional_statement : basic_statement | compound_statement | block ; statement : unconditional_statement | conditional_statement | for_statement ; compound_tail : statement End_ | statement Semi_ compound_tail ; block_head : Begin_ declaration | block_head Semi_ declaration ; unlabelled_compound : Begin_ compound_tail ; unlabelled_block : block_head Semi_ compound_tail ; compound_statement : unlabelled_compound | label Colon_ compound_statement ; block : unlabelled_block | label Colon_ block ; program : (block | compound_statement) EOF ; // 4.2.1 destination : variable | procedure_identifier ; left_part : variable Assign_ | procedure_identifier Assign_ ; left_part_list : left_part | left_part_list left_part ; assignment_statement : left_part_list arithmetic_expression | left_part_list boolean_expression ; // 4.3.1 go_to_statement : Goto_ designational_expression ; // 4.4.1 dummy_statement : empty ; // 4.5.1 // dup if_clause // dup unconditional statement if_statement : if_clause unconditional_statement ; conditional_statement : if_statement | if_statement Else_ statement | if_clause for_statement | label Colon_ conditional_statement ; // 4.6.1 for_list_element : arithmetic_expression | arithmetic_expression Step_ arithmetic_expression Until_ arithmetic_expression | arithmetic_expression While_ boolean_expression ; for_list : for_list_element | for_list Comma_ for_list_element ; for_clause : For_ variable Assign_ for_list Do_ ; for_statement : for_clause statement | label Colon_ for_statement ; // 4.7.1 // dup actual_parameter // dup letter_string // dup parameter_delimiter // dup actual_parameter_list actual_parameter_part : empty | LP_ actual_parameter_list Rp_ ; procedure_statement : procedure_identifier actual_parameter_part ; // 4.7.8 code : .* ; // match anything. // 5 declaration : type_declaration | array_declaration | switch_declaration | procedure_declaration ; // 5.1.1 type_list : simple_variable | simple_variable Comma_ type_list ; type : Real_ | Integer_ | Boolean_ ; local_or_own : empty | Own_ ; type_declaration : local_or_own type type_list ; // 5.2.1 lower_bound : arithmetic_expression ; upper_bound : arithmetic_expression ; bound_pair : lower_bound Colon_ upper_bound ; bound_pair_list : bound_pair | bound_pair_list Comma_ bound_pair ; array_segment : array_identifier Lb_ bound_pair_list Rb_ | array_identifier Comma_ array_segment ; array_list : array_segment | array_list Comma_ array_segment ; array_declarer : type Array_ | Array_ ; array_declaration : local_or_own array_declarer array_list ; // 5.3.1 switch_list : designational_expression | switch_list Comma_ designational_expression ; switch_declaration : Switch_ switch_identifier Assign_ switch_list ; // 5.4.1 formal_parameter : Identifier ; formal_parameter_list : formal_parameter | formal_parameter_list parameter_delimiter formal_parameter ; formal_parameter_part : empty | LP_ formal_parameter_list Rp_ ; identifier_list : Identifier | identifier_list Comma_ Identifier ; value_part : Value_ identifier_list Semi_ | empty ; specifier : String_ | type | Array_ | type Array_ | Label_ | Switch_ | Procedure_ | type Procedure_ ; specification_part : empty | specifier identifier_list Semi_ | specification_part specifier identifier_list ; procedure_heading : procedure_identifier formal_parameter_part Semi_ value_part specification_part ; procedure_body : statement | code ; procedure_declaration : Procedure_ procedure_heading procedure_body | type Procedure_ procedure_heading procedure_body ; WS : Ws -> channel(HIDDEN) ; fragment Ws : [ \r\n\t]+ ;
grammar algol60; // Derived from the authoratitive source ISO 1538 // You can download a free copy at: // http://www.softwarepreservation.org/projects/ALGOL/report/ISO1538.pdf // The spec, typical for most grammars at the time, do not distinguish // BNF between the lexer and parser. The rules are divided here as: // // TBD // 1.1 empty : ; fragment Basic_symbol : Letter | Digit | Logical_value_f | Delimiter ; // The alphabet can be extended in any way. // If memory serves me, I recall no case sensitivity. Array_ : [aA] [rR] [rR] [aA] [yY] ; Begin_ : [bB] [eE] [gG] [iI] [nN] ; Boolean_ : [bB] [oO] [oO] [lL] [eE] [aA] [nN] ; Comment_ : [cC] [oO] [mM] [mM] [eE] [nN] [tT] ; Do_ : [dD] [oO] ; Else_ : [eE] [lL] [sS] [eE] ; End_ : [eE] [nN] [dD] ; False_ : [fF] [aA] [lL] [sS] [eE] ; For_ : [fF] [oO] [rR] ; Goto_ : [gG] [oO] Ws* [tT] [oO] ; If_ : [iI] [fF] ; Integer_ : [iI] [nN] [tT] [eE] [gG] [eE] [rR] ; Label_ : [lL] [aA] [bB] [eE] [lL] ; Own_ : [oO] [wW] [nN] ; Procedure_ : [pP] [rR] [oO] [cC] [eE] [dD] [uU] [rR] [eE] ; Real_ : [rR] [eE] [aA] [lL] ; Step_ : [sS] [tT] [eE] [pP] ; String_ : [sS] [tT] [rR] [iI] [nN] [gG] ; Switch_ : [sS] [wW] [iI] [tT] [cC] [hH] ; Then_ : [tT] [hH] [eE] [nN] ; True_ : [tT] [rR] [uU] [eE] ; Until_ : [uU] [nN] [tT] [iI] [lL] ; Value_ : [vV] [aA] [lL] [uU] [eE] ; While_ : [wW] [hH] [iI] [lL] [eE] ; And_ : '⋀' | '&' ; // '⊃' | ∧ | '⋀' Assign_ : ':=' ; Colon_ : ':' ; Comma_ : ',' ; Dot_ : '.' ; Divide_ : '/' | '÷' ; Eor_ : '^=' ; Eq_ : '=' ; Equiv_ : '≡' ; Exp_ : '↑' | '^' ; Gt_ : '>' ; Ge_ : '≥' | '>=' ; Includes_ : '⊃' ; Lb_ : '[' ; Le_ : '<=' | '≤' ; LP_ : '(' ; Lt_ : '<' ; Minus_ : '-' | '–'; Mult_ : '×' | '*' ; Ne_ : '≠' | '!=' ; Not_ : '¬' | '!' ; Or_ : '⋁' | '|' ; Plus_ : '+' ; Rb_ : ']' ; Rp_ : ')' ; Semi_ : ';' ; Underscore_ : '_' ; // 2.1 fragment Letter : 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z' | '_' // an extension. ; // 2.2.1 fragment Digit : '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' ; fragment ULCorner_f : '\u231C' ; ULCorner : ULCorner_f ; fragment URCorner_f : '\u231D' ; URCorner : URCorner_f ; // 2.2.2 fragment Logical_value_f : True_ | False_ ; Logical_value : Logical_value_f ; // 2.3 fragment Delimiter : Operator | Separator | Bracket | Declarator | Specificator ; fragment Operator : Arithmetic_operator | Relational_operator_f | Logical_operator | Sequential_operator ; fragment Arithmetic_operator : Plus_ | Minus_ | Mult_ | Divide_ | Exp_ ; fragment Relational_operator_f : Lt_ | Le_ | Eq_ | Ne_ | Gt_ | Ge_ ; Relational_operator : Relational_operator_f ; fragment Logical_operator : Equiv_ | Includes_ | Or_ | And_ | Not_ ; fragment Sequential_operator : Goto_ | If_ | Then_ | Else_ | For_ | Do_ ; fragment Separator : Comma_ | Dot_ | '10' | Colon_ | Semi_ | Assign_ | Underscore_ | Step_ | Until_ | While_ | Comment_ ; fragment Bracket : LP_ | Rp_ | Lb_ | Rb_ | '⌈' | '⌝' | Begin_ | End_ ; fragment Declarator : Own_ | Boolean_ | Integer_ | Real_ | Array_ | Switch_ | Procedure_ ; fragment Specificator : String_ | Label_ | Value_ ; // Antlr restriction cannot use ~Semi_. Comment : Comment_ (~';')+ Semi_ -> channel(HIDDEN) ; // 2.4.1 // rewritten to avoid MLR. Identifier : (Letter | Digit)+ ; // 2.5.1 // rewritten to avoid MLR. Unsigned_integer : Digit+ ; integer : Unsigned_integer | Plus_ Unsigned_integer | Minus_ Unsigned_integer ; Decimal_fraction : Dot_ Unsigned_integer ; // unfold Exponential_part : '10' (Unsigned_integer | Plus_ Unsigned_integer | Minus_ Unsigned_integer) ; Decimal_number : Unsigned_integer | Decimal_fraction | Unsigned_integer Decimal_fraction ; Unsigned_number : Decimal_number | Exponential_part | Decimal_number Exponential_part ; number : Unsigned_number | Plus_ Unsigned_number | Minus_ Unsigned_number ; // 2.6.1 fragment Proper_string : (~('\u231C' | '\u231D'))* ; fragment Open_string : Proper_string | Proper_string Closed_string Open_string ; fragment Closed_string : ULCorner Open_string URCorner ; fragment StdString : Closed_string | Closed_string StdString ; String : StdString // String according to spec. | '"' ~'"'* '"' | '`' ~'\''* '\'' ; // Additional non-standard strings used in examples. // 3 expression : arithmetic_expression | boolean_expression | designational_expression ; // 3.1 variable_identifier : Identifier ; simple_variable : variable_identifier ; subscript_expression : arithmetic_expression ; subscript_list : subscript_expression | subscript_list Comma_ subscript_expression ; array_identifier : Identifier ; subscripted_variable : array_identifier Lb_ subscript_list Rb_ ; variable : simple_variable | subscripted_variable ; // 3.2.1 procedure_identifier : Identifier ; // The following rules replaced because there is no context sensitive lexing. //letter_string : letter | letter_string letter ; //parameter_delimiter : Comma_ | Rp_ letter_string Colon_ LP_ ; parameter_delimiter : Comma_ | Rp_ Identifier Colon_ LP_ ; actual_parameter : String | expression | array_identifier | switch_identifier | procedure_identifier ; actual_parameter_list : actual_parameter | actual_parameter_list parameter_delimiter actual_parameter ; function_designator : procedure_identifier actual_parameter_part ; // 3.3.1 adding_operator : Plus_ | Minus_ ; multiplying_operator : Mult_ | Divide_ ; primary : Unsigned_number | variable | function_designator | LP_ arithmetic_expression Rp_ ; factor : primary | factor Exp_ primary ; term : factor | term multiplying_operator factor ; simple_arithmetic_expression : term | adding_operator term | simple_arithmetic_expression adding_operator term ; if_clause : If_ boolean_expression Then_ ; arithmetic_expression : simple_arithmetic_expression | if_clause simple_arithmetic_expression Else_ arithmetic_expression ; // 3.4.1 // dup relational_operator. relation : simple_arithmetic_expression Relational_operator simple_arithmetic_expression ; boolean_primary : Logical_value | variable | function_designator | relation | LP_ boolean_expression Rp_ ; boolean_secondary : boolean_primary | Not_ boolean_primary ; boolean_factor : boolean_secondary | boolean_factor And_ boolean_secondary ; boolean_term : boolean_factor | boolean_term Or_ boolean_factor ; implication : boolean_term | implication Includes_ boolean_term ; simple_boolean : implication | simple_boolean Equiv_ implication ; boolean_expression : simple_boolean | if_clause simple_boolean Else_ boolean_expression ; // 3.5.1 label : Identifier | Unsigned_integer ; switch_identifier : Identifier ; switch_designator : switch_identifier Lb_ subscript_expression Rb_ ; simple_designational_expression : label | switch_designator | LP_ designational_expression Rp_ ; designational_expression : simple_designational_expression | if_clause simple_designational_expression Else_ designational_expression ; // 4.1.1 unlabelled_basic_statement : assignment_statement | go_to_statement | dummy_statement | procedure_statement ; basic_statement : unlabelled_basic_statement | label Colon_ basic_statement ; unconditional_statement : basic_statement | compound_statement | block ; statement : unconditional_statement | conditional_statement | for_statement ; compound_tail : statement End_ | statement Semi_ compound_tail ; block_head : Begin_ declaration | block_head Semi_ declaration ; unlabelled_compound : Begin_ compound_tail ; unlabelled_block : block_head Semi_ compound_tail ; compound_statement : unlabelled_compound | label Colon_ compound_statement ; block : unlabelled_block | label Colon_ block ; program : (block | compound_statement) EOF ; // 4.2.1 destination : variable | procedure_identifier ; left_part : variable Assign_ | procedure_identifier Assign_ ; left_part_list : left_part | left_part_list left_part ; assignment_statement : left_part_list arithmetic_expression | left_part_list boolean_expression ; // 4.3.1 go_to_statement : Goto_ designational_expression ; // 4.4.1 dummy_statement : empty ; // 4.5.1 // dup if_clause // dup unconditional statement if_statement : if_clause unconditional_statement ; conditional_statement : if_statement | if_statement Else_ statement | if_clause for_statement | label Colon_ conditional_statement ; // 4.6.1 for_list_element : arithmetic_expression | arithmetic_expression Step_ arithmetic_expression Until_ arithmetic_expression | arithmetic_expression While_ boolean_expression ; for_list : for_list_element | for_list Comma_ for_list_element ; for_clause : For_ variable Assign_ for_list Do_ ; for_statement : for_clause statement | label Colon_ for_statement ; // 4.7.1 // dup actual_parameter // dup letter_string // dup parameter_delimiter // dup actual_parameter_list actual_parameter_part : empty | LP_ actual_parameter_list Rp_ ; procedure_statement : procedure_identifier actual_parameter_part ; // 4.7.8 code : .* ; // match anything. // 5 declaration : type_declaration | array_declaration | switch_declaration | procedure_declaration ; // 5.1.1 type_list : simple_variable | simple_variable Comma_ type_list ; type : Real_ | Integer_ | Boolean_ ; local_or_own : empty | Own_ ; type_declaration : local_or_own type type_list ; // 5.2.1 lower_bound : arithmetic_expression ; upper_bound : arithmetic_expression ; bound_pair : lower_bound Colon_ upper_bound ; bound_pair_list : bound_pair | bound_pair_list Comma_ bound_pair ; array_segment : array_identifier Lb_ bound_pair_list Rb_ | array_identifier Comma_ array_segment ; array_list : array_segment | array_list Comma_ array_segment ; array_declarer : type Array_ | Array_ ; array_declaration : local_or_own array_declarer array_list ; // 5.3.1 switch_list : designational_expression | switch_list Comma_ designational_expression ; switch_declaration : Switch_ switch_identifier Assign_ switch_list ; // 5.4.1 formal_parameter : Identifier ; formal_parameter_list : formal_parameter | formal_parameter_list parameter_delimiter formal_parameter ; formal_parameter_part : empty | LP_ formal_parameter_list Rp_ ; identifier_list : Identifier | identifier_list Comma_ Identifier ; value_part : Value_ identifier_list Semi_ | empty ; specifier : String_ | type | Array_ | type Array_ | Label_ | Switch_ | Procedure_ | type Procedure_ ; specification_part : empty | specifier identifier_list Semi_ | specification_part specifier identifier_list ; procedure_heading : procedure_identifier formal_parameter_part Semi_ value_part specification_part ; procedure_body : statement | code ; procedure_declaration : Procedure_ procedure_heading procedure_body | type Procedure_ procedure_heading procedure_body ; WS : Ws -> channel(HIDDEN) ; fragment Ws : [ \r\n\t]+ ;
Fix String, Open_string, Closed_string, and recursion.
Fix String, Open_string, Closed_string, and recursion.
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
e7781986cd378f26a4a2a9cb09ff98b7b57e8cdd
pymola/Modelica.g4
pymola/Modelica.g4
grammar Modelica; //========================================================= // B.2.1 Stored Definition - Within //========================================================= // B.2.1.1 ------------------------------------------------ stored_definition : (WITHIN component_reference? ';')? (stored_definition_class)* ; stored_definition_class : FINAL? class_definition ';' ; //========================================================= // B.2.2 Class Definition //========================================================= // B.2.2.1 ------------------------------------------------ class_definition : ENCAPSULATED? class_prefixes class_specifier ; // B.2.2.2 ------------------------------------------------ class_prefixes : PARTIAL? class_type ; class_type: 'class' | 'model' | 'operator'? 'record' | 'block' | 'expandable'? 'connector' | 'type' | 'package' | ('pure' | 'impure')? 'operator'? 'function' | 'operator' ; // B.2.2.3 ------------------------------------------------ class_specifier : IDENT string_comment composition 'end' IDENT # class_spec_comp | IDENT '=' base_prefix name array_subscripts? class_modification? comment # class_spec_base | IDENT '=' 'enumeration' '(' (enum_list? | ':') ')' comment # class_spec_enum | IDENT '=' 'der' '(' name ',' IDENT (',' IDENT )* ')' comment # class_spec_der | 'extends' IDENT class_modification? string_comment composition 'end' IDENT # class_spec_extends ; // B.2.2.4 ------------------------------------------------ base_prefix : type_prefix ; // B.2.2.5 ------------------------------------------------ enum_list : enumeration_literal (',' enumeration_literal)* ; // B.2.2.6 ------------------------------------------------ enumeration_literal : IDENT comment ; // B.2.2.7 ------------------------------------------------ composition : epriv=element_list ( 'public' epub=element_list | 'protected' epro=element_list | equation_section | algorithm_section )* ( 'external' language_specification? external_function_call? ext_annotation=annotation? ':')? (comp_annotation=annotation ';')? ; // B.2.2.8 ------------------------------------------------ language_specification : STRING ; // B.2.2.9 ------------------------------------------------ external_function_call : (component_reference '=')? IDENT '(' expression_list? ')' ; // B.2.2.10 ------------------------------------------------ element_list : (element ';')* ; // B.2.2.11 ------------------------------------------------ element : import_clause | extends_clause | regular_element | replaceable_element ; regular_element: REDECLARE? FINAL? INNER? OUTER? (class_elem=class_definition | comp_elem=component_clause) ; replaceable_element: REDECLARE? FINAL? INNER? OUTER? 'replaceable' (class_elem=class_definition | comp_elem=component_clause) (constraining_clause comment)? ; // B.2.2.12 ------------------------------------------------ import_clause : 'import' ( IDENT '=' component_reference | component_reference ('.' ( '*' | '{' import_list '}' ) )? ) comment ; // B.2.2.13 ------------------------------------------------ import_list : IDENT (',' import_list)* ; //========================================================= // B.2.3 Extends //========================================================= // B.2.3.1 ------------------------------------------------ extends_clause : 'extends' component_reference class_modification? annotation? ; // B.2.3.2 ------------------------------------------------ constraining_clause: 'constrainedby' name class_modification? ; //========================================================= // B.2.4 Component Clause //========================================================= // B.2.4.1 ------------------------------------------------ component_clause : type_prefix type_specifier array_subscripts? component_list ; // B.2.4.2 ------------------------------------------------ type_prefix : ('flow' | 'stream')? ('discrete' | 'parameter' | 'constant')? ('input' | 'output')? ; // B.2.4.3 ------------------------------------------------ type_specifier: component_reference ; // B.2.4.4 ------------------------------------------------ component_list: component_declaration ( ',' component_declaration)* ; // B.2.4.5 ------------------------------------------------ component_declaration : declaration condition_attribute? comment ; // B.2.4.6 ------------------------------------------------ condition_attribute : 'if' expression ; // B.2.4.7 ------------------------------------------------ declaration : IDENT array_subscripts? modification? ; //========================================================= // B.2.5 Modification //========================================================= // B.2.5.1 ------------------------------------------------ modification : class_modification ('=' expression)? # modification_class | '=' expression # modification_asesignment | ':=' expression # modification_assignment2 ; // B.2.5.2 ------------------------------------------------ class_modification : '(' argument_list? ')' ; // B.2.5.3 ------------------------------------------------ argument_list : argument (',' argument)* ; // B.2.5.4 ------------------------------------------------ argument : element_modification_or_replaceable | element_redeclaration ; // B.2.5.5 ------------------------------------------------ element_modification_or_replaceable: EACH? FINAL? (element_modification | element_replaceable) ; // B.2.5.6 ------------------------------------------------ element_modification : component_reference modification? string_comment ; // B.2.5.7 ------------------------------------------------ element_redeclaration : REDECLARE EACH? FINAL? ( (short_class_definition | component_clause1) | element_replaceable) ; // B.2.5.8 ------------------------------------------------ element_replaceable : 'replaceable' (short_class_definition | component_clause1) constraining_clause? ; // B.2.5.9 ------------------------------------------------ component_clause1 : type_prefix type_specifier component_declaration1 ; // B.2.5.10 ------------------------------------------------ component_declaration1 : declaration comment ; // B.2.5.11 ------------------------------------------------ short_class_definition : class_prefixes IDENT '=' ( base_prefix component_reference array_subscripts? class_modification? comment | 'enumeration' '(' (enum_list? | ':') ')' comment) ; //========================================================= // B.2.6 Equations //========================================================= // B.2.6.1 ------------------------------------------------ equation_section : INITIAL? 'equation' (equation ';')* ; // B.2.6.2 ------------------------------------------------ algorithm_section : INITIAL? 'algorithm' (statement ';')* ; // B.2.6.3 ------------------------------------------------ equation_options : simple_expression '=' expression # equation_simple | if_equation # equation_if | for_equation # equation_for | connect_clause # equation_connect_clause | when_equation # equation_when | name function_call_args # equation_function ; // B.2.6.4 ------------------------------------------------ equation : equation_options comment ; // B.2.6.5 ------------------------------------------------ statement_options : component_reference (':=' expression | function_call_args) # statement_component_reference | '(' component_reference (',' component_reference)* ')' ':=' component_reference function_call_args # statement_component_function | 'break' # statement_break | 'return' # statement_return | if_statement # statement_if | for_statement # statement_for | while_statement # statement_while | when_statement # statement_when ; // B.2.6.6 ------------------------------------------------ statement : statement_options comment ; // B.2.6.7 ------------------------------------------------ if_equation : 'if' expression 'then' (equation ';')* ('elseif' expression 'then' (equation ';')* )* ('else' (equation ';')* )? 'end' 'if' ; // B.2.6.8 ------------------------------------------------ if_statement : 'if' expression 'then' (statement ';')* ('elseif' expression 'then' (statement ';')* )* ('else' (statement ';')* )? 'end' 'if' ; // B.2.6.9 ------------------------------------------------ for_equation : 'for' for_indices 'loop' (equation ';')* 'end' 'for' ; // B.2.6.10 ------------------------------------------------ for_statement : 'for' for_indices 'loop' (statement ';')* 'end' 'for' ; // B.2.6.11 ------------------------------------------------ for_indices : for_index (',' for_index)* ; // B.2.6.12 ------------------------------------------------ for_index : IDENT ('in' expression)? ; // B.2.6.13 ------------------------------------------------ while_statement: 'while' expression 'loop' (statement ';')* 'end' 'while' ; // B.2.6.14 ------------------------------------------------ when_equation: 'when' expression 'then' (equation ';')* ('elsewhen' expression 'then' (equation ';')* )* 'end' 'when' ; // B.2.6.15 ------------------------------------------------ when_statement: 'when' expression 'then' (statement ';')* ('elsewhen' expression 'then' (statement ';')* )* 'end' 'when' ; // B.2.6.16 ------------------------------------------------ connect_clause : 'connect' '(' component_reference ',' component_reference ')' ; //========================================================= // B.2.7 Expressions //========================================================= // B.2.7.1 ------------------------------------------------ // TODO: What is the difference between expression and simple_expression? // Can't we get rid of one of them? expression : simple_expression # expression_simple | 'if' expression 'then' expression ( 'elseif' expression 'then' expression)* 'else' expression # expression_if ; // B.2.7.2 ------------------------------------------------ simple_expression : expr (':' expr (':' expr)?)? ; // B.2.7.3 ------------------------------------------------ expr : op='-' expr # expr_neg | primary op=('^' | '.^') primary # expr_exp | expr op=('*' | '/' | '.*' | './') expr # expr_mul | expr op=('+' | '-' | '.+' | '.-') expr # expr_add | expr op=('<' | '<=' | '>' | '>=' | '==' | '<>') expr # expr_rel | 'not' expr # expr_not | expr 'and' expr # expr_and | expr 'or' expr # expr_or | primary # expr_primary ; // B.2.7.4 ------------------------------------------------ // TODO: Figure out what an output_expression_list is (i.e. find an example). primary : UNSIGNED_NUMBER # primary_unsigned_number | STRING # primary_string | 'false' # primary_false | 'true' # primary_true | component_reference function_call_args # primary_function | 'der' function_call_args # primary_derivative | 'initial' function_call_args # primary_initial | component_reference # primary_component_reference | '(' output_expression_list ')' # primary_output_expression_list | '[' expression_list (';' expression_list)* ']' # primary_expression_list | '{' function_arguments '}' # primary_function_arguments | 'end' # primary_end ; // B.2.7.5 ------------------------------------------------ name : '.'? IDENT ('.' IDENT)* ; // B.2.7.6 ------------------------------------------------ component_reference_element : IDENT array_subscripts? ; component_reference : component_reference_element ('.' component_reference_element)* ; // B.2.7.7 ------------------------------------------------ function_call_args : '(' function_arguments? ')' ; // B.2.7.8 ------------------------------------------------ function_arguments : function_argument (',' function_argument | 'for' for_indices)* | named_arguments ; // B.2.7.9 ------------------------------------------------ named_arguments : named_argument (',' named_argument)* ; // B.2.7.10 ------------------------------------------------ named_argument : IDENT '=' function_argument ; // B.2.7.11 ------------------------------------------------ function_argument : 'function' name '(' named_arguments? ')' # argument_function | expression # argument_expression ; // B.2.7.12 ------------------------------------------------ output_expression_list : expression? (',' expression)* ; // B.2.7.13 ------------------------------------------------ expression_list : expression (',' expression)* ; // B.2.7.14 ------------------------------------------------ array_subscripts : '[' subscript (',' subscript)* ']' ; // B.2.7.15 ------------------------------------------------ subscript : ':' | expression ; // B.2.7.16 ------------------------------------------------ comment : string_comment annotation? ; // B.2.7.17 ------------------------------------------------ string_comment : (STRING ('+' STRING)*)? ; // B.2.7.18 ------------------------------------------------ annotation : 'annotation' class_modification ; //========================================================= // Keywords //========================================================= EACH : 'each'; PARTIAL : 'partial'; FINAL : 'final'; WITHIN : 'within'; ENCAPSULATED : 'encapsulated'; REDECLARE : 'redeclare'; INNER : 'inner'; OUTER : 'outer'; INITIAL : 'initial'; IDENT : NONDIGIT ( DIGIT | NONDIGIT )* | Q_IDENT; STRING : '"' ('\\"' | ~('"'))* '"'; //STRING : '"' (S_CHAR | S_ESCAPE | ' ')* '"'; UNSIGNED_NUMBER : UNSIGNED_INTEGER ( '.' UNSIGNED_NUMBER? )* ( [eE] [+-]? UNSIGNED_INTEGER)?; COMMENT : ('/' '/' .*? '\n' | '/*' .*? '*/') -> channel(HIDDEN) ; WS : [ \r\n\t]+ -> skip ; // toss out whitespace //========================================================= // Fragments //========================================================= fragment Q_IDENT : '\'' ( Q_CHAR | S_ESCAPE)+; fragment NONDIGIT : [_a-zA-Z]; fragment S_CHAR : [A-Za-z\u0000-\u00FF]; fragment Q_CHAR : NONDIGIT | DIGIT | [!#$%&()*+,-./:;<>=?@[\]^{}|! ]; fragment S_ESCAPE : ('\\\'' | '\\"' | '\\\\' | '\\?' | '\\b' | '\\f' | '\\n' | '\\r' | '\\t' | '\\v' | '\\a'); fragment DIGIT : [0-9]; fragment UNSIGNED_INTEGER : DIGIT+; // vi:ts=4:sw=4:expandtab:
grammar Modelica; //========================================================= // B.2.1 Stored Definition - Within //========================================================= // B.2.1.1 ------------------------------------------------ stored_definition : (WITHIN component_reference? ';')? (stored_definition_class)* ; stored_definition_class : FINAL? class_definition ';' ; //========================================================= // B.2.2 Class Definition //========================================================= // B.2.2.1 ------------------------------------------------ class_definition : ENCAPSULATED? class_prefixes class_specifier ; // B.2.2.2 ------------------------------------------------ class_prefixes : PARTIAL? class_type ; class_type: 'class' | 'model' | 'operator'? 'record' | 'block' | 'expandable'? 'connector' | 'type' | 'package' | ('pure' | 'impure')? 'operator'? 'function' | 'operator' ; // B.2.2.3 ------------------------------------------------ class_specifier : IDENT string_comment composition 'end' IDENT # class_spec_comp | IDENT '=' base_prefix name array_subscripts? class_modification? comment # class_spec_base | IDENT '=' 'enumeration' '(' (enum_list? | ':') ')' comment # class_spec_enum | IDENT '=' 'der' '(' name ',' IDENT (',' IDENT )* ')' comment # class_spec_der | 'extends' IDENT class_modification? string_comment composition 'end' IDENT # class_spec_extends ; // B.2.2.4 ------------------------------------------------ base_prefix : type_prefix ; // B.2.2.5 ------------------------------------------------ enum_list : enumeration_literal (',' enumeration_literal)* ; // B.2.2.6 ------------------------------------------------ enumeration_literal : IDENT comment ; // B.2.2.7 ------------------------------------------------ composition : epriv=element_list ( 'public' epub=element_list | 'protected' epro=element_list | equation_section | algorithm_section )* ( 'external' language_specification? external_function_call? ext_annotation=annotation? ':')? (comp_annotation=annotation ';')? ; // B.2.2.8 ------------------------------------------------ language_specification : STRING ; // B.2.2.9 ------------------------------------------------ external_function_call : (component_reference '=')? IDENT '(' expression_list? ')' ; // B.2.2.10 ------------------------------------------------ element_list : (element ';')* ; // B.2.2.11 ------------------------------------------------ element : import_clause | extends_clause | regular_element | replaceable_element ; regular_element: REDECLARE? FINAL? INNER? OUTER? (class_elem=class_definition | comp_elem=component_clause) ; replaceable_element: REDECLARE? FINAL? INNER? OUTER? 'replaceable' (class_elem=class_definition | comp_elem=component_clause) (constraining_clause comment)? ; // B.2.2.12 ------------------------------------------------ import_clause : 'import' ( IDENT '=' component_reference | component_reference ('.' ( '*' | '{' import_list '}' ) )? ) comment ; // B.2.2.13 ------------------------------------------------ import_list : IDENT (',' import_list)* ; //========================================================= // B.2.3 Extends //========================================================= // B.2.3.1 ------------------------------------------------ extends_clause : 'extends' component_reference class_modification? annotation? ; // B.2.3.2 ------------------------------------------------ constraining_clause: 'constrainedby' name class_modification? ; //========================================================= // B.2.4 Component Clause //========================================================= // B.2.4.1 ------------------------------------------------ component_clause : type_prefix type_specifier array_subscripts? component_list ; // B.2.4.2 ------------------------------------------------ type_prefix : ('flow' | 'stream')? ('discrete' | 'parameter' | 'constant')? ('input' | 'output')? ; // B.2.4.3 ------------------------------------------------ type_specifier: component_reference ; // B.2.4.4 ------------------------------------------------ component_list: component_declaration ( ',' component_declaration)* ; // B.2.4.5 ------------------------------------------------ component_declaration : declaration condition_attribute? comment ; // B.2.4.6 ------------------------------------------------ condition_attribute : 'if' expression ; // B.2.4.7 ------------------------------------------------ declaration : IDENT array_subscripts? modification? ; //========================================================= // B.2.5 Modification //========================================================= // B.2.5.1 ------------------------------------------------ modification : class_modification ('=' expression)? # modification_class | '=' expression # modification_assignment | ':=' expression # modification_assignment2 ; // B.2.5.2 ------------------------------------------------ class_modification : '(' argument_list? ')' ; // B.2.5.3 ------------------------------------------------ argument_list : argument (',' argument)* ; // B.2.5.4 ------------------------------------------------ argument : element_modification_or_replaceable | element_redeclaration ; // B.2.5.5 ------------------------------------------------ element_modification_or_replaceable: EACH? FINAL? (element_modification | element_replaceable) ; // B.2.5.6 ------------------------------------------------ element_modification : component_reference modification? string_comment ; // B.2.5.7 ------------------------------------------------ element_redeclaration : REDECLARE EACH? FINAL? ( (short_class_definition | component_clause1) | element_replaceable) ; // B.2.5.8 ------------------------------------------------ element_replaceable : 'replaceable' (short_class_definition | component_clause1) constraining_clause? ; // B.2.5.9 ------------------------------------------------ component_clause1 : type_prefix type_specifier component_declaration1 ; // B.2.5.10 ------------------------------------------------ component_declaration1 : declaration comment ; // B.2.5.11 ------------------------------------------------ short_class_definition : class_prefixes IDENT '=' ( base_prefix component_reference array_subscripts? class_modification? comment | 'enumeration' '(' (enum_list? | ':') ')' comment) ; //========================================================= // B.2.6 Equations //========================================================= // B.2.6.1 ------------------------------------------------ equation_section : INITIAL? 'equation' (equation ';')* ; // B.2.6.2 ------------------------------------------------ algorithm_section : INITIAL? 'algorithm' (statement ';')* ; // B.2.6.3 ------------------------------------------------ equation_options : simple_expression '=' expression # equation_simple | if_equation # equation_if | for_equation # equation_for | connect_clause # equation_connect_clause | when_equation # equation_when | name function_call_args # equation_function ; // B.2.6.4 ------------------------------------------------ equation : equation_options comment ; // B.2.6.5 ------------------------------------------------ statement_options : component_reference (':=' expression | function_call_args) # statement_component_reference | '(' component_reference (',' component_reference)* ')' ':=' component_reference function_call_args # statement_component_function | 'break' # statement_break | 'return' # statement_return | if_statement # statement_if | for_statement # statement_for | while_statement # statement_while | when_statement # statement_when ; // B.2.6.6 ------------------------------------------------ statement : statement_options comment ; // B.2.6.7 ------------------------------------------------ if_equation : 'if' expression 'then' (equation ';')* ('elseif' expression 'then' (equation ';')* )* ('else' (equation ';')* )? 'end' 'if' ; // B.2.6.8 ------------------------------------------------ if_statement : 'if' expression 'then' (statement ';')* ('elseif' expression 'then' (statement ';')* )* ('else' (statement ';')* )? 'end' 'if' ; // B.2.6.9 ------------------------------------------------ for_equation : 'for' for_indices 'loop' (equation ';')* 'end' 'for' ; // B.2.6.10 ------------------------------------------------ for_statement : 'for' for_indices 'loop' (statement ';')* 'end' 'for' ; // B.2.6.11 ------------------------------------------------ for_indices : for_index (',' for_index)* ; // B.2.6.12 ------------------------------------------------ for_index : IDENT ('in' expression)? ; // B.2.6.13 ------------------------------------------------ while_statement: 'while' expression 'loop' (statement ';')* 'end' 'while' ; // B.2.6.14 ------------------------------------------------ when_equation: 'when' expression 'then' (equation ';')* ('elsewhen' expression 'then' (equation ';')* )* 'end' 'when' ; // B.2.6.15 ------------------------------------------------ when_statement: 'when' expression 'then' (statement ';')* ('elsewhen' expression 'then' (statement ';')* )* 'end' 'when' ; // B.2.6.16 ------------------------------------------------ connect_clause : 'connect' '(' component_reference ',' component_reference ')' ; //========================================================= // B.2.7 Expressions //========================================================= // B.2.7.1 ------------------------------------------------ // TODO: What is the difference between expression and simple_expression? // Can't we get rid of one of them? expression : simple_expression # expression_simple | 'if' expression 'then' expression ( 'elseif' expression 'then' expression)* 'else' expression # expression_if ; // B.2.7.2 ------------------------------------------------ simple_expression : expr (':' expr (':' expr)?)? ; // B.2.7.3 ------------------------------------------------ expr : op='-' expr # expr_neg | primary op=('^' | '.^') primary # expr_exp | expr op=('*' | '/' | '.*' | './') expr # expr_mul | expr op=('+' | '-' | '.+' | '.-') expr # expr_add | expr op=('<' | '<=' | '>' | '>=' | '==' | '<>') expr # expr_rel | 'not' expr # expr_not | expr 'and' expr # expr_and | expr 'or' expr # expr_or | primary # expr_primary ; // B.2.7.4 ------------------------------------------------ // TODO: Figure out what an output_expression_list is (i.e. find an example). primary : UNSIGNED_NUMBER # primary_unsigned_number | STRING # primary_string | 'false' # primary_false | 'true' # primary_true | component_reference function_call_args # primary_function | 'der' function_call_args # primary_derivative | 'initial' function_call_args # primary_initial | component_reference # primary_component_reference | '(' output_expression_list ')' # primary_output_expression_list | '[' expression_list (';' expression_list)* ']' # primary_expression_list | '{' function_arguments '}' # primary_function_arguments | 'end' # primary_end ; // B.2.7.5 ------------------------------------------------ name : '.'? IDENT ('.' IDENT)* ; // B.2.7.6 ------------------------------------------------ component_reference_element : IDENT array_subscripts? ; component_reference : component_reference_element ('.' component_reference_element)* ; // B.2.7.7 ------------------------------------------------ function_call_args : '(' function_arguments? ')' ; // B.2.7.8 ------------------------------------------------ function_arguments : function_argument (',' function_argument | 'for' for_indices)* | named_arguments ; // B.2.7.9 ------------------------------------------------ named_arguments : named_argument (',' named_argument)* ; // B.2.7.10 ------------------------------------------------ named_argument : IDENT '=' function_argument ; // B.2.7.11 ------------------------------------------------ function_argument : 'function' name '(' named_arguments? ')' # argument_function | expression # argument_expression ; // B.2.7.12 ------------------------------------------------ output_expression_list : expression? (',' expression)* ; // B.2.7.13 ------------------------------------------------ expression_list : expression (',' expression)* ; // B.2.7.14 ------------------------------------------------ array_subscripts : '[' subscript (',' subscript)* ']' ; // B.2.7.15 ------------------------------------------------ subscript : ':' | expression ; // B.2.7.16 ------------------------------------------------ comment : string_comment annotation? ; // B.2.7.17 ------------------------------------------------ string_comment : (STRING ('+' STRING)*)? ; // B.2.7.18 ------------------------------------------------ annotation : 'annotation' class_modification ; //========================================================= // Keywords //========================================================= EACH : 'each'; PARTIAL : 'partial'; FINAL : 'final'; WITHIN : 'within'; ENCAPSULATED : 'encapsulated'; REDECLARE : 'redeclare'; INNER : 'inner'; OUTER : 'outer'; INITIAL : 'initial'; IDENT : NONDIGIT ( DIGIT | NONDIGIT )* | Q_IDENT; STRING : '"' ('\\"' | ~('"'))* '"'; //STRING : '"' (S_CHAR | S_ESCAPE | ' ')* '"'; UNSIGNED_NUMBER : UNSIGNED_INTEGER ( '.' UNSIGNED_NUMBER? )* ( [eE] [+-]? UNSIGNED_INTEGER)?; COMMENT : ('/' '/' .*? '\n' | '/*' .*? '*/') -> channel(HIDDEN) ; WS : [ \r\n\t]+ -> skip ; // toss out whitespace //========================================================= // Fragments //========================================================= fragment Q_IDENT : '\'' ( Q_CHAR | S_ESCAPE)+; fragment NONDIGIT : [_a-zA-Z]; fragment S_CHAR : [A-Za-z\u0000-\u00FF]; fragment Q_CHAR : NONDIGIT | DIGIT | [!#$%&()*+,-./:;<>=?@[\]^{}|! ]; fragment S_ESCAPE : ('\\\'' | '\\"' | '\\\\' | '\\?' | '\\b' | '\\f' | '\\n' | '\\r' | '\\t' | '\\v' | '\\a'); fragment DIGIT : [0-9]; fragment UNSIGNED_INTEGER : DIGIT+; // vi:ts=4:sw=4:expandtab:
Fix typo in grammar
Fix typo in grammar
ANTLR
bsd-3-clause
jgoppert/pymola,jgoppert/pymola
098ce30f2b458d488070405b6f3d42908b5555a9
src/main/antlr4/nl/basjes/parse/useragent/UserAgentTreeWalker.g4
src/main/antlr4/nl/basjes/parse/useragent/UserAgentTreeWalker.g4
/* * Yet Another UserAgent Analyzer * Copyright (C) 2013-2016 Niels Basjes * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ grammar UserAgentTreeWalker; // =============================================================== VALUENAME : [a-zA-Z][a-zA-Z0-9]+ ; VALUE : DOUBLEQUOTE ( '\\' [btnfr"'\\] | ~[\\"] )* DOUBLEQUOTE ; UP : '^' ; NEXT : '>' ; PREV : '<' ; DOT : '.' ; MINUS : '-' ; STAR : '*' ; NUMBER : [0-9]+ ; BLOCKOPEN : '[' ; BLOCKCLOSE : ']' ; BRACEOPEN : '(' ; BRACECLOSE : ')' ; DOUBLEQUOTE : '"' ; COLON : ':' ; SEMICOLON : ';' ; SPACE : (' '|'\t')+ ; NOTEQUALS : '!=' ; EQUALS : '=' ; CONTAINS : '~' ; STARTSWITH : '{' ; ENDSWITH : '}' ; FIRSTWORDS : '#' ; SINGLEWORD : '%' ; BACKTOFULL : '@' ; // =============================================================== // TridentName[agent.(1)product.([2-4])comments.(*)product.name="Trident"^.(*)version~"7.";"DefaultValue"] // LookUp[TridentName;agent.(1)product.([2-4])comments.(*)product.name#1="Trident"^.(*)version%1="7.";"DefaultValue"] matcher : matcherLookup #matcherNextLookup | 'Concat' BLOCKOPEN VALUE SEMICOLON matcherLookup BLOCKCLOSE #matcherConcat1 | 'Concat' BLOCKOPEN matcherLookup SEMICOLON VALUE BLOCKCLOSE #matcherConcat2 | 'CleanVersion' BLOCKOPEN matcherLookup BLOCKCLOSE #matcherCleanVersion | 'IsNull' BLOCKOPEN matcherLookup BLOCKCLOSE #matcherPathIsNull ; matcherLookup : basePath #matcherPath | 'LookUp' BLOCKOPEN lookup=VALUENAME SEMICOLON matcherLookup (SEMICOLON defaultValue=VALUE )? BLOCKCLOSE #matcherPathLookup ; basePath : value=VALUE #pathFixedValue | ('__SyntaxError__'|'agent') #pathNoWalk | 'agent' nextStep=path #pathWalk ; path : DOT numberRange name=VALUENAME (nextStep=path)? #stepDown | UP (nextStep=path)? #stepUp | NEXT (nextStep=path)? #stepNext | PREV (nextStep=path)? #stepPrev | EQUALS value=VALUE (nextStep=path)? #stepEqualsValue | NOTEQUALS value=VALUE (nextStep=path)? #stepNotEqualsValue | STARTSWITH value=VALUE (nextStep=path)? #stepStartsWithValue | ENDSWITH value=VALUE (nextStep=path)? #stepEndsWithValue | CONTAINS value=VALUE (nextStep=path)? #stepContainsValue | FIRSTWORDS NUMBER (nextStep=path)? #stepFirstWords | SINGLEWORD NUMBER (nextStep=path)? #stepSingleWord | BACKTOFULL (nextStep=path)? #stepBackToFull ; numberRange : ( BRACEOPEN BLOCKOPEN rangeStart=NUMBER MINUS rangeEnd=NUMBER BLOCKCLOSE BRACECLOSE ) #numberRangeStartToEnd | ( BRACEOPEN count=NUMBER BRACECLOSE ) #numberRangeSingleValue | ( BRACEOPEN STAR BRACECLOSE ) #numberRangeAll | ( ) #numberRangeEmpty ;
/* * Yet Another UserAgent Analyzer * Copyright (C) 2013-2016 Niels Basjes * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ grammar UserAgentTreeWalker; // =============================================================== VALUENAME : [a-zA-Z][a-zA-Z0-9]+ ; VALUE : DOUBLEQUOTE ( '\\' [btnfr"'\\] | ~[\\"] )* DOUBLEQUOTE ; UP : '^' ; NEXT : '>' ; PREV : '<' ; DOT : '.' ; MINUS : '-' ; STAR : '*' ; NUMBER : [0-9]+ ; BLOCKOPEN : '[' ; BLOCKCLOSE : ']' ; BRACEOPEN : '(' ; BRACECLOSE : ')' ; DOUBLEQUOTE : '"' ; COLON : ':' ; SEMICOLON : ';' ; SPACE : (' '|'\t')+ ; NOTEQUALS : '!=' ; EQUALS : '=' ; CONTAINS : '~' ; STARTSWITH : '{' ; ENDSWITH : '}' ; FIRSTWORDS : '#' ; SINGLEWORD : '%' ; BACKTOFULL : '@' ; // =============================================================== // TridentName[agent.(1)product.([2-4])comments.(*)product.name="Trident"^.(*)version~"7.";"DefaultValue"] // LookUp[TridentName;agent.(1)product.([2-4])comments.(*)product.name#1="Trident"^.(*)version%1="7.";"DefaultValue"] matcher : matcherLookup #matcherNextLookup // | 'Concat' BLOCKOPEN VALUE SEMICOLON matcherLookup BLOCKCLOSE #matcherConcat1 // | 'Concat' BLOCKOPEN matcherLookup SEMICOLON VALUE BLOCKCLOSE #matcherConcat2 | 'CleanVersion' BLOCKOPEN matcherLookup BLOCKCLOSE #matcherCleanVersion | 'IsNull' BLOCKOPEN matcherLookup BLOCKCLOSE #matcherPathIsNull ; matcherLookup : basePath #matcherPath | 'LookUp' BLOCKOPEN lookup=VALUENAME SEMICOLON matcherLookup (SEMICOLON defaultValue=VALUE )? BLOCKCLOSE #matcherPathLookup ; basePath : value=VALUE #pathFixedValue | ('__SyntaxError__'|'agent') #pathNoWalk | 'agent' nextStep=path #pathWalk ; path : DOT numberRange name=VALUENAME (nextStep=path)? #stepDown | UP (nextStep=path)? #stepUp | NEXT (nextStep=path)? #stepNext | PREV (nextStep=path)? #stepPrev | EQUALS value=VALUE (nextStep=path)? #stepEqualsValue | NOTEQUALS value=VALUE (nextStep=path)? #stepNotEqualsValue | STARTSWITH value=VALUE (nextStep=path)? #stepStartsWithValue | ENDSWITH value=VALUE (nextStep=path)? #stepEndsWithValue | CONTAINS value=VALUE (nextStep=path)? #stepContainsValue | FIRSTWORDS NUMBER (nextStep=path)? #stepFirstWords | SINGLEWORD NUMBER (nextStep=path)? #stepSingleWord | BACKTOFULL (nextStep=path)? #stepBackToFull ; numberRange : ( BRACEOPEN BLOCKOPEN rangeStart=NUMBER MINUS rangeEnd=NUMBER BLOCKCLOSE BRACECLOSE ) #numberRangeStartToEnd | ( BRACEOPEN count=NUMBER BRACECLOSE ) #numberRangeSingleValue | ( BRACEOPEN STAR BRACECLOSE ) #numberRangeAll | ( ) #numberRangeEmpty ;
Comment not yet implemented partial feature
Comment not yet implemented partial feature
ANTLR
apache-2.0
Innometrics/yauaa,nielsbasjes/yauaa,nielsbasjes/yauaa,nielsbasjes/yauaa,Innometrics/yauaa,nielsbasjes/yauaa
36c5b2f564229d355713aa59f38992dcea9fd3a0
omni-cx2x/src/cx2x/translator/language/Claw.g4
omni-cx2x/src/cx2x/translator/language/Claw.g4
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import java.util.List; import java.util.ArrayList; import cx2x.translator.common.Constant; import cx2x.translator.pragma.*; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage language] @init{ $language = new ClawLanguage(); } : CLAW directive[$language] ; ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; directive[ClawLanguage language]: LFUSION { $language.setDirective(ClawDirective.LOOP_FUSION); } group_option[$language] EOF | LINTERCHANGE { $language.setDirective(ClawDirective.LOOP_INTERCHANGE); } indexes_option[$language] EOF | LEXTRACT range_option EOF { $language.setDirective(ClawDirective.LOOP_EXTRACT); $language.setRange($range_option.r); } | REMOVE { $language.setDirective(ClawDirective.REMOVE); } EOF | END REMOVE { $language.setDirective(ClawDirective.END_REMOVE); } EOF ; group_option[ClawLanguage language]: GROUP '(' group_name=IDENTIFIER ')' { $language.setGroupOption($group_name.text); } | /* empty */ ; indexes_option[ClawLanguage language] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $language.setIndexes(indexes); } | /* empty */ ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(Constant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ',' step=IDENTIFIER ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; /* mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); } : MAP '(' ids_list ':' ids_list ')' ; map_list: mapping_option | mapping_option map_list ; */ /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // Directives LFUSION : 'loop-fusion'; LINTERCHANGE : 'loop-interchange'; LEXTRACT : 'loop-extract'; REMOVE : 'remove'; END : 'end'; // Options GROUP : 'group'; RANGE : 'range'; MAP : 'map'; // Special elements IDENTIFIER : [a-zA-Z_$0-9] [a-zA-Z_$0-9]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : '0'..'9' ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import java.util.List; import java.util.ArrayList; import cx2x.translator.common.Constant; import cx2x.translator.pragma.*; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage language] @init{ $language = new ClawLanguage(); } : CLAW directive[$language] ; ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; directive[ClawLanguage language]: LFUSION { $language.setDirective(ClawDirective.LOOP_FUSION); } group_option[$language] EOF | LINTERCHANGE { $language.setDirective(ClawDirective.LOOP_INTERCHANGE); } indexes_option[$language] EOF | LEXTRACT range_option EOF { $language.setDirective(ClawDirective.LOOP_EXTRACT); $language.setRange($range_option.r); } | REMOVE { $language.setDirective(ClawDirective.REMOVE); } EOF | END REMOVE { $language.setDirective(ClawDirective.END_REMOVE); } EOF ; group_option[ClawLanguage language]: GROUP '(' group_name=IDENTIFIER ')' { $language.setGroupOption($group_name.text); } | /* empty */ ; indexes_option[ClawLanguage language] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $language.setIndexes(indexes); } | /* empty */ ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(Constant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ',' step=IDENTIFIER ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; mapping_var_list[List<ClawMappingVar> vars]: mv=mapping_var { $vars.add($mv.mappingVar); } | mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars] ; /* mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); } : MAP '(' ids_list ':' ids_list ')' ; map_list: mapping_option | mapping_option map_list ; */ /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // Directives LFUSION : 'loop-fusion'; LINTERCHANGE : 'loop-interchange'; LEXTRACT : 'loop-extract'; REMOVE : 'remove'; END : 'end'; // Options GROUP : 'group'; RANGE : 'range'; MAP : 'map'; // Special elements IDENTIFIER : [a-zA-Z_$0-9] [a-zA-Z_$0-9]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : '0'..'9' ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
Add mapping_var_list parser rule
Add mapping_var_list parser rule
ANTLR
bsd-2-clause
clementval/claw-compiler,clementval/claw-compiler
f5c6cc11d2d9230b74952bb267c74111ef81e9cd
graphql/GraphQL.g4
graphql/GraphQL.g4
/* The MIT License (MIT) Copyright (c) 2015 Joseph T. McBride Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. GraphQL grammar derived from: GraphQL Draft Specification - July 2015 http://facebook.github.io/graphql/ https://github.com/facebook/graphql AB:10-sep19: replaced type with type_ to resolve conflict for golang generator AB: 13-oct-19: added type system as per June 2018 specs AB: 26-oct-19: added ID type AB: 30-Oct-19: description, boolean, schema & Block string fix. now parses: https://raw.githubusercontent.com/graphql-cats/graphql-cats/master/scenarios/validation/validation.schema.graphql */ grammar GraphQL; //https://spec.graphql.org/June2018/#sec-Language.Document document: definition+; definition: executableDefinition | typeSystemDefinition | typeSystemExtension; //https://spec.graphql.org/June2018/#ExecutableDefinition executableDefinition: operationDefinition | fragmentDefinition; //https://spec.graphql.org/June2018/#sec-Language.Operations operationDefinition: operationType name? variableDefinitions? directives? selectionSet | selectionSet ; operationType: 'query' | 'mutation' | 'subscription'; //https://spec.graphql.org/June2018/#sec-Selection-Sets selectionSet: '{' selection+ '}'; selection: field | fragmentSpread | inlineFragment ; //https://spec.graphql.org/June2018/#sec-Language.Fields field: alias? name arguments? directives? selectionSet?; //https://spec.graphql.org/June2018/#sec-Language.Arguments arguments: '(' argument+ ')'; argument: name ':' value; //https://spec.graphql.org/June2018/#sec-Field-Alias alias: name ':'; //https://spec.graphql.org/June2018/#sec-Language.Fragments fragmentSpread: '...' fragmentName directives?; fragmentDefinition: 'fragment' fragmentName 'on' typeCondition directives? selectionSet; fragmentName: name; // except on //https://spec.graphql.org/June2018/#sec-Type-Conditions typeCondition: 'on' namedType; //https://spec.graphql.org/June2018/#sec-Inline-Fragments inlineFragment: '...' typeCondition? directives? selectionSet; //https://spec.graphql.org/June2018/#sec-Input-Values value: variable | intValue | floatValue | stringValue | booleanValue | nullValue | enumValue | listValue | objectValue ; //https://spec.graphql.org/June2018/#sec-Int-Value intValue: INT; //https://spec.graphql.org/June2018/#sec-Float-Value floatValue: FLOAT; //https://spec.graphql.org/June2018/#sec-Boolean-Value booleanValue : 'true' | 'false' ; //https://spec.graphql.org/June2018/#sec-String-Value stringValue : STRING | BLOCK_STRING; //https://spec.graphql.org/June2018/#sec-Null-Value nullValue: 'null'; //https://spec.graphql.org/June2018/#sec-Enum-Value enumValue: name; //{ not (nullValue | booleanValue) }; //https://spec.graphql.org/June2018/#sec-List-Value listValue: '[' ']' | '[' value+ ']' ; //https://spec.graphql.org/June2018/#sec-Input-Object-Values objectValue: '{' '}' | '{' objectField '}' ; objectField: name ':' value; //https://spec.graphql.org/June2018/#sec-Language.Variables variable: '$' name; variableDefinitions: '(' variableDefinition+ ')'; variableDefinition: variable ':' type_ defaultValue?; defaultValue: '=' value; //https://spec.graphql.org/June2018/#sec-Type-References type_: namedType '!'? | listType '!'? ; namedType: name; listType: '[' type_ ']'; //https://spec.graphql.org/June2018/#sec-Language.Directives directives: directive+; directive: '@' name arguments?; // https://graphql.github.io/graphql-spec/June2018/#TypeSystemDefinition typeSystemDefinition: schemaDefinition | typeDefinition | directiveDefinition ; //https://spec.graphql.org/June2018/#TypeSystemExtension typeSystemExtension: schemaExtension | typeExtension ; // https://graphql.github.io/graphql-spec/June2018/#sec-Schema schemaDefinition: 'schema' directives? '{' rootOperationTypeDefinition+ '}'; rootOperationTypeDefinition: operationType ':' namedType; //https://spec.graphql.org/June2018/#sec-Schema-Extension schemaExtension: 'extend' 'schema' directives? '{' operationTypeDefinition+ '}' | 'extend' 'schema' directives ; //https://spec.graphql.org/June2018/#OperationTypeDefinition operationTypeDefinition: operationType ':' namedType; //https://spec.graphql.org/June2018/#sec-Descriptions description: stringValue; //https://spec.graphql.org/June2018/#sec-Types typeDefinition: scalarTypeDefinition | objectTypeDefinition | interfaceTypeDefinition | unionTypeDefinition | enumTypeDefinition | inputObjectTypeDefinition; //https://spec.graphql.org/June2018/#sec-Type-Extensions typeExtension : scalarTypeExtension | objectTypeExtension | interfaceTypeExtension | unionTypeExtension | enumTypeExtension | inputObjectTypeExtension ; //https://spec.graphql.org/June2018/#sec-Scalars scalarTypeDefinition: description? 'scalar' name directives?; //https://spec.graphql.org/June2018/#sec-Scalar-Extensions scalarTypeExtension: 'extends' 'scalar' name directives; // https://graphql.github.io/graphql-spec/June2018/#sec-Objects objectTypeDefinition : description? 'type' name implementsInterfaces? directives? fieldsDefinition?; implementsInterfaces: 'implements' '&'? namedType | implementsInterfaces '&' namedType ; fieldsDefinition: '{' fieldDefinition+ '}'; fieldDefinition: description? name argumentsDefinition? ':' type_ directives? ; //https://spec.graphql.org/June2018/#sec-Field-Arguments argumentsDefinition: '(' inputValueDefinition+ ')'; inputValueDefinition: description? name ':' type_ defaultValue? directives?; //https://spec.graphql.org/June2018/#sec-Object-Extensions objectTypeExtension: 'extend' 'type' name implementsInterfaces? directives? fieldsDefinition | 'extend' 'type' name implementsInterfaces? directives | 'extend' 'type' name implementsInterfaces ; //https://spec.graphql.org/June2018/#sec-Interfaces interfaceTypeDefinition: description? 'interface' name directives? fieldsDefinition?; //https://spec.graphql.org/June2018/#sec-Interface-Extensions interfaceTypeExtension: 'extend' 'interface' name directives? fieldsDefinition | 'extend' 'interface' name directives ; // https://graphql.github.io/graphql-spec/June2018/#sec-Unions unionTypeDefinition: description? 'union' name directives? unionMemberTypes?; unionMemberTypes: '=' '|'? namedType ('|'namedType)* ; //https://spec.graphql.org/June2018/#sec-Union-Extensions unionTypeExtension : 'extend' 'union' name directives? unionMemberTypes | 'extend' 'union' name directives ; //https://spec.graphql.org/June2018/#sec-Enums enumTypeDefinition: description? 'enum' name directives? enumValuesDefinition?; enumValuesDefinition: '{' enumValueDefinition '}'; enumValueDefinition: description? enumValue directives?; //https://spec.graphql.org/June2018/#sec-Enum-Extensions enumTypeExtension: 'extend' 'enum' name directives? enumValuesDefinition | 'extend' 'enum' name directives ; //https://spec.graphql.org/June2018/#sec-Input-Objects inputObjectTypeDefinition: description? 'input' name directives? inputFieldsDefinition?; inputFieldsDefinition: '{' inputValueDefinition+ '}'; //https://spec.graphql.org/June2018/#sec-Input-Object-Extensions inputObjectTypeExtension: 'extend' 'input' name directives? inputFieldsDefinition | 'extend' 'input' name directives ; //https://spec.graphql.org/June2018/#sec-Type-System.Directives directiveDefinition: description? 'directive' '@' name argumentsDefinition? 'on' directiveLocations; directiveLocations: directiveLocation ('|' directiveLocation)*; directiveLocation: executableDirectiveLocation | typeSystemDirectiveLocation; executableDirectiveLocation: 'QUERY' | 'MUTATION' | 'SUBSCRIPTION' | 'FIELD' | 'FRAGMENT_DEFINITION' | 'FRAGMENT_SPREAD' | 'INLINE_FRAGMENT' ; typeSystemDirectiveLocation: 'SCHEMA' | 'SCALAR' | 'OBJECT' | 'FIELD_DEFINITION' | 'ARGUMENT_DEFINITION' | 'INTERFACE' | 'UNION' | 'ENUM' | 'ENUM_VALUE' | 'INPUT_OBJECT' | 'INPUT_FIELD_DEFINITION' ; name: NAME; //Start lexer NAME: [_A-Za-z] [_0-9A-Za-z]*; fragment CHARACTER: ( ESC | ~ ["\\]); STRING: '"' CHARACTER* '"'; BLOCK_STRING : '"""' .*? '"""' ; ID: STRING; fragment ESC: '\\' ( ["\\/bfnrt] | UNICODE); fragment UNICODE: 'u' HEX HEX HEX HEX; fragment HEX: [0-9a-fA-F]; fragment NONZERO_DIGIT: [1-9]; fragment DIGIT: [0-9]; fragment FRACTIONAL_PART: '.' DIGIT+; fragment EXPONENTIAL_PART: EXPONENT_INDICATOR SIGN? DIGIT+; fragment EXPONENT_INDICATOR: [eE]; fragment SIGN: [+-]; fragment NEGATIVE_SIGN: '-'; FLOAT: INT FRACTIONAL_PART | INT EXPONENTIAL_PART | INT FRACTIONAL_PART EXPONENTIAL_PART ; INT: NEGATIVE_SIGN? '0'? | NEGATIVE_SIGN? NONZERO_DIGIT DIGIT* ; PUNCTUATOR: '!' | '$' | '(' | ')' | '...' | ':' | '=' | '@' | '[' | ']' | '{' | '}' | '|' ; // no leading zeros fragment EXP: [Ee] [+\-]? INT; // \- since - means "range" inside [...] WS: [ \t\n\r]+ -> skip; COMMA: ',' -> skip; LineComment : '#' ~[\r\n]* -> skip ; UNICODE_BOM: (UTF8_BOM | UTF16_BOM | UTF32_BOM ) -> skip ; UTF8_BOM: '\uEFBBBF'; UTF16_BOM: '\uFEFF'; UTF32_BOM: '\u0000FEFF';
/* The MIT License (MIT) Copyright (c) 2015 Joseph T. McBride Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. GraphQL grammar derived from: GraphQL Draft Specification - July 2015 http://facebook.github.io/graphql/ https://github.com/facebook/graphql AB:10-sep19: replaced type with type_ to resolve conflict for golang generator AB: 13-oct-19: added type system as per June 2018 specs AB: 26-oct-19: added ID type AB: 30-Oct-19: description, boolean, schema & Block string fix. now parses: https://raw.githubusercontent.com/graphql-cats/graphql-cats/master/scenarios/validation/validation.schema.graphql */ grammar GraphQL; //https://spec.graphql.org/June2018/#sec-Language.Document document: definition+; definition: executableDefinition | typeSystemDefinition | typeSystemExtension; //https://spec.graphql.org/June2018/#ExecutableDefinition executableDefinition: operationDefinition | fragmentDefinition; //https://spec.graphql.org/June2018/#sec-Language.Operations operationDefinition: operationType name? variableDefinitions? directives? selectionSet | selectionSet ; operationType: 'query' | 'mutation' | 'subscription'; //https://spec.graphql.org/June2018/#sec-Selection-Sets selectionSet: '{' selection+ '}'; selection: field | fragmentSpread | inlineFragment ; //https://spec.graphql.org/June2018/#sec-Language.Fields field: alias? name arguments? directives? selectionSet?; //https://spec.graphql.org/June2018/#sec-Language.Arguments arguments: '(' argument+ ')'; argument: name ':' value; //https://spec.graphql.org/June2018/#sec-Field-Alias alias: name ':'; //https://spec.graphql.org/June2018/#sec-Language.Fragments fragmentSpread: '...' fragmentName directives?; fragmentDefinition: 'fragment' fragmentName 'on' typeCondition directives? selectionSet; fragmentName: name; // except on //https://spec.graphql.org/June2018/#sec-Type-Conditions typeCondition: 'on' namedType; //https://spec.graphql.org/June2018/#sec-Inline-Fragments inlineFragment: '...' typeCondition? directives? selectionSet; //https://spec.graphql.org/June2018/#sec-Input-Values value: variable | intValue | floatValue | stringValue | booleanValue | nullValue | enumValue | listValue | objectValue ; //https://spec.graphql.org/June2018/#sec-Int-Value intValue: INT; //https://spec.graphql.org/June2018/#sec-Float-Value floatValue: FLOAT; //https://spec.graphql.org/June2018/#sec-Boolean-Value booleanValue : 'true' | 'false' ; //https://spec.graphql.org/June2018/#sec-String-Value stringValue : STRING | BLOCK_STRING; //https://spec.graphql.org/June2018/#sec-Null-Value nullValue: 'null'; //https://spec.graphql.org/June2018/#sec-Enum-Value enumValue: name; //{ not (nullValue | booleanValue) }; //https://spec.graphql.org/June2018/#sec-List-Value listValue: '[' ']' | '[' value+ ']' ; //https://spec.graphql.org/June2018/#sec-Input-Object-Values objectValue: '{' '}' | '{' objectField '}' ; objectField: name ':' value; //https://spec.graphql.org/June2018/#sec-Language.Variables variable: '$' name; variableDefinitions: '(' variableDefinition+ ')'; variableDefinition: variable ':' type_ defaultValue?; defaultValue: '=' value; //https://spec.graphql.org/June2018/#sec-Type-References type_: namedType '!'? | listType '!'? ; namedType: name; listType: '[' type_ ']'; //https://spec.graphql.org/June2018/#sec-Language.Directives directives: directive+; directive: '@' name arguments?; // https://graphql.github.io/graphql-spec/June2018/#TypeSystemDefinition typeSystemDefinition: schemaDefinition | typeDefinition | directiveDefinition ; //https://spec.graphql.org/June2018/#TypeSystemExtension typeSystemExtension: schemaExtension | typeExtension ; // https://graphql.github.io/graphql-spec/June2018/#sec-Schema schemaDefinition: 'schema' directives? '{' rootOperationTypeDefinition+ '}'; rootOperationTypeDefinition: operationType ':' namedType; //https://spec.graphql.org/June2018/#sec-Schema-Extension schemaExtension: 'extend' 'schema' directives? '{' operationTypeDefinition+ '}' | 'extend' 'schema' directives ; //https://spec.graphql.org/June2018/#OperationTypeDefinition operationTypeDefinition: operationType ':' namedType; //https://spec.graphql.org/June2018/#sec-Descriptions description: stringValue; //https://spec.graphql.org/June2018/#sec-Types typeDefinition: scalarTypeDefinition | objectTypeDefinition | interfaceTypeDefinition | unionTypeDefinition | enumTypeDefinition | inputObjectTypeDefinition; //https://spec.graphql.org/June2018/#sec-Type-Extensions typeExtension : scalarTypeExtension | objectTypeExtension | interfaceTypeExtension | unionTypeExtension | enumTypeExtension | inputObjectTypeExtension ; //https://spec.graphql.org/June2018/#sec-Scalars scalarTypeDefinition: description? 'scalar' name directives?; //https://spec.graphql.org/June2018/#sec-Scalar-Extensions scalarTypeExtension: 'extends' 'scalar' name directives; // https://graphql.github.io/graphql-spec/June2018/#sec-Objects objectTypeDefinition : description? 'type' name implementsInterfaces? directives? fieldsDefinition?; implementsInterfaces: 'implements' '&'? namedType | implementsInterfaces '&' namedType ; fieldsDefinition: '{' fieldDefinition+ '}'; fieldDefinition: description? name argumentsDefinition? ':' type_ directives? ; //https://spec.graphql.org/June2018/#sec-Field-Arguments argumentsDefinition: '(' inputValueDefinition+ ')'; inputValueDefinition: description? name ':' type_ defaultValue? directives?; //https://spec.graphql.org/June2018/#sec-Object-Extensions objectTypeExtension: 'extend' 'type' name implementsInterfaces? directives? fieldsDefinition | 'extend' 'type' name implementsInterfaces? directives | 'extend' 'type' name implementsInterfaces ; //https://spec.graphql.org/June2018/#sec-Interfaces interfaceTypeDefinition: description? 'interface' name directives? fieldsDefinition?; //https://spec.graphql.org/June2018/#sec-Interface-Extensions interfaceTypeExtension: 'extend' 'interface' name directives? fieldsDefinition | 'extend' 'interface' name directives ; // https://graphql.github.io/graphql-spec/June2018/#sec-Unions unionTypeDefinition: description? 'union' name directives? unionMemberTypes?; unionMemberTypes: '=' '|'? namedType ('|'namedType)* ; //https://spec.graphql.org/June2018/#sec-Union-Extensions unionTypeExtension : 'extend' 'union' name directives? unionMemberTypes | 'extend' 'union' name directives ; //https://spec.graphql.org/June2018/#sec-Enums enumTypeDefinition: description? 'enum' name directives? enumValuesDefinition?; enumValuesDefinition: '{' enumValueDefinition '}'; enumValueDefinition: description? enumValue directives?; //https://spec.graphql.org/June2018/#sec-Enum-Extensions enumTypeExtension: 'extend' 'enum' name directives? enumValuesDefinition | 'extend' 'enum' name directives ; //https://spec.graphql.org/June2018/#sec-Input-Objects inputObjectTypeDefinition: description? 'input' name directives? inputFieldsDefinition?; inputFieldsDefinition: '{' inputValueDefinition+ '}'; //https://spec.graphql.org/June2018/#sec-Input-Object-Extensions inputObjectTypeExtension: 'extend' 'input' name directives? inputFieldsDefinition | 'extend' 'input' name directives ; //https://spec.graphql.org/June2018/#sec-Type-System.Directives directiveDefinition: description? 'directive' '@' name argumentsDefinition? 'on' directiveLocations; directiveLocations: directiveLocation ('|' directiveLocation)*; directiveLocation: executableDirectiveLocation | typeSystemDirectiveLocation; executableDirectiveLocation: 'QUERY' | 'MUTATION' | 'SUBSCRIPTION' | 'FIELD' | 'FRAGMENT_DEFINITION' | 'FRAGMENT_SPREAD' | 'INLINE_FRAGMENT' ; typeSystemDirectiveLocation: 'SCHEMA' | 'SCALAR' | 'OBJECT' | 'FIELD_DEFINITION' | 'ARGUMENT_DEFINITION' | 'INTERFACE' | 'UNION' | 'ENUM' | 'ENUM_VALUE' | 'INPUT_OBJECT' | 'INPUT_FIELD_DEFINITION' ; name: NAME; //Start lexer NAME: [_A-Za-z] [_0-9A-Za-z]*; fragment CHARACTER: ( ESC | ~ ["\\]); STRING: '"' CHARACTER* '"'; BLOCK_STRING : '"""' .*? '"""' ; ID: STRING; fragment ESC: '\\' ( ["\\/bfnrt] | UNICODE); fragment UNICODE: 'u' HEX HEX HEX HEX; fragment HEX: [0-9a-fA-F]; fragment NONZERO_DIGIT: [1-9]; fragment DIGIT: [0-9]; fragment FRACTIONAL_PART: '.' DIGIT+; fragment EXPONENTIAL_PART: EXPONENT_INDICATOR SIGN? DIGIT+; fragment EXPONENT_INDICATOR: [eE]; fragment SIGN: [+-]; fragment NEGATIVE_SIGN: '-'; FLOAT: INT FRACTIONAL_PART | INT EXPONENTIAL_PART | INT FRACTIONAL_PART EXPONENTIAL_PART ; INT: NEGATIVE_SIGN? '0' | NEGATIVE_SIGN? NONZERO_DIGIT DIGIT* ; PUNCTUATOR: '!' | '$' | '(' | ')' | '...' | ':' | '=' | '@' | '[' | ']' | '{' | '}' | '|' ; // no leading zeros fragment EXP: [Ee] [+\-]? INT; // \- since - means "range" inside [...] WS: [ \t\n\r]+ -> skip; COMMA: ',' -> skip; LineComment : '#' ~[\r\n]* -> skip ; UNICODE_BOM: (UTF8_BOM | UTF16_BOM | UTF32_BOM ) -> skip ; UTF8_BOM: '\uEFBBBF'; UTF16_BOM: '\uFEFF'; UTF32_BOM: '\u0000FEFF';
Fix minor warning in lexer
Fix minor warning in lexer * Fragment rule can match empty string
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
476c1bdcbc9b16ae19e5387cccc05e7b24293ebc
antlr/antlr4/Python3/ANTLRv4Lexer.g4
antlr/antlr4/Python3/ANTLRv4Lexer.g4
/* * [The "BSD license"] * Copyright (c) 2012-2015 Terence Parr * Copyright (c) 2012-2015 Sam Harwell * Copyright (c) 2015 Gerald Rosenberg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * A grammar for ANTLR v4 implemented using v4 syntax * * Modified 2015.06.16 gbr * -- update for compatibility with Antlr v4.5 */ // ====================================================== // Lexer specification // ====================================================== lexer grammar ANTLRv4LexerPythonTarget; options { superClass = LexerAdaptor; } import LexBasic; // Standard set of fragments tokens { TOKEN_REF , RULE_REF , LEXER_CHAR_SET } channels { OFF_CHANNEL , COMMENT } // ------------------------- // Comments DOC_COMMENT : DocComment -> channel (COMMENT) ; BLOCK_COMMENT : BlockComment -> channel (COMMENT) ; LINE_COMMENT : LineComment -> channel (COMMENT) ; // ------------------------- // Integer INT : DecimalNumeral ; // ------------------------- // Literal string // // ANTLR makes no distinction between a single character literal and a // multi-character string. All literals are single quote delimited and // may contain unicode escape sequences of the form \uxxxx, where x // is a valid hexadecimal number (per Unicode standard). STRING_LITERAL : SQuoteLiteral ; UNTERMINATED_STRING_LITERAL : USQuoteLiteral ; // ------------------------- // Arguments // // Certain argument lists, such as those specifying call parameters // to a rule invocation, or input parameters to a rule specification // are contained within square brackets. BEGIN_ARGUMENT : LBrack { self.handleBeginArgument() } ; // ------------------------- // Target Language Actions BEGIN_ACTION : LBrace -> pushMode (TargetLanguageAction) ; // ------------------------- // Keywords // // 'options', 'tokens', and 'channels' are considered keywords // but only when followed by '{', and considered as a single token. // Otherwise, the symbols are tokenized as RULE_REF and allowed as // an identifier in a labeledElement. OPTIONS : 'options' WSNLCHARS* '{' ; TOKENS : 'tokens' WSNLCHARS* '{' ; CHANNELS : 'channels' WSNLCHARS* '{' ; fragment WSNLCHARS : ' ' | '\t' | '\f' | '\n' | '\r' ; IMPORT : 'import' ; FRAGMENT : 'fragment' ; LEXER : 'lexer' ; PARSER : 'parser' ; GRAMMAR : 'grammar' ; PROTECTED : 'protected' ; PUBLIC : 'public' ; PRIVATE : 'private' ; RETURNS : 'returns' ; LOCALS : 'locals' ; THROWS : 'throws' ; CATCH : 'catch' ; FINALLY : 'finally' ; MODE : 'mode' ; // ------------------------- // Punctuation COLON : Colon ; COLONCOLON : DColon ; COMMA : Comma ; SEMI : Semi ; LPAREN : LParen ; RPAREN : RParen ; LBRACE : LBrace ; RBRACE : RBrace ; RARROW : RArrow ; LT : Lt ; GT : Gt ; ASSIGN : Equal ; QUESTION : Question ; STAR : Star ; PLUS_ASSIGN : PlusAssign ; PLUS : Plus ; OR : Pipe ; DOLLAR : Dollar ; RANGE : Range ; DOT : Dot ; AT : At ; POUND : Pound ; NOT : Tilde ; // ------------------------- // Identifiers - allows unicode rule/token names ID : Id ; // ------------------------- // Whitespace WS : Ws+ -> channel (OFF_CHANNEL) ; // ------------------------- // Illegal Characters // // This is an illegal character trap which is always the last rule in the // lexer specification. It matches a single character of any value and being // the last rule in the file will match when no other rule knows what to do // about the character. It is reported as an error but is not passed on to the // parser. This means that the parser to deal with the gramamr file anyway // but we will not try to analyse or code generate from a file with lexical // errors. // Comment this rule out to allow the error to be propagated to the parser ERRCHAR : . -> channel (HIDDEN) ; // ====================================================== // Lexer modes // ------------------------- // Arguments mode Argument; // E.g., [int x, List<String> a[]] NESTED_ARGUMENT : LBrack -> type (ARGUMENT_CONTENT) , pushMode (Argument) ; ARGUMENT_ESCAPE : EscAny -> type (ARGUMENT_CONTENT) ; ARGUMENT_STRING_LITERAL : DQuoteLiteral -> type (ARGUMENT_CONTENT) ; ARGUMENT_CHAR_LITERAL : SQuoteLiteral -> type (ARGUMENT_CONTENT) ; END_ARGUMENT : RBrack { self.handleEndArgument() } ; // added this to return non-EOF token type here. EOF does something weird UNTERMINATED_ARGUMENT : EOF -> popMode ; ARGUMENT_CONTENT : . ; // ------------------------- // Target Language Actions // // Many language targets use {} as block delimiters and so we // must recursively match {} delimited blocks to balance the // braces. Additionally, we must make some assumptions about // literal string representation in the target language. We assume // that they are delimited by ' or " and so consume these // in their own alts so as not to inadvertantly match {}. mode TargetLanguageAction; NESTED_ACTION : LBrace -> type (ACTION_CONTENT) , pushMode (TargetLanguageAction) ; ACTION_ESCAPE : EscAny -> type (ACTION_CONTENT) ; ACTION_STRING_LITERAL : DQuoteLiteral -> type (ACTION_CONTENT) ; ACTION_CHAR_LITERAL : SQuoteLiteral -> type (ACTION_CONTENT) ; ACTION_DOC_COMMENT : DocComment -> type (ACTION_CONTENT) ; ACTION_BLOCK_COMMENT : BlockComment -> type (ACTION_CONTENT) ; ACTION_LINE_COMMENT : LineComment -> type (ACTION_CONTENT) ; END_ACTION : RBrace { self.handleEndAction() } ; UNTERMINATED_ACTION : EOF -> popMode ; ACTION_CONTENT : . ; // ------------------------- mode LexerCharSet; LEXER_CHAR_SET_BODY : (~ [\]\\] | EscAny)+ -> more ; LEXER_CHAR_SET : RBrack -> popMode ; UNTERMINATED_CHAR_SET : EOF -> popMode ; // ------------------------------------------------------------------------------ // Grammar specific Keywords, Punctuation, etc. fragment Id : NameStartChar NameChar* ;
/* * [The "BSD license"] * Copyright (c) 2012-2015 Terence Parr * Copyright (c) 2012-2015 Sam Harwell * Copyright (c) 2015 Gerald Rosenberg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * A grammar for ANTLR v4 implemented using v4 syntax * * Modified 2015.06.16 gbr * -- update for compatibility with Antlr v4.5 */ // ====================================================== // Lexer specification // ====================================================== lexer grammar ANTLRv4Lexer; options { superClass = LexerAdaptor; } import LexBasic; // Standard set of fragments tokens { TOKEN_REF , RULE_REF , LEXER_CHAR_SET } channels { OFF_CHANNEL , COMMENT } // ------------------------- // Comments DOC_COMMENT : DocComment -> channel (COMMENT) ; BLOCK_COMMENT : BlockComment -> channel (COMMENT) ; LINE_COMMENT : LineComment -> channel (COMMENT) ; // ------------------------- // Integer INT : DecimalNumeral ; // ------------------------- // Literal string // // ANTLR makes no distinction between a single character literal and a // multi-character string. All literals are single quote delimited and // may contain unicode escape sequences of the form \uxxxx, where x // is a valid hexadecimal number (per Unicode standard). STRING_LITERAL : SQuoteLiteral ; UNTERMINATED_STRING_LITERAL : USQuoteLiteral ; // ------------------------- // Arguments // // Certain argument lists, such as those specifying call parameters // to a rule invocation, or input parameters to a rule specification // are contained within square brackets. BEGIN_ARGUMENT : LBrack { self.handleBeginArgument() } ; // ------------------------- // Target Language Actions BEGIN_ACTION : LBrace -> pushMode (TargetLanguageAction) ; // ------------------------- // Keywords // // 'options', 'tokens', and 'channels' are considered keywords // but only when followed by '{', and considered as a single token. // Otherwise, the symbols are tokenized as RULE_REF and allowed as // an identifier in a labeledElement. OPTIONS : 'options' WSNLCHARS* '{' ; TOKENS : 'tokens' WSNLCHARS* '{' ; CHANNELS : 'channels' WSNLCHARS* '{' ; fragment WSNLCHARS : ' ' | '\t' | '\f' | '\n' | '\r' ; IMPORT : 'import' ; FRAGMENT : 'fragment' ; LEXER : 'lexer' ; PARSER : 'parser' ; GRAMMAR : 'grammar' ; PROTECTED : 'protected' ; PUBLIC : 'public' ; PRIVATE : 'private' ; RETURNS : 'returns' ; LOCALS : 'locals' ; THROWS : 'throws' ; CATCH : 'catch' ; FINALLY : 'finally' ; MODE : 'mode' ; // ------------------------- // Punctuation COLON : Colon ; COLONCOLON : DColon ; COMMA : Comma ; SEMI : Semi ; LPAREN : LParen ; RPAREN : RParen ; LBRACE : LBrace ; RBRACE : RBrace ; RARROW : RArrow ; LT : Lt ; GT : Gt ; ASSIGN : Equal ; QUESTION : Question ; STAR : Star ; PLUS_ASSIGN : PlusAssign ; PLUS : Plus ; OR : Pipe ; DOLLAR : Dollar ; RANGE : Range ; DOT : Dot ; AT : At ; POUND : Pound ; NOT : Tilde ; // ------------------------- // Identifiers - allows unicode rule/token names ID : Id ; // ------------------------- // Whitespace WS : Ws+ -> channel (OFF_CHANNEL) ; // ------------------------- // Illegal Characters // // This is an illegal character trap which is always the last rule in the // lexer specification. It matches a single character of any value and being // the last rule in the file will match when no other rule knows what to do // about the character. It is reported as an error but is not passed on to the // parser. This means that the parser to deal with the gramamr file anyway // but we will not try to analyse or code generate from a file with lexical // errors. // Comment this rule out to allow the error to be propagated to the parser ERRCHAR : . -> channel (HIDDEN) ; // ====================================================== // Lexer modes // ------------------------- // Arguments mode Argument; // E.g., [int x, List<String> a[]] NESTED_ARGUMENT : LBrack -> type (ARGUMENT_CONTENT) , pushMode (Argument) ; ARGUMENT_ESCAPE : EscAny -> type (ARGUMENT_CONTENT) ; ARGUMENT_STRING_LITERAL : DQuoteLiteral -> type (ARGUMENT_CONTENT) ; ARGUMENT_CHAR_LITERAL : SQuoteLiteral -> type (ARGUMENT_CONTENT) ; END_ARGUMENT : RBrack { self.handleEndArgument() } ; // added this to return non-EOF token type here. EOF does something weird UNTERMINATED_ARGUMENT : EOF -> popMode ; ARGUMENT_CONTENT : . ; // ------------------------- // Target Language Actions // // Many language targets use {} as block delimiters and so we // must recursively match {} delimited blocks to balance the // braces. Additionally, we must make some assumptions about // literal string representation in the target language. We assume // that they are delimited by ' or " and so consume these // in their own alts so as not to inadvertantly match {}. mode TargetLanguageAction; NESTED_ACTION : LBrace -> type (ACTION_CONTENT) , pushMode (TargetLanguageAction) ; ACTION_ESCAPE : EscAny -> type (ACTION_CONTENT) ; ACTION_STRING_LITERAL : DQuoteLiteral -> type (ACTION_CONTENT) ; ACTION_CHAR_LITERAL : SQuoteLiteral -> type (ACTION_CONTENT) ; ACTION_DOC_COMMENT : DocComment -> type (ACTION_CONTENT) ; ACTION_BLOCK_COMMENT : BlockComment -> type (ACTION_CONTENT) ; ACTION_LINE_COMMENT : LineComment -> type (ACTION_CONTENT) ; END_ACTION : RBrace { self.handleEndAction() } ; UNTERMINATED_ACTION : EOF -> popMode ; ACTION_CONTENT : . ; // ------------------------- mode LexerCharSet; LEXER_CHAR_SET_BODY : (~ [\]\\] | EscAny)+ -> more ; LEXER_CHAR_SET : RBrack -> popMode ; UNTERMINATED_CHAR_SET : EOF -> popMode ; // ------------------------------------------------------------------------------ // Grammar specific Keywords, Punctuation, etc. fragment Id : NameStartChar NameChar* ;
Fix name of Python-specific ANTLRv4 lexer grammar
Fix name of Python-specific ANTLRv4 lexer grammar
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
0fee3e3e0151ec293959c64df28db6776bb4d79b
sharding-jdbc-ddl-parser/src/main/antlr4/imports/PostgreBase.g4
sharding-jdbc-ddl-parser/src/main/antlr4/imports/PostgreBase.g4
grammar PostgreBase; import PostgreKeyword, DataType, Keyword, Symbol, BaseRule; columnDefinition : columnName dataType collateClause? columnConstraint* ; dataType : typeName intervalFields? dataTypeLength? (WITHOUT TIME ZONE | WITH TIME ZONE)? (LEFT_BRACKET RIGHT_BRACKET)* | ID ; typeName : (SMALLINT | INT2 | INTEGER | INT | INT4 | BIGINT | INT8 | NUMERIC | DECIMAL | REAL | FLOAT4 | DOUBLE PRECISION | FLOAT8 | SMALLSERIAL | SERIAL2 | SERIAL | SERIAL4 | BIGSERIAL | SERIAL8) | MONEY | (CHARACTER VARYING? | VARCHAR | CHAR | TEXT) | TEXT | BYTEA | (TIMESTAMP | TIMESTAMPTZ | DATE | TIME | TIMETZ |INTERVAL) | (BOOLEAN | BOOL) | ID | (POINT | LINE | LSEG | BOX | PATH | POLYGON | CIRCLE) | (CIDR | INET | MACADDR | MACADDR8) | BIT VARYING? | (TSVECTOR | TSQUERY) | UUID | XML | (JSON | JSONB) ; intervalFields : intervalField (TO intervalField)? ; intervalField : YEAR | MONTH | DAY | HOUR | MINUTE | SECOND ; collateClause : COLLATE collationName ; usingIndexType: USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN) ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT constraintName ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LEFT_PAREN sequenceOptions RIGHT_PAREN)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName (LEFT_PAREN columnName RIGHT_PAREN)? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)?(ON DELETE action)? (ON UPDATE action)? ; checkOption : CHECK expr (NO INHERIT )? ; defaultExpr : CURRENT_TIMESTAMP | expr; sequenceOptions: sequenceOption (START WITH? NUMBER)? (CACHE NUMBER)? (NO? CYCLE)? ; sequenceOption : (INCREMENT BY? NUMBER)? (MINVALUE NUMBER | NO MINVALUE)? (MAXVALUE NUMBER | NO MAXVALUE)? ; indexParameters : (USING INDEX TABLESPACE tablespaceName)? ; action : NO ACTION | RESTRICT | CASCADE | SET NULL | SET DEFAULT ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED |IMMEDIATE))? ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnList indexParameters | primaryKey columnList indexParameters | FOREIGN KEY columnList REFERENCES tableName columnList ; excludeElement : (columnName | expr) opclass? (ASC | DESC)? (NULLS (FIRST | LAST))? ; privateExprOfDb: aggregateExpression |windowFunction |arrayConstructorWithCast |(TIMESTAMP (WITH TIME ZONE)? STRING) |extractFromFunction ; pgExpr : castExpr | collateExpr | expr ; aggregateExpression : ID (LEFT_PAREN (ALL | DISTINCT)? exprs orderByClause? RIGHT_PAREN) asteriskWithParen (LEFT_PAREN exprs RIGHT_PAREN WITHIN GROUP LEFT_PAREN orderByClause RIGHT_PAREN) filterClause? ; filterClause : FILTER LEFT_PAREN WHERE booleanPrimary RIGHT_PAREN ; asteriskWithParen : LEFT_PAREN ASTERISK RIGHT_PAREN ; windowFunction : ID (exprsWithParen | asteriskWithParen) filterClause? windowFunctionWithClause ; windowFunctionWithClause : OVER (ID | LEFT_PAREN windowDefinition RIGHT_PAREN ) ; windowDefinition : ID? (PARTITION BY exprs)? (orderByExpr (COMMA orderByExpr)*)? frameClause? ; orderByExpr : ORDER BY expr (ASC | DESC | USING operator)? (NULLS (FIRST | LAST ))? ; operator : SAFE_EQ | EQ_OR_ASSIGN | NEQ | NEQ_SYM | GT | GTE | LT | LTE | AND_SYM | OR_SYM | NOT_SYM ; frameClause : (RANGE | ROWS) frameStart | (RANGE | ROWS ) BETWEEN frameStart AND frameEnd ; frameStart : UNBOUNDED PRECEDING | NUMBER PRECEDING | CURRENT ROW | NUMBER FOLLOWING | UNBOUNDED FOLLOWING ; frameEnd : frameStart ; castExpr : CAST LEFT_PAREN expr AS dataType RIGHT_PAREN | expr COLON COLON dataType ; castExprWithColon : COLON COLON dataType(LEFT_BRACKET RIGHT_BRACKET)* ; collateExpr : expr COLLATE expr ; arrayConstructorWithCast : arrayConstructor castExprWithColon? | ARRAY LEFT_BRACKET RIGHT_BRACKET castExprWithColon ; arrayConstructor : ARRAY LEFT_BRACKET exprs RIGHT_BRACKET | ARRAY LEFT_BRACKET arrayConstructor (COMMA arrayConstructor)* RIGHT_BRACKET ; extractFromFunction : EXTRACT LEFT_PAREN ID FROM ID RIGHT_PAREN ;
grammar PostgreBase; import PostgreKeyword, DataType, Keyword, Symbol, BaseRule; columnDefinition : columnName dataType collateClause? columnConstraint* ; dataType : typeName intervalFields? dataTypeLength? (WITHOUT TIME ZONE | WITH TIME ZONE)? (LEFT_BRACKET RIGHT_BRACKET)* | ID ; typeName : DOUBLE PRECISION | CHARACTER VARYING? | BIT VARYING? | ID ; intervalFields : intervalField (TO intervalField)? ; intervalField : YEAR | MONTH | DAY | HOUR | MINUTE | SECOND ; collateClause : COLLATE collationName ; usingIndexType: USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN) ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT constraintName ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LEFT_PAREN sequenceOptions RIGHT_PAREN)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName (LEFT_PAREN columnName RIGHT_PAREN)? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)?(ON DELETE action)? (ON UPDATE action)? ; checkOption : CHECK expr (NO INHERIT )? ; defaultExpr : CURRENT_TIMESTAMP | expr; sequenceOptions: sequenceOption (START WITH? NUMBER)? (CACHE NUMBER)? (NO? CYCLE)? ; sequenceOption : (INCREMENT BY? NUMBER)? (MINVALUE NUMBER | NO MINVALUE)? (MAXVALUE NUMBER | NO MAXVALUE)? ; indexParameters : (USING INDEX TABLESPACE tablespaceName)? ; action : NO ACTION | RESTRICT | CASCADE | SET NULL | SET DEFAULT ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED |IMMEDIATE))? ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnList indexParameters | primaryKey columnList indexParameters | FOREIGN KEY columnList REFERENCES tableName columnList ; excludeElement : (columnName | expr) opclass? (ASC | DESC)? (NULLS (FIRST | LAST))? ; privateExprOfDb: aggregateExpression |windowFunction |arrayConstructorWithCast |(TIMESTAMP (WITH TIME ZONE)? STRING) |extractFromFunction ; pgExpr : castExpr | collateExpr | expr ; aggregateExpression : ID (LEFT_PAREN (ALL | DISTINCT)? exprs orderByClause? RIGHT_PAREN) asteriskWithParen (LEFT_PAREN exprs RIGHT_PAREN WITHIN GROUP LEFT_PAREN orderByClause RIGHT_PAREN) filterClause? ; filterClause : FILTER LEFT_PAREN WHERE booleanPrimary RIGHT_PAREN ; asteriskWithParen : LEFT_PAREN ASTERISK RIGHT_PAREN ; windowFunction : ID (exprsWithParen | asteriskWithParen) filterClause? windowFunctionWithClause ; windowFunctionWithClause : OVER (ID | LEFT_PAREN windowDefinition RIGHT_PAREN ) ; windowDefinition : ID? (PARTITION BY exprs)? (orderByExpr (COMMA orderByExpr)*)? frameClause? ; orderByExpr : ORDER BY expr (ASC | DESC | USING operator)? (NULLS (FIRST | LAST ))? ; operator : SAFE_EQ | EQ_OR_ASSIGN | NEQ | NEQ_SYM | GT | GTE | LT | LTE | AND_SYM | OR_SYM | NOT_SYM ; frameClause : (RANGE | ROWS) frameStart | (RANGE | ROWS ) BETWEEN frameStart AND frameEnd ; frameStart : UNBOUNDED PRECEDING | NUMBER PRECEDING | CURRENT ROW | NUMBER FOLLOWING | UNBOUNDED FOLLOWING ; frameEnd : frameStart ; castExpr : CAST LEFT_PAREN expr AS dataType RIGHT_PAREN | expr COLON COLON dataType ; castExprWithColon : COLON COLON dataType(LEFT_BRACKET RIGHT_BRACKET)* ; collateExpr : expr COLLATE expr ; arrayConstructorWithCast : arrayConstructor castExprWithColon? | ARRAY LEFT_BRACKET RIGHT_BRACKET castExprWithColon ; arrayConstructor : ARRAY LEFT_BRACKET exprs RIGHT_BRACKET | ARRAY LEFT_BRACKET arrayConstructor (COMMA arrayConstructor)* RIGHT_BRACKET ; extractFromFunction : EXTRACT LEFT_PAREN ID FROM ID RIGHT_PAREN ;
Simplify typeName rule
Simplify typeName rule
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
14f44e9fee73dc25d22113cbe3741af150855dd6
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
grammar OracleDCLStatement; import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol; /** * each statement has a url, * each base url : https://docs.oracle.com/database/121/SQLRF/. * no begin statement in oracle */ //statements_9014.htm#SQLRF01603 grant : GRANT ( (grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))? | grantRolesToPrograms ) ; grantSystemPrivileges : systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)? ; systemObjects : systemObject(COMMA systemObject)* ; systemObject : ALL PRIVILEGES | roleName | systemPrivilege ; systemPrivilege : ID *? ; grantees : grantee (COMMA grantee)* ; grantee : userName | roleName | PUBLIC ; granteeIdentifiedBy : userName (COMMA userName)* IDENTIFIED BY STRING (COMMA STRING)* ; grantObjectPrivilegeClause : grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause TO granteeClause(WITH HIERARCHY OPTION)?(WITH GRANT OPTION)? ; grantObjectPrivilege : (objectPrivilege | ALL PRIVILEGES?)( LP_ columnName (COMMA columnName)* RP_)? ; objectPrivilege : ID *? ; onObjectClause : ON ( schemaName? ID | USER userName ( COMMA userName)* | (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID ) ; grantRolesToPrograms : roleName (COMMA roleName)* TO programUnit ( COMMA programUnit )* ; programUnit : (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID ;
grammar OracleDCLStatement; import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol; /** * each statement has a url, * each base url : https://docs.oracle.com/database/121/SQLRF/. * no begin statement in oracle */ //statements_9014.htm#SQLRF01603 grant : GRANT ( (grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))? | grantRolesToPrograms ) ; grantSystemPrivileges : systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)? ; systemObjects : systemObject(COMMA systemObject)* ; systemObject : ALL PRIVILEGES | roleName | systemPrivilege ; systemPrivilege : ID *? ; grantees : grantee (COMMA grantee)* ; grantee : userName | roleName | PUBLIC ; granteeIdentifiedBy : userName (COMMA userName)* IDENTIFIED BY STRING (COMMA STRING)* ; grantObjectPrivilegeClause : grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause TO grantees (WITH HIERARCHY OPTION)?(WITH GRANT OPTION)? ; grantObjectPrivilege : (objectPrivilege | ALL PRIVILEGES?)( LP_ columnName (COMMA columnName)* RP_)? ; objectPrivilege : ID *? ; onObjectClause : ON ( schemaName? ID | USER userName ( COMMA userName)* | (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID ) ; grantRolesToPrograms : roleName (COMMA roleName)* TO programUnit ( COMMA programUnit )* ; programUnit : (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID ;
rename granteeClause to grantees
rename granteeClause to grantees
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
2481992c8fdf536248a869470bfaa7662ec8fe3c
src/main/antlr4/JmesPath.g4
src/main/antlr4/JmesPath.g4
grammar JmesPath; import JSON; query : expression EOF ; expression : expression '.' (IDENTIFIER | multi_select_list | multi_select_hash | function_expression | '*') | expression bracket_specifier | bracket_specifier | expression '||' expression | IDENTIFIER | expression '&&' expression | expression COMPARATOR expression | not_expression | paren_expression | '*' | multi_select_list | multi_select_hash | literal | function_expression | expression '|' expression | RAW_STRING | current_node ; not_expression : '!' expression ; paren_expression : '(' expression ')' ; multi_select_list : '[' expression (',' expression)* ']' ; multi_select_hash : '{' keyval_expr (',' keyval_expr)* '}' ; keyval_expr : IDENTIFIER ':' expression ; bracket_specifier : '[' (SIGNED_INT | '*' | SLICE_EXPRESSION) ']' | '[]' | '[' '?' expression ']' ; SLICE_EXPRESSION : SIGNED_INT? ':' SIGNED_INT? (':' SIGNED_INT?)? ; COMPARATOR : '<' | '<=' | '==' | '>=' | '>' | '!=' ; // TODO: should be UNQUOTED_STRING and not IDENTIFIER, but that doesn't work function_expression : IDENTIFIER (no_args | one_or_more_args) ; no_args : '(' ')' ; one_or_more_args : '(' function_arg (',' function_arg)* ')' ; function_arg : expression | expression_type ; current_node : '@' ; expression_type : '&' expression ; RAW_STRING : '\'' (ESCAPE '\'' | ~['\\])* '\'' ; literal : '`' value '`' ; SIGNED_INT : '-'? DIGIT+ ; fragment ESCAPE : '\\' ; DIGIT : [0-9] ; LETTER : [a-zA-Z] ; IDENTIFIER : UNQUOTED_STRING | STRING ; fragment UNQUOTED_STRING : LETTER (LETTER | DIGIT | '_')* ; WS : [ \t\r\n]+ -> skip ;
grammar JmesPath; import JSON; query : expression EOF ; expression : expression '.' (IDENTIFIER | multi_select_list | multi_select_hash | function_expression | '*') | expression bracket_specifier | bracket_specifier | expression '||' expression | IDENTIFIER | expression '&&' expression | expression COMPARATOR expression | not_expression | paren_expression | '*' | multi_select_list | multi_select_hash | literal | function_expression | expression '|' expression | RAW_STRING | current_node ; not_expression : '!' expression ; paren_expression : '(' expression ')' ; multi_select_list : '[' expression (',' expression)* ']' ; multi_select_hash : '{' keyval_expr (',' keyval_expr)* '}' ; keyval_expr : IDENTIFIER ':' expression ; bracket_specifier : '[' (SIGNED_INT | '*' | SLICE_EXPRESSION) ']' | '[]' | '[' '?' expression ']' ; SLICE_EXPRESSION : SIGNED_INT? ':' SIGNED_INT? (':' SIGNED_INT?)? ; COMPARATOR : '<' | '<=' | '==' | '>=' | '>' | '!=' ; // TODO: should be UNQUOTED_STRING and not IDENTIFIER, but that doesn't work function_expression : IDENTIFIER (no_args | one_or_more_args) ; no_args : '(' ')' ; one_or_more_args : '(' function_arg (',' function_arg)* ')' ; function_arg : expression | expression_type ; current_node : '@' ; expression_type : '&' expression ; RAW_STRING : '\'' (ESCAPE '\'' | ~['\\])* '\'' ; literal : '`' value '`' ; SIGNED_INT : '-'? DIGIT+ ; fragment ESCAPE : '\\' ; DIGIT : [0-9] ; LETTER : [a-zA-Z] ; IDENTIFIER : UNQUOTED_STRING | STRING ; fragment UNQUOTED_STRING : LETTER (LETTER | DIGIT | '_')* ;
Use JSON.g4's definition of WS, it's the same
Use JSON.g4's definition of WS, it's the same
ANTLR
bsd-3-clause
burtcorp/jmespath-java
b3511c646e6f136a0545f49d4f8a62f122c39b1c
webidl/WebIDL.g4
webidl/WebIDL.g4
/* BSD License Copyright (c) 2013,2015 Rainer Schuster All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Rainer Schuster nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Web IDL grammar derived from: http://heycam.github.io/webidl/ Web IDL (Second Edition) W3C Editor's Draft 17 November 2015 */ grammar WebIDL; // Note: Replaced keywords: const, default, enum, interface, null. // Note: Added "wrapper" rule webIDL with EOF token. webIDL : definitions EOF ; definitions : extendedAttributeList definition definitions | /* empty */ ; definition : callbackOrInterface | partial | dictionary | enum_ | typedef_ | implementsStatement ; callbackOrInterface : 'callback' callbackRestOrInterface | interface_ | class_ ; callbackRestOrInterface : callbackRest | interface_ ; interface_ : 'interface' IDENTIFIER_WEBIDL inheritance '{' interfaceMembers '}' ';' ; class_ : 'class' IDENTIFIER_WEBIDL extension_ '{' interfaceMembers '}' ';' ; partial : 'partial' partialDefinition ; partialDefinition : partialInterface | partialDictionary ; partialInterface : 'interface' IDENTIFIER_WEBIDL '{' interfaceMembers '}' ';' ; interfaceMembers : extendedAttributeList interfaceMember interfaceMembers | /* empty */ ; interfaceMember : const_ | operation | serializer | stringifier | staticMember | iterable | readonlyMember | readWriteAttribute | readWriteMaplike | readWriteSetlike ; dictionary : 'dictionary' IDENTIFIER_WEBIDL inheritance '{' dictionaryMembers '}' ';' ; dictionaryMembers : extendedAttributeList dictionaryMember dictionaryMembers | /* empty */ ; dictionaryMember : required_ type_ IDENTIFIER_WEBIDL default_ ';' ; required_ : 'required' | /* empty */ ; partialDictionary : 'dictionary' IDENTIFIER_WEBIDL '{' dictionaryMembers '}' ';' ; default_ : '=' defaultValue | /* empty */ ; defaultValue : constValue | STRING_WEBIDL | '[' ']' ; inheritance : ':' IDENTIFIER_WEBIDL | /* empty */ ; extension_ : 'extends' IDENTIFIER_WEBIDL | /* empty */ ; enum_ : 'enum' IDENTIFIER_WEBIDL '{' enumValueList '}' ';' ; enumValueList : STRING_WEBIDL enumValueListComma ; enumValueListComma : ',' enumValueListString | /* empty */ ; enumValueListString : STRING_WEBIDL enumValueListComma | /* empty */ ; callbackRest : IDENTIFIER_WEBIDL '=' returnType '(' argumentList ')' ';' ; typedef_ : 'typedef' type_ IDENTIFIER_WEBIDL ';' ; implementsStatement : IDENTIFIER_WEBIDL 'implements' IDENTIFIER_WEBIDL ';' ; const_ : 'const' constType IDENTIFIER_WEBIDL '=' constValue ';' ; constValue : booleanLiteral | floatLiteral | INTEGER_WEBIDL | 'null' ; booleanLiteral : 'true' | 'false' ; floatLiteral : FLOAT_WEBIDL | '-Infinity' | 'Infinity' | 'NaN' ; serializer : 'serializer' serializerRest ; serializerRest : operationRest | '=' serializationPattern ';' | ';' ; serializationPattern : '{' serializationPatternMap '}' | '[' serializationPatternList ']' | IDENTIFIER_WEBIDL ; serializationPatternMap : 'getter' | 'inherit' identifiers | IDENTIFIER_WEBIDL identifiers | /* empty */ ; serializationPatternList : 'getter' | IDENTIFIER_WEBIDL identifiers | /* empty */ ; stringifier : 'stringifier' stringifierRest ; stringifierRest : readOnly attributeRest | returnType operationRest | ';' ; staticMember : 'static' staticMemberRest ; staticMemberRest : readOnly attributeRest | returnType operationRest ; readonlyMember : 'readonly' readonlyMemberRest ; readonlyMemberRest : attributeRest | readWriteMaplike | readWriteSetlike ; readWriteAttribute : 'inherit' readOnly attributeRest | attributeRest ; attributeRest : 'attribute' type_ attributeName ';' ; attributeName : attributeNameKeyword | IDENTIFIER_WEBIDL ; attributeNameKeyword : 'required' ; inherit : 'inherit' | /* empty */ ; readOnly : 'readonly' | /* empty */ ; operation : returnType operationRest | specialOperation ; specialOperation : special specials returnType operationRest ; specials : special specials | /* empty */ ; special : 'getter' | 'setter' | 'deleter' | 'legacycaller' ; operationRest : optionalIdentifier '(' argumentList ')' ';' ; optionalIdentifier : IDENTIFIER_WEBIDL | /* empty */ ; argumentList : argument arguments | /* empty */ ; arguments : ',' argument arguments | /* empty */ ; argument : extendedAttributeList optionalOrRequiredArgument ; optionalOrRequiredArgument : 'optional' type_ argumentName default_ | type_ ellipsis argumentName ; argumentName : argumentNameKeyword | IDENTIFIER_WEBIDL ; ellipsis : '...' | /* empty */ ; iterable : 'iterable' '<' type_ optionalType '>' ';' ; optionalType : ',' type_ | /* empty */ ; readWriteMaplike : maplikeRest ; readWriteSetlike : setlikeRest ; maplikeRest : 'maplike' '<' type_ ',' type_ '>' ';' ; setlikeRest : 'setlike' '<' type_ '>' ';' ; extendedAttributeList : '[' extendedAttribute extendedAttributes ']' | /* empty */ ; extendedAttributes : ',' extendedAttribute extendedAttributes | /* empty */ ; extendedAttribute : '(' extendedAttributeInner ')' extendedAttributeRest | '[' extendedAttributeInner ']' extendedAttributeRest | '{' extendedAttributeInner '}' extendedAttributeRest | other extendedAttributeRest ; extendedAttributeRest : extendedAttribute | /* empty */ ; extendedAttributeInner : '(' extendedAttributeInner ')' extendedAttributeInner | '[' extendedAttributeInner ']' extendedAttributeInner | '{' extendedAttributeInner '}' extendedAttributeInner | otherOrComma extendedAttributeInner | /* empty */ ; other : INTEGER_WEBIDL | FLOAT_WEBIDL | IDENTIFIER_WEBIDL | STRING_WEBIDL | OTHER_WEBIDL | '-' | '-Infinity' | '.' | '...' | ':' | ';' | '<' | '=' | '>' | '?' | 'ByteString' | 'DOMString' | 'FrozenArray' | 'Infinity' | 'NaN' | 'RegExp' | 'USVString' | 'any' | 'boolean' | 'byte' | 'double' | 'false' | 'float' | 'long' | 'null' | 'object' | 'octet' | 'or' | 'optional' | 'sequence' | 'short' | 'true' | 'unsigned' | 'void' | argumentNameKeyword | bufferRelatedType ; argumentNameKeyword : 'attribute' | 'callback' | 'const' | 'deleter' | 'dictionary' | 'enum' | 'getter' | 'implements' | 'inherit' | 'interface' | 'iterable' | 'legacycaller' | 'maplike' | 'partial' | 'required' | 'serializer' | 'setlike' | 'setter' | 'static' | 'stringifier' | 'typedef' | 'unrestricted' ; otherOrComma : other | ',' ; type_ : singleType | unionType null_ ; singleType : nonAnyType | 'any' ; unionType : '(' unionMemberType 'or' unionMemberType unionMemberTypes ')' ; unionMemberType : nonAnyType | unionType null_ ; unionMemberTypes : 'or' unionMemberType unionMemberTypes | /* empty */ ; nonAnyType : primitiveType null_ | promiseType null_ | 'ByteString' null_ | 'DOMString' null_ | 'USVString' null_ | IDENTIFIER_WEBIDL null_ | 'sequence' '<' type_ '>' null_ | 'object' null_ | 'RegExp' null_ | 'DOMException' null_ | bufferRelatedType null_ | 'FrozenArray' '<' type_ '>' null_ ; bufferRelatedType : 'ArrayBuffer' | 'DataView' | 'Int8Array' | 'Int16Array' | 'Int32Array' | 'Uint8Array' | 'Uint16Array' | 'Uint32Array' | 'Uint8ClampedArray' | 'Float32Array' | 'Float64Array' ; constType : primitiveType null_ | IDENTIFIER_WEBIDL null_ ; primitiveType : unsignedIntegerType | unrestrictedFloatType | 'boolean' | 'byte' | 'octet' ; unrestrictedFloatType : 'unrestricted' floatType | floatType ; floatType : 'float' | 'double' ; unsignedIntegerType : 'unsigned' integerType | integerType ; integerType : 'short' | 'long' optionalLong ; optionalLong : 'long' | /* empty */ ; promiseType : 'Promise' '<' returnType '>' ; null_ : '?' | /* empty */ ; returnType : type_ | 'void' ; identifierList : IDENTIFIER_WEBIDL identifiers ; identifiers : ',' IDENTIFIER_WEBIDL identifiers | /* empty */ ; extendedAttributeNoArgs : IDENTIFIER_WEBIDL ; extendedAttributeArgList : IDENTIFIER_WEBIDL '(' argumentList ')' ; extendedAttributeIdent : IDENTIFIER_WEBIDL '=' IDENTIFIER_WEBIDL ; extendedAttributeIdentList : IDENTIFIER_WEBIDL '=' '(' identifierList ')' ; extendedAttributeNamedArgList : IDENTIFIER_WEBIDL '=' IDENTIFIER_WEBIDL '(' argumentList ')' ; INTEGER_WEBIDL : '-'?('0'([Xx][0-9A-Fa-f]+|[0-7]*)|[1-9][0-9]*) ; FLOAT_WEBIDL : '-'?(([0-9]+'.'[0-9]*|[0-9]*'.'[0-9]+)([Ee][+\-]?[0-9]+)?|[0-9]+[Ee][+\-]?[0-9]+) ; IDENTIFIER_WEBIDL : [A-Z_a-z][0-9A-Z_a-z]* ; STRING_WEBIDL : '"' ~["]* '"' ; WHITESPACE_WEBIDL : [\t\n\r ]+ -> channel(HIDDEN) ; COMMENT_WEBIDL : ('//'~[\n\r]*|'/*'(.|'\n')*?'*/')+ -> channel(HIDDEN) ; // Note: '/''/'~[\n\r]* instead of '/''/'.* (non-greedy because of wildcard). OTHER_WEBIDL : ~[\t\n\r 0-9A-Z_a-z] ;
/* BSD License Copyright (c) 2013,2015 Rainer Schuster Copyright (c) 2021 ethanmdavidson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Rainer Schuster nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Web IDL grammar derived from: http://heycam.github.io/webidl/ Web IDL (Second Edition) Editor’s Draft, 3 May 2021 */ grammar WebIDL; // Note: Replaced keywords: const, default, enum, interface, null. // Note: Added "wrapper" rule webIDL with EOF token. webIDL : definitions EOF ; definitions : extendedAttributeList definition definitions | /* empty */ ; definition : callbackOrInterfaceOrMixin | namespace | partial | dictionary | enum_ | typedef_ | includesStatement ; argumentNameKeyword : 'async' | 'attribute' | 'callback' | 'const' | 'constructor' | 'deleter' | 'dictionary' | 'enum' | 'getter' | 'includes' | 'inherit' | 'interface' | 'iterable' | 'maplike' | 'mixin' | 'namespace' | 'partial' | 'readonly' | 'required' | 'setlike' | 'setter' | 'static' | 'stringifier' | 'typedef' | 'unrestricted' ; callbackOrInterfaceOrMixin : 'callback' callbackRestOrInterface | 'interface' interfaceOrMixin ; interfaceOrMixin : interfaceRest | mixinRest ; interfaceRest : IDENTIFIER_WEBIDL inheritance '{' interfaceMembers '}' ';' ; partial : 'partial' partialDefinition ; partialDefinition : 'interface' partialInterfaceOrPartialMixin | partialDictionary | namespace ; partialInterfaceOrPartialMixin : partialInterfaceRest | mixinRest ; partialInterfaceRest : IDENTIFIER_WEBIDL '{' partialInterfaceMembers '}' ';' ; interfaceMembers : extendedAttributeList interfaceMember interfaceMembers | /* empty */ ; interfaceMember : partialInterfaceMember | constructor ; partialInterfaceMembers : extendedAttributeList partialInterfaceMember partialInterfaceMembers | /* empty */ ; partialInterfaceMember : const_ | operation | stringifier | staticMember | iterable | asyncIterable | readonlyMember | readWriteAttribute | readWriteMaplike | readWriteSetlike | inheritAttribute ; inheritance : ':' IDENTIFIER_WEBIDL | /* empty */ ; mixinRest : 'mixin' IDENTIFIER_WEBIDL '{' mixinMembers '}' ';' ; mixinMembers : extendedAttributeList mixinMember mixinMembers | /* empty */ ; mixinMember : const_ | regularOperation | stringifier | optionalReadOnly attributeRest ; includesStatement : IDENTIFIER_WEBIDL 'includes' IDENTIFIER_WEBIDL ';' ; callbackRestOrInterface : callbackRest | 'interface' IDENTIFIER_WEBIDL '{' callbackInterfaceMembers '}' ';' ; callbackInterfaceMembers : extendedAttributeList callbackInterfaceMember callbackInterfaceMembers | /* empty */ ; callbackInterfaceMember : const_ | regularOperation ; const_ : 'const' constType IDENTIFIER_WEBIDL '=' constValue ';' ; constValue : booleanLiteral | floatLiteral | INTEGER_WEBIDL | 'null' //TODO: webidl grammar doesn't include null in constValue, but // the docs seem to imply that its valid ; booleanLiteral : 'true' | 'false' ; floatLiteral : DECIMAL_WEBIDL | '-Infinity' | 'Infinity' | 'NaN' ; constType : primitiveType | IDENTIFIER_WEBIDL ; readonlyMember : 'readonly' readonlyMemberRest ; readonlyMemberRest : attributeRest | maplikeRest | setlikeRest ; readWriteAttribute : attributeRest ; inheritAttribute : 'inherit' attributeRest ; attributeRest : 'attribute' typeWithExtendedAttributes attributeName ';' ; attributeName : attributeNameKeyword | IDENTIFIER_WEBIDL ; attributeNameKeyword : 'async' | 'required' ; optionalReadOnly : 'readonly' | /* empty */ ; defaultValue : constValue | STRING_WEBIDL | '[' ']' | '{' '}' | 'null' ; operation : regularOperation | specialOperation ; regularOperation : type_ operationRest ; specialOperation : special regularOperation ; special : 'getter' | 'setter' | 'deleter' ; operationRest : optionalOperationName '(' argumentList ')' ';' ; optionalOperationName : operationName | /* empty */ ; operationName : operationNameKeyword | IDENTIFIER_WEBIDL ; operationNameKeyword : 'includes' ; argumentList : argument arguments | /* empty */ ; arguments : ',' argument arguments | /* empty */ ; argument : extendedAttributeList argumentRest ; argumentRest : 'optional' typeWithExtendedAttributes argumentName default_ | type_ ellipsis argumentName ; argumentName : argumentNameKeyword | IDENTIFIER_WEBIDL ; ellipsis : '...' | /* empty */ ; constructor : 'constructor' '(' argumentList ')' ';' ; stringifier : 'stringifier' stringifierRest ; stringifierRest : optionalReadOnly attributeRest | regularOperation | ';' ; staticMember : 'static' staticMemberRest ; staticMemberRest : optionalReadOnly attributeRest | regularOperation ; iterable : 'iterable' '<' typeWithExtendedAttributes optionalType '>' ';' ; optionalType : ',' typeWithExtendedAttributes | /* empty */ ; asyncIterable : 'async' 'iterable' '<' typeWithExtendedAttributes optionalType '>' optionalArgumentList ';' ; optionalArgumentList : '(' argumentList ')' | /* empty */ ; readWriteMaplike : maplikeRest ; maplikeRest : 'maplike' '<' typeWithExtendedAttributes ',' typeWithExtendedAttributes '>' ';' ; readWriteSetlike : setlikeRest ; setlikeRest : 'setlike' '<' typeWithExtendedAttributes '>' ';' ; namespace : 'namespace' IDENTIFIER_WEBIDL '{' namespaceMembers '}' ';' ; namespaceMembers : extendedAttributeList namespaceMember namespaceMembers | /* empty */ ; namespaceMember : regularOperation | 'readonly' attributeRest | const_ ; dictionary : 'dictionary' IDENTIFIER_WEBIDL inheritance '{' dictionaryMembers '}' ';' ; dictionaryMembers : dictionaryMember dictionaryMembers | /* empty */ ; dictionaryMember : extendedAttributeList dictionaryMemberRest ; dictionaryMemberRest : 'required' typeWithExtendedAttributes IDENTIFIER_WEBIDL ';' | type_ IDENTIFIER_WEBIDL default_ ';' ; partialDictionary : 'dictionary' IDENTIFIER_WEBIDL '{' dictionaryMembers '}' ';' ; default_ : '=' defaultValue | /* empty */ ; enum_ : 'enum' IDENTIFIER_WEBIDL '{' enumValueList '}' ';' ; enumValueList : STRING_WEBIDL enumValueListComma ; enumValueListComma : ',' enumValueListString | /* empty */ ; enumValueListString : STRING_WEBIDL enumValueListComma | /* empty */ ; callbackRest : IDENTIFIER_WEBIDL '=' type_ '(' argumentList ')' ';' ; typedef_ : 'typedef' typeWithExtendedAttributes IDENTIFIER_WEBIDL ';' ; type_ : singleType | unionType null_ ; typeWithExtendedAttributes : extendedAttributeList type_ ; singleType : distinguishableType | 'any' | promiseType ; unionType : '(' unionMemberType 'or' unionMemberType unionMemberTypes ')' ; unionMemberType : extendedAttributeList distinguishableType | unionType null_ ; unionMemberTypes : 'or' unionMemberType unionMemberTypes | /* empty */ ; distinguishableType : primitiveType null_ | stringType null_ | IDENTIFIER_WEBIDL null_ | 'sequence' '<' typeWithExtendedAttributes '>' null_ | 'object' null_ | 'symbol' null_ | bufferRelatedType null_ | 'FrozenArray' '<' typeWithExtendedAttributes '>' null_ | 'ObservableArray' '<' typeWithExtendedAttributes '>' null_ | recordType null_ ; primitiveType : unsignedIntegerType | unrestrictedFloatType | 'undefined' | 'boolean' | 'byte' | 'octet' | 'bigint' ; unrestrictedFloatType : 'unrestricted' floatType | floatType ; floatType : 'float' | 'double' ; unsignedIntegerType : 'unsigned' integerType | integerType ; integerType : 'short' | 'long' optionalLong ; optionalLong : 'long' | /* empty */ ; stringType : 'ByteString' | 'DOMString' | 'USVString' ; promiseType : 'Promise' '<' type_ '>' ; recordType : 'record' '<' stringType ',' typeWithExtendedAttributes '>' ; null_ : '?' | /* empty */ ; bufferRelatedType : 'ArrayBuffer' | 'DataView' | 'Int8Array' | 'Int16Array' | 'Int32Array' | 'Uint8Array' | 'Uint16Array' | 'Uint32Array' | 'Uint8ClampedArray' | 'Float32Array' | 'Float64Array' ; extendedAttributeList : '[' extendedAttribute extendedAttributes ']' | /* empty */ ; extendedAttributes : ',' extendedAttribute extendedAttributes | /* empty */ ; extendedAttribute : '(' extendedAttributeInner ')' extendedAttributeRest | '[' extendedAttributeInner ']' extendedAttributeRest | '{' extendedAttributeInner '}' extendedAttributeRest | other extendedAttributeRest ; extendedAttributeRest : extendedAttribute | /* empty */ ; extendedAttributeInner : '(' extendedAttributeInner ')' extendedAttributeInner | '[' extendedAttributeInner ']' extendedAttributeInner | '{' extendedAttributeInner '}' extendedAttributeInner | otherOrComma extendedAttributeInner | /* empty */ ; other : INTEGER_WEBIDL | DECIMAL_WEBIDL | IDENTIFIER_WEBIDL | STRING_WEBIDL | OTHER_WEBIDL | '-' | '-Infinity' | '.' | '...' | ':' | ';' | '<' | '=' | '>' | '?' | 'ByteString' | 'DOMString' | 'FrozenArray' | 'Infinity' | 'NaN' | 'ObservableArray' | 'Promise' | 'USVString' | 'any' | 'bigint' | 'boolean' | 'byte' | 'double' | 'false' | 'float' | 'long' | 'null' | 'object' | 'octet' | 'or' | 'optional' | 'record' | 'sequence' | 'short' | 'symbol' | 'true' | 'unsigned' | 'undefined' | argumentNameKeyword | bufferRelatedType ; otherOrComma : other | ',' ; identifierList : IDENTIFIER_WEBIDL identifiers ; identifiers : ',' IDENTIFIER_WEBIDL identifiers | /* empty */ ; extendedAttributeNoArgs : IDENTIFIER_WEBIDL ; extendedAttributeArgList : IDENTIFIER_WEBIDL '(' argumentList ')' ; extendedAttributeIdent : IDENTIFIER_WEBIDL '=' IDENTIFIER_WEBIDL ; extendedAttributeIdentList : IDENTIFIER_WEBIDL '=' '(' identifierList ')' ; extendedAttributeNamedArgList : IDENTIFIER_WEBIDL '=' IDENTIFIER_WEBIDL '(' argumentList ')' ; INTEGER_WEBIDL : '-'?('0'([Xx][0-9A-Fa-f]+|[0-7]*)|[1-9][0-9]*) ; DECIMAL_WEBIDL : '-'?(([0-9]+'.'[0-9]*|[0-9]*'.'[0-9]+)([Ee][+\-]?[0-9]+)?|[0-9]+[Ee][+\-]?[0-9]+) ; IDENTIFIER_WEBIDL : [_-]?[A-Z_a-z][0-9A-Z_a-z]* ; STRING_WEBIDL : '"' ~["]* '"' ; WHITESPACE_WEBIDL : [\t\n\r ]+ -> channel(HIDDEN) ; COMMENT_WEBIDL : ('//'~[\n\r]*|'/*'(.|'\n')*?'*/')+ -> channel(HIDDEN) ; // Note: '/''/'~[\n\r]* instead of '/''/'.* (non-greedy because of wildcard). OTHER_WEBIDL : ~[\t\n\r 0-9A-Z_a-z] ;
update to 3 May 2021 editors draft
update to 3 May 2021 editors draft
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
6f44cc2e7d64abb9db0d2236622fafefe61e7ff5
refal/refal.g4
refal/refal.g4
/* BSD License Copyright (c) 2021, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar refal; program : f_definition (';'? program)? | external_decl ';' program | program external_decl ';' ; f_definition : f_name '{' block_ '}' | '$ENTRY' f_name '{' block_ '}' ; external_decl : ('$EXTERNAL' | '$EXTERN' | '$EXTRN') f_name_list ; f_name_list : f_name (',' f_name_list ';')? ; f_name : identifier ; block_ : sentence | sentence ';' | sentence ';' block_ ; sentence : left_side conditions ('=' right_side | ',' block_ending) ; left_side : pattern ; conditions : (',' arg_ ':' pattern conditions)? ; pattern : expression_ ; arg_ : expression_ ; right_side : expression_ ; expression_ : (term_ expression_)? ; term_ : symbol | variable | '<' expression_ '>' ; block_ending : arg_ ':' '{' block_ '}' ; symbol : identifier | DIGITS | STRING | STRING2 | CHAR ; identifier : IDENTIFER | STRING ; variable : svar | tvar | evar ; svar : 's' '.' index ; tvar : 't' '.' index ; evar : 'e' '.' index ; index : identifier | DIGITS ; DIGITS : [0-9]+ ; IDENTIFER : [a-zA-Z] [a-zA-Z0-9_-]* ; STRING : '"' ~ '"'* '"' ; STRING2 : '\'' ~ '\''* '\'' ; CHAR : '\\\'' | '\\"' | '\\\\' | '\\n' | '\\r' | '\\t' | ('\\x' [0-9] [0-9]) ; WS : [ \r\n\t]+ -> skip ;
/* BSD License Copyright (c) 2021, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar refal; program : f_definition (';'? program)? | external_decl ';' program | program external_decl ';' ; f_definition : f_name '{' block_ '}' | '$ENTRY' f_name '{' block_ '}' ; external_decl : ('$EXTERNAL' | '$EXTERN' | '$EXTRN') f_name_list ; f_name_list : f_name (',' f_name_list ';')? ; f_name : identifier ; block_ : sentence | sentence ';' | sentence ';' block_ ; sentence : left_side conditions ('=' right_side | ',' block_ending) ; left_side : pattern ; conditions : (',' arg_ ':' pattern conditions)? ; pattern : expression_ ; arg_ : expression_ ; right_side : expression_ ; expression_ : (term_ expression_)? ; term_ : symbol | variable | '<' expression_ '>' ; block_ending : arg_ ':' '{' block_ '}' ; symbol : identifier | DIGITS | STRING | STRING2 | CHAR ; identifier : IDENTIFER | STRING ; variable : svar | tvar | evar ; svar : 's' '.' index ; tvar : 't' '.' index ; evar : 'e' '.' index ; index : identifier | DIGITS ; DIGITS : [0-9]+ ; IDENTIFER : [a-zA-Z] [a-zA-Z0-9_-]* ; STRING : '"' ~ '"'* '"' ; STRING2 : '\'' ~ '\''* '\'' ; CHAR : '\\\'' | '\\"' | '\\\\' | '\\n' | '\\r' | '\\t' | '\\x' [0-9] [0-9] ; WS : [ \r\n\t]+ -> skip ;
Update refal/refal.g4
Update refal/refal.g4 Co-authored-by: Ivan Kochurkin <[email protected]>
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
cfa8b77bb0ac7d09ab5258cfda07dafe2fd4922f
sharding-core/src/main/antlr4/imports/OracleKeyword.g4
sharding-core/src/main/antlr4/imports/OracleKeyword.g4
lexer grammar OracleKeyword; import Symbol; ADMIN : A D M I N ; AT : A T ; BATCH : B A T C H ; BITMAP : B I T M A P ; CACHE : C A C H E ; CASE : C A S E ; CHECKPOINT : C H E C K P O I N T ; COMMENT : C O M M E N T ; CONSTRAINTS : C O N S T R A I N T S ; CONTAINER : C O N T A I N E R ; CURRENT : C U R R E N T ; CYCLE : C Y C L E ; DAY : D A Y ; DBTIMEZONE : D B T I M E Z O N E ; DECRYPT : D E C R Y P T ; DEFERRABLE : D E F E R R A B L E ; DEFERRED : D E F E R R E D ; DELEGATE : D E L E G A T E ; DIRECTORY : D I R E C T O R Y ; DOUBLE : D O U B L E ; EDITION : E D I T I O N ; ELEMENT : E L E M E N T ; ELSE : E L S E ; ENCRYPT : E N C R Y P T ; END : E N D ; EXCEPTIONS : E X C E P T I O N S ; FOR : F O R ; FORCE : F O R C E ; FUNCTION : F U N C T I O N ; GLOBAL : G L O B A L ; GRANT : G R A N T ; HIERARCHY : H I E R A R C H Y ; IDENTIFIED : I D E N T I F I E D ; IDENTITY : I D E N T I T Y ; IMMEDIATE : I M M E D I A T E ; INCREMENT : I N C R E M E N T ; INITIALLY : I N I T I A L L Y ; INTERVAL : I N T E R V A L ; INTO : I N T O ; INVALIDATE : I N V A L I D A T E ; JAVA : J A V A ; KEEP : K E E P ; LEVELS : L E V E L S ; LOCAL : L O C A L ; MAXVALUE : M A X V A L U E ; MINING : M I N I N G ; MINVALUE : M I N V A L U E ; MODEL : M O D E L ; MODIFY : M O D I F Y ; MONTH : M O N T H ; NAME : N A M E ; NATIONAL : N A T I O N A L ; NEW : N E W ; NOCACHE : N O C A C H E ; NOCYCLE : N O C Y C L E ; NOMAXVALUE : N O M A X V A L U E ; NOMINVALUE : N O M I N V A L U E ; NOORDER : N O O R D E R ; NORELY : N O R E L Y ; NOVALIDATE : N O V A L I D A T E ; NOWAIT : N O W A I T ; OF : O F ; ONLY : O N L Y ; OPTION : O P T I O N ; PACKAGE : P A C K A G E ; PRECISION : P R E C I S I O N ; PRESERVE : P R E S E R V E ; PRIOR : P R I O R ; PRIVILEGES : P R I V I L E G E S ; PROCEDURE : P R O C E D U R E ; PROFILE : P R O F I L E ; PUBLIC : P U B L I C ; REF : R E F ; REKEY : R E K E Y ; RELY : R E L Y ; RENAME : R E N A M E ; RESOURCE : R E S O U R C E ; ROWID : R O W I D ; ROWS : R O W S ; SALT : S A L T ; SAVEPOINT : S A V E P O I N T ; SCOPE : S C O P E ; SECOND : S E C O N D ; SEGMENT : S E G M E N T ; SORT : S O R T ; SOURCE : S O U R C E ; SQL : S Q L ; SQLRF : S Q L R F ; SUBSTITUTABLE : S U B S T I T U T A B L E ; TABLESPACE : T A B L E S P A C E ; TEMPORARY : T E M P O R A R Y ; THEN : T H E N ; TRANSLATION : T R A N S L A T I O N ; TREAT : T R E A T ; TYPE : T Y P E ; UNUSED : U N U S E D ; USE : U S E ; USER : U S E R ; USING : U S I N G ; VALIDATE : V A L I D A T E ; VALUE : V A L U E ; VARYING : V A R Y I N G ; VIRTUAL : V I R T U A L ; WAIT : W A I T ; WHEN : W H E N ; WRITE : W R I T E ; ZONE : Z O N E ;
lexer grammar OracleKeyword; import Symbol; ADMIN : A D M I N ; AT : A T ; BATCH : B A T C H ; BITMAP : B I T M A P ; CACHE : C A C H E ; CASE : C A S E ; CHECKPOINT : C H E C K P O I N T ; COMMENT : C O M M E N T ; CONSTRAINTS : C O N S T R A I N T S ; CONTAINER : C O N T A I N E R ; CURRENT : C U R R E N T ; CYCLE : C Y C L E ; DAY : D A Y ; DBTIMEZONE : D B T I M E Z O N E ; DECRYPT : D E C R Y P T ; DEFERRABLE : D E F E R R A B L E ; DEFERRED : D E F E R R E D ; DELEGATE : D E L E G A T E ; DIRECTORY : D I R E C T O R Y ; DOUBLE : D O U B L E ; EDITION : E D I T I O N ; ELEMENT : E L E M E N T ; ELSE : E L S E ; ENCRYPT : E N C R Y P T ; END : E N D ; EXCEPTIONS : E X C E P T I O N S ; FOR : F O R ; FORCE : F O R C E ; FUNCTION : F U N C T I O N ; GLOBAL : G L O B A L ; GRANT : G R A N T ; HIERARCHY : H I E R A R C H Y ; IDENTIFIED : I D E N T I F I E D ; IDENTITY : I D E N T I T Y ; IMMEDIATE : I M M E D I A T E ; INCREMENT : I N C R E M E N T ; INITIALLY : I N I T I A L L Y ; INTERVAL : I N T E R V A L ; INTO : I N T O ; INVALIDATE : I N V A L I D A T E ; JAVA : J A V A ; KEEP : K E E P ; LEVELS : L E V E L S ; LOCAL : L O C A L ; MAXVALUE : M A X V A L U E ; MINING : M I N I N G ; MINVALUE : M I N V A L U E ; MODEL : M O D E L ; MODIFY : M O D I F Y ; MONTH : M O N T H ; NAME : N A M E ; NATIONAL : N A T I O N A L ; NEW : N E W ; NOCACHE : N O C A C H E ; NOCYCLE : N O C Y C L E ; NOMAXVALUE : N O M A X V A L U E ; NOMINVALUE : N O M I N V A L U E ; NOORDER : N O O R D E R ; NORELY : N O R E L Y ; NOVALIDATE : N O V A L I D A T E ; NOWAIT : N O W A I T ; OF : O F ; ONLY : O N L Y ; OPTION : O P T I O N ; PACKAGE : P A C K A G E ; PRECISION : P R E C I S I O N ; PRESERVE : P R E S E R V E ; PRIOR : P R I O R ; PRIVILEGES : P R I V I L E G E S ; PROCEDURE : P R O C E D U R E ; PROFILE : P R O F I L E ; PUBLIC : P U B L I C ; REF : R E F ; REKEY : R E K E Y ; RELY : R E L Y ; RENAME : R E N A M E ; RESOURCE : R E S O U R C E ; REVOKE : R E V O K E ; ROWID : R O W I D ; ROWS : R O W S ; SALT : S A L T ; SAVEPOINT : S A V E P O I N T ; SCOPE : S C O P E ; SECOND : S E C O N D ; SEGMENT : S E G M E N T ; SORT : S O R T ; SOURCE : S O U R C E ; SQL : S Q L ; SQLRF : S Q L R F ; SUBSTITUTABLE : S U B S T I T U T A B L E ; TABLESPACE : T A B L E S P A C E ; TEMPORARY : T E M P O R A R Y ; THEN : T H E N ; TRANSLATION : T R A N S L A T I O N ; TREAT : T R E A T ; TYPE : T Y P E ; UNUSED : U N U S E D ; USE : U S E ; USER : U S E R ; USING : U S I N G ; VALIDATE : V A L I D A T E ; VALUE : V A L U E ; VARYING : V A R Y I N G ; VIRTUAL : V I R T U A L ; WAIT : W A I T ; WHEN : W H E N ; WRITE : W R I T E ; ZONE : Z O N E ;
add revoke keyword
add revoke keyword
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
76aa78d09858d84c076831cf999e53aeca65ccb0
grakn-graql/src/main/antlr4/ai/grakn/graql/internal/antlr/Graql.g4
grakn-graql/src/main/antlr4/ai/grakn/graql/internal/antlr/Graql.g4
grammar Graql; queryList : query* EOF ; queryEOF : query EOF ; query : getQuery | insertQuery | defineQuery | undefineQuery | deleteQuery | aggregateQuery | computeQuery ; matchPart : MATCH patterns # matchBase | matchPart 'limit' INTEGER ';' # matchLimit | matchPart 'offset' INTEGER ';' # matchOffset | matchPart 'order' 'by' VARIABLE order? ';' # matchOrderBy ; getQuery : matchPart 'get' variables? ';' ; insertQuery : matchPart? INSERT varPatterns ; defineQuery : DEFINE varPatterns ; undefineQuery : UNDEFINE varPatterns ; deleteQuery : matchPart 'delete' variables? ';' ; aggregateQuery : matchPart 'aggregate' aggregate ';' ; variables : VARIABLE (',' VARIABLE)* ; // GRAQL COMPUTE QUERY: OVERALL SYNTAX GRAMMAR ========================================================================= // Author: Haikal Pribadi // // A compute query is composed of 3 things: // the 'compute' keyword, followed by a compute method, and a set of conditions (that may be optional) // // A compute method could only be: // count (to count the number of concepts in the graph) // min, max, median, mean, std and sum (to calculate statistics functions) // path (to compute the paths between concepts) // centrality (to compute how densely connected concepts are in the graph) // cluster (to detect communities in the graph) // // The compute conditions can be a set of zero or more individual condition separated by a comma // A compute condition can either be a FromID, ToID, OfLabels, InLabels, Algorithm or Args computeQuery : COMPUTE computeMethod computeConditions? ';'; computeMethod : COUNT // compute count | MIN | MAX | MEDIAN | MEAN | STD | SUM // compute statistics | PATH // compute path | CENTRALITY // compute centrality | CLUSTER // compute cluster ; computeConditions : computeCondition (',' computeCondition)* ; computeCondition : FROM computeFromID | TO computeToID | OF computeOfLabels | IN computeInLabels | USING computeAlgorithm | WHERE computeArgs ; // GRAQL COMPUTE QUERY: CONDITIONS GRAMMAR ============================================================================= // Author: Haikal Pribadi // // The following are definitions of computeConditions for the Graql Compute Query // computeFromID and computeToID takes in a concept ID // computeOfLabels and computeInLabels takes in labels, such as types in the schema // computeAlgorithm are the different algorithm names that determines how the compute method is performed // computeArgs can either be a single argument or an array of arguments // computeArgsArray is an arry of arguments // computeArg is a single argument computeFromID : id ; computeToID : id ; computeOfLabels : labels ; computeInLabels : labels ; computeAlgorithm : DEGREE | K_CORE | CONNECTED_COMPONENT ; computeArgs : computeArgsArray | computeArg ; computeArgsArray : '[' computeArg (',' computeArg)* ']' ; computeArg : MIN_K '=' INTEGER # computeArgMinK | K '=' INTEGER # computeArgK | SIZE '=' INTEGER # computeArgSize | CONTAINS '=' id # computeArgContains ; aggregate : identifier argument* # customAgg ; argument : VARIABLE # variableArgument | aggregate # aggregateArgument ; patterns : (pattern ';')+ ; pattern : varPattern # varPatternCase | pattern 'or' pattern # orPattern | '{' patterns '}' # andPattern ; varPatterns : (varPattern ';')+ ; varPattern : VARIABLE | variable? property (','? property)* ; property : 'isa' variable # isa | 'isa!' variable # isaExplicit | 'sub' variable # sub | 'relates' role=variable ('as' superRole=variable)? # relates | 'plays' variable # plays | 'id' id # propId | 'label' label # propLabel | predicate # propValue | 'when' '{' patterns '}' # propWhen | 'then' '{' varPatterns '}' # propThen | 'has' label (resource=VARIABLE | predicate) ('via' relation=VARIABLE)? # propHas | 'has' variable # propResource | 'key' variable # propKey | '(' casting (',' casting)* ')' # propRel | 'is-abstract' # isAbstract | 'datatype' datatype # propDatatype | 'regex' REGEX # propRegex | '!=' variable # propNeq ; casting : variable (':' VARIABLE)? | variable VARIABLE {notifyErrorListeners("expecting {',', ':'}");}; variable : label | VARIABLE ; predicate : '=='? value # predicateEq | '==' VARIABLE # predicateVariable | '!==' valueOrVar # predicateNeq | '>' valueOrVar # predicateGt | '>=' valueOrVar # predicateGte | '<' valueOrVar # predicateLt | '<=' valueOrVar # predicateLte | 'contains' (STRING | VARIABLE) # predicateContains | REGEX # predicateRegex ; valueOrVar : VARIABLE # valueVariable | value # valuePrimitive ; value : STRING # valueString | INTEGER # valueInteger | REAL # valueReal | bool # valueBoolean | DATE # valueDate | DATETIME # valueDateTime ; labels : labelsArray | label ; labelsArray : '[' label (',' label)* ']' ; label : identifier | IMPLICIT_IDENTIFIER; id : identifier ; // Some keywords can also be used as identifiers identifier : ID | STRING | MIN | MAX| MEDIAN | MEAN | STD | SUM | COUNT | PATH | CLUSTER | FROM | TO | OF | IN | DEGREE | K_CORE | CONNECTED_COMPONENT | MIN_K | K | CONTAINS | SIZE | WHERE ; datatype : LONG_TYPE | DOUBLE_TYPE | STRING_TYPE | BOOLEAN_TYPE | DATE_TYPE ; order : ASC | DESC ; bool : TRUE | FALSE ; // keywords MIN : 'min' ; MAX : 'max' ; MEDIAN : 'median' ; MEAN : 'mean' ; STD : 'std' ; SUM : 'sum' ; COUNT : 'count' ; PATH : 'path' ; CLUSTER : 'cluster' ; CENTRALITY : 'centrality' ; FROM : 'from' ; TO : 'to' ; OF : 'of' ; IN : 'in' ; DEGREE : 'degree' ; K_CORE : 'k-core' ; CONNECTED_COMPONENT : 'connected-component' ; MIN_K : 'min-k' ; K : 'k' ; CONTAINS : 'contains' ; SIZE : 'size' ; USING : 'using' ; WHERE : 'where' ; MATCH : 'match' ; INSERT : 'insert' ; DEFINE : 'define' ; UNDEFINE : 'undefine' ; COMPUTE : 'compute' ; ASC : 'asc' ; DESC : 'desc' ; LONG_TYPE : 'long' ; DOUBLE_TYPE : 'double' ; STRING_TYPE : 'string' ; BOOLEAN_TYPE : 'boolean' ; DATE_TYPE : 'date' ; TRUE : 'true' ; FALSE : 'false' ; // In StringConverter.java we inspect the lexer to find out which values are keywords. // If literals are used in an alternation (e.g. `'true' | 'false'`) in the grammar, then they don't register as keywords. // Therefore, we never use an alternation of literals and instead give them proper rule names (e.g. `TRUE | FALSE`). VARIABLE : '$' [a-zA-Z0-9_-]+ ; ID : [a-zA-Z_] [a-zA-Z0-9_-]* ; STRING : '"' (~["\\] | ESCAPE_SEQ)* '"' | '\'' (~['\\] | ESCAPE_SEQ)* '\''; REGEX : '/' (~'/' | '\\/')* '/' ; INTEGER : ('+' | '-')? [0-9]+ ; REAL : ('+' | '-')? [0-9]+ '.' [0-9]+ ; DATE : DATE_FRAGMENT ; DATETIME : DATE_FRAGMENT 'T' TIME ; fragment DATE_FRAGMENT : YEAR '-' MONTH '-' DAY ; fragment MONTH : [0-1][0-9] ; fragment DAY : [0-3][0-9] ; fragment YEAR : [0-9][0-9][0-9][0-9] | ('+' | '-') [0-9]+ ; fragment TIME : HOUR ':' MINUTE (':' SECOND)? ; fragment HOUR : [0-2][0-9] ; fragment MINUTE : [0-6][0-9] ; fragment SECOND : [0-6][0-9] ('.' [0-9]+)? ; fragment ESCAPE_SEQ : '\\' . ; COMMENT : '#' .*? '\r'? ('\n' | EOF) -> channel(HIDDEN) ; IMPLICIT_IDENTIFIER : '@' [a-zA-Z0-9_-]+ ; WS : [ \t\r\n]+ -> channel(HIDDEN) ; // Unused lexer rule to help with autocomplete on variable names DOLLAR : '$' ;
grammar Graql; queryList : query* EOF ; queryEOF : query EOF ; query : getQuery | insertQuery | defineQuery | undefineQuery | deleteQuery | aggregateQuery | computeQuery ; matchPart : MATCH patterns # matchBase | matchPart 'limit' INTEGER ';' # matchLimit | matchPart 'offset' INTEGER ';' # matchOffset | matchPart 'order' 'by' VARIABLE order? ';' # matchOrderBy ; getQuery : matchPart 'get' variables? ';' ; insertQuery : matchPart? INSERT varPatterns ; defineQuery : DEFINE varPatterns ; undefineQuery : UNDEFINE varPatterns ; deleteQuery : matchPart 'delete' variables? ';' ; aggregateQuery : matchPart 'aggregate' aggregate ';' ; variables : VARIABLE (',' VARIABLE)* ; // GRAQL COMPUTE QUERY: OVERALL SYNTAX GRAMMAR ========================================================================= // // A compute query is composed of 3 things: // the 'compute' keyword, followed by a compute method, and a set of conditions (that may be optional) // // A compute method could only be: // count (to count the number of concepts in the graph) // min, max, median, mean, std and sum (to calculate statistics functions) // path (to compute the paths between concepts) // centrality (to compute how densely connected concepts are in the graph) // cluster (to detect communities in the graph) // // The compute conditions can be a set of zero or more individual condition separated by a comma // A compute condition can either be a FromID, ToID, OfLabels, InLabels, Algorithm or Args computeQuery : COMPUTE computeMethod computeConditions? ';'; computeMethod : COUNT // compute count | MIN | MAX | MEDIAN | MEAN | STD | SUM // compute statistics | PATH // compute path | CENTRALITY // compute centrality | CLUSTER // compute cluster ; computeConditions : computeCondition (',' computeCondition)* ; computeCondition : FROM computeFromID | TO computeToID | OF computeOfLabels | IN computeInLabels | USING computeAlgorithm | WHERE computeArgs ; // GRAQL COMPUTE QUERY: CONDITIONS GRAMMAR ============================================================================= // // The following are definitions of computeConditions for the Graql Compute Query // computeFromID and computeToID takes in a concept ID // computeOfLabels and computeInLabels takes in labels, such as types in the schema // computeAlgorithm are the different algorithm names that determines how the compute method is performed // computeArgs can either be a single argument or an array of arguments // computeArgsArray is an arry of arguments // computeArg is a single argument computeFromID : id ; computeToID : id ; computeOfLabels : labels ; computeInLabels : labels ; computeAlgorithm : DEGREE | K_CORE | CONNECTED_COMPONENT ; computeArgs : computeArgsArray | computeArg ; computeArgsArray : '[' computeArg (',' computeArg)* ']' ; computeArg : MIN_K '=' INTEGER # computeArgMinK | K '=' INTEGER # computeArgK | SIZE '=' INTEGER # computeArgSize | CONTAINS '=' id # computeArgContains ; aggregate : identifier argument* # customAgg ; argument : VARIABLE # variableArgument | aggregate # aggregateArgument ; patterns : (pattern ';')+ ; pattern : varPattern # varPatternCase | pattern 'or' pattern # orPattern | '{' patterns '}' # andPattern ; varPatterns : (varPattern ';')+ ; varPattern : VARIABLE | variable? property (','? property)* ; property : 'isa' variable # isa | 'isa!' variable # isaExplicit | 'sub' variable # sub | 'relates' role=variable ('as' superRole=variable)? # relates | 'plays' variable # plays | 'id' id # propId | 'label' label # propLabel | predicate # propValue | 'when' '{' patterns '}' # propWhen | 'then' '{' varPatterns '}' # propThen | 'has' label (resource=VARIABLE | predicate) ('via' relation=VARIABLE)? # propHas | 'has' variable # propResource | 'key' variable # propKey | '(' casting (',' casting)* ')' # propRel | 'is-abstract' # isAbstract | 'datatype' datatype # propDatatype | 'regex' REGEX # propRegex | '!=' variable # propNeq ; casting : variable (':' VARIABLE)? | variable VARIABLE {notifyErrorListeners("expecting {',', ':'}");}; variable : label | VARIABLE ; predicate : '=='? value # predicateEq | '==' VARIABLE # predicateVariable | '!==' valueOrVar # predicateNeq | '>' valueOrVar # predicateGt | '>=' valueOrVar # predicateGte | '<' valueOrVar # predicateLt | '<=' valueOrVar # predicateLte | 'contains' (STRING | VARIABLE) # predicateContains | REGEX # predicateRegex ; valueOrVar : VARIABLE # valueVariable | value # valuePrimitive ; value : STRING # valueString | INTEGER # valueInteger | REAL # valueReal | bool # valueBoolean | DATE # valueDate | DATETIME # valueDateTime ; labels : labelsArray | label ; labelsArray : '[' label (',' label)* ']' ; label : identifier | IMPLICIT_IDENTIFIER; id : identifier ; // Some keywords can also be used as identifiers identifier : ID | STRING | MIN | MAX| MEDIAN | MEAN | STD | SUM | COUNT | PATH | CLUSTER | FROM | TO | OF | IN | DEGREE | K_CORE | CONNECTED_COMPONENT | MIN_K | K | CONTAINS | SIZE | WHERE ; datatype : LONG_TYPE | DOUBLE_TYPE | STRING_TYPE | BOOLEAN_TYPE | DATE_TYPE ; order : ASC | DESC ; bool : TRUE | FALSE ; // keywords MIN : 'min' ; MAX : 'max' ; MEDIAN : 'median' ; MEAN : 'mean' ; STD : 'std' ; SUM : 'sum' ; COUNT : 'count' ; PATH : 'path' ; CLUSTER : 'cluster' ; CENTRALITY : 'centrality' ; FROM : 'from' ; TO : 'to' ; OF : 'of' ; IN : 'in' ; DEGREE : 'degree' ; K_CORE : 'k-core' ; CONNECTED_COMPONENT : 'connected-component' ; MIN_K : 'min-k' ; K : 'k' ; CONTAINS : 'contains' ; SIZE : 'size' ; USING : 'using' ; WHERE : 'where' ; MATCH : 'match' ; INSERT : 'insert' ; DEFINE : 'define' ; UNDEFINE : 'undefine' ; COMPUTE : 'compute' ; ASC : 'asc' ; DESC : 'desc' ; LONG_TYPE : 'long' ; DOUBLE_TYPE : 'double' ; STRING_TYPE : 'string' ; BOOLEAN_TYPE : 'boolean' ; DATE_TYPE : 'date' ; TRUE : 'true' ; FALSE : 'false' ; // In StringConverter.java we inspect the lexer to find out which values are keywords. // If literals are used in an alternation (e.g. `'true' | 'false'`) in the grammar, then they don't register as keywords. // Therefore, we never use an alternation of literals and instead give them proper rule names (e.g. `TRUE | FALSE`). VARIABLE : '$' [a-zA-Z0-9_-]+ ; ID : [a-zA-Z_] [a-zA-Z0-9_-]* ; STRING : '"' (~["\\] | ESCAPE_SEQ)* '"' | '\'' (~['\\] | ESCAPE_SEQ)* '\''; REGEX : '/' (~'/' | '\\/')* '/' ; INTEGER : ('+' | '-')? [0-9]+ ; REAL : ('+' | '-')? [0-9]+ '.' [0-9]+ ; DATE : DATE_FRAGMENT ; DATETIME : DATE_FRAGMENT 'T' TIME ; fragment DATE_FRAGMENT : YEAR '-' MONTH '-' DAY ; fragment MONTH : [0-1][0-9] ; fragment DAY : [0-3][0-9] ; fragment YEAR : [0-9][0-9][0-9][0-9] | ('+' | '-') [0-9]+ ; fragment TIME : HOUR ':' MINUTE (':' SECOND)? ; fragment HOUR : [0-2][0-9] ; fragment MINUTE : [0-6][0-9] ; fragment SECOND : [0-6][0-9] ('.' [0-9]+)? ; fragment ESCAPE_SEQ : '\\' . ; COMMENT : '#' .*? '\r'? ('\n' | EOF) -> channel(HIDDEN) ; IMPLICIT_IDENTIFIER : '@' [a-zA-Z0-9_-]+ ; WS : [ \t\r\n]+ -> channel(HIDDEN) ; // Unused lexer rule to help with autocomplete on variable names DOLLAR : '$' ;
Update Graql.g4
Update Graql.g4
ANTLR
agpl-3.0
graknlabs/grakn,lolski/grakn,lolski/grakn,lolski/grakn,lolski/grakn,graknlabs/grakn,graknlabs/grakn,graknlabs/grakn
57409d562963d85b6f14d8e3153d75546021ef7a
VineScript/Compiler/VineParser.g4
VineScript/Compiler/VineParser.g4
parser grammar VineParser; /* // django syntax: https://docs.djangoproject.com/en/1.10/topics/templates/#the-django-template-language // django: // * var: {{ foo }} // * code: {% if foo %} // * comment: {# comment #} // detail: https://github.com/benjohnson/atom-django-templates/blob/master/grammars/html%20(django).cson grammar VineScript; script: sequence+ EOF; sequence: text | code | ; code: stmt | text ; // conditionStmt or controlStmt (control structure) stmt: conditionStmt | assign | print | stmt ';' | variable ; // {{ foo }} is equal to << print foo >> // built-in filters: // * upper // * lower // * truncatechars:8 // * truncatewords:2 // * pluralize // * default:"nothing" // * length // * random // * stringformat:"#.0" // * yesno:"yeah,no,maybe" // ---- added by myself: ---- // * min // * max // built-in functions: // * ParseInt(string) // * ParseNumber(string) // * Range(int):[] // custom template tags // https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-tags // custom template filters : // https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-filters //<< autoescape off >> // {{ body }} // << autoescape on >> // {{ foo }} // << endautoescape >> //<< endautoescape >> // preformatted: (on by default) << formatted on >> << formatted off >> // or like html: << pre on >> << pre off >> // maybe: << tab >> << br >> '<<' 'set' ID ('='|'to') expr '>>' */ @members{ public enum EVineParseMode { SINGLE_PASSAGE, EVAL_EXPR } // by default, parse as a single passage public EVineParseMode ParseMode = EVineParseMode.SINGLE_PASSAGE; internal static readonly string errReservedChar000B = "'\\v' (vertical tabulation) is a reserved character and is not allowed to be used!"; internal static readonly string errReservedChar001E = "'\\u001E' (record separator) is a reserved character and is not allowed to be used!"; internal static readonly string errReservedChar001F = "'\\u001F' (unit separator) is a reserved character and is not allowed to be used!"; internal static readonly string errVarDefReservedKw = "Can't use a reserved keyword as a variable name!"; internal static readonly string errMissingSpaceBefore = "Missing space before "; internal static readonly string errMissingSpaceAfter = "Missing space after "; private void ReservedChar() { var token = _input.Lt(-1); ReservedChar(token); } private void ReservedChar(IToken token) { string msg = ""; if (token.Text.Contains("\u000B")) { msg = errReservedChar000B; } else if (token.Text.Contains("\u001E")) { msg = errReservedChar001E; } else if (token.Text.Contains("\u001F")) { msg = errReservedChar001F; } NotifyPrev(token, msg); } private void NotifyPrev(string msg) { var token = _input.Lt(-1); NotifyPrev(token, msg); } private void NotifyPrev(IToken token, string msg) { NotifyErrorListeners(token, msg, null); } } options { tokenVocab=VineLexer; } /* * Parser Rules */ passage : {ParseMode == EVineParseMode.EVAL_EXPR}? evalExprMode NL? EOF // active only if we're expr parse mode | block* NL? EOF | RESERVED_CHARS { ReservedChar(); } | { NotifyErrorListeners("Error char"); } ERROR_CHAR ; evalExprMode : expr ; // directOutput will add the text/code markups to the output. // The output will then be parsed by the formatter. block : NL # directOutput | verbatimStmt # noOutput // `as it is, escape << tags >> too` | text # directOutput // foobar | display # noOutput // {{ foo }} | controlStmt # noOutput // << open stmt >> something << close stmt >> | simpleStmtBlock # noOutput // << set foo = 0 >> | link # noOutput // [[label|link]] | collapseStmt # noOutput // { foo\nbar } => foobar | BLOCK_COMMENT # directOutput // /* comment */ | LINE_COMMENT # directOutput // // inline comment | RESERVED_CHARS { ReservedChar(); } # blockError ; text : TXT ; simpleStmtBlock : '<<' setStmt '>>' | '<<' unsetStmt '>>' | '<<' funcCall '>>' ; link : '[[' title=linkContent+ ']]' | '[[' title=linkContent+ '|' passageName=linkContent+ ']]' | '[[' title=linkContent+ '->' passageName=linkContent+ ']]' | '[[' passageName=linkContent+ '<-' title=linkContent+ ']]' ; linkContent : LINK_TEXT+ | RESERVED_CHARS { ReservedChar(); } ; verbatimStmt : VERBATIM ; collapseStmt : LCOLLAPSE | RCOLLAPSE //| LCOLLAPSE block* RCOLLAPSE // could use this rule if we want to be more strict ; /** * Display something in the text (variable, expression, function return, ...) **/ display : '{{' expr '}}' ; setStmt : 'set' assignList ; assignList : assign (',' assign)* | assignList { NotifyErrorListeners("Missing ',' separator"); } assign (',' assign)* | assignList { NotifyErrorListeners("Too many ','"); } ',' ',' assignList ; assign : variable (sequenceAccess)* op=('='|'to') expr | variable (sequenceAccess)* op=('+='|'-='|'*='|'/='|'%=') expr | variable (sequenceAccess)* { NotifyErrorListeners("Missing assignation operator"); } expr | variable (sequenceAccess)* op=('='|'to'|'+='|'-='|'*='|'/='|'%=') { NotifyErrorListeners("Missing expression after the operator"); } ; unsetStmt : 'unset' unsetList ; unsetList : variable (',' variable)* | unsetList { NotifyErrorListeners("Missing ',' separator"); } variable (',' variable)* | unsetList { NotifyErrorListeners("Too many ','"); } ',' ',' unsetList ; funcCall : ID '(' expressionList? ')' | ID '(' expressionList? ')' { NotifyErrorListeners("Too many parentheses"); } ')' | ID '(' expressionList? { NotifyErrorListeners("Missing closing ')'"); } ; newSequence : LBRACK expressionList? RBRACK # newArray | LBRACE keyValueList? RBRACE # newDict // array errors: | LBRACK expressionList? RBRACK { NotifyErrorListeners("Too many brackets"); } RBRACK # newArrayError | LBRACK expressionList? { NotifyErrorListeners("Missing closing ']'"); } # newArrayError // dict errors: | LBRACE keyValueList? RBRACE { NotifyErrorListeners("Too many braces"); } RBRACE # newDictError | LBRACE keyValueList? { NotifyErrorListeners("Missing closing '}'"); } # newDictError ; // if, elif, else, for, end controlStmt : ifStmt (elifStmt)* (elseStmt)? endStmt # ifCtrlStmt | forStmt endStmt # forCtrlStmt | ifStmt (elifStmt)* (elseStmt)? {NotifyErrorListeners("'if' statement is missing a closing '<< end >>'");} # ctrlStmtError | ifStmt (elifStmt)* elseStmt {NotifyErrorListeners("Too many 'else' statements");} (elseStmt)+ # ctrlStmtError | ifStmt {NotifyErrorListeners("Misplaced '<< else >>'");} (elseStmt) (elifStmt)+ endStmt # ctrlStmtError | forStmt {NotifyErrorListeners("'for' statement is missing a closing '<< end >>'");} # ctrlStmtError ; ifStmt : '<<' 'if' wsa expr '>>' block* ; elifStmt : '<<' 'elif' wsa expr '>>' block* ; elseStmt : '<<' 'else' '>>' block* ; endStmt : '<<' 'end' '>>' ; forStmt : '<<' 'for' wsa variable 'in' expr '>>' NL? block* # forValueStmt | '<<' 'for' wsa variable 'in' interval '>>' NL? block* # forValueStmt | '<<' 'for' wsa key=variable ',' val=variable 'in' expr '>>' NL? block* # forKeyValueStmt ; expr : <assoc=right> left=expr '^' right=expr # powExpr | op=(MINUS|'!') expr # unaryExpr | left=expr op=('*' | DIV | '%') right=expr # mulDivModExpr | left=expr op=('+'|MINUS) right=expr # addSubExpr | left=expr op=(LT|GT|'<='|'>=') right=expr # relationalExpr | left=expr op=('=='|'!=') right=expr # equalityExpr | left=expr ('&&'|wsb 'and' wsa) right=expr # andExpr | left=expr ('||'|wsb 'or' wsa) right=expr # orExpr | '(' expr ')' # parensExpr | newSequence # sequenceExpr | funcCall # funcCallExpr | atom # atomExpr | variable (sequenceAccess)* # varExpr ; expressionList : expr (',' expr)* | expr (',' { NotifyErrorListeners("Too many comma separators"); } ','+ expr)+ | expr (',' expr)* { NotifyErrorListeners("Too many comma separators"); } ',' ; keyValue : stringLiteral ':' expr | { NotifyErrorListeners("Invalid key value: it should look like this: '\"key\": value'"); } . ; keyValueList : keyValue (',' keyValue)* | keyValue (',' { NotifyErrorListeners("Too many comma separators"); } ','+ keyValue)+ | keyValue (',' keyValue)* { NotifyErrorListeners("Too many comma separators"); } ',' ; atom: INT # intAtom | FLOAT # floatAtom | (TRUE | FALSE) # boolAtom | stringLiteral # stringAtom | NULL # nullAtom ; stringLiteral : STRING | ILLEGAL_STRING { ReservedChar(); } ; // Variable access. The '$' prefix is optional variable : '$'? ID ('.' ID)* | { NotifyErrorListeners(errVarDefReservedKw); } reservedKeyword ; sequenceAccess : LBRACK expr RBRACK ; interval : left=expr '...' right=expr ; // Call to force whitespace. Kind of hacky? // If the current token is not a white space => error. // We use semantic predicates here because WS is in a different // channel and the parser can't access directly wsb // before : { if (_input.Get(_input.Index - 1).Type != WS) { string offendingSymbol = _input.Get(_input.Index).Text; NotifyErrorListeners(errMissingSpaceBefore + "'" + offendingSymbol + "'"); } } ; wsa // after : { if (_input.Get(_input.Index - 1).Type != WS) { string offendingSymbol = _input.Get(_input.Index - 1).Text; NotifyErrorListeners(errMissingSpaceAfter + "'" + offendingSymbol + "'"); } } ; reservedKeyword : IF | ELIF | ELSE | END | KW_AND | KW_OR | TO | SET | UNSET | TRUE | FALSE | NULL ;
parser grammar VineParser; /* // django syntax: https://docs.djangoproject.com/en/1.10/topics/templates/#the-django-template-language // django: // * var: {{ foo }} // * code: {% if foo %} // * comment: {# comment #} // detail: https://github.com/benjohnson/atom-django-templates/blob/master/grammars/html%20(django).cson grammar VineScript; script: sequence+ EOF; sequence: text | code | ; code: stmt | text ; // conditionStmt or controlStmt (control structure) stmt: conditionStmt | assign | print | stmt ';' | variable ; // {{ foo }} is equal to << print foo >> // built-in filters: // * upper // * lower // * truncatechars:8 // * truncatewords:2 // * pluralize // * default:"nothing" // * length // * random // * stringformat:"#.0" // * yesno:"yeah,no,maybe" // ---- added by myself: ---- // * min // * max // built-in functions: // * ParseInt(string) // * ParseNumber(string) // * Range(int):[] // custom template tags // https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-tags // custom template filters : // https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-filters //<< autoescape off >> // {{ body }} // << autoescape on >> // {{ foo }} // << endautoescape >> //<< endautoescape >> // preformatted: (on by default) << formatted on >> << formatted off >> // or like html: << pre on >> << pre off >> // maybe: << tab >> << br >> '<<' 'set' ID ('='|'to') expr '>>' */ @members{ public enum EVineParseMode { SINGLE_PASSAGE, EVAL_EXPR } // by default, parse as a single passage public EVineParseMode ParseMode = EVineParseMode.SINGLE_PASSAGE; internal static readonly string errReservedChar000B = "'\\v' (vertical tabulation) is a reserved character and is not allowed to be used!"; internal static readonly string errReservedChar001E = "'\\u001E' (record separator) is a reserved character and is not allowed to be used!"; internal static readonly string errReservedChar001F = "'\\u001F' (unit separator) is a reserved character and is not allowed to be used!"; internal static readonly string errVarDefReservedKw = "Can't use a reserved keyword as a variable name!"; internal static readonly string errMissingSpaceBefore = "Missing space before "; internal static readonly string errMissingSpaceAfter = "Missing space after "; private void ReservedChar() { var token = _input.Lt(-1); ReservedChar(token); } private void ReservedChar(IToken token) { string msg = ""; if (token.Text.Contains("\u000B")) { msg = errReservedChar000B; } else if (token.Text.Contains("\u001E")) { msg = errReservedChar001E; } else if (token.Text.Contains("\u001F")) { msg = errReservedChar001F; } NotifyPrev(token, msg); } private void NotifyPrev(string msg) { var token = _input.Lt(-1); NotifyPrev(token, msg); } private void NotifyPrev(IToken token, string msg) { NotifyErrorListeners(token, msg, null); } } options { tokenVocab=VineLexer; } /* * Parser Rules */ passage : {ParseMode == EVineParseMode.EVAL_EXPR}? evalExprMode NL? EOF // active only if we're expr parse mode | block* NL? EOF | RESERVED_CHARS { ReservedChar(); } | { NotifyErrorListeners("Error char"); } ERROR_CHAR ; evalExprMode : expr ; // directOutput will add the text/code markups to the output. // The output will then be parsed by the formatter. block : NL # directOutput | verbatimStmt # noOutput // `as it is, escape << tags >> too` | text # directOutput // foobar | display # noOutput // {{ foo }} | controlStmt # noOutput // << open stmt >> something << close stmt >> | simpleStmtBlock # noOutput // << set foo = 0 >> | link # noOutput // [[label|link]] | collapseStmt # noOutput // { foo\nbar } => foobar | BLOCK_COMMENT # directOutput // /* comment */ | LINE_COMMENT # directOutput // // inline comment | RESERVED_CHARS { ReservedChar(); } # blockError ; text : TXT ; simpleStmtBlock : '<<' setStmt '>>' | '<<' unsetStmt '>>' | '<<' funcCall '>>' ; link : '[[' title=linkContent+ ']]' | '[[' title=linkContent+ '|' passageName=linkContent+ ']]' | '[[' title=linkContent+ '->' passageName=linkContent+ ']]' | '[[' passageName=linkContent+ '<-' title=linkContent+ ']]' ; linkContent : LINK_TEXT+ | RESERVED_CHARS { ReservedChar(); } ; verbatimStmt : VERBATIM ; collapseStmt : LCOLLAPSE | RCOLLAPSE //| LCOLLAPSE block* RCOLLAPSE // could use this rule if we want to be more strict ; /** * Display something in the text (variable, expression, function return, ...) **/ display : LOUTPUT expr ROUTPUT ; setStmt : 'set' assignList ; assignList : assign (',' assign)* | assignList { NotifyErrorListeners("Missing ',' separator"); } assign (',' assign)* | assignList { NotifyErrorListeners("Too many ','"); } ',' ',' assignList ; assign : variable (sequenceAccess)* op=('='|'to') expr | variable (sequenceAccess)* op=('+='|'-='|'*='|'/='|'%=') expr | variable (sequenceAccess)* { NotifyErrorListeners("Missing assignation operator"); } expr | variable (sequenceAccess)* op=('='|'to'|'+='|'-='|'*='|'/='|'%=') { NotifyErrorListeners("Missing expression after the operator"); } ; unsetStmt : 'unset' unsetList ; unsetList : variable (',' variable)* | unsetList { NotifyErrorListeners("Missing ',' separator"); } variable (',' variable)* | unsetList { NotifyErrorListeners("Too many ','"); } ',' ',' unsetList ; funcCall : ID '(' expressionList? ')' | ID '(' expressionList? ')' { NotifyErrorListeners("Too many parentheses"); } ')' | ID '(' expressionList? { NotifyErrorListeners("Missing closing ')'"); } ; newSequence : LBRACK expressionList? RBRACK # newArray | LBRACE keyValueList? RBRACE # newDict // array errors: | LBRACK expressionList? RBRACK { NotifyErrorListeners("Too many brackets"); } RBRACK # newArrayError | LBRACK expressionList? { NotifyErrorListeners("Missing closing ']'"); } # newArrayError // dict errors: | LBRACE keyValueList? RBRACE { NotifyErrorListeners("Too many braces"); } RBRACE # newDictError | LBRACE keyValueList? { NotifyErrorListeners("Missing closing '}'"); } # newDictError ; // if, elif, else, for, end controlStmt : ifStmt (elifStmt)* (elseStmt)? endStmt # ifCtrlStmt | forStmt endStmt # forCtrlStmt | ifStmt (elifStmt)* (elseStmt)? {NotifyErrorListeners("'if' statement is missing a closing '<< end >>'");} # ctrlStmtError | ifStmt (elifStmt)* elseStmt {NotifyErrorListeners("Too many 'else' statements");} (elseStmt)+ # ctrlStmtError | ifStmt {NotifyErrorListeners("Misplaced '<< else >>'");} (elseStmt) (elifStmt)+ endStmt # ctrlStmtError | forStmt {NotifyErrorListeners("'for' statement is missing a closing '<< end >>'");} # ctrlStmtError ; ifStmt : '<<' 'if' wsa expr '>>' block* ; elifStmt : '<<' 'elif' wsa expr '>>' block* ; elseStmt : '<<' 'else' '>>' block* ; endStmt : '<<' 'end' '>>' ; forStmt : '<<' 'for' wsa variable 'in' expr '>>' NL? block* # forValueStmt | '<<' 'for' wsa variable 'in' interval '>>' NL? block* # forValueStmt | '<<' 'for' wsa key=variable ',' val=variable 'in' expr '>>' NL? block* # forKeyValueStmt ; expr : <assoc=right> left=expr '^' right=expr # powExpr | op=(MINUS|'!') expr # unaryExpr | left=expr op=('*' | DIV | '%') right=expr # mulDivModExpr | left=expr op=('+'|MINUS) right=expr # addSubExpr | left=expr op=(LT|GT|'<='|'>=') right=expr # relationalExpr | left=expr op=('=='|'!=') right=expr # equalityExpr | left=expr ('&&'|wsb 'and' wsa) right=expr # andExpr | left=expr ('||'|wsb 'or' wsa) right=expr # orExpr | '(' expr ')' # parensExpr | newSequence # sequenceExpr | funcCall # funcCallExpr | atom # atomExpr | variable (sequenceAccess)* # varExpr ; expressionList : expr (',' expr)* | expr (',' { NotifyErrorListeners("Too many comma separators"); } ','+ expr)+ | expr (',' expr)* { NotifyErrorListeners("Too many comma separators"); } ',' ; keyValue : stringLiteral ':' expr | { NotifyErrorListeners("Invalid key value: it should look like this: '\"key\": value'"); } . ; keyValueList : keyValue (',' keyValue)* | keyValue (',' { NotifyErrorListeners("Too many comma separators"); } ','+ keyValue)+ | keyValue (',' keyValue)* { NotifyErrorListeners("Too many comma separators"); } ',' ; atom: INT # intAtom | FLOAT # floatAtom | (TRUE | FALSE) # boolAtom | stringLiteral # stringAtom | NULL # nullAtom ; stringLiteral : STRING | ILLEGAL_STRING { ReservedChar(); } ; // Variable access. The '$' prefix is optional variable : '$'? ID ('.' ID)* | { NotifyErrorListeners(errVarDefReservedKw); } reservedKeyword ; sequenceAccess : LBRACK expr RBRACK ; interval : left=expr '...' right=expr ; // Call to force whitespace. Kind of hacky? // If the current token is not a white space => error. // We use semantic predicates here because WS is in a different // channel and the parser can't access directly wsb // before : { if (_input.Get(_input.Index - 1).Type != WS) { string offendingSymbol = _input.Get(_input.Index).Text; NotifyErrorListeners(errMissingSpaceBefore + "'" + offendingSymbol + "'"); } } ; wsa // after : { if (_input.Get(_input.Index - 1).Type != WS) { string offendingSymbol = _input.Get(_input.Index - 1).Text; NotifyErrorListeners(errMissingSpaceAfter + "'" + offendingSymbol + "'"); } } ; reservedKeyword : IF | ELIF | ELSE | END | KW_AND | KW_OR | TO | SET | UNSET | TRUE | FALSE | NULL ;
fix nested dictionary declaration (2) Forgot to commit the change in the parser's grammar in commit b567ab3e64875226c436dc13ed1603dbf9d4e4ed
Grammar: fix nested dictionary declaration (2) Forgot to commit the change in the parser's grammar in commit b567ab3e64875226c436dc13ed1603dbf9d4e4ed
ANTLR
mit
julsam/VineScript
3084074200e9aac6cfb7d05cf97fedd09dc894fc
omni-cx2x/src/cx2x/translator/language/parser/Claw.g4
omni-cx2x/src/cx2x/translator/language/parser/Claw.g4
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import cx2x.translator.common.ClawConstant; import cx2x.translator.language.base.*; import cx2x.translator.language.common.*; import cx2x.translator.common.Utility; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage l] @init{ $l = new ClawLanguage(); } : CLAW directive[$l] EOF | CLAW VERBATIM // this directive accept anything after the verbatim { $l.setDirective(ClawDirective.VERBATIM); } | CLAW ACC // this directive accept anything after the acc { $l.setDirective(ClawDirective.PRIMITIVE); } | CLAW OMP // this directive accept anything after the omp { $l.setDirective(ClawDirective.PRIMITIVE); } ; directive[ClawLanguage l] @init{ List<ClawMapping> m = new ArrayList<>(); List<String> o = new ArrayList<>(); List<String> s = new ArrayList<>(); List<Integer> i = new ArrayList<>(); } : // loop-fusion directive LOOPFUSION group_clause_optional[$l] collapse_clause_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_FUSION); } // loop-interchange directive | LOOPINTERCHANGE indexes_option[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } // loop-extract directive | LOOPEXTRACT range_option mapping_option_list[m] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_EXTRACT); $l.setRange($range_option.r); $l.setMappings(m); } // remove directive | REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); } | END REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); $l.setEndPragma(); } // Kcache directive | KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); } | KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); $l.setInitClause(); } // Array notation transformation directive | ARRAY_TRANS induction_optional[$l] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); } | END ARRAY_TRANS { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); $l.setEndPragma(); } // loop-hoist directive | LOOPHOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF { $l.setHoistInductionVars(o); $l.setDirective(ClawDirective.LOOP_HOIST); } | END LOOPHOIST EOF { $l.setDirective(ClawDirective.LOOP_HOIST); $l.setEndPragma(); } // on the fly directive | ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')' { $l.setDirective(ClawDirective.ARRAY_TO_CALL); $l.setFctParams(o); $l.setFctName($fct_name.text); $l.setArrayName($array_name.text); } // parallelize directive | define_option[$l]* PARALLELIZE data_over_clause[$l]* parallelize_clauses[$l] { $l.setDirective(ClawDirective.PARALLELIZE); } | PARALLELIZE FORWARD { $l.setDirective(ClawDirective.PARALLELIZE); $l.setForwardClause(); } | END PARALLELIZE { $l.setDirective(ClawDirective.PARALLELIZE); $l.setEndPragma(); } // ignore directive | IGNORE { $l.setDirective(ClawDirective.IGNORE); } | END IGNORE { $l.setDirective(ClawDirective.IGNORE); $l.setEndPragma(); } ; // Comma-separated identifiers list ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; // Comma-separated identifiers or colon symbol list ids_or_colon_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | ':' { $ids.add(":"); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_or_colon_list[$ids] | ':' { $ids.add(":"); } ',' ids_or_colon_list[$ids] ; // data over clause used in parallelize directive data_over_clause[ClawLanguage l] @init{ List<String> overLst = new ArrayList<>(); List<String> dataLst = new ArrayList<>(); } : DATA '(' ids_list[dataLst] ')' OVER '(' ids_or_colon_list[overLst] ')' { $l.setOverDataClause(dataLst); $l.setOverClause(overLst); } ; // group clause group_clause_optional[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupClause($group_name.text); } | /* empty */ ; // collapse clause collapse_clause_optional[ClawLanguage l]: COLLAPSE '(' n=NUMBER ')' { $l.setCollapseClause($n.text); } | /* empty */ ; // fusion clause fusion_clause_optional[ClawLanguage l]: FUSION group_clause_optional[$l] { $l.setFusionClause(); } | /* empty */ ; // parallel clause parallel_clause_optional[ClawLanguage l]: PARALLEL { $l.setParallelClause(); } | /* empty */ ; // acc clause acc_optional[ClawLanguage l] @init{ List<String> tempAcc = new ArrayList<>(); } : ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); } | /* empty */ ; // interchange clause interchange_optional[ClawLanguage l]: INTERCHANGE indexes_option[$l] { $l.setInterchangeClause(); } | /* empty */ ; // induction clause induction_optional[ClawLanguage l] @init{ List<String> temp = new ArrayList<>(); } : INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); } | /* empty */ ; // data clause data_clause[ClawLanguage l] @init { List<String> temp = new ArrayList<>(); } : DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); } ; // private clause private_optional[ClawLanguage l]: PRIVATE { $l.setPrivateClause(); } | /* empty */ ; // reshape clause reshape_optional[ClawLanguage l] @init{ List<ClawReshapeInfo> r = new ArrayList(); } : RESHAPE '(' reshape_list[r] ')' { $l.setReshapeClauseValues(r); } | /* empty */ ; // reshape clause reshape_element returns [ClawReshapeInfo i] @init{ List<Integer> temp = new ArrayList(); } : array_name=IDENTIFIER '(' target_dim=NUMBER ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } | array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } ; reshape_list[List<ClawReshapeInfo> r]: info=reshape_element { $r.add($info.i); } ',' reshape_list[$r] | info=reshape_element { $r.add($info.i); } ; identifiers[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids] ; identifiers_list[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids] ; integers[List<Integer> ints]: ; integers_list[List<Integer> ints]: i=NUMBER { $ints.add(Integer.parseInt($i.text)); } | i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints] ; indexes_option[ClawLanguage l] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $l.setIndexes(indexes); } | /* empty */ ; offset_list_optional[List<Integer> offsets]: OFFSET '(' offset_list[$offsets] ')' | /* empty */ ; offset_list[List<Integer> offsets]: offset[$offsets] | offset[$offsets] ',' offset_list[$offsets] ; offset[List<Integer> offsets]: n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } | '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); } | '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(ClawConstant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; range_id returns [String text]: n=NUMBER { $text = $n.text; } | i=IDENTIFIER { $text = $i.text; } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; mapping_var_list[List<ClawMappingVar> vars]: mv=mapping_var { $vars.add($mv.mappingVar); } | mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars] ; mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>(); List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>(); $mapping.setMappedVariables(listMapped); $mapping.setMappingVariables(listMapping); } : MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')' ; mapping_option_list[List<ClawMapping> mappings]: m=mapping_option { $mappings.add($m.mapping); } | m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings] ; define_option[ClawLanguage l]: DEFINE DIMENSION id=IDENTIFIER '(' lower=range_id ':' upper=range_id ')' { ClawDimension cd = new ClawDimension($id.text, $lower.text, $upper.text); $l.addDimension(cd); } ; // Allow to switch order parallelize_clauses[ClawLanguage l]: copy_clause_optional[$l] update_clause_optional[$l] | update_clause_optional[$l] copy_clause_optional[$l] ; copy_clause_optional[ClawLanguage l]: /* empty */ | COPY { $l.setCopyClauseValue(ClawDMD.BOTH); } | COPY '(' IN ')' { $l.setCopyClauseValue(ClawDMD.IN); } | COPY '(' OUT ')' { $l.setCopyClauseValue(ClawDMD.OUT); } ; update_clause_optional[ClawLanguage l]: /* empty */ | UPDATE { $l.setUpdateClauseValue(ClawDMD.BOTH); } | UPDATE '(' IN ')' { $l.setUpdateClauseValue(ClawDMD.IN); } | UPDATE '(' OUT ')' { $l.setUpdateClauseValue(ClawDMD.OUT); } ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // CLAW Directives ARRAY_TRANS : 'array-transform'; ARRAY_TO_CALL : 'call'; DEFINE : 'define'; END : 'end'; KCACHE : 'kcache'; LOOPEXTRACT : 'loop-extract'; LOOPFUSION : 'loop-fusion'; LOOPHOIST : 'loop-hoist'; LOOPINTERCHANGE : 'loop-interchange'; PARALLELIZE : 'parallelize'; REMOVE : 'remove'; IGNORE : 'ignore'; VERBATIM : 'verbatim'; // CLAW Clauses COLLAPSE : 'collapse'; COPY : 'copy'; DATA : 'data'; DIMENSION : 'dimension'; FORWARD : 'forward'; FUSION : 'fusion'; GROUP : 'group'; INDUCTION : 'induction'; INIT : 'init'; INTERCHANGE : 'interchange'; MAP : 'map'; OFFSET : 'offset'; OVER : 'over'; PARALLEL : 'parallel'; PRIVATE : 'private'; RANGE : 'range'; RESHAPE : 'reshape'; UPDATE : 'update'; // data copy/update clause keywords IN : 'in'; OUT : 'out'; // Directive primitive clause ACC : 'acc'; OMP : 'omp'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : [0-9] ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import cx2x.translator.common.ClawConstant; import cx2x.translator.language.base.*; import cx2x.translator.language.common.*; import cx2x.translator.common.Utility; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage l] @init{ $l = new ClawLanguage(); } : CLAW directive[$l] EOF | CLAW VERBATIM // this directive accept anything after the verbatim { $l.setDirective(ClawDirective.VERBATIM); } | CLAW ACC // this directive accept anything after the acc { $l.setDirective(ClawDirective.PRIMITIVE); } | CLAW OMP // this directive accept anything after the omp { $l.setDirective(ClawDirective.PRIMITIVE); } ; directive[ClawLanguage l] @init{ List<ClawMapping> m = new ArrayList<>(); List<String> o = new ArrayList<>(); List<String> s = new ArrayList<>(); List<Integer> i = new ArrayList<>(); } : // loop-fusion directive LOOPFUSION group_clause_optional[$l] collapse_clause_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_FUSION); } // loop-interchange directive | LOOPINTERCHANGE indexes_option[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } // loop-extract directive | LOOPEXTRACT range_option mapping_option_list[m] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_EXTRACT); $l.setRange($range_option.r); $l.setMappings(m); } // remove directive | REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); } | END REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); $l.setEndPragma(); } // Kcache directive | KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); } | KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); $l.setInitClause(); } // Array notation transformation directive | ARRAY_TRANS induction_optional[$l] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); } | END ARRAY_TRANS { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); $l.setEndPragma(); } // loop-hoist directive | LOOPHOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF { $l.setHoistInductionVars(o); $l.setDirective(ClawDirective.LOOP_HOIST); } | END LOOPHOIST EOF { $l.setDirective(ClawDirective.LOOP_HOIST); $l.setEndPragma(); } // on the fly directive | ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')' { $l.setDirective(ClawDirective.ARRAY_TO_CALL); $l.setFctParams(o); $l.setFctName($fct_name.text); $l.setArrayName($array_name.text); } // parallelize directive | define_option[$l]* PARALLELIZE data_over_clause[$l]* parallelize_clauses[$l] { $l.setDirective(ClawDirective.PARALLELIZE); } | PARALLELIZE FORWARD parallelize_clauses[$l] { $l.setDirective(ClawDirective.PARALLELIZE); $l.setForwardClause(); } | END PARALLELIZE { $l.setDirective(ClawDirective.PARALLELIZE); $l.setEndPragma(); } // ignore directive | IGNORE { $l.setDirective(ClawDirective.IGNORE); } | END IGNORE { $l.setDirective(ClawDirective.IGNORE); $l.setEndPragma(); } ; // Comma-separated identifiers list ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; // Comma-separated identifiers or colon symbol list ids_or_colon_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | ':' { $ids.add(":"); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_or_colon_list[$ids] | ':' { $ids.add(":"); } ',' ids_or_colon_list[$ids] ; // data over clause used in parallelize directive data_over_clause[ClawLanguage l] @init{ List<String> overLst = new ArrayList<>(); List<String> dataLst = new ArrayList<>(); } : DATA '(' ids_list[dataLst] ')' OVER '(' ids_or_colon_list[overLst] ')' { $l.setOverDataClause(dataLst); $l.setOverClause(overLst); } ; // group clause group_clause_optional[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupClause($group_name.text); } | /* empty */ ; // collapse clause collapse_clause_optional[ClawLanguage l]: COLLAPSE '(' n=NUMBER ')' { $l.setCollapseClause($n.text); } | /* empty */ ; // fusion clause fusion_clause_optional[ClawLanguage l]: FUSION group_clause_optional[$l] { $l.setFusionClause(); } | /* empty */ ; // parallel clause parallel_clause_optional[ClawLanguage l]: PARALLEL { $l.setParallelClause(); } | /* empty */ ; // acc clause acc_optional[ClawLanguage l] @init{ List<String> tempAcc = new ArrayList<>(); } : ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); } | /* empty */ ; // interchange clause interchange_optional[ClawLanguage l]: INTERCHANGE indexes_option[$l] { $l.setInterchangeClause(); } | /* empty */ ; // induction clause induction_optional[ClawLanguage l] @init{ List<String> temp = new ArrayList<>(); } : INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); } | /* empty */ ; // data clause data_clause[ClawLanguage l] @init { List<String> temp = new ArrayList<>(); } : DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); } ; // private clause private_optional[ClawLanguage l]: PRIVATE { $l.setPrivateClause(); } | /* empty */ ; // reshape clause reshape_optional[ClawLanguage l] @init{ List<ClawReshapeInfo> r = new ArrayList(); } : RESHAPE '(' reshape_list[r] ')' { $l.setReshapeClauseValues(r); } | /* empty */ ; // reshape clause reshape_element returns [ClawReshapeInfo i] @init{ List<Integer> temp = new ArrayList(); } : array_name=IDENTIFIER '(' target_dim=NUMBER ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } | array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } ; reshape_list[List<ClawReshapeInfo> r]: info=reshape_element { $r.add($info.i); } ',' reshape_list[$r] | info=reshape_element { $r.add($info.i); } ; identifiers[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids] ; identifiers_list[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids] ; integers[List<Integer> ints]: ; integers_list[List<Integer> ints]: i=NUMBER { $ints.add(Integer.parseInt($i.text)); } | i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints] ; indexes_option[ClawLanguage l] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $l.setIndexes(indexes); } | /* empty */ ; offset_list_optional[List<Integer> offsets]: OFFSET '(' offset_list[$offsets] ')' | /* empty */ ; offset_list[List<Integer> offsets]: offset[$offsets] | offset[$offsets] ',' offset_list[$offsets] ; offset[List<Integer> offsets]: n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } | '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); } | '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(ClawConstant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; range_id returns [String text]: n=NUMBER { $text = $n.text; } | i=IDENTIFIER { $text = $i.text; } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; mapping_var_list[List<ClawMappingVar> vars]: mv=mapping_var { $vars.add($mv.mappingVar); } | mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars] ; mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>(); List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>(); $mapping.setMappedVariables(listMapped); $mapping.setMappingVariables(listMapping); } : MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')' ; mapping_option_list[List<ClawMapping> mappings]: m=mapping_option { $mappings.add($m.mapping); } | m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings] ; define_option[ClawLanguage l]: DEFINE DIMENSION id=IDENTIFIER '(' lower=range_id ':' upper=range_id ')' { ClawDimension cd = new ClawDimension($id.text, $lower.text, $upper.text); $l.addDimension(cd); } ; // Allow to switch order parallelize_clauses[ClawLanguage l]: copy_clause_optional[$l] update_clause_optional[$l] | update_clause_optional[$l] copy_clause_optional[$l] ; copy_clause_optional[ClawLanguage l]: /* empty */ | COPY { $l.setCopyClauseValue(ClawDMD.BOTH); } | COPY '(' IN ')' { $l.setCopyClauseValue(ClawDMD.IN); } | COPY '(' OUT ')' { $l.setCopyClauseValue(ClawDMD.OUT); } ; update_clause_optional[ClawLanguage l]: /* empty */ | UPDATE { $l.setUpdateClauseValue(ClawDMD.BOTH); } | UPDATE '(' IN ')' { $l.setUpdateClauseValue(ClawDMD.IN); } | UPDATE '(' OUT ')' { $l.setUpdateClauseValue(ClawDMD.OUT); } ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // CLAW Directives ARRAY_TRANS : 'array-transform'; ARRAY_TO_CALL : 'call'; DEFINE : 'define'; END : 'end'; KCACHE : 'kcache'; LOOPEXTRACT : 'loop-extract'; LOOPFUSION : 'loop-fusion'; LOOPHOIST : 'loop-hoist'; LOOPINTERCHANGE : 'loop-interchange'; PARALLELIZE : 'parallelize'; REMOVE : 'remove'; IGNORE : 'ignore'; VERBATIM : 'verbatim'; // CLAW Clauses COLLAPSE : 'collapse'; COPY : 'copy'; DATA : 'data'; DIMENSION : 'dimension'; FORWARD : 'forward'; FUSION : 'fusion'; GROUP : 'group'; INDUCTION : 'induction'; INIT : 'init'; INTERCHANGE : 'interchange'; MAP : 'map'; OFFSET : 'offset'; OVER : 'over'; PARALLEL : 'parallel'; PRIVATE : 'private'; RANGE : 'range'; RESHAPE : 'reshape'; UPDATE : 'update'; // data copy/update clause keywords IN : 'in'; OUT : 'out'; // Directive primitive clause ACC : 'acc'; OMP : 'omp'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : [0-9] ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
Add copy/update clauses to parallelize forward
Add copy/update clauses to parallelize forward
ANTLR
bsd-2-clause
clementval/claw-compiler,clementval/claw-compiler
18d7325bc5668ac9b2577b66cb933953b61020e9
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/BaseRule.g4
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/BaseRule.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar BaseRule; import Keyword, Symbol, Literals; schemaName : IDENTIFIER_ ; tableName : IDENTIFIER_ ; columnName : IDENTIFIER_ ; collationName : STRING_ | IDENTIFIER_ ; indexName : IDENTIFIER_ ; alias : IDENTIFIER_ ; dataTypeLength : LP_ (NUMBER_ (COMMA_ NUMBER_)?)? RP_ ; primaryKey : PRIMARY? KEY ; columnNames : LP_ columnName (COMMA_ columnName)* RP_ ; exprs : expr (COMMA_ expr)* ; exprList : LP_ exprs RP_ ; expr : expr AND expr | expr AND_ expr | expr XOR expr | LP_ expr RP_ | NOT expr | NOT_ expr | expr OR expr | expr OR_ expr | booleanPrimary | exprRecursive ; exprRecursive : matchNone ; booleanPrimary : booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL) | booleanPrimary SAFE_EQ_ predicate | booleanPrimary comparisonOperator predicate | booleanPrimary comparisonOperator (ALL | ANY) subquery | predicate ; comparisonOperator : EQ_ | GTE_ | GT_ | LTE_ | LT_ | NEQ_ ; predicate : bitExpr NOT? IN subquery | bitExpr NOT? IN LP_ simpleExpr (COMMA_ simpleExpr)* RP_ | bitExpr NOT? BETWEEN simpleExpr AND predicate | bitExpr SOUNDS LIKE simpleExpr | bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)* | bitExpr NOT? REGEXP simpleExpr | bitExpr ; bitExpr : bitExpr VERTICAL_BAR_ bitExpr | bitExpr AMPERSAND_ bitExpr | bitExpr SIGNED_LEFT_SHIFT_ bitExpr | bitExpr SIGNED_RIGHT_SHIFT_ bitExpr | bitExpr PLUS_ bitExpr | bitExpr MINUS_ bitExpr | bitExpr ASTERISK_ bitExpr | bitExpr SLASH_ bitExpr | bitExpr MOD bitExpr | bitExpr MOD_ bitExpr | bitExpr CARET_ bitExpr | bitExpr PLUS_ intervalExpr | bitExpr MINUS_ intervalExpr | simpleExpr ; simpleExpr : functionCall | literal | columnName | simpleExpr collateClause //| param_marker | variable | simpleExpr AND_ simpleExpr | PLUS_ simpleExpr | MINUS_ simpleExpr | TILDE_ simpleExpr | NOT_ simpleExpr | BINARY simpleExpr | exprList | ROW exprList | subquery | EXISTS subquery // | (identifier_ expr) //| match_expr | caseExpress | intervalExpr | privateExprOfDb ; functionCall : IDENTIFIER_ LP_ distinct? (exprs | ASTERISK_)? RP_ ; distinct : DISTINCT ; intervalExpr : matchNone ; caseExpress : matchNone ; privateExprOfDb : aggregateExpression | windowFunction | arrayConstructorWithCast | (TIMESTAMP (WITH TIME ZONE)? STRING_) | extractFromFunction ; variable : matchNone ; literal : question | number | TRUE | FALSE | NULL | LBE_ IDENTIFIER_ STRING_ RBE_ | HEX_DIGIT_ | string | IDENTIFIER_ STRING_ collateClause? | (DATE | TIME | TIMESTAMP) STRING_ | IDENTIFIER_? BIT_NUM_ collateClause? ; question : QUESTION_ ; number : NUMBER_ ; string : STRING_ ; subquery : matchNone ; collateClause : COLLATE collationName ; orderByClause : ORDER BY expr (ASC | DESC | USING operator)? (NULLS (FIRST | LAST))? ; orderByItem : (columnName | number | expr) (ASC | DESC)? ; asterisk : ASTERISK_ ; dataType : dataTypeName_ intervalFields? dataTypeLength? (WITHOUT TIME ZONE | WITH TIME ZONE)? (LBT_ RBT_)* | IDENTIFIER_ ; dataTypeName_ : IDENTIFIER_ IDENTIFIER_ | IDENTIFIER_ ; intervalFields : intervalField (TO intervalField)? ; intervalField : YEAR | MONTH | DAY | HOUR | MINUTE | SECOND ; pgExpr : castExpr | collateExpr | expr ; aggregateExpression : IDENTIFIER_ (LP_ (ALL | DISTINCT)? exprs orderByClause? RP_) asteriskWithParen (LP_ exprs RP_ WITHIN GROUP LP_ orderByClause RP_) filterClause? ; filterClause : FILTER LP_ WHERE booleanPrimary RP_ ; asteriskWithParen : LP_ ASTERISK_ RP_ ; windowFunction : IDENTIFIER_ (exprList | asteriskWithParen) filterClause? windowFunctionWithClause ; windowFunctionWithClause : OVER (IDENTIFIER_ | LP_ windowDefinition RP_) ; windowDefinition : IDENTIFIER_? (PARTITION BY exprs)? (orderByClause (COMMA_ orderByClause)*)? frameClause? ; operator : SAFE_EQ_ | EQ_ | NEQ_ | GT_ | GTE_ | LT_ | LTE_ | AND_ | OR_ | NOT_ ; frameClause : (RANGE | ROWS) frameStart | (RANGE | ROWS) BETWEEN frameStart AND frameEnd ; frameStart : UNBOUNDED PRECEDING | NUMBER_ PRECEDING | CURRENT ROW | NUMBER_ FOLLOWING | UNBOUNDED FOLLOWING ; frameEnd : frameStart ; castExpr : CAST LP_ expr AS dataType RP_ | expr COLON_ COLON_ dataType ; castExprWithCOLON_ : COLON_ COLON_ dataType(LBT_ RBT_)* ; collateExpr : expr COLLATE expr ; arrayConstructorWithCast : arrayConstructor castExprWithCOLON_? | ARRAY LBT_ RBT_ castExprWithCOLON_ ; arrayConstructor : ARRAY LBT_ exprs RBT_ | ARRAY LBT_ arrayConstructor (COMMA_ arrayConstructor)* RBT_ ; extractFromFunction : EXTRACT LP_ IDENTIFIER_ FROM IDENTIFIER_ RP_ ; ignoredIdentifier_ : IDENTIFIER_ ; ignoredIdentifiers_ : ignoredIdentifier_ (COMMA_ ignoredIdentifier_)* ; matchNone : 'Default does not match anything' ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar BaseRule; import Keyword, Symbol, Literals; schemaName : IDENTIFIER_ ; tableName : IDENTIFIER_ ; tableNames : LP_? tableName (COMMA_ tableName)* RP_? ; columnName : IDENTIFIER_ ; columnNames : LP_ columnName (COMMA_ columnName)* RP_ ; collationName : STRING_ | IDENTIFIER_ ; indexName : IDENTIFIER_ ; alias : IDENTIFIER_ ; dataTypeLength : LP_ (NUMBER_ (COMMA_ NUMBER_)?)? RP_ ; primaryKey : PRIMARY? KEY ; exprs : expr (COMMA_ expr)* ; exprList : LP_ exprs RP_ ; expr : expr AND expr | expr AND_ expr | expr XOR expr | LP_ expr RP_ | NOT expr | NOT_ expr | expr OR expr | expr OR_ expr | booleanPrimary | exprRecursive ; exprRecursive : matchNone ; booleanPrimary : booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL) | booleanPrimary SAFE_EQ_ predicate | booleanPrimary comparisonOperator predicate | booleanPrimary comparisonOperator (ALL | ANY) subquery | predicate ; comparisonOperator : EQ_ | GTE_ | GT_ | LTE_ | LT_ | NEQ_ ; predicate : bitExpr NOT? IN subquery | bitExpr NOT? IN LP_ simpleExpr (COMMA_ simpleExpr)* RP_ | bitExpr NOT? BETWEEN simpleExpr AND predicate | bitExpr SOUNDS LIKE simpleExpr | bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)* | bitExpr NOT? REGEXP simpleExpr | bitExpr ; bitExpr : bitExpr VERTICAL_BAR_ bitExpr | bitExpr AMPERSAND_ bitExpr | bitExpr SIGNED_LEFT_SHIFT_ bitExpr | bitExpr SIGNED_RIGHT_SHIFT_ bitExpr | bitExpr PLUS_ bitExpr | bitExpr MINUS_ bitExpr | bitExpr ASTERISK_ bitExpr | bitExpr SLASH_ bitExpr | bitExpr MOD bitExpr | bitExpr MOD_ bitExpr | bitExpr CARET_ bitExpr | bitExpr PLUS_ intervalExpr | bitExpr MINUS_ intervalExpr | simpleExpr ; simpleExpr : functionCall | literal | columnName | simpleExpr collateClause //| param_marker | variable | simpleExpr AND_ simpleExpr | PLUS_ simpleExpr | MINUS_ simpleExpr | TILDE_ simpleExpr | NOT_ simpleExpr | BINARY simpleExpr | exprList | ROW exprList | subquery | EXISTS subquery // | (identifier_ expr) //| match_expr | caseExpress | intervalExpr | privateExprOfDb ; functionCall : IDENTIFIER_ LP_ distinct? (exprs | ASTERISK_)? RP_ ; distinct : DISTINCT ; intervalExpr : matchNone ; caseExpress : matchNone ; privateExprOfDb : aggregateExpression | windowFunction | arrayConstructorWithCast | (TIMESTAMP (WITH TIME ZONE)? STRING_) | extractFromFunction ; variable : matchNone ; literal : question | number | TRUE | FALSE | NULL | LBE_ IDENTIFIER_ STRING_ RBE_ | HEX_DIGIT_ | string | IDENTIFIER_ STRING_ collateClause? | (DATE | TIME | TIMESTAMP) STRING_ | IDENTIFIER_? BIT_NUM_ collateClause? ; question : QUESTION_ ; number : NUMBER_ ; string : STRING_ ; subquery : matchNone ; collateClause : COLLATE collationName ; orderByClause : ORDER BY expr (ASC | DESC | USING operator)? (NULLS (FIRST | LAST))? ; orderByItem : (columnName | number | expr) (ASC | DESC)? ; asterisk : ASTERISK_ ; dataType : dataTypeName_ intervalFields? dataTypeLength? (WITHOUT TIME ZONE | WITH TIME ZONE)? (LBT_ RBT_)* | IDENTIFIER_ ; dataTypeName_ : IDENTIFIER_ IDENTIFIER_ | IDENTIFIER_ ; intervalFields : intervalField (TO intervalField)? ; intervalField : YEAR | MONTH | DAY | HOUR | MINUTE | SECOND ; pgExpr : castExpr | collateExpr | expr ; aggregateExpression : IDENTIFIER_ (LP_ (ALL | DISTINCT)? exprs orderByClause? RP_) asteriskWithParen (LP_ exprs RP_ WITHIN GROUP LP_ orderByClause RP_) filterClause? ; filterClause : FILTER LP_ WHERE booleanPrimary RP_ ; asteriskWithParen : LP_ ASTERISK_ RP_ ; windowFunction : IDENTIFIER_ (exprList | asteriskWithParen) filterClause? windowFunctionWithClause ; windowFunctionWithClause : OVER (IDENTIFIER_ | LP_ windowDefinition RP_) ; windowDefinition : IDENTIFIER_? (PARTITION BY exprs)? (orderByClause (COMMA_ orderByClause)*)? frameClause? ; operator : SAFE_EQ_ | EQ_ | NEQ_ | GT_ | GTE_ | LT_ | LTE_ | AND_ | OR_ | NOT_ ; frameClause : (RANGE | ROWS) frameStart | (RANGE | ROWS) BETWEEN frameStart AND frameEnd ; frameStart : UNBOUNDED PRECEDING | NUMBER_ PRECEDING | CURRENT ROW | NUMBER_ FOLLOWING | UNBOUNDED FOLLOWING ; frameEnd : frameStart ; castExpr : CAST LP_ expr AS dataType RP_ | expr COLON_ COLON_ dataType ; castExprWithCOLON_ : COLON_ COLON_ dataType(LBT_ RBT_)* ; collateExpr : expr COLLATE expr ; arrayConstructorWithCast : arrayConstructor castExprWithCOLON_? | ARRAY LBT_ RBT_ castExprWithCOLON_ ; arrayConstructor : ARRAY LBT_ exprs RBT_ | ARRAY LBT_ arrayConstructor (COMMA_ arrayConstructor)* RBT_ ; extractFromFunction : EXTRACT LP_ IDENTIFIER_ FROM IDENTIFIER_ RP_ ; ignoredIdentifier_ : IDENTIFIER_ ; ignoredIdentifiers_ : ignoredIdentifier_ (COMMA_ ignoredIdentifier_)* ; matchNone : 'Default does not match anything' ;
add tableNames rule
add tableNames rule
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
be6ceba788af3ffafd65e6ee9dc2a382aa837bd9
clojure/Clojure.g4
clojure/Clojure.g4
/* Converted to ANTLR 4 by Terence Parr. Unsure of provence. I see it commited by matthias.koester for clojure-eclipse project on Oct 5, 2009: https://code.google.com/p/clojure-eclipse/ Seems to me Laurent Petit had a version of this. I also see Jingguo Yao submitting a link to a now-dead github project on Jan 1, 2011. https://github.com/laurentpetit/ccw/tree/master/clojure-antlr-grammar Regardless, there are some issues perhaps related to "sugar"; I've tried to fix them. This parses https://github.com/weavejester/compojure project. I also note this is hardly a grammar; more like "match a bunch of crap in parens" but I guess that is LISP for you ;) */ grammar Clojure; file: list*; form: literal | list | vector | map | reader_macro | '#\'' SYMBOL // TJP added (get Var object instead of the value of a symbol) ; list: '(' form* ')' ; vector: '[' form* ']' ; map: '{' (form form)* '}' ; // TJP added '&' (gather a variable number of arguments) special_form: ('\'' | '`' | '~' | '~@' | '^' | '@' | '&') form ; lambda: '#(' form* ')' ; meta_data: '#^' map form ; var_quote: '\'' '#' SYMBOL ; regex: '#' STRING ; reader_macro : lambda | meta_data | special_form | regex | var_quote | SYMBOL '#' // TJP added (auto-gensym) ; literal : STRING | NUMBER | CHARACTER | NIL | BOOLEAN | KEYWORD | SYMBOL | PARAM_NAME ; STRING : '"' ( ~'"' | '\\' '"' )* '"' ; NUMBER : '-'? [0-9]+ ('.' [0-9]+)? ([eE] '-'? [0-9]+)? ; CHARACTER : '\\' . ; NIL : 'nil'; BOOLEAN : 'true' | 'false' ; KEYWORD : ':' SYMBOL ; SYMBOL: '.' | '/' | NAME ('/' NAME)? ; PARAM_NAME: '%' (('1'..'9')('0'..'9')*)? ; fragment NAME: SYMBOL_HEAD SYMBOL_REST* (':' SYMBOL_REST+)* ; fragment SYMBOL_HEAD : 'a'..'z' | 'A'..'Z' | '*' | '+' | '!' | '-' | '_' | '?' | '>' | '<' | '=' | '$' ; fragment SYMBOL_REST : SYMBOL_HEAD | '&' // apparently this is legal in an ID: "(defn- assoc-&-binding ..." TJP | '0'..'9' | '.' ; WS : [ \n\r\t\,] -> channel(HIDDEN) ; COMMENT : ';' ~[\r\n]* -> channel(HIDDEN) ;
/* Reworked for grammar specificity by Reid Mckenzie. Did a bunch of work so that rather than reading "a bunch of crap in parens" some syntactic information is preserved and recovered. Dec. 14 2014. Converted to ANTLR 4 by Terence Parr. Unsure of provence. I see it commited by matthias.koester for clojure-eclipse project on Oct 5, 2009: https://code.google.com/p/clojure-eclipse/ Seems to me Laurent Petit had a version of this. I also see Jingguo Yao submitting a link to a now-dead github project on Jan 1, 2011. https://github.com/laurentpetit/ccw/tree/master/clojure-antlr-grammar Regardless, there are some issues perhaps related to "sugar"; I've tried to fix them. This parses https://github.com/weavejester/compojure project. I also note this is hardly a grammar; more like "match a bunch of crap in parens" but I guess that is LISP for you ;) */ grammar Clojure; file: form *; form: literal | list | vector | map | reader_macro ; forms: form* ; list: '(' forms ')' ; vector: '[' forms ']' ; map: '{' (form form)* '}' ; set: '#{' forms '}' ; reader_macro : lambda | meta_data | regex | var_quote | host_expr | set | tag | discard | dispatch | deref | quote | backtick | unquote | unquote_splicing | gensym ; // TJP added '&' (gather a variable number of arguments) quote : '\'' form ; backtick : '`' form ; unquote : '~' form ; unquote_splicing : '~@' form ; tag : '^' form form ; deref : '@' form ; gensym : SYMBOL '#' ; lambda : '#(' form* ')' ; meta_data : '#^' map form ; var_quote : '#\'' symbol ; host_expr : '#+' form form ; discard : '#_' form ; dispatch : '#' symbol form ; regex : '#' string ; literal : string | number | character | nil | boolean | keyword | symbol | param_name ; string: STRING; float: FLOAT; hex: HEX; bin: BIN; bign: BIGN; long: LONG; number : float | hex | bin | bign | long ; character : named_char | u_hex_quad | any_char ; named_char: CHAR_NAMED ; any_char: CHAR_ANY ; u_hex_quad: CHAR_U ; nil: NIL; boolean: BOOLEAN; keyword: macro_keyword | simple_keyword; simple_keyword: ':' symbol; macro_keyword: ':' ':' symbol; symbol: ns_symbol | simple_sym; simple_sym: SYMBOL; ns_symbol: NS_SYMBOL; param_name: PARAM_NAME; // Lexers //-------------------------------------------------------------------- STRING : '"' ( ~'"' | '\\' '"' )* '"' ; // FIXME: Doesn't deal with arbitrary read radixes, BigNums FLOAT : '-'? [0-9]+ FLOAT_TAIL | '-'? 'Infinity' | '-'? 'NaN' ; fragment FLOAT_TAIL : FLOAT_DECIMAL FLOAT_EXP | FLOAT_DECIMAL | FLOAT_EXP ; fragment FLOAT_DECIMAL : '.' [0-9]+ ; fragment FLOAT_EXP : [eE] '-'? [0-9]+ ; fragment HEXD: [0-9a-fA-F] ; HEX: '0' [xX] HEXD+ ; BIN: '0' [bB] [10]+ ; LONG: '-'? [0-9]+[lL]?; BIGN: '-'? [0-9]+[nN]; CHAR_U : '\\' 'u'[0-9D-Fd-f] HEXD HEXD HEXD ; CHAR_NAMED : '\\' ( 'newline' | 'return' | 'space' | 'tab' | 'formfeed' | 'backspace' ) ; CHAR_ANY : '\\' . ; NIL : 'nil'; BOOLEAN : 'true' | 'false' ; SYMBOL : '.' | '/' | NAME ; NS_SYMBOL : NAME '/' SYMBOL ; PARAM_NAME: '%' ((('1'..'9')('0'..'9')*)|'&')? ; // Fragments //-------------------------------------------------------------------- fragment NAME: SYMBOL_HEAD SYMBOL_REST* (':' SYMBOL_REST+)* ; fragment SYMBOL_HEAD : ~('0' .. '9' | '^' | '`' | '\'' | '"' | '#' | '~' | '@' | ':' | '/' | '%' | '(' | ')' | '[' | ']' | '{' | '}' // FIXME: could be one group | [ \n\r\t\,] // FIXME: could be WS ) ; fragment SYMBOL_REST : SYMBOL_HEAD | '0'..'9' | '.' ; // Discard //-------------------------------------------------------------------- fragment WS : [ \n\r\t\,] ; fragment COMMENT: ';' ~[\r\n]* ; TRASH : ( WS | COMMENT ) -> channel(HIDDEN) ;
Improve grammar specificity
Improve grammar specificity While the original grammar worked, the resulting tree was very hard to analyze as it had little remaining tag information. This reworked grammar supports all the existing reader macros, host expressions as proposed for Clojure 1.7 and retains significantly more context information making it easy to manipulate the resulting tree.
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
91a277c6ebd71997ff66fe175371d39eabadabce
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
grammar OracleDCLStatement; import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol; /** * each statement has a url, * each base url : https://docs.oracle.com/database/121/SQLRF/. * no begin statement in oracle */ //statements_9014.htm#SQLRF01603 grant : GRANT ( (grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))? | grantRolesToPrograms ) ; grantSystemPrivileges : systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)? ; systemObjects : systemObject(COMMA systemObject)* ; systemObject : ALL PRIVILEGES | roleName | ID *? ; grantees : grantee (COMMA grantee)* ; grantee : userName | roleName | PUBLIC ; granteeIdentifiedBy : userName (COMMA userName)* IDENTIFIED BY STRING (COMMA STRING)* ; grantObjectPrivilegeClause : grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause TO grantees (WITH HIERARCHY OPTION)?(WITH GRANT OPTION)? ; grantObjectPrivilege : objectPrivilege ( LP_ columnName (COMMA columnName)* RP_)? ; objectPrivilege : ID *? | ALL PRIVILEGES? ; onObjectClause : ON ( schemaName? ID | USER userName ( COMMA userName)* | (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID ) ; grantRolesToPrograms : roleName (COMMA roleName)* TO programUnit ( COMMA programUnit )* ; programUnit : (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID ; revokeSystemPrivileges : systemObjects FROM ; revokeObjectPrivileges : objectPrivilege (COMMA objectPrivilege)* onObjectClause FROM grantees (CASCADE CONSTRAINTS | FORCE)? ;
grammar OracleDCLStatement; import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol; /** * each statement has a url, * each base url : https://docs.oracle.com/database/121/SQLRF/. * no begin statement in oracle */ //statements_9014.htm#SQLRF01603 grant : GRANT ( (grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))? | grantRolesToPrograms ) ; grantSystemPrivileges : systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)? ; systemObjects : systemObject(COMMA systemObject)* ; systemObject : ALL PRIVILEGES | roleName | ID *? ; grantees : grantee (COMMA grantee)* ; grantee : userName | roleName | PUBLIC ; granteeIdentifiedBy : userNames IDENTIFIED BY STRING (COMMA STRING)* ; grantObjectPrivilegeClause : grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause TO grantees (WITH HIERARCHY OPTION)?(WITH GRANT OPTION)? ; grantObjectPrivilege : objectPrivilege columnList? ; objectPrivilege : ID *? | ALL PRIVILEGES? ; onObjectClause : ON ( schemaName? ID | USER userName ( COMMA userName)* | (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID ) ; grantRolesToPrograms : roleNames TO programUnits ; programUnits : programUnit (COMMA programUnit)* ; programUnit : (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID ; revokeSystemPrivileges : systemObjects FROM ; revokeObjectPrivileges : objectPrivilege (COMMA objectPrivilege)* onObjectClause FROM grantees (CASCADE CONSTRAINTS | FORCE)? ; revokeRolesFromPrograms : (roleNames | ALL) FROM programUnits ;
add revokeRolesFromPrograms add programUnits use userNames roleNames
add revokeRolesFromPrograms add programUnits use userNames roleNames
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
2500d006d5ee48a32763093a5f3431afbb209629
VineScriptLib/Compilers/Vine/VineLexer.g4
VineScriptLib/Compilers/Vine/VineLexer.g4
lexer grammar VineLexer; @header { using System; } @members{ //public override IToken Emit(){ // switch (_type) { // case RESERVED_CHARS: // //setType(RESERVED_CHARS); // IToken result = base.Emit(); // // you'll need to define this method // System.Console.WriteLine("Unterminated string literal"); // //reportError(result, "Unterminated string literal"); // return result; // default: // return base.Emit(); // } //} } /* * Lexer Rules */ // Default "mode" (text mode) : Everything that is outside of tags '{{ .. }}', '{% .. %}' or '{# .. #}' OUTPUT: '{{' -> pushMode(VineCode) ; STMT: '{%' -> pushMode(VineCode) ; //LINE_COMMENT: '#' ~('#')*? NL -> channel(HIDDEN); BLOCK_COMMENT: '{#' .*? '#}' ; NL: '\r'? '\n' ; // Reserved/illegal characters: // * '\u000B': \v vertical tabulation, marks '\n' in strings returned by a function // and then used by LinesFormatter to keep those '\n' in place RESERVED_CHARS: [\u000B]+ ; TXT_LBRACE : '{' -> type(TXT) ; TXT : ~[{\r\n\u000B]+ ; // A text is either : // 1. anything that's not {, \r, \n // 2. or it is { but then it's not followed by {, %, #. ? // TODO: should allow escaping tags //TXT : ( ~('{'|'\r'|'\n') // | '{' ~('{'|'%'|'#'|'?') // )+ // | '{' ~('{'|'%'|'#'|'?')*? // special case when { is not followed by anything (EOF) // ; //TXT: ('{'? ~('{'|'%'|'#'|'?'|'\r'|'\n'))+ ; //TXT: ( '{' ~('{'|'%'|'#'|'?') // | {_input.La(-1) != '{'}? ~('{'|'\r'|'\n') // )+ ; ERROR_CHAR: . ; // ---------------------------------------------------------- mode VineCode; END_OUTPUT: '}}' -> popMode ; END_STMT: '%}' -> popMode ; LPAREN: '(' ; RPAREN: ')' ; LBRACK: '[' ; RBRACK: ']' ; LBRACE: '{' ; RBRACE: '}' ; // Separators DOT: '.' ; COMMA: ',' ; COLON: ':' ; // Unary op MINUS: '-' ; NOT: '!' ; NOT2: 'not ' -> type(NOT) ; POW: '^' ; // right assoc // Arithmetic op MUL: '*' ; DIV: '/' ; ADD: '+' ; MOD: '%' ; // Equality op EQ: '==' ; NEQ: '!=' ; IS_EQ: ' is ' -> type(EQ) ; IS_NEQ: ' is not ' -> type(NEQ) ; // Bool op AND: '&&' ; OR: '||' ; AND2: ' and ' -> type(AND) ; OR2: ' or ' -> type(OR) ; // Comparison op LT: '<' ; GT: '>' ; LTE: '<=' ; GTE: '>=' ; // Keywords IF: 'if ' ; ELIF: 'elif ' ; ELSE: 'else' ; ENDIF: 'endif' ; TRUE: 'true' ; FALSE: 'false' ; NULL: 'null' ; // Assign TO: 'to' ; ASSIGN: '=' ; // TODO complete list. Commands are built-in functions COMMAND: 'array' | 'TODO' ; SET: 'set' ; STRING: '"' (ESC | ~('\u000B'))*? '"' ; // catches string containing '\u000B': ILLEGAL_STRING: '"' (ESC | .)*? '"' ; //tokens { STRING } //DOUBLE : '"' .*? '"' -> type(STRING) ; //SINGLE : '\'' .*? '\'' -> type(STRING) ; //STRING_SQUOTE: '\'' (ESC_SQUOTE|.)*? '\'' ; //STRING_DQUOTE: '"' (ESC_DQUOTE|.)*? '"' ; VAR_PREFIX: '$' ; // Unicode ID https://github.com/antlr/antlr4/blob/master/doc/lexer-rules.md //UNICODE_ID : [\p{Alpha}\p{General_Category=Other_Letter}] [\p{Alnum}\p{General_Category=Other_Letter}]* ; // match full Unicode alphabetic ids ID: ID_LETTER (ID_LETTER | DIGIT)* ; INT: DIGIT+ ; FLOAT: DIGIT+ '.' DIGIT+ ; // From Harlowe: // This includes all forms of Unicode 6 whitespace except \n, \r, and Ogham space mark. //WS_CODE: [ \f\t\v\u00a0\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+ -> skip ; // Unicode whitespace https://github.com/antlr/antlr4/blob/master/doc/lexer-rules.md //UNICODE_WS : [\p{White_Space}] -> skip; // match all Unicode whitespace WS_CODE: [ \t\f]+ -> channel(HIDDEN) ; VineCode_ERROR_CHAR: ERROR_CHAR -> type(ERROR_CHAR) ; // fragments fragment ESC: '\\"' | '\\\\' ; // 2-char sequences \" and \\ //fragment ESC_SQUOTE: '\\\'' | '\\\\' ; // 2-char sequences \" and \\ //fragment ESC_DQUOTE: '\\"' | '\\\\' ; // 2-char sequences \" and \\ fragment DIGIT: [0-9] ; fragment ID_LETTER: [A-Za-z\u0080-\uFFFF_] ; // goes from 41 ('A') to z then 128 to 65535 (unicode)
lexer grammar VineLexer; @header { using System; } @members{ //public override IToken Emit(){ // switch (_type) { // case RESERVED_CHARS: // //setType(RESERVED_CHARS); // IToken result = base.Emit(); // // you'll need to define this method // System.Console.WriteLine("Unterminated string literal"); // //reportError(result, "Unterminated string literal"); // return result; // default: // return base.Emit(); // } //} } /* * Lexer Rules */ // Default "mode" (text mode) : Everything that is outside of tags '{{ .. }}', '{% .. %}' or '{# .. #}' OUTPUT: '{{' -> pushMode(VineCode) ; STMT: '{%' -> pushMode(VineCode) ; //LINE_COMMENT: '#' ~('#')*? NL -> channel(HIDDEN); BLOCK_COMMENT: '{#' .*? '#}' ; NL: '\r'? '\n' ; // Reserved/illegal characters: // * '\u000B': \v vertical tabulation, marks '\n' in strings returned by a function // and then used by LinesFormatter to keep those '\n' in place RESERVED_CHARS: [\u000B]+ ; TXT_LBRACE : '{' -> type(TXT) ; TXT : ~[{\r\n\u000B]+ ; // A text is either : // 1. anything that's not {, \r, \n // 2. or it is { but then it's not followed by {, %, #. ? // TODO: should allow escaping tags //TXT : ( ~('{'|'\r'|'\n') // | '{' ~('{'|'%'|'#'|'?') // )+ // | '{' ~('{'|'%'|'#'|'?')*? // special case when { is not followed by anything (EOF) // ; //TXT: ('{'? ~('{'|'%'|'#'|'?'|'\r'|'\n'))+ ; //TXT: ( '{' ~('{'|'%'|'#'|'?') // | {_input.La(-1) != '{'}? ~('{'|'\r'|'\n') // )+ ; ERROR_CHAR: . ; // ---------------------------------------------------------- mode VineCode; END_OUTPUT: '}}' -> popMode ; END_STMT: '%}' -> popMode ; LPAREN: '(' ; RPAREN: ')' ; LBRACK: '[' ; RBRACK: ']' ; LBRACE: '{' ; RBRACE: '}' ; // Separators DOT: '.' ; COMMA: ',' ; COLON: ':' ; // Unary op MINUS: '-' ; NOT: '!' ; POW: '^' ; // right assoc // Arithmetic op MUL: '*' ; DIV: '/' ; ADD: '+' ; MOD: '%' ; // Equality op EQ: '==' ; NEQ: '!=' ; // Bool op AND: '&&' ; OR: '||' ; AND2: ' and ' -> type(AND) ; OR2: ' or ' -> type(OR) ; // Comparison op LT: '<' ; GT: '>' ; LTE: '<=' ; GTE: '>=' ; // Keywords IF: 'if ' ; ELIF: 'elif ' ; ELSE: 'else' ; ENDIF: 'endif' ; TRUE: 'true' ; FALSE: 'false' ; NULL: 'null' ; // Assign TO: 'to' ; ASSIGN: '=' ; // TODO complete list. Commands are built-in functions COMMAND: 'array' | 'TODO' ; SET: 'set' ; STRING: '"' (ESC | ~('\u000B'))*? '"' ; // catches string containing '\u000B': ILLEGAL_STRING: '"' (ESC | .)*? '"' ; //tokens { STRING } //DOUBLE : '"' .*? '"' -> type(STRING) ; //SINGLE : '\'' .*? '\'' -> type(STRING) ; //STRING_SQUOTE: '\'' (ESC_SQUOTE|.)*? '\'' ; //STRING_DQUOTE: '"' (ESC_DQUOTE|.)*? '"' ; VAR_PREFIX: '$' ; // Unicode ID https://github.com/antlr/antlr4/blob/master/doc/lexer-rules.md //UNICODE_ID : [\p{Alpha}\p{General_Category=Other_Letter}] [\p{Alnum}\p{General_Category=Other_Letter}]* ; // match full Unicode alphabetic ids ID: ID_LETTER (ID_LETTER | DIGIT)* ; INT: DIGIT+ ; FLOAT: DIGIT+ '.' DIGIT+ ; // From Harlowe: // This includes all forms of Unicode 6 whitespace except \n, \r, and Ogham space mark. //WS_CODE: [ \f\t\v\u00a0\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+ -> skip ; // Unicode whitespace https://github.com/antlr/antlr4/blob/master/doc/lexer-rules.md //UNICODE_WS : [\p{White_Space}] -> skip; // match all Unicode whitespace WS_CODE: [ \t\f]+ -> channel(HIDDEN) ; VineCode_ERROR_CHAR: ERROR_CHAR -> type(ERROR_CHAR) ; // fragments fragment ESC: '\\"' | '\\\\' ; // 2-char sequences \" and \\ //fragment ESC_SQUOTE: '\\\'' | '\\\\' ; // 2-char sequences \" and \\ //fragment ESC_DQUOTE: '\\"' | '\\\\' ; // 2-char sequences \" and \\ fragment DIGIT: [0-9] ; fragment ID_LETTER: [A-Za-z\u0080-\uFFFF_] ; // goes from 41 ('A') to z then 128 to 65535 (unicode)
Rollback commit introducing 'is' and 'not' c40bceb3896dedb68c3df29bc122073f173e5d43 That was actually very confusing, didn't think things through. Couldn't tell the difference between 'foo != bar' and 'foo == !bar' as it would translate to 'foo is not bar' in both cases...
Rollback commit introducing 'is' and 'not' c40bceb3896dedb68c3df29bc122073f173e5d43 That was actually very confusing, didn't think things through. Couldn't tell the difference between 'foo != bar' and 'foo == !bar' as it would translate to 'foo is not bar' in both cases...
ANTLR
mit
julsam/VineScript
ed88021e54955b0e8f58c8382b788d6efce7e311
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
/* Todo: * - Comments justifying and explaining every rule. */ lexer grammar CreoleTokens; options { superClass=ContextSensitiveLexer; } @members { Formatting bold; Formatting italic; Formatting strike; public void setupFormatting() { bold = new Formatting("**"); italic = new Formatting("//"); strike = new Formatting("--"); inlineFormatting.add(bold); inlineFormatting.add(italic); inlineFormatting.add(strike); } public boolean inHeader = false; public boolean start = false; public int listLevel = 0; boolean nowiki = false; boolean cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = false; boolean intr = false; public void doHdr() { String prefix = getText().trim(); boolean seekback = false; if(!prefix.substring(prefix.length() - 1).equals("=")) { prefix = prefix.substring(0, prefix.length() - 1); seekback = true; } if(prefix.length() <= 6) { if(seekback) { seek(-1); } setText(prefix); inHeader = true; } else { setType(Any); } } public void setStart() { String next1 = next(); String next2 = get(1); start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#")); } public void doList(int level) { listLevel = level; seek(-1); setStart(); resetFormatting(); } public void doUrl() { String url = getText(); String last = url.substring(url.length()-1); String next = next(); if(url.endsWith("://") || url.endsWith("mailto:")) { setType(Any); } while((last + next).equals("//") || last.matches("[\\.,)\"';:\\\\-=]")) { seek(-1); url = url.substring(0, url.length() - 1); last = url.substring(url.length()-1); next = next(); } setText(url); } public void breakOut() { resetFormatting(); listLevel = 0; inHeader = false; intr = false; nowiki = false; cpp = false; html = false; java = false; xhtml = false; xml = false; } public String[] thisKillsTheFormatting() { String[] ends = new String[7]; if(inHeader || intr) { ends[0] = "\n"; ends[1] = "\r\n"; } else { ends[0] = null; ends[1] = null; } if(intr) { ends[2] = "|"; } else { ends[2] = null; } ends[3] = "\n\n"; ends[4] = "\r\n\r\n"; if(listLevel > 0) { // \L (when at the start) matches the start of a line. ends[5] = "\\L*"; ends[6] = "\\L#"; } else { ends[5] = null; ends[6] = null; } return ends; } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' {doHdr();} ; HEnd : WS? '='* WS? (LineBreak | ParBreak) {inHeader}? {breakOut();} ; /* ***** Lists ***** */ U1 : START '*' ~'*' {doList(1);} ; U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ; U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ; U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ; U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ; U6 : START '******' ~'*' {listLevel >= 5}? {doList(6);} ; U7 : START '*******' ~'*' {listLevel >= 6}? {doList(7);} ; U8 : START '********' ~'*' {listLevel >= 7}? {doList(8);} ; U9 : START '*********' ~'*' {listLevel >= 8}? {doList(9);} ; U10 : START '**********' ~'*' {listLevel >= 9}? {doList(10);} ; O1 : START '#' ~'#' {doList(1);} ; O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ; O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ; O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ; O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ; O6 : START '######' ~'#' {listLevel >= 5}? {doList(6);} ; O7 : START '#######' ~'#' {listLevel >= 6}? {doList(7);} ; O8 : START '########' ~'#' {listLevel >= 7}? {doList(8);} ; O9 : START '#########' ~'#' {listLevel >= 8}? {doList(9);} ; O10 : START '##########' ~'#' {listLevel >= 9}? {doList(10);} ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+ {breakOut();} ; /* ***** Tables ***** */ TdStartLn : LINE '|'+ {intr=true; setType(TdStart);} ; ThStartLn : LINE '|'+ '=' {intr=true; setType(ThStart);} ; RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ; TdStart : '|'+ {intr}? {breakOut(); intr=true;} ; ThStart : '|'+ '=' {intr}? {breakOut(); intr=true;} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active && !prior().matches("[a-zA-Z0-9]:")}? {setFormatting(italic, Any);} ; SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ; BEnd : '**' {bold.active}? {unsetFormatting(bold);} ; IEnd : '//' {italic.active && !prior().matches("[a-zA-Z0-9]:")}? {unsetFormatting(italic);} ; SEnd : '--' {strike.active}? {unsetFormatting(strike);} ; NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ; StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ; StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ; StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ; StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ; StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ; /* ***** Links ***** */ LiSt : '[[' -> mode(LINK) ; ImSt : '{{' -> mode(LINK) ; /* ***** Breaks ***** */ InlineBrk : '\\\\' ; ParBreak : LineBreak WS? LineBreak+ {breakOut();} ; LineBreak : '\r'? '\n' ; /* ***** Links ***** */ RawUrl : PROTOCOL (~(' '|'\t'|'\r'|'\n'|'|'|'['|']')+ '/'?)+ {doUrl();} ; fragment PROTOCOL : ('http' 's'? | 'file' | 'ftp') '://' | 'file:/' | 'mailto:' ; Attachment : ALNUM+ '.' ALNUM+ ; WikiWords : (UPPER (ABBR | CAMEL) | INTERWIKI ALNUM+) {checkBounds("[\\.\\w:]", "\\w")}? ; fragment INTERWIKI : ALPHA ALNUM+ ':' ; fragment ABBR : UPPER UPPER+ ; fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ; /* ***** Macros ***** */ MacroSt : '<<' -> mode(MACRO) ; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t')+ ; EmptyLink : ('[[' WS? ']]' | '{{' WS? '}}' |'[[' WS? '|' WS? ']]' | '{{' WS? '|' WS? '}}') -> skip ; fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ; fragment START : {start}? | LINE ; fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*; fragment LOWNUM : (LOWER | DIGIT) ; fragment UPNUM : (UPPER | DIGIT) ; fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ; ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ; Sep : ' '* '|' ' '*; InLink : (~('|'|'\r'|'\n'|']'|'}') | ']' ~']' {seek(-1);} | '}' ~'}' {seek(-1);})+ {setText(getText().trim());}; mode MACRO; MacroName : ~(':'|'>')+ ; MacroEndNoArgs : '>>' -> mode(DEFAULT_MODE) ; MacroSep : ':' -> mode(MACRO_ARGS) ; mode MACRO_ARGS; MacroArgs : . -> more ; MacroEnd : '>>' -> mode(DEFAULT_MODE) ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') {seek(-1);} -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' ~'}' {nowiki}? {nowiki=false; seek(-1);} -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
/* Todo: * - Comments justifying and explaining every rule. */ lexer grammar CreoleTokens; options { superClass=ContextSensitiveLexer; } @members { Formatting bold; Formatting italic; Formatting strike; public void setupFormatting() { bold = new Formatting("**"); italic = new Formatting("//"); strike = new Formatting("--"); inlineFormatting.add(bold); inlineFormatting.add(italic); inlineFormatting.add(strike); } public boolean inHeader = false; public boolean start = false; public int listLevel = 0; boolean nowiki = false; boolean cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = false; boolean intr = false; public void doHdr() { String prefix = getText().trim(); boolean seekback = false; if(!prefix.substring(prefix.length() - 1).equals("=")) { prefix = prefix.substring(0, prefix.length() - 1); seekback = true; } if(prefix.length() <= 6) { if(seekback) { seek(-1); } setText(prefix); inHeader = true; } else { setType(Any); } } public void setStart() { String next1 = next(); String next2 = get(1); start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#")); } public void doList(int level) { listLevel = level; seek(-1); setStart(); resetFormatting(); } public void doUrl() { String url = getText(); String last = url.substring(url.length()-1); String next = next(); if(url.endsWith("://") || url.endsWith("mailto:")) { setType(Any); } while((last + next).equals("//") || last.matches("[\\.,)\"';:\\\\-=]")) { seek(-1); url = url.substring(0, url.length() - 1); last = url.substring(url.length()-1); next = next(); } setText(url); } public void breakOut() { resetFormatting(); listLevel = 0; inHeader = false; intr = false; nowiki = false; cpp = false; html = false; java = false; xhtml = false; xml = false; } public String[] thisKillsTheFormatting() { String[] ends = new String[7]; if(inHeader || intr) { ends[0] = "\n"; ends[1] = "\r\n"; } else { ends[0] = null; ends[1] = null; } if(intr) { ends[2] = "|"; } else { ends[2] = null; } ends[3] = "\n\n"; ends[4] = "\r\n\r\n"; if(listLevel > 0) { // \L (when at the start) matches the start of a line. ends[5] = "\\L*"; ends[6] = "\\L#"; } else { ends[5] = null; ends[6] = null; } return ends; } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' {doHdr();} ; HEnd : WS? '='* WS? (LineBreak | ParBreak) {inHeader}? {breakOut();} ; /* ***** Lists ***** */ U1 : START '*' ~'*' {doList(1);} ; U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ; U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ; U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ; U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ; U6 : START '******' ~'*' {listLevel >= 5}? {doList(6);} ; U7 : START '*******' ~'*' {listLevel >= 6}? {doList(7);} ; U8 : START '********' ~'*' {listLevel >= 7}? {doList(8);} ; U9 : START '*********' ~'*' {listLevel >= 8}? {doList(9);} ; U10 : START '**********' ~'*' {listLevel >= 9}? {doList(10);} ; O1 : START '#' ~'#' {doList(1);} ; O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ; O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ; O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ; O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ; O6 : START '######' ~'#' {listLevel >= 5}? {doList(6);} ; O7 : START '#######' ~'#' {listLevel >= 6}? {doList(7);} ; O8 : START '########' ~'#' {listLevel >= 7}? {doList(8);} ; O9 : START '#########' ~'#' {listLevel >= 8}? {doList(9);} ; O10 : START '##########' ~'#' {listLevel >= 9}? {doList(10);} ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+ {breakOut();} ; /* ***** Tables ***** */ TdStartLn : LINE '|'+ {intr=true; setType(TdStart);} ; ThStartLn : LINE '|'+ '=' {intr=true; setType(ThStart);} ; RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ; TdStart : '|'+ {intr}? {breakOut(); intr=true;} ; ThStart : '|'+ '=' {intr}? {breakOut(); intr=true;} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active && !prior().matches("[a-zA-Z0-9]:")}? {setFormatting(italic, Any);} ; SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ; BEnd : '**' {bold.active}? {unsetFormatting(bold);} ; IEnd : '//' {italic.active && !prior().matches("[a-zA-Z0-9]:")}? {unsetFormatting(italic);} ; SEnd : '--' {strike.active}? {unsetFormatting(strike);} ; NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ; StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ; StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ; StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ; StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ; StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ; /* ***** Links ***** */ LiSt : '[[' -> mode(LINK) ; ImSt : '{{' -> mode(LINK) ; /* ***** Breaks ***** */ InlineBrk : '\\\\' ; ParBreak : LineBreak WS? LineBreak+ {breakOut();} ; LineBreak : '\r'? '\n' ; /* ***** Links ***** */ RawUrl : PROTOCOL (~(' '|'\t'|'\r'|'\n'|'|'|'['|']')+ '/'?)+ {doUrl();} ; fragment PROTOCOL : ('http' 's'? | 'file' | 'ftp') '://' | 'file:/' | 'mailto:' ; Attachment : ALNUM+ '.' ALNUM+ ; WikiWords : (UPPER (ABBR | CAMEL) | INTERWIKI ALNUM+) {checkBounds("[\\.\\w:]", "\\w")}? ; fragment INTERWIKI : ALPHA ALNUM+ ':' ; fragment ABBR : UPPER UPPER+ ; fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ; /* ***** Macros ***** */ MacroSt : '<<' -> mode(MACRO) ; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t')+ ; EmptyLink : ('[[' WS? ']]' | '{{' WS? '}}' |'[[' WS? '|' WS? ']]' | '{{' WS? '|' WS? '}}') -> skip ; fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ; fragment START : {start}? | LINE ; fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*; fragment LOWNUM : (LOWER | DIGIT) ; fragment UPNUM : (UPPER | DIGIT) ; fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ; ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ; Sep : ' '* '|' ' '*; InLink : (~('|'|'\r'|'\n'|']'|'}') | ']' ~']' {seek(-1);} | '}' ~'}' {seek(-1);})+ {setText(getText().trim());}; mode MACRO; MacroName : ~(':'|'>')+ ; MacroEndNoArgs : '>>' -> mode(DEFAULT_MODE) ; MacroSep : ':' -> mode(MACRO_ARGS) ; mode MACRO_ARGS; MacroArgs : . -> more ; MacroEnd : '>>' -> mode(DEFAULT_MODE) ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') {seek(-1);} -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' ~'}' {nowiki}? {nowiki=false; seek(-1);} -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : (~' ' '}}}' | ' }}}' '\r'? '\n' {seek(-1);}) {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
Allow ending a NoWiki block with a ' }}}' if it's the last thing before a newline
Allow ending a NoWiki block with a ' }}}' if it's the last thing before a newline
ANTLR
apache-2.0
strr/reviki,ashirley/reviki,ashirley/reviki,ashirley/reviki,ashirley/reviki,CoreFiling/reviki,CoreFiling/reviki,strr/reviki,strr/reviki,CoreFiling/reviki,strr/reviki,ashirley/reviki,strr/reviki,CoreFiling/reviki,CoreFiling/reviki
42752dc59f1720683ce5d91cb7c3be78ca41a483
terraform/terraform.g4
terraform/terraform.g4
/* BSD License Copyright (c) 2020, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar terraform; file : (local | module | output | provider | variable | data | resource)+ ; resource : 'resource' resourcetype name blockbody ; data : 'data' resourcetype name blockbody ; provider : 'provider' resourcetype blockbody ; output : 'output' name blockbody ; local : 'locals' blockbody ; module : 'module' name blockbody ; variable : 'variable' name blockbody ; block : blocktype label* blockbody ; blocktype : IDENTIFIER ; resourcetype : STRING ; name : STRING ; label : STRING ; blockbody : '{' (argument | block)* '}' ; argument : identifier '=' expression ; identifier : IDENTIFIER ; expression // : section ('.' section)* : RESOURCEREFERENCE | section ; RESOURCEREFERENCE : [a-zA-Z] [a-zA-Z0-9_-]* RESOURCEINDEX? '.' ([a-zA-Z0-9_.-] RESOURCEINDEX?)+ ; RESOURCEINDEX : '[' [0-9]+ ']' ; section : list | map | val ; val : NULL | NUMBER | string | BOOL | IDENTIFIER index? | DESCRIPTION | filedecl | functioncall | EOF_ ; functioncall : functionname '(' functionarguments ')' ; functionname : IDENTIFIER ; functionarguments : //no arguments | expression (',' expression)* ; index : '[' expression ']' ; filedecl : 'file' '(' expression ')' ; list : '[' expression (',' expression)* ','? ']' ; map : '{' argument* '}' ; string : STRING | MULTILINESTRING ; fragment DIGIT : [0-9] ; EOF_ : '<<EOF' .*? 'EOF' ; NULL : 'nul' ; NUMBER : DIGIT+ ('.' DIGIT+)? ; BOOL : 'true' | 'false' ; DESCRIPTION : '<<DESCRIPTION' .*? 'DESCRIPTION' ; MULTILINESTRING : '<<-EOF' .*? 'EOF' ; STRING : '"' (~ [\r\n"] | '""')* '"' ; IDENTIFIER : [a-zA-Z] ([a-zA-Z0-9_-])* ; COMMENT : ('#' | '//') ~ [\r\n]* -> channel(HIDDEN) ; BLOCKCOMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; WS : [ \r\n\t]+ -> skip ;
/* BSD License Copyright (c) 2020, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar terraform; file : (local | module | output | provider | variable | data | resource)+ ; resource : 'resource' resourcetype name blockbody ; data : 'data' resourcetype name blockbody ; provider : 'provider' resourcetype blockbody ; output : 'output' name blockbody ; local : 'locals' blockbody ; module : 'module' name blockbody ; variable : 'variable' name blockbody ; block : blocktype label* blockbody ; blocktype : IDENTIFIER ; resourcetype : STRING ; name : STRING ; label : STRING ; blockbody : '{' (argument | block)* '}' ; argument : identifier '=' expression ; identifier : IDENTIFIER ; expression : RESOURCEREFERENCE | section ; RESOURCEREFERENCE : [a-zA-Z] [a-zA-Z0-9_-]* RESOURCEINDEX? '.' ([a-zA-Z0-9_.-] RESOURCEINDEX?)+ ; RESOURCEINDEX : '[' [0-9]+ ']' ; section : list | map | val ; val : NULL | NUMBER | string | BOOL | IDENTIFIER index? | DESCRIPTION | filedecl | functioncall | EOF_ ; functioncall : functionname '(' functionarguments ')' ; functionname : IDENTIFIER ; functionarguments : //no arguments | expression (',' expression)* ; index : '[' expression ']' ; filedecl : 'file' '(' expression ')' ; list : '[' expression (',' expression)* ','? ']' ; map : '{' argument* '}' ; string : STRING | MULTILINESTRING ; fragment DIGIT : [0-9] ; EOF_ : '<<EOF' .*? 'EOF' ; NULL : 'nul' ; NUMBER : DIGIT+ ('.' DIGIT+)? ; BOOL : 'true' | 'false' ; DESCRIPTION : '<<DESCRIPTION' .*? 'DESCRIPTION' ; MULTILINESTRING : '<<-EOF' .*? 'EOF' ; STRING : '"' (~ [\r\n"] | '""')* '"' ; IDENTIFIER : [a-zA-Z] ([a-zA-Z0-9_-])* ; COMMENT : ('#' | '//') ~ [\r\n]* -> channel(HIDDEN) ; BLOCKCOMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; WS : [ \r\n\t]+ -> skip ;
Remove old code
Remove old code
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
46d6ed447d97a00244d687772b5bb33426d89064
src/IFC-gen/Express.g4
src/IFC-gen/Express.g4
grammar Express; schema_declaration : SCHEMA Version ';' type_declaration* entity_declaration* function_declaration* END_SCHEMA';' EOF; type_declaration : TYPE type_name EQ (value_type|enumeration|select) FIXED? ';' type_declaration_body? END_TYPE ';' ; type_name : Identifier ; value_type : BOOLEAN | INTEGER | LOGICAL | REAL | STRING | STRING_SIZED | set_declaration | list_declaration | array_declaration | Identifier ; set_declaration : SET '[' Integer COLON (set_size|'?') ']' OF value_type (FOR Identifier)? ; set_size : Integer ; list_declaration : LIST '[' Integer COLON (list_size|'?') ']' OF value_type ; list_size : Integer ; array_declaration : ARRAY '[' Integer COLON (array_size|'?') ']' OF value_type ; array_size : Integer ; enumeration : ENUMERATION OF LP enum_id_list RP ; enum_id_list : id_list ; select : SELECT LP select_id_list RP ; select_id_list : id_list ; id_list : Identifier(','Identifier)* | IfcType(','IfcType)* ; type_declaration_body : rule_declaration ; rule_declaration : 'WHERE' rule+ ; rule : Identifier COLON expr ';' ; expr : func_call_expr | bool_expr | LB bool_expr RB ; func_call_expr : (EXISTS|SIZEOF|TYPEOF|QUERY|ABS|USEDIN|Identifier)'(' func_parameters ')' ; func_parameters : atom(','atom)* | formula_expr ; query_expr : Identifier INIT (Identifier|Path|PropertyAccessor|func_call_expr) PIPE bool_expr ; bool_expr : atom((LT|GT|LTE|GTE|EQ|NEQ|AND|OR)atom)* | (IfcType|Path|PropertyAccessor|Identifier|SELF) IN (func_call_expr|'['id_list']') ; formula_expr : atom((ADD|SUB|MUL|DIV)atom)+ ; atom : SELF | IfcType | Integer | Float | Identifier | Path | PropertyAccessor | SetAccessor | '[' id_list ']' | query_expr | func_call_expr | '('NOT? expr ')' | NOT?'('expr')' ; self_property : SELF '.' Identifier ; entity_declaration : ENTITY entity_name ';'? entity_declaration_body END_ENTITY ';' ; entity_name : Identifier ; entity_declaration_body : attribute* supertype_declaration? subtype_declaration? inverse_declaration? derive_declaration? rule_declaration? unique_declaration? ; supertype_declaration : ABSTRACT? SUPERTYPE OF LP (one_of | supertype_name) RP ';'? attribute* ; supertype_name : Identifier ; subtype_declaration : SUBTYPE OF LP (one_of | subtype_name) RP ';' attribute* ; subtype_name : Identifier ; attribute : attribute_name COLON OPTIONAL? value_type definition? ';' ; attribute_name : Identifier ; definition : DEF expr; one_of : ONEOF LP id_list RP ; inverse_declaration : INVERSE attribute+ ; derive_declaration : DERIVE attribute+ ; unique_declaration : UNIQUE unique_statement+ ; unique_statement : Identifier COLON .*? ';' ; function_declaration : 'FUNCTION' function_declaration_body 'END_FUNCTION' ; function_declaration_body : .*? ; // Lexer //Base Types BOOLEAN : 'BOOLEAN' ; INTEGER : 'INTEGER' ; LIST : 'LIST'; LOGICAL : 'LOGICAL' ; REAL : 'REAL' ; SET : 'SET' ; STRING_SIZED : 'STRING(' Integer ')'; FIXED : 'FIXED'; STRING : 'STRING' ; ARRAY : 'ARRAY' ; // Keywords ABSTRACT : 'ABSTRACT' ; AND : 'AND' ; DERIVE : 'DERIVE' ; ENTITY : 'ENTITY' ; END_ENTITY : 'END_ENTITY' ; ENUMERATION : 'ENUMERATION' ; FOR : 'FOR' ; IN : 'IN' ; INVERSE : 'INVERSE'; OF : 'OF'; ONEOF : 'ONEOF' ; OPTIONAL : 'OPTIONAL' ; OR : 'OR' ; SCHEMA : 'SCHEMA' ; END_SCHEMA : 'END_SCHEMA' ; SELECT : 'SELECT' ; SELF : 'SELF' ; SUBTYPE : 'SUBTYPE' ; SUPERTYPE : 'SUPERTYPE' ; TYPE : 'TYPE' ; END_TYPE : 'END_TYPE' ; UNIQUE : 'UNIQUE' ; //WHERE : 'WHERE' ; // Functions EXISTS : 'EXISTS' ; SIZEOF : 'SIZEOF' ; QUERY : 'QUERY' ; TYPEOF : 'TYPEOF' ; ABS : 'ABS' ; USEDIN : 'USEDIN' ; IfcType : '\'' Version ('.'Identifier)+ '\'' ; Version : 'IFC' Integer ; fragment Digit : '0'..'9' ; Integer : Digit+; LP : '(' ; RP : ')' ; LB : '{' ; RB : '}' ; COLON : ':' ; PIPE : '|' ; // Operators NOT : 'NOT'; EQ : '=' ; GT : '>' ; LT : '<' ; GTE : '>=' ; LTE : '<=' ; NEQ : '<>' ; MUL : '*' ; DIV : '/' ; ADD : '+' ; SUB : '-' ; DEF : ':=' ; INIT : '<*' ; Float : Digit+ '.' Digit* | '.' Digit+ ; SetAccessor : Identifier '[' (Integer|Identifier) ']' | SELF '[' (Integer|Identifier) ']' ; Path : (SELF'\\')? (Identifier|PropertyAccessor)('\\'(Identifier|PropertyAccessor))+ ; PropertyAccessor : (SetAccessor|Identifier)('.'(SetAccessor|Identifier))+ ; Identifier : IdLetter (IdLetter | Digit)* | '\'' (IdLetter|Digit) (IdLetter|Digit|' ')* '\'' ; fragment IdLetter : CapitalLetter | LowercaseLetter | '_' | '-' ; fragment CapitalLetter : 'A'..'Z' ; fragment LowercaseLetter : 'a'..'z' ; Rules : 'RULE ' Identifier .*? 'END_RULE;' -> skip ; Functions : 'FUNCTION ' Identifier .*? 'END_FUNCTION;' -> skip ; WS : [ \t\r\n\u000c]+ -> skip ; Comments : '(*' .*? '*)' -> skip ;
grammar Express; schemaDeclaration : SCHEMA Version ';' typeDeclaration* entityDeclaration* functionDeclaration* END_SCHEMA';' EOF; typeDeclaration : TYPE typeName EQ (valueType|enumeration|select) FIXED? ';' typeDeclarationBody? END_TYPE ';' ; typeName : Identifier ; valueType : BOOLEAN | INTEGER | LOGICAL | REAL | STRING | STRING_SIZED | setDeclaration | listDeclaration | arrayDeclaration | Identifier ; setDeclaration : SET '[' Integer COLON (setSize|'?') ']' OF valueType (FOR Identifier)? ; setSize : Integer ; listDeclaration : LIST '[' Integer COLON (listSize|'?') ']' OF valueType ; listSize : Integer ; arrayDeclaration : ARRAY '[' Integer COLON (arraySize|'?') ']' OF valueType ; arraySize : Integer ; enumeration : ENUMERATION OF LP enumIdList RP ; enumIdList : idList ; select : SELECT LP selectIdList RP ; selectIdList : idList ; idList : Identifier(','Identifier)* | IfcType(','IfcType)* ; typeDeclarationBody : ruleDeclaration ; ruleDeclaration : 'WHERE' rule+ ; rule : Identifier COLON expr ';' ; expr : funcCallExpr | boolExpr | LB boolExpr RB ; funcCallExpr : (EXISTS|SIZEOF|TYPEOF|QUERY|ABS|USEDIN|Identifier)'(' funcParameters ')' ; funcParameters : atom(','atom)* | formulaExpr ; queryExpr : Identifier INIT (Identifier|Path|PropertyAccessor|funcCallExpr) PIPE boolExpr ; boolExpr : atom((LT|GT|LTE|GTE|EQ|NEQ|AND|OR)atom)* | (IfcType|Path|PropertyAccessor|Identifier|SELF) IN (funcCallExpr|'['idList']') ; formulaExpr : atom((ADD|SUB|MUL|DIV)atom)+ ; atom : SELF | IfcType | Integer | Float | Identifier | Path | PropertyAccessor | SetAccessor | '[' idList ']' | queryExpr | funcCallExpr | '('NOT? expr ')' | NOT?'('expr')' ; selfProperty : SELF '.' Identifier ; entityDeclaration : ENTITY entityName ';'? entityDeclarationBody END_ENTITY ';' ; entityName : Identifier ; entityDeclarationBody : attribute* supertypeDeclaration? subtypeDeclaration? inverseDeclaration? deriveDeclaration? ruleDeclaration? uniqueDeclaration? ; supertypeDeclaration : ABSTRACT? SUPERTYPE OF LP (oneOf | supertypeName) RP ';'? attribute* ; supertypeName : Identifier ; subtypeDeclaration : SUBTYPE OF LP (oneOf | subtypeName) RP ';' attribute* ; subtypeName : Identifier ; attribute : attributeName COLON OPTIONAL? valueType definition? ';' ; attributeName : Identifier ; definition : DEF expr; oneOf : ONEOF LP idList RP ; inverseDeclaration : INVERSE attribute+ ; deriveDeclaration : DERIVE attribute+ ; uniqueDeclaration : UNIQUE uniqueStatement+ ; uniqueStatement : Identifier COLON .*? ';' ; functionDeclaration : 'FUNCTION' functionDeclarationBody 'END_FUNCTION' ; functionDeclarationBody : .*? ; // Lexer //Base Types BOOLEAN : 'BOOLEAN' ; INTEGER : 'INTEGER' ; LIST : 'LIST'; LOGICAL : 'LOGICAL' ; REAL : 'REAL' ; SET : 'SET' ; STRING_SIZED : 'STRING(' Integer ')'; FIXED : 'FIXED'; STRING : 'STRING' ; ARRAY : 'ARRAY' ; // Keywords ABSTRACT : 'ABSTRACT' ; AND : 'AND' ; DERIVE : 'DERIVE' ; ENTITY : 'ENTITY' ; END_ENTITY : 'END_ENTITY' ; ENUMERATION : 'ENUMERATION' ; FOR : 'FOR' ; IN : 'IN' ; INVERSE : 'INVERSE'; OF : 'OF'; ONEOF : 'ONEOF' ; OPTIONAL : 'OPTIONAL' ; OR : 'OR' ; SCHEMA : 'SCHEMA' ; END_SCHEMA : 'END_SCHEMA' ; SELECT : 'SELECT' ; SELF : 'SELF' ; SUBTYPE : 'SUBTYPE' ; SUPERTYPE : 'SUPERTYPE' ; TYPE : 'TYPE' ; END_TYPE : 'END_TYPE' ; UNIQUE : 'UNIQUE' ; //WHERE : 'WHERE' ; // Functions EXISTS : 'EXISTS' ; SIZEOF : 'SIZEOF' ; QUERY : 'QUERY' ; TYPEOF : 'TYPEOF' ; ABS : 'ABS' ; USEDIN : 'USEDIN' ; IfcType : '\'' Version ('.'Identifier)+ '\'' ; Version : 'IFC' Integer ; fragment Digit : '0'..'9' ; Integer : Digit+; LP : '(' ; RP : ')' ; LB : '{' ; RB : '}' ; COLON : ':' ; PIPE : '|' ; // Operators NOT : 'NOT'; EQ : '=' ; GT : '>' ; LT : '<' ; GTE : '>=' ; LTE : '<=' ; NEQ : '<>' ; MUL : '*' ; DIV : '/' ; ADD : '+' ; SUB : '-' ; DEF : ':=' ; INIT : '<*' ; Float : Digit+ '.' Digit* | '.' Digit+ ; SetAccessor : Identifier '[' (Integer|Identifier) ']' | SELF '[' (Integer|Identifier) ']' ; Path : (SELF'\\')? (Identifier|PropertyAccessor)('\\'(Identifier|PropertyAccessor))+ ; PropertyAccessor : (SetAccessor|Identifier)('.'(SetAccessor|Identifier))+ ; Identifier : IdLetter (IdLetter | Digit)* | '\'' (IdLetter|Digit) (IdLetter|Digit|' ')* '\'' ; fragment IdLetter : CapitalLetter | LowercaseLetter | '_' | '-' ; fragment CapitalLetter : 'A'..'Z' ; fragment LowercaseLetter : 'a'..'z' ; Rules : 'RULE ' Identifier .*? 'END_RULE;' -> skip ; Functions : 'FUNCTION ' Identifier .*? 'END_FUNCTION;' -> skip ; WS : [ \t\r\n\u000c]+ -> skip ; Comments : '(*' .*? '*)' -> skip ;
Remove underscores from rule names.
Remove underscores from rule names.
ANTLR
mit
ikeough/IFC-gen,ikeough/IFC-gen,ikeough/IFC-gen
766e29ceef19c0f915dfc706fe368e60e77a682c
erlang/Erlang.g4
erlang/Erlang.g4
/* [The "BSD licence"] Copyright (c) 2013 Terence Parr All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES */ // An ANTLR4 Grammar of Erlang R16B01 made by Pierre Fenoll from // https://github.com/erlang/otp/blob/maint/lib/stdlib/src/erl_parse.yrl grammar Erlang; forms : form+ EOF ; form : (attribute | function_ | ruleClauses) '.' ; /// Tokens fragment DIGIT : [0-9] ; fragment LOWERCASE : [a-z] | '\u00df'..'\u00f6' | '\u00f8'..'\u00ff' ; fragment UPPERCASE : [A-Z] | '\u00c0'..'\u00d6' | '\u00d8'..'\u00de' ; tokAtom : TokAtom ; TokAtom : LOWERCASE (DIGIT | LOWERCASE | UPPERCASE | '_' | '@')* | '\'' ( '\\' (~'\\'|'\\') | ~[\\'] )* '\'' ; tokVar : TokVar ; TokVar : (UPPERCASE | '_') (DIGIT | LOWERCASE | UPPERCASE | '_' | '@')* ; tokFloat : TokFloat ; TokFloat : '-'? DIGIT+ '.' DIGIT+ ([Ee] [+-]? DIGIT+)? ; tokInteger : TokInteger ; TokInteger : '-'? DIGIT+ ('#' (DIGIT | [a-zA-Z])+)? ; tokChar : TokChar ; TokChar : '$' ('\\'? ~[\r\n] | '\\' DIGIT DIGIT DIGIT) ; tokString : TokString ; TokString : '"' ( '\\' (~'\\'|'\\') | ~[\\"] )* '"' ; // antlr4 would not accept spec as an Atom otherwise. AttrName : '-' ('spec' | 'callback') ; Comment : '%' ~[\r\n]* '\r'? '\n' -> skip ; WS : [\u0000-\u0020\u0080-\u00a0]+ -> skip ; attribute : '-' tokAtom attrVal | '-' tokAtom typedAttrVal | '-' tokAtom '(' typedAttrVal ')' | AttrName typeSpec ; /// Typing typeSpec : specFun typeSigs | '(' specFun typeSigs ')' ; specFun : tokAtom | tokAtom ':' tokAtom // The following two are retained only for backwards compatibility; // they are not part of the EEP syntax and should be removed. | tokAtom '/' tokInteger '::' | tokAtom ':' tokAtom '/' tokInteger '::' ; typedAttrVal : expr ',' typedRecordFields | expr '::' topType ; typedRecordFields : '{' typedExprs '}' ; typedExprs : typedExpr | typedExpr ',' typedExprs | expr ',' typedExprs | typedExpr ',' exprs ; typedExpr : expr '::' topType ; typeSigs : typeSig (';' typeSig)* ; typeSig : funType ('when' typeGuards)? ; typeGuards : typeGuard (',' typeGuard)* ; typeGuard : tokAtom '(' topTypes ')' | tokVar '::' topType ; topTypes : topType (',' topType)* ; topType : (tokVar '::')? topType100 ; topType100 : type200 ('|' topType100)? ; type200 : type300 ('..' type300)? ; type300 : type300 addOp type400 | type400 ; type400 : type400 multOp type500 | type500 ; type500 : prefixOp? type ; type : '(' topType ')' | tokVar | tokAtom | tokAtom '(' ')' | tokAtom '(' topTypes ')' | tokAtom ':' tokAtom '(' ')' | tokAtom ':' tokAtom '(' topTypes ')' | '[' ']' | '[' topType ']' | '[' topType ',' '...' ']' | '{' '}' | '{' topTypes '}' | '#' tokAtom '{' '}' | '#' tokAtom '{' fieldTypes '}' | binaryType | tokInteger | 'fun' '(' ')' | 'fun' '(' funType100 ')' ; funType100 : '(' '...' ')' '->' topType | funType ; funType : '(' (topTypes)? ')' '->' topType ; fieldTypes : fieldType (',' fieldType)* ; fieldType : tokAtom '::' topType ; binaryType : '<<' '>>' | '<<' binBaseType '>>' | '<<' binUnitType '>>' | '<<' binBaseType ',' binUnitType '>>' ; binBaseType : tokVar ':' type ; binUnitType : tokVar ':' tokVar '*' type ; /// Exprs attrVal : expr | '(' expr ')' | expr ',' exprs | '(' expr ',' exprs ')' ; function_ : functionClause (';' functionClause)* ; functionClause : tokAtom clauseArgs clauseGuard clauseBody ; clauseArgs : argumentList ; clauseGuard : ('when' guard)? ; clauseBody : '->' exprs ; expr : 'catch' expr | expr100 ; expr100 : expr150 (('=' | '!') expr150)* ; expr150 : expr160 ('orelse' expr160)* ; expr160 : expr200 ('andalso' expr200)* ; expr200 : expr300 (compOp expr300)? ; expr300 : expr400 (listOp expr400)* ; expr400 : expr500 (addOp expr500)* ; expr500 : expr600 (multOp expr600)* ; expr600 : prefixOp? expr700 ; expr700 : functionCall | recordExpr | expr800 ; expr800 : exprMax (':' exprMax)? ; exprMax : tokVar | atomic | list | binary | listComprehension | binaryComprehension | tuple // | struct | '(' expr ')' | 'begin' exprs 'end' | ifExpr | caseExpr | receiveExpr | funExpr | tryExpr ; list : '[' ']' | '[' expr tail ; tail : ']' | '|' expr ']' | ',' expr tail ; binary : '<<' '>>' | '<<' binElements '>>' ; binElements : binElement (',' binElement)* ; binElement : bitExpr optBitSizeExpr optBitTypeList ; bitExpr : prefixOp? exprMax ; optBitSizeExpr : (':' bitSizeExpr)? ; optBitTypeList : ('/' bitTypeList)? ; bitTypeList : bitType ('-' bitType)* ; bitType : tokAtom (':' tokInteger)? ; bitSizeExpr : exprMax ; listComprehension : '[' expr '||' lcExprs ']' ; binaryComprehension : '<<' binary '||' lcExprs '>>' ; lcExprs : lcExpr (',' lcExpr)* ; lcExpr : expr | expr '<-' expr | binary '<=' expr ; tuple : '{' exprs? '}' ; /* struct : tokAtom tuple ; */ /* N.B. This is called from expr700. N.B. Field names are returned as the complete object, even if they are always atoms for the moment, this might change in the future. */ recordExpr : exprMax? '#' tokAtom ('.' tokAtom | recordTuple) | recordExpr '#' tokAtom ('.' tokAtom | recordTuple) ; recordTuple : '{' recordFields? '}' ; recordFields : recordField (',' recordField)* ; recordField : (tokVar | tokAtom) '=' expr ; /* N.B. This is called from expr700. */ functionCall : expr800 argumentList ; ifExpr : 'if' ifClauses 'end' ; ifClauses : ifClause (';' ifClause)* ; ifClause : guard clauseBody ; caseExpr : 'case' expr 'of' crClauses 'end' ; crClauses : crClause (';' crClause)* ; crClause : expr clauseGuard clauseBody ; receiveExpr : 'receive' crClauses 'end' | 'receive' 'after' expr clauseBody 'end' | 'receive' crClauses 'after' expr clauseBody 'end' ; funExpr : 'fun' tokAtom '/' tokInteger | 'fun' atomOrVar ':' atomOrVar '/' integerOrVar | 'fun' funClauses 'end' ; atomOrVar : tokAtom | tokVar ; integerOrVar : tokInteger | tokVar ; funClauses : funClause (';' funClause)* ; funClause : argumentList clauseGuard clauseBody ; tryExpr : 'try' exprs ('of' crClauses)? tryCatch ; tryCatch : 'catch' tryClauses 'end' | 'catch' tryClauses 'after' exprs 'end' | 'after' exprs 'end' ; tryClauses : tryClause (';' tryClause)* ; tryClause : (atomOrVar ':')? expr clauseGuard clauseBody ; argumentList : '(' exprs? ')' ; exprs : expr (',' expr)* ; guard : exprs (';' exprs)* ; atomic : tokChar | tokInteger | tokFloat | tokAtom | (tokString)+ ; prefixOp : '+' | '-' | 'bnot' | 'not' ; multOp : '/' | '*' | 'div' | 'rem' | 'band' | 'and' ; addOp : '+' | '-' | 'bor' | 'bxor' | 'bsl' | 'bsr' | 'or' | 'xor' ; listOp : '++' | '--' ; compOp : '==' | '/=' | '=<' | '<' | '>=' | '>' | '=:=' | '=/=' ; ruleClauses : ruleClause (';' ruleClause)* ; ruleClause : tokAtom clauseArgs clauseGuard ruleBody ; ruleBody : ':-' lcExprs ;
/* [The "BSD licence"] Copyright (c) 2013 Terence Parr All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES */ // An ANTLR4 Grammar of Erlang R16B01 made by Pierre Fenoll from // https://github.com/erlang/otp/blob/maint/lib/stdlib/src/erl_parse.yrl // Update to Erlang/OTP 23.3 grammar Erlang; forms : form+ EOF ; form : (attribute | function_) '.' ; /// Tokens fragment DIGIT : [0-9] ; fragment LOWERCASE : [a-z] | '\u00df'..'\u00f6' | '\u00f8'..'\u00ff' ; fragment UPPERCASE : [A-Z] | '\u00c0'..'\u00d6' | '\u00d8'..'\u00de' ; tokAtom : TokAtom ; TokAtom : LOWERCASE (DIGIT | LOWERCASE | UPPERCASE | '_' | '@')* | '\'' ( '\\' (~'\\'|'\\') | ~[\\'] )* '\'' ; tokVar : TokVar ; TokVar : (UPPERCASE | '_') (DIGIT | LOWERCASE | UPPERCASE | '_' | '@')* ; tokFloat : TokFloat ; TokFloat : '-'? DIGIT+ '.' DIGIT+ ([Ee] [+-]? DIGIT+)? ; tokInteger : TokInteger ; TokInteger : '-'? DIGIT+ ('#' (DIGIT | [a-zA-Z])+)? ; tokChar : TokChar ; TokChar : '$' ('\\'? ~[\r\n] | '\\' DIGIT DIGIT DIGIT) ; tokString : TokString ; TokString : '"' ( '\\' (~'\\'|'\\') | ~[\\"] )* '"' ; // antlr4 would not accept spec as an Atom otherwise. AttrName : '-' ('spec' | 'callback') ; Comment : '%' ~[\r\n]* '\r'? '\n' -> skip ; WS : [\u0000-\u0020\u0080-\u00a0]+ -> skip ; attribute : '-' tokAtom attrVal | '-' tokAtom typedAttrVal | '-' tokAtom '(' typedAttrVal ')' | AttrName typeSpec ; /// Typing typeSpec : specFun typeSigs | '(' specFun typeSigs ')' ; specFun : tokAtom | tokAtom ':' tokAtom ; typedAttrVal : expr ',' typedRecordFields | expr '::' topType ; typedRecordFields : '{' typedExprs '}' ; typedExprs : typedExpr | typedExpr ',' typedExprs | expr ',' typedExprs | typedExpr ',' exprs ; typedExpr : expr '::' topType ; typeSigs : typeSig (';' typeSig)* ; typeSig : funType ('when' typeGuards)? ; typeGuards : typeGuard (',' typeGuard)* ; typeGuard : tokAtom '(' topTypes ')' | tokVar '::' topType ; topTypes : topType (',' topType)* ; topType : (tokVar '::')? topType100 ; topType100 : type200 ('|' topType100)? ; type200 : type300 ('..' type300)? ; type300 : type300 addOp type400 | type400 ; type400 : type400 multOp type500 | type500 ; type500 : prefixOp? type ; type : '(' topType ')' | tokVar | tokAtom | tokAtom '(' ')' | tokAtom '(' topTypes ')' | tokAtom ':' tokAtom '(' ')' | tokAtom ':' tokAtom '(' topTypes ')' | '[' ']' | '[' topType ']' | '[' topType ',' '...' ']' | '#' '{' '}' | '#' '{' mapPairTypes '}' | '{' '}' | '{' topTypes '}' | '#' tokAtom '{' '}' | '#' tokAtom '{' fieldTypes '}' | binaryType | tokInteger | tokChar | 'fun' '(' ')' | 'fun' '(' funType100 ')' ; funType100 : '(' '...' ')' '->' topType | funType ; funType : '(' (topTypes)? ')' '->' topType ; mapPairTypes : mapPairType (',' mapPairType)* ; mapPairType : topType ('=>' | ':=') topType ; fieldTypes : fieldType (',' fieldType)* ; fieldType : tokAtom '::' topType ; binaryType : '<<' '>>' | '<<' binBaseType '>>' | '<<' binUnitType '>>' | '<<' binBaseType ',' binUnitType '>>' ; binBaseType : tokVar ':' type ; binUnitType : tokVar ':' tokVar '*' type ; /// Exprs attrVal : expr | '(' expr ')' | expr ',' exprs | '(' expr ',' exprs ')' ; function_ : functionClause (';' functionClause)* ; functionClause : tokAtom clauseArgs clauseGuard clauseBody ; clauseArgs : patArgumentList ; clauseGuard : ('when' guard)? ; clauseBody : '->' exprs ; expr : 'catch' expr | expr100 ; expr100 : expr150 (('=' | '!') expr150)* ; expr150 : expr160 ('orelse' expr160)* ; expr160 : expr200 ('andalso' expr200)* ; expr200 : expr300 (compOp expr300)? ; expr300 : expr400 (listOp expr400)* ; expr400 : expr500 (addOp expr500)* ; expr500 : expr600 (multOp expr600)* ; expr600 : prefixOp expr600 | expr650 ; expr650 : mapExpr | expr700 ; expr700 : functionCall | recordExpr | expr800 ; expr800 : exprMax (':' exprMax)? ; exprMax : tokVar | atomic | list | binary | listComprehension | binaryComprehension | tuple | '(' expr ')' | 'begin' exprs 'end' | ifExpr | caseExpr | receiveExpr | funExpr | tryExpr ; patExpr : patExpr200 ('=' patExpr)? ; patExpr200 : patExpr300 (compOp patExpr300)? ; patExpr300 : patExpr400 (listOp patExpr300)? ; patExpr400 : patExpr400 addOp patExpr500 | patExpr500 ; patExpr500 : patExpr500 multOp patExpr600 | patExpr600 ; patExpr600 : prefixOp patExpr600 | patExpr650 ; patExpr650 : mapPatExpr | patExpr700 ; patExpr700 : recordPatExpr | patExpr800 ; patExpr800 : patExprMax ; patExprMax : tokVar | atomic | list | binary | tuple | '(' patExpr ')' ; mapPatExpr : patExprMax? '#' mapTuple | mapPatExpr '#' mapTuple ; recordPatExpr : '#' tokAtom ('.' tokAtom | recordTuple) ; list : '[' ']' | '[' expr tail ; tail : ']' | '|' expr ']' | ',' expr tail ; binary : '<<' '>>' | '<<' binElements '>>' ; binElements : binElement (',' binElement)* ; binElement : bitExpr optBitSizeExpr optBitTypeList ; bitExpr : prefixOp? exprMax ; optBitSizeExpr : (':' bitSizeExpr)? ; optBitTypeList : ('/' bitTypeList)? ; bitTypeList : bitType ('-' bitType)* ; bitType : tokAtom (':' tokInteger)? ; bitSizeExpr : exprMax ; listComprehension : '[' expr '||' lcExprs ']' ; binaryComprehension : '<<' exprMax '||' lcExprs '>>' ; lcExprs : lcExpr (',' lcExpr)* ; lcExpr : expr | expr '<-' expr | binary '<=' expr ; tuple : '{' exprs? '}' ; mapExpr : exprMax? '#' mapTuple | mapExpr '#' mapTuple ; mapTuple : '{' (mapField (',' mapField)*)? '}' ; mapField : mapFieldAssoc | mapFieldExact ; mapFieldAssoc : mapKey '=>' expr ; mapFieldExact : mapKey ':=' expr ; mapKey : expr ; /* struct : tokAtom tuple ; */ /* N.B. This is called from expr700. N.B. Field names are returned as the complete object, even if they are always atoms for the moment, this might change in the future. */ recordExpr : exprMax? '#' tokAtom ('.' tokAtom | recordTuple) | recordExpr '#' tokAtom ('.' tokAtom | recordTuple) ; recordTuple : '{' recordFields? '}' ; recordFields : recordField (',' recordField)* ; recordField : (tokVar | tokAtom) '=' expr ; /* N.B. This is called from expr700. */ functionCall : expr800 argumentList ; ifExpr : 'if' ifClauses 'end' ; ifClauses : ifClause (';' ifClause)* ; ifClause : guard clauseBody ; caseExpr : 'case' expr 'of' crClauses 'end' ; crClauses : crClause (';' crClause)* ; crClause : expr clauseGuard clauseBody ; receiveExpr : 'receive' crClauses 'end' | 'receive' 'after' expr clauseBody 'end' | 'receive' crClauses 'after' expr clauseBody 'end' ; funExpr : 'fun' tokAtom '/' tokInteger | 'fun' atomOrVar ':' atomOrVar '/' integerOrVar | 'fun' funClauses 'end' ; atomOrVar : tokAtom | tokVar ; integerOrVar : tokInteger | tokVar ; funClauses : funClause (';' funClause)* ; funClause : patArgumentList clauseGuard clauseBody | tokVar patArgumentList clauseGuard clauseBody ; tryExpr : 'try' exprs ('of' crClauses)? tryCatch ; tryCatch : 'catch' tryClauses 'end' | 'catch' tryClauses 'after' exprs 'end' | 'after' exprs 'end' ; tryClauses : tryClause (';' tryClause)* ; tryClause : expr clauseGuard clauseBody | (atomOrVar ':')? patExpr tryOptStackTrace clauseGuard clauseBody ; tryOptStackTrace : (':' tokVar)? ; argumentList : '(' exprs? ')' ; patArgumentList : '(' patExprs? ')' ; exprs : expr (',' expr)* ; patExprs : patExpr (',' patExpr)* ; guard : exprs (';' exprs)* ; atomic : tokChar | tokInteger | tokFloat | tokAtom | (tokString)+ ; prefixOp : '+' | '-' | 'bnot' | 'not' ; multOp : '/' | '*' | 'div' | 'rem' | 'band' | 'and' ; addOp : '+' | '-' | 'bor' | 'bxor' | 'bsl' | 'bsr' | 'or' | 'xor' ; listOp : '++' | '--' ; compOp : '==' | '/=' | '=<' | '<' | '>=' | '>' | '=:=' | '=/=' ;
Update Erlang grammar to OTP 23.3
Update Erlang grammar to OTP 23.3
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
962d8b658b4d4209b67f38064b1378e0470187c1
sharding-jdbc-ddl-parser/src/main/resources/io/shardingsphere/parser/antlr/mysql/MySQLDDL.g4
sharding-jdbc-ddl-parser/src/main/resources/io/shardingsphere/parser/antlr/mysql/MySQLDDL.g4
grammar MySQLDDL; import MySQLBase,MySQLKeyword,DDLBase,SQLBase,Keyword,Symbol; @header{ package io.shardingsphere.parser.antlr.mysql; } createTableOptions: createTableBasic |createTableSelect |createTableLike ; createTableBasic: ; createDefinition: columnNameAndDefinition (constraintDefinition|indexDefinition) ; createTableSelect: ; createTableLike: ; alterSpecifications: alterSpecification (COMMA alterSpecification)* ; alterSpecification: tableOptions | ADD COLUMN? (singleColumn | multiColumn) | ADD indexDefinition | ADD constraintDefinition | ALGORITHM EQ_OR_ASSIGN? (DEFAULT|INPLACE|COPY) | ALTER COLUMN? columnName (SET DEFAULT | DROP DEFAULT) | CHANGE COLUMN? columnName columnName columnDefinition (FIRST|AFTER columnName)? | DEFAULT? CHARACTER SET EQ_OR_ASSIGN? charsetName (COLLATE EQ_OR_ASSIGN? collationName)? | CONVERT TO CHARACTER SET charsetName (COLLATE collationName)? | (DISABLE|ENABLE) KEYS | (DISCARD|IMPORT_) TABLESPACE | DROP COLUMN? columnName | DROP (INDEX|KEY) indexName | DROP PRIMARY KEY | DROP FOREIGN KEY fkSymbol | FORCE | LOCK EQ_OR_ASSIGN? (DEFAULT|NONE|SHARED|EXCLUSIVE) | MODIFY COLUMN? columnName columnDefinition (FIRST | AFTER columnName)? | (ORDER BY columnName (COMMA columnName)* )+ | RENAME (INDEX|KEY) indexName TO indexName | RENAME (TO|AS)? tableName | (WITHOUT|WITH) VALIDATION | ADD PARTITION partitionDefinitions | DROP PARTITION partitionNames | DISCARD PARTITION (partitionNames | ALL) TABLESPACE | IMPORT_ PARTITION (partitionNames | ALL) TABLESPACE | TRUNCATE PARTITION (partitionNames | ALL) | COALESCE PARTITION INT | REORGANIZE PARTITION partitionNames INTO partitionDefinitions | EXCHANGE PARTITION partitionName WITH TABLE tableName ((WITH|WITHOUT) VALIDATION)? | ANALYZE PARTITION (partitionNames | ALL) | CHECK PARTITION (partitionNames | ALL) | OPTIMIZE PARTITION (partitionNames | ALL) | REBUILD PARTITION (partitionNames | ALL) | REPAIR PARTITION (partitionNames | ALL) | REMOVE PARTITIONING | UPGRADE PARTITIONING ; indexDefinition: (((FULLTEXT | SPATIAL) indexAndKey?)|indexAndKey) indexDefOption ; indexAndKey: INDEX|KEY ; indexDefOption: indexName? indexType? keyParts indexOption? ; singleColumn: columnNameAndDefinition (FIRST | AFTER columnName)? ; multiColumn: LEFT_PAREN columnNameAndDefinition (COMMA columnNameAndDefinition)* RIGHT_PAREN ; constraintDefinition: (CONSTRAINT symbol?)? (primaryKeyOption | uniqueOption | foreignKeyOption) ; primaryKeyOption: PRIMARY KEY indexType? keyParts indexOption? ; uniqueOption: UNIQUE (INDEX|KEY)? indexName? indexType? keyParts indexOption? ; foreignKeyOption: FOREIGN KEY indexName? LEFT_PAREN columnName (COMMA columnName)* RIGHT_PAREN referenceDefinition ; tableOptions: tableOption (COMMA tableOption)* ; tableOption: AUTO_INCREMENT EQ_OR_ASSIGN? INT | AVG_ROW_LENGTH EQ_OR_ASSIGN? INT | DEFAULT? CHARACTER SET EQ_OR_ASSIGN? charsetName | CHECKSUM EQ_OR_ASSIGN? INT | DEFAULT? COLLATE EQ_OR_ASSIGN? collationName | COMMENT EQ_OR_ASSIGN? STRING | COMPRESSION EQ_OR_ASSIGN? (ZLIB|'LZ4'|NONE) | CONNECTION EQ_OR_ASSIGN? STRING | (DATA|INDEX) DIRECTORY EQ_OR_ASSIGN? STRING | DELAY_KEY_WRITE EQ_OR_ASSIGN? INT | ENCRYPTION EQ_OR_ASSIGN? STRING | ENGINE EQ_OR_ASSIGN? engineName | INSERT_METHOD EQ_OR_ASSIGN? ( NO | FIRST | LAST ) | KEY_BLOCK_SIZE EQ_OR_ASSIGN? INT | MAX_ROWS EQ_OR_ASSIGN? INT | MIN_ROWS EQ_OR_ASSIGN? INT | PACK_KEYS EQ_OR_ASSIGN? (INT | DEFAULT) | PASSWORD EQ_OR_ASSIGN? STRING | ROW_FORMAT EQ_OR_ASSIGN? (DEFAULT|DYNAMIC|FIXED|COMPRESSED|REDUNDANT|COMPACT) | STATS_AUTO_RECALC EQ_OR_ASSIGN? (DEFAULT|INT) | STATS_PERSISTENT EQ_OR_ASSIGN? (DEFAULT|INT) | STATS_SAMPLE_PAGES EQ_OR_ASSIGN? INT | TABLESPACE tablespaceName (STORAGE (DISK|MEMORY|DEFAULT))? | UNION EQ_OR_ASSIGN? ; columnNameAndDefinition: columnName columnDefinition ; columnDefinition: dataType (dataTypeOption | dataTypeGenerated) ; dataType: simpleExpr ; dataTypeOption: (NOT? NULL)? (DEFAULT defaultValue)? AUTO_INCREMENT? (UNIQUE KEY?)? (PRIMARY? KEY)? (COMMENT STRING)? (COLUMN_FORMAT (FIXED|DYNAMIC|DEFAULT))? (STORAGE (DISK|MEMORY|DEFAULT))? (referenceDefinition)? ; dataTypeGenerated: (GENERATED ALWAYS)? AS LEFT_PAREN expr RIGHT_PAREN (VIRTUAL | STORED)? (NOT NULL | NULL)? (UNIQUE (KEY)?)? ((PRIMARY)? KEY)? (COMMENT STRING)? ; referenceDefinition: REFERENCES tableName keyParts (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON DELETE referenceOption)? (ON UPDATE referenceOption)? ; referenceOption: RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT ; symbol: ID ; fkSymbol: ID ; keyParts: LEFT_PAREN keyPart (COMMA keyPart)* RIGHT_PAREN ; charsetName: ; defaultValue: ; keyPart: columnName (LEFT_PAREN NUMBER RIGHT_PAREN)? (ASC | DESC)? ; indexName: ID ; indexType: USING (BTREE | HASH) ; indexOption: KEY_BLOCK_SIZE EQ_OR_ASSIGN? value | indexType | WITH PARSER parserName | COMMENT STRING ; parserName: ID ; engineName: ID ; partitionNames: partitionName (COMMA partitionName)* ; partitionName: ID ; partitionOptions: PARTITION BY (linearPartition | rangeOrListPartition) (PARTITIONS INT)? (SUBPARTITION BY linearPartition (SUBPARTITIONS INT)? )? partitionDefinitions? ; linearPartition: LINEAR? (HASH exprWithParen |keyColumnList) ; keyColumnList: KEY (ALGORITHM EQ_OR_ASSIGN INT)? columnList ; exprWithParen: LEFT_PAREN expr RIGHT_PAREN ; rangeOrListPartition: (RANGE | LIST ) exprOrColumns ; exprOrColumns: LEFT_PAREN expr RIGHT_PAREN | COLUMNS columnList ; partitionDefinitions: LEFT_PAREN partitionDefinition (COMMA partitionDefinition)* RIGHT_PAREN ; partitionDefinition: PARTITION partitionName (VALUES (lessThanPartition|IN valueListWithParen))? (STORAGE? ENGINE EQ_OR_ASSIGN? engineName)? (COMMENT EQ_OR_ASSIGN? STRING )? (DATA DIRECTORY EQ_OR_ASSIGN? STRING)? (INDEX DIRECTORY EQ_OR_ASSIGN? STRING)? (MAX_ROWS EQ_OR_ASSIGN? INT)? (MIN_ROWS EQ_OR_ASSIGN? INT)? (TABLESPACE EQ_OR_ASSIGN? tablespaceName)? (subpartitionDefinition (COMMA subpartitionDefinition)*)? ; lessThanPartition: LESS THAN ((LEFT_PAREN (expr | valueList) RIGHT_PAREN) | MAXVALUE) ; subpartitionDefinition: SUBPARTITION partitionName ((STORAGE)? ENGINE EQ_OR_ASSIGN? engineName)? (COMMENT EQ_OR_ASSIGN? STRING )? (DATA DIRECTORY EQ_OR_ASSIGN? STRING)? (INDEX DIRECTORY EQ_OR_ASSIGN? STRING)? (MAX_ROWS EQ_OR_ASSIGN? INT)? (MIN_ROWS EQ_OR_ASSIGN? INT)? (TABLESPACE EQ_OR_ASSIGN? tablespaceName)? ; tablespaceName: ID ; collationName: ID ;
grammar MySQLDDL; import MySQLBase,MySQLKeyword,DDLBase,SQLBase,Keyword,Symbol; @header{ package io.shardingsphere.parser.antlr.mysql; } createTableOptions: createTableBasic |createTableSelect |createTableLike ; createTableBasic: LEFT_PAREN createDefinitions RIGHT_PAREN tableOptions? partitionOptions? ; createDefinitions: createDefinition (COMMA createDefinition)* ; createDefinition: (columnNameAndDefinition) |(constraintDefinition|indexDefinition| checkExpr) ; checkExpr: CHECK exprWithParen ; createTableSelect: LEFT_PAREN createDefinitions RIGHT_PAREN? tableOptions? partitionOptions?? (IGNORE | REPLACE)? AS? ; createTableLike: (likeTable) | LEFT_PAREN likeTable RIGHT_PAREN ; likeTable: LIKE tableName ; alterSpecifications: alterSpecification (COMMA alterSpecification)* ; alterSpecification: (tableOptions) | ADD COLUMN? (singleColumn | multiColumn) | ADD indexDefinition | ADD constraintDefinition | ALGORITHM EQ_OR_ASSIGN? (DEFAULT|INPLACE|COPY) | ALTER COLUMN? columnName (SET DEFAULT | DROP DEFAULT) | CHANGE COLUMN? columnName columnName columnDefinition (FIRST|AFTER columnName)? | DEFAULT? characterAndCollateWithEqual | CONVERT TO characterAndCollate | (DISABLE|ENABLE) KEYS | (DISCARD|IMPORT_) TABLESPACE | DROP COLUMN? columnName | DROP (INDEX|KEY) indexName | DROP PRIMARY KEY | DROP FOREIGN KEY fkSymbol | FORCE | LOCK EQ_OR_ASSIGN? (DEFAULT|NONE|SHARED|EXCLUSIVE) | MODIFY COLUMN? columnName columnDefinition (FIRST | AFTER columnName)? | (ORDER BY columnName (COMMA columnName)* )+ | RENAME (INDEX|KEY) indexName TO indexName | RENAME (TO|AS)? tableName | (WITHOUT|WITH) VALIDATION | ADD PARTITION partitionDefinitions | DROP PARTITION partitionNames | DISCARD PARTITION (partitionNames | ALL) TABLESPACE | IMPORT_ PARTITION (partitionNames | ALL) TABLESPACE | TRUNCATE PARTITION (partitionNames | ALL) | COALESCE PARTITION NUMBER | REORGANIZE PARTITION partitionNames INTO partitionDefinitions | EXCHANGE PARTITION partitionName WITH TABLE tableName ((WITH|WITHOUT) VALIDATION)? | ANALYZE PARTITION (partitionNames | ALL) | CHECK PARTITION (partitionNames | ALL) | OPTIMIZE PARTITION (partitionNames | ALL) | REBUILD PARTITION (partitionNames | ALL) | REPAIR PARTITION (partitionNames | ALL) | REMOVE PARTITIONING | UPGRADE PARTITIONING ; indexDefinition: (((FULLTEXT | SPATIAL) indexAndKey?)|indexAndKey) indexDefOption ; indexAndKey: INDEX|KEY ; indexDefOption: indexName? indexType? keyParts indexOption? ; singleColumn: columnNameAndDefinition (FIRST | AFTER columnName)? ; multiColumn: LEFT_PAREN columnNameAndDefinition (COMMA columnNameAndDefinition)* RIGHT_PAREN ; constraintDefinition: (CONSTRAINT symbol?)? (primaryKeyOption | uniqueOption | foreignKeyOption) ; primaryKeyOption: PRIMARY KEY indexType? keyParts indexOption? ; uniqueOption: UNIQUE (INDEX|KEY)? indexName? indexType? keyParts indexOption? ; foreignKeyOption: FOREIGN KEY indexName? LEFT_PAREN columnName (COMMA columnName)* RIGHT_PAREN referenceDefinition ; tableOptions: tableOption (COMMA? tableOption)* ; tableOption: AUTO_INCREMENT EQ_OR_ASSIGN? NUMBER |AVG_ROW_LENGTH EQ_OR_ASSIGN? NUMBER | DEFAULT? characterSetWithEqual | CHECKSUM EQ_OR_ASSIGN? NUMBER | DEFAULT? collateClauseWithEqual | COMMENT EQ_OR_ASSIGN? STRING | COMPRESSION EQ_OR_ASSIGN? (ZLIB|'LZ4'|NONE) | CONNECTION EQ_OR_ASSIGN? STRING | (DATA|INDEX) DIRECTORY EQ_OR_ASSIGN? STRING | DELAY_KEY_WRITE EQ_OR_ASSIGN? NUMBER | ENCRYPTION EQ_OR_ASSIGN? STRING | ENGINE EQ_OR_ASSIGN? engineName | INSERT_METHOD EQ_OR_ASSIGN? ( NO | FIRST | LAST ) | KEY_BLOCK_SIZE EQ_OR_ASSIGN? NUMBER | MAX_ROWS EQ_OR_ASSIGN? NUMBER | MIN_ROWS EQ_OR_ASSIGN? NUMBER | PACK_KEYS EQ_OR_ASSIGN? (NUMBER | DEFAULT) | PASSWORD EQ_OR_ASSIGN? STRING | ROW_FORMAT EQ_OR_ASSIGN? (DEFAULT|DYNAMIC|FIXED|COMPRESSED|REDUNDANT|COMPACT) | STATS_AUTO_RECALC EQ_OR_ASSIGN? (DEFAULT|NUMBER) | STATS_PERSISTENT EQ_OR_ASSIGN? (DEFAULT|NUMBER) | STATS_SAMPLE_PAGES EQ_OR_ASSIGN? NUMBER | TABLESPACE tablespaceName (STORAGE (DISK|MEMORY|DEFAULT))? | UNION EQ_OR_ASSIGN? idList ; columnNameAndDefinition: columnName columnDefinition ; columnDefinition: dataType (dataTypeOption | dataTypeGenerated) ; dataType: BIT dataTypeLength? |((TINYINT | SMALLINT | MEDIUMINT | INT | INTEGER| BIGINT) dataTypeLength? (NOT? NULL)? AUTO_INCREMENT? numberTypeSuffix) |((REAL | DOUBLE | FLOAT | DECIMAL | NUMERIC) dataTypeLengthWithPrecision? (NOT? NULL)? AUTO_INCREMENT? numberTypeSuffix ) |((DATE | TIME) (NOT? NULL)? (DEFAULT (STRING | NULL))?) |((timestampType | DATETIME) (NOT? NULL)? (DEFAULT (currentTimestampType | NUMBER | STRING | NULL))? (ON UPDATE currentTimestampType)? ) |(YEAR dataTypeLength? (NOT? NULL)? (DEFAULT (NUMBER | STRING | NULL))?) |((CHAR | VARCHAR) dataTypeLength? (NOT? NULL)? characterSet? collateClause? (DEFAULT (STRING | NULL))?) |((BINARY | VARBINARY) dataTypeLength? (NOT? NULL)? (DEFAULT NUMBER |STRING | NULL)? ) |(TINYBLOB | BLOB | MEDIUMBLOB | LONGBLOB |JSON) (NOT? NULL)? |((TINYTEXT | TEXT | MEDIUMTEXT | LONGTEXT ) (NOT? NULL)? BINARY ? characterSet? collateClause? ) |((ENUM | SET) (LEFT_PAREN STRING (COMMA STRING)* RIGHT_PAREN (NOT? NULL)? (DEFAULT (STRING | NULL))? characterSet? collateClause?)) ; timestampType: TIMESTAMP dataTypeLength? ; currentTimestampType: CURRENT_TIMESTAMP dataTypeLength? ; dataTypeLength: (LEFT_PAREN NUMBER RIGHT_PAREN) ; dataTypeLengthWithPrecision: (LEFT_PAREN NUMBER COMMA NUMBER RIGHT_PAREN) ; numberTypeSuffix: UNSIGNED? ZEROFILL? (DEFAULT (NUMBER |STRING | NULL))? ; dataTypeOption: (UNIQUE KEY?)? (PRIMARY? KEY)? (COMMENT STRING)? (COLUMN_FORMAT (FIXED|DYNAMIC|DEFAULT))? (STORAGE (DISK|MEMORY|DEFAULT))? (referenceDefinition)? ; dataTypeGenerated: (GENERATED ALWAYS)? AS LEFT_PAREN expr RIGHT_PAREN (VIRTUAL | STORED)? (NOT NULL | NULL)? (UNIQUE (KEY)?)? ((PRIMARY)? KEY)? (COMMENT STRING)? ; referenceDefinition: REFERENCES tableName keyParts (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (((ON UPDATE referenceOption)? (ON DELETE referenceOption)?) |((ON DELETE referenceOption)? (ON UPDATE referenceOption)?) ) ; referenceOption: (RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT) ; symbol: ID ; fkSymbol: ID ; keyParts: LEFT_PAREN keyPart (COMMA keyPart)* RIGHT_PAREN ; defaultValue: NULL |simpleExpr ; keyPart: columnName (LEFT_PAREN NUMBER RIGHT_PAREN)? (ASC | DESC)? ; indexName: ID ; indexType: USING (BTREE | HASH) ; indexOption: KEY_BLOCK_SIZE EQ_OR_ASSIGN? value | indexType | WITH PARSER parserName | COMMENT STRING ; parserName: ID ; engineName: ID |MEMORY ; partitionNames: partitionName (COMMA partitionName)* ; partitionName: ID ; partitionOptions: PARTITION BY (linearPartition | rangeOrListPartition) (PARTITIONS NUMBER)? (SUBPARTITION BY linearPartition (SUBPARTITIONS NUMBER)? )? partitionDefinitions? ; //hash(YEAR(col)) YEAR is keyword which does not match expr linearPartition: LINEAR? ((HASH (yearFunctionExpr | exprWithParen)) |keyColumnList) ; yearFunctionExpr: LEFT_PAREN YEAR exprWithParen RIGHT_PAREN ; keyColumnList: KEY (ALGORITHM EQ_OR_ASSIGN NUMBER)? columnList ; exprWithParen: LEFT_PAREN expr RIGHT_PAREN ; rangeOrListPartition: (RANGE | LIST ) exprOrColumns ; exprOrColumns: LEFT_PAREN expr RIGHT_PAREN | COLUMNS columnList ; partitionDefinitions: LEFT_PAREN partitionDefinition (COMMA partitionDefinition)* RIGHT_PAREN ; partitionDefinition: PARTITION partitionName (VALUES (lessThanPartition|IN valueListWithParen))? (STORAGE? ENGINE EQ_OR_ASSIGN? engineName)? (COMMENT EQ_OR_ASSIGN? STRING )? (DATA DIRECTORY EQ_OR_ASSIGN? STRING)? (INDEX DIRECTORY EQ_OR_ASSIGN? STRING)? (MAX_ROWS EQ_OR_ASSIGN? NUMBER)? (MIN_ROWS EQ_OR_ASSIGN? NUMBER)? (TABLESPACE EQ_OR_ASSIGN? tablespaceName)? (subpartitionDefinition (COMMA subpartitionDefinition)*)? ; lessThanPartition: LESS THAN ((LEFT_PAREN (expr | valueList) RIGHT_PAREN) | MAXVALUE) ; subpartitionDefinition: SUBPARTITION partitionName ((STORAGE)? ENGINE EQ_OR_ASSIGN? engineName)? (COMMENT EQ_OR_ASSIGN? STRING )? (DATA DIRECTORY EQ_OR_ASSIGN? STRING)? (INDEX DIRECTORY EQ_OR_ASSIGN? STRING)? (MAX_ROWS EQ_OR_ASSIGN? NUMBER)? (MIN_ROWS EQ_OR_ASSIGN? NUMBER)? (TABLESPACE EQ_OR_ASSIGN? tablespaceName)? ;
add create table rule
add create table rule
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
e3fa7c5b78efd0e35637ae88872b5988e83da614
sharding-jdbc-ddl-parser/src/main/antlr4/imports/BaseRule.g4
sharding-jdbc-ddl-parser/src/main/antlr4/imports/BaseRule.g4
//rule in this file does not allow override grammar BaseRule; import DataType,Keyword,Symbol; ID: (BACK_QUOTA?[a-zA-Z_$][a-zA-Z0-9_$]* BACK_QUOTA? DOT)? (BACK_QUOTA?[a-zA-Z_$][a-zA-Z0-9_$]* BACK_QUOTA?) |[a-zA-Z_$0-9]+ DOT ASTERISK ; schemaName: ID; tableName: ID; columnName: ID; tablespaceName: ID; collationName: STRING | ID; indexName: ID; alias: ID; cteName:ID; parserName: ID; extensionName: ID; rowName: ID; opclass: ID; fileGroup: ID; groupName: ID; constraintName: ID; keyName: ID; typeName: ID; xmlSchemaCollection:ID; columnSetName: ID; directoryName: ID; triggerName: ID; roleName: ID; partitionName: ID; rewriteRuleName: ID; ownerName: ID; ifExists : IF EXISTS; ifNotExists : IF NOT EXISTS; dataTypeLength : LEFT_PAREN (NUMBER (COMMA NUMBER)?)? RIGHT_PAREN ; nullNotnull : NULL | NOT NULL ; primaryKey: PRIMARY KEY ; matchNone: 'Default does not match anything' ; idList: LEFT_PAREN ID (COMMA ID)* RIGHT_PAREN ; rangeClause: NUMBER (COMMA NUMBER)* | NUMBER OFFSET NUMBER ; tableNamesWithParen: LEFT_PAREN tableNames RIGHT_PAREN ; tableNames: tableName (COMMA tableName)* ; columnNamesWithParen: LEFT_PAREN columnNames RIGHT_PAREN ; columnNames: columnName (COMMA columnName)* ; columnList: LEFT_PAREN columnNames RIGHT_PAREN ; indexNames: indexName (COMMA indexName)* ; rowNames: rowName (COMMA rowName)* ; bitExprs: bitExpr (COMMA bitExpr)* ; exprs: expr (COMMA expr)* ; exprsWithParen: LEFT_PAREN exprs RIGHT_PAREN ; //https://dev.mysql.com/doc/refman/8.0/en/expressions.html expr: expr OR expr | expr OR_SYM expr | expr XOR expr | expr AND expr | expr AND_SYM expr | LEFT_PAREN expr RIGHT_PAREN | NOT expr | NOT_SYM expr | booleanPrimary | exprRecursive ; exprRecursive: matchNone ; booleanPrimary: booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL) | booleanPrimary SAFE_EQ predicate | booleanPrimary comparisonOperator predicate | booleanPrimary comparisonOperator (ALL | ANY) subquery | predicate ; comparisonOperator: EQ_OR_ASSIGN | GTE | GT | LTE | LT | NEQ_SYM | NEQ ; predicate: bitExpr NOT? IN subquery | bitExpr NOT? IN LEFT_PAREN simpleExpr ( COMMA simpleExpr)* RIGHT_PAREN | bitExpr NOT? BETWEEN simpleExpr AND predicate | bitExpr SOUNDS LIKE simpleExpr | bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)* | bitExpr NOT? REGEXP simpleExpr | bitExpr ; bitExpr: bitExpr BIT_INCLUSIVE_OR bitExpr | bitExpr BIT_AND bitExpr | bitExpr SIGNED_LEFT_SHIFT bitExpr | bitExpr SIGNED_RIGHT_SHIFT bitExpr | bitExpr PLUS bitExpr | bitExpr MINUS bitExpr | bitExpr ASTERISK bitExpr | bitExpr SLASH bitExpr | bitExpr DIV bitExpr | bitExpr MOD bitExpr | bitExpr MOD_SYM bitExpr | bitExpr BIT_EXCLUSIVE_OR bitExpr //| bitExpr '+' interval_expr //| bitExpr '-' interval_expr | simpleExpr ; simpleExpr: functionCall | liter | ID | simpleExpr collateClause //| param_marker //| variable | simpleExpr AND_SYM simpleExpr | PLUS simpleExpr | MINUS simpleExpr | UNARY_BIT_COMPLEMENT simpleExpr | NOT_SYM simpleExpr | BINARY simpleExpr | LEFT_PAREN expr RIGHT_PAREN | ROW LEFT_PAREN simpleExpr( COMMA simpleExpr)* RIGHT_PAREN | subquery | EXISTS subquery // | (identifier expr) //| match_expr //| case_expr // | interval_expr |privateExprOfDb ; functionCall: ID LEFT_PAREN( bitExprs?) RIGHT_PAREN ; privateExprOfDb: matchNone ; liter: QUESTION |NUMBER |TRUE |FALSE |NULL |LEFT_BRACE ID STRING RIGHT_BRACE // |HEX_DIGIT |ID? STRING collateClause? |(DATE | TIME |TIMESTAMP)STRING |ID? BIT_NUM collateClause? ; subquery: matchNone ; collateClause: matchNone ; orderByClause: ORDER BY groupByItem (COMMA groupByItem)* ; groupByItem: (columnName | NUMBER |expr) (ASC|DESC)? ;
//rule in this file does not allow override grammar BaseRule; import DataType,Keyword,Symbol; ID: (BACK_QUOTA?[a-zA-Z_$][a-zA-Z0-9_$]* BACK_QUOTA? DOT)? (BACK_QUOTA?[a-zA-Z_$][a-zA-Z0-9_$]* BACK_QUOTA?) |[a-zA-Z_$0-9]+ DOT ASTERISK ; schemaName: ID; tableName: ID; columnName: ID; tablespaceName: ID; collationName: STRING | ID; indexName: ID; alias: ID; cteName:ID; parserName: ID; extensionName: ID; rowName: ID; opclass: ID; fileGroup: ID; groupName: ID; constraintName: ID; keyName: ID; typeName: ID; xmlSchemaCollection:ID; columnSetName: ID; directoryName: ID; triggerName: ID; roleName: ID; partitionName: ID; rewriteRuleName: ID; ownerName: ID; ifExists : IF EXISTS; ifNotExists : IF NOT EXISTS; dataTypeLength : LEFT_PAREN (NUMBER (COMMA NUMBER)?)? RIGHT_PAREN ; nullNotnull : NULL | NOT NULL ; primaryKey : PRIMARY KEY ; matchNone : 'Default does not match anything' ; idList : LEFT_PAREN ID (COMMA ID)* RIGHT_PAREN ; rangeClause : NUMBER (COMMA NUMBER)* | NUMBER OFFSET NUMBER ; tableNamesWithParen : LEFT_PAREN tableNames RIGHT_PAREN ; tableNames : tableName (COMMA tableName)* ; columnNamesWithParen : LEFT_PAREN columnNames RIGHT_PAREN ; columnNames : columnName (COMMA columnName)* ; columnList : LEFT_PAREN columnNames RIGHT_PAREN ; indexNames : indexName (COMMA indexName)* ; rowNames : rowName (COMMA rowName)* ; bitExprs: bitExpr (COMMA bitExpr)* ; exprs : expr (COMMA expr)* ; exprsWithParen : LEFT_PAREN exprs RIGHT_PAREN ; //https://dev.mysql.com/doc/refman/8.0/en/expressions.html expr : expr OR expr | expr OR_SYM expr | expr XOR expr | expr AND expr | expr AND_SYM expr | LEFT_PAREN expr RIGHT_PAREN | NOT expr | NOT_SYM expr | booleanPrimary | exprRecursive ; exprRecursive : matchNone ; booleanPrimary : booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL) | booleanPrimary SAFE_EQ predicate | booleanPrimary comparisonOperator predicate | booleanPrimary comparisonOperator (ALL | ANY) subquery | predicate ; comparisonOperator : EQ_OR_ASSIGN | GTE | GT | LTE | LT | NEQ_SYM | NEQ ; predicate : bitExpr NOT? IN subquery | bitExpr NOT? IN LEFT_PAREN simpleExpr ( COMMA simpleExpr)* RIGHT_PAREN | bitExpr NOT? BETWEEN simpleExpr AND predicate | bitExpr SOUNDS LIKE simpleExpr | bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)* | bitExpr NOT? REGEXP simpleExpr | bitExpr ; bitExpr : bitExpr BIT_INCLUSIVE_OR bitExpr | bitExpr BIT_AND bitExpr | bitExpr SIGNED_LEFT_SHIFT bitExpr | bitExpr SIGNED_RIGHT_SHIFT bitExpr | bitExpr PLUS bitExpr | bitExpr MINUS bitExpr | bitExpr ASTERISK bitExpr | bitExpr SLASH bitExpr | bitExpr MOD bitExpr | bitExpr MOD_SYM bitExpr | bitExpr BIT_EXCLUSIVE_OR bitExpr //| bitExpr '+' interval_expr //| bitExpr '-' interval_expr | simpleExpr ; simpleExpr : functionCall | liter | ID | simpleExpr collateClause //| param_marker //| variable | simpleExpr AND_SYM simpleExpr | PLUS simpleExpr | MINUS simpleExpr | UNARY_BIT_COMPLEMENT simpleExpr | NOT_SYM simpleExpr | BINARY simpleExpr | LEFT_PAREN expr RIGHT_PAREN | ROW LEFT_PAREN simpleExpr( COMMA simpleExpr)* RIGHT_PAREN | subquery | EXISTS subquery // | (identifier expr) //| match_expr //| case_expr // | interval_expr |privateExprOfDb ; functionCall : ID LEFT_PAREN( bitExprs?) RIGHT_PAREN ; privateExprOfDb : matchNone ; liter : QUESTION | NUMBER | TRUE | FALSE | NULL | LEFT_BRACE ID STRING RIGHT_BRACE | HEX_DIGIT | ID? STRING collateClause? | (DATE | TIME |TIMESTAMP) STRING | ID? BIT_NUM collateClause? ; subquery : matchNone ; collateClause : matchNone ; orderByClause : ORDER BY groupByItem (COMMA groupByItem)* ; groupByItem : (columnName | NUMBER |expr) (ASC|DESC)? ;
Format BaseRule
Format BaseRule
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
afbab7b7ff704cfa9fb8e4eaed25abde11f8cc87
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
/* Todo: * - Comments justifying and explaining every rule. */ lexer grammar CreoleTokens; options { superClass=ContextSensitiveLexer; } @members { Formatting bold; Formatting italic; Formatting strike; public void setupFormatting() { bold = new Formatting("**"); italic = new Formatting("//"); strike = new Formatting("--"); inlineFormatting.add(bold); inlineFormatting.add(italic); inlineFormatting.add(strike); } public boolean inHeader = false; public boolean start = false; public int listLevel = 0; boolean nowiki = false; boolean cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = false; boolean intr = false; public void doHdr() { String prefix = getText().trim(); boolean seekback = false; if(!prefix.substring(prefix.length() - 1).equals("=")) { prefix = prefix.substring(0, prefix.length() - 1); seekback = true; } if(prefix.length() <= 6) { if(seekback) { seek(-1); } setText(prefix); inHeader = true; } else { setType(Any); } } public void setStart() { String next1 = next(); String next2 = get(1); start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#")); } public void doList(int level) { listLevel = level; seek(-1); setStart(); resetFormatting(); } public void doUrl() { String url = getText(); String last = url.substring(url.length()-1); String next = next(); if(url.endsWith("://") || url.endsWith("mailto:")) { setType(Any); } while((last + next).equals("//") || last.matches("[\\.,)\"]")) { seek(-1); url = url.substring(0, url.length() - 1); last = url.substring(url.length()-1); next = next(); } setText(url); } public void breakOut() { resetFormatting(); listLevel = 0; inHeader = false; intr = false; nowiki = false; cpp = false; html = false; java = false; xhtml = false; xml = false; } public String[] thisKillsTheFormatting() { String[] ends = new String[7]; if(inHeader || intr) { ends[0] = "\n"; ends[1] = "\r\n"; } else { ends[0] = null; ends[1] = null; } if(intr) { ends[2] = "|"; } else { ends[2] = null; } ends[3] = "\n\n"; ends[4] = "\r\n\r\n"; if(listLevel > 0) { ends[5] = "\n*"; ends[6] = "\n#"; } else { ends[5] = null; ends[6] = null; } return ends; } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' WS? {doHdr();} ; HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ; /* ***** Lists ***** */ U1 : START '*' ~'*' {doList(1);} ; U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ; U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ; U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ; U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ; U6 : START '******' ~'*' {listLevel >= 5}? {doList(6);} ; U7 : START '*******' ~'*' {listLevel >= 6}? {doList(7);} ; U8 : START '********' ~'*' {listLevel >= 7}? {doList(8);} ; U9 : START '*********' ~'*' {listLevel >= 8}? {doList(9);} ; U10 : START '**********' ~'*' {listLevel >= 9}? {doList(10);} ; O1 : START '#' ~'#' {doList(1);} ; O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ; O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ; O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ; O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ; O6 : START '######' ~'#' {listLevel >= 5}? {doList(6);} ; O7 : START '#######' ~'#' {listLevel >= 6}? {doList(7);} ; O8 : START '########' ~'#' {listLevel >= 7}? {doList(8);} ; O9 : START '#########' ~'#' {listLevel >= 8}? {doList(9);} ; O10 : START '##########' ~'#' {listLevel >= 9}? {doList(10);} ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+? {breakOut();} ; /* ***** Tables ***** */ TdStartLn : LINE '|'+ {intr=true; setType(TdStart);} ; ThStartLn : LINE '|'+ '=' {intr=true; setType(ThStart);} ; RowEnd : '|'+ WS? LineBreak {intr}? {breakOut();} ; TdStart : '|'+ {intr}? {breakOut(); intr=true;} ; ThStart : '|'+ '=' {intr}? {breakOut(); intr=true;} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active && !prior().equals(":")}? {setFormatting(italic, Any);} ; SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ; BEnd : '**' {bold.active}? {unsetFormatting(bold);} ; IEnd : '//' {italic.active && !prior().equals(":")}? {unsetFormatting(italic);} ; SEnd : '--' {strike.active}? {unsetFormatting(strike);} ; NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ; StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ; StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ; StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ; StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ; StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ; /* ***** Links ***** */ LiSt : '[[' -> mode(LINK) ; ImSt : '{{' -> mode(LINK) ; /* ***** Breaks ***** */ InlineBrk : '\\\\' ; ParBreak : LineBreak WS? LineBreak+ {breakOut();} ; LineBreak : '\r'? '\n' ; /* ***** Links ***** */ RawUrl : PROTOCOL (~(' '|'\t'|'\r'|'\n'|'|'|'['|']')+ '/'?)+ {doUrl();} ; fragment PROTOCOL : ('http' 's'? | 'file' | 'ftp') '://' | 'mailto:' ; Attachment : UPPER ALNUM* ALPHA ALNUM+ '.' LOWNUM+ {checkBounds("[a-zA-Z0-9@\\./=-]", "[a-zA-Z0-9@/=-]")}? ; WikiWords : (UPPER (ABBR | CAMEL) | INTERWIKI ALNUM+) {checkBounds("[\\.\\w]", "\\w")}? ; fragment INTERWIKI : ALPHA ALNUM+ ':' ; fragment ABBR : UPPER UPPER+ ; fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ; /* ***** Macros ***** */ MacroSt : '<<' -> mode(MACRO) ; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t')+ ; fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ; fragment START : {start}? | LINE ; fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*; fragment LOWNUM : (LOWER | DIGIT) ; fragment UPNUM : (UPPER | DIGIT) ; fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ; ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ; Sep : ' '* '|' ' '*; InLink : ~(']'|'}'|'|'|'\r'|'\n')+ {setText(getText().trim());}; mode MACRO; MacroName : ~(':'|'>')+ ; MacroSep : ':' -> mode(MACRO_ARGS) ; mode MACRO_ARGS; MacroArgs : . -> more ; MacroEnd : '>>' -> mode(DEFAULT_MODE) ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' ~'}' {nowiki}? {nowiki=false; seek(-1);} -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
/* Todo: * - Comments justifying and explaining every rule. */ lexer grammar CreoleTokens; options { superClass=ContextSensitiveLexer; } @members { Formatting bold; Formatting italic; Formatting strike; public void setupFormatting() { bold = new Formatting("**"); italic = new Formatting("//"); strike = new Formatting("--"); inlineFormatting.add(bold); inlineFormatting.add(italic); inlineFormatting.add(strike); } public boolean inHeader = false; public boolean start = false; public int listLevel = 0; boolean nowiki = false; boolean cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = false; boolean intr = false; public void doHdr() { String prefix = getText().trim(); boolean seekback = false; if(!prefix.substring(prefix.length() - 1).equals("=")) { prefix = prefix.substring(0, prefix.length() - 1); seekback = true; } if(prefix.length() <= 6) { if(seekback) { seek(-1); } setText(prefix); inHeader = true; } else { setType(Any); } } public void setStart() { String next1 = next(); String next2 = get(1); start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#")); } public void doList(int level) { listLevel = level; seek(-1); setStart(); resetFormatting(); } public void doUrl() { String url = getText(); String last = url.substring(url.length()-1); String next = next(); if(url.endsWith("://") || url.endsWith("mailto:")) { setType(Any); } while((last + next).equals("//") || last.matches("[\\.,)\"]")) { seek(-1); url = url.substring(0, url.length() - 1); last = url.substring(url.length()-1); next = next(); } setText(url); } public void breakOut() { resetFormatting(); listLevel = 0; inHeader = false; intr = false; nowiki = false; cpp = false; html = false; java = false; xhtml = false; xml = false; } public String[] thisKillsTheFormatting() { String[] ends = new String[7]; if(inHeader || intr) { ends[0] = "\n"; ends[1] = "\r\n"; } else { ends[0] = null; ends[1] = null; } if(intr) { ends[2] = "|"; } else { ends[2] = null; } ends[3] = "\n\n"; ends[4] = "\r\n\r\n"; if(listLevel > 0) { ends[5] = "\n*"; ends[6] = "\n#"; } else { ends[5] = null; ends[6] = null; } return ends; } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' WS? {doHdr();} ; HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ; /* ***** Lists ***** */ U1 : START '*' ~'*' {doList(1);} ; U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ; U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ; U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ; U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ; U6 : START '******' ~'*' {listLevel >= 5}? {doList(6);} ; U7 : START '*******' ~'*' {listLevel >= 6}? {doList(7);} ; U8 : START '********' ~'*' {listLevel >= 7}? {doList(8);} ; U9 : START '*********' ~'*' {listLevel >= 8}? {doList(9);} ; U10 : START '**********' ~'*' {listLevel >= 9}? {doList(10);} ; O1 : START '#' ~'#' {doList(1);} ; O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ; O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ; O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ; O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ; O6 : START '######' ~'#' {listLevel >= 5}? {doList(6);} ; O7 : START '#######' ~'#' {listLevel >= 6}? {doList(7);} ; O8 : START '########' ~'#' {listLevel >= 7}? {doList(8);} ; O9 : START '#########' ~'#' {listLevel >= 8}? {doList(9);} ; O10 : START '##########' ~'#' {listLevel >= 9}? {doList(10);} ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+ {breakOut();} ; /* ***** Tables ***** */ TdStartLn : LINE '|'+ {intr=true; setType(TdStart);} ; ThStartLn : LINE '|'+ '=' {intr=true; setType(ThStart);} ; RowEnd : '|'+ WS? LineBreak {intr}? {breakOut();} ; TdStart : '|'+ {intr}? {breakOut(); intr=true;} ; ThStart : '|'+ '=' {intr}? {breakOut(); intr=true;} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active && !prior().equals(":")}? {setFormatting(italic, Any);} ; SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ; BEnd : '**' {bold.active}? {unsetFormatting(bold);} ; IEnd : '//' {italic.active && !prior().equals(":")}? {unsetFormatting(italic);} ; SEnd : '--' {strike.active}? {unsetFormatting(strike);} ; NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ; StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ; StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ; StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ; StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ; StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ; /* ***** Links ***** */ LiSt : '[[' -> mode(LINK) ; ImSt : '{{' -> mode(LINK) ; /* ***** Breaks ***** */ InlineBrk : '\\\\' ; ParBreak : LineBreak WS? LineBreak+ {breakOut();} ; LineBreak : '\r'? '\n' ; /* ***** Links ***** */ RawUrl : PROTOCOL (~(' '|'\t'|'\r'|'\n'|'|'|'['|']')+ '/'?)+ {doUrl();} ; fragment PROTOCOL : ('http' 's'? | 'file' | 'ftp') '://' | 'mailto:' ; Attachment : UPPER ALNUM* ALPHA ALNUM+ '.' LOWNUM+ {checkBounds("[a-zA-Z0-9@\\./=-]", "[a-zA-Z0-9@/=-]")}? ; WikiWords : (UPPER (ABBR | CAMEL) | INTERWIKI ALNUM+) {checkBounds("[\\.\\w]", "\\w")}? ; fragment INTERWIKI : ALPHA ALNUM+ ':' ; fragment ABBR : UPPER UPPER+ ; fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ; /* ***** Macros ***** */ MacroSt : '<<' -> mode(MACRO) ; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t')+ ; fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ; fragment START : {start}? | LINE ; fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*; fragment LOWNUM : (LOWER | DIGIT) ; fragment UPNUM : (UPPER | DIGIT) ; fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ; ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ; Sep : ' '* '|' ' '*; InLink : ~(']'|'}'|'|'|'\r'|'\n')+ {setText(getText().trim());}; mode MACRO; MacroName : ~(':'|'>')+ ; MacroSep : ':' -> mode(MACRO_ARGS) ; mode MACRO_ARGS; MacroArgs : . -> more ; MacroEnd : '>>' -> mode(DEFAULT_MODE) ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' ~'}' {nowiki}? {nowiki=false; seek(-1);} -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
Allow horizontal rules to be any number of -s greater than 4 long
Allow horizontal rules to be any number of -s greater than 4 long
ANTLR
apache-2.0
ashirley/reviki,CoreFiling/reviki,strr/reviki,CoreFiling/reviki,strr/reviki,strr/reviki,CoreFiling/reviki,strr/reviki,strr/reviki,CoreFiling/reviki,ashirley/reviki,CoreFiling/reviki,ashirley/reviki,ashirley/reviki,ashirley/reviki
9bfbfadac8c01a8527d819a4c7e52c07ed76e4e6
projects/batfish/src/org/batfish/grammar/flatjuniper/FlatJuniper_isis.g4
projects/batfish/src/org/batfish/grammar/flatjuniper/FlatJuniper_isis.g4
parser grammar FlatJuniper_isis; import FlatJuniper_common; options { tokenVocab = FlatJuniperLexer; } isisilt_enable : ENABLE ; isisilt_metric : METRIC DEC ; isisilt_te_metric : TE_METRIC DEC ; isisilt_null : ( HELLO_AUTHENTICATION_KEY | HELLO_AUTHENTICATION_TYPE | HELLO_INTERVAL | HOLD_TIME ) s_null_filler ; isisit_level : LEVEL DEC isisit_level_tail ; isisit_level_tail : isisilt_enable | isisilt_metric | isisilt_te_metric | isisilt_null ; isisit_null : ( BFD_LIVENESS_DETECTION | HELLO_PADDING | LSP_INTERVAL ) s_null_filler ; isisit_passive : PASSIVE ; isisit_point_to_point : POINT_TO_POINT ; isislt_disable : DISABLE ; isislt_enable : ENABLE ; isislt_null : ( AUTHENTICATION_KEY | AUTHENTICATION_TYPE | PREFIX_EXPORT_LIMIT ) s_null_filler ; isislt_wide_metrics_only : WIDE_METRICS_ONLY ; isist_apply_groups : s_apply_groups ; isist_export : EXPORT ( policies += variable )+ ; isist_interface : INTERFACE ( id = interface_id | WILDCARD ) isist_interface_tail ; isist_interface_tail : // intentional blank | isisit_level | isisit_null | isisit_passive | isisit_point_to_point ; isist_level : LEVEL ( DEC | WILDCARD ) isist_level_tail ; isist_level_tail : isislt_disable | isislt_enable | isislt_null | isislt_wide_metrics_only ; isist_null : ( LSP_LIFETIME | SPF_OPTIONS | OVERLOAD | TRACEOPTIONS ) s_null_filler ; isist_no_ipv4_routing : NO_IPV4_ROUTING ; isist_rib_group : RIB_GROUP INET name = variable ; isist_traffic_engineering : TRAFFIC_ENGINEERING isist_traffic_engineering_tail ; isist_traffic_engineering_tail : isistet_credibility_protocol_preference | isistet_family_shortcuts | isistet_multipath ; isistet_credibility_protocol_preference : CREDIBILITY_PROTOCOL_PREFERENCE ; isistet_family_shortcuts : FAMILY ( INET | INET6 ) SHORTCUTS ; isistet_multipath : MULTIPATH LSP_EQUAL_COST ; s_protocols_isis : ISIS s_protocols_isis_tail ; s_protocols_isis_tail : isist_apply_groups | isist_export | isist_interface | isist_level | isist_null | isist_no_ipv4_routing | isist_rib_group | isist_traffic_engineering ;
parser grammar FlatJuniper_isis; import FlatJuniper_common; options { tokenVocab = FlatJuniperLexer; } isisilt_enable : ENABLE ; isisilt_metric : METRIC DEC ; isisilt_te_metric : TE_METRIC DEC ; isisilt_null : ( HELLO_AUTHENTICATION_KEY | HELLO_AUTHENTICATION_TYPE | HELLO_INTERVAL | HOLD_TIME ) s_null_filler ; isisit_apply_groups : s_apply_groups ; isisit_apply_groups_except : s_apply_groups_except ; isisit_level : LEVEL DEC isisit_level_tail ; isisit_level_tail : isisilt_enable | isisilt_metric | isisilt_te_metric | isisilt_null ; isisit_null : ( BFD_LIVENESS_DETECTION | HELLO_PADDING | LSP_INTERVAL ) s_null_filler ; isisit_passive : PASSIVE ; isisit_point_to_point : POINT_TO_POINT ; isislt_disable : DISABLE ; isislt_enable : ENABLE ; isislt_null : ( AUTHENTICATION_KEY | AUTHENTICATION_TYPE | PREFIX_EXPORT_LIMIT ) s_null_filler ; isislt_wide_metrics_only : WIDE_METRICS_ONLY ; isist_apply_groups : s_apply_groups ; isist_export : EXPORT ( policies += variable )+ ; isist_interface : INTERFACE ( id = interface_id | WILDCARD ) isist_interface_tail ; isist_interface_tail : // intentional blank | isisit_apply_groups | isisit_apply_groups_except | isisit_level | isisit_null | isisit_passive | isisit_point_to_point ; isist_level : LEVEL ( DEC | WILDCARD ) isist_level_tail ; isist_level_tail : isislt_disable | isislt_enable | isislt_null | isislt_wide_metrics_only ; isist_null : ( LSP_LIFETIME | SPF_OPTIONS | OVERLOAD | TRACEOPTIONS ) s_null_filler ; isist_no_ipv4_routing : NO_IPV4_ROUTING ; isist_rib_group : RIB_GROUP INET name = variable ; isist_traffic_engineering : TRAFFIC_ENGINEERING isist_traffic_engineering_tail ; isist_traffic_engineering_tail : isistet_credibility_protocol_preference | isistet_family_shortcuts | isistet_multipath ; isistet_credibility_protocol_preference : CREDIBILITY_PROTOCOL_PREFERENCE ; isistet_family_shortcuts : FAMILY ( INET | INET6 ) SHORTCUTS ; isistet_multipath : MULTIPATH LSP_EQUAL_COST ; s_protocols_isis : ISIS s_protocols_isis_tail ; s_protocols_isis_tail : isist_apply_groups | isist_export | isist_interface | isist_level | isist_null | isist_no_ipv4_routing | isist_rib_group | isist_traffic_engineering ;
apply groups
apply groups
ANTLR
apache-2.0
arifogel/batfish,intentionet/batfish,batfish/batfish,dhalperi/batfish,intentionet/batfish,batfish/batfish,arifogel/batfish,batfish/batfish,arifogel/batfish,dhalperi/batfish,intentionet/batfish,intentionet/batfish,intentionet/batfish,dhalperi/batfish
673e8b86843afc5c092b753c7c419738252a1ddd
grammars/cs652/cdecl/CDecl.g4
grammars/cs652/cdecl/CDecl.g4
grammar CDecl; declaration : typename declarator ';' ; typename : 'void' | 'float' | 'int' | ID ; declarator : declarator '[' ']' # Array // right operators have highest precedence | declarator '(' ')' # Func | '*' declarator # Pointer | '(' declarator ')' # Grouping | ID # Var ; // the following also would work but with less cool trees declaration2 : typename declarator2 ';' ; declarator2 : ( '*' declarator2 | '(' declarator2 ')' | ID ) ( '[' ']' | '(' ')' )* ; ID : [a-zA-Z_] [a-zA-Z0-9_]+ ; WS : [ \t\n\r]+ -> skip ;
grammar CDecl; declaration : typename declarator ';' ; typename : 'void' | 'float' | 'int' | ID ; declarator : declarator '[' ']' # Array // right operators have highest precedence | declarator '(' ')' # Func | '*' declarator # Pointer | '(' declarator ')' # Grouping | ID # Var ; // the following also would work but with less cool trees declaration2 : typename declarator2 ';' ; declarator2 : ( '*' declarator2 | '(' declarator2 ')' | ID ) ( '[' ']' | '(' ')' )* ; ID : [a-zA-Z_] [a-zA-Z0-9_]* ; WS : [ \t\n\r]+ -> skip ;
Update CDecl.g4
Update CDecl.g4
ANTLR
bsd-2-clause
USF-CS652-starterkits/parrt-cdecl
7586abf01b5c6fcbb60926c7cab7d3e5d133fa9a
src/grammar/RustLexer.g4
src/grammar/RustLexer.g4
lexer grammar RustLexer; tokens { EQ, LT, LE, EQEQ, NE, GE, GT, ANDAND, OROR, NOT, TILDE, PLUT, MINUS, STAR, SLASH, PERCENT, CARET, AND, OR, SHL, SHR, BINOP, BINOPEQ, AT, DOT, DOTDOT, DOTDOTDOT, COMMA, SEMI, COLON, MOD_SEP, RARROW, FAT_ARROW, LPAREN, RPAREN, LBRACKET, RBRACKET, LBRACE, RBRACE, POUND, DOLLAR, UNDERSCORE, LIT_CHAR, LIT_INTEGER, LIT_FLOAT, LIT_STR, LIT_STR_RAW, LIT_BINARY, LIT_BINARY_RAW, IDENT, LIFETIME, WHITESPACE, DOC_COMMENT, COMMENT } /* Note: due to antlr limitations, we can't represent XID_start and * XID_continue properly. ASCII-only substitute. */ fragment XID_start : [_a-zA-Z] ; fragment XID_continue : [_a-zA-Z0-9] ; /* Expression-operator symbols */ EQ : '=' ; LT : '<' ; LE : '<=' ; EQEQ : '==' ; NE : '!=' ; GE : '>=' ; GT : '>' ; ANDAND : '&&' ; OROR : '||' ; NOT : '!' ; TILDE : '~' ; PLUS : '+' ; MINUS : '-' ; STAR : '*' ; SLASH : '/' ; PERCENT : '%' ; CARET : '^' ; AND : '&' ; OR : '|' ; SHL : '<<' ; SHR : '>>' ; BINOP : PLUS | SLASH | MINUS | STAR | PERCENT | CARET | AND | OR | SHL | SHR ; BINOPEQ : BINOP EQ ; /* "Structural symbols" */ AT : '@' ; DOT : '.' ; DOTDOT : '..' ; DOTDOTDOT : '...' ; COMMA : ',' ; SEMI : ';' ; COLON : ':' ; MOD_SEP : '::' ; RARROW : '->' ; FAT_ARROW : '=>' ; LPAREN : '(' ; RPAREN : ')' ; LBRACKET : '[' ; RBRACKET : ']' ; LBRACE : '{' ; RBRACE : '}' ; POUND : '#'; DOLLAR : '$' ; UNDERSCORE : '_' ; // Literals fragment HEXIT : [0-9a-fA-F] ; fragment CHAR_ESCAPE : [nrt\\'"0] | [xX] HEXIT HEXIT | 'u' HEXIT HEXIT HEXIT HEXIT | 'U' HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT ; LIT_CHAR : '\'' ( '\\' CHAR_ESCAPE | ~[\\'\n\t\r] ) '\'' ; LIT_BYTE : 'b\'' ( '\\' ( [xX] HEXIT HEXIT | [nrt\\'"0] ) | ~[\\'\n\t\r] ) '\'' ; fragment INT_SUFFIX : 'i' | 'i8' | 'i16' | 'i32' | 'i64' | 'u' | 'u8' | 'u16' | 'u32' | 'u64' ; LIT_INTEGER : [0-9][0-9_]* INT_SUFFIX? | '0b' [01][01_]* INT_SUFFIX? | '0o' [0-7][0-7_]* INT_SUFFIX? | '0x' [0-9a-fA-F][0-9a-fA-F_]* INT_SUFFIX? ; fragment FLOAT_SUFFIX : 'f32' | 'f64' ; LIT_FLOAT : [0-9][0-9_]* ('.' | ('.' [0-9][0-9_]*)? ([eE] [-+]? [0-9][0-9_]*)? FLOAT_SUFFIX?) ; LIT_STR : '"' ('\\\n' | '\\\r\n' | '\\' CHAR_ESCAPE | .)*? '"' ; LIT_BINARY : 'b' LIT_STR ; LIT_BINARY_RAW : 'rb' LIT_STR_RAW ; /* this is a bit messy */ fragment LIT_STR_RAW_INNER : '"' .*? '"' | LIT_STR_RAW_INNER2 ; fragment LIT_STR_RAW_INNER2 : POUND LIT_STR_RAW_INNER POUND ; LIT_STR_RAW : 'r' LIT_STR_RAW_INNER ; IDENT : XID_start XID_continue* ; LIFETIME : '\'' IDENT ; WHITESPACE : [ \r\n\t]+ ; UNDOC_COMMENT : '////' ~[\r\n]* -> type(COMMENT) ; YESDOC_COMMENT : '///' ~[\r\n]* -> type(DOC_COMMENT) ; OUTER_DOC_COMMENT : '//!' ~[\r\n]* -> type(DOC_COMMENT) ; LINE_COMMENT : '//' ~[\r\n]* -> type(COMMENT) ; DOC_BLOCK_COMMENT : ('/**' ~[*] | '/*!') (DOC_BLOCK_COMMENT | .)*? '*/' -> type(DOC_COMMENT) ; BLOCK_COMMENT : '/*' (BLOCK_COMMENT | .)*? '*/' -> type(COMMENT) ;
lexer grammar RustLexer; tokens { EQ, LT, LE, EQEQ, NE, GE, GT, ANDAND, OROR, NOT, TILDE, PLUT, MINUS, STAR, SLASH, PERCENT, CARET, AND, OR, SHL, SHR, BINOP, BINOPEQ, AT, DOT, DOTDOT, DOTDOTDOT, COMMA, SEMI, COLON, MOD_SEP, RARROW, FAT_ARROW, LPAREN, RPAREN, LBRACKET, RBRACKET, LBRACE, RBRACE, POUND, DOLLAR, UNDERSCORE, LIT_CHAR, LIT_INTEGER, LIT_FLOAT, LIT_STR, LIT_STR_RAW, LIT_BINARY, LIT_BINARY_RAW, IDENT, LIFETIME, WHITESPACE, DOC_COMMENT, COMMENT } /* Note: due to antlr limitations, we can't represent XID_start and * XID_continue properly. ASCII-only substitute. */ fragment XID_start : [_a-zA-Z] ; fragment XID_continue : [_a-zA-Z0-9] ; /* Expression-operator symbols */ EQ : '=' ; LT : '<' ; LE : '<=' ; EQEQ : '==' ; NE : '!=' ; GE : '>=' ; GT : '>' ; ANDAND : '&&' ; OROR : '||' ; NOT : '!' ; TILDE : '~' ; PLUS : '+' ; MINUS : '-' ; STAR : '*' ; SLASH : '/' ; PERCENT : '%' ; CARET : '^' ; AND : '&' ; OR : '|' ; SHL : '<<' ; SHR : '>>' ; BINOP : PLUS | SLASH | MINUS | STAR | PERCENT | CARET | AND | OR | SHL | SHR ; BINOPEQ : BINOP EQ ; /* "Structural symbols" */ AT : '@' ; DOT : '.' ; DOTDOT : '..' ; DOTDOTDOT : '...' ; COMMA : ',' ; SEMI : ';' ; COLON : ':' ; MOD_SEP : '::' ; RARROW : '->' ; FAT_ARROW : '=>' ; LPAREN : '(' ; RPAREN : ')' ; LBRACKET : '[' ; RBRACKET : ']' ; LBRACE : '{' ; RBRACE : '}' ; POUND : '#'; DOLLAR : '$' ; UNDERSCORE : '_' ; // Literals fragment HEXIT : [0-9a-fA-F] ; fragment CHAR_ESCAPE : [nrt\\'"0] | [xX] HEXIT HEXIT | 'u' HEXIT HEXIT HEXIT HEXIT | 'U' HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT ; fragment SUFFIX : IDENT ; LIT_CHAR : '\'' ( '\\' CHAR_ESCAPE | ~[\\'\n\t\r] ) '\'' SUFFIX? ; LIT_BYTE : 'b\'' ( '\\' ( [xX] HEXIT HEXIT | [nrt\\'"0] ) | ~[\\'\n\t\r] ) '\'' SUFFIX? ; LIT_INTEGER : [0-9][0-9_]* SUFFIX? | '0b' [01][01_]* SUFFIX? | '0o' [0-7][0-7_]* SUFFIX? | '0x' [0-9a-fA-F][0-9a-fA-F_]* SUFFIX? ; LIT_FLOAT : [0-9][0-9_]* ('.' | ('.' [0-9][0-9_]*)? ([eE] [-+]? [0-9][0-9_]*)? SUFFIX?) ; LIT_STR : '"' ('\\\n' | '\\\r\n' | '\\' CHAR_ESCAPE | .)*? '"' SUFFIX? ; LIT_BINARY : 'b' LIT_STR SUFFIX?; LIT_BINARY_RAW : 'rb' LIT_STR_RAW SUFFIX?; /* this is a bit messy */ fragment LIT_STR_RAW_INNER : '"' .*? '"' | LIT_STR_RAW_INNER2 ; fragment LIT_STR_RAW_INNER2 : POUND LIT_STR_RAW_INNER POUND ; LIT_STR_RAW : 'r' LIT_STR_RAW_INNER SUFFIX? ; IDENT : XID_start XID_continue* ; LIFETIME : '\'' IDENT ; WHITESPACE : [ \r\n\t]+ ; UNDOC_COMMENT : '////' ~[\r\n]* -> type(COMMENT) ; YESDOC_COMMENT : '///' ~[\r\n]* -> type(DOC_COMMENT) ; OUTER_DOC_COMMENT : '//!' ~[\r\n]* -> type(DOC_COMMENT) ; LINE_COMMENT : '//' ~[\r\n]* -> type(COMMENT) ; DOC_BLOCK_COMMENT : ('/**' ~[*] | '/*!') (DOC_BLOCK_COMMENT | .)*? '*/' -> type(DOC_COMMENT) ; BLOCK_COMMENT : '/*' (BLOCK_COMMENT | .)*? '*/' -> type(COMMENT) ;
Adjust Antlr4 lexer to include suffixes.
Adjust Antlr4 lexer to include suffixes. This makes the formal lexical grammar (more closely) reflect the one implemented by the compiler.
ANTLR
apache-2.0
0x73/rust,rprichard/rust,pshc/rust,jashank/rust,aepsil0n/rust,kwantam/rust,untitaker/rust,GBGamer/rust,ktossell/rust,rprichard/rust,bombless/rust,mvdnes/rust,quornian/rust,cllns/rust,hauleth/rust,bombless/rust,carols10cents/rust,nwin/rust,bombless/rust,miniupnp/rust,GBGamer/rust,jroesch/rust,carols10cents/rust,zaeleus/rust,l0kod/rust,kimroen/rust,ebfull/rust,ejjeong/rust,miniupnp/rust,mahkoh/rust,rohitjoshi/rust,krzysz00/rust,kimroen/rust,robertg/rust,KokaKiwi/rust,bombless/rust-docs-chinese,jroesch/rust,reem/rust,mahkoh/rust,richo/rust,kwantam/rust,aneeshusa/rust,mahkoh/rust,gifnksm/rust,hauleth/rust,zubron/rust,mihneadb/rust,untitaker/rust,pshc/rust,kwantam/rust,robertg/rust,reem/rust,AerialX/rust,pshc/rust,krzysz00/rust,rohitjoshi/rust,aepsil0n/rust,GBGamer/rust,gifnksm/rust,ktossell/rust,0x73/rust,pshc/rust,dwillmer/rust,vhbit/rust,ejjeong/rust,zubron/rust,quornian/rust,AerialX/rust,mdinger/rust,reem/rust,sae-bom/rust,TheNeikos/rust,mahkoh/rust,0x73/rust,mihneadb/rust,zubron/rust,emk/rust,omasanori/rust,defuz/rust,ruud-v-a/rust,philyoon/rust,nwin/rust,jroesch/rust,bombless/rust,aidancully/rust,victorvde/rust,graydon/rust,sae-bom/rust,nwin/rust,emk/rust,XMPPwocky/rust,l0kod/rust,kimroen/rust,miniupnp/rust,avdi/rust,miniupnp/rust,ejjeong/rust,reem/rust,dinfuehr/rust,ktossell/rust,dinfuehr/rust,defuz/rust,mvdnes/rust,XMPPwocky/rust,sae-bom/rust,cllns/rust,dwillmer/rust,mdinger/rust,l0kod/rust,AerialX/rust-rt-minimal,kimroen/rust,defuz/rust,ruud-v-a/rust,jroesch/rust,seanrivera/rust,hauleth/rust,ktossell/rust,krzysz00/rust,nwin/rust,miniupnp/rust,jroesch/rust,andars/rust,nwin/rust,mdinger/rust,victorvde/rust,cllns/rust,mdinger/rust,vhbit/rust,miniupnp/rust,kimroen/rust,defuz/rust,defuz/rust,richo/rust,victorvde/rust,jashank/rust,vhbit/rust,cllns/rust,XMPPwocky/rust,reem/rust,hauleth/rust,carols10cents/rust,0x73/rust,aidancully/rust,mahkoh/rust,andars/rust,ruud-v-a/rust,dinfuehr/rust,richo/rust,andars/rust,philyoon/rust,nwin/rust,robertg/rust,ejjeong/rust,pshc/rust,aidancully/rust,KokaKiwi/rust,aneeshusa/rust,AerialX/rust,aepsil0n/rust,dwillmer/rust,robertg/rust,ktossell/rust,KokaKiwi/rust,zubron/rust,rprichard/rust,graydon/rust,krzysz00/rust,l0kod/rust,nwin/rust,AerialX/rust-rt-minimal,graydon/rust,rohitjoshi/rust,graydon/rust,jashank/rust,zaeleus/rust,rprichard/rust,dwillmer/rust,ebfull/rust,richo/rust,ebfull/rust,bombless/rust,ebfull/rust,ebfull/rust,AerialX/rust,emk/rust,seanrivera/rust,carols10cents/rust,carols10cents/rust,dinfuehr/rust,GBGamer/rust,avdi/rust,quornian/rust,quornian/rust,seanrivera/rust,rohitjoshi/rust,KokaKiwi/rust,bombless/rust,zubron/rust,TheNeikos/rust,mihneadb/rust,quornian/rust,zachwick/rust,zachwick/rust,ejjeong/rust,jashank/rust,ejjeong/rust,victorvde/rust,quornian/rust,GBGamer/rust,rprichard/rust,avdi/rust,mvdnes/rust,avdi/rust,zubron/rust,omasanori/rust,jroesch/rust,pshc/rust,mdinger/rust,victorvde/rust,zaeleus/rust,ktossell/rust,aneeshusa/rust,aneeshusa/rust,jashank/rust,graydon/rust,dwillmer/rust,0x73/rust,zaeleus/rust,rprichard/rust,pelmers/rust,mdinger/rust,TheNeikos/rust,quornian/rust,zachwick/rust,mahkoh/rust,kwantam/rust,sae-bom/rust,l0kod/rust,emk/rust,mvdnes/rust,dinfuehr/rust,zachwick/rust,zubron/rust,pelmers/rust,hauleth/rust,andars/rust,kwantam/rust,sae-bom/rust,vhbit/rust,GBGamer/rust,philyoon/rust,GBGamer/rust,sae-bom/rust,zachwick/rust,dinfuehr/rust,seanrivera/rust,aidancully/rust,rohitjoshi/rust,robertg/rust,vhbit/rust,krzysz00/rust,TheNeikos/rust,aepsil0n/rust,XMPPwocky/rust,jroesch/rust,AerialX/rust,jashank/rust,zubron/rust,pelmers/rust,aidancully/rust,KokaKiwi/rust,cllns/rust,victorvde/rust,rohitjoshi/rust,aneeshusa/rust,omasanori/rust,seanrivera/rust,omasanori/rust,mvdnes/rust,aepsil0n/rust,0x73/rust,XMPPwocky/rust,gifnksm/rust,untitaker/rust,pshc/rust,mihneadb/rust,philyoon/rust,aneeshusa/rust,AerialX/rust-rt-minimal,robertg/rust,mvdnes/rust,mihneadb/rust,vhbit/rust,ebfull/rust,TheNeikos/rust,zaeleus/rust,dwillmer/rust,miniupnp/rust,dwillmer/rust,philyoon/rust,defuz/rust,untitaker/rust,aepsil0n/rust,l0kod/rust,ruud-v-a/rust,reem/rust,gifnksm/rust,l0kod/rust,avdi/rust,aidancully/rust,jashank/rust,emk/rust,andars/rust,nwin/rust,AerialX/rust-rt-minimal,jashank/rust,andars/rust,untitaker/rust,jroesch/rust,emk/rust,KokaKiwi/rust,AerialX/rust,omasanori/rust,graydon/rust,mihneadb/rust,AerialX/rust-rt-minimal,pelmers/rust,ktossell/rust,gifnksm/rust,pelmers/rust,carols10cents/rust,dwillmer/rust,gifnksm/rust,kimroen/rust,richo/rust,GBGamer/rust,krzysz00/rust,AerialX/rust-rt-minimal,0x73/rust,vhbit/rust,pshc/rust,miniupnp/rust,vhbit/rust,kimroen/rust,richo/rust,avdi/rust,untitaker/rust,l0kod/rust,seanrivera/rust,omasanori/rust,emk/rust,cllns/rust,ruud-v-a/rust,philyoon/rust,pelmers/rust,kwantam/rust,hauleth/rust,zaeleus/rust,XMPPwocky/rust,TheNeikos/rust,ruud-v-a/rust,zachwick/rust
3cbeea95857b1bbee9744cf7b9024b7819b476c3
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE temporaryClause_ TABLE existClause_ tableName (createDefinitionClause_ | createLikeClause_) ; createIndex : CREATE (UNIQUE | FULLTEXT | SPATIAL)? INDEX indexName indexType_? ON tableName ; alterTable : ALTER TABLE tableName alterSpecifications_? ; dropTable : DROP TEMPORARY? TABLE (IF EXISTS)? tableName (COMMA_ tableName)* ; dropIndex : DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName ; truncateTable : TRUNCATE TABLE? tableName ; temporaryClause_ : TEMPORARY? ; existClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ createDefinitions_ RP_ ; createDefinitions_ : createDefinition_ (COMMA_ createDefinition_)* ; createDefinition_ : columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_ ; columnDefinition : columnName dataType (inlineDataType_* | generatedDataType_*) ; inlineDataType_ : commonDataTypeOption_ | AUTO_INCREMENT | DEFAULT (literals | expr) | COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT) | STORAGE (DISK | MEMORY | DEFAULT) ; commonDataTypeOption_ : primaryKey | UNIQUE KEY? | NOT? NULL | collateName_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_ ; checkConstraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)? ; referenceDefinition_ : REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)* ; referenceOption_ : RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT ; generatedDataType_ : commonDataTypeOption_ | (GENERATED ALWAYS)? AS expr | (VIRTUAL | STORED) ; indexDefinition_ : (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_* ; indexType_ : USING (BTREE | HASH) ; keyParts_ : LP_ keyPart_ (COMMA_ keyPart_)* RP_ ; keyPart_ : (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)? ; indexOption_ : KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE ; constraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_) ; primaryKeyOption_ : primaryKey indexType_? columnNames indexOption_* ; primaryKey : PRIMARY? KEY ; uniqueOption_ : UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_* ; foreignKeyOption_ : FOREIGN KEY indexName? columnNames referenceDefinition_ ; createLikeClause_ : LP_? LIKE tableName RP_? ; alterSpecifications_ : alterSpecification_ (COMMA_ alterSpecification_)* ; alterSpecification_ : tableOptions_ | addColumnSpecification | addIndexSpecification | addConstraintSpecification | ADD checkConstraintDefinition_ | DROP CHECK ignoredIdentifier_ | ALTER CHECK ignoredIdentifier_ NOT? ENFORCED | ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY) | ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT) | ALTER INDEX indexName (VISIBLE | INVISIBLE) | changeColumnSpecification | DEFAULT? characterSet_ collateClause_? | CONVERT TO characterSet_ collateClause_? | (DISABLE | ENABLE) KEYS | (DISCARD | IMPORT_) TABLESPACE | dropColumnSpecification | dropIndexSpecification | dropPrimaryKeySpecification | DROP FOREIGN KEY ignoredIdentifier_ | FORCE | LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE) | modifyColumnSpecification // TODO hongjun investigate ORDER BY col_name [, col_name] ... | ORDER BY columnName (COMMA_ columnName)* | renameColumnSpecification | renameIndexSpecification | renameTableSpecification_ | (WITHOUT | WITH) VALIDATION | ADD PARTITION LP_ partitionDefinition_ RP_ | DROP PARTITION ignoredIdentifiers_ | DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE | IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE | TRUNCATE PARTITION (ignoredIdentifiers_ | ALL) | COALESCE PARTITION NUMBER_ | REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_ | EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)? | ANALYZE PARTITION (ignoredIdentifiers_ | ALL) | CHECK PARTITION (ignoredIdentifiers_ | ALL) | OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL) | REBUILD PARTITION (ignoredIdentifiers_ | ALL) | REPAIR PARTITION (ignoredIdentifiers_ | ALL) | REMOVE PARTITIONING | UPGRADE PARTITIONING ; tableOptions_ : tableOption_ (COMMA_? tableOption_)* ; tableOption_ : AUTO_INCREMENT EQ_? NUMBER_ | AVG_ROW_LENGTH EQ_? NUMBER_ | DEFAULT? (characterSet_ | collateClause_) | CHECKSUM EQ_? NUMBER_ | COMMENT EQ_? STRING_ | COMPRESSION EQ_? STRING_ | CONNECTION EQ_? STRING_ | (DATA | INDEX) DIRECTORY EQ_? STRING_ | DELAY_KEY_WRITE EQ_? NUMBER_ | ENCRYPTION EQ_? STRING_ | ENGINE EQ_? ignoredIdentifier_ | INSERT_METHOD EQ_? (NO | FIRST | LAST) | KEY_BLOCK_SIZE EQ_? NUMBER_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | PACK_KEYS EQ_? (NUMBER_ | DEFAULT) | PASSWORD EQ_? STRING_ | ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT) | STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_) | STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_) | STATS_SAMPLE_PAGES EQ_? NUMBER_ | TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))? | UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_ ; addColumnSpecification : ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_) ; firstOrAfterColumn : FIRST | AFTER columnName ; addIndexSpecification : ADD indexDefinition_ ; addConstraintSpecification : ADD constraintDefinition_ ; changeColumnSpecification : CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn? ; dropColumnSpecification : DROP COLUMN? columnName ; dropIndexSpecification : DROP (INDEX | KEY) indexName ; dropPrimaryKeySpecification : DROP primaryKey ; modifyColumnSpecification : MODIFY COLUMN? columnDefinition firstOrAfterColumn? ; // TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column renameColumnSpecification : RENAME COLUMN columnName TO columnName ; // TODO hongjun: should support renameIndexSpecification on mysql renameIndexSpecification : RENAME (INDEX | KEY) indexName TO indexName ; // TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table renameTableSpecification_ : RENAME (TO | AS)? newTableName ; newTableName : identifier_ ; partitionDefinitions_ : LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_ ; partitionDefinition_ : PARTITION identifier_ (VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))? partitionDefinitionOption_* (LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)? ; partitionLessThanValue_ : LP_ (expr | partitionValueList_) RP_ | MAXVALUE ; partitionValueList_ : literals (COMMA_ literals)* ; partitionDefinitionOption_ : STORAGE? ENGINE EQ_? identifier_ | COMMENT EQ_? STRING_ | DATA DIRECTORY EQ_? STRING_ | INDEX DIRECTORY EQ_? STRING_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | TABLESPACE EQ_? identifier_ ; subpartitionDefinition_ : SUBPARTITION identifier_ partitionDefinitionOption_* ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createSpecification_ TABLE notExistClause_ tableName (createDefinitionClause_ | createLikeClause_) ; createIndex : CREATE (UNIQUE | FULLTEXT | SPATIAL)? INDEX indexName indexType_? ON tableName ; alterTable : ALTER TABLE tableName alterSpecifications_? ; dropTable : DROP TEMPORARY? TABLE (IF EXISTS)? tableName (COMMA_ tableName)* ; dropIndex : DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName ; truncateTable : TRUNCATE TABLE? tableName ; createSpecification_ : TEMPORARY? ; notExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ createDefinitions_ RP_ ; createDefinitions_ : createDefinition_ (COMMA_ createDefinition_)* ; createDefinition_ : columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_ ; columnDefinition : columnName dataType (inlineDataType_* | generatedDataType_*) ; inlineDataType_ : commonDataTypeOption_ | AUTO_INCREMENT | DEFAULT (literals | expr) | COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT) | STORAGE (DISK | MEMORY | DEFAULT) ; commonDataTypeOption_ : primaryKey | UNIQUE KEY? | NOT? NULL | collateName_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_ ; checkConstraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)? ; referenceDefinition_ : REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)* ; referenceOption_ : RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT ; generatedDataType_ : commonDataTypeOption_ | (GENERATED ALWAYS)? AS expr | (VIRTUAL | STORED) ; indexDefinition_ : (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_* ; indexType_ : USING (BTREE | HASH) ; keyParts_ : LP_ keyPart_ (COMMA_ keyPart_)* RP_ ; keyPart_ : (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)? ; indexOption_ : KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE ; constraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_) ; primaryKeyOption_ : primaryKey indexType_? columnNames indexOption_* ; primaryKey : PRIMARY? KEY ; uniqueOption_ : UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_* ; foreignKeyOption_ : FOREIGN KEY indexName? columnNames referenceDefinition_ ; createLikeClause_ : LP_? LIKE tableName RP_? ; alterSpecifications_ : alterSpecification_ (COMMA_ alterSpecification_)* ; alterSpecification_ : tableOptions_ | addColumnSpecification | addIndexSpecification | addConstraintSpecification | ADD checkConstraintDefinition_ | DROP CHECK ignoredIdentifier_ | ALTER CHECK ignoredIdentifier_ NOT? ENFORCED | ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY) | ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT) | ALTER INDEX indexName (VISIBLE | INVISIBLE) | changeColumnSpecification | DEFAULT? characterSet_ collateClause_? | CONVERT TO characterSet_ collateClause_? | (DISABLE | ENABLE) KEYS | (DISCARD | IMPORT_) TABLESPACE | dropColumnSpecification | dropIndexSpecification | dropPrimaryKeySpecification | DROP FOREIGN KEY ignoredIdentifier_ | FORCE | LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE) | modifyColumnSpecification // TODO hongjun investigate ORDER BY col_name [, col_name] ... | ORDER BY columnName (COMMA_ columnName)* | renameColumnSpecification | renameIndexSpecification | renameTableSpecification_ | (WITHOUT | WITH) VALIDATION | ADD PARTITION LP_ partitionDefinition_ RP_ | DROP PARTITION ignoredIdentifiers_ | DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE | IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE | TRUNCATE PARTITION (ignoredIdentifiers_ | ALL) | COALESCE PARTITION NUMBER_ | REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_ | EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)? | ANALYZE PARTITION (ignoredIdentifiers_ | ALL) | CHECK PARTITION (ignoredIdentifiers_ | ALL) | OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL) | REBUILD PARTITION (ignoredIdentifiers_ | ALL) | REPAIR PARTITION (ignoredIdentifiers_ | ALL) | REMOVE PARTITIONING | UPGRADE PARTITIONING ; tableOptions_ : tableOption_ (COMMA_? tableOption_)* ; tableOption_ : AUTO_INCREMENT EQ_? NUMBER_ | AVG_ROW_LENGTH EQ_? NUMBER_ | DEFAULT? (characterSet_ | collateClause_) | CHECKSUM EQ_? NUMBER_ | COMMENT EQ_? STRING_ | COMPRESSION EQ_? STRING_ | CONNECTION EQ_? STRING_ | (DATA | INDEX) DIRECTORY EQ_? STRING_ | DELAY_KEY_WRITE EQ_? NUMBER_ | ENCRYPTION EQ_? STRING_ | ENGINE EQ_? ignoredIdentifier_ | INSERT_METHOD EQ_? (NO | FIRST | LAST) | KEY_BLOCK_SIZE EQ_? NUMBER_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | PACK_KEYS EQ_? (NUMBER_ | DEFAULT) | PASSWORD EQ_? STRING_ | ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT) | STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_) | STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_) | STATS_SAMPLE_PAGES EQ_? NUMBER_ | TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))? | UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_ ; addColumnSpecification : ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_) ; firstOrAfterColumn : FIRST | AFTER columnName ; addIndexSpecification : ADD indexDefinition_ ; addConstraintSpecification : ADD constraintDefinition_ ; changeColumnSpecification : CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn? ; dropColumnSpecification : DROP COLUMN? columnName ; dropIndexSpecification : DROP (INDEX | KEY) indexName ; dropPrimaryKeySpecification : DROP primaryKey ; modifyColumnSpecification : MODIFY COLUMN? columnDefinition firstOrAfterColumn? ; // TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column renameColumnSpecification : RENAME COLUMN columnName TO columnName ; // TODO hongjun: should support renameIndexSpecification on mysql renameIndexSpecification : RENAME (INDEX | KEY) indexName TO indexName ; // TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table renameTableSpecification_ : RENAME (TO | AS)? newTableName ; newTableName : identifier_ ; partitionDefinitions_ : LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_ ; partitionDefinition_ : PARTITION identifier_ (VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))? partitionDefinitionOption_* (LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)? ; partitionLessThanValue_ : LP_ (expr | partitionValueList_) RP_ | MAXVALUE ; partitionValueList_ : literals (COMMA_ literals)* ; partitionDefinitionOption_ : STORAGE? ENGINE EQ_? identifier_ | COMMENT EQ_? STRING_ | DATA DIRECTORY EQ_? STRING_ | INDEX DIRECTORY EQ_? STRING_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | TABLESPACE EQ_? identifier_ ; subpartitionDefinition_ : SUBPARTITION identifier_ partitionDefinitionOption_* ;
rename to Specification
rename to Specification
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere