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
494f5c5edd607c283f5a789ca9f4c48eea84bf68
webidl/WebIDL.g4
webidl/WebIDL.g4
/* BSD License Copyright (c) 2013, 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://dev.w3.org/2006/webapi/WebIDL/ Web IDL (Second Edition) W3C Editor's Draft 14 January 2013 */ 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 | exception | enum_ | typedef | implementsStatement ; callbackOrInterface : 'callback' callbackRestOrInterface | interface_ ; callbackRestOrInterface : callbackRest | interface_ ; interface_ : 'interface' IDENTIFIER_WEBIDL inheritance '{' interfaceMembers '}' ';' ; partial : 'partial' partialDefinition ; partialDefinition : partialInterface | partialDictionary ; partialInterface : 'interface' IDENTIFIER_WEBIDL '{' interfaceMembers '}' ';' ; interfaceMembers : extendedAttributeList interfaceMember interfaceMembers | /* empty */ ; interfaceMember : const_ | attributeOrOperationOrIterator ; dictionary : 'dictionary' IDENTIFIER_WEBIDL inheritance '{' dictionaryMembers '}' ';' ; dictionaryMembers : extendedAttributeList dictionaryMember dictionaryMembers | /* empty */ ; dictionaryMember : type IDENTIFIER_WEBIDL default_ ';' ; partialDictionary : 'dictionary' IDENTIFIER_WEBIDL '{' dictionaryMembers '}' ';' ; default_ : '=' defaultValue | /* empty */ ; defaultValue : constValue | STRING_WEBIDL ; exception : 'exception' IDENTIFIER_WEBIDL inheritance '{' exceptionMembers '}' ';' ; exceptionMembers : extendedAttributeList exceptionMember exceptionMembers | /* empty */ ; inheritance : ':' IDENTIFIER_WEBIDL | /* empty */ ; enum_ : 'enum' IDENTIFIER_WEBIDL '{' enumValueList '}' ';' ; enumValueList : STRING_WEBIDL enumValues ; enumValues : ',' STRING_WEBIDL enumValues | /* empty */ ; callbackRest : IDENTIFIER_WEBIDL '=' returnType '(' argumentList ')' ';' ; typedef : 'typedef' extendedAttributeList 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' ; attributeOrOperationOrIterator : serializer | qualifier attributeOroperationRest | attribute | operationOrIterator ; serializer : 'serializer' serializerRest ; serializerRest : operationRest | '=' serializationPattern | /* empty */ ; serializationPattern : '{' serializationPatternMap '}' | '[' serializationPatternList ']' | IDENTIFIER_WEBIDL ; serializationPatternMap : 'getter' | 'inherit' identifiers | IDENTIFIER_WEBIDL identifiers | /* empty */ ; serializationPatternList : 'getter' | IDENTIFIER_WEBIDL identifiers | /* empty */ ; identifiers : ',' IDENTIFIER_WEBIDL identifiers | /* empty */ ; qualifier : 'static' | 'stringifier' ; attributeOroperationRest : attributeRest | returnType operationRest | ';' ; attribute : inherit attributeRest ; attributeRest : readOnly 'attribute' type IDENTIFIER_WEBIDL ';' ; inherit : 'inherit' | /* empty */ ; readOnly : 'readonly' | /* empty */ ; operationOrIterator : returnType operationOrIteratorRest | specialOperation ; specialOperation : special specials returnType operationRest ; specials : special specials | /* empty */ ; special : 'getter' | 'setter' | 'creator' | 'deleter' | 'legacycaller' ; operationOrIteratorRest : iteratorRest | operationRest ; iteratorRest : 'iterator' optionalIteratorInterfaceOrObject ';' ; optionalIteratorInterfaceOrObject : optionalIteratorInterface | 'object' ; optionalIteratorInterface : '=' IDENTIFIER_WEBIDL | /* empty */ ; 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 */ ; exceptionMember : const_ | exceptionField ; exceptionField : type IDENTIFIER_WEBIDL ';' ; 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 | '-' | '.' | '...' | ':' | ';' | '<' | '=' | '>' | '?' | 'ByteString' | 'Date' | 'DOMString' | 'Infinity' | 'NaN' | 'RegExp' | 'any' | 'boolean' | 'byte' | 'double' | 'false' | 'float' | 'long' | 'null' | 'object' | 'octet' | 'or' | 'optional' | 'sequence' | 'short' | 'true' | 'unsigned' | 'void' | argumentNameKeyword ; argumentNameKeyword : 'attribute' | 'callback' | 'const' | 'creator' | 'deleter' | 'dictionary' | 'enum' | 'exception' | 'getter' | 'implements' | 'inherit' | 'interface' | 'legacycaller' | 'partial' | 'serializer' | 'setter' | 'static' | 'stringifier' | 'typedef' | 'unrestricted' ; otherOrComma : other | ',' ; type : singleType | unionType typeSuffix ; singleType : nonAnyType | 'any' typeSuffixStartingWithArray ; unionType : '(' unionMemberType 'or' unionMemberType unionMemberTypes ')' ; unionMemberType : nonAnyType | unionType typeSuffix | 'any' '[' ']' typeSuffix ; unionMemberTypes : 'or' unionMemberType unionMemberTypes | /* empty */ ; nonAnyType : primitiveType typeSuffix | 'ByteString' typeSuffix | 'DOMString' typeSuffix | IDENTIFIER_WEBIDL typeSuffix | 'sequence' '<' type '>' null_ | 'object' typeSuffix | 'Date' typeSuffix | 'RegExp' typeSuffix ; constType : primitiveType null_ | IDENTIFIER_WEBIDL null_ ; primitiveType : unsignedIntegerType | unrestrictedFloatType | 'boolean' | 'byte' | 'octet' ; unrestrictedFloatType : 'unrestricted' floatType | floatType ; floatType : 'FLOAT_WEBIDL' | 'double' ; unsignedIntegerType : 'unsigned' integerType | integerType ; integerType : 'short' | 'long' optionalLong ; optionalLong : 'long' | /* empty */ ; typeSuffix : '[' ']' typeSuffix | '?' typeSuffixStartingWithArray | /* empty */ ; typeSuffixStartingWithArray : '[' ']' typeSuffix | /* empty */ ; null_ : '?' | /* empty */ ; returnType : type | 'void' ; extendedAttributeNoArgs : IDENTIFIER_WEBIDL ; extendedAttributeArgList : IDENTIFIER_WEBIDL '(' argumentList ')' ; extendedAttributeIdent : IDENTIFIER_WEBIDL '=' IDENTIFIER_WEBIDL ; 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 ]+|[\t\n\r ]*(('/''/'~[\n\r]*|'/''\\'*(.|'\n')*?'\\'*'/')[\t\n\r ]*)+) -> skip ; // 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, 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://dev.w3.org/2006/webapi/WebIDL/ Web IDL (Second Edition) W3C Editor's Draft 24 January 2013 */ 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 | exception | enum_ | typedef | implementsStatement ; callbackOrInterface : 'callback' callbackRestOrInterface | interface_ ; callbackRestOrInterface : callbackRest | interface_ ; interface_ : 'interface' IDENTIFIER_WEBIDL inheritance '{' interfaceMembers '}' ';' ; partial : 'partial' partialDefinition ; partialDefinition : partialInterface | partialDictionary ; partialInterface : 'interface' IDENTIFIER_WEBIDL '{' interfaceMembers '}' ';' ; interfaceMembers : extendedAttributeList interfaceMember interfaceMembers | /* empty */ ; interfaceMember : const_ | attributeOrOperationOrIterator ; dictionary : 'dictionary' IDENTIFIER_WEBIDL inheritance '{' dictionaryMembers '}' ';' ; dictionaryMembers : extendedAttributeList dictionaryMember dictionaryMembers | /* empty */ ; dictionaryMember : type IDENTIFIER_WEBIDL default_ ';' ; partialDictionary : 'dictionary' IDENTIFIER_WEBIDL '{' dictionaryMembers '}' ';' ; default_ : '=' defaultValue | /* empty */ ; defaultValue : constValue | STRING_WEBIDL ; exception : 'exception' IDENTIFIER_WEBIDL inheritance '{' exceptionMembers '}' ';' ; exceptionMembers : extendedAttributeList exceptionMember exceptionMembers | /* empty */ ; inheritance : ':' IDENTIFIER_WEBIDL | /* empty */ ; enum_ : 'enum' IDENTIFIER_WEBIDL '{' enumValueList '}' ';' ; enumValueList : STRING_WEBIDL enumValues ; enumValues : ',' STRING_WEBIDL enumValues | /* empty */ ; callbackRest : IDENTIFIER_WEBIDL '=' returnType '(' argumentList ')' ';' ; typedef : 'typedef' extendedAttributeList 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' ; attributeOrOperationOrIterator : serializer | qualifier attributeOroperationRest | attribute | operationOrIterator ; serializer : 'serializer' serializerRest ; serializerRest : operationRest | '=' serializationPattern | /* empty */ ; serializationPattern : '{' serializationPatternMap '}' | '[' serializationPatternList ']' | IDENTIFIER_WEBIDL ; serializationPatternMap : 'getter' | 'inherit' identifiers | IDENTIFIER_WEBIDL identifiers | /* empty */ ; serializationPatternList : 'getter' | IDENTIFIER_WEBIDL identifiers | /* empty */ ; identifiers : ',' IDENTIFIER_WEBIDL identifiers | /* empty */ ; qualifier : 'static' | 'stringifier' ; attributeOroperationRest : attributeRest | returnType operationRest | ';' ; attribute : inherit attributeRest ; attributeRest : readOnly 'attribute' type IDENTIFIER_WEBIDL ';' ; inherit : 'inherit' | /* empty */ ; readOnly : 'readonly' | /* empty */ ; operationOrIterator : returnType operationOrIteratorRest | specialOperation ; specialOperation : special specials returnType operationRest ; specials : special specials | /* empty */ ; special : 'getter' | 'setter' | 'creator' | 'deleter' | 'legacycaller' ; operationOrIteratorRest : iteratorRest | operationRest ; iteratorRest : 'iterator' optionalIteratorInterfaceOrObject ';' ; optionalIteratorInterfaceOrObject : optionalIteratorInterface | 'object' ; optionalIteratorInterface : '=' IDENTIFIER_WEBIDL | /* empty */ ; 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 */ ; exceptionMember : const_ | exceptionField ; exceptionField : type IDENTIFIER_WEBIDL ';' ; 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 | '-' | '.' | '...' | ':' | ';' | '<' | '=' | '>' | '?' | 'ByteString' | 'Date' | 'DOMString' | 'Infinity' | 'NaN' | 'RegExp' | 'any' | 'boolean' | 'byte' | 'double' | 'false' | 'float' | 'long' | 'null' | 'object' | 'octet' | 'or' | 'optional' | 'sequence' | 'short' | 'true' | 'unsigned' | 'void' | argumentNameKeyword ; argumentNameKeyword : 'attribute' | 'callback' | 'const' | 'creator' | 'deleter' | 'dictionary' | 'enum' | 'exception' | 'getter' | 'implements' | 'inherit' | 'interface' | 'legacycaller' | 'partial' | 'serializer' | 'setter' | 'static' | 'stringifier' | 'typedef' | 'unrestricted' ; otherOrComma : other | ',' ; type : singleType | unionType typeSuffix ; singleType : nonAnyType | 'any' typeSuffixStartingWithArray ; unionType : '(' unionMemberType 'or' unionMemberType unionMemberTypes ')' ; unionMemberType : nonAnyType | unionType typeSuffix | 'any' '[' ']' typeSuffix ; unionMemberTypes : 'or' unionMemberType unionMemberTypes | /* empty */ ; nonAnyType : primitiveType typeSuffix | 'ByteString' typeSuffix | 'DOMString' typeSuffix | IDENTIFIER_WEBIDL typeSuffix | 'sequence' '<' type '>' null_ | 'object' typeSuffix | 'Date' typeSuffix | 'RegExp' typeSuffix ; constType : primitiveType null_ | IDENTIFIER_WEBIDL null_ ; primitiveType : unsignedIntegerType | unrestrictedFloatType | 'boolean' | 'byte' | 'octet' ; unrestrictedFloatType : 'unrestricted' floatType | floatType ; floatType : 'FLOAT_WEBIDL' | 'double' ; unsignedIntegerType : 'unsigned' integerType | integerType ; integerType : 'short' | 'long' optionalLong ; optionalLong : 'long' | /* empty */ ; typeSuffix : '[' ']' typeSuffix | '?' typeSuffixStartingWithArray | /* empty */ ; typeSuffixStartingWithArray : '[' ']' typeSuffix | /* empty */ ; null_ : '?' | /* empty */ ; returnType : type | 'void' ; extendedAttributeNoArgs : IDENTIFIER_WEBIDL ; extendedAttributeArgList : IDENTIFIER_WEBIDL '(' argumentList ')' ; extendedAttributeIdent : IDENTIFIER_WEBIDL '=' IDENTIFIER_WEBIDL ; 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 ]+|[\t\n\r ]*(('/''/'~[\n\r]*|'/''\\'*(.|'\n')*?'\\'*'/')[\t\n\r ]*)+) -> skip ; // Note: '/''/'~[\n\r]* instead of '/''/'.* (non-greedy because of wildcard). OTHER_WEBIDL : ~[\t\n\r 0-9A-Z_a-z] ;
Update to newest draft version.
Update to newest draft version.
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
62cf0091a869a4830fd9cb81e005c3f0447d1a53
sharding-jdbc-ddl-parser/src/main/resources/io/shardingsphere/parser/antlr/Keyword.g4
sharding-jdbc-ddl-parser/src/main/resources/io/shardingsphere/parser/antlr/Keyword.g4
lexer grammar Keyword; import Symbol; SELECT: S E L E C T; ALL: A L L; ANY: A N Y; DISTINCT: D I S T I N C T; FROM: F R O M; PARTITION: P A R T I T I O N; WHERE: W H E R E; GROUP: G R O U P; BY: B Y; ASC: A S C; DESC: D E S C; WITH: W I T H; RECURSIVE: R E C U R S I V E; ROLLUP: R O L L U P; HAVING: H A V I N G; WINDOW: W I N D O W; AS: A S; ORDER: O R D E R; LIMIT: L I M I T; OFFSET: O F F S E T; INTO: I N T O; ALTER: A L T E R; CREATE: C R E A T E; TEMPORARY: T E M P O R A R Y; TABLE: T A B L E; COLUMN: C O L U M N; ADD: A D D; DROP: D R O P; ENABLE: E N A B L E; DISABLE: D I S A B L E; CONSTRAINT: C O N S T R A I N T; UNIQUE: U N I Q U E; FULLTEXT: F U L L T E X T; FOREIGN: F O R E I G N; NONE: N O N E; MODIFY: M O D I F Y; RENAME: R E N A M E; VALIDATION: V A L I D A T I O N; IMPORT_: I M P O R T; TABLESPACE: T A B L E S P A C E; TRUNCATE: T R U N C A T E; ANALYZE: A N A L Y Z E; CHECK: C H E C K; OPTIMIZE: O P T I M I Z E; REBUILD: R E B U I L D; REPAIR: R E P A I R; REMOVE: R E M O V E; UPGRADE: U P G R A D E; TO: T O; COPY: C O P Y; PRIMARY: P R I M A R Y; KEYS: K E Y S; WITHOUT: W I T H O U T; COALESCE: C O A L E S C E; SET: S E T; FOR: F O R; UPDATE: U P D A T E; SHARE: S H A R E; OF: O F; NOWAIT: N O W A I T; LOCKED: L O C K E D; LOCK: L O C K; IN: I N; MODE: M O D E; INNER: I N N E R; CROSS: C R O S S; JOIN: J O I N; ON: O N; LEFT: L E F T; RIGHT: R I G H T; OUTER: O U T E R; NATURAL: N A T U R A L; USING: U S I N G; USE: U S E; INDEX: I N D E X; KEY: K E Y; IGNORE: I G N O R E; FORCE: F O R C E; UNION: U N I O N; DEFAULT: D E F A U L T; DELETE: D E L E T E; QUICK: Q U I C K; INSERT: I N S E R T; VALUES: V A L U E S; VALUE: V A L U E; DUPLICATE: D U P L I C A T E; EXISTS: E X I S T S; IS: I S; AND: A N D; OR: O R; XOR: X O R; NOT: N O T; BETWEEN: B E T W E E N; NULL: N U L L; TRUE:T R U E; FALSE : F A L S E; UNKNOWN: U N K N O W N; SOUNDS: S O U N D S; LIKE: L I K E; DIV: D I V; MOD: M O D; BINARY: B I N A R Y; ROW: R O W; ESCAPE: E S C A P E; REGEXP: R E G E X P; DATE: D A T E; TIME: T I M E; TIMESTAMP:TIME S T A M P; CASE: C A S E; WHEN: W H E N; THEN: T H E N; IF: I F; ELSE: E L S E; END: E N D; 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 ;
lexer grammar Keyword; import Symbol; SELECT: S E L E C T; ALL: A L L; ANY: A N Y; DISTINCT: D I S T I N C T; FROM: F R O M; PARTITION: P A R T I T I O N; WHERE: W H E R E; GROUP: G R O U P; BY: B Y; ASC: A S C; DESC: D E S C; WITH: W I T H; RECURSIVE: R E C U R S I V E; ROLLUP: R O L L U P; HAVING: H A V I N G; WINDOW: W I N D O W; AS: A S; ORDER: O R D E R; LIMIT: L I M I T; OFFSET: O F F S E T; INTO: I N T O; ALTER: A L T E R; CREATE: C R E A T E; TEMPORARY: T E M P O R A R Y; TABLE: T A B L E; COLUMN: C O L U M N; ADD: A D D; DROP: D R O P; ENABLE: E N A B L E; DISABLE: D I S A B L E; CONSTRAINT: C O N S T R A I N T; UNIQUE: U N I Q U E; FULLTEXT: F U L L T E X T; FOREIGN: F O R E I G N; NONE: N O N E; MODIFY: M O D I F Y; RENAME: R E N A M E; VALIDATION: V A L I D A T I O N; IMPORT_: I M P O R T; TABLESPACE: T A B L E S P A C E; TRUNCATE: T R U N C A T E; ANALYZE: A N A L Y Z E; CHECK: C H E C K; OPTIMIZE: O P T I M I Z E; REBUILD: R E B U I L D; REPAIR: R E P A I R; REMOVE: R E M O V E; UPGRADE: U P G R A D E; TO: T O; COPY: C O P Y; PRIMARY: P R I M A R Y; KEYS: K E Y S; WITHOUT: W I T H O U T; COALESCE: C O A L E S C E; SET: S E T; FOR: F O R; UPDATE: U P D A T E; SHARE: S H A R E; OF: O F; NOWAIT: N O W A I T; LOCKED: L O C K E D; LOCK: L O C K; IN: I N; MODE: M O D E; INNER: I N N E R; CROSS: C R O S S; JOIN: J O I N; ON: O N; LEFT: L E F T; RIGHT: R I G H T; OUTER: O U T E R; NATURAL: N A T U R A L; USING: U S I N G; USE: U S E; INDEX: I N D E X; KEY: K E Y; IGNORE: I G N O R E; FORCE: F O R C E; UNION: U N I O N; DEFAULT: D E F A U L T; DELETE: D E L E T E; QUICK: Q U I C K; INSERT: I N S E R T; VALUES: V A L U E S; VALUE: V A L U E; DUPLICATE: D U P L I C A T E; EXISTS: E X I S T S; IS: I S; AND: A N D; OR: O R; XOR: X O R; NOT: N O T; BETWEEN: B E T W E E N; NULL: N U L L; TRUE:T R U E; FALSE : F A L S E; UNKNOWN: U N K N O W N; SOUNDS: S O U N D S; LIKE: L I K E; DIV: D I V; MOD: M O D; ROW: R O W; ESCAPE: E S C A P E; REGEXP: R E G E X P; CASE: C A S E; WHEN: W H E N; THEN: T H E N; IF: I F; ELSE: E L S E; END: E N D; BIT: B I T; TINYINT: T I N Y I N T; UNSIGNED: U N S I G N E D; ZEROFILL: Z E R O F I L L; SMALLINT: S M A L L I N T; MEDIUMINT: M E D I U M I N T; INT: I N T; INTEGER: I N T E G E R; BIGINT: B I G I N T; REAL: R E A L; DOUBLE: D O U B L E; FLOAT: F L O A T; DECIMAL: D E C I M A L; NUMERIC: N U M E R I C; DATE: D A T E; TIME: T I M E; TIMESTAMP: T I M E S T A M P; CURRENT_TIMESTAMP: C U R R E N T UL_ T I M E S T A M P; DATETIME: D A T E T I M E; YEAR: Y E A R; CHAR: C H A R; VARCHAR: V A R C H A R; BINARY: B I N A R Y; VARBINARY: V A R B I N A R Y; TINYBLOB: T I N Y B L O B; BLOB: B L O B; MEDIUMBLOB: M E D I U M B L O B; LONGBLOB: L O N G B L O B; TINYTEXT: T I N Y T E X T; TEXT: T E X T; MEDIUMTEXT: M E D I U M T E X T; LONGTEXT: L O N G T E X T; ENUM: E N U M; JSON: J S O N; REPLACE: R E P L A C E; 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 ;
add data type keyword
add data type keyword
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
d0c82768eb9ec99b6d6748f97036c5b861dc890b
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; private static readonly string errReservedChar = "'\u000B' (vertical tabulation) is a reserved character and is not allowed to be used!"; private static readonly string errVarDefReservedKw = "Can't use a reserved keyword as a variable name!"; private static readonly string errMissingSpaceBefore = "Missing space before "; private static readonly string errMissingSpaceAfter = "Missing space after "; } options { tokenVocab=VineLexer; } /* * Parser Rules */ passage : {ParseMode == EVineParseMode.EVAL_EXPR}? evalExprMode NL? EOF // active only if we're expr parse mode | block* NL? EOF | { NotifyErrorListeners(errReservedChar); } RESERVED_CHARS //| { 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 | text # directOutput // foobar | display # noOutput // {{ foo }} | controlStmt # noOutput // << open stmt >> something << close stmt >> | simpleStmtBlock # directOutput // << set foo = 0 >> | link # noOutput // [[label|link]] | BLOCK_COMMENT # directOutput // /* comment */ | LINE_COMMENT # directOutput // // inline comment ; text : TXT ; simpleStmtBlock : '<<' setStmt '>>' | '<<' unsetStmt '>>' | '<<' funcCall '>>' ; link : '[[' title=linkContent+ ']]' | '[[' title=linkContent+ '|' passageName=linkContent+ ']]' | '[[' title=linkContent+ '->' passageName=linkContent+ ']]' | '[[' passageName=linkContent+ '<-' title=linkContent+ ']]' ; linkContent : LINK_TEXT+ ; /** * 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)? endIfStmt # ifCtrlStmt | forStmt endForStmt # forCtrlStmt ; ifStmt : '<<' 'if' wsa expr '>>' block* ; elifStmt : '<<' 'elif' wsa expr '>>' block* ; elseStmt : '<<' 'else' '>>' block* ; endIfStmt : '<<' 'end' '>>' ; forStmt : '<<' 'for' wsa variable 'in' expr '>>' NL? block* //| '<<' 'for' wsa key=variable ',' val=variable 'in' expr '>>' NL? block* | '<<' 'for' wsa variable 'in' interval '>>' NL? block* ; endForStmt : '<<' 'end' '>>' ; 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 | { NotifyErrorListeners(errReservedChar); } ILLEGAL_STRING ; // 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 - 1).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 | TRUE | FALSE | NULL ; /* variable: ID # variableValue | variable Dot variable # combinedVariable // | ID[expr]+ ; postfixExpression : atom //should be ID (and maybe allow STRING too) | postfixExpression '[' expr ']' | postfixExpression '(' argumentExpressionList? ')' | postfixExpression '.' ID # attributeLookup | postfixExpression '++' | postfixExpression '--' ; */
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; private static readonly string errReservedChar = "'\u000B' (vertical tabulation) is a reserved character and is not allowed to be used!"; private static readonly string errVarDefReservedKw = "Can't use a reserved keyword as a variable name!"; private static readonly string errMissingSpaceBefore = "Missing space before "; private static readonly string errMissingSpaceAfter = "Missing space after "; } options { tokenVocab=VineLexer; } /* * Parser Rules */ passage : {ParseMode == EVineParseMode.EVAL_EXPR}? evalExprMode NL? EOF // active only if we're expr parse mode | block* NL? EOF | { NotifyErrorListeners(errReservedChar); } RESERVED_CHARS //| { 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 | text # directOutput // foobar | display # noOutput // {{ foo }} | controlStmt # noOutput // << open stmt >> something << close stmt >> | simpleStmtBlock # directOutput // << set foo = 0 >> | link # noOutput // [[label|link]] | BLOCK_COMMENT # directOutput // /* comment */ | LINE_COMMENT # directOutput // // inline comment ; text : TXT ; simpleStmtBlock : '<<' setStmt '>>' | '<<' unsetStmt '>>' | '<<' funcCall '>>' ; link : '[[' title=linkContent+ ']]' | '[[' title=linkContent+ '|' passageName=linkContent+ ']]' | '[[' title=linkContent+ '->' passageName=linkContent+ ']]' | '[[' passageName=linkContent+ '<-' title=linkContent+ ']]' ; linkContent : LINK_TEXT+ ; /** * 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)? endIfStmt # ifCtrlStmt | forStmt endForStmt # forCtrlStmt ; ifStmt : '<<' 'if' wsa expr '>>' block* ; elifStmt : '<<' 'elif' wsa expr '>>' block* ; elseStmt : '<<' 'else' '>>' block* ; endIfStmt : '<<' 'end' '>>' ; forStmt : '<<' 'for' wsa variable 'in' expr '>>' NL? block* //| '<<' 'for' wsa key=variable ',' val=variable 'in' expr '>>' NL? block* | '<<' 'for' wsa variable 'in' interval '>>' NL? block* ; endForStmt : '<<' 'end' '>>' ; 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 | { NotifyErrorListeners(errReservedChar); } ILLEGAL_STRING ; // 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 - 1).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 ; /* variable: ID # variableValue | variable Dot variable # combinedVariable // | ID[expr]+ ; postfixExpression : atom //should be ID (and maybe allow STRING too) | postfixExpression '[' expr ']' | postfixExpression '(' argumentExpressionList? ')' | postfixExpression '.' ID # attributeLookup | postfixExpression '++' | postfixExpression '--' ; */
add 'unset' to the 'reservedKeyword' rule
Grammar: add 'unset' to the 'reservedKeyword' rule
ANTLR
mit
julsam/VineScript
04735aef115efd3497afae0402b8edb74927a236
sickbay/sickbay.g4
sickbay/sickbay.g4
/* BSD License Copyright (c) 2019, 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 sickbay; sickbay : line* EOF ; line : intExpr stmt ';'? (':' stmt)* NL ; stmt : REM | ('LET' intVar '=' intExpr) | ('GOTO' INTCONST) | ('GOSUB' INTCONST) | ('RETURN' | 'END') | ('PRINT' (STRCONST | intExpr | intVar)) | ('PROLONG' INTCONST) | ('CUTSHORT') | ('DIM' 'RING' '(' intExpr ')') | ('INPUT' (intVar | 'CHR$' intVar)) ; intExpr : intVar | INTCONST | 'RND%' '(' intExpr ')' | '(' intExpr INTOP intExpr ')' ; intVar : IINTID ('(' intExpr ')')? ; INTOP : '+' | '-' | '*' | '/' ; IINTID : [A-Z] [A-Z0-9%]* ; INTCONST : [0-9] [0-9]* ; STRCONST : '"' ~ '"'* '"' ; NL : [\r\n] ; WS : [ \t\r\n] -> skip ; REM : 'REM' ([ \t]+) ~'\n'* ;
/* BSD License Copyright (c) 2019, 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 sickbay; sickbay : line* EOF ; line : intExpr stmt ';'? (':' stmt)* NL ; stmt : REM | ('LET' intVar '=' intExpr) | ('GOTO' INTCONST) | ('GOSUB' INTCONST) | ('RETURN' | 'END') | ('PRINT' (STRCONST | intExpr | intVar)) | ('PROLONG' INTCONST) | ('CUTSHORT') | ('DIM' 'RING' '(' intExpr ')') | ('INPUT' (intVar | 'CHR$' intVar)) ; intExpr : intVar | INTCONST | 'RND%' '(' intExpr ')' | '(' intExpr INTOP intExpr ')' ; intVar : IINTID ('(' intExpr ')')? ; INTOP : '+' | '-' | '*' | '/' ; IINTID : [A-Z] [A-Z0-9%]* ; INTCONST : [0-9] [0-9]* ; STRCONST : '"' ~ '"'* '"' ; NL : [\r\n]+ ; WS : [ \t\r\n] -> skip ; REM : 'REM' ([ \t]+) ~[\r\n]* ;
Fix sickbay/ for NL on various platforms.
Fix sickbay/ for NL on various platforms.
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
7c9652ddc5c9d690e47faf2dfc0c0b50618c4c90
watertemplate-engine/grammar.g4
watertemplate-engine/grammar.g4
prop_name_head : [a-zA-Z] ; prop_name_body : '_' | [0-9] | prop_name_head ; prop_name : prop_name_head | prop_name_head prop_name ; id : prop_name | prop_name '.' id ; // --------------------------------------------- prop_eval : '~' id '~' ; if : '~if' id ':' statements ':~' | '~if' id ':' statements ':else:' statements ':~' ; for : '~for' prop_name 'in' id ':' statements ':~' | '~for' prop_name 'in' id ':' statements ':else:' statements ':~' ; text : Any string ; // --------------------------------------------- statement : prop_eval | if | for | text | ε ; statements : statement | statement statements ;
prop_name_head : [a-zA-Z] ; prop_name_body_char : '_' | [0-9] | prop_name_head ; prop_name_body : prop_name_body_char | prop_name_body_char prop_name_body prop_name : prop_name_head | prop_name_head prop_name_body ; id : prop_name | prop_name '.' id ; // --------------------------------------------- prop_eval : '~' id '~' ; if : '~if' id ':' statements ':~' | '~if' id ':' statements ':else:' statements ':~' ; for : '~for' prop_name 'in' id ':' statements ':~' | '~for' prop_name 'in' id ':' statements ':else:' statements ':~' ; text : Any string ; // --------------------------------------------- statement : prop_eval | if | for | text | ε ; statements : statement | statement statements ;
Update grammar.g4
Update grammar.g4
ANTLR
apache-2.0
tiagobento/watertemplate-engine,tiagobento/watertemplate-engine,codefacts/watertemplate-engine,codefacts/watertemplate-engine
b988eb855c8a513696866236ad2095ff3c9807f4
java/monasca-common-model/src/main/resources/monasca/common/model/alarm/AlarmExpression.g4
java/monasca-common-model/src/main/resources/monasca/common/model/alarm/AlarmExpression.g4
/* * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP * Copyright 2016 FUJITSU LIMITED * * 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 AlarmExpression; start : expression EOF ; expression : compoundIdentifier relational_operator literal # relationalExprFwd | function relational_operator literal ('times' repeat)? # relationalExprFuncFwd | expression and expression # andExpr | expression or expression # orExpr | '(' expression ')' # parenExpr ; function : functionType '(' compoundIdentifier (',' deterministic)? (',' period)? ')' ; relational_operator : lt | lte | gt | gte ; lt : LT_S | LT ; lte : LTE | LTE_S ; gt : GT | GT_S ; gte : GTE | GTE_S ; and : AND | AND_S ; or : OR | OR_S ; functionType : MIN | MAX | SUM | CNT | AVG | LAST ; primary : literal | compoundIdentifier ; compoundIdentifier : namespace ('{' (dimensionList)? '}')? ; namespace : txt ; dimensionList : dimension (',' dimension)* ; dimension : (txt)+ '=' (txt)+ ; keyword : LT | LTE | GT | GTE | AND | OR | MIN | MAX | SUM | CNT | AVG | LAST ; period : INTEGER ; deterministic : 'deterministic' ; literal : DECIMAL | INTEGER ; repeat : INTEGER ; txt : TXT | keyword | INTEGER | STRING ; LT : [lL][tT] ; LT_S : '<' ; LTE : [lL][tT][eE] ; LTE_S : '<=' ; GT : [gG][tT] ; GT_S : '>' ; GTE : [gG][tT][eE] ; GTE_S : '>=' ; AND : [aA][nN][dD] ; AND_S : '&&' ; OR : [oO][rR] ; OR_S : '||' ; MIN : [mM][iI][nN] ; MAX : [mM][aA][xX] ; SUM : [sS][uU][mM] ; CNT : [cC][oO][uU][nN][tT] ; AVG : [aA][vV][gG] ; LAST : [lL][aA][sS][tT] ; INTEGER : DIGIT+ ; DECIMAL : '-'?DIGIT+('.'DIGIT+)? ; TXT : ~('}' | '{' | '&' | '|' | '>' | '<' | '=' | ',' | ')' | '(' | ' ' | '"' )+ ; STRING : '"' .*? '"' ; fragment DIGIT : '\u0030'..'\u0039' // 0-9 ; WS : [ \t\r\n]+ -> skip ; FALL_THROUGH : . {if(true) {throw new IllegalArgumentException("IllegalCharacter: " + getText());}} ;
/* * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP * Copyright 2016 FUJITSU LIMITED * * 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 AlarmExpression; start : expression EOF ; expression : compoundIdentifier relational_operator literal # relationalExprFwd | function relational_operator literal ('times' repeat)? # relationalExprFuncFwd | expression and expression # andExpr | expression or expression # orExpr | '(' expression ')' # parenExpr ; function : functionType '(' compoundIdentifier (',' deterministic)? (',' period)? ')' ; relational_operator : lt | lte | gt | gte ; lt : LT_S | LT ; lte : LTE | LTE_S ; gt : GT | GT_S ; gte : GTE | GTE_S ; and : AND | AND_S ; or : OR | OR_S ; functionType : MIN | MAX | SUM | CNT | AVG | LAST ; primary : literal | compoundIdentifier ; compoundIdentifier : namespace ('{' (dimensionList)? '}')? ; namespace : txt ; dimensionList : dimension (',' dimension)* ; dimension : (txt)+ '=' (txt)+ ; keyword : LT | LTE | GT | GTE | AND | OR | MIN | MAX | SUM | CNT | AVG | LAST ; period : INTEGER ; deterministic : 'deterministic' ; literal : DECIMAL | INTEGER ; repeat : INTEGER ; txt : TXT | keyword | INTEGER | DECIMAL | STRING ; LT : [lL][tT] ; LT_S : '<' ; LTE : [lL][tT][eE] ; LTE_S : '<=' ; GT : [gG][tT] ; GT_S : '>' ; GTE : [gG][tT][eE] ; GTE_S : '>=' ; AND : [aA][nN][dD] ; AND_S : '&&' ; OR : [oO][rR] ; OR_S : '||' ; MIN : [mM][iI][nN] ; MAX : [mM][aA][xX] ; SUM : [sS][uU][mM] ; CNT : [cC][oO][uU][nN][tT] ; AVG : [aA][vV][gG] ; LAST : [lL][aA][sS][tT] ; INTEGER : DIGIT+ ; DECIMAL : '-'?DIGIT+('.'DIGIT+)? ; TXT : ~('}' | '{' | '&' | '|' | '>' | '<' | '=' | ',' | ')' | '(' | ' ' | '"' )+ ; STRING : '"' .*? '"' ; fragment DIGIT : '\u0030'..'\u0039' // 0-9 ; WS : [ \t\r\n]+ -> skip ; FALL_THROUGH : . {if(true) {throw new IllegalArgumentException("IllegalCharacter: " + getText());}} ;
Fix crash-loop in thresholder caused by floating point numbers used as dimension filter
Fix crash-loop in thresholder caused by floating point numbers used as dimension filter Example: avg(some_timer{quantile=0.99}) > 0.1) Changes: * add DECIMAL (floating point value) to allowed tokens for dimensions Without this fix, an alarm-definition like the above one once injected through the Python API will break the Java-ORM layer because the alarm-definition cannot be parsed by the generated ANTLR parser. As a consequence the thresholder worker will terminate, leading to a crash-cycle. I could not find a way to make the ORM-layer ignore non-parseable alarm-definitions. So maybe this fix should be complemented by an extension of the Python API that uses exactly the same ANTLR grammar to validate incoming alarm-definitions. Change-Id: Ibbd41e1b817ebadc74b1b4a677db898cfa173ccb
ANTLR
apache-2.0
stackforge/monasca-common,openstack/monasca-common,openstack/monasca-common,openstack/monasca-common,stackforge/monasca-common,stackforge/monasca-common
c7a33b1f01b572531bbbdc394cb2061f86694950
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,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
1e73800cc811873231cead0d6710bc65b5696a50
src/main/antlr/PythonLexer.g4
src/main/antlr/PythonLexer.g4
lexer grammar PythonLexer; tokens { INDENT, DEDENT, NEWLINE } DOT : '.'; ELLIPSIS : '...'; STAR : '*'; OPEN_PAREN : '('; CLOSE_PAREN : ')'; COMMA : ','; COLON : ':'; SEMI_COLON : ';'; POWER : '**'; ASSIGN : '='; OPEN_BRACK : '['; CLOSE_BRACK : ']'; OR_OP : '|'; XOR : '^'; AND_OP : '&'; LEFT_SHIFT : '<<'; RIGHT_SHIFT : '>>'; ADD : '+'; MINUS : '-'; DIV : '/'; MOD : '%'; IDIV : '//'; NOT_OP : '~'; OPEN_BRACE : '{'; CLOSE_BRACE : '}'; LESS_THAN : '<'; GREATER_THAN : '>'; EQUALS : '=='; GT_EQ : '>='; LT_EQ : '<='; NOT_EQ_1 : '<>'; NOT_EQ_2 : '!='; AT : '@'; ARROW : '->'; 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 : '//='; DEF : 'def'; RETURN : 'return'; RAISE : 'raise'; FROM : 'from'; IMPORT : 'import'; AS : 'as'; GLOBAL : 'global'; NONLOCAL : 'nonlocal'; ASSERT : 'assert'; IF : 'if'; ELIF : 'elif'; ELSE : 'else'; WHILE : 'while'; FOR : 'for'; IN : 'in'; TRY : 'try'; FINALLY : 'finally'; WITH : 'with'; EXCEPT : 'except'; LAMBDA : 'lambda'; OR : 'or'; AND : 'and'; NOT : 'not'; IS : 'is'; NONE : 'None'; TRUE : 'True'; FALSE : 'False'; CLASS : 'class'; YIELD : 'yield'; DEL : 'del'; PASS : 'pass'; CONTINUE : 'continue'; BREAK : 'break'; ASYNC : 'async'; AWAIT : 'await'; STRING_LITERAL : ( [rR] | [uU] | [fF] | ( [fF] [rR] ) | ( [rR] [fF] ) )? ( SHORT_STRING | LONG_STRING ) ; /// decimalinteger ::= nonzerodigit digit* | "0"+ DECIMAL_INTEGER : NON_ZERO_DIGIT DIGIT* | '0'+ ; /// octinteger ::= "0" ("o" | "O") octdigit+ OCT_INTEGER : '0' [oO] OCT_DIGIT+ ; /// hexinteger ::= "0" ("x" | "X") hexdigit+ HEX_INTEGER : '0' [xX] HEX_DIGIT+ ; /// bininteger ::= "0" ("b" | "B") bindigit+ BIN_INTEGER : '0' [bB] BIN_DIGIT+ ; /// floatnumber ::= pointfloat | exponentfloat FLOAT_NUMBER : POINT_FLOAT | EXPONENT_FLOAT ; /// imagnumber ::= (floatnumber | intpart) ("j" | "J") IMAG_NUMBER : ( FLOAT_NUMBER | INT_PART ) [jJ] ; NAME : ID_START ID_CONTINUE* ; PHYSICAL_NEWLINE : ('\r'? '\n' | '\r' | '\f') ; SKIP_ : ( SPACES | COMMENT ) -> skip ; LINE_JOINING : '\\' SPACES? PHYSICAL_NEWLINE? ; fragment SHORT_STRING : '\'' ( STRING_ESCAPE_SEQ | ~[\\\r\n\f'] )* '\'' | '"' ( STRING_ESCAPE_SEQ | ~[\\\r\n\f"] )* '"' ; /// longstring ::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""' fragment LONG_STRING : '\'\'\'' LONG_STRING_ITEM*? '\'\'\'' | '"""' LONG_STRING_ITEM*? '"""' ; fragment LONG_STRING_ITEM : LONG_STRING_CHAR | STRING_ESCAPE_SEQ ; fragment LONG_STRING_CHAR : ~'\\' ; fragment STRING_ESCAPE_SEQ : '\\' . ; /// nonzerodigit ::= "1"..."9" fragment NON_ZERO_DIGIT : [1-9] ; fragment DIGIT : [0-9] ; /// octdigit ::= "0"..."7" fragment OCT_DIGIT : [0-7] ; /// hexdigit ::= digit | "a"..."f" | "A"..."F" fragment HEX_DIGIT : [0-9a-fA-F] ; /// bindigit ::= "0" | "1" fragment BIN_DIGIT : [01] ; /// pointfloat ::= [intpart] fraction | intpart "." fragment POINT_FLOAT : INT_PART? FRACTION | INT_PART '.' ; /// exponentfloat ::= (intpart | pointfloat) exponent fragment EXPONENT_FLOAT : ( INT_PART | POINT_FLOAT ) EXPONENT ; /// intpart ::= digit+ fragment INT_PART : DIGIT+ ; /// fraction ::= "." digit+ fragment FRACTION : '.' DIGIT+ ; /// exponent ::= ("e" | "E") ["+" | "-"] digit+ fragment EXPONENT : [eE] [+-]? DIGIT+ ; fragment SPACES : [ \t]+ ; fragment COMMENT : '#' ~[\r\n\f]* ; fragment ID_START : [a-z] | [A-Z] ; fragment ID_CONTINUE : ID_START | [0-9] ;
lexer grammar PythonLexer; tokens { INDENT, DEDENT, NEWLINE } DOT : '.'; ELLIPSIS : '...'; STAR : '*'; OPEN_PAREN : '('; CLOSE_PAREN : ')'; COMMA : ','; COLON : ':'; SEMI_COLON : ';'; POWER : '**'; ASSIGN : '='; OPEN_BRACK : '['; CLOSE_BRACK : ']'; OR_OP : '|'; XOR : '^'; AND_OP : '&'; LEFT_SHIFT : '<<'; RIGHT_SHIFT : '>>'; ADD : '+'; MINUS : '-'; DIV : '/'; MOD : '%'; IDIV : '//'; NOT_OP : '~'; OPEN_BRACE : '{'; CLOSE_BRACE : '}'; LESS_THAN : '<'; GREATER_THAN : '>'; EQUALS : '=='; GT_EQ : '>='; LT_EQ : '<='; NOT_EQ_1 : '<>'; NOT_EQ_2 : '!='; AT : '@'; ARROW : '->'; 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 : '//='; DEF : 'def'; RETURN : 'return'; RAISE : 'raise'; FROM : 'from'; IMPORT : 'import'; AS : 'as'; GLOBAL : 'global'; NONLOCAL : 'nonlocal'; ASSERT : 'assert'; IF : 'if'; ELIF : 'elif'; ELSE : 'else'; WHILE : 'while'; FOR : 'for'; IN : 'in'; TRY : 'try'; FINALLY : 'finally'; WITH : 'with'; EXCEPT : 'except'; LAMBDA : 'lambda'; OR : 'or'; AND : 'and'; NOT : 'not'; IS : 'is'; NONE : 'None'; TRUE : 'True'; FALSE : 'False'; CLASS : 'class'; YIELD : 'yield'; DEL : 'del'; PASS : 'pass'; CONTINUE : 'continue'; BREAK : 'break'; ASYNC : 'async'; AWAIT : 'await'; STRING_LITERAL : ( [rR] | [uU] | [fF] | ( [fF] [rR] ) | ( [rR] [fF] ) )? ( SHORT_STRING | LONG_STRING ) ; /// decimalinteger ::= nonzerodigit digit* | "0"+ DECIMAL_INTEGER : NON_ZERO_DIGIT DIGIT* | '0'+ ; /// octinteger ::= "0" ("o" | "O") octdigit+ OCT_INTEGER : '0' [oO] OCT_DIGIT+ ; /// hexinteger ::= "0" ("x" | "X") hexdigit+ HEX_INTEGER : '0' [xX] HEX_DIGIT+ ; /// bininteger ::= "0" ("b" | "B") bindigit+ BIN_INTEGER : '0' [bB] BIN_DIGIT+ ; /// floatnumber ::= pointfloat | exponentfloat FLOAT_NUMBER : POINT_FLOAT | EXPONENT_FLOAT ; /// imagnumber ::= (floatnumber | intpart) ("j" | "J") IMAG_NUMBER : ( FLOAT_NUMBER | INT_PART ) [jJ] ; NAME : ID_START ID_CONTINUE* ; PHYSICAL_NEWLINE : ('\r'? '\n' | '\r' | '\f') ; SKIP_ : ( SPACES | COMMENT ) -> skip ; LINE_JOINING : '\\' SPACES? PHYSICAL_NEWLINE? ; fragment SHORT_STRING : '\'' ( STRING_ESCAPE_SEQ | ~[\\\r\n\f'] )* '\'' | '"' ( STRING_ESCAPE_SEQ | ~[\\\r\n\f"] )* '"' ; /// longstring ::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""' fragment LONG_STRING : '\'\'\'' LONG_STRING_ITEM*? '\'\'\'' | '"""' LONG_STRING_ITEM*? '"""' ; fragment LONG_STRING_ITEM : LONG_STRING_CHAR | STRING_ESCAPE_SEQ ; fragment LONG_STRING_CHAR : ~'\\' ; fragment STRING_ESCAPE_SEQ : '\\' . ; /// nonzerodigit ::= "1"..."9" fragment NON_ZERO_DIGIT : [1-9] ; fragment DIGIT : [0-9] ; /// octdigit ::= "0"..."7" fragment OCT_DIGIT : [0-7] ; /// hexdigit ::= digit | "a"..."f" | "A"..."F" fragment HEX_DIGIT : [0-9a-fA-F] ; /// bindigit ::= "0" | "1" fragment BIN_DIGIT : [01] ; /// pointfloat ::= [intpart] fraction | intpart "." fragment POINT_FLOAT : INT_PART? FRACTION | INT_PART '.' ; /// exponentfloat ::= (intpart | pointfloat) exponent fragment EXPONENT_FLOAT : ( INT_PART | POINT_FLOAT ) EXPONENT ; /// intpart ::= digit+ fragment INT_PART : DIGIT+ ; /// fraction ::= "." digit+ fragment FRACTION : '.' DIGIT+ ; /// exponent ::= ("e" | "E") ["+" | "-"] digit+ fragment EXPONENT : [eE] [+-]? DIGIT+ ; fragment SPACES : [ \t]+ ; fragment COMMENT : '#' ~[\r\n\f]* ; fragment ID_START : [a-z] | [A-Z] | '_' ; fragment ID_CONTINUE : ID_START | [0-9] ;
Add '_' to lexer ID
Add '_' to lexer ID
ANTLR
bsd-3-clause
yotchang4s/cafebabepy
cf359076efd862aa4eb23eccd5c99a07d78e7260
src/main/antlr4/Config.g4
src/main/antlr4/Config.g4
grammar Config; // [done] STRING lexer rule定义过于简单,不满足需求, 包括其中包含Quote(',")的String // [done] nested bool expression中的字段引用 // [done] nested bool expression // [done] Filter, Output 允许if else, 包含nested if..else // [done] 允许key不包含双引号 // [done] 允许多行配置没有","分割 // [done] 允许plugin中不包含任何配置 // notes: lexer rule vs parser rule // notes: don't let two lexer rule match the same token import BoolExpr; config : COMMENT* 'input' input_block COMMENT* 'filter' filter_block COMMENT* 'output' output_block COMMENT* EOF ; input_block : '{' (plugin | COMMENT)* '}' ; filter_block : '{' statement '}' ; output_block : '{' statement '}' ; statement : (plugin | if_statement | COMMENT)* ; if_statement : IF expression '{' statement '}' (ELSE IF expression '{' statement '}')* (ELSE '{' statement '}')? ; plugin : IDENTIFIER entries // : plugin_name entries ; entries : '{' (pair | COMMENT)* '}' ; // entries // : '{' pair (','? pair)* '}' // | '{' '}' // ; pair : IDENTIFIER '=' value ; array : '[' value (',' value)* ']' | '[' ']' ; value : DECIMAL | QUOTED_STRING // | entries | array | TRUE | FALSE | NULL ; COMMENT : '#' ~( '\r' | '\n' )* -> skip ; // double and single quoted string support fragment BSLASH : '\\'; fragment DQUOTE : '"'; fragment SQUOTE : '\''; fragment DQ_STRING_ESC : BSLASH ["\\/bfnrt] ; fragment SQ_STRING_ESC : BSLASH ['\\/bfnrt] ; fragment DQ_STRING : DQUOTE (DQ_STRING_ESC | ~["\\])* DQUOTE ; fragment SQ_STRING : SQUOTE (SQ_STRING_ESC | ~['\\])* SQUOTE ; QUOTED_STRING : DQ_STRING | SQ_STRING ; NULL : 'null' ; WS : [ \t\n\r]+ -> skip ;
grammar Config; // [done] STRING lexer rule定义过于简单,不满足需求, 包括其中包含Quote(',")的String // [done] nested bool expression中的字段引用 // [done] nested bool expression // [done] Filter, Output 允许if else, 包含nested if..else // [done] 允许key不包含双引号 // [done] 允许多行配置没有","分割 // [done] 允许plugin中不包含任何配置 // notes: lexer rule vs parser rule // notes: don't let two lexer rule match the same token import BoolExpr; config : COMMENT* 'input' input_block COMMENT* 'filter' filter_block COMMENT* 'output' output_block COMMENT* EOF ; input_block : '{' (plugin | COMMENT)* '}' ; filter_block : '{' statement* '}' ; output_block : '{' statement* '}' ; statement : plugin | if_statement | COMMENT ; if_statement : IF expression '{' statement* '}' (ELSE IF expression '{' statement* '}')* (ELSE '{' statement* '}')? ; plugin : IDENTIFIER entries // : plugin_name entries ; entries : '{' (pair | COMMENT)* '}' ; // entries // : '{' pair (','? pair)* '}' // | '{' '}' // ; pair : IDENTIFIER '=' value ; array : '[' value (',' value)* ']' | '[' ']' ; value : DECIMAL | QUOTED_STRING // | entries | array | TRUE | FALSE | NULL ; COMMENT : '#' ~( '\r' | '\n' )* -> skip ; // double and single quoted string support fragment BSLASH : '\\'; fragment DQUOTE : '"'; fragment SQUOTE : '\''; fragment DQ_STRING_ESC : BSLASH ["\\/bfnrt] ; fragment SQ_STRING_ESC : BSLASH ['\\/bfnrt] ; fragment DQ_STRING : DQUOTE (DQ_STRING_ESC | ~["\\])* DQUOTE ; fragment SQ_STRING : SQUOTE (SQ_STRING_ESC | ~['\\])* SQUOTE ; QUOTED_STRING : DQ_STRING | SQ_STRING ; NULL : 'null' ; WS : [ \t\n\r]+ -> skip ;
update parser rule
update parser rule
ANTLR
apache-2.0
InterestingLab/waterdrop,InterestingLab/waterdrop
61e42b424dd33fdb87a3a377c25d8b64ff3c8284
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.equals(".") || last.equals(",")) { seek(-1); setText(url.substring(0, url.length() - 1)); } } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' WS? {doHdr();} ; HEnd : ' '* '='* (LineBreak | ParBreak) {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')+ ; 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.equals(".") || last.equals(",")) { seek(-1); setText(url.substring(0, url.length() - 1)); } } public void breakOut() { resetFormatting(); ulistLevel = 0; olistLevel = 0; inHeader = false; intr = false; nowiki = false; cpp = false; html = false; java = false; xhtml = false; xml = false; } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' WS? {doHdr();} ; HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ; /* ***** 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 '---' '-'+? {breakOut();} ; /* ***** Tables ***** */ RowEnd : '|' LineBreak {intr}? {breakOut();} ; TdStart : '|' {breakOut(); intr=true;} ; ThStart : '|=' {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 : (('http' 's'? | 'ftp') '://' | 'mailto:') (~(' '|'\t'|'\r'|'\n'|'/'|'|')+ '/'?)+ {doUrl();}; WikiWords : (ALNUM+ ':')? (UPPER ((ALNUM|'.')* ALNUM)*) (UPPER ((ALNUM|'.')* ALNUM)*)+; /* ***** Macros ***** */ MacroSt : '<<' -> mode(MACRO) ; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t')+ ; 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) ;
Break out of lists properly upon exiting a block.
Break out of lists properly upon exiting a block.
ANTLR
apache-2.0
ashirley/reviki,strr/reviki,strr/reviki,ashirley/reviki,strr/reviki,CoreFiling/reviki,strr/reviki,ashirley/reviki,CoreFiling/reviki,strr/reviki,CoreFiling/reviki,CoreFiling/reviki,CoreFiling/reviki,ashirley/reviki,ashirley/reviki
1ddb133a8e241aa8a861d88f35a719498f422d23
src/grammars/org/antlr/intellij/plugin/parser/ANTLRv4Lexer.g4
src/grammars/org/antlr/intellij/plugin/parser/ANTLRv4Lexer.g4
/* * [The "BSD license"] * Copyright (c) 2012 Terence Parr * Copyright (c) 2012 Sam Harwell * 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 tokens */ lexer grammar ANTLRv4Lexer; tokens { TOKEN_REF, RULE_REF, LEXER_CHAR_SET } @members { /** Track whether we are inside of a rule and whether it is lexical parser. * _currentRuleType==Token.INVALID_TYPE means that we are outside of a rule. * At the first sign of a rule name reference and _currentRuleType==invalid, * we can assume that we are starting a parser rule. Similarly, seeing * a token reference when not already in rule means starting a token * rule. The terminating ';' of a rule, flips this back to invalid type. * * This is not perfect logic but works. For example, "grammar T;" means * that we start and stop a lexical rule for the "T;". Dangerous but works. * * The whole point of this state information is to distinguish * between [..arg actions..] and [charsets]. Char sets can only occur in * lexical rules and arg actions cannot occur. */ private int _currentRuleType = Token.INVALID_TYPE; public int getCurrentRuleType() { return _currentRuleType; } public void setCurrentRuleType(int ruleType) { this._currentRuleType = ruleType; } protected void handleBeginArgAction() { if (inLexerRule()) { pushMode(LexerCharSet); more(); } else { pushMode(ArgAction); more(); } } @Override public Token emit() { if (_type == ID) { String firstChar = _input.getText(Interval.of(_tokenStartCharIndex, _tokenStartCharIndex)); if (Character.isUpperCase(firstChar.charAt(0))) { _type = TOKEN_REF; } else { _type = RULE_REF; } if (_currentRuleType == Token.INVALID_TYPE) { // if outside of rule def _currentRuleType = _type; // set to inside lexer or parser rule } } else if (_type == SEMI) { // exit rule def _currentRuleType = Token.INVALID_TYPE; } return super.emit(); } private boolean inLexerRule() { return _currentRuleType == TOKEN_REF; } private boolean inParserRule() { // not used, but added for clarity return _currentRuleType == RULE_REF; } } DOC_COMMENT : '/**' .*? ('*/' | EOF) ; BLOCK_COMMENT : '/*' .*? ('*/' | EOF) -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ; DOUBLE_QUOTE_STRING_LITERAL : '"' ('\\' . | ~'"' )*? ('"' | EOF) ; BEGIN_ARG_ACTION : '[' {handleBeginArgAction();} ; BEGIN_ACTION : '{' -> more, pushMode(Action) ; // OPTIONS and TOKENS must also consume the opening brace that captures // their option block, as this is teh easiest way to parse it separate // to an ACTION block, despite it usingthe same {} delimiters. // OPTIONS : 'options' [ \t\f\n\r]* '{' ; TOKENS : 'tokens' [ \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' ; COLON : ':' ; COLONCOLON : '::' ; COMMA : ',' ; SEMI : ';' ; LPAREN : '(' ; RPAREN : ')' ; RARROW : '->' ; LT : '<' ; GT : '>' ; ASSIGN : '=' ; QUESTION : '?' ; STAR : '*' ; PLUS : '+' ; PLUS_ASSIGN : '+=' ; OR : '|' ; DOLLAR : '$' ; DOT : '.' ; RANGE : '..' ; AT : '@' ; POUND : '#' ; NOT : '~' ; RBRACE : '}' ; /** Allow unicode rule/token names */ ID : NameStartChar NameChar*; fragment NameChar : NameStartChar | '0'..'9' | '_' | '\u00B7' | '\u0300'..'\u036F' | '\u203F'..'\u2040' ; fragment NameStartChar : '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' ; // ignores | ['\u10000-'\uEFFFF] ; INT : [0-9]+ ; // 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 (as per Java basically). STRING_LITERAL : '\'' (ESC_SEQ | ~['\r\n\\])* '\'' ; UNTERMINATED_STRING_LITERAL : '\'' (ESC_SEQ | ~['\r\n\\])* ; // Any kind of escaped character that we can embed within ANTLR // literal strings. fragment ESC_SEQ : '\\' ( // The standard escaped character set such as tab, newline, etc. [btnfr"'\\] | // A Java style Unicode escape sequence UNICODE_ESC | // Invalid escape . | // Invalid escape at end of file EOF ) ; fragment UNICODE_ESC : 'u' (HEX_DIGIT (HEX_DIGIT (HEX_DIGIT HEX_DIGIT?)?)?)? ; fragment HEX_DIGIT : [0-9a-fA-F] ; WS : [ \t\r\n\f]+ -> channel(HIDDEN) ; // ----------------- // Illegal Character // // 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. // ERRCHAR : . -> channel(HIDDEN) ; mode ArgAction; // E.g., [int x, List<String> a[]] NESTED_ARG_ACTION : '[' -> more, pushMode(ArgAction) ; ARG_ACTION_ESCAPE : '\\' . -> more ; ARG_ACTION_STRING_LITERAL : ('"' ('\\' . | ~["\\])* '"')-> more ; ARG_ACTION_CHAR_LITERAL : ('"' '\\' . | ~["\\] '"') -> more ; ARG_ACTION : ']' -> popMode ; UNTERMINATED_ARG_ACTION // added this to return non-EOF token type here. EOF did something weird : EOF -> popMode ; ARG_ACTION_CHAR // must be last : . -> more ; // ---------------- // Action structure // // 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 {}. // This mode is recursive on matching a { mode Action; NESTED_ACTION : '{' -> more, pushMode(Action) ; ACTION_ESCAPE : '\\' . -> more ; ACTION_STRING_LITERAL : '"' ('\\' . | ~["\\])* '"' -> more ; ACTION_CHAR_LITERAL : ('"' '\\' . | ~["\\] '"') -> more ; ACTION_COMMENT : (BLOCK_COMMENT |LINE_COMMENT ) -> more ; ACTION : '}' { popMode(); if ( _modeStack.size()>0 ) more(); // keep scarfing until outermost } } ; UNTERMINATED_ACTION : EOF -> popMode ; ACTION_CHAR : . -> more ; mode LexerCharSet; LEXER_CHAR_SET_BODY : ( ~[\]\\] | '\\' . )+ -> more ; LEXER_CHAR_SET : ']' -> popMode ; UNTERMINATED_CHAR_SET : EOF -> popMode ;
/* * [The "BSD license"] * Copyright (c) 2012 Terence Parr * Copyright (c) 2012 Sam Harwell * 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 tokens */ lexer grammar ANTLRv4Lexer; tokens { TOKEN_REF, RULE_REF, LEXER_CHAR_SET } @members { /** Track whether we are inside of a rule and whether it is lexical parser. * _currentRuleType==Token.INVALID_TYPE means that we are outside of a rule. * At the first sign of a rule name reference and _currentRuleType==invalid, * we can assume that we are starting a parser rule. Similarly, seeing * a token reference when not already in rule means starting a token * rule. The terminating ';' of a rule, flips this back to invalid type. * * This is not perfect logic but works. For example, "grammar T;" means * that we start and stop a lexical rule for the "T;". Dangerous but works. * * The whole point of this state information is to distinguish * between [..arg actions..] and [charsets]. Char sets can only occur in * lexical rules and arg actions cannot occur. */ private int _currentRuleType = Token.INVALID_TYPE; public int getCurrentRuleType() { return _currentRuleType; } public void setCurrentRuleType(int ruleType) { this._currentRuleType = ruleType; } protected void handleBeginArgAction() { if (inLexerRule()) { pushMode(LexerCharSet); more(); } else { pushMode(ArgAction); more(); } } @Override public Token emit() { if (_type == ID) { String firstChar = _input.getText(Interval.of(_tokenStartCharIndex, _tokenStartCharIndex)); if (Character.isUpperCase(firstChar.charAt(0))) { _type = TOKEN_REF; } else { _type = RULE_REF; } if (_currentRuleType == Token.INVALID_TYPE) { // if outside of rule def _currentRuleType = _type; // set to inside lexer or parser rule } } else if (_type == SEMI) { // exit rule def _currentRuleType = Token.INVALID_TYPE; } return super.emit(); } private boolean inLexerRule() { return _currentRuleType == TOKEN_REF; } private boolean inParserRule() { // not used, but added for clarity return _currentRuleType == RULE_REF; } } DOC_COMMENT : '/**' .*? ('*/' | EOF) ; BLOCK_COMMENT : '/*' .*? ('*/' | EOF) -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ; BEGIN_ARG_ACTION : '[' {handleBeginArgAction();} ; BEGIN_ACTION : '{' -> more, pushMode(Action) ; // OPTIONS and TOKENS must also consume the opening brace that captures // their option block, as this is teh easiest way to parse it separate // to an ACTION block, despite it usingthe same {} delimiters. // OPTIONS : 'options' [ \t\f\n\r]* '{' ; TOKENS : 'tokens' [ \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' ; COLON : ':' ; COLONCOLON : '::' ; COMMA : ',' ; SEMI : ';' ; LPAREN : '(' ; RPAREN : ')' ; RARROW : '->' ; LT : '<' ; GT : '>' ; ASSIGN : '=' ; QUESTION : '?' ; STAR : '*' ; PLUS : '+' ; PLUS_ASSIGN : '+=' ; OR : '|' ; DOLLAR : '$' ; DOT : '.' ; RANGE : '..' ; AT : '@' ; POUND : '#' ; NOT : '~' ; RBRACE : '}' ; /** Allow unicode rule/token names */ ID : NameStartChar NameChar*; fragment NameChar : NameStartChar | '0'..'9' | '_' | '\u00B7' | '\u0300'..'\u036F' | '\u203F'..'\u2040' ; fragment NameStartChar : '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' ; // ignores | ['\u10000-'\uEFFFF] ; INT : [0-9]+ ; // 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 (as per Java basically). STRING_LITERAL : '\'' (ESC_SEQ | ~['\r\n\\])* '\'' ; UNTERMINATED_STRING_LITERAL : '\'' (ESC_SEQ | ~['\r\n\\])* ; // Any kind of escaped character that we can embed within ANTLR // literal strings. fragment ESC_SEQ : '\\' ( // The standard escaped character set such as tab, newline, etc. [btnfr"'\\] | // A Java style Unicode escape sequence UNICODE_ESC | // Invalid escape . | // Invalid escape at end of file EOF ) ; fragment UNICODE_ESC : 'u' (HEX_DIGIT (HEX_DIGIT (HEX_DIGIT HEX_DIGIT?)?)?)? ; fragment HEX_DIGIT : [0-9a-fA-F] ; WS : [ \t\r\n\f]+ -> channel(HIDDEN) ; // ----------------- // Illegal Character // // 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. // ERRCHAR : . -> channel(HIDDEN) ; mode ArgAction; // E.g., [int x, List<String> a[]] NESTED_ARG_ACTION : '[' -> more, pushMode(ArgAction) ; ARG_ACTION_ESCAPE : '\\' . -> more ; ARG_ACTION_STRING_LITERAL : ('"' ('\\' . | ~["\\])* '"')-> more ; ARG_ACTION_CHAR_LITERAL : ('"' '\\' . | ~["\\] '"') -> more ; ARG_ACTION : ']' -> popMode ; UNTERMINATED_ARG_ACTION // added this to return non-EOF token type here. EOF did something weird : EOF -> popMode ; ARG_ACTION_CHAR // must be last : . -> more ; // ---------------- // Action structure // // 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 {}. // This mode is recursive on matching a { mode Action; NESTED_ACTION : '{' -> more, pushMode(Action) ; ACTION_ESCAPE : '\\' . -> more ; ACTION_STRING_LITERAL : '"' ('\\' . | ~["\\])* '"' -> more ; ACTION_CHAR_LITERAL : ('"' '\\' . | ~["\\] '"') -> more ; ACTION_COMMENT : (BLOCK_COMMENT |LINE_COMMENT ) -> more ; ACTION : '}' { popMode(); if ( _modeStack.size()>0 ) more(); // keep scarfing until outermost } } ; UNTERMINATED_ACTION : EOF -> popMode ; ACTION_CHAR : . -> more ; mode LexerCharSet; LEXER_CHAR_SET_BODY : ( ~[\]\\] | '\\' . )+ -> more ; LEXER_CHAR_SET : ']' -> popMode ; UNTERMINATED_CHAR_SET : EOF -> popMode ;
Remove the DOUBLE_QUOTE_STRING_LITERAL rule since ANTLR 4 doesn't allow it anywhere
Remove the DOUBLE_QUOTE_STRING_LITERAL rule since ANTLR 4 doesn't allow it anywhere
ANTLR
bsd-3-clause
rojaster/intellij-plugin-v4,antlr/intellij-plugin-v4,parrt/intellij-plugin-v4,bjansen/intellij-plugin-v4,Maccimo/intellij-plugin-v4,consulo/consulo-antlr4,Maccimo/intellij-plugin-v4,sharwell/intellij-plugin-v4,bjansen/intellij-plugin-v4,antlr/intellij-plugin-v4,rojaster/intellij-plugin-v4,parrt/intellij-plugin-v4
21b0dee2c3c1a35da4b92a43f5912a940c03cac3
golang/Go/GoParser.g4
golang/Go/GoParser.g4
/* [The "BSD licence"] Copyright (c) 2017 Sasa Coh, Michał Błotniak Copyright (c) 2019 Ivan Kochurkin, [email protected], Positive Technologies Copyright (c) 2019 Dmitry Rassadin, [email protected],Positive Technologies All rights reserved. Copyright (c) 2021 Martin Mirchev, [email protected] 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 Go grammar for ANTLR 4 derived from the Go Language Specification https://golang.org/ref/spec */ parser grammar GoParser; options { tokenVocab = GoLexer; superClass = GoParserBase; } sourceFile: packageClause eos (importDecl eos)* ( (functionDecl | methodDecl | declaration) eos )* EOF; packageClause: PACKAGE packageName = IDENTIFIER; importDecl: IMPORT (importSpec | L_PAREN (importSpec eos)* R_PAREN); importSpec: alias = (DOT | IDENTIFIER)? importPath; importPath: string_; declaration: constDecl | typeDecl | varDecl; constDecl: CONST (constSpec | L_PAREN (constSpec eos)* R_PAREN); constSpec: identifierList (type_? ASSIGN expressionList)?; identifierList: IDENTIFIER (COMMA IDENTIFIER)*; expressionList: expression (COMMA expression)*; typeDecl: TYPE (typeSpec | L_PAREN (typeSpec eos)* R_PAREN); typeSpec: IDENTIFIER ASSIGN? type_; // Function declarations functionDecl: FUNC IDENTIFIER (signature block?); methodDecl: FUNC receiver IDENTIFIER ( signature block?); receiver: parameters; varDecl: VAR (varSpec | L_PAREN (varSpec eos)* R_PAREN); varSpec: identifierList ( type_ (ASSIGN expressionList)? | ASSIGN expressionList ); block: L_CURLY statementList? R_CURLY; statementList: (statement eos)+; statement: declaration | labeledStmt | simpleStmt | goStmt | returnStmt | breakStmt | continueStmt | gotoStmt | fallthroughStmt | block | ifStmt | switchStmt | selectStmt | forStmt | deferStmt; simpleStmt: sendStmt | incDecStmt | assignment | expressionStmt | shortVarDecl | emptyStmt; expressionStmt: expression; sendStmt: channel = expression RECEIVE expression; incDecStmt: expression (PLUS_PLUS | MINUS_MINUS); assignment: expressionList assign_op expressionList; assign_op: ( PLUS | MINUS | OR | CARET | STAR | DIV | MOD | LSHIFT | RSHIFT | AMPERSAND | BIT_CLEAR )? ASSIGN; shortVarDecl: identifierList DECLARE_ASSIGN expressionList; emptyStmt: SEMI; labeledStmt: IDENTIFIER COLON statement?; returnStmt: RETURN expressionList?; breakStmt: BREAK IDENTIFIER?; continueStmt: CONTINUE IDENTIFIER?; gotoStmt: GOTO IDENTIFIER; fallthroughStmt: FALLTHROUGH; deferStmt: DEFER expression; ifStmt: IF (simpleStmt SEMI)? expression block ( ELSE (ifStmt | block) )?; switchStmt: exprSwitchStmt | typeSwitchStmt; exprSwitchStmt: SWITCH (simpleStmt SEMI)? expression? L_CURLY exprCaseClause* R_CURLY; exprCaseClause: exprSwitchCase COLON statementList?; exprSwitchCase: CASE expressionList | DEFAULT; typeSwitchStmt: SWITCH (simpleStmt SEMI)? typeSwitchGuard L_CURLY typeCaseClause* R_CURLY; typeSwitchGuard: (IDENTIFIER DECLARE_ASSIGN)? primaryExpr DOT L_PAREN TYPE R_PAREN; typeCaseClause: typeSwitchCase COLON statementList?; typeSwitchCase: CASE typeList | DEFAULT; typeList: (type_ | NIL_LIT) (COMMA (type_ | NIL_LIT))*; selectStmt: SELECT L_CURLY commClause* R_CURLY; commClause: commCase COLON statementList?; commCase: CASE (sendStmt | recvStmt) | DEFAULT; recvStmt: (expressionList ASSIGN | identifierList DECLARE_ASSIGN)? recvExpr = expression; forStmt: FOR (expression | forClause | rangeClause)? block; forClause: initStmt = simpleStmt? SEMI expression? SEMI postStmt = simpleStmt?; rangeClause: ( expressionList ASSIGN | identifierList DECLARE_ASSIGN )? RANGE expression; goStmt: GO expression; type_: typeName | typeLit | L_PAREN type_ R_PAREN; typeName: qualifiedIdent | IDENTIFIER; typeLit: arrayType | structType | pointerType | functionType | interfaceType | sliceType | mapType | channelType; arrayType: L_BRACKET arrayLength R_BRACKET elementType; arrayLength: expression; elementType: type_; pointerType: STAR type_; interfaceType: INTERFACE L_CURLY ((methodSpec | typeName) eos)* R_CURLY; sliceType: L_BRACKET R_BRACKET elementType; // It's possible to replace `type` with more restricted typeLit list and also pay attention to nil maps mapType: MAP L_BRACKET type_ R_BRACKET elementType; channelType: (CHAN | CHAN RECEIVE | RECEIVE CHAN) elementType; methodSpec: { p.noTerminatorAfterParams(2) }? IDENTIFIER parameters result | IDENTIFIER parameters; functionType: FUNC signature; signature: { p.noTerminatorAfterParams(1) }? parameters result | parameters; result: parameters | type_; parameters: L_PAREN (parameterDecl (COMMA parameterDecl)* COMMA?)? R_PAREN; parameterDecl: identifierList? ELLIPSIS? type_; expression: primaryExpr | unaryExpr | expression mul_op = ( STAR | DIV | MOD | LSHIFT | RSHIFT | AMPERSAND | BIT_CLEAR ) expression | expression add_op = (PLUS | MINUS | OR | CARET) expression | expression rel_op = ( EQUALS | NOT_EQUALS | LESS | LESS_OR_EQUALS | GREATER | GREATER_OR_EQUALS ) expression | expression LOGICAL_AND expression | expression LOGICAL_OR expression; primaryExpr: operand | conversion | methodExpr | primaryExpr ( (DOT IDENTIFIER) | index | slice | typeAssertion | arguments ); unaryExpr: primaryExpr | unary_op = ( PLUS | MINUS | EXCLAMATION | CARET | STAR | AMPERSAND | RECEIVE ) expression; conversion: type_ L_PAREN expression COMMA? R_PAREN; operand: literal | operandName | L_PAREN expression R_PAREN; literal: basicLit | compositeLit | functionLit; basicLit: NIL_LIT | integer | string_ | FLOAT_LIT | IMAGINARY_LIT | RUNE_LIT; integer: DECIMAL_LIT | BINARY_LIT | OCTAL_LIT | HEX_LIT | IMAGINARY_LIT | RUNE_LIT; operandName: IDENTIFIER (DOT IDENTIFIER)?; qualifiedIdent: IDENTIFIER DOT IDENTIFIER; compositeLit: literalType literalValue; literalType: structType | arrayType | L_BRACKET ELLIPSIS R_BRACKET elementType | sliceType | mapType | typeName; literalValue: L_CURLY (elementList COMMA?)? R_CURLY; elementList: keyedElement (COMMA keyedElement)*; keyedElement: (key COLON)? element; key: IDENTIFIER | expression | literalValue; element: expression | literalValue; structType: STRUCT L_CURLY (fieldDecl eos)* R_CURLY; fieldDecl: ( { p.noTerminatorBetween(2) }? identifierList type_ | embeddedField ) tag = string_?; string_: RAW_STRING_LIT | INTERPRETED_STRING_LIT; embeddedField: STAR? typeName; functionLit: FUNC signature block; // function index: L_BRACKET expression R_BRACKET; slice: L_BRACKET ( expression? COLON expression? | expression? COLON expression COLON expression ) R_BRACKET; typeAssertion: DOT L_PAREN type_ R_PAREN; arguments: L_PAREN ( (expressionList | type_ (COMMA expressionList)?) ELLIPSIS? COMMA? )? R_PAREN; methodExpr: receiverType DOT IDENTIFIER; //receiverType: typeName | '(' ('*' typeName | receiverType) ')'; receiverType: type_; eos: SEMI | EOF | { p.lineTerminatorAhead() }? | { p.checkPreviousTokenText("}") }?;
/* [The "BSD licence"] Copyright (c) 2017 Sasa Coh, Michał Błotniak Copyright (c) 2019 Ivan Kochurkin, [email protected], Positive Technologies Copyright (c) 2019 Dmitry Rassadin, [email protected],Positive Technologies All rights reserved. Copyright (c) 2021 Martin Mirchev, [email protected] 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 Go grammar for ANTLR 4 derived from the Go Language Specification https://golang.org/ref/spec */ parser grammar GoParser; options { tokenVocab = GoLexer; superClass = GoParserBase; } sourceFile: packageClause eos (importDecl eos)* ( (functionDecl | methodDecl | declaration) eos )* EOF; packageClause: PACKAGE packageName = IDENTIFIER; importDecl: IMPORT (importSpec | L_PAREN (importSpec eos)* R_PAREN); importSpec: alias = (DOT | IDENTIFIER)? importPath; importPath: string_; declaration: constDecl | typeDecl | varDecl; constDecl: CONST (constSpec | L_PAREN (constSpec eos)* R_PAREN); constSpec: identifierList (type_? ASSIGN expressionList)?; identifierList: IDENTIFIER (COMMA IDENTIFIER)*; expressionList: expression (COMMA expression)*; typeDecl: TYPE (typeSpec | L_PAREN (typeSpec eos)* R_PAREN); typeSpec: IDENTIFIER ASSIGN? type_; // Function declarations functionDecl: FUNC IDENTIFIER (signature block?); methodDecl: FUNC receiver IDENTIFIER ( signature block?); receiver: parameters; varDecl: VAR (varSpec | L_PAREN (varSpec eos)* R_PAREN); varSpec: identifierList ( type_ (ASSIGN expressionList)? | ASSIGN expressionList ); block: L_CURLY statementList? R_CURLY; statementList: (statement eos)+; statement: declaration | labeledStmt | simpleStmt | goStmt | returnStmt | breakStmt | continueStmt | gotoStmt | fallthroughStmt | block | ifStmt | switchStmt | selectStmt | forStmt | deferStmt; simpleStmt: sendStmt | incDecStmt | assignment | expressionStmt | shortVarDecl | emptyStmt; expressionStmt: expression; sendStmt: channel = expression RECEIVE expression; incDecStmt: expression (PLUS_PLUS | MINUS_MINUS); assignment: expressionList assign_op expressionList; assign_op: ( PLUS | MINUS | OR | CARET | STAR | DIV | MOD | LSHIFT | RSHIFT | AMPERSAND | BIT_CLEAR )? ASSIGN; shortVarDecl: identifierList DECLARE_ASSIGN expressionList; emptyStmt: SEMI; labeledStmt: IDENTIFIER COLON statement?; returnStmt: RETURN expressionList?; breakStmt: BREAK IDENTIFIER?; continueStmt: CONTINUE IDENTIFIER?; gotoStmt: GOTO IDENTIFIER; fallthroughStmt: FALLTHROUGH; deferStmt: DEFER expression; ifStmt: IF (simpleStmt SEMI)? expression block ( ELSE (ifStmt | block) )?; switchStmt: exprSwitchStmt | typeSwitchStmt; exprSwitchStmt: SWITCH (simpleStmt SEMI)? expression? L_CURLY exprCaseClause* R_CURLY; exprCaseClause: exprSwitchCase COLON statementList?; exprSwitchCase: CASE expressionList | DEFAULT; typeSwitchStmt: SWITCH (simpleStmt SEMI)? typeSwitchGuard L_CURLY typeCaseClause* R_CURLY; typeSwitchGuard: (IDENTIFIER DECLARE_ASSIGN)? primaryExpr DOT L_PAREN TYPE R_PAREN; typeCaseClause: typeSwitchCase COLON statementList?; typeSwitchCase: CASE typeList | DEFAULT; typeList: (type_ | NIL_LIT) (COMMA (type_ | NIL_LIT))*; selectStmt: SELECT L_CURLY commClause* R_CURLY; commClause: commCase COLON statementList?; commCase: CASE (sendStmt | recvStmt) | DEFAULT; recvStmt: (expressionList ASSIGN | identifierList DECLARE_ASSIGN)? recvExpr = expression; forStmt: FOR (expression | forClause | rangeClause)? block; forClause: initStmt = simpleStmt? SEMI expression? SEMI postStmt = simpleStmt?; rangeClause: ( expressionList ASSIGN | identifierList DECLARE_ASSIGN )? RANGE expression; goStmt: GO expression; type_: typeName | typeLit | L_PAREN type_ R_PAREN; typeName: qualifiedIdent | IDENTIFIER; typeLit: arrayType | structType | pointerType | functionType | interfaceType | sliceType | mapType | channelType; arrayType: L_BRACKET arrayLength R_BRACKET elementType; arrayLength: expression; elementType: type_; pointerType: STAR type_; interfaceType: INTERFACE L_CURLY ((methodSpec | typeName) eos)* R_CURLY; sliceType: L_BRACKET R_BRACKET elementType; // It's possible to replace `type` with more restricted typeLit list and also pay attention to nil maps mapType: MAP L_BRACKET type_ R_BRACKET elementType; channelType: (CHAN | CHAN RECEIVE | RECEIVE CHAN) elementType; methodSpec: { p.noTerminatorAfterParams(2) }? IDENTIFIER parameters result | IDENTIFIER parameters; functionType: FUNC signature; signature: { p.noTerminatorAfterParams(1) }? parameters result | parameters; result: parameters | type_; parameters: L_PAREN (parameterDecl (COMMA parameterDecl)* COMMA?)? R_PAREN; parameterDecl: identifierList? ELLIPSIS? type_; expression: primaryExpr | unaryExpr | expression mul_op = ( STAR | DIV | MOD | LSHIFT | RSHIFT | AMPERSAND | BIT_CLEAR ) expression | expression add_op = (PLUS | MINUS | OR | CARET) expression | expression rel_op = ( EQUALS | NOT_EQUALS | LESS | LESS_OR_EQUALS | GREATER | GREATER_OR_EQUALS ) expression | expression LOGICAL_AND expression | expression LOGICAL_OR expression; primaryExpr: operand | conversion | methodExpr | primaryExpr ( (DOT IDENTIFIER) | index | slice | typeAssertion | arguments ); unaryExpr: primaryExpr | unary_op = ( PLUS | MINUS | EXCLAMATION | CARET | STAR | AMPERSAND | RECEIVE ) expression; conversion: type_ L_PAREN expression COMMA? R_PAREN; operand: literal | operandName | L_PAREN expression R_PAREN; literal: basicLit | compositeLit | functionLit; basicLit: NIL_LIT | integer | string_ | FLOAT_LIT | IMAGINARY_LIT | RUNE_LIT; integer: DECIMAL_LIT | BINARY_LIT | OCTAL_LIT | HEX_LIT | IMAGINARY_LIT | RUNE_LIT; operandName: IDENTIFIER (DOT IDENTIFIER)?; qualifiedIdent: IDENTIFIER DOT IDENTIFIER; compositeLit: literalType literalValue; literalType: structType | arrayType | L_BRACKET ELLIPSIS R_BRACKET elementType | sliceType | mapType | typeName; literalValue: L_CURLY (elementList COMMA?)? R_CURLY; elementList: keyedElement (COMMA keyedElement)*; keyedElement: (key COLON)? element; key: IDENTIFIER | expression | literalValue; element: expression | literalValue; structType: STRUCT L_CURLY (fieldDecl eos)* R_CURLY; fieldDecl: ( { p.noTerminatorBetween(2) }? identifierList type_ | embeddedField ) tag = string_?; string_: RAW_STRING_LIT | INTERPRETED_STRING_LIT; embeddedField: STAR? typeName; functionLit: FUNC signature block; // function index: L_BRACKET expression R_BRACKET; slice: L_BRACKET ( expression? COLON expression? | expression? COLON expression COLON expression ) R_BRACKET; typeAssertion: DOT L_PAREN type_ R_PAREN; arguments: L_PAREN ( (expressionList | type_ (COMMA expressionList)?) ELLIPSIS? COMMA? )? R_PAREN; methodExpr: receiverType DOT IDENTIFIER; //receiverType: typeName | '(' ('*' typeName | receiverType) ')'; receiverType: type_; eos: SEMI | EOF | { p.lineTerminatorAhead() }? | { p.checkPreviousTokenText("}") }? | { p.checkPreviousTokenText(")") }?;
adjust grammar for Go target
adjust grammar for Go target
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
30b20a8fdd3fee543dce4071fc42f89da60553c6
solidity/Solidity.g4
solidity/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 : '0x' 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/>. // Copied from https://solidity.readthedocs.io/en/latest/grammar.html grammar Solidity; sourceUnit : (pragmaDirective | importDirective | structDefinition | enumDefinition | contractDefinition)* EOF ; pragmaDirective : 'pragma' pragmaName pragmaValue ';' ; pragmaName : identifier ; pragmaValue : version | expression ; version : versionConstraint versionConstraint? ; versionConstraint : versionOperator? VersionLiteral ; versionOperator : '^' | '~' | '>=' | '>' | '<' | '<=' | '=' ; importDirective : 'import' StringLiteralFragment ('as' identifier)? ';' | 'import' ('*' | identifier) ('as' identifier)? 'from' StringLiteralFragment ';' | 'import' '{' importDeclaration ( ',' importDeclaration )* '}' 'from' StringLiteralFragment ';' ; importDeclaration : identifier ('as' identifier)? ; contractDefinition : 'abstract'? ( 'contract' | 'interface' | 'library' ) identifier ( 'is' inheritanceSpecifier (',' inheritanceSpecifier )* )? '{' contractPart* '}' ; inheritanceSpecifier : userDefinedTypeName ( '(' expressionList? ')' )? ; contractPart : stateVariableDeclaration | usingForDeclaration | structDefinition | modifierDefinition | functionDefinition | eventDefinition | enumDefinition ; stateVariableDeclaration : typeName ( PublicKeyword | InternalKeyword | PrivateKeyword | ConstantKeyword | ImmutableKeyword | overrideSpecifier )* identifier ('=' expression)? ';' ; overrideSpecifier : 'override' ( '(' userDefinedTypeName (',' userDefinedTypeName)* ')' )? ; usingForDeclaration : 'using' identifier 'for' ('*' | typeName) ';' ; structDefinition : 'struct' identifier '{' ( variableDeclaration ';' (variableDeclaration ';')* )? '}' ; modifierDefinition : 'modifier' identifier parameterList? ( VirtualKeyword | overrideSpecifier )* ( ';' | block ) ; functionDefinition : functionDescriptor parameterList modifierList returnParameters? ( ';' | block ) ; functionDescriptor : 'function' ( identifier | ReceiveKeyword | FallbackKeyword )? | ConstructorKeyword | FallbackKeyword | ReceiveKeyword ; returnParameters : 'returns' parameterList ; modifierList : ( modifierInvocation | stateMutability | ExternalKeyword | PublicKeyword | InternalKeyword | PrivateKeyword | VirtualKeyword | overrideSpecifier )* ; modifierInvocation : identifier ( '(' expressionList? ')' )? ; eventDefinition : 'event' identifier eventParameterList AnonymousKeyword? ';' ; enumDefinition : 'enum' identifier '{' enumValue? (',' enumValue)* '}' ; enumValue : identifier ; parameterList : '(' ( parameter (',' parameter)* )? ')' ; parameter : typeName storageLocation? identifier? ; eventParameterList : '(' ( eventParameter (',' eventParameter)* )? ')' ; eventParameter : typeName IndexedKeyword? identifier? ; variableDeclaration : typeName storageLocation? identifier ; typeName : elementaryTypeName | userDefinedTypeName | mapping | typeName '[' expression? ']' | functionTypeName ; userDefinedTypeName : identifier ( '.' identifier )* ; mapping : 'mapping' '(' (elementaryTypeName | userDefinedTypeName) '=>' typeName ')' ; functionTypeName : 'function' parameterList modifierList returnParameters? ; storageLocation : 'memory' | 'storage' | 'calldata'; stateMutability : PureKeyword | ConstantKeyword | ViewKeyword | PayableKeyword ; block : '{' statement* '}' ; statement : ifStatement | tryStatement | whileStatement | forStatement | block | inlineAssemblyStatement | doWhileStatement | continueStatement | breakStatement | returnStatement | throwStatement | emitStatement | simpleStatement ; expressionStatement : expression ';' ; ifStatement : 'if' '(' expression ')' statement ( 'else' statement )? ; tryStatement : 'try' expression returnParameters? block catchClause+ ; // In reality catch clauses still are not processed as below // the identifier can only be a set string: "Error". But plans // of the Solidity team include possible expansion so we'll // leave this as is, befitting with the Solidity docs. catchClause : 'catch' ( identifier? parameterList )? block ; whileStatement : 'while' '(' expression ')' statement ; forStatement : 'for' '(' ( simpleStatement | ';' ) ( expressionStatement | ';' ) expression? ')' statement ; simpleStatement : ( variableDeclarationStatement | expressionStatement ) ; inlineAssemblyStatement : 'assembly' StringLiteralFragment? assemblyBlock ; doWhileStatement : 'do' statement 'while' '(' expression ')' ';' ; continueStatement : 'continue' ';' ; breakStatement : 'break' ';' ; returnStatement : 'return' expression? ';' ; // throw is no longer supported by latest Solidity. throwStatement : 'throw' ';' ; emitStatement : 'emit' functionCall ';' ; // 'var' is no longer supported by latest Solidity. variableDeclarationStatement : ( 'var' identifierList | variableDeclaration | '(' variableDeclarationList ')' ) ( '=' expression )? ';'; variableDeclarationList : variableDeclaration? (',' variableDeclaration? )* ; identifierList : '(' ( identifier? ',' )* identifier? ')' ; elementaryTypeName : 'address' PayableKeyword? | '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 '[' expression? ':' expression? ']' | expression '.' identifier | expression '{' nameValueList '}' | expression '(' functionCallArguments ')' | PayableKeyword '(' expression ')' | '(' 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 ('[' ']')? | TypeKeyword | tupleExpression | typeNameExpression ('[' ']')? ; expressionList : expression (',' expression)* ; nameValueList : nameValue (',' nameValue)* ','? ; nameValue : identifier ':' expression ; functionCallArguments : '{' nameValueList? '}' | expressionList? ; functionCall : expression '(' functionCallArguments ')' ; tupleExpression : '(' ( expression? ( ',' expression? )* ) ')' | '[' ( expression ( ',' expression )* )? ']' ; typeNameExpression : elementaryTypeName | userDefinedTypeName ; assemblyItem : identifier | assemblyBlock | assemblyExpression | assemblyLocalDefinition | assemblyAssignment | assemblyStackAssignment | labelDefinition | assemblySwitch | assemblyFunctionDefinition | assemblyFor | assemblyIf | BreakKeyword | ContinueKeyword | LeaveKeyword | subAssembly | numberLiteral | stringLiteral | hexLiteral ; assemblyBlock : '{' assemblyItem* '}' ; assemblyExpression : assemblyCall | assemblyLiteral ; assemblyCall : ( 'return' | 'address' | 'byte' | identifier ) ( '(' assemblyExpression? ( ',' assemblyExpression )* ')' )? ; assemblyLocalDefinition : 'let' assemblyIdentifierList ( ':=' assemblyExpression )? ; assemblyAssignment : assemblyIdentifierList ':=' assemblyExpression ; assemblyIdentifierList : identifier ( ',' identifier )* ; assemblyStackAssignment : '=:' identifier ; labelDefinition : identifier ':' ; assemblySwitch : 'switch' assemblyExpression assemblyCase* ; assemblyCase : 'case' assemblyLiteral assemblyType? assemblyBlock | 'default' assemblyBlock ; assemblyFunctionDefinition : 'function' identifier '(' assemblyTypedVariableList? ')' assemblyFunctionReturns? assemblyBlock ; assemblyFunctionReturns : ( '-' '>' assemblyTypedVariableList ) ; assemblyFor : 'for' assemblyBlock assemblyExpression assemblyBlock assemblyBlock ; assemblyIf : 'if' assemblyExpression assemblyBlock ; assemblyLiteral : ( stringLiteral | DecimalNumber | HexNumber | hexLiteral | BooleanLiteral ) assemblyType? ; assemblyTypedVariableList : identifier assemblyType? ( ',' assemblyTypedVariableList )? ; assemblyType : ':' identifier ; subAssembly : 'assembly' identifier assemblyBlock ; numberLiteral : (DecimalNumber | HexNumber) NumberUnit? ; identifier : ('from' | 'calldata' | 'address' | Identifier) ; BooleanLiteral : 'true' | 'false' ; DecimalNumber : ( DecimalDigits | (DecimalDigits? '.' DecimalDigits) ) ( [eE] '-'? DecimalDigits )? ; fragment DecimalDigits : [0-9] ( '_'? [0-9] )* ; HexNumber : '0' [xX] HexDigits ; fragment HexDigits : HexCharacter ( '_'? HexCharacter )* ; NumberUnit : 'wei' | 'szabo' | 'finney' | 'ether' | 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'years' ; HexLiteralFragment : 'hex' (('"' HexDigits? '"') | ('\'' HexDigits? '\'')) ; hexLiteral : HexLiteralFragment+ ; fragment HexPair : HexCharacter HexCharacter ; fragment HexCharacter : [0-9A-Fa-f] ; ReservedKeyword : 'after' | 'case' | 'default' | 'final' | 'in' | 'inline' | 'let' | 'match' | 'null' | 'of' | 'relocatable' | 'static' | 'switch' | 'typeof' ; AnonymousKeyword : 'anonymous' ; BreakKeyword : 'break' ; ConstantKeyword : 'constant' ; ImmutableKeyword : 'immutable' ; ContinueKeyword : 'continue' ; LeaveKeyword : 'leave' ; ExternalKeyword : 'external' ; IndexedKeyword : 'indexed' ; InternalKeyword : 'internal' ; PayableKeyword : 'payable' ; PrivateKeyword : 'private' ; PublicKeyword : 'public' ; VirtualKeyword : 'virtual' ; PureKeyword : 'pure' ; TypeKeyword : 'type' ; ViewKeyword : 'view' ; ConstructorKeyword : 'constructor' ; FallbackKeyword : 'fallback' ; ReceiveKeyword : 'receive' ; Identifier : IdentifierStart IdentifierPart* ; fragment IdentifierStart : [a-zA-Z$_] ; fragment IdentifierPart : [a-zA-Z0-9$_] ; stringLiteral : StringLiteralFragment+ ; StringLiteralFragment : '"' DoubleQuotedStringCharacter* '"' | '\'' SingleQuotedStringCharacter* '\'' ; fragment DoubleQuotedStringCharacter : ~["\r\n\\] | ('\\' .) ; fragment SingleQuotedStringCharacter : ~['\r\n\\] | ('\\' .) ; VersionLiteral : [0-9]+ '.' [0-9]+ ('.' [0-9]+)? ; WS : [ \t\r\n\u000C]+ -> skip ; COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ;
update solidity grammar
feat(solidity): update solidity 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
bb7d5c05285141034f6738d8d3a4e4a07f7f18e2
projects/batfish/src/org/batfish/grammar/flatjuniper/FlatJuniper_bgp.g4
projects/batfish/src/org/batfish/grammar/flatjuniper/FlatJuniper_bgp.g4
parser grammar FlatJuniper_bgp; import FlatJuniper_common; options { tokenVocab = FlatJuniperLexer; } bfi6t_null : LABELED_UNICAST s_null_filler ; bfi6t_unicast : UNICAST bfi6t_unicast_tail ; bfi6t_unicast_tail : //intentional blank | bfi6ut_prefix_limit ; bfi6ut_prefix_limit : PREFIX_LIMIT s_null_filler ; bfit_flow : FLOW s_null_filler ; bfit_unicast : UNICAST bfit_unicast_tail ; bfit_unicast_tail : //intentional blank | bfiut_add_path | bfiut_prefix_limit | bfiut_rib_group ; bfiut_add_path : ADD_PATH RECEIVE ; bfiut_prefix_limit : PREFIX_LIMIT s_null_filler ; bfiut_rib_group : RIB_GROUP name = variable ; bft_inet : INET bft_inet_tail ; bft_inet_tail : bfit_flow | bfit_unicast ; bft_inet6 : INET6 bft_inet6_tail ; bft_inet6_tail : bfi6t_null | bfi6t_unicast ; bft_null : ( INET_VPN | INET6_VPN ) s_null_filler ; bmt_no_nexthop_change : NO_NEXTHOP_CHANGE ; bmt_ttl : TTL DEC ; bt_advertise_inactive : ADVERTISE_INACTIVE ; bt_as_override : AS_OVERRIDE ; bt_cluster : CLUSTER IP_ADDRESS ; bt_common : bt_advertise_inactive | bt_as_override | bt_cluster | bt_damping | bt_description | bt_export | bt_family | bt_import | bt_local_address | bt_local_as | bt_multihop | bt_multipath | bt_null | bt_path_selection | bt_peer_as | bt_remove_private | bt_type ; bt_damping : DAMPING ; bt_description : s_description ; bt_enable : ENABLE ; bt_export : EXPORT expr = policy_expression ; bt_family : FAMILY bt_family_tail ; bt_family_tail : bft_inet | bft_inet6 | bft_null ; bt_group : GROUP ( name = variable | WILDCARD ) bt_group_tail ; bt_group_tail : bt_common | bt_neighbor ; bt_import : IMPORT expr = policy_expression ; bt_local_address : LOCAL_ADDRESS ( IP_ADDRESS | IPV6_ADDRESS ) ; bt_local_as : LOCAL_AS bt_local_as_tail ; bt_local_as_tail : last_loops | last_number | last_private ; bt_multihop : MULTIHOP bt_multihop_tail ; bt_multihop_tail : // intentional blank | bmt_no_nexthop_change | bmt_ttl ; bt_multipath : MULTIPATH MULTIPLE_AS? ; bt_neighbor : NEIGHBOR ( IP_ADDRESS | IPV6_ADDRESS ) bt_neighbor_tail ; bt_neighbor_tail : // intentional blank | bt_common ; bt_null : ( AUTHENTICATION_KEY | BFD_LIVENESS_DETECTION | HOLD_TIME | LOG_UPDOWN | OUT_DELAY | TRACEOPTIONS ) s_null_filler ; bt_path_selection : PATH_SELECTION bt_path_selection_tail ; bt_path_selection_tail : pst_always_compare_med ; bt_peer_as : PEER_AS as = DEC ; bt_remove_private : 'remove-private' ; bt_type : TYPE ( EXTERNAL | INTERNAL ) ; last_loops : LOOPS DEC ; last_number : as = DEC ; last_private : PRIVATE ; pe_conjunction : OPEN_PAREN policy_expression DOUBLE_AMPERSAND policy_expression CLOSE_PAREN ; pe_disjunction : OPEN_PAREN policy_expression DOUBLE_PIPE policy_expression CLOSE_PAREN ; pe_nested : OPEN_PAREN policy_expression CLOSE_PAREN ; policy_expression : pe_conjunction | pe_disjunction | pe_nested | variable ; pst_always_compare_med : ALWAYS_COMPARE_MED ; s_protocols_bgp : BGP s_protocols_bgp_tail ; s_protocols_bgp_tail : bt_common | bt_enable | bt_group | bt_neighbor ;
parser grammar FlatJuniper_bgp; import FlatJuniper_common; options { tokenVocab = FlatJuniperLexer; } bfi6t_null : LABELED_UNICAST s_null_filler ; bfi6t_unicast : UNICAST bfi6t_unicast_tail ; bfi6t_unicast_tail : //intentional blank | bfi6ut_prefix_limit ; bfi6ut_prefix_limit : PREFIX_LIMIT s_null_filler ; bfit_flow : FLOW s_null_filler ; bfit_unicast : UNICAST bfit_unicast_tail ; bfit_unicast_tail : //intentional blank | bfiut_add_path | bfiut_prefix_limit | bfiut_rib_group ; bfiut_add_path : ADD_PATH RECEIVE ; bfiut_prefix_limit : PREFIX_LIMIT s_null_filler ; bfiut_rib_group : RIB_GROUP name = variable ; bft_inet : INET bft_inet_tail ; bft_inet_tail : bfit_flow | bfit_unicast ; bft_inet6 : INET6 bft_inet6_tail ; bft_inet6_tail : bfi6t_null | bfi6t_unicast ; bft_null : ( INET_VPN | INET6_VPN ) s_null_filler ; bmt_no_nexthop_change : NO_NEXTHOP_CHANGE ; bmt_ttl : TTL DEC ; bt_advertise_inactive : ADVERTISE_INACTIVE ; bt_as_override : AS_OVERRIDE ; bt_cluster : CLUSTER IP_ADDRESS ; bt_common : bt_advertise_inactive | bt_as_override | bt_cluster | bt_damping | bt_description | bt_export | bt_family | bt_import | bt_local_address | bt_local_as | bt_multihop | bt_multipath | bt_null | bt_path_selection | bt_peer_as | bt_remove_private | bt_type ; bt_damping : DAMPING ; bt_description : s_description ; bt_enable : ENABLE ; bt_export : EXPORT expr = policy_expression ; bt_family : FAMILY bt_family_tail ; bt_family_tail : bft_inet | bft_inet6 | bft_null ; bt_group : GROUP ( name = variable | WILDCARD ) bt_group_tail ; bt_group_tail : bt_common | bt_neighbor ; bt_import : IMPORT expr = policy_expression ; bt_local_address : LOCAL_ADDRESS ( IP_ADDRESS | IPV6_ADDRESS ) ; bt_local_as : LOCAL_AS bt_local_as_tail ; bt_local_as_tail : last_loops | last_number | last_private ; bt_multihop : MULTIHOP bt_multihop_tail ; bt_multihop_tail : // intentional blank | bmt_no_nexthop_change | bmt_ttl ; bt_multipath : MULTIPATH MULTIPLE_AS? ; bt_neighbor : NEIGHBOR ( IP_ADDRESS | IPV6_ADDRESS ) bt_neighbor_tail ; bt_neighbor_tail : // intentional blank | bt_common ; bt_null : ( AUTHENTICATION_KEY | BFD_LIVENESS_DETECTION | HOLD_TIME | LOG_UPDOWN | OUT_DELAY | TRACEOPTIONS ) s_null_filler ; bt_path_selection : PATH_SELECTION bt_path_selection_tail ; bt_path_selection_tail : pst_always_compare_med ; bt_peer_as : PEER_AS as = DEC ; bt_remove_private : 'remove-private' ; bt_type : TYPE ( EXTERNAL | INTERNAL ) ; last_loops : LOOPS DEC ; last_number : as = DEC ; last_private : PRIVATE ; pe_conjunction : OPEN_PAREN policy_expression ( DOUBLE_AMPERSAND policy_expression )+ CLOSE_PAREN ; pe_disjunction : OPEN_PAREN policy_expression ( DOUBLE_PIPE policy_expression )+ CLOSE_PAREN ; pe_nested : OPEN_PAREN policy_expression CLOSE_PAREN ; policy_expression : pe_conjunction | pe_disjunction | pe_nested | variable ; pst_always_compare_med : ALWAYS_COMPARE_MED ; s_protocols_bgp : BGP s_protocols_bgp_tail ; s_protocols_bgp_tail : bt_common | bt_enable | bt_group | bt_neighbor ;
allow multi-ary disjunctions and conjunctions in juniper policy expressions
allow multi-ary disjunctions and conjunctions in juniper policy expressions
ANTLR
apache-2.0
batfish/batfish,arifogel/batfish,dhalperi/batfish,intentionet/batfish,intentionet/batfish,intentionet/batfish,batfish/batfish,arifogel/batfish,arifogel/batfish,dhalperi/batfish,dhalperi/batfish,batfish/batfish,intentionet/batfish,intentionet/batfish
21abc4a2c9df6e99e47183b2b419f958f2565e93
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' ; 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) ; 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' 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) ; 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] ;
Add new keywords "a temp file" and "a temporary file"
Add new keywords "a temp file" and "a temporary file"
ANTLR
mit
tkob/yokohamaunit,tkob/yokohamaunit
2f793fe17876da89f5b48434dd53d212077dfe19
src/net/hillsdon/reviki/wiki/renderer/creole/parser/CreoleTokens.g4
src/net/hillsdon/reviki/wiki/renderer/creole/parser/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 cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = 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 ***** */ CellSep : '|' {resetFormatting();} ; TdStart : '|' {resetFormatting();} ; ThStart : '|=' {resetFormatting();} ; /* ***** 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 : '{{{' -> mode(PREFORMATTED_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') '://' (~(' '|'\t'|'\r'|'\n'|'/')+ '/'?)+ {doUrl();}; WikiWords : (ALNUM+ ':')? (UPPER ((ALNUM|'.')* ALNUM)*) (UPPER ((ALNUM|'.')* ALNUM)*)+; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t'|'\r'|'\n')+ -> skip ; fragment START : {start}? | LINE ; fragment LINE : ({getCharPositionInLine()==0}? WS? | LineBreak WS?); 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 PREFORMATTED_INLINE; AnyInlineText : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') -> mode(PREFORMATTED_BLOCK), more ; EndNoWikiInline : '}}}' (~'}' {seek(-1);} | EOF) -> mode(DEFAULT_MODE) ; mode PREFORMATTED_BLOCK; AnyText : . -> more ; EndNoWikiBlock : {getCharPositionInLine()==0}? '}}}' -> mode(DEFAULT_MODE) ; mode CODE_INLINE; AnyInlineCode : ~('\r'|'\n') -> more; OopsItsACodeBlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ; 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; AnyCode : . -> more ; 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; 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 ***** */ CellSep : '|' {resetFormatting();} ; TdStart : '|' {resetFormatting();} ; ThStart : '|=' {resetFormatting();} ; /* ***** 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') '://' (~(' '|'\t'|'\r'|'\n'|'/')+ '/'?)+ {doUrl();}; WikiWords : (ALNUM+ ':')? (UPPER ((ALNUM|'.')* ALNUM)*) (UPPER ((ALNUM|'.')* ALNUM)*)+; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t'|'\r'|'\n')+ -> skip ; fragment START : {start}? | LINE ; fragment LINE : ({getCharPositionInLine()==0}? WS? | LineBreak WS?); 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 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 : {getCharPositionInLine()==0}? '}}}' {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) ;
Handle NoWiki in exactly the same way as code
Handle NoWiki in exactly the same way as code
ANTLR
apache-2.0
CoreFiling/reviki,ashirley/reviki,CoreFiling/reviki,CoreFiling/reviki,strr/reviki,ashirley/reviki,strr/reviki,ashirley/reviki,CoreFiling/reviki,CoreFiling/reviki,ashirley/reviki,strr/reviki,strr/reviki,ashirley/reviki,strr/reviki
cfbf6e0ef7965fd0f9f46a4dd6f4ac4ba6ae5d57
projects/batfish/src/main/antlr4/org/batfish/grammar/flatjuniper/FlatJuniperParser.g4
projects/batfish/src/main/antlr4/org/batfish/grammar/flatjuniper/FlatJuniperParser.g4
parser grammar FlatJuniperParser; import FlatJuniper_applications, FlatJuniper_common, FlatJuniper_fabric, FlatJuniper_firewall, FlatJuniper_forwarding_options, FlatJuniper_interfaces, FlatJuniper_policy_options, FlatJuniper_protocols, FlatJuniper_routing_instances, FlatJuniper_security, FlatJuniper_snmp, FlatJuniper_system; options { superClass = 'org.batfish.grammar.BatfishParser'; tokenVocab = FlatJuniperLexer; } deactivate_line : DEACTIVATE deactivate_line_tail NEWLINE ; deactivate_line_tail : ( interface_id | ~NEWLINE )* ; flat_juniper_configuration : NEWLINE? ( deactivate_line | protect_line | set_line )+ NEWLINE? EOF ; protect_line : PROTECT ~NEWLINE* NEWLINE ; statement : s_common | s_logical_systems ; s_common : s_applications | apply_groups | s_fabric | s_firewall | s_forwarding_options | s_interfaces | s_null | s_policy_options | s_protocols | s_routing_instances | s_routing_options | s_security | s_snmp | s_system | s_vlans ; s_groups : GROUPS s_groups_named ; s_groups_named : name = variable s_groups_tail ; s_groups_tail : // intentional blank | statement ; s_logical_systems : LOGICAL_SYSTEMS ( name = variable | WILDCARD ) s_logical_systems_tail ; s_logical_systems_tail : // intentional blank | statement ; s_null : ( ( ACCESS | APPLY_MACRO | ETHERNET_SWITCHING_OPTIONS | MULTI_CHASSIS | POE | SWITCH_OPTIONS | VIRTUAL_CHASSIS ) null_filler ) | ri_null ; s_version : VERSION VERSION_STRING ; s_vlans : // intentional blank | VLANS s_vlans_named ; s_vlans_named : name = variable s_vlans_tail ; s_vlans_tail : // intentional blank | vlt_description | vlt_filter | vlt_l3_interface | vlt_vlan_id ; set_line : SET set_line_tail NEWLINE ; set_line_tail : s_groups | statement | s_version ; vlt_description : DESCRIPTION M_Description_DESCRIPTION ; vlt_filter : FILTER ( INPUT | OUTPUT ) name = variable ; vlt_l3_interface : L3_INTERFACE interface_id ; vlt_vlan_id : VLAN_ID name = variable ;
parser grammar FlatJuniperParser; import FlatJuniper_applications, FlatJuniper_common, FlatJuniper_fabric, FlatJuniper_firewall, FlatJuniper_forwarding_options, FlatJuniper_interfaces, FlatJuniper_policy_options, FlatJuniper_protocols, FlatJuniper_routing_instances, FlatJuniper_security, FlatJuniper_snmp, FlatJuniper_system; options { superClass = 'org.batfish.grammar.BatfishParser'; tokenVocab = FlatJuniperLexer; } deactivate_line : DEACTIVATE deactivate_line_tail NEWLINE ; deactivate_line_tail : ( interface_id | ~NEWLINE )* ; flat_juniper_configuration : NEWLINE? ( deactivate_line | protect_line | set_line )+ NEWLINE? EOF ; protect_line : PROTECT ~NEWLINE* NEWLINE ; statement : s_common | s_logical_systems ; s_common : s_applications | apply_groups | s_fabric | s_firewall | s_forwarding_options | s_interfaces | s_null | s_policy_options | s_protocols | s_routing_instances | s_routing_options | s_security | s_snmp | s_system | s_vlans ; s_groups : GROUPS s_groups_named ; s_groups_named : name = variable s_groups_tail ; s_groups_tail : // intentional blank | statement ; s_logical_systems : LOGICAL_SYSTEMS ( name = variable | WILDCARD ) s_logical_systems_tail ; s_logical_systems_tail : // intentional blank | statement ; s_null : ( ( ACCESS | APPLY_MACRO | ETHERNET_SWITCHING_OPTIONS | MULTI_CHASSIS | POE | SWITCH_OPTIONS | VIRTUAL_CHASSIS ) null_filler ) | ri_null ; s_version : VERSION VERSION_STRING ; s_vlans : VLANS ( apply | s_vlans_named ) ; s_vlans_named : name = variable s_vlans_tail ; s_vlans_tail : // intentional blank | vlt_description | vlt_filter | vlt_l3_interface | vlt_vlan_id ; set_line : SET set_line_tail NEWLINE ; set_line_tail : s_groups | statement | s_version ; vlt_description : DESCRIPTION M_Description_DESCRIPTION ; vlt_filter : FILTER ( INPUT | OUTPUT ) name = variable ; vlt_l3_interface : L3_INTERFACE interface_id ; vlt_vlan_id : VLAN_ID name = variable ;
stop flatjuniper s_vlan rule incorrectly allowing blank 'set' line
stop flatjuniper s_vlan rule incorrectly allowing blank 'set' line
ANTLR
apache-2.0
intentionet/batfish,dhalperi/batfish,intentionet/batfish,batfish/batfish,batfish/batfish,arifogel/batfish,intentionet/batfish,dhalperi/batfish,intentionet/batfish,batfish/batfish,arifogel/batfish,arifogel/batfish,intentionet/batfish,dhalperi/batfish
8234fdc9680a8ada7de13ebcb708c406c5992d48
parser/Cel.g4
parser/Cel.g4
// Common Expression Language grammar for C++ // Based on Java grammar with the following changes: // - rename grammar from CEL to Cel to generate C++ style compatible names. grammar Cel; // Grammar Rules // ============= start : e=expr EOF ; expr : e=conditionalOr (op='?' e1=conditionalOr ':' e2=expr)? ; conditionalOr : e=conditionalAnd (ops+='||' e1+=conditionalAnd)* ; conditionalAnd : e=relation (ops+='&&' e1+=relation)* ; relation : calc | relation op=('<'|'<='|'>='|'>'|'=='|'!='|'in') relation ; calc : unary | calc op=('*'|'/'|'%') calc | calc op=('+'|'-') calc ; unary : member # MemberExpr | (ops+='!')+ member # LogicalNot | (ops+='-')+ member # Negate ; member : primary # PrimaryExpr | member op='.' id=IDENTIFIER (open='(' args=exprList? ')')? # SelectOrCall | member op='[' index=expr ']' # Index | member op='{' entries=fieldInitializerList? ','? '}' # CreateMessage ; primary : leadingDot='.'? id=IDENTIFIER (op='(' args=exprList? ')')? # IdentOrGlobalCall | '(' e=expr ')' # Nested | op='[' elems=exprList? ','? ']' # CreateList | op='{' entries=mapInitializerList? ','? '}' # CreateStruct | literal # ConstantLiteral ; exprList : e+=expr (',' e+=expr)* ; fieldInitializerList : fields+=IDENTIFIER cols+=':' values+=expr (',' fields+=IDENTIFIER cols+=':' values+=expr)* ; mapInitializerList : keys+=expr cols+=':' values+=expr (',' keys+=expr cols+=':' values+=expr)* ; literal : sign=MINUS? tok=NUM_INT # Int | tok=NUM_UINT # Uint | sign=MINUS? tok=NUM_FLOAT # Double | tok=STRING # String | tok=BYTES # Bytes | tok=CELTRUE # BoolTrue | tok=CELFALSE # BoolFalse | tok=NUL # Null ; // Lexer Rules // =========== EQUALS : '=='; NOT_EQUALS : '!='; LESS : '<'; LESS_EQUALS : '<='; GREATER_EQUALS : '>='; GREATER : '>'; LOGICAL_AND : '&&'; LOGICAL_OR : '||'; LBRACKET : '['; RPRACKET : ']'; LBRACE : '{'; RBRACE : '}'; LPAREN : '('; RPAREN : ')'; DOT : '.'; COMMA : ','; MINUS : '-'; EXCLAM : '!'; QUESTIONMARK : '?'; COLON : ':'; PLUS : '+'; STAR : '*'; SLASH : '/'; PERCENT : '%'; CELTRUE : 'true'; CELFALSE : 'false'; NUL : 'null'; fragment BACKSLASH : '\\'; fragment LETTER : 'A'..'Z' | 'a'..'z' ; fragment DIGIT : '0'..'9' ; fragment EXPONENT : ('e' | 'E') ( '+' | '-' )? DIGIT+ ; fragment HEXDIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ; fragment RAW : 'r' | 'R'; fragment ESC_SEQ : ESC_CHAR_SEQ | ESC_BYTE_SEQ | ESC_UNI_SEQ | ESC_OCT_SEQ ; fragment ESC_CHAR_SEQ : BACKSLASH ('a'|'b'|'f'|'n'|'r'|'t'|'v'|'"'|'\''|'\\'|'?'|'`') ; fragment ESC_OCT_SEQ : BACKSLASH ('0'..'3') ('0'..'7') ('0'..'7') ; fragment ESC_BYTE_SEQ : BACKSLASH ( 'x' | 'X' ) HEXDIGIT HEXDIGIT ; fragment ESC_UNI_SEQ : BACKSLASH 'u' HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT | BACKSLASH 'U' HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT ; WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ -> channel(HIDDEN) ; COMMENT : '//' (~'\n')* -> channel(HIDDEN) ; NUM_FLOAT : ( DIGIT+ ('.' DIGIT+) EXPONENT? | DIGIT+ EXPONENT | '.' DIGIT+ EXPONENT? ) ; NUM_INT : ( DIGIT+ | '0x' HEXDIGIT+ ); NUM_UINT : DIGIT+ ( 'u' | 'U' ) | '0x' HEXDIGIT+ ( 'u' | 'U' ) ; STRING : '"' (ESC_SEQ | ~('\\'|'"'|'\n'|'\r'))* '"' | '\'' (ESC_SEQ | ~('\\'|'\''|'\n'|'\r'))* '\'' | '"""' (ESC_SEQ | ~('\\'))*? '"""' | '\'\'\'' (ESC_SEQ | ~('\\'))*? '\'\'\'' | RAW '"' ~('"'|'\n'|'\r')* '"' | RAW '\'' ~('\''|'\n'|'\r')* '\'' | RAW '"""' .*? '"""' | RAW '\'\'\'' .*? '\'\'\'' ; BYTES : ('b' | 'B') STRING; IDENTIFIER : (LETTER | '_') ( LETTER | DIGIT | '_')*;
// Common Expression Language grammar for C++ // Based on Java grammar with the following changes: // - rename grammar from CEL to Cel to generate C++ style compatible names. grammar Cel; // Grammar Rules // ============= start : e=expr EOF ; expr : e=conditionalOr (op='?' e1=conditionalOr ':' e2=expr)? ; conditionalOr : e=conditionalAnd (ops+='||' e1+=conditionalAnd)* ; conditionalAnd : e=relation (ops+='&&' e1+=relation)* ; relation : calc | relation op=('<'|'<='|'>='|'>'|'=='|'!='|'in') relation ; calc : unary | calc op=('*'|'/'|'%') calc | calc op=('+'|'-') calc ; unary : member # MemberExpr | (ops+='!')+ member # LogicalNot | (ops+='-')+ member # Negate ; member : primary # PrimaryExpr | member op='.' id=IDENTIFIER (open='(' args=exprList? ')')? # SelectOrCall | member op='[' index=expr ']' # Index | member op='{' entries=fieldInitializerList? ','? '}' # CreateMessage ; primary : leadingDot='.'? id=IDENTIFIER (op='(' args=exprList? ')')? # IdentOrGlobalCall | '(' e=expr ')' # Nested | op='[' elems=exprList? ','? ']' # CreateList | op='{' entries=mapInitializerList? ','? '}' # CreateStruct | literal # ConstantLiteral ; exprList : e+=expr (',' e+=expr)* ; fieldInitializerList : fields+=IDENTIFIER cols+=':' values+=expr (',' fields+=IDENTIFIER cols+=':' values+=expr)* ; mapInitializerList : keys+=expr cols+=':' values+=expr (',' keys+=expr cols+=':' values+=expr)* ; literal : sign=MINUS? tok=NUM_INT # Int | tok=NUM_UINT # Uint | sign=MINUS? tok=NUM_FLOAT # Double | tok=STRING # String | tok=BYTES # Bytes | tok=CEL_TRUE # BoolTrue | tok=CEL_FALSE # BoolFalse | tok=NUL # Null ; // Lexer Rules // =========== EQUALS : '=='; NOT_EQUALS : '!='; LESS : '<'; LESS_EQUALS : '<='; GREATER_EQUALS : '>='; GREATER : '>'; LOGICAL_AND : '&&'; LOGICAL_OR : '||'; LBRACKET : '['; RPRACKET : ']'; LBRACE : '{'; RBRACE : '}'; LPAREN : '('; RPAREN : ')'; DOT : '.'; COMMA : ','; MINUS : '-'; EXCLAM : '!'; QUESTIONMARK : '?'; COLON : ':'; PLUS : '+'; STAR : '*'; SLASH : '/'; PERCENT : '%'; CEL_TRUE : 'true'; CEL_FALSE : 'false'; NUL : 'null'; fragment BACKSLASH : '\\'; fragment LETTER : 'A'..'Z' | 'a'..'z' ; fragment DIGIT : '0'..'9' ; fragment EXPONENT : ('e' | 'E') ( '+' | '-' )? DIGIT+ ; fragment HEXDIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ; fragment RAW : 'r' | 'R'; fragment ESC_SEQ : ESC_CHAR_SEQ | ESC_BYTE_SEQ | ESC_UNI_SEQ | ESC_OCT_SEQ ; fragment ESC_CHAR_SEQ : BACKSLASH ('a'|'b'|'f'|'n'|'r'|'t'|'v'|'"'|'\''|'\\'|'?'|'`') ; fragment ESC_OCT_SEQ : BACKSLASH ('0'..'3') ('0'..'7') ('0'..'7') ; fragment ESC_BYTE_SEQ : BACKSLASH ( 'x' | 'X' ) HEXDIGIT HEXDIGIT ; fragment ESC_UNI_SEQ : BACKSLASH 'u' HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT | BACKSLASH 'U' HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT ; WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ -> channel(HIDDEN) ; COMMENT : '//' (~'\n')* -> channel(HIDDEN) ; NUM_FLOAT : ( DIGIT+ ('.' DIGIT+) EXPONENT? | DIGIT+ EXPONENT | '.' DIGIT+ EXPONENT? ) ; NUM_INT : ( DIGIT+ | '0x' HEXDIGIT+ ); NUM_UINT : DIGIT+ ( 'u' | 'U' ) | '0x' HEXDIGIT+ ( 'u' | 'U' ) ; STRING : '"' (ESC_SEQ | ~('\\'|'"'|'\n'|'\r'))* '"' | '\'' (ESC_SEQ | ~('\\'|'\''|'\n'|'\r'))* '\'' | '"""' (ESC_SEQ | ~('\\'))*? '"""' | '\'\'\'' (ESC_SEQ | ~('\\'))*? '\'\'\'' | RAW '"' ~('"'|'\n'|'\r')* '"' | RAW '\'' ~('\''|'\n'|'\r')* '\'' | RAW '"""' .*? '"""' | RAW '\'\'\'' .*? '\'\'\'' ; BYTES : ('b' | 'B') STRING; IDENTIFIER : (LETTER | '_') ( LETTER | DIGIT | '_')*;
Add underscore to names
Add underscore to names
ANTLR
apache-2.0
google/cel-cpp,google/cel-cpp
7ef1fede9cb4c6c038d61abea8c3322ccf35eda0
pattern_grammar/STIXPattern.g4
pattern_grammar/STIXPattern.g4
// This is an ANTLR4 grammar for the STIX Patterning Language. // // http://docs.oasis-open.org/cti/stix/v2.0/stix-v2.0-part5-stix-patterning.html grammar STIXPattern; pattern : observationExpressions ; observationExpressions : <assoc=left> observationExpressions FOLLOWEDBY observationExpressions | observationExpressionOr ; observationExpressionOr : <assoc=left> observationExpressionOr OR observationExpressionOr | observationExpressionAnd ; observationExpressionAnd : <assoc=left> observationExpressionAnd AND observationExpressionAnd | observationExpression ; observationExpression : LBRACK comparisonExpression RBRACK # observationExpressionSimple | LPAREN observationExpressions RPAREN # observationExpressionCompound | observationExpression startStopQualifier # observationExpressionStartStop | observationExpression withinQualifier # observationExpressionWithin | observationExpression repeatedQualifier # observationExpressionRepeated ; comparisonExpression : <assoc=left> comparisonExpression OR comparisonExpression | comparisonExpressionAnd ; comparisonExpressionAnd : <assoc=left> comparisonExpressionAnd AND comparisonExpressionAnd | propTest ; propTest : objectPath NOT? (EQ|NEQ) primitiveLiteral # propTestEqual | objectPath NOT? (GT|LT|GE|LE) orderableLiteral # propTestOrder | objectPath NOT? IN setLiteral # propTestSet | objectPath NOT? LIKE StringLiteral # propTestLike | objectPath NOT? MATCHES StringLiteral # propTestRegex | objectPath NOT? ISSUBSET StringLiteral # propTestIsSubset | objectPath NOT? ISSUPERSET StringLiteral # propTestIsSuperset | LPAREN comparisonExpression RPAREN # propTestParen ; startStopQualifier : START StringLiteral STOP StringLiteral ; withinQualifier : WITHIN (IntPosLiteral|FloatPosLiteral) SECONDS ; repeatedQualifier : REPEATS IntPosLiteral TIMES ; objectPath : objectType COLON firstPathComponent objectPathComponent? ; objectType : IdentifierWithoutHyphen | IdentifierWithHyphen ; firstPathComponent : IdentifierWithoutHyphen | StringLiteral ; objectPathComponent : <assoc=left> objectPathComponent objectPathComponent # pathStep | '.' (IdentifierWithoutHyphen | StringLiteral) # keyPathStep | LBRACK (IntPosLiteral|IntNegLiteral|ASTERISK) RBRACK # indexPathStep ; setLiteral : LPAREN RPAREN | LPAREN primitiveLiteral (COMMA primitiveLiteral)* RPAREN ; primitiveLiteral : orderableLiteral | BoolLiteral ; orderableLiteral : IntPosLiteral | IntNegLiteral | FloatPosLiteral | FloatNegLiteral | StringLiteral | BinaryLiteral | HexLiteral | TimestampLiteral ; IntNegLiteral : '-' ('0' | [1-9] [0-9]*) ; IntPosLiteral : '+'? ('0' | [1-9] [0-9]*) ; FloatNegLiteral : '-' [0-9]* '.' [0-9]+ ; FloatPosLiteral : '+'? [0-9]* '.' [0-9]+ ; HexLiteral : 'h' QUOTE TwoHexDigits* QUOTE ; BinaryLiteral : 'b' QUOTE ( Base64Char Base64Char Base64Char Base64Char )* ( (Base64Char Base64Char Base64Char Base64Char ) | (Base64Char Base64Char Base64Char ) '=' | (Base64Char Base64Char ) '==' ) QUOTE ; StringLiteral : QUOTE ( ~['\\] | '\\\'' | '\\\\' )* QUOTE ; BoolLiteral : TRUE | FALSE ; TimestampLiteral : 't' QUOTE [0-9] [0-9] [0-9] [0-9] HYPHEN ( ('0' [1-9]) | ('1' [012]) ) HYPHEN ( ('0' [1-9]) | ([12] [0-9]) | ('3' [01]) ) 'T' ( ([01] [0-9]) | ('2' [0-3]) ) COLON [0-5] [0-9] COLON ([0-5] [0-9] | '60') (DOT [0-9]+)? 'Z' QUOTE ; ////////////////////////////////////////////// // Keywords AND: A N D; OR: O R; NOT: N O T; FOLLOWEDBY: F O L L O W E D B Y; LIKE: L I K E ; MATCHES: M A T C H E S ; ISSUPERSET: I S S U P E R S E T ; ISSUBSET: I S S U B S E T ; LAST: L A S T ; IN: I N; START: S T A R T ; STOP: S T O P ; SECONDS: S E C O N D S; TRUE: T R U E; FALSE: F A L S E; WITHIN: W I T H I N; REPEATS: R E P E A T S; TIMES: T I M E S; // After keywords, so the lexer doesn't tokenize them as identifiers. // Object types may have unquoted hyphens, but property names // (in object paths) cannot. IdentifierWithoutHyphen : [a-zA-Z_] [a-zA-Z0-9_]* ; IdentifierWithHyphen : [a-zA-Z_] [a-zA-Z0-9_-]* ; EQ : '=' | '=='; NEQ : '!=' | '<>'; LT : '<'; LE : '<='; GT : '>'; GE : '>='; QUOTE : '\''; COLON : ':' ; DOT : '.' ; COMMA : ',' ; RPAREN : ')' ; LPAREN : '(' ; RBRACK : ']' ; LBRACK : '[' ; PLUS : '+' ; HYPHEN : MINUS ; MINUS : '-' ; POWER_OP : '^' ; DIVIDE : '/' ; ASTERISK : '*'; fragment A: [aA]; fragment B: [bB]; fragment C: [cC]; fragment D: [dD]; fragment E: [eE]; fragment F: [fF]; fragment G: [gG]; fragment H: [hH]; fragment I: [iI]; fragment J: [jJ]; fragment K: [kK]; fragment L: [lL]; fragment M: [mM]; fragment N: [nN]; fragment O: [oO]; fragment P: [pP]; fragment Q: [qQ]; fragment R: [rR]; fragment S: [sS]; fragment T: [tT]; fragment U: [uU]; fragment V: [vV]; fragment W: [wW]; fragment X: [xX]; fragment Y: [yY]; fragment Z: [zZ]; fragment HexDigit: [A-Fa-f0-9]; fragment TwoHexDigits: HexDigit HexDigit; fragment Base64Char: [A-Za-z0-9+/]; // Whitespace and comments // WS : [ \t\r\n\u000B\u000C\u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+ -> skip ; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '//' ~[\r\n]* -> skip ; // Catch-all to prevent lexer from silently eating unusable characters. InvalidCharacter : . ;
// This is an ANTLR4 grammar for the STIX Patterning Language. // // http://docs.oasis-open.org/cti/stix/v2.0/stix-v2.0-part5-stix-patterning.html grammar STIXPattern; pattern : observationExpressions ; observationExpressions : <assoc=left> observationExpressions FOLLOWEDBY observationExpressions | observationExpressionOr ; observationExpressionOr : <assoc=left> observationExpressionOr OR observationExpressionOr | observationExpressionAnd ; observationExpressionAnd : <assoc=left> observationExpressionAnd AND observationExpressionAnd | observationExpression ; observationExpression : LBRACK comparisonExpression RBRACK # observationExpressionSimple | LPAREN observationExpressions RPAREN # observationExpressionCompound | observationExpression startStopQualifier # observationExpressionStartStop | observationExpression withinQualifier # observationExpressionWithin | observationExpression repeatedQualifier # observationExpressionRepeated ; comparisonExpression : <assoc=left> comparisonExpression OR comparisonExpression | comparisonExpressionAnd ; comparisonExpressionAnd : <assoc=left> comparisonExpressionAnd AND comparisonExpressionAnd | propTest ; propTest : objectPath NOT? (EQ|NEQ) primitiveLiteral # propTestEqual | objectPath NOT? (GT|LT|GE|LE) orderableLiteral # propTestOrder | objectPath NOT? IN setLiteral # propTestSet | objectPath NOT? LIKE StringLiteral # propTestLike | objectPath NOT? MATCHES StringLiteral # propTestRegex | objectPath NOT? ISSUBSET StringLiteral # propTestIsSubset | objectPath NOT? ISSUPERSET StringLiteral # propTestIsSuperset | LPAREN comparisonExpression RPAREN # propTestParen ; startStopQualifier : START StringLiteral STOP StringLiteral ; withinQualifier : WITHIN (IntPosLiteral|FloatPosLiteral) SECONDS ; repeatedQualifier : REPEATS IntPosLiteral TIMES ; objectPath : objectType COLON firstPathComponent objectPathComponent? ; objectType : IdentifierWithoutHyphen | IdentifierWithHyphen ; firstPathComponent : IdentifierWithoutHyphen | StringLiteral ; objectPathComponent : <assoc=left> objectPathComponent objectPathComponent # pathStep | '.' (IdentifierWithoutHyphen | StringLiteral) # keyPathStep | LBRACK (IntPosLiteral|IntNegLiteral|ASTERISK) RBRACK # indexPathStep ; setLiteral : LPAREN RPAREN | LPAREN primitiveLiteral (COMMA primitiveLiteral)* RPAREN ; primitiveLiteral : orderableLiteral | BoolLiteral ; orderableLiteral : IntPosLiteral | IntNegLiteral | FloatPosLiteral | FloatNegLiteral | StringLiteral | BinaryLiteral | HexLiteral | TimestampLiteral ; IntNegLiteral : '-' ('0' | [1-9] [0-9]*) ; IntPosLiteral : '+'? ('0' | [1-9] [0-9]*) ; FloatNegLiteral : '-' [0-9]* '.' [0-9]+ ; FloatPosLiteral : '+'? [0-9]* '.' [0-9]+ ; HexLiteral : 'h' QUOTE TwoHexDigits* QUOTE ; BinaryLiteral : 'b' QUOTE ( Base64Char Base64Char Base64Char Base64Char )* ( (Base64Char Base64Char Base64Char Base64Char ) | (Base64Char Base64Char Base64Char ) '=' | (Base64Char Base64Char ) '==' ) QUOTE ; StringLiteral : QUOTE ( ~['\\] | '\\\'' | '\\\\' )* QUOTE ; BoolLiteral : TRUE | FALSE ; TimestampLiteral : 't' QUOTE [0-9] [0-9] [0-9] [0-9] HYPHEN ( ('0' [1-9]) | ('1' [012]) ) HYPHEN ( ('0' [1-9]) | ([12] [0-9]) | ('3' [01]) ) 'T' ( ([01] [0-9]) | ('2' [0-3]) ) COLON [0-5] [0-9] COLON ([0-5] [0-9] | '60') (DOT [0-9]+)? 'Z' QUOTE ; ////////////////////////////////////////////// // Keywords AND: 'AND' ; OR: 'OR' ; NOT: 'NOT' ; FOLLOWEDBY: 'FOLLOWEDBY'; LIKE: 'LIKE' ; MATCHES: 'MATCHES' ; ISSUPERSET: 'ISSUPERSET' ; ISSUBSET: 'ISSUBSET' ; LAST: 'LAST' ; IN: 'IN' ; START: 'START' ; STOP: 'STOP' ; SECONDS: 'SECONDS' ; TRUE: 'true' ; FALSE: 'false' ; WITHIN: 'WITHIN' ; REPEATS: 'REPEATS' ; TIMES: 'TIMES' ; // After keywords, so the lexer doesn't tokenize them as identifiers. // Object types may have unquoted hyphens, but property names // (in object paths) cannot. IdentifierWithoutHyphen : [a-zA-Z_] [a-zA-Z0-9_]* ; IdentifierWithHyphen : [a-zA-Z_] [a-zA-Z0-9_-]* ; EQ : '=' | '=='; NEQ : '!=' | '<>'; LT : '<'; LE : '<='; GT : '>'; GE : '>='; QUOTE : '\''; COLON : ':' ; DOT : '.' ; COMMA : ',' ; RPAREN : ')' ; LPAREN : '(' ; RBRACK : ']' ; LBRACK : '[' ; PLUS : '+' ; HYPHEN : MINUS ; MINUS : '-' ; POWER_OP : '^' ; DIVIDE : '/' ; ASTERISK : '*'; fragment HexDigit: [A-Fa-f0-9]; fragment TwoHexDigits: HexDigit HexDigit; fragment Base64Char: [A-Za-z0-9+/]; // Whitespace and comments // WS : [ \t\r\n\u000B\u000C\u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+ -> skip ; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '//' ~[\r\n]* -> skip ; // Catch-all to prevent lexer from silently eating unusable characters. InvalidCharacter : . ;
Change the keyword tokens to require correct case (mostly upper case), and remove the single letter lexer grammar fragments.
Change the keyword tokens to require correct case (mostly upper case), and remove the single letter lexer grammar fragments.
ANTLR
bsd-3-clause
oasis-open/cti-stix2-json-schemas
34686e76ad702eb05e156fb047e6c852300aed63
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_EOL: '|' [ \t]* '\r'? '\n' ; BAR: '|' ; HBAR: '|' [|\-=\:\.\+ \t]* '|' [ \t]* '\r'? '\n' ; STARLBRACKET: '*[' -> skip, mode(ABBREVIATION); ASSERT: 'Assert' ; THAT: 'that' ; STOP: '.' ; AND: 'and' ; IS: 'is' ; NOT: 'not' ; THROWS: 'throws' ; FOR: 'for' ; ALL: 'all' ; COMMA: ',' ; RULES: 'rules' ; IN: 'in' ; UTABLE: 'Table' -> mode(AFTER_TABLE) ; CSV: 'CSV' -> mode(AFTER_CSV) ; TSV: 'TSV' -> mode(AFTER_CSV) ; EXCEL: 'Excel' -> mode(AFTER_EXCEL) ; WHERE: 'where' ; EQ: '=' ; LET: 'Let' ; BE: 'be' ; DO: 'Do' ; A_STUB_OF: 'a' [ \t\r\n]+ 'stub' [ \t\r\n]+ 'of' -> mode(EXPECT_CLASS) ; SUCH: 'such' ; METHOD: 'method' -> mode(AFTER_METHOD) ; RETURNS: 'returns' ; 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) ; ON: 'on' ; WITH: 'with' ; NULL: 'null' ; NOTHING: 'nothing' ; TRUE: 'true' ; FALSE: 'false' ; Identifier: IdentStart IdentPart* ; Integer: IntegerLiteral ; FloatingPoint: FloatingPointLiteral ; MINUS: '-' ; EMPTY_STRING: '""' ; OPENBACKTICK: '`' -> skip, mode(IN_BACKTICK) ; OPENDOUBLEQUOTE: '"' -> skip, mode(IN_DOUBLEQUOTE) ; OPENSINGLEQUOTE: '\'' -> skip, mode(IN_SINGLEQUOTE) ; NEW_LINE : ('\r'? '\n')+ -> skip ; WS : [ \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; Str: (~["\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSEDOUBLEQUOTE: '"' -> skip, mode(DEFAULT_MODE) ; mode IN_SINGLEQUOTE; Char: (~['\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSESINGLEQUOTE: '\'' -> skip, mode(DEFAULT_MODE) ; mode IN_BACKTICK; Expr: ~[`]+ /*-> type(Expr)*/ ; CLOSEBACKTICK: '`' -> 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(DEFAULT_MODE) ; 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(DEFAULT_MODE) ; 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; OPENSINGLEQUOTE3: '\'' -> skip, mode(IN_FILE_NAME) ; SPACETABNEWLINE7: [ \t\r\n]+ -> skip ; mode AFTER_EXCEL; OPENSINGLEQUOTE4: '\'' -> skip, mode(IN_BOOK_NAME) ; SPACETABNEWLINE8: [ \t\r\n]+ -> skip ; mode IN_TABLE_NAME; SingleQuoteName: ~[\]\r\n]* ; RBRACKET2: ']' -> skip, mode(DEFAULT_MODE) ; mode IN_FILE_NAME; SingleQuoteName2: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ; CLOSESINGLEQUOTE2: '\'' -> skip, mode(DEFAULT_MODE) ; mode IN_BOOK_NAME; SingleQuoteName3: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ; CLOSESINGLEQUOTE3: '\'' -> skip, mode(DEFAULT_MODE) ; 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 ; 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; HASH1: '#' ; HASH2: '##' ; HASH3: '###' ; HASH4: '####' ; HASH5: '#####' ; HASH6: '######' ; TEST: 'Test:' -> mode(TEST_LEADING); TABLE_CAPTION: '[' -> 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_EOL: '|' [ \t]* '\r'? '\n' ; BAR: '|' ; HBAR: '|' [|\-=\:\.\+ \t]* '|' [ \t]* '\r'? '\n' ; STAR_LBRACKET: '*[' -> skip, mode(ABBREVIATION); ASSERT: 'Assert' ; THAT: 'that' ; STOP: '.' ; AND: 'and' ; IS: 'is' ; NOT: 'not' ; THROWS: 'throws' ; FOR: 'for' ; ALL: 'all' ; COMMA: ',' ; RULES: 'rules' ; IN: 'in' ; UTABLE: 'Table' -> mode(AFTER_TABLE) ; CSV: 'CSV' -> mode(AFTER_CSV) ; TSV: 'TSV' -> mode(AFTER_CSV) ; EXCEL: 'Excel' -> mode(AFTER_EXCEL) ; WHERE: 'where' ; EQ: '=' ; LET: 'Let' ; BE: 'be' ; DO: 'Do' ; A_STUB_OF: 'a' [ \t\r\n]+ 'stub' [ \t\r\n]+ 'of' -> mode(EXPECT_CLASS) ; SUCH: 'such' ; METHOD: 'method' -> mode(AFTER_METHOD) ; RETURNS: 'returns' ; 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) ; ON: 'on' ; WITH: 'with' ; NULL: 'null' ; NOTHING: 'nothing' ; TRUE: 'true' ; FALSE: 'false' ; Identifier: IdentStart IdentPart* ; Integer: IntegerLiteral ; FloatingPoint: FloatingPointLiteral ; MINUS: '-' ; EMPTY_STRING: '""' ; OPEN_BACK_TICK: '`' -> skip, mode(IN_BACK_TICK) ; OPEN_DOUBLE_QUOTE: '"' -> skip, mode(IN_DOUBLE_QUOTE) ; OPEN_SINGLE_QUOTE: '\'' -> skip, mode(IN_SINGLE_QUOTE) ; NEW_LINE : ('\r'? '\n')+ -> skip ; WS : [ \t]+ -> skip ; mode TEST_LEADING; WS3: [ \t]+ -> skip, mode(TEST_NAME); mode TEST_NAME; TestName: ~[\r\n]+ ; NEW_LINE_TEST_NAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode TABLE_NAME; TableName: ~[\]\r\n]+ ; NEW_LINE_TABLE_NAME: ']' [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode PHASE_LEADING; COLON: ':' [ \t]* -> skip, mode(PHASE_DESCRIPTION) ; NEW_LINE_PHASE_LEADING: [ \t]* '\r'? '\n' -> skip, mode(DEFAULT_MODE) ; mode PHASE_DESCRIPTION; PhaseDescription: ~[\r\n]+ ; NEW_LINE_PHASE_DESCRIPTION: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode IN_DOUBLE_QUOTE; Str: (~["\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_DOUBLE_QUOTE: '"' -> skip, mode(DEFAULT_MODE) ; mode IN_SINGLE_QUOTE; Char: (~['\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_SINGLE_QUOTE: '\'' -> skip, mode(DEFAULT_MODE) ; mode IN_BACK_TICK; Expr: ~[`]+ ; CLOSE_BACK_TICK: '`' -> skip, mode(DEFAULT_MODE) ; mode AFTER_METHOD; OPEN_BACK_TICK3: '`' -> 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 ; CLOSE_BACK_TICK2: '`' -> skip, mode(DEFAULT_MODE) ; mode EXPECT_CLASS; OPEN_BACK_TICK4: '`' -> skip, mode(CLASS) ; SPACETABNEWLINE3: [ \t\r\n]+ -> skip ; mode CLASS; DOT2: '.' -> type(DOT) ; Identifier4 : IdentStart IdentPart* -> type(Identifier) ; SPACETABNEWLINE4: [ \t\r\n]+ -> skip ; CLOSE_BACK_TICK3: '`' -> skip, mode(DEFAULT_MODE) ; mode AFTER_AN_INSTANCE; OF: 'of' ; Identifier5 : IdentStart IdentPart* -> type(Identifier) ; OPEN_BACK_TICK5: '`' -> 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; OPEN_SINGLE_QUOTE3: '\'' -> skip, mode(IN_FILE_NAME) ; SPACETABNEWLINE7: [ \t\r\n]+ -> skip ; mode AFTER_EXCEL; OPEN_SINGLE_QUOTE4: '\'' -> skip, mode(IN_BOOK_NAME) ; SPACETABNEWLINE8: [ \t\r\n]+ -> skip ; mode IN_TABLE_NAME; SingleQuoteName: ~[\]\r\n]* ; RBRACKET2: ']' -> skip, mode(DEFAULT_MODE) ; mode IN_FILE_NAME; SingleQuoteName2: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ; CLOSE_SINGLE_QUOTE2: '\'' -> skip, mode(DEFAULT_MODE) ; mode IN_BOOK_NAME; SingleQuoteName3: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ; CLOSE_SINGLE_QUOTE3: '\'' -> skip, mode(DEFAULT_MODE) ; mode ABBREVIATION; ShortName: ~[\]\r\n]* ; RBRACKET_COLON: ']:' [ \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 ; 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] ;
Use snake stype identifiyer for upper case identifiers
Use snake stype identifiyer for upper case identifiers
ANTLR
mit
tkob/yokohamaunit,tkob/yokohamaunit
4dfd2917d91a32b1d5008018c7a6c63af8e3251b
python3-cs/Python3Parser.g4
python3-cs/Python3Parser.g4
/* * The MIT License (MIT) * * Copyright (c) 2014 by Bart Kiers * * 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. * * Project : python3-parser; an ANTLR4 grammar for Python 3 * https://github.com/bkiers/python3-parser * Developed by : Bart Kiers, [email protected] */ parser grammar Python3Parser; options { tokenVocab=Python3Lexer; } 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; decorators: decorator+; decorated: decorators (classdef | funcdef); funcdef: (ASYNC)? DEF NAME parameters (func_annotation)? COLON suite; func_annotation: ARROW test; parameters: OPEN_PAREN (typedargslist)? CLOSE_PAREN; typedargslist : (def_parameters COMMA)? args (COMMA def_parameters)? (COMMA kwargs)? |(def_parameters COMMA)? kwargs | def_parameters; args: STAR named_parameter; kwargs: POWER named_parameter; def_parameters: def_parameter (COMMA def_parameter)*; vardef_parameters: vardef_parameter (COMMA vardef_parameter)*; def_parameter: named_parameter (ASSIGN test)?; vardef_parameter: NAME (ASSIGN test)?; named_parameter: NAME (COLON test)?; varargslist : (vardef_parameters COMMA)? varargs (COMMA vardef_parameters)? (COMMA varkwargs) | vardef_parameters; varargs: STAR NAME; varkwargs: POWER NAME; vfpdef: NAME; stmt: simple_stmt | compound_stmt; simple_stmt: small_stmt (SEMI_COLON small_stmt)* (SEMI_COLON)? (NEWLINE | EOF); small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | nonlocal_stmt | assert_stmt); expr_stmt: testlist_star_expr | annassign | augassign | assign; assign: testlist_star_expr (ASSIGN (yield_expr|testlist_star_expr))*; annassign: testlist_star_expr COLON test (ASSIGN test)? (yield_expr|testlist); testlist_star_expr: (test|star_expr) (COMMA (test|star_expr))* (COMMA)?; augassign: testlist_star_expr op=('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '**=' | '//=') (yield_expr|testlist); // For normal and annotated assignments, additional restrictions enforced by the interpreter 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 (FROM test)?)?; import_stmt: import_name | import_from; import_name: IMPORT dotted_as_names; // note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS 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 dotted_name | NAME; global_stmt: GLOBAL NAME (COMMA NAME)*; nonlocal_stmt: NONLOCAL NAME (COMMA NAME)*; 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 (with_stmt | for_stmt); if_stmt: IF test COLON suite (elif_clause)* (else_clause)?; elif_clause: ELIF test 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)); with_stmt: WITH with_item (COMMA with_item)* COLON suite; with_item: test (AS expr)?; // NB compile.c makes sure that the default except clause is last except_clause: EXCEPT (test (AS NAME)?)? COLON suite; else_clause: ELSE COLON suite; finaly_clause: FINALLY COLON suite; suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT; test: logical_test (IF logical_test ELSE test)? | lambdef; test_nocond: logical_test | lambdef_nocond; lambdef: LAMBDA (varargslist)? COLON test; 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_1|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|'@'|'/'|'%'|'//') expr | expr op=('+'|'-'|'~') expr | expr op=POWER expr | expr op=('+'|'-'|'~') expr | atom_expr; atom_expr: (AWAIT)? atom trailer*; atom: (OPEN_PAREN (yield_expr|testlist_comp)? CLOSE_PAREN | OPEN_BRACK (testlist_comp)? CLOSE_BRACK | OPEN_BRACE (dictorsetmaker)? CLOSE_BRACE | dotted_name | NUMBER | STRING+ | ELLIPSIS | NONE | TRUE | FALSE); testlist_comp: (test|star_expr) ( comp_for | (COMMA (test|star_expr))* (COMMA)? ); trailer: OPEN_PAREN (arglist)? CLOSE_PAREN | OPEN_BRACK subscriptlist CLOSE_BRACK; subscriptlist: subscript (COMMA subscript)* (COMMA)?; subscript: test | (test)? COLON (test)? (sliceop)?; sliceop: COLON (test)?; exprlist: (expr|star_expr) (COMMA (expr|star_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: argument (COMMA argument)* (COMMA)?; // 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. // "test ASSIGN test" is really "keyword ASSIGN test", but we have no such token. // These need to be in a single rule to avoid grammar that is ambiguous // to our LL(1) parser. Even though 'test' includes '*expr' in star_expr, // we explicitly match STAR here, too, to give it proper precedence. // Illegal combinations and orderings are blocked in ast.c: // multiple (test comp_for) arguments are blocked; keyword unpackings // that precede iterable unpackings are blocked; etc. argument: ( test (comp_for)? | test ASSIGN test | POWER test | STAR test ); comp_iter: comp_for | comp_if; comp_for: (ASYNC)? FOR exprlist IN logical_test (comp_iter)?; comp_if: IF test_nocond (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;
/* * The MIT License (MIT) * * Copyright (c) 2014 by Bart Kiers * * 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. * * Project : python3-parser; an ANTLR4 grammar for Python 3 * https://github.com/bkiers/python3-parser * Developed by : Bart Kiers, [email protected] */ parser grammar Python3Parser; options { tokenVocab=Python3Lexer; } 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; decorators: decorator+; decorated: decorators (classdef | funcdef); funcdef: (ASYNC)? DEF NAME parameters (func_annotation)? COLON suite; func_annotation: ARROW test; parameters: OPEN_PAREN (typedargslist)? CLOSE_PAREN; typedargslist : (def_parameters COMMA)? args (COMMA def_parameters)? (COMMA kwargs)? |(def_parameters COMMA)? kwargs | def_parameters; args: STAR named_parameter; kwargs: POWER named_parameter; def_parameters: def_parameter (COMMA def_parameter)*; vardef_parameters: vardef_parameter (COMMA vardef_parameter)*; def_parameter: named_parameter (ASSIGN test)?; vardef_parameter: NAME (ASSIGN test)?; named_parameter: NAME (COLON test)?; varargslist : (vardef_parameters COMMA)? varargs (COMMA vardef_parameters)? (COMMA varkwargs) | vardef_parameters; varargs: STAR NAME; varkwargs: POWER NAME; vfpdef: NAME; stmt: simple_stmt | compound_stmt; simple_stmt: small_stmt (SEMI_COLON small_stmt)* (SEMI_COLON)? (NEWLINE | EOF); small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | nonlocal_stmt | assert_stmt); expr_stmt: testlist_star_expr | annassign | augassign | assign; assign: testlist_star_expr (ASSIGN (yield_expr|testlist_star_expr))*; annassign: testlist_star_expr COLON test (ASSIGN test)? (yield_expr|testlist); testlist_star_expr: (test|star_expr) (COMMA (test|star_expr))* (COMMA)?; augassign: testlist_star_expr op=('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '**=' | '//=') (yield_expr|testlist); // For normal and annotated assignments, additional restrictions enforced by the interpreter 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 (FROM test)?)?; import_stmt: import_name | import_from; import_name: IMPORT dotted_as_names; // note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS 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 dotted_name | NAME; global_stmt: GLOBAL NAME (COMMA NAME)*; nonlocal_stmt: NONLOCAL NAME (COMMA NAME)*; 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 (with_stmt | for_stmt); if_stmt: IF test COLON suite (elif_clause)* (else_clause)?; elif_clause: ELIF test 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)); with_stmt: WITH with_item (COMMA with_item)* COLON suite; with_item: test (AS expr)?; // NB compile.c makes sure that the default except clause is last except_clause: EXCEPT (test (AS NAME)?)? COLON suite; else_clause: ELSE COLON suite; finaly_clause: FINALLY COLON suite; suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT; test: logical_test (IF logical_test ELSE test)? | lambdef; test_nocond: logical_test | lambdef_nocond; lambdef: LAMBDA (varargslist)? COLON test; 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|'@'|'/'|'%'|'//') expr | expr op=('+'|'-'|'~') expr | expr op=POWER expr | expr op=('+'|'-'|'~') expr | atom_expr; atom_expr: (AWAIT)? atom trailer*; atom: (OPEN_PAREN (yield_expr|testlist_comp)? CLOSE_PAREN | OPEN_BRACK (testlist_comp)? CLOSE_BRACK | OPEN_BRACE (dictorsetmaker)? CLOSE_BRACE | dotted_name | NUMBER | STRING+ | ELLIPSIS | NONE | TRUE | FALSE); testlist_comp: (test|star_expr) ( comp_for | (COMMA (test|star_expr))* (COMMA)? ); trailer: OPEN_PAREN (arglist)? CLOSE_PAREN | OPEN_BRACK subscriptlist CLOSE_BRACK; subscriptlist: subscript (COMMA subscript)* (COMMA)?; subscript: test | (test)? COLON (test)? (sliceop)?; sliceop: COLON (test)?; exprlist: (expr|star_expr) (COMMA (expr|star_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: argument (COMMA argument)* (COMMA)?; // 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. // "test ASSIGN test" is really "keyword ASSIGN test", but we have no such token. // These need to be in a single rule to avoid grammar that is ambiguous // to our LL(1) parser. Even though 'test' includes '*expr' in star_expr, // we explicitly match STAR here, too, to give it proper precedence. // Illegal combinations and orderings are blocked in ast.c: // multiple (test comp_for) arguments are blocked; keyword unpackings // that precede iterable unpackings are blocked; etc. argument: ( test (comp_for)? | test ASSIGN test | POWER test | STAR test ); comp_iter: comp_for | comp_if; comp_for: (ASYNC)? FOR exprlist IN logical_test (comp_iter)?; comp_if: IF test_nocond (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;
Fix error in Python3Parser grammar
Fix error in Python3Parser 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
88272816f3029a6660babec32674c6dc61ac3dbb
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 usesStatements* dataDefs; dataDefsHeader: KW_DATA_DEFINITIONS namespace; usesStatements: usesStatement+; usesStatement: KW_USES namespace; dataDefs: dataDef+; dataDef: vocabularyDef | elementDef | entryDef; vocabularyDef: KW_VOCABULARY ALL_CAPS EQUAL URL; elementDef: elementHeader elementProps? (singleValue | multiValue); elementHeader: KW_ELEMENT simpleName; entryDef: entryHeader elementProps? (singleValue | multiValue); entryHeader: KW_ENTRY simpleName; elementProps: elementProp+; elementProp: conceptProp | descriptionProp; singleValue: countedType (KW_OR countedType)*; countedType: count types; types: type | OPEN_PAREN type (KW_OR type)* CLOSE_PAREN; type: simpleOrFQName | ref | codeConstraint | primitive; multiValue: countedElements+; countedElements: countedElement (KW_OR countedElement)*; countedElement: count elements; elements: element | OPEN_PAREN element (KW_OR element)* CLOSE_PAREN; element: simpleOrFQName | ref; conceptProp: KW_CONCEPT (KW_TBD | concepts); concepts: fullyQualifiedCode (COMMA fullyQualifiedCode)*; descriptionProp: KW_DESCRIPTION STRING; // VALUESET DEFINITIONS valuesetDefsDoc: valuesetDefsHeader valuesetDefs; valuesetDefsHeader: KW_VALUESET_DEFINITIONS namespace; valuesetDefs: valuesetDef+; valuesetDef: valuesetHeader valuesetValues?; valuesetHeader: KW_VALUESET URL; valuesetValues: valuesetValue+; valuesetValue: CODE STRING?; // 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 EXTRA_INFO?; fullyQualifiedCode: ALL_CAPS code; codeConstraint: codeFromValueset | codeDescendent; codeFromValueset: KW_CODE KW_FROM valueset; codeDescendent: KW_CODE KW_DESCENDING_FROM fullyQualifiedCode; valueset: URL; 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);
parser grammar SHRParser; options { tokenVocab=SHRLexer; } shr: dataDefsDoc | valuesetDefsDoc /* | contentProfiles*/; // DATA DEFINITIONS (Vocabularies, Entries, Elements) dataDefsDoc: dataDefsHeader usesStatement? dataDefs; dataDefsHeader: KW_DATA_DEFINITIONS namespace; usesStatement: KW_USES namespace (COMMA namespace)*; dataDefs: dataDef+; dataDef: vocabularyDef | elementDef | entryDef; vocabularyDef: KW_VOCABULARY ALL_CAPS EQUAL URL; elementDef: elementHeader elementProps? (singleValue | multiValue); elementHeader: KW_ELEMENT simpleName; entryDef: entryHeader elementProps? (singleValue | multiValue); entryHeader: KW_ENTRY simpleName; elementProps: elementProp+; elementProp: conceptProp | descriptionProp; singleValue: countedType (KW_OR countedType)*; countedType: count types; types: type | OPEN_PAREN type (KW_OR type)* CLOSE_PAREN; type: simpleOrFQName | ref | codeConstraint | primitive; multiValue: countedElements+; countedElements: countedElement (KW_OR countedElement)*; countedElement: count elements; elements: element | OPEN_PAREN element (KW_OR element)* CLOSE_PAREN; element: simpleOrFQName | ref; conceptProp: KW_CONCEPT (KW_TBD | concepts); concepts: fullyQualifiedCode (COMMA fullyQualifiedCode)*; descriptionProp: KW_DESCRIPTION STRING; // VALUESET DEFINITIONS valuesetDefsDoc: valuesetDefsHeader usesStatement? valuesetDefs; valuesetDefsHeader: KW_VALUESET_DEFINITIONS namespace; valuesetDefs: valuesetDef+; valuesetDef: valuesetHeader valuesetValues?; valuesetHeader: KW_VALUESET URL; valuesetValues: valuesetValue+; valuesetValue: CODE STRING?; // 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 EXTRA_INFO?; fullyQualifiedCode: ALL_CAPS code; codeConstraint: codeFromValueset | codeDescendent; codeFromValueset: KW_CODE KW_FROM valueset; codeDescendent: KW_CODE KW_DESCENDING_FROM fullyQualifiedCode; valueset: URL; 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);
Fix ANTLR4 grammar for 'Uses'
Fix ANTLR4 grammar for 'Uses' Fix grammar to reflect that `Uses:` puts all used namespaces in a single comma-separated statement. Also allow `Uses:` for value set def files.
ANTLR
apache-2.0
standardhealth/shr_spec
b102b81b64bd21b74b76b1683f4bd6488f4a022a
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 createTableSpecification_ TABLE tableName createDefinitionClause_ ; createIndex : CREATE createIndexSpecification_ INDEX indexName ON createIndexDefinitionClause_ ; alterTable : ALTER TABLE tableName alterDefinitionClause_ ; // TODO hongjun throw exeption when alter index on oracle alterIndex : ALTER INDEX indexName renameIndexClause_ ; dropTable : DROP TABLE tableName ; dropIndex : DROP INDEX indexName ; truncateTable : TRUNCATE TABLE tableName ; createTableSpecification_ : (GLOBAL TEMPORARY)? ; tablespaceClauseWithParen : LP_ tablespaceClause RP_ ; tablespaceClause : TABLESPACE ignoredIdentifier_ ; domainIndexClause : indexTypeName ; createDefinitionClause_ : (LP_ relationalProperties RP_)? (ON COMMIT (DELETE | PRESERVE) ROWS)? ; relationalProperties : relationalProperty (COMMA_ relationalProperty)* ; relationalProperty : columnDefinition | virtualColumnDefinition | outOfLineConstraint | outOfLineRefConstraint ; columnDefinition : columnName dataType SORT? visibleClause_ (defaultNullClause_ expr | identityClause)? (ENCRYPT encryptionSpecification_)? (inlineConstraint+ | inlineRefConstraint)? ; visibleClause_ : (VISIBLE | INVISIBLE)? ; defaultNullClause_ : DEFAULT (ON NULL)? ; identityClause : GENERATED (ALWAYS | BY DEFAULT (ON NULL)?) AS IDENTITY identifyOptions ; identifyOptions : LP_? (identityOption+)? RP_? ; identityOption : START WITH (NUMBER_ | LIMIT VALUE) | INCREMENT BY NUMBER_ | MAXVALUE NUMBER_ | NOMAXVALUE | MINVALUE NUMBER_ | NOMINVALUE | CYCLE | NOCYCLE | CACHE NUMBER_ | NOCACHE | ORDER | NOORDER ; encryptionSpecification_ : (USING STRING_)? (IDENTIFIED BY STRING_)? STRING_? (NO? SALT)? ; 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* ; virtualColumnDefinition : columnName dataType? (GENERATED ALWAYS)? AS LP_ expr RP_ VIRTUAL? inlineConstraint* ; 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* ; createIndexSpecification_ : (UNIQUE | BITMAP)? ; tableIndexClause_ : tableName alias? indexExpressions_ ; indexExpressions_ : LP_ indexExpression_ (COMMA_ indexExpression_)* RP_ ; indexExpression_ : (columnName | expr) (ASC | DESC)? ; bitmapJoinIndexClause_ : tableName columnSortsClause_ FROM tableAlias WHERE expr ; columnSortsClause_ : LP_ columnSortClause_ (COMMA_ columnSortClause_)* RP_ ; columnSortClause_ : (tableName | alias)? columnName (ASC | DESC)? ; createIndexDefinitionClause_ : tableIndexClause_ | bitmapJoinIndexClause_ ; tableAlias : tableName alias? (COMMA_ tableName alias?)* ; alterDefinitionClause_ : (alterTableProperties | columnClauses | constraintClauses | alterExternalTable)? ; alterTableProperties : renameTableSpecification_ | REKEY encryptionSpecification_ ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; columnClauses : operateColumnClause+ | renameColumnClause ; operateColumnClause : addColumnSpecification | modifyColumnSpecification | dropColumnClause ; addColumnSpecification : ADD columnOrVirtualDefinitions columnProperties? ; columnOrVirtualDefinitions : LP_ columnOrVirtualDefinition (COMMA_ columnOrVirtualDefinition)* RP_ | columnOrVirtualDefinition ; columnOrVirtualDefinition : columnDefinition | virtualColumnDefinition ; columnProperties : columnProperty+ ; columnProperty : objectTypeColProperties ; objectTypeColProperties : COLUMN columnName substitutableColumnClause ; substitutableColumnClause : ELEMENT? IS OF TYPE? LP_ ONLY? dataTypeName_ RP_ | NOT? SUBSTITUTABLE AT ALL LEVELS ; modifyColumnSpecification : MODIFY (LP_? modifyColProperties (COMMA_ modifyColProperties)* RP_? | modifyColSubstitutable) ; modifyColProperties : columnName dataType? (DEFAULT expr)? (ENCRYPT encryptionSpecification_ | 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_ ; renameColumnClause : 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)+ ; objectProperties : objectProperty (COMMA_ objectProperty)* ; objectProperty : (columnName | attributeName) (DEFAULT expr)? (inlineConstraint* | inlineRefConstraint?) | outOfLineConstraint | outOfLineRefConstraint ; renameIndexClause_ : (RENAME TO indexName)? ;
/* * 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 tableName createDefinitionClause_ ; createIndex : CREATE createIndexSpecification_ INDEX indexName ON createIndexDefinitionClause_ ; alterTable : ALTER TABLE tableName alterDefinitionClause_ ; // TODO hongjun throw exeption when alter index on oracle alterIndex : ALTER INDEX indexName renameIndexClause_ ; dropTable : DROP TABLE tableName ; dropIndex : DROP INDEX indexName ; truncateTable : TRUNCATE TABLE tableName ; createTableSpecification_ : (GLOBAL TEMPORARY)? ; tablespaceClauseWithParen : LP_ tablespaceClause RP_ ; tablespaceClause : TABLESPACE ignoredIdentifier_ ; domainIndexClause : indexTypeName ; createDefinitionClause_ : (LP_ relationalProperties RP_)? (ON COMMIT (DELETE | PRESERVE) ROWS)? ; relationalProperties : relationalProperty (COMMA_ relationalProperty)* ; relationalProperty : columnDefinition | virtualColumnDefinition | outOfLineConstraint | outOfLineRefConstraint ; columnDefinition : columnName dataType SORT? visibleClause_ (defaultNullClause_ expr | identityClause)? (ENCRYPT encryptionSpecification_)? (inlineConstraint+ | inlineRefConstraint)? ; visibleClause_ : (VISIBLE | INVISIBLE)? ; defaultNullClause_ : DEFAULT (ON NULL)? ; identityClause : GENERATED (ALWAYS | BY DEFAULT (ON NULL)?) AS IDENTITY identifyOptions ; identifyOptions : LP_? (identityOption+)? RP_? ; identityOption : START WITH (NUMBER_ | LIMIT VALUE) | INCREMENT BY NUMBER_ | MAXVALUE NUMBER_ | NOMAXVALUE | MINVALUE NUMBER_ | NOMINVALUE | CYCLE | NOCYCLE | CACHE NUMBER_ | NOCACHE | ORDER | NOORDER ; encryptionSpecification_ : (USING STRING_)? (IDENTIFIED BY STRING_)? STRING_? (NO? SALT)? ; 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 | createIndexClause_)? ; createIndexClause_ : LP_ createIndex RP_ ; inlineRefConstraint : SCOPE IS tableName | WITH ROWID | (CONSTRAINT ignoredIdentifier_)? referencesClause constraintState* ; virtualColumnDefinition : columnName dataType? (GENERATED ALWAYS)? AS LP_ expr RP_ VIRTUAL? inlineConstraint* ; 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* ; createIndexSpecification_ : (UNIQUE | BITMAP)? ; tableIndexClause_ : tableName alias? indexExpressions_ ; indexExpressions_ : LP_ indexExpression_ (COMMA_ indexExpression_)* RP_ ; indexExpression_ : (columnName | expr) (ASC | DESC)? ; bitmapJoinIndexClause_ : tableName columnSortsClause_ FROM tableAlias WHERE expr ; columnSortsClause_ : LP_ columnSortClause_ (COMMA_ columnSortClause_)* RP_ ; columnSortClause_ : (tableName | alias)? columnName (ASC | DESC)? ; createIndexDefinitionClause_ : tableIndexClause_ | bitmapJoinIndexClause_ ; tableAlias : tableName alias? (COMMA_ tableName alias?)* ; alterDefinitionClause_ : (alterTableProperties | columnClauses | constraintClauses | alterExternalTable)? ; alterTableProperties : renameTableSpecification_ | REKEY encryptionSpecification_ ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; columnClauses : operateColumnClause+ | renameColumnClause ; operateColumnClause : addColumnSpecification | modifyColumnSpecification | dropColumnClause ; addColumnSpecification : ADD columnOrVirtualDefinitions columnProperties? ; columnOrVirtualDefinitions : LP_ columnOrVirtualDefinition (COMMA_ columnOrVirtualDefinition)* RP_ | columnOrVirtualDefinition ; columnOrVirtualDefinition : columnDefinition | virtualColumnDefinition ; columnProperties : columnProperty+ ; columnProperty : objectTypeColProperties ; objectTypeColProperties : COLUMN columnName substitutableColumnClause ; substitutableColumnClause : ELEMENT? IS OF TYPE? LP_ ONLY? dataTypeName_ RP_ | NOT? SUBSTITUTABLE AT ALL LEVELS ; modifyColumnSpecification : MODIFY (LP_? modifyColProperties (COMMA_ modifyColProperties)* RP_? | modifyColSubstitutable) ; modifyColProperties : columnName dataType? (DEFAULT expr)? (ENCRYPT encryptionSpecification_ | 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_ ; renameColumnClause : 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)+ ; objectProperties : objectProperty (COMMA_ objectProperty)* ; objectProperty : (columnName | attributeName) (DEFAULT expr)? (inlineConstraint* | inlineRefConstraint?) | outOfLineConstraint | outOfLineRefConstraint ; renameIndexClause_ : (RENAME TO indexName)? ;
add createIndexClause_
add createIndexClause_
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
a734b4572060b250744f15a06a0498920fb0addd
DogeSharp/DogeSharp.g4
DogeSharp/DogeSharp.g4
grammar DogeSharp; prog: useNamespace* declareClass*; stmt: expr+ ';'; expr: 'such' ID=Ident Expr=expr # Declare | Left=expr 'so' Right=expr # Assign | Pre=('plz'|'gimme') (Expr=expr '.')? ID=Ident ('many' expr+)? # Call | 'fetch' Target=expr '.' ID=Ident # GetField | 'wow' Expr=expr # Print | Value=Ident # Ident | Value=Number # Number | '"' (~'"')* '"' # String | 'so maths' Left=expr (Operator expr)+ # Operation | 'amaze' Expr=expr? # Return ; declareFunction: 'very' ID=Ident ('so' ReturnType=Ident)? ('many' (Ident Ident)*)? ('much' Modifier)* stmt*; classProperty: 'such' Name=Ident 'so' Type=Ident ('much' Modifier)*; declareClass: 'much' ID=Ident ('so' Ident)* (classProperty|declareFunction)*; useNamespace: 'many' Ident ('.' Ident)*; Modifier: 'static'|'public'|'readonly'; Operator: '+'|'-'|'*'|'/'; Number: [0-9]+; Ident: IdentChar(IdentChar|Number)*; IdentChar: [a-zA-Z]; WS: (' '|'\r'|'\n'|'\t') -> channel(HIDDEN);
grammar DogeSharp; prog: useNamespace* declareClass*; stmt: expr+ ';'; expr: 'such' ID=Ident Expr=expr # Declare | Left=expr 'so' Right=expr # Assign | Pre=('plz'|'gimme') (Expr=expr '.')? ID=Ident ('many' expr+)? # Call | 'fetch' Target=expr '.' ID=Ident # GetField | 'wow' Expr=expr # Print | Value=Ident # Ident | Value=Number # Number | '"' (~'"')* '"' # String | 'so maths' Left=expr (Operator expr)+ # Operation | 'amaze' Expr=expr? # Return ; declareFunction: 'very' ID=Ident ('so' ReturnType=Ident)? ('many' (Ident Ident)*)? ('much' Modifier)* stmt*; classProperty: 'such' Name=Ident 'so' Type=Ident ('much' Modifier)*; declareClass: 'much' ID=Ident ('so' Ident)* (classProperty|declareFunction)*; useNamespace: 'many' Ident ('.' Ident)*; Modifier: 'static'|'public'|'readonly'|'protected'|'override'|'virtual'; Operator: '+'|'-'|'*'|'/'; Number: [0-9]+; Ident: IdentChar(IdentChar|Number)*; IdentChar: [a-zA-Z]; WS: (' '|'\r'|'\n'|'\t') -> channel(HIDDEN);
Support for virtual, override and protected
[lang] Support for virtual, override and protected
ANTLR
mit
returnString/DogeSharp,returnString/DogeSharp
be76f72643d95cf6bb08d23ac5516c6f2e4ed54d
de.peeeq.wurstscript/parserspec/Wurst.g4
de.peeeq.wurstscript/parserspec/Wurst.g4
grammar Wurst; compilationUnit : NL* decls+=topLevelDeclaration*; topLevelDeclaration: wpackage | jassTopLevelDeclaration ; jassTopLevelDeclaration: jassGlobalsBlock | jassFuncDef | jassTypeDecl | jassNativeDecl ; jassGlobalsBlock: 'globals' NL vars+=jassGlobalDecl* 'endglobals' NL ; jassGlobalDecl: constant='constant'? typeExpr name=ID ('=' initial=expr)? NL ; jassFuncDef: constant='constant'? 'function' jassFuncSignature NL (jassLocals+=jassLocal)* jassStatements 'endfunction' NL ; jassLocal: 'local' typeExpr name=ID ('=' initial=expr)? NL; jassStatements: stmts+=jassStatement*; jassStatement: jassStatementIf | jassStatementLoop | jassStatementExithwhen | jassStatementReturn | jassStatementSet | jassStatementCall ; jassStatementIf: 'if' cond=expr 'then' NL thenStatements=jassStatements jassElseIfs ; jassElseIfs: 'elseif' cond=expr 'then' NL thenStatements=jassStatements jassElseIfs | 'else' NL elseStmts=jassStatements 'endif' NL | 'endif' NL ; jassStatementLoop: 'loop' NL jassStatements 'endloop' NL ; jassStatementExithwhen: 'exitwhen' cond=expr NL ; jassStatementReturn: 'return' expr NL ; jassStatementSet: 'set' left=exprAssignable '=' right=expr NL ; jassStatementCall: 'call' exprFunctionCall NL ; jassNativeDecl: constant='constant'? 'native' jassFuncSignature NL ; jassFuncSignature: name=ID 'takes' ('nothing' | args+=formalParameter (',' args+=formalParameter)*) 'returns' ('nothing'|returnType=typeExpr) ; jassTypeDecl: 'type' name=ID 'extends' extended=typeExpr NL; wpackage: 'package' name=ID NL ( imports+=wImport* entities+=entity* | STARTBLOCK imports+=wImport* entities+=entity* ENDBLOCK ) 'endpackage' NL ; wImport: 'import' isPublic='public'? isInitLater='initlater'? importedPackage=ID NL ; entity: nativeType | funcDef | varDef | initBlock | nativeDef | classDef | enumDef | moduleDef | interfaceDef | tupleDef | extensionFuncDef ; interfaceDef: modifiersWithDoc 'interface' name=ID typeParams ('extends' extended+=typeExpr (',' extended+=typeExpr)*)? NL (STARTBLOCK classSlots ENDBLOCK)? ; classDef: modifiersWithDoc 'class' name=ID typeParams ('extends' extended=typeExpr)? ('implements' implemented+=typeExpr (',' implemented+=typeExpr)*)? NL (STARTBLOCK classSlots ENDBLOCK)? ; enumDef: modifiersWithDoc 'enum' name=ID NL (STARTBLOCK (enumMembers+=ID NL)* ENDBLOCK)?; moduleDef: modifiersWithDoc 'module' name=ID typeParams NL STARTBLOCK classSlots ENDBLOCK ; classSlots: slots+=classSlot*; classSlot: constructorDef | moduleUse | ondestroyDef | varDef | funcDef ; constructorDef: modifiersWithDoc 'construct' formalParameters NL (STARTBLOCK ('super' '(' superArgs=exprList ')' NL)? stmts+=statement* ENDBLOCK)? ; moduleUse: modifiersWithDoc 'use' moduleName=ID typeArgs NL ; ondestroyDef: 'ondestroy' NL statementsBlock ; funcDef: modifiersWithDoc 'function' funcSignature NL statementsBlock ; modifiersWithDoc: (hotdocComment NL)? modifiers+=modifier* ; modifier: modType=( 'public' | 'private' | 'protected' | 'publicread' | 'static' | 'override' | 'abstract' | 'constant' ) | annotation ; annotation: ANNOTATION; hotdocComment: HOTDOC_COMMENT; funcSignature: name=ID typeParams formalParameters ('returns' returnType=typeExpr)? ; formalParameters: '(' (params+=formalParameter (',' params+=formalParameter)*)? ')'; formalParameter: typeExpr name=ID ; typeExpr: thistype='thistype' | typeName=ID typeArgs | typeExpr 'array' ('[' arraySize=expr ']')? ; varDef: modifiersWithDoc ('var'|constant='constant' varType=typeExpr?|constant='let'|varType=typeExpr) name=ID ('=' initial=expr)? NL ; statements: statement* ; statementsBlock: (STARTBLOCK statement* ENDBLOCK)?; statement: ( localVarDef | stmtSet | stmtReturn | stmtBreak | stmtSkip | expr ) NL | stmtIf | stmtWhile | stmtForLoop | stmtSwitch ; exprDestroy: 'destroy' expr ; stmtReturn: 'return' expr ; stmtIf: 'if' cond=expr NL thenStatements=statementsBlock ('else' elseStatements)? ; elseStatements: stmtIf | NL statementsBlock ; stmtSwitch: 'switch' expr NL (STARTBLOCK switchCase* switchDefaultCase? ENDBLOCK)? ; switchCase: 'case' expr NL statementsBlock ; switchDefaultCase: 'default' NL statementsBlock ; stmtWhile: 'while' cond=expr NL statementsBlock ; localVarDef: (var='var'|let='let'|type=typeExpr) name=ID ('=' initial=expr)? ; localVarDefInline: typeExpr? name=ID ; stmtSet: left=exprAssignable (assignOp=('='|'+='|'-='|'*='|'/=') right=expr | incOp='++' | decOp='--' ) ; exprAssignable: exprMemberVar | exprVarAccess ; exprMemberVar: expr dots=('.'|'..') varname=ID indexes? ; exprVarAccess: varname=ID indexes? ; indexes: '[' expr ']' ; stmtCall: exprMemberMethod | exprFunctionCall | exprNewObject ; exprMemberMethod: receiver=expr dots=('.'|'..') funcName=ID? typeArgs ('(' exprList ')')? ; expr: exprPrimary | left=expr 'castTo' castToType=typeExpr | left=expr 'instanceof' instaneofType=typeExpr | receiver=expr dotsCall=('.'|'..') funcName=ID? typeArgs '(' exprList ')' | receiver=expr dotsVar=('.'|'..') varName=ID? indexes? | left=expr op=('*'|'/'|'%'|'div'|'mod') right=expr | op='-' right=expr // TODO move unary minus one up to be compatible with Java etc. // currently it is here to be backwards compatible with the old wurst parser | left=expr op=('+'|'-') right=expr | left=expr op=('<='|'<'|'>'|'>=') right=expr | left=expr op=('=='|'!=') right=expr | op='not' right=expr | left=expr op='and' right=expr | left=expr op='or' right=expr | ; exprPrimary: exprFunctionCall | exprNewObject | exprClosure | exprStatementsBlock | exprDestroy | varname=ID indexes? | atom=(INT | REAL | STRING | 'null' | 'true' | 'false' | 'this' | 'super') | exprFuncRef | '(' expr ')' ; exprFuncRef: 'function' (scopeName=ID '.')? funcName=ID; exprStatementsBlock: 'begin' NL statementsBlock 'end' ; exprFunctionCall: funcName=ID typeArgs '(' exprList ')' ; exprNewObject:'new' className=ID typeArgs ('(' exprList ')')?; exprClosure: formalParameters '->' expr; typeParams: ('<' (params+=typeParam (',' params+=typeParam)*)? '>')?; typeParam: name=ID; stmtForLoop: forRangeLoop | forIteratorLoop ; forRangeLoop: 'for' loopVar=localVarDefInline '=' start=expr direction=('to'|'downto') end=expr ('step' step=expr)? NL statementsBlock ; forIteratorLoop: 'for' loopVar=localVarDefInline iterStyle=('in'|'from') iteratorExpr=expr NL statementsBlock ; stmtBreak:'break'; stmtSkip:'skip'; typeArgs: ('<' (args+=typeExpr (',' args+=typeExpr)*)? '>')?; exprList : exprs+=expr (',' exprs+=expr)*; nativeType: 'nativetype' name=ID ('extends' extended=ID)? NL; initBlock: 'init' NL statementsBlock; nativeDef: modifiersWithDoc 'native' funcSignature NL; tupleDef: modifiersWithDoc 'tuple' name=ID formalParameters NL; extensionFuncDef: modifiersWithDoc 'function' receiverType=typeExpr '.' funcSignature NL statementsBlock; // Lexer: CLASS: 'class'; RETURN: 'return'; IF: 'if'; ELSE: 'else'; WHILE: 'while'; FOR: 'for'; IN: 'in'; BREAK: 'break'; NEW: 'new'; NULL: 'null'; PACKAGE: 'package'; ENDPACKAGE: 'endpackage'; FUNCTION: 'function'; RETURNS: 'returns'; PUBLIC: 'public'; PULBICREAD: 'publicread'; PRIVATE: 'private'; PROTECTED: 'protected'; IMPORT: 'import'; INITLATER: 'initlater'; NATIVE: 'native'; NATIVETYPE: 'nativetype'; EXTENDS: 'extends'; INTERFACE: 'interface'; IMPLEMENTS: 'implements'; MODULE: 'module'; USE: 'use'; ABSTRACT: 'abstract'; STATIC: 'static'; THISTYPE: 'thistype'; OVERRIDE: 'override'; IMMUTABLE: 'immutable'; IT: 'it'; ARRAY: 'array'; AND: 'and'; OR: 'or'; NOT: 'not'; THIS: 'this'; CONSTRUCT: 'construct'; ONDESTROY: 'ondestroy'; DESTROY: 'destroy'; TYPE: 'type'; CONSTANT: 'constant'; ENDFUNCTION: 'endfunction'; NOTHING: 'nothing'; INIT: 'init'; CASTTO: 'castTo'; TUPLE: 'tuple'; DIV: 'div'; MOD: 'mod'; LET: 'let'; FROM: 'from'; TO: 'to'; DOWNTO: 'downto'; STEP: 'step'; SKIP: 'skip'; TRUE: 'true'; FALSE: 'false'; VAR: 'var'; INSTANCEOF: 'instanceof'; SUPER: 'super'; ENUM: 'enum'; SWITCH: 'switch'; CASE: 'case'; DEFAULT: 'default'; BEGIN: 'begin'; END: 'end'; LIBRARY: 'library'; ENDLIBRARY: 'endlibrary'; SCOPE: 'scope'; ENDSCOPE: 'endscope'; REQUIRES: 'requires'; USES: 'uses'; NEEDS: 'needs'; STRUCT: 'struct'; ENDSTRUCT: 'endstruct'; THEN: 'then'; ENDIF: 'endif'; LOOP: 'loop'; EXITHWHEN: 'exithwhen'; ENDLOOP: 'endloop'; METHOD: 'method'; TAKES: 'takes'; ENDMETHOD: 'endmethod'; SET: 'set'; CALL: 'call'; EXITWHEN: 'exitwhen'; COMMA: ','; PLUS: '+'; PLUSPLUS: '++'; MINUS: '-'; MINUSMINUS: '--'; MULT: '*'; DIV_REAL: '/'; MOD_REAL: '%'; DOT: '.'; DOTDOT: '..'; PAREN_LEFT: '('; PAREN_RIGHT: ')'; BRACKET_LEFT: '['; BRACKET_RIGHT: ']'; EQ: '='; EQEQ: '=='; NOT_EQ: '!='; LESS: '<'; LESS_EQ: '<='; GREATER: '>'; GREATER_EQ: '>='; PLUS_EQ: '+='; MINUS_EQ: '-='; MULT_EQ: '*='; DIV_EQ: '/='; ARROW: '->'; STARTBLOCK:[]; ENDBLOCK:[]; INVALID:[]; JASS_GLOBALS: 'globals'; JASS_ENDGLOBALS: 'endglobals'; JASS_LOCAL: 'local'; JASS_ELSEIF: 'elseif'; NL: [\r\n]+; ID: [a-zA-Z_][a-zA-Z0-9_]* ; ANNOTATION: '@' [a-zA-Z0-9_]+; STRING: '"' ( EscapeSequence | ~('\\'|'"'|'\r'|'\n') )* '"'; REAL: [0-9]+ '.' [0-9]* | '.'[0-9]+; INT: [0-9]+ | '0x' [0-9a-fA-F]+ | '\'' . . . . '\'' | '\'' . '\''; fragment EscapeSequence: '\\' [abfnrtvz"'\\]; TAB: [\t]; WS : [ ]+ -> skip ; HOTDOC_COMMENT: '/**' .*? '*/'; ML_COMMENT: '/*' .*? '*/' -> skip; LINE_COMMENT: '//' ~[\r\n]* -> skip;
grammar Wurst; compilationUnit : NL* decls+=topLevelDeclaration*; topLevelDeclaration: wpackage | jassTopLevelDeclaration ; jassTopLevelDeclaration: jassGlobalsBlock | jassFuncDef | jassTypeDecl | jassNativeDecl ; jassGlobalsBlock: 'globals' NL vars+=jassGlobalDecl* 'endglobals' NL ; jassGlobalDecl: constant='constant'? typeExpr name=ID ('=' initial=expr)? NL ; jassFuncDef: constant='constant'? 'function' jassFuncSignature NL (jassLocals+=jassLocal)* jassStatements 'endfunction' NL ; jassLocal: 'local' typeExpr name=ID ('=' initial=expr)? NL; jassStatements: stmts+=jassStatement*; jassStatement: jassStatementIf | jassStatementLoop | jassStatementExithwhen | jassStatementReturn | jassStatementSet | jassStatementCall ; jassStatementIf: 'if' cond=expr 'then' NL thenStatements=jassStatements jassElseIfs ; jassElseIfs: 'elseif' cond=expr 'then' NL thenStatements=jassStatements jassElseIfs | 'else' NL elseStmts=jassStatements 'endif' NL | 'endif' NL ; jassStatementLoop: 'loop' NL jassStatements 'endloop' NL ; jassStatementExithwhen: 'exitwhen' cond=expr NL ; jassStatementReturn: 'return' expr NL ; jassStatementSet: 'set' left=exprAssignable '=' right=expr NL ; jassStatementCall: 'call' exprFunctionCall NL ; jassNativeDecl: constant='constant'? 'native' jassFuncSignature NL ; jassFuncSignature: name=ID 'takes' ('nothing' | args+=formalParameter (',' args+=formalParameter)*) 'returns' ('nothing'|returnType=typeExpr) ; jassTypeDecl: 'type' name=ID 'extends' extended=typeExpr NL; wpackage: 'package' name=ID NL ( imports+=wImport* entities+=entity* | STARTBLOCK imports+=wImport* entities+=entity* ENDBLOCK ) 'endpackage' NL ; wImport: 'import' isPublic='public'? isInitLater='initlater'? importedPackage=ID NL ; entity: nativeType | funcDef | varDef | initBlock | nativeDef | classDef | enumDef | moduleDef | interfaceDef | tupleDef | extensionFuncDef ; interfaceDef: modifiersWithDoc 'interface' name=ID typeParams ('extends' extended+=typeExpr (',' extended+=typeExpr)*)? NL (STARTBLOCK classSlots ENDBLOCK)? ; classDef: modifiersWithDoc 'class' name=ID typeParams ('extends' extended=typeExpr)? ('implements' implemented+=typeExpr (',' implemented+=typeExpr)*)? NL (STARTBLOCK classSlots ENDBLOCK)? ; enumDef: modifiersWithDoc 'enum' name=ID NL (STARTBLOCK (enumMembers+=ID NL)* ENDBLOCK)?; moduleDef: modifiersWithDoc 'module' name=ID typeParams NL STARTBLOCK classSlots ENDBLOCK ; classSlots: slots+=classSlot*; classSlot: constructorDef | moduleUse | ondestroyDef | varDef | funcDef ; constructorDef: modifiersWithDoc 'construct' formalParameters NL (STARTBLOCK ('super' '(' superArgs=exprList ')' NL)? stmts+=statement* ENDBLOCK)? ; moduleUse: modifiersWithDoc 'use' moduleName=ID typeArgs NL ; ondestroyDef: 'ondestroy' NL statementsBlock ; funcDef: modifiersWithDoc 'function' funcSignature NL statementsBlock ; modifiersWithDoc: (hotdocComment NL)? (modifiers+=modifier NL?)* ; modifier: modType=( 'public' | 'private' | 'protected' | 'publicread' | 'static' | 'override' | 'abstract' | 'constant' ) | annotation ; annotation: ANNOTATION; hotdocComment: HOTDOC_COMMENT; funcSignature: name=ID typeParams formalParameters ('returns' returnType=typeExpr)? ; formalParameters: '(' (params+=formalParameter (',' params+=formalParameter)*)? ')'; formalParameter: typeExpr name=ID ; typeExpr: thistype='thistype' | typeName=ID typeArgs | typeExpr 'array' ('[' arraySize=expr ']')? ; varDef: modifiersWithDoc ('var'|constant='constant' varType=typeExpr?|constant='let'|varType=typeExpr) name=ID ('=' initial=expr)? NL ; statements: statement* ; statementsBlock: (STARTBLOCK statement* ENDBLOCK)?; statement: ( localVarDef | stmtSet | stmtReturn | stmtBreak | stmtSkip | expr ) NL | stmtIf | stmtWhile | stmtForLoop | stmtSwitch ; exprDestroy: 'destroy' expr ; stmtReturn: 'return' expr ; stmtIf: 'if' cond=expr NL thenStatements=statementsBlock ('else' elseStatements)? ; elseStatements: stmtIf | NL statementsBlock ; stmtSwitch: 'switch' expr NL (STARTBLOCK switchCase* switchDefaultCase? ENDBLOCK)? ; switchCase: 'case' expr NL statementsBlock ; switchDefaultCase: 'default' NL statementsBlock ; stmtWhile: 'while' cond=expr NL statementsBlock ; localVarDef: (var='var'|let='let'|type=typeExpr) name=ID ('=' initial=expr)? ; localVarDefInline: typeExpr? name=ID ; stmtSet: left=exprAssignable (assignOp=('='|'+='|'-='|'*='|'/=') right=expr | incOp='++' | decOp='--' ) ; exprAssignable: exprMemberVar | exprVarAccess ; exprMemberVar: expr dots=('.'|'..') varname=ID indexes? ; exprVarAccess: varname=ID indexes? ; indexes: '[' expr ']' ; stmtCall: exprMemberMethod | exprFunctionCall | exprNewObject ; exprMemberMethod: receiver=expr dots=('.'|'..') funcName=ID? typeArgs ('(' exprList ')')? ; expr: exprPrimary | left=expr 'castTo' castToType=typeExpr | left=expr 'instanceof' instaneofType=typeExpr | receiver=expr dotsCall=('.'|'..') funcName=ID? typeArgs '(' exprList ')' | receiver=expr dotsVar=('.'|'..') varName=ID? indexes? | left=expr op=('*'|'/'|'%'|'div'|'mod') right=expr | op='-' right=expr // TODO move unary minus one up to be compatible with Java etc. // currently it is here to be backwards compatible with the old wurst parser | left=expr op=('+'|'-') right=expr | left=expr op=('<='|'<'|'>'|'>=') right=expr | left=expr op=('=='|'!=') right=expr | op='not' right=expr | left=expr op='and' right=expr | left=expr op='or' right=expr | ; exprPrimary: exprFunctionCall | exprNewObject | exprClosure | exprStatementsBlock | exprDestroy | varname=ID indexes? | atom=(INT | REAL | STRING | 'null' | 'true' | 'false' | 'this' | 'super') | exprFuncRef | '(' expr ')' ; exprFuncRef: 'function' (scopeName=ID '.')? funcName=ID; exprStatementsBlock: 'begin' NL statementsBlock 'end' ; exprFunctionCall: funcName=ID typeArgs '(' exprList ')' ; exprNewObject:'new' className=ID typeArgs ('(' exprList ')')?; exprClosure: formalParameters '->' expr; typeParams: ('<' (params+=typeParam (',' params+=typeParam)*)? '>')?; typeParam: name=ID; stmtForLoop: forRangeLoop | forIteratorLoop ; forRangeLoop: 'for' loopVar=localVarDefInline '=' start=expr direction=('to'|'downto') end=expr ('step' step=expr)? NL statementsBlock ; forIteratorLoop: 'for' loopVar=localVarDefInline iterStyle=('in'|'from') iteratorExpr=expr NL statementsBlock ; stmtBreak:'break'; stmtSkip:'skip'; typeArgs: ('<' (args+=typeExpr (',' args+=typeExpr)*)? '>')?; exprList : exprs+=expr (',' exprs+=expr)*; nativeType: 'nativetype' name=ID ('extends' extended=ID)? NL; initBlock: 'init' NL statementsBlock; nativeDef: modifiersWithDoc 'native' funcSignature NL; tupleDef: modifiersWithDoc 'tuple' name=ID formalParameters NL; extensionFuncDef: modifiersWithDoc 'function' receiverType=typeExpr '.' funcSignature NL statementsBlock; // Lexer: CLASS: 'class'; RETURN: 'return'; IF: 'if'; ELSE: 'else'; WHILE: 'while'; FOR: 'for'; IN: 'in'; BREAK: 'break'; NEW: 'new'; NULL: 'null'; PACKAGE: 'package'; ENDPACKAGE: 'endpackage'; FUNCTION: 'function'; RETURNS: 'returns'; PUBLIC: 'public'; PULBICREAD: 'publicread'; PRIVATE: 'private'; PROTECTED: 'protected'; IMPORT: 'import'; INITLATER: 'initlater'; NATIVE: 'native'; NATIVETYPE: 'nativetype'; EXTENDS: 'extends'; INTERFACE: 'interface'; IMPLEMENTS: 'implements'; MODULE: 'module'; USE: 'use'; ABSTRACT: 'abstract'; STATIC: 'static'; THISTYPE: 'thistype'; OVERRIDE: 'override'; IMMUTABLE: 'immutable'; IT: 'it'; ARRAY: 'array'; AND: 'and'; OR: 'or'; NOT: 'not'; THIS: 'this'; CONSTRUCT: 'construct'; ONDESTROY: 'ondestroy'; DESTROY: 'destroy'; TYPE: 'type'; CONSTANT: 'constant'; ENDFUNCTION: 'endfunction'; NOTHING: 'nothing'; INIT: 'init'; CASTTO: 'castTo'; TUPLE: 'tuple'; DIV: 'div'; MOD: 'mod'; LET: 'let'; FROM: 'from'; TO: 'to'; DOWNTO: 'downto'; STEP: 'step'; SKIP: 'skip'; TRUE: 'true'; FALSE: 'false'; VAR: 'var'; INSTANCEOF: 'instanceof'; SUPER: 'super'; ENUM: 'enum'; SWITCH: 'switch'; CASE: 'case'; DEFAULT: 'default'; BEGIN: 'begin'; END: 'end'; LIBRARY: 'library'; ENDLIBRARY: 'endlibrary'; SCOPE: 'scope'; ENDSCOPE: 'endscope'; REQUIRES: 'requires'; USES: 'uses'; NEEDS: 'needs'; STRUCT: 'struct'; ENDSTRUCT: 'endstruct'; THEN: 'then'; ENDIF: 'endif'; LOOP: 'loop'; EXITHWHEN: 'exithwhen'; ENDLOOP: 'endloop'; METHOD: 'method'; TAKES: 'takes'; ENDMETHOD: 'endmethod'; SET: 'set'; CALL: 'call'; EXITWHEN: 'exitwhen'; COMMA: ','; PLUS: '+'; PLUSPLUS: '++'; MINUS: '-'; MINUSMINUS: '--'; MULT: '*'; DIV_REAL: '/'; MOD_REAL: '%'; DOT: '.'; DOTDOT: '..'; PAREN_LEFT: '('; PAREN_RIGHT: ')'; BRACKET_LEFT: '['; BRACKET_RIGHT: ']'; EQ: '='; EQEQ: '=='; NOT_EQ: '!='; LESS: '<'; LESS_EQ: '<='; GREATER: '>'; GREATER_EQ: '>='; PLUS_EQ: '+='; MINUS_EQ: '-='; MULT_EQ: '*='; DIV_EQ: '/='; ARROW: '->'; STARTBLOCK:[]; ENDBLOCK:[]; INVALID:[]; JASS_GLOBALS: 'globals'; JASS_ENDGLOBALS: 'endglobals'; JASS_LOCAL: 'local'; JASS_ELSEIF: 'elseif'; NL: [\r\n]+; ID: [a-zA-Z_][a-zA-Z0-9_]* ; ANNOTATION: '@' [a-zA-Z0-9_]+; STRING: '"' ( EscapeSequence | ~('\\'|'"'|'\r'|'\n') )* '"'; REAL: [0-9]+ '.' [0-9]* | '.'[0-9]+; INT: [0-9]+ | '0x' [0-9a-fA-F]+ | '\'' . . . . '\'' | '\'' . '\''; fragment EscapeSequence: '\\' [abfnrtvz"'\\]; TAB: [\t]; WS : [ ]+ -> skip ; HOTDOC_COMMENT: '/**' .*? '*/'; ML_COMMENT: '/*' .*? '*/' -> skip; LINE_COMMENT: '//' ~[\r\n]* -> skip;
allow newline after annotations and modifiers
allow newline after annotations and modifiers
ANTLR
apache-2.0
Cokemonkey11/WurstScript,wurstscript/WurstScript,peq/WurstScript,Cokemonkey11/WurstScript,Cokemonkey11/WurstScript,wurstscript/WurstScript,Cokemonkey11/WurstScript,Crigges/WurstScript,wurstscript/WurstScript,peq/WurstScript,Cokemonkey11/WurstScript,Crigges/WurstScript,Crigges/WurstScript,peq/WurstScript,Crigges/WurstScript,Crigges/WurstScript,Crigges/WurstScript,peq/WurstScript,Crigges/WurstScript,Crigges/WurstScript
59cb8b24ee16cc04d523e07330359851c63b15c1
kquery/KQuery.g4
kquery/KQuery.g4
/* [The "BSD licence"] Copyright (c) 2013 Sumit Lahiri 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. */ // Grammar for KLEE KQuery parsing. (A bit more verbose with richer parsing) // Ported to Antlr4 by Sumit Lahiri. grammar KQuery; kqueryExpression : ktranslationUnit* EOF ; ktranslationUnit : arrayDeclaration | queryCommand ; queryCommand : LeftParen Query evalExprList queryExpr RightParen ; queryExpr : expression | expression evalExprList | expression evalExprList evalArrayList ; evalExprList : LeftBracket expression* RightBracket ; evalArrayList : LeftBracket Identifier* RightBracket ; arrayDeclaration : Array arrName LeftBracket numArrayElements RightBracket Colon domain Arrow rangeLimit Equal arrayInitializer ; numArrayElements : Constant ; arrayInitializer : Symbolic | LeftBracket numberList RightBracket ; expression : varName | namedConstant Colon fullyQualifiedExpression | LeftParen widthOrSizeExpr number RightParen | LeftParen arithmeticExpr widthOrSizeExpr leftExpr rightExpr RightParen | LeftParen notExpr LeftBracket widthOrSizeExpr RightBracket expression RightParen | LeftParen bitwiseExpr widthOrSizeExpr leftExpr rightExpr RightParen | LeftParen comparisonExpr widthOrSizeExpr leftExpr rightExpr RightParen | LeftParen comparisonExpr leftExpr rightExpr RightParen | LeftParen concatExpr widthOrSizeExpr leftExpr rightExpr RightParen | LeftParen concatExpr leftExpr rightExpr RightParen | LeftParen arrExtractExpr widthOrSizeExpr number expression RightParen | LeftParen bitExtractExpr widthOrSizeExpr expression RightParen | LeftParen genericBitRead widthOrSizeExpr expression version RightParen | LeftParen selectExpr widthOrSizeExpr leftExpr rightExpr expression RightParen | LeftParen exprNegation widthOrSizeExpr expression RightParen | LeftParen exprNegation expression RightParen | LeftParen genericBitRead widthOrSizeExpr expression RightParen | version | number ; genericBitRead : READ | READLSB | READMSB ; bitExtractExpr : ZEXT | SEXT ; version : varName | namedConstant Colon fullyQualifiedExpression | LeftBracket updateList RightBracket ATR version | LeftBracket RightBracket ATR version ; fullyQualifiedExpression : expression ; notExpr : NOT ; concatExpr : CONCAT ; exprNegation : NEGETION ; selectExpr : SELECT ; arrExtractExpr : EXTRACT ; varName : Identifier ; leftExpr : expression ; rightExpr : expression ; namedConstant : Identifier ; updateList : expression Equal expression COMMA updateList | expression Equal expression ; bitwiseExpr : BITWISEAND | BITWISEOR | BITWISEXOR | SHL | LSHR | ASHR ; comparisonExpr : EQ | NEQ | ULT | UGT | ULE | UGE | SLT | SLE | SGT | SGE ; arithmeticExpr : ADD | SUB | MUL | UDIV | UREM | SDIV | SREM ; domain : widthOrSizeExpr ; rangeLimit : widthOrSizeExpr ; arrName : Identifier ; numberList : number | number numberList ; number : boolnum | signedConstant | constant ; constant: Constant; boolnum: Boolean; signedConstant: SignedConstant; Boolean : TrueMatch | FalseMatch ; SignedConstant : (PLUS | MINUS)Constant ; Constant : DIGIT+ | BinConstant | OctConstant | HexConstant ; BinConstant : BinId BIN_DIGIT+ ; OctConstant : OctId OCTAL_DIGIT+ ; HexConstant : HexId HEX_DIGIT+ ; FloatingPointType : FP DIGIT ((.).*?)? ; IntegerType : INT DIGIT+ ; widthOrSizeExpr : WidthType ; WidthType : WIDTH DIGIT+ ; BinId : '0b'; OctId : '0o'; WIDTH : 'w'; HexId : '0x'; TrueMatch : 'true'; FalseMatch : 'false'; Query : 'query'; Array : 'array'; Symbolic : 'symbolic'; Colon : ':'; Arrow : '->'; Equal : '='; COMMA : ','; NOT : 'Not'; SHL : 'Shl'; LSHR : 'LShr'; ASHR : 'AShr'; CONCAT : 'Concat'; EXTRACT: 'Extract'; ZEXT: 'ZExt'; SEXT: 'SExt'; READ: 'Read'; SELECT: 'Select'; NEGETION: 'Neg'; READLSB: 'ReadLSB'; READMSB: 'ReadMSB'; PLUS : '+'; MINUS : '-'; ATR : '@'; FP : 'fp'; BITWISEAND : 'And'; BITWISEOR : 'Or'; BITWISEXOR : 'Xor'; EQ : 'Eq'; NEQ : 'Ne' ; ULT : 'Ult' ; ULE : 'Ule' ; UGT : 'Ugt' ; UGE : 'Uge' ; SLT : 'Slt' ; SLE : 'Sle' ; SGT : 'Sgt' ; SGE : 'Sge' ; ADD : 'Add' ; SUB : 'Sub' ; MUL : 'Mul' ; UDIV : 'UDiv'; UREM : 'URem'; SDIV : 'SDiv'; SREM : 'SRem'; fragment DIGIT : ('0'..'9') ; fragment BIN_DIGIT : ('0' | '1' | '_') ; fragment OCTAL_DIGIT : ('0'..'7' | '_') ; fragment HEX_DIGIT : ('0'..'9'|'a'..'f'|'A'..'F'|'_') ; Identifier : ('a'..'z' | 'A'..'Z' | '_')('a'..'z' | 'A'..'Z' | '_' | '0'..'9' | '.' )* ; INT : 'i'; Whitespace : [ \t]+ -> skip ; Newline : ( '\r' '\n'? | '\n' ) -> skip ; BlockComment : '/*' .*? '*/' -> skip ; LineComment : '#' ~[\r\n]* -> skip ; LeftParen : '('; RightParen : ')'; LeftBracket : '['; RightBracket : ']'; LeftBrace : '{'; RightBrace : '}';
/* [The "BSD licence"] Copyright (c) 2013 Sumit Lahiri 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. */ // Grammar for KLEE KQuery parsing. (A bit more verbose with richer parsing) // Ported to Antlr4 by Sumit Lahiri. grammar KQuery; kqueryExpression : queryStatements EOF ; queryStatements : (ktranslationUnit)* ; ktranslationUnit : arrayDeclaration | queryCommand ; queryCommand : LeftParen Query evalExprList queryExpr RightParen ; queryExpr : expression | expression evalExprList | expression evalExprList evalArrayList ; evalExprList : LeftBracket expression* RightBracket ; evalArrayList : LeftBracket Identifier* RightBracket ; arrayDeclaration : Array arrName LeftBracket numArrayElements RightBracket Colon domain Arrow rangeLimit Equal arrayInitializer ; numArrayElements : Constant ; arrayInitializer : Symbolic | LeftBracket numberList RightBracket ; expression : varName | namedConstant Colon fullyQualifiedExpression | LeftParen widthOrSizeExpr number RightParen | LeftParen arithmeticExpr widthOrSizeExpr leftExpr rightExpr RightParen | LeftParen notExpr LeftBracket widthOrSizeExpr RightBracket expression RightParen | LeftParen bitwiseExpr widthOrSizeExpr leftExpr rightExpr RightParen | LeftParen comparisonExpr widthOrSizeExpr leftExpr rightExpr RightParen | LeftParen comparisonExpr leftExpr rightExpr RightParen | LeftParen concatExpr widthOrSizeExpr leftExpr rightExpr RightParen | LeftParen concatExpr leftExpr rightExpr RightParen | LeftParen arrExtractExpr widthOrSizeExpr number expression RightParen | LeftParen bitExtractExpr widthOrSizeExpr expression RightParen | LeftParen genericBitRead widthOrSizeExpr expression version RightParen | LeftParen selectExpr widthOrSizeExpr leftExpr rightExpr expression RightParen | LeftParen exprNegation widthOrSizeExpr expression RightParen | LeftParen exprNegation expression RightParen | LeftParen genericBitRead widthOrSizeExpr expression RightParen | version | number ; genericBitRead : READ | READLSB | READMSB ; bitExtractExpr : ZEXT | SEXT ; version : varName | namedConstant Colon fullyQualifiedExpression | LeftBracket updateList RightBracket ATR version | LeftBracket RightBracket ATR version ; fullyQualifiedExpression : expression ; notExpr : NOT ; concatExpr : CONCAT ; exprNegation : NEGETION ; selectExpr : SELECT ; arrExtractExpr : EXTRACT ; varName : Identifier ; leftExpr : expression ; rightExpr : expression ; namedConstant : Identifier ; updateList : expression Equal expression COMMA updateList | expression Equal expression ; bitwiseExpr : BITWISEAND | BITWISEOR | BITWISEXOR | SHL | LSHR | ASHR ; comparisonExpr : EQ | NEQ | ULT | UGT | ULE | UGE | SLT | SLE | SGT | SGE ; arithmeticExpr : ADD | SUB | MUL | UDIV | UREM | SDIV | SREM ; domain : widthOrSizeExpr ; rangeLimit : widthOrSizeExpr ; arrName : Identifier ; numberList : number | number numberList ; number : boolnum | signedConstant | constant ; constant: Constant; boolnum: Boolean; signedConstant: SignedConstant; Boolean : TrueMatch | FalseMatch ; SignedConstant : (PLUS | MINUS)Constant ; Constant : DIGIT+ | BinConstant | OctConstant | HexConstant ; BinConstant : BinId BIN_DIGIT+ ; OctConstant : OctId OCTAL_DIGIT+ ; HexConstant : HexId HEX_DIGIT+ ; FloatingPointType : FP DIGIT ((.).*?)? ; IntegerType : INT DIGIT+ ; widthOrSizeExpr : WidthType ; WidthType : WIDTH DIGIT+ ; BinId : '0b'; OctId : '0o'; WIDTH : 'w'; HexId : '0x'; TrueMatch : 'true'; FalseMatch : 'false'; Query : 'query'; Array : 'array'; Symbolic : 'symbolic'; Colon : ':'; Arrow : '->'; Equal : '='; COMMA : ','; NOT : 'Not'; SHL : 'Shl'; LSHR : 'LShr'; ASHR : 'AShr'; CONCAT : 'Concat'; EXTRACT: 'Extract'; ZEXT: 'ZExt'; SEXT: 'SExt'; READ: 'Read'; SELECT: 'Select'; NEGETION: 'Neg'; READLSB: 'ReadLSB'; READMSB: 'ReadMSB'; PLUS : '+'; MINUS : '-'; ATR : '@'; FP : 'fp'; BITWISEAND : 'And'; BITWISEOR : 'Or'; BITWISEXOR : 'Xor'; EQ : 'Eq'; NEQ : 'Ne' ; ULT : 'Ult' ; ULE : 'Ule' ; UGT : 'Ugt' ; UGE : 'Uge' ; SLT : 'Slt' ; SLE : 'Sle' ; SGT : 'Sgt' ; SGE : 'Sge' ; ADD : 'Add' ; SUB : 'Sub' ; MUL : 'Mul' ; UDIV : 'UDiv'; UREM : 'URem'; SDIV : 'SDiv'; SREM : 'SRem'; fragment DIGIT : ('0'..'9') ; fragment BIN_DIGIT : ('0' | '1' | '_') ; fragment OCTAL_DIGIT : ('0'..'7' | '_') ; fragment HEX_DIGIT : ('0'..'9'|'a'..'f'|'A'..'F'|'_') ; Identifier : ('a'..'z' | 'A'..'Z' | '_')('a'..'z' | 'A'..'Z' | '_' | '0'..'9' | '.' )* ; INT : 'i'; Whitespace : [ \t]+ -> skip ; Newline : ( '\r' '\n'? | '\n' ) -> skip ; BlockComment : '/*' .*? '*/' -> skip ; LineComment : '#' ~[\r\n]* -> skip ; LeftParen : '('; RightParen : ')'; LeftBracket : '['; RightBracket : ']'; LeftBrace : '{'; RightBrace : '}';
Update KQuery.g4
Update KQuery.g4
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
54bdd611119013f3b8094a681883f58ef261c6c2
Code/src/main/antlr4/nl/utwente/group10/haskell/typeparser/Type.g4
Code/src/main/antlr4/nl/utwente/group10/haskell/typeparser/Type.g4
grammar Type; CT : [A-Z][a-z]+ ; VT : [a-z]+ ; WS : [ \t\r\n]+ -> skip ; baseType : typeClasses ? type ; type : functionType | compoundType ; // function type functionType : compoundType '->' type ; compoundType : constantType | variableType | tupleType | listType | parenType ; tupleType : '(' type (',' type)+ ')' ; // tuple type, k>=2 listType : '[' type ']' ; // list type parenType : '(' type ')' ; // type with parentheses constantType : typeConstructor (WS* type)* ; typeConstructor : CT ; variableType : VT ; typeClasses : '(' typeWithClass (',' typeWithClass)* ')' '=>' ; typeWithClass : typeClass WS* classedType ; classedType : VT ; typeClass : CT ;
grammar Type; CT : [A-Z][a-z]+ ; VT : [a-z]+ ; WS : [ \t\r\n]+ -> skip ; type : typeClasses ? innerType ; innerType : functionType | compoundType ; // function type functionType : compoundType '->' innerType ; compoundType : constantType | variableType | tupleType | listType | parenType ; tupleType : '(' innerType (',' innerType)+ ')' ; // tuple type, k>=2 listType : '[' innerType ']' ; // list type parenType : '(' innerType ')' ; // type with parentheses constantType : typeConstructor (WS* innerType)* ; typeConstructor : CT ; variableType : VT ; typeClasses : '(' typeWithClass (',' typeWithClass)* ')' '=>' ; typeWithClass : typeClass WS* classedType ; classedType : VT ; typeClass : CT ;
Fix bug in Antlr grammar
Fix bug in Antlr grammar
ANTLR
mit
viskell/viskell,andrewdavidmackenzie/viskell,wandernauta/viskell
3a779f34b286a4d30ed89e0c2b042dc589cced83
grakn-graql/src/main/antlr4/ai/grakn/graql/internal/antlr/GraqlTemplate.g4
grakn-graql/src/main/antlr4/ai/grakn/graql/internal/antlr/GraqlTemplate.g4
grammar GraqlTemplate; @lexer::members { public static final int WHITESPACE = 1; public static final int COMMENTS = 2; } template : blockContents EOF ; block : '{' blockContents '}' ; blockContents : (statement | graqlVariable | keyword | ID)* ; statement : forStatement | ifStatement | replaceStatement ; forStatement : FOR LPAREN (ID IN expr | expr) RPAREN DO block ; ifStatement : ifPartial elseIfPartial* elsePartial? ; ifPartial : IF LPAREN expr RPAREN DO block ; elseIfPartial : ELSEIF LPAREN expr RPAREN DO block ; elsePartial : ELSE block ; macro : ID_MACRO LPAREN expr? (',' expr)* RPAREN ; // evaluate and return value expr : LPAREN expr RPAREN #groupExpression | NOT expr #notExpression | expr EQ expr #eqExpression | expr NEQ expr #notEqExpression | expr OR expr #orExpression | expr AND expr #andExpression | expr GREATER expr #greaterExpression | expr GREATEREQ expr #greaterEqExpression | expr LESS expr #lessExpression | expr LESSEQ expr #lessEqExpression | STRING #stringExpression | INT #intExpression | DOUBLE #doubleExpression | BOOLEAN #booleanExpression | NULL #nullExpression | resolve #resolveExpression | macro #macroExpression ; resolve : '<' (ID | STRING) '>' ; replaceStatement : DOLLAR? (resolve | macro)+ ; graqlVariable : ID_GRAQL ; keyword : ',' | ';' | RPAREN | LPAREN | ':' | FOR | IF | ELSEIF | ELSE | TRUE | FALSE | DO | IN | BOOLEAN | AND | OR | NOT | NULL | EQ | NEQ | GREATER | GREATEREQ | LESS | LESSEQ | QUOTE | SQOUTE | STRING ; FOR : 'for'; IF : 'if'; ELSEIF : 'elseif'; ELSE : 'else'; DO : 'do'; IN : 'in'; EQ : '='; NEQ : '!='; AND : 'and'; OR : 'or'; NOT : 'not'; GREATER : '>'; GREATEREQ : '>='; LESS : '<'; LESSEQ : '<='; LPAREN : '('; RPAREN : ')'; DOLLAR : '$'; QUOTE : '"'; SQOUTE : '\''; NULL : 'null'; INT : [0-9]+; DOUBLE : [0-9.]+; BOOLEAN : 'true' | 'false' ; ID : [a-zA-Z0-9_-]+ ('.' [a-zA-Z0-9_-]+ )*; STRING : '"' (~["\\] | ESCAPE_SEQ)* '"' | '\'' (~['\\] | ESCAPE_SEQ)* '\''; ID_GRAQL : '$' ID; ID_MACRO : '@' ID; // hidden channels WS : [ \t\r\n] -> channel(1); COMMENT : '#' .*? '\r'? ('\n' | EOF) -> channel(2); fragment ESCAPE_SEQ : '\\' . ;
grammar GraqlTemplate; @lexer::members { public static final int WHITESPACE = 1; public static final int COMMENTS = 2; } template : blockContents EOF ; block : '{' blockContents '}' ; blockContents : (statement | graqlVariable | keyword | ID)* ; statement : forStatement | ifStatement | replaceStatement ; forStatement : FOR LPAREN (ID IN expr | expr) RPAREN DO block ; ifStatement : ifPartial elseIfPartial* elsePartial? ; ifPartial : IF LPAREN expr RPAREN DO block ; elseIfPartial : ELSEIF LPAREN expr RPAREN DO block ; elsePartial : ELSE block ; macro : ID_MACRO LPAREN expr? (',' expr)* RPAREN ; // evaluate and return value expr : LPAREN expr RPAREN #groupExpression | NOT expr #notExpression | expr EQ expr #eqExpression | expr NEQ expr #notEqExpression | expr OR expr #orExpression | expr AND expr #andExpression | expr GREATER expr #greaterExpression | expr GREATEREQ expr #greaterEqExpression | expr LESS expr #lessExpression | expr LESSEQ expr #lessEqExpression | STRING #stringExpression | INT #intExpression | DOUBLE #doubleExpression | BOOLEAN #booleanExpression | NULL #nullExpression | resolve #resolveExpression | macro #macroExpression ; resolve : '<' (ID | STRING) '>' ; replaceStatement : DOLLAR? (resolve | macro)+ ; graqlVariable : ID_GRAQL ; keyword : ',' | ';' | RPAREN | LPAREN | ':' | FOR | IF | ELSEIF | ELSE | DO | IN | BOOLEAN | AND | OR | NOT | NULL | EQ | NEQ | GREATER | GREATEREQ | LESS | LESSEQ | QUOTE | SQOUTE | STRING ; FOR : 'for'; IF : 'if'; ELSEIF : 'elseif'; ELSE : 'else'; DO : 'do'; IN : 'in'; EQ : '='; NEQ : '!='; AND : 'and'; OR : 'or'; NOT : 'not'; GREATER : '>'; GREATEREQ : '>='; LESS : '<'; LESSEQ : '<='; LPAREN : '('; RPAREN : ')'; DOLLAR : '$'; QUOTE : '"'; SQOUTE : '\''; NULL : 'null'; INT : [0-9]+; DOUBLE : [0-9.]+; BOOLEAN : 'true' | 'false' ; ID : [a-zA-Z0-9_-]+ ('.' [a-zA-Z0-9_-]+ )*; STRING : '"' (~["\\] | ESCAPE_SEQ)* '"' | '\'' (~['\\] | ESCAPE_SEQ)* '\''; ID_GRAQL : '$' ID; ID_MACRO : '@' ID; // hidden channels WS : [ \t\r\n] -> channel(1); COMMENT : '#' .*? '\r'? ('\n' | EOF) -> channel(2); fragment ESCAPE_SEQ : '\\' . ;
Remove undefined tokens from Graql template syntax
Remove undefined tokens from Graql template syntax
ANTLR
agpl-3.0
graknlabs/grakn,lolski/grakn,graknlabs/grakn,lolski/grakn,graknlabs/grakn,lolski/grakn,lolski/grakn,graknlabs/grakn
8bc2e6652288852b0e451878fa85562d7e3a5eaa
versions/1.0/parsers/antlr4/WdlLexer.g4
versions/1.0/parsers/antlr4/WdlLexer.g4
lexer grammar WdlLexer; channels { WdlComments, SkipChannel } // Keywords VERSION: 'version' -> pushMode(Version); IMPORT: 'import'; WORKFLOW: 'workflow'; TASK: 'task'; STRUCT: 'struct'; SCATTER: 'scatter'; CALL: 'call'; IF: 'if'; THEN: 'then'; ELSE: 'else'; ALIAS: 'alias'; AS: 'as'; In: 'in'; INPUT: 'input'; OUTPUT: 'output'; PARAMETERMETA: 'parameter_meta'; META: 'meta'; HEREDOC_COMMAND: 'command' ' '* '<<<' -> pushMode(HereDocCommand); COMMAND: 'command' ' '* '{' -> pushMode(Command); RUNTIME: 'runtime'; BOOLEAN: 'Boolean'; INT: 'Int'; FLOAT: 'Float'; STRING: 'String'; FILE: 'File'; ARRAY: 'Array'; MAP: 'Map'; PAIR: 'Pair'; OBJECT: 'Object'; OBJECT_LITERAL: 'object'; SEP: 'sep'; DEFAULT: 'default'; // Primitive Literals IntLiteral : Digits | SignedDigits ; FloatLiteral : SignedFloatFragment | FloatFragment ; BoolLiteral : 'true' | 'false' ; // Symbols LPAREN: '('; RPAREN: ')'; LBRACE: '{' -> pushMode(DEFAULT_MODE); RBRACE: '}' -> popMode; LBRACK: '['; RBRACK: ']'; ESC: '\\'; COLON: ':'; LT: '<'; GT: '>'; GTE: '>='; LTE: '<='; EQUALITY: '=='; NOTEQUAL: '!='; EQUAL: '='; AND: '&&'; OR: '||'; OPTIONAL: '?'; STAR: '*'; PLUS: '+'; MINUS: '-'; DOLLAR: '$'; COMMA: ','; SEMI: ';'; DOT: '.'; NOT: '!'; TILDE: '~'; DIVIDE: '/'; MOD: '%'; SQUOTE: '\'' -> pushMode(SquoteInterpolatedString); DQUOTE: '"' -> pushMode(DquoteInterpolatedString); WHITESPACE : [ \t\r\n]+ -> channel(HIDDEN) ; COMMENT : '#' ~[\r\n]* -> channel(HIDDEN) ; Identifier: CompleteIdentifier; mode SquoteInterpolatedString; SQuoteEscapedChar: '\\' . -> type(StringPart); SQuoteDollarString: '$' -> type(StringPart); SQuoteTildeString: '~' -> type(StringPart); SQuoteCurlyString: '{' -> type(StringPart); SQuoteCommandStart: ('${' | '~{' ) -> pushMode(DEFAULT_MODE) , type(StringCommandStart); SQuoteUnicodeEscape: '\\u' (HexDigit (HexDigit (HexDigit HexDigit?)?)?)? -> type(StringPart); EndSquote: '\'' -> popMode, type(SQUOTE); StringPart: ~[$~{\r\n']+; mode DquoteInterpolatedString; DQuoteEscapedChar: '\\' . -> type(StringPart); DQuoteTildeString: '~' -> type(StringPart); DQuoteDollarString: '$' -> type(StringPart); DQUoteCurlString: '{' -> type(StringPart); DQuoteCommandStart: ('${' | '~{' ) -> pushMode(DEFAULT_MODE), type(StringCommandStart); DQuoteUnicodeEscape: '\\u' (HexDigit (HexDigit (HexDigit HexDigit?)?)?) -> type(StringPart); EndDQuote: '"' -> popMode, type(DQUOTE); DQuoteStringPart: ~[$~{\r\n"]+ -> type(StringPart); mode HereDocCommand; HereDocUnicodeEscape: '\\u' (HexDigit (HexDigit (HexDigit HexDigit?)?)?)?; HereDocEscapedChar: '\\' . -> type(CommandStringPart); HereDocTildeString: '~' -> type(CommandStringPart); HereDocCurlyString: '{' -> type(CommandStringPart); HereDocCurlyStringCommand: '~{' -> pushMode(DEFAULT_MODE), type(StringCommandStart); HereDocEscapedEnd: '\\>>>' -> type(CommandStringPart); EndHereDocCommand: '>>>' -> popMode, type(EndCommand); HereDocEscape: ( '>' | '>>' | '>>>>' '>'*) -> type(CommandStringPart); HereDocStringPart: ~[~{>]+ -> type(CommandStringPart); mode Command; CommandEscapedChar: '\\' . -> type(CommandStringPart); CommandUnicodeEscape: '\\u' (HexDigit (HexDigit (HexDigit HexDigit?)?)?)?; CommandTildeString: '~' -> type(CommandStringPart); CommandDollarString: '$' -> type(CommandStringPart); CommandCurlyString: '{' -> type(CommandStringPart); StringCommandStart: ('${' | '~{' ) -> pushMode(DEFAULT_MODE); EndCommand: '}' -> popMode; CommandStringPart: ~[$~{}]+; mode Version; VERSION_WHITESPACE : [ \t]+ -> channel(HIDDEN) ; RELEASE_VERSION: [a-zA-Z0-9.-]+ -> popMode; // Fragments fragment CompleteIdentifier : IdentifierStart IdentifierFollow* ; fragment IdentifierStart : [a-zA-Z] ; fragment IdentifierFollow : [a-zA-Z0-9_]+ ; fragment EscapeSequence : '\\' [btnfr"'\\] | '\\' ([0-3]? [0-7])? [0-7] | '\\' UnicodeEsc ; fragment UnicodeEsc : 'u' (HexDigit (HexDigit (HexDigit HexDigit?)?)?)? ; fragment HexDigit : [0-9a-fA-F] ; fragment Digit : [0-9] ; fragment Digits : Digit+ ; fragment Decimals : Digits '.' Digits? | '.' Digits ; fragment SignedDigits : ('+' | '-' ) Digits ; fragment FloatFragment : Digits EXP? | Decimals EXP? ; fragment SignedFloatFragment : ('+' |'e') FloatFragment ; fragment EXP : ('e'|'E') SignedDigits ;
lexer grammar WdlLexer; channels { WdlComments, SkipChannel } // Keywords VERSION: 'version' -> pushMode(Version); IMPORT: 'import'; WORKFLOW: 'workflow'; TASK: 'task'; STRUCT: 'struct'; SCATTER: 'scatter'; CALL: 'call'; IF: 'if'; THEN: 'then'; ELSE: 'else'; ALIAS: 'alias'; AS: 'as'; In: 'in'; INPUT: 'input'; OUTPUT: 'output'; PARAMETERMETA: 'parameter_meta'; META: 'meta'; HEREDOC_COMMAND: 'command' ' '* '<<<' -> pushMode(HereDocCommand); COMMAND: 'command' ' '* '{' -> pushMode(Command); RUNTIME: 'runtime'; BOOLEAN: 'Boolean'; INT: 'Int'; FLOAT: 'Float'; STRING: 'String'; FILE: 'File'; ARRAY: 'Array'; MAP: 'Map'; PAIR: 'Pair'; OBJECT: 'Object'; OBJECT_LITERAL: 'object'; SEP: 'sep'; DEFAULT: 'default'; // Primitive Literals IntLiteral : Digits ; FloatLiteral : FloatFragment ; BoolLiteral : 'true' | 'false' ; // Symbols LPAREN: '('; RPAREN: ')'; LBRACE: '{' -> pushMode(DEFAULT_MODE); RBRACE: '}' -> popMode; LBRACK: '['; RBRACK: ']'; ESC: '\\'; COLON: ':'; LT: '<'; GT: '>'; GTE: '>='; LTE: '<='; EQUALITY: '=='; NOTEQUAL: '!='; EQUAL: '='; AND: '&&'; OR: '||'; OPTIONAL: '?'; STAR: '*'; PLUS: '+'; MINUS: '-'; DOLLAR: '$'; COMMA: ','; SEMI: ';'; DOT: '.'; NOT: '!'; TILDE: '~'; DIVIDE: '/'; MOD: '%'; SQUOTE: '\'' -> pushMode(SquoteInterpolatedString); DQUOTE: '"' -> pushMode(DquoteInterpolatedString); WHITESPACE : [ \t\r\n]+ -> channel(HIDDEN) ; COMMENT : '#' ~[\r\n]* -> channel(HIDDEN) ; Identifier: CompleteIdentifier; mode SquoteInterpolatedString; SQuoteEscapedChar: '\\' . -> type(StringPart); SQuoteDollarString: '$' -> type(StringPart); SQuoteTildeString: '~' -> type(StringPart); SQuoteCurlyString: '{' -> type(StringPart); SQuoteCommandStart: ('${' | '~{' ) -> pushMode(DEFAULT_MODE) , type(StringCommandStart); SQuoteUnicodeEscape: '\\u' (HexDigit (HexDigit (HexDigit HexDigit?)?)?)? -> type(StringPart); EndSquote: '\'' -> popMode, type(SQUOTE); StringPart: ~[$~{\r\n']+; mode DquoteInterpolatedString; DQuoteEscapedChar: '\\' . -> type(StringPart); DQuoteTildeString: '~' -> type(StringPart); DQuoteDollarString: '$' -> type(StringPart); DQUoteCurlString: '{' -> type(StringPart); DQuoteCommandStart: ('${' | '~{' ) -> pushMode(DEFAULT_MODE), type(StringCommandStart); DQuoteUnicodeEscape: '\\u' (HexDigit (HexDigit (HexDigit HexDigit?)?)?) -> type(StringPart); EndDQuote: '"' -> popMode, type(DQUOTE); DQuoteStringPart: ~[$~{\r\n"]+ -> type(StringPart); mode HereDocCommand; HereDocUnicodeEscape: '\\u' (HexDigit (HexDigit (HexDigit HexDigit?)?)?)?; HereDocEscapedChar: '\\' . -> type(CommandStringPart); HereDocTildeString: '~' -> type(CommandStringPart); HereDocCurlyString: '{' -> type(CommandStringPart); HereDocCurlyStringCommand: '~{' -> pushMode(DEFAULT_MODE), type(StringCommandStart); HereDocEscapedEnd: '\\>>>' -> type(CommandStringPart); EndHereDocCommand: '>>>' -> popMode, type(EndCommand); HereDocEscape: ( '>' | '>>' | '>>>>' '>'*) -> type(CommandStringPart); HereDocStringPart: ~[~{>]+ -> type(CommandStringPart); mode Command; CommandEscapedChar: '\\' . -> type(CommandStringPart); CommandUnicodeEscape: '\\u' (HexDigit (HexDigit (HexDigit HexDigit?)?)?)?; CommandTildeString: '~' -> type(CommandStringPart); CommandDollarString: '$' -> type(CommandStringPart); CommandCurlyString: '{' -> type(CommandStringPart); StringCommandStart: ('${' | '~{' ) -> pushMode(DEFAULT_MODE); EndCommand: '}' -> popMode; CommandStringPart: ~[$~{}]+; mode Version; VERSION_WHITESPACE : [ \t]+ -> channel(HIDDEN) ; RELEASE_VERSION: [a-zA-Z0-9.-]+ -> popMode; // Fragments fragment CompleteIdentifier : IdentifierStart IdentifierFollow* ; fragment IdentifierStart : [a-zA-Z] ; fragment IdentifierFollow : [a-zA-Z0-9_]+ ; fragment EscapeSequence : '\\' [btnfr"'\\] | '\\' ([0-3]? [0-7])? [0-7] | '\\' UnicodeEsc ; fragment UnicodeEsc : 'u' (HexDigit (HexDigit (HexDigit HexDigit?)?)?)? ; fragment HexDigit : [0-9a-fA-F] ; fragment Digit : [0-9] ; fragment Digits : Digit+ ; fragment Decimals : Digits '.' Digits? | '.' Digits ; fragment SignedDigits : ('+' | '-' ) Digits ; fragment FloatFragment : Digits EXP? | Decimals EXP? ; fragment SignedFloatFragment : ('+' |'e') FloatFragment ; fragment EXP : ('e'|'E') SignedDigits ;
Update WdlLexer.g4
Update WdlLexer.g4
ANTLR
bsd-3-clause
openwdl/wdl,openwdl/wdl,openwdl/wdl,openwdl/wdl
29e286cdb0dc0bb8a6d0d99b1b242ef585778f03
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 | block)+ ; 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)* | expression OPERATOR expression | '(' expression ')' ; section : list | map | val ; val : NULL | SIGNED_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] ; SIGNED_NUMBER : '+' NUMBER | '-' NUMBER | NUMBER ; OPERATOR : '*' | '/' | '%' | '+' | '-' | '>' | '>=' | '<' | '<=' | '==' | '!=' | '&&' | '||' ; 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 | block)+ ; 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)* | expression OPERATOR expression | LPAREN expression RPAREN ; section : list | map | val ; val : NULL | SIGNED_NUMBER | string | BOOL | IDENTIFIER index? | 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 : '{' argument* '}' ; string : STRING | MULTILINESTRING ; fragment DIGIT : [0-9] ; SIGNED_NUMBER : '+' NUMBER | '-' NUMBER | NUMBER ; OPERATOR : '*' | '/' | '%' | '+' | '-' | '>' | '>=' | '<' | '<=' | '==' | '!=' | '&&' | '||' ; LPAREN : '(' ; RPAREN : ')' ; 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 ;
Introduce LPAREN and RPAREN
Introduce LPAREN and RPAREN
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
33847c87b5e8e0600c4d568f0cadc0488d536fef
golang/GoParser.g4
golang/GoParser.g4
parser grammar GoParser; options { tokenVocab=GoLexer; superClass=GoBaseParser; } sourceFile : packageClause eos (importDecl eos)* (topLevelDecl eos)* ; packageClause : 'package' IDENTIFIER ; importDecl : 'import' (importSpec | '(' (importSpec eos)* ')') ; importSpec : ('.' | IDENTIFIER)? importPath ; importPath : string ; topLevelDecl : declaration | functionDecl | methodDecl ; declaration : constDecl | typeDecl | varDecl ; constDecl : 'const' (constSpec | '(' (constSpec eos)* ')') ; constSpec : identifierList (type? '=' expressionList)? ; identifierList : IDENTIFIER (',' IDENTIFIER)* ; expressionList : expression (',' expression)* ; typeDecl : 'type' (typeSpec | '(' (typeSpec eos)* ')') ; typeSpec : IDENTIFIER type ; // Function declarations functionDecl : 'func' IDENTIFIER (function | signature) ; function : signature block ; methodDecl : 'func' receiver IDENTIFIER (function | signature) ; receiver : parameters ; varDecl : 'var' (varSpec | '(' (varSpec eos)* ')') ; varSpec : identifierList (type ('=' expressionList)? | '=' expressionList) ; block : '{' statementList '}' ; statementList : (statement eos)* ; statement : declaration | labeledStmt | simpleStmt | goStmt | returnStmt | breakStmt | continueStmt | gotoStmt | fallthroughStmt | block | ifStmt | switchStmt | selectStmt | forStmt | deferStmt ; simpleStmt : sendStmt | expressionStmt | incDecStmt | assignment | shortVarDecl | emptyStmt ; expressionStmt : expression ; sendStmt : expression '<-' expression ; incDecStmt : expression ('++' | '--') ; assignment : expressionList assign_op expressionList ; assign_op : ('+' | '-' | '|' | '^' | '*' | '/' | '%' | '<<' | '>>' | '&' | '&^')? '=' ; shortVarDecl : identifierList ':=' expressionList ; emptyStmt : ';' ; labeledStmt : IDENTIFIER ':' statement ; returnStmt : 'return' expressionList? ; breakStmt : 'break' IDENTIFIER? ; continueStmt : 'continue' IDENTIFIER? ; gotoStmt : 'goto' IDENTIFIER ; fallthroughStmt : 'fallthrough' ; deferStmt : 'defer' expression ; ifStmt : 'if' (simpleStmt ';')? expression block ('else' (ifStmt | block))? ; switchStmt : exprSwitchStmt | typeSwitchStmt ; exprSwitchStmt : 'switch' (simpleStmt ';')? expression? '{' exprCaseClause* '}' ; exprCaseClause : exprSwitchCase ':' statementList ; exprSwitchCase : 'case' expressionList | 'default' ; typeSwitchStmt : 'switch' (simpleStmt ';')? typeSwitchGuard '{' typeCaseClause* '}' ; typeSwitchGuard : (IDENTIFIER ':=')? primaryExpr '.' '(' 'type' ')' ; typeCaseClause : typeSwitchCase ':' statementList ; typeSwitchCase : 'case' typeList | 'default' ; typeList : type (',' type)* ; selectStmt : 'select' '{' commClause* '}' ; commClause : commCase ':' statementList ; commCase : 'case' (sendStmt | recvStmt) | 'default' ; recvStmt : (expressionList '=' | identifierList ':=')? expression ; forStmt : 'for' (expression | forClause | rangeClause)? block ; forClause : simpleStmt? ';' expression? ';' simpleStmt? ; rangeClause : (expressionList '=' | identifierList ':=')? 'range' expression ; goStmt : 'go' expression ; type : typeName | typeLit | '(' type ')' ; typeName : IDENTIFIER | qualifiedIdent ; typeLit : arrayType | structType | pointerType | functionType | interfaceType | sliceType | mapType | channelType ; arrayType : '[' arrayLength ']' elementType ; arrayLength : expression ; elementType : type ; pointerType : '*' type ; interfaceType : 'interface' '{' (methodSpec eos)* '}' ; sliceType : '[' ']' elementType ; mapType : 'map' '[' type ']' elementType ; channelType : ('chan' | 'chan' '<-' | '<-' 'chan') elementType ; methodSpec : {noTerminatorAfterParams(2)}? IDENTIFIER parameters result | typeName | IDENTIFIER parameters ; functionType : 'func' signature ; signature : {noTerminatorAfterParams(1)}? parameters result | parameters ; result : parameters | type ; parameters : '(' (parameterList ','?)? ')' ; parameterList : parameterDecl (',' parameterDecl)* ; parameterDecl : identifierList? '...'? type ; // Operands operand : literal | operandName | methodExpr | '(' expression ')' ; literal : basicLit | compositeLit | functionLit ; basicLit : integer | string | FLOAT_LIT | IMAGINARY_LIT | RUNE_LIT ; integer : DECIMAL_LIT | OCTAL_LIT | HEX_LIT | IMAGINARY_LIT | RUNE_LIT ; operandName : IDENTIFIER | qualifiedIdent ; qualifiedIdent : IDENTIFIER '.' IDENTIFIER ; compositeLit : literalType literalValue ; literalType : structType | arrayType | '[' '...' ']' elementType | sliceType | mapType | typeName ; literalValue : '{' (elementList ','?)? '}' ; elementList : keyedElement (',' keyedElement)* ; keyedElement : (key ':')? element ; key : IDENTIFIER | expression | literalValue ; element : expression | literalValue ; structType : 'struct' '{' (fieldDecl eos)* '}' ; fieldDecl : ({noTerminatorBetween(2)}? identifierList type | anonymousField) string? ; string : RAW_STRING_LIT | INTERPRETED_STRING_LIT ; anonymousField : '*'? typeName ; functionLit : 'func' function ; primaryExpr : operand | conversion | primaryExpr selector | primaryExpr index | primaryExpr slice | primaryExpr typeAssertion | primaryExpr arguments ; selector : '.' IDENTIFIER ; index : '[' expression ']' ; slice : '[' ((expression? ':' expression?) | (expression? ':' expression ':' expression)) ']' ; typeAssertion : '.' '(' type ')' ; arguments : '(' ((expressionList | type (',' expressionList)?) '...'? ','?)? ')' ; methodExpr : receiverType '.' IDENTIFIER ; receiverType : typeName | '(' '*' typeName ')' | '(' receiverType ')' ; expression : unaryExpr // | expression BINARY_OP expression | expression ('||' | '&&' | '==' | '!=' | '<' | '<=' | '>' | '>=' | '+' | '-' | '|' | '^' | '*' | '/' | '%' | '<<' | '>>' | '&' | '&^') expression ; unaryExpr : primaryExpr | ('+'|'-'|'!'|'^'|'*'|'&'|'<-') unaryExpr ; conversion : type '(' expression ','? ')' ; eos : ';' | EOF | {lineTerminatorAhead()}? | {checkPreviousTokenText("}")}? ;
parser grammar GoParser; options { tokenVocab=GoLexer; superClass=GoBaseParser; } sourceFile : packageClause eos (importDecl eos)* (topLevelDecl eos)* ; packageClause : 'package' IDENTIFIER ; importDecl : 'import' (importSpec | '(' (importSpec eos)* ')') ; importSpec : ('.' | IDENTIFIER)? importPath ; importPath : string ; topLevelDecl : declaration | functionDecl | methodDecl ; declaration : constDecl | typeDecl | varDecl ; constDecl : 'const' (constSpec | '(' (constSpec eos)* ')') ; constSpec : identifierList (type? '=' expressionList)? ; identifierList : IDENTIFIER (',' IDENTIFIER)* ; expressionList : expression (',' expression)* ; typeDecl : 'type' (typeSpec | '(' (typeSpec eos)* ')') ; typeSpec : IDENTIFIER type ; // Function declarations functionDecl : 'func' IDENTIFIER (function | signature) ; function : signature block ; methodDecl : 'func' receiver IDENTIFIER (function | signature) ; receiver : parameters ; varDecl : 'var' (varSpec | '(' (varSpec eos)* ')') ; varSpec : identifierList (type ('=' expressionList)? | '=' expressionList) ; block : '{' statementList? '}' ; statementList : (statement eos)+ ; statement : declaration | labeledStmt | simpleStmt | goStmt | returnStmt | breakStmt | continueStmt | gotoStmt | fallthroughStmt | block | ifStmt | switchStmt | selectStmt | forStmt | deferStmt ; simpleStmt : sendStmt | expressionStmt | incDecStmt | assignment | shortVarDecl | emptyStmt ; expressionStmt : expression ; sendStmt : expression '<-' expression ; incDecStmt : expression ('++' | '--') ; assignment : expressionList assign_op expressionList ; assign_op : ('+' | '-' | '|' | '^' | '*' | '/' | '%' | '<<' | '>>' | '&' | '&^')? '=' ; shortVarDecl : identifierList ':=' expressionList ; emptyStmt : ';' ; labeledStmt : IDENTIFIER ':' statement ; returnStmt : 'return' expressionList? ; breakStmt : 'break' IDENTIFIER? ; continueStmt : 'continue' IDENTIFIER? ; gotoStmt : 'goto' IDENTIFIER ; fallthroughStmt : 'fallthrough' ; deferStmt : 'defer' expression ; ifStmt : 'if' (simpleStmt ';')? expression block ('else' (ifStmt | block))? ; switchStmt : exprSwitchStmt | typeSwitchStmt ; exprSwitchStmt : 'switch' (simpleStmt ';')? expression? '{' exprCaseClause* '}' ; exprCaseClause : exprSwitchCase ':' statementList? ; exprSwitchCase : 'case' expressionList | 'default' ; typeSwitchStmt : 'switch' (simpleStmt ';')? typeSwitchGuard '{' typeCaseClause* '}' ; typeSwitchGuard : (IDENTIFIER ':=')? primaryExpr '.' '(' 'type' ')' ; typeCaseClause : typeSwitchCase ':' statementList? ; typeSwitchCase : 'case' typeList | 'default' ; typeList : type (',' type)* ; selectStmt : 'select' '{' commClause* '}' ; commClause : commCase ':' statementList ; commCase : 'case' (sendStmt | recvStmt) | 'default' ; recvStmt : (expressionList '=' | identifierList ':=')? expression ; forStmt : 'for' (expression | forClause | rangeClause)? block ; forClause : simpleStmt? ';' expression? ';' simpleStmt? ; rangeClause : (expressionList '=' | identifierList ':=')? 'range' expression ; goStmt : 'go' expression ; type : typeName | typeLit | '(' type ')' ; typeName : IDENTIFIER | qualifiedIdent ; typeLit : arrayType | structType | pointerType | functionType | interfaceType | sliceType | mapType | channelType ; arrayType : '[' arrayLength ']' elementType ; arrayLength : expression ; elementType : type ; pointerType : '*' type ; interfaceType : 'interface' '{' (methodSpec eos)* '}' ; sliceType : '[' ']' elementType ; mapType : 'map' '[' type ']' elementType ; channelType : ('chan' | 'chan' '<-' | '<-' 'chan') elementType ; methodSpec : {noTerminatorAfterParams(2)}? IDENTIFIER parameters result | typeName | IDENTIFIER parameters ; functionType : 'func' signature ; signature : {noTerminatorAfterParams(1)}? parameters result | parameters ; result : parameters | type ; parameters : '(' (parameterList ','?)? ')' ; parameterList : parameterDecl (',' parameterDecl)* ; parameterDecl : identifierList? '...'? type ; expression : primaryExpr | ('+' | '-' | '!' | '^' | '*' | '&' | '<-') expression | expression ('*' | '/' | '%' | '<<' | '>>' | '&' | '&^') expression | expression ('+' | '-' | '|' | '^') expression | expression ('==' | '!=' | '<' | '<=' | '>' | '>=') expression | expression '&&' expression | expression '||' expression ; primaryExpr : operand | conversion | primaryExpr ( selector | index | slice | typeAssertion | arguments) ; conversion : type '(' expression ','? ')' ; operand : literal | operandName | methodExpr | '(' expression ')' ; literal : basicLit | compositeLit | functionLit ; basicLit : integer | string | FLOAT_LIT | IMAGINARY_LIT | RUNE_LIT ; integer : DECIMAL_LIT | OCTAL_LIT | HEX_LIT | IMAGINARY_LIT | RUNE_LIT ; operandName : IDENTIFIER | qualifiedIdent ; qualifiedIdent : IDENTIFIER '.' IDENTIFIER ; compositeLit : literalType literalValue ; literalType : structType | arrayType | '[' '...' ']' elementType | sliceType | mapType | typeName ; literalValue : '{' (elementList ','?)? '}' ; elementList : keyedElement (',' keyedElement)* ; keyedElement : (key ':')? element ; key : IDENTIFIER | expression | literalValue ; element : expression | literalValue ; structType : 'struct' '{' (fieldDecl eos)* '}' ; fieldDecl : ({noTerminatorBetween(2)}? identifierList type | anonymousField) string? ; string : RAW_STRING_LIT | INTERPRETED_STRING_LIT ; anonymousField : '*'? typeName ; functionLit : 'func' function ; selector : '.' IDENTIFIER ; index : '[' expression ']' ; slice : '[' (expression? ':' expression? | expression? ':' expression ':' expression) ']' ; typeAssertion : '.' '(' type ')' ; arguments : '(' ((expressionList | type (',' expressionList)?) '...'? ','?)? ')' ; methodExpr : receiverType '.' IDENTIFIER ; receiverType : typeName | '(' ('*' typeName | receiverType) ')' ; eos : ';' | EOF | {lineTerminatorAhead()}? | {checkPreviousTokenText("}")}? ;
Fix binary operators priority; fix formatting and useless parentheses
Fix binary operators priority; fix formatting and useless parentheses
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
886d949040816af63aeec57797bddf59e6167ab5
antlr4/ANTLRv4Parser.g4
antlr4/ANTLRv4Parser.g4
/* * [The "BSD license"] * Copyright (c) 2013 Terence Parr * Copyright (c) 2013 Sam Harwell * 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 written in ANTLR v4. */ parser grammar ANTLRv4Parser; options { tokenVocab=ANTLRv4Lexer; } // The main entry point for parsing a v4 grammar. grammarSpec : DOC_COMMENT? grammarType id SEMI prequelConstruct* rules modeSpec* EOF ; grammarType : ( LEXER GRAMMAR | PARSER GRAMMAR | GRAMMAR ) ; // This is the list of all constructs that can be declared before // the set of rules that compose the grammar, and is invoked 0..n // times by the grammarPrequel rule. prequelConstruct : optionsSpec | delegateGrammars | tokensSpec | action ; // A list of options that affect analysis and/or code generation optionsSpec : OPTIONS (option SEMI)* RBRACE ; option : id ASSIGN optionValue ; optionValue : id (DOT id)* | STRING_LITERAL | ACTION | INT ; delegateGrammars : IMPORT delegateGrammar (COMMA delegateGrammar)* SEMI ; delegateGrammar : id ASSIGN id | id ; tokensSpec : TOKENS id (COMMA id)* COMMA? RBRACE ; /** Match stuff like @parser::members {int i;} */ action : AT (actionScopeName COLONCOLON)? id ACTION ; /** Sometimes the scope names will collide with keywords; allow them as * ids for action scopes. */ actionScopeName : id | LEXER | PARSER ; modeSpec : MODE id SEMI ruleSpec+ ; rules : ruleSpec* ; ruleSpec : parserRuleSpec | lexerRule ; parserRuleSpec : DOC_COMMENT? ruleModifiers? RULE_REF ARG_ACTION? ruleReturns? throwsSpec? localsSpec? rulePrequel* COLON ruleBlock SEMI exceptionGroup ; exceptionGroup : exceptionHandler* finallyClause? ; exceptionHandler : CATCH ARG_ACTION ACTION ; finallyClause : FINALLY ACTION ; rulePrequel : optionsSpec | ruleAction ; ruleReturns : RETURNS ARG_ACTION ; throwsSpec : THROWS id (COMMA id)* ; localsSpec : LOCALS ARG_ACTION ; /** Match stuff like @init {int i;} */ ruleAction : AT id ACTION ; ruleModifiers : ruleModifier+ ; // An individual access modifier for a rule. The 'fragment' modifier // is an internal indication for lexer rules that they do not match // from the input but are like subroutines for other lexer rules to // reuse for certain lexical patterns. The other modifiers are passed // to the code generation templates and may be ignored by the template // if they are of no use in that language. ruleModifier : PUBLIC | PRIVATE | PROTECTED | FRAGMENT ; ruleBlock : ruleAltList ; ruleAltList : labeledAlt (OR labeledAlt)* ; labeledAlt : alternative (POUND id)? ; lexerRule : DOC_COMMENT? FRAGMENT? TOKEN_REF COLON lexerRuleBlock SEMI ; lexerRuleBlock : lexerAltList ; lexerAltList : lexerAlt (OR lexerAlt)* ; lexerAlt : lexerElements? lexerCommands? ; lexerElements : lexerElement+ ; lexerElement : labeledLexerElement ebnfSuffix? | lexerAtom ebnfSuffix? | lexerBlock ebnfSuffix? | ACTION QUESTION? // actions only allowed at end of outer alt actually, // but preds can be anywhere ; labeledLexerElement : id (ASSIGN|PLUS_ASSIGN) ( lexerAtom | block ) ; lexerBlock : LPAREN lexerAltList RPAREN ; // E.g., channel(HIDDEN), skip, more, mode(INSIDE), push(INSIDE), pop lexerCommands : RARROW lexerCommand (COMMA lexerCommand)* ; lexerCommand : lexerCommandName LPAREN lexerCommandExpr RPAREN | lexerCommandName ; lexerCommandName : id | MODE ; lexerCommandExpr : id | INT ; altList : alternative (OR alternative)* ; alternative : elements | // empty alt ; elements : element+ ; element : labeledElement ( ebnfSuffix | ) | atom ( ebnfSuffix | ) | ebnf | ACTION QUESTION? // SEMPRED is ACTION followed by QUESTION ; labeledElement : id (ASSIGN|PLUS_ASSIGN) ( atom | block ) ; ebnf: block blockSuffix? ; blockSuffix : ebnfSuffix // Standard EBNF ; ebnfSuffix : QUESTION QUESTION? | STAR QUESTION? | PLUS QUESTION? ; lexerAtom : range | terminal | RULE_REF | notSet | LEXER_CHAR_SET | DOT elementOptions? ; atom : range // Range x..y - only valid in lexers | terminal | ruleref | notSet | DOT elementOptions? ; notSet : NOT setElement | NOT blockSet ; blockSet : LPAREN setElement (OR setElement)* RPAREN ; setElement : TOKEN_REF | STRING_LITERAL | range | LEXER_CHAR_SET ; block : LPAREN ( optionsSpec? ruleAction* COLON )? altList RPAREN ; ruleref : RULE_REF ARG_ACTION? ; range : STRING_LITERAL RANGE STRING_LITERAL ; terminal : TOKEN_REF elementOptions? | STRING_LITERAL elementOptions? ; // Terminals may be adorned with certain options when // reference in the grammar: TOK<,,,> elementOptions : LT elementOption (COMMA elementOption)* GT ; elementOption : // This format indicates the default node option id | // This format indicates option assignment id ASSIGN (id | STRING_LITERAL) ; id : RULE_REF | TOKEN_REF ;
/* * [The "BSD license"] * Copyright (c) 2013 Terence Parr * Copyright (c) 2013 Sam Harwell * 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 written in ANTLR v4. */ parser grammar ANTLRv4Parser; options { tokenVocab=ANTLRv4Lexer; } // The main entry point for parsing a v4 grammar. grammarSpec : DOC_COMMENT? grammarType id SEMI prequelConstruct* rules modeSpec* EOF ; grammarType : ( LEXER GRAMMAR | PARSER GRAMMAR | GRAMMAR ) ; // This is the list of all constructs that can be declared before // the set of rules that compose the grammar, and is invoked 0..n // times by the grammarPrequel rule. prequelConstruct : optionsSpec | delegateGrammars | tokensSpec | action ; // A list of options that affect analysis and/or code generation optionsSpec : OPTIONS (option SEMI)* RBRACE ; option : id ASSIGN optionValue ; optionValue : id (DOT id)* | STRING_LITERAL | ACTION | INT ; delegateGrammars : IMPORT delegateGrammar (COMMA delegateGrammar)* SEMI ; delegateGrammar : id ASSIGN id | id ; tokensSpec : TOKENS id (COMMA id)* COMMA? RBRACE ; /** Match stuff like @parser::members {int i;} */ action : AT (actionScopeName COLONCOLON)? id ACTION ; /** Sometimes the scope names will collide with keywords; allow them as * ids for action scopes. */ actionScopeName : id | LEXER | PARSER ; modeSpec : MODE id SEMI lexerRule* ; rules : ruleSpec* ; ruleSpec : parserRuleSpec | lexerRule ; parserRuleSpec : DOC_COMMENT? ruleModifiers? RULE_REF ARG_ACTION? ruleReturns? throwsSpec? localsSpec? rulePrequel* COLON ruleBlock SEMI exceptionGroup ; exceptionGroup : exceptionHandler* finallyClause? ; exceptionHandler : CATCH ARG_ACTION ACTION ; finallyClause : FINALLY ACTION ; rulePrequel : optionsSpec | ruleAction ; ruleReturns : RETURNS ARG_ACTION ; throwsSpec : THROWS id (COMMA id)* ; localsSpec : LOCALS ARG_ACTION ; /** Match stuff like @init {int i;} */ ruleAction : AT id ACTION ; ruleModifiers : ruleModifier+ ; // An individual access modifier for a rule. The 'fragment' modifier // is an internal indication for lexer rules that they do not match // from the input but are like subroutines for other lexer rules to // reuse for certain lexical patterns. The other modifiers are passed // to the code generation templates and may be ignored by the template // if they are of no use in that language. ruleModifier : PUBLIC | PRIVATE | PROTECTED | FRAGMENT ; ruleBlock : ruleAltList ; ruleAltList : labeledAlt (OR labeledAlt)* ; labeledAlt : alternative (POUND id)? ; lexerRule : DOC_COMMENT? FRAGMENT? TOKEN_REF COLON lexerRuleBlock SEMI ; lexerRuleBlock : lexerAltList ; lexerAltList : lexerAlt (OR lexerAlt)* ; lexerAlt : lexerElements lexerCommands? | ; lexerElements : lexerElement+ ; lexerElement : labeledLexerElement ebnfSuffix? | lexerAtom ebnfSuffix? | lexerBlock ebnfSuffix? | ACTION QUESTION? // actions only allowed at end of outer alt actually, // but preds can be anywhere ; labeledLexerElement : id (ASSIGN|PLUS_ASSIGN) ( lexerAtom | block ) ; lexerBlock : LPAREN lexerAltList RPAREN ; // E.g., channel(HIDDEN), skip, more, mode(INSIDE), push(INSIDE), pop lexerCommands : RARROW lexerCommand (COMMA lexerCommand)* ; lexerCommand : lexerCommandName LPAREN lexerCommandExpr RPAREN | lexerCommandName ; lexerCommandName : id | MODE ; lexerCommandExpr : id | INT ; altList : alternative (OR alternative)* ; alternative : elementOptions? element* ; element : labeledElement ( ebnfSuffix | ) | atom ( ebnfSuffix | ) | ebnf | ACTION QUESTION? // SEMPRED is ACTION followed by QUESTION ; labeledElement : id (ASSIGN|PLUS_ASSIGN) ( atom | block ) ; ebnf: block blockSuffix? ; blockSuffix : ebnfSuffix // Standard EBNF ; ebnfSuffix : QUESTION QUESTION? | STAR QUESTION? | PLUS QUESTION? ; lexerAtom : range | terminal | RULE_REF | notSet | LEXER_CHAR_SET | DOT elementOptions? ; atom : range // Range x..y - only valid in lexers | terminal | ruleref | notSet | DOT elementOptions? ; notSet : NOT setElement | NOT blockSet ; blockSet : LPAREN setElement (OR setElement)* RPAREN ; setElement : TOKEN_REF elementOptions? | STRING_LITERAL elementOptions? | range | LEXER_CHAR_SET ; block : LPAREN ( optionsSpec? ruleAction* COLON )? altList RPAREN ; ruleref : RULE_REF ARG_ACTION? elementOptions? ; range : STRING_LITERAL RANGE STRING_LITERAL ; terminal : TOKEN_REF elementOptions? | STRING_LITERAL elementOptions? ; // Terminals may be adorned with certain options when // reference in the grammar: TOK<,,,> elementOptions : LT elementOption (COMMA elementOption)* GT ; elementOption : // This format indicates the default node option id | // This format indicates option assignment id ASSIGN (id | STRING_LITERAL) ; id : RULE_REF | TOKEN_REF ;
update to 4.3 syntax
update to 4.3 syntax
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
8f5555ab7bafd489be12a294656483ea1f422e9d
de.peeeq.wurstscript/src/main/antlr/de/peeeq/wurstscript/antlr/Jass.g4
de.peeeq.wurstscript/src/main/antlr/de/peeeq/wurstscript/antlr/Jass.g4
grammar Jass; @header { package de.peeeq.wurstscript.antlr; } compilationUnit : NL? decls+=jassTopLevelDeclaration*; jassTopLevelDeclaration: jassGlobalsBlock | jassFuncDef | jassTypeDecl | jassNativeDecl ; jassGlobalsBlock: 'globals' NL vars+=jassGlobalDecl* 'endglobals' NL ; jassGlobalDecl: constant='constant'? jassTypeExpr name=ID ('=' initial=jassExpr)? NL ; jassFuncDef: constant='constant'? 'function' jassFuncSignature NL (jassLocals+=jassLocal)* jassStatements 'endfunction' NL ; jassLocal: 'local' jassTypeExpr name=ID ('=' initial=jassExpr)? NL; jassStatements: stmts+=jassStatement*; jassStatement: jassStatementIf | jassStatementLoop | jassStatementExithwhen | jassStatementReturn | jassStatementSet | jassStatementCall ; jassStatementIf: 'if' cond=jassExpr 'then' NL thenStatements=jassStatements jassElseIfs ; jassElseIfs: 'elseif' cond=jassExpr 'then' NL thenStatements=jassStatements jassElseIfs | 'else' NL elseStmts=jassStatements 'endif' NL | 'endif' NL ; jassStatementLoop: 'loop' NL jassStatements 'endloop' NL ; jassStatementExithwhen: 'exitwhen' cond=jassExpr NL; jassStatementReturn: 'return' jassExpr NL; jassStatementSet: 'set' left=exprVarAccess '=' right=jassExpr NL; jassStatementCall:'call' exprFunctionCall NL; jassNativeDecl: constant='constant'? 'native' jassFuncSignature NL; jassFuncSignature: name=ID 'takes' ('nothing'|args+=formalParam (',' args+=formalParam)*) 'returns' ('nothing'|returnType=jassTypeExpr) ; jassTypeDecl: 'type' name=ID 'extends' extended=jassTypeExpr NL; formalParam: jassTypeExpr name=ID; jassTypeExpr: | typeName=ID | jassTypeExpr 'array' ; exprVarAccess: varname=ID indexes?; indexes: '[' jassExpr ']'; jassExpr: jassExprPrimary | left=jassExpr op=('*'|'/'|'%') right=jassExpr | op='-' right=jassExpr // TODO move unary minus one up to be compatible with Java etc. // currently it is here to be backwards compatible with the old wurst parser | left=jassExpr op=('+'|'-') right=jassExpr | left=jassExpr op=('<='|'<'|'>'|'>=') right=jassExpr | left=jassExpr op=('=='|'!=') right=jassExpr | op='not' right=jassExpr | left=jassExpr op='and' right=jassExpr | left=jassExpr op='or' right=jassExpr | ; jassExprPrimary: exprFunctionCall | varname=ID indexes? | atom=(INT | REAL | STRING | 'null' | 'true' | 'false') | exprFuncRef | '(' jassExpr ')' ; exprFuncRef: 'function' (scopeName=ID '.')? funcName=ID; argumentList: '(' exprList ')'; exprFunctionCall: funcName=ID jassTypeExpr argumentList; exprList : exprs+=jassExpr (',' exprs+=jassExpr)*; // Lexer: RETURN: 'return'; IF: 'if'; ELSE: 'else'; NULL: 'null'; FUNCTION: 'function'; RETURNS: 'returns'; NATIVE: 'native'; EXTENDS: 'extends'; ARRAY: 'array'; AND: 'and'; OR: 'or'; NOT: 'not'; TYPE: 'type'; CONSTANT: 'constant'; ENDFUNCTION: 'endfunction'; NOTHING: 'nothing'; TRUE: 'true'; FALSE: 'false'; THEN: 'then'; ENDIF: 'endif'; LOOP: 'loop'; EXITHWHEN: 'exithwhen'; ENDLOOP: 'endloop'; TAKES: 'takes'; SET: 'set'; CALL: 'call'; COMMA: ','; PLUS: '+'; MINUS: '-'; MULT: '*'; DIV_REAL: '/'; MOD_REAL: '%'; PAREN_LEFT: '('; PAREN_RIGHT: ')'; BRACKET_LEFT: '['; BRACKET_RIGHT: ']'; EQ: '='; EQEQ: '=='; NOT_EQ: '!='; LESS: '<'; LESS_EQ: '<='; GREATER: '>'; GREATER_EQ: '>='; STARTBLOCK:[()]; ENDBLOCK:[()]; INVALID:[()]; JASS_GLOBALS: 'globals'; JASS_LOCAL: 'local'; JASS_ENDGLOBALS: 'endglobals'; JASS_ELSEIF: 'elseif'; NL: [\r\n]+; ID: [a-zA-Z_][a-zA-Z0-9_]* ; STRING: '"' ( EscapeSequence | ~('\\'|'"'|'\r'|'\n') )* '"'; REAL: [0-9]+ '.' [0-9]* | '.'[0-9]+; fragment HexInt: '$'[0-9a-fA-F]+ | '0'[xX][0-9a-fA-F]+; fragment CharIntPart: ('\\' [btrnf"\\]) | ~[\\']; fragment CharInt: '\'' CharIntPart+ '\'' | '\'' [\\'] '\''; INT: [0-9]+ | HexInt | CharInt; fragment EscapeSequence: '\\' [abfnrtvz"'\\]; DEBUG: 'debug' -> skip; WS : [ \t]+ -> skip ; ML_COMMENT: '/*' .*? '*/' -> skip; LINE_COMMENT: '//' ~[\r\n]* -> skip;
grammar Jass; @header { package de.peeeq.wurstscript.antlr; } compilationUnit : NL? decls+=jassTopLevelDeclaration*; jassTopLevelDeclaration: jassGlobalsBlock | jassFuncDef | jassTypeDecl | jassNativeDecl ; jassGlobalsBlock: 'globals' NL vars+=jassGlobalDecl* 'endglobals' NL ; jassGlobalDecl: constant='constant'? jassTypeExpr name=ID ('=' initial=jassExpr)? NL ; jassFuncDef: constant='constant'? 'function' jassFuncSignature NL (jassLocals+=jassLocal)* jassStatements 'endfunction' NL ; jassLocal: 'local' jassTypeExpr name=ID ('=' initial=jassExpr)? NL; jassStatements: stmts+=jassStatement*; jassStatement: jassStatementIf | jassStatementLoop | jassStatementExithwhen | jassStatementReturn | jassStatementSet | jassStatementCall ; jassStatementIf: 'if' cond=jassExpr 'then' NL thenStatements=jassStatements jassElseIfs ; jassElseIfs: 'elseif' cond=jassExpr 'then' NL thenStatements=jassStatements jassElseIfs | 'else' NL elseStmts=jassStatements 'endif' NL | 'endif' NL ; jassStatementLoop: 'loop' NL jassStatements 'endloop' NL ; jassStatementExithwhen: 'exitwhen' cond=jassExpr NL; jassStatementReturn: 'return' jassExpr NL; jassStatementSet: 'set' left=exprVarAccess '=' right=jassExpr NL; jassStatementCall:'call' exprFunctionCall NL; jassNativeDecl: constant='constant'? 'native' jassFuncSignature NL; jassFuncSignature: name=ID 'takes' ('nothing'|args+=formalParam (',' args+=formalParam)*) 'returns' ('nothing'|returnType=jassTypeExpr) ; jassTypeDecl: 'type' name=ID 'extends' extended=jassTypeExpr NL; formalParam: jassTypeExpr name=ID; jassTypeExpr: | typeName=ID | jassTypeExpr 'array' ; exprVarAccess: varname=ID indexes?; indexes: '[' jassExpr ']'; jassExpr: jassExprPrimary | left=jassExpr op=('*'|'/'|'%') right=jassExpr | op='-' right=jassExpr // TODO move unary minus one up to be compatible with Java etc. // currently it is here to be backwards compatible with the old wurst parser | left=jassExpr op=('+'|'-') right=jassExpr | left=jassExpr op=('<='|'<'|'>'|'>=') right=jassExpr | left=jassExpr op=('=='|'!=') right=jassExpr | op='not' right=jassExpr | left=jassExpr op='or' right=jassExpr | left=jassExpr op='and' right=jassExpr | ; jassExprPrimary: exprFunctionCall | varname=ID indexes? | atom=(INT | REAL | STRING | 'null' | 'true' | 'false') | exprFuncRef | '(' jassExpr ')' ; exprFuncRef: 'function' (scopeName=ID '.')? funcName=ID; argumentList: '(' exprList ')'; exprFunctionCall: funcName=ID jassTypeExpr argumentList; exprList : exprs+=jassExpr (',' exprs+=jassExpr)*; // Lexer: RETURN: 'return'; IF: 'if'; ELSE: 'else'; NULL: 'null'; FUNCTION: 'function'; RETURNS: 'returns'; NATIVE: 'native'; EXTENDS: 'extends'; ARRAY: 'array'; AND: 'and'; OR: 'or'; NOT: 'not'; TYPE: 'type'; CONSTANT: 'constant'; ENDFUNCTION: 'endfunction'; NOTHING: 'nothing'; TRUE: 'true'; FALSE: 'false'; THEN: 'then'; ENDIF: 'endif'; LOOP: 'loop'; EXITHWHEN: 'exithwhen'; ENDLOOP: 'endloop'; TAKES: 'takes'; SET: 'set'; CALL: 'call'; COMMA: ','; PLUS: '+'; MINUS: '-'; MULT: '*'; DIV_REAL: '/'; MOD_REAL: '%'; PAREN_LEFT: '('; PAREN_RIGHT: ')'; BRACKET_LEFT: '['; BRACKET_RIGHT: ']'; EQ: '='; EQEQ: '=='; NOT_EQ: '!='; LESS: '<'; LESS_EQ: '<='; GREATER: '>'; GREATER_EQ: '>='; STARTBLOCK:[()]; ENDBLOCK:[()]; INVALID:[()]; JASS_GLOBALS: 'globals'; JASS_LOCAL: 'local'; JASS_ENDGLOBALS: 'endglobals'; JASS_ELSEIF: 'elseif'; NL: [\r\n]+; ID: [a-zA-Z_][a-zA-Z0-9_]* ; STRING: '"' ( EscapeSequence | ~('\\'|'"'|'\r'|'\n') )* '"'; REAL: [0-9]+ '.' [0-9]* | '.'[0-9]+; fragment HexInt: '$'[0-9a-fA-F]+ | '0'[xX][0-9a-fA-F]+; fragment CharIntPart: ('\\' [btrnf"\\]) | ~[\\']; fragment CharInt: '\'' CharIntPart+ '\'' | '\'' [\\'] '\''; INT: [0-9]+ | HexInt | CharInt; fragment EscapeSequence: '\\' [abfnrtvz"'\\]; DEBUG: 'debug' -> skip; WS : [ \t]+ -> skip ; ML_COMMENT: '/*' .*? '*/' -> skip; LINE_COMMENT: '//' ~[\r\n]* -> skip;
fix Jass operator precedence
fix Jass operator precedence
ANTLR
apache-2.0
Cokemonkey11/WurstScript,peq/WurstScript,wurstscript/WurstScript,Cokemonkey11/WurstScript,wurstscript/WurstScript,Cokemonkey11/WurstScript,Cokemonkey11/WurstScript,peq/WurstScript,peq/WurstScript,Cokemonkey11/WurstScript,peq/WurstScript,wurstscript/WurstScript
abde1177bf85b83d726938cbde1494223a36795e
src/net/hillsdon/reviki/wiki/renderer/creole/Creole.g4
src/net/hillsdon/reviki/wiki/renderer/creole/Creole.g4
/* Todo: * - Comments justifying and explaining every rule. * - Allow arbitrarily-nested lists (see actions/attributes) */ parser grammar Creole; options { tokenVocab=CreoleTokens; } @members { public boolean nobreaks = false; } /* ***** Top level elements ***** */ creole : (block (LineBreak | ParBreak)*)* EOF ; block : heading | ulist | olist | hrule | table | code | nowiki | paragraph ; /* ***** Block Elements ***** */ heading : HSt inline HEnd ; paragraph : inline ; ulist : ulist1+ ; ulist1 : U1 (WS ulist | olist | inline) ulist2* ; ulist2 : U2 (WS ulist | olist | inline) ulist3* ; ulist3 : U3 (WS ulist | olist | inline) ulist4* ; ulist4 : U4 (WS ulist | olist | inline) ulist5* ; ulist5 : U5 (WS ulist | olist | inline) ; olist : olist1+ ; olist1 : O1 (WS olist | ulist | inline) olist2* ; olist2 : O2 (WS olist | ulist | inline) olist3* ; olist3 : O3 (WS olist | ulist | inline) olist4* ; olist4 : O4 (WS olist | ulist | inline) olist5* ; olist5 : O5 (WS olist | ulist | inline) ; hrule : Rule ; table : {nobreaks=true;} trow+ {nobreaks=false;}; trow : tcell+ (RowEnd | LineBreak) ; tcell : th | td ; th : ThStart inline? ; td : TdStart inline? ; nowiki : NoWiki EndNoWikiBlock ; /* ***** Inline Elements ***** */ inline : inlinestep+ ; inlinestep : bold | italic | sthrough | link | titlelink | simpleimg | imglink | wikiwlink | rawlink | inlinecode | preformat | linebreak | macro | any ; bold : BSt inline? BEnd ; italic : ISt inline? IEnd ; sthrough : SSt inline? SEnd ; link : LiSt InLink LiEnd ; titlelink : LiSt InLink Sep InLink LiEnd ; imglink : ImSt InLink Sep InLink ImEnd ; simpleimg : ImSt InLink ImEnd ; wikiwlink : WikiWords ; rawlink : RawUrl ; preformat : NoWiki EndNoWikiInline ; linebreak : InlineBrk ({!nobreaks}? LineBreak)? ; macro : MacroSt MacroName MacroSep MacroEnd ; any : Any | WS | {!nobreaks}? LineBreak ; /* ***** Syntax Highlighting ***** */ code : cpp | html | java | xhtml | xml ; inlinecode : inlinecpp | inlinehtml | inlinejava | inlinexhtml | inlinexml ; cpp : StartCpp EndCppBlock ; inlinecpp : StartCpp EndCppInline ; html : StartHtml EndHtmlBlock ; inlinehtml : StartHtml EndHtmlInline ; java : StartJava EndJavaBlock ; inlinejava : StartJava EndJavaInline ; xhtml : StartXhtml EndXhtmlBlock ; inlinexhtml : StartXhtml EndXhtmlInline ; xml : StartXml EndXmlBlock ; inlinexml : StartXml EndXmlInline ;
/* Todo: * - Comments justifying and explaining every rule. * - Allow arbitrarily-nested lists (see actions/attributes) */ parser grammar Creole; options { tokenVocab=CreoleTokens; } @members { public boolean nobreaks = false; } /* ***** Top level elements ***** */ creole : (block (LineBreak | ParBreak)*)* EOF ; block : heading | ulist | olist | hrule | table | code | nowiki | paragraph ; /* ***** Block Elements ***** */ heading : HSt inline HEnd? ; paragraph : inline ; ulist : ulist1+ ; ulist1 : U1 (WS ulist | olist | inline) ulist2* ; ulist2 : U2 (WS ulist | olist | inline) ulist3* ; ulist3 : U3 (WS ulist | olist | inline) ulist4* ; ulist4 : U4 (WS ulist | olist | inline) ulist5* ; ulist5 : U5 (WS ulist | olist | inline) ; olist : olist1+ ; olist1 : O1 (WS olist | ulist | inline) olist2* ; olist2 : O2 (WS olist | ulist | inline) olist3* ; olist3 : O3 (WS olist | ulist | inline) olist4* ; olist4 : O4 (WS olist | ulist | inline) olist5* ; olist5 : O5 (WS olist | ulist | inline) ; hrule : Rule ; table : {nobreaks=true;} trow+ {nobreaks=false;}; trow : tcell+ (RowEnd | LineBreak) ; tcell : th | td ; th : ThStart inline? ; td : TdStart inline? ; nowiki : NoWiki EndNoWikiBlock ; /* ***** Inline Elements ***** */ inline : inlinestep+ ; inlinestep : bold | italic | sthrough | link | titlelink | simpleimg | imglink | wikiwlink | rawlink | inlinecode | preformat | linebreak | macro | any ; bold : BSt inline? BEnd ; italic : ISt inline? IEnd ; sthrough : SSt inline? SEnd ; link : LiSt InLink LiEnd ; titlelink : LiSt InLink Sep InLink LiEnd ; imglink : ImSt InLink Sep InLink ImEnd ; simpleimg : ImSt InLink ImEnd ; wikiwlink : WikiWords ; rawlink : RawUrl ; preformat : NoWiki EndNoWikiInline ; linebreak : InlineBrk ({!nobreaks}? LineBreak)? ; macro : MacroSt MacroName MacroSep MacroEnd ; any : Any | WS | {!nobreaks}? LineBreak ; /* ***** Syntax Highlighting ***** */ code : cpp | html | java | xhtml | xml ; inlinecode : inlinecpp | inlinehtml | inlinejava | inlinexhtml | inlinexml ; cpp : StartCpp EndCppBlock ; inlinecpp : StartCpp EndCppInline ; html : StartHtml EndHtmlBlock ; inlinehtml : StartHtml EndHtmlInline ; java : StartJava EndJavaBlock ; inlinejava : StartJava EndJavaInline ; xhtml : StartXhtml EndXhtmlBlock ; inlinexhtml : StartXhtml EndXhtmlInline ; xml : StartXml EndXmlBlock ; inlinexml : StartXml EndXmlInline ;
Make header endings optional
Make header endings optional
ANTLR
apache-2.0
strr/reviki,strr/reviki,ashirley/reviki,ashirley/reviki,strr/reviki,strr/reviki,CoreFiling/reviki,ashirley/reviki,CoreFiling/reviki,ashirley/reviki,CoreFiling/reviki,ashirley/reviki,CoreFiling/reviki,CoreFiling/reviki,strr/reviki
39ad1bbd00d2fa6c550127a54c7ea5e35bb31395
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 | '_')* ;
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 : '\'' (RAW_ESC | ~['\\])* '\'' ; fragment RAW_ESC : '\\' ['\\] ; literal : '`' value '`' ; SIGNED_INT : '-'? DIGIT+ ; DIGIT : [0-9] ; LETTER : [a-zA-Z] ; IDENTIFIER : UNQUOTED_STRING | STRING ; fragment UNQUOTED_STRING : LETTER (LETTER | DIGIT | '_')* ;
Remove ESCAPE and make RAW_STRING more like STRING
Remove ESCAPE and make RAW_STRING more like STRING
ANTLR
bsd-3-clause
burtcorp/jmespath-java
3d023d14d5c7787f71edd84dc4542731cff14ba2
java-vtl-parser/src/main/resources/kohl/hadrien/antlr4/Clauses.g4
java-vtl-parser/src/main/resources/kohl/hadrien/antlr4/Clauses.g4
grammar Clauses; clause : '[' ( rename | filter | keep | calc | attrcalc | aggregate ) ']' ; // [ rename component as string, // component as string role = IDENTIFIER, // component as string role = MEASURE, // component as string role = ATTRIBUTE // ] rename : 'rename' renameParam (',' renameParam )* ; renameParam : component 'as' string role? ; role : 'role' '=' ( 'IDENTIFIER' | 'MEASURE' | 'ATTRIBUTE' ) ; filter : 'filter' booleanExpression ; keep : 'keep' booleanExpression ( ',' booleanExpression )* ; calc : 'calc' ; attrcalc : 'attrcalc' ; aggregate : 'aggregate' ; booleanExpression : 'booleanExpression' ; string : 'string' ; component : 'componentName' ; WS : [ \t\n\t] -> skip ;
grammar Clauses; clause : '[' ( rename | filter | keep | calc | attrcalc | aggregate ) ']' ; // [ rename component as string, // component as string role = IDENTIFIER, // component as string role = MEASURE, // component as string role = ATTRIBUTE // ] rename : 'rename' renameParam (',' renameParam )* ; renameParam : from=varID 'as' to=varID role? ; role : 'role' '=' ( 'IDENTIFIER' | 'MEASURE' | 'ATTRIBUTE' ) ; filter : 'filter' booleanExpression ; keep : 'keep' booleanExpression ( ',' booleanExpression )* ; calc : 'calc' ; attrcalc : 'attrcalc' ; aggregate : 'aggregate' ; varID : 'varId'; booleanExpression : 'booleanExpression' ; WS : [ \t\n\t] -> skip ;
Use correct rule name in Clauses
Use correct rule name in Clauses
ANTLR
apache-2.0
statisticsnorway/java-vtl,hadrienk/java-vtl,hadrienk/java-vtl,statisticsnorway/java-vtl,statisticsnorway/java-vtl,hadrienk/java-vtl,statisticsnorway/java-vtl
40ed86b6dee6cbe78b3143eb3522a9d305fc8bec
sharding-core/src/main/antlr4/imports/BaseRule.g4
sharding-core/src/main/antlr4/imports/BaseRule.g4
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_?) ; BLOCK_COMMENT : SLASH ASTERISK .*? ASTERISK SLASH -> channel(HIDDEN) ; SL_COMMENT : MINUS MINUS ~[\r\n]* -> channel(HIDDEN) ; schemaName : ID ; databaseName : ID ; domainName : ID ; tableName : ID ; columnName : ID ; sequenceName : 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 ; routineName : ID ; roleName : STRING | ID ; partitionName : ID ; rewriteRuleName : ID ; ownerName : ID ; userName : STRING | ID ; serverName : ID ; dataTypeLength : LP_ (NUMBER (COMMA NUMBER)?)? RP_ ; primaryKey : PRIMARY? KEY ; matchNone : 'Default does not match anything' ; ids : ID (COMMA ID)* ; idList : LP_ ids RP_ ; rangeClause : rangeItem (COMMA rangeItem)* | rangeItem OFFSET rangeItem ; rangeItem : number | question ; schemaNames : schemaName (COMMA schemaName)* ; databaseNames : databaseName (COMMA databaseName)* ; domainNames : domainName (COMMA domainName)* ; tableNamesWithParen : LP_ tableNames RP_ ; tableNames : tableName (COMMA tableName)* ; columnNamesWithParen : LP_ columnNames RP_ ; columnNames : columnName (COMMA columnName)* ; columnList : LP_ columnNames RP_ ; sequenceNames : sequenceName (COMMA sequenceName)* ; tablespaceNames : tablespaceName (COMMA tablespaceName)* ; indexNames : indexName (COMMA indexName)* ; indexList : LP_ indexNames RP_ ; typeNames : typeName (COMMA typeName)* ; rowNames : rowName (COMMA rowName)* ; roleNames : roleName (COMMA roleName)* ; userNames : userName (COMMA userName)* ; serverNames : serverName (COMMA serverName)* ; bitExprs: bitExpr (COMMA bitExpr)* ; exprs : expr (COMMA expr)* ; exprsWithParen : 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_ | 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 | columnName | simpleExpr collateClause //| param_marker //| variable | simpleExpr AND_ simpleExpr | PLUS simpleExpr | MINUS simpleExpr | UNARY_BIT_COMPLEMENT simpleExpr | NOT_ simpleExpr | BINARY simpleExpr | exprsWithParen | ROW exprsWithParen | subquery | EXISTS subquery // | (identifier expr) //| match_expr | caseExpress | intervalExpr | privateExprOfDb ; functionCall : ID LP_ distinct? (exprs | ASTERISK)? RP_ ; distinct : DISTINCT ; intervalExpr : matchNone ; caseExpress : matchNone ; privateExprOfDb : matchNone ; liter : question | number | TRUE | FALSE | NULL | LBE_ ID STRING RBE_ | HEX_DIGIT | string | ID STRING collateClause? | (DATE | TIME |TIMESTAMP) STRING | ID? BIT_NUM collateClause? ; question : QUESTION ; number : NUMBER ; string : STRING ; subquery : matchNone ; collateClause : matchNone ; orderByClause : ORDER BY orderByItem (COMMA orderByItem)* ; orderByItem : (columnName | number |expr) (ASC|DESC)? ;
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_?) ; BLOCK_COMMENT : SLASH ASTERISK .*? ASTERISK SLASH -> channel(HIDDEN) ; SL_COMMENT : MINUS MINUS ~[\r\n]* -> channel(HIDDEN) ; schemaName : ID ; databaseName : ID ; domainName : ID ; tableName : ID ; columnName : ID ; sequenceName : 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 ; routineName : ID ; roleName : STRING | ID ; partitionName : ID ; rewriteRuleName : ID ; ownerName : ID ; userName : STRING | ID ; serverName : ID ; dataTypeLength : LP_ (NUMBER (COMMA NUMBER)?)? RP_ ; primaryKey : PRIMARY? KEY ; matchNone : 'Default does not match anything' ; ids : ID (COMMA ID)* ; idList : LP_ ids RP_ ; rangeClause : rangeItem (COMMA rangeItem)* | rangeItem OFFSET rangeItem ; rangeItem : number | question ; schemaNames : schemaName (COMMA schemaName)* ; databaseNames : databaseName (COMMA databaseName)* ; domainNames : domainName (COMMA domainName)* ; tableNamesWithParen : LP_ tableNames RP_ ; tableNames : tableName (COMMA tableName)* ; columnNamesWithParen : LP_ columnNames RP_ ; columnNames : columnName (COMMA columnName)* ; columnList : LP_ columnNames RP_ ; sequenceNames : sequenceName (COMMA sequenceName)* ; tablespaceNames : tablespaceName (COMMA tablespaceName)* ; indexNames : indexName (COMMA indexName)* ; indexList : LP_ indexNames RP_ ; typeNames : typeName (COMMA typeName)* ; rowNames : rowName (COMMA rowName)* ; roleNames : roleName (COMMA roleName)* ; userNames : userName (COMMA userName)* ; serverNames : serverName (COMMA serverName)* ; bitExprs: bitExpr (COMMA bitExpr)* ; exprs : expr (COMMA expr)* ; exprsWithParen : 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_ | 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 PLUS intervalExpr | bitExpr MINUS intervalExpr | simpleExpr ; simpleExpr : functionCall | liter | columnName | simpleExpr collateClause //| param_marker | variable | simpleExpr AND_ simpleExpr | PLUS simpleExpr | MINUS simpleExpr | UNARY_BIT_COMPLEMENT simpleExpr | NOT_ simpleExpr | BINARY simpleExpr | exprsWithParen | ROW exprsWithParen | subquery | EXISTS subquery // | (identifier expr) //| match_expr | caseExpress | intervalExpr | privateExprOfDb ; functionCall : ID LP_ distinct? (exprs | ASTERISK)? RP_ ; distinct : DISTINCT ; intervalExpr : matchNone ; caseExpress : matchNone ; privateExprOfDb : matchNone ; variable : matchNone ; liter : question | number | TRUE | FALSE | NULL | LBE_ ID STRING RBE_ | HEX_DIGIT | string | ID STRING collateClause? | (DATE | TIME |TIMESTAMP) STRING | ID? BIT_NUM collateClause? ; question : QUESTION ; number : NUMBER ; string : STRING ; subquery : matchNone ; collateClause : matchNone ; orderByClause : ORDER BY orderByItem (COMMA orderByItem)* ; orderByItem : (columnName | number |expr) (ASC|DESC)? ;
support interval expr
support interval expr
ANTLR
apache-2.0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
ea2897309e23e10c4caf3993492a3b21aaf90625
src/main/antlr4/io/burt/jmespath/JmesPath.g4
src/main/antlr4/io/burt/jmespath/JmesPath.g4
grammar JmesPath; query : expression EOF ; expression : expression '.' (identifier | multiSelectList | multiSelectHash | functionExpression | wildcard='*') # chainExpression | expression bracketSpecifier # bracketedExpression | bracketSpecifier # bracketExpression | expression COMPARATOR expression # comparisonExpression | expression '&&' expression # andExpression | expression '||' expression # orExpression | identifier # identifierExpression | '!' expression # notExpression | '(' expression ')' # parenExpression | '*' # wildcardExpression | multiSelectList # multiSelectListExpression | multiSelectHash # multiSelectHashExpression | literal # literalExpression | functionExpression # functionCallExpression | expression '|' expression # pipeExpression | RAW_STRING # rawStringExpression | currentNode # currentNodeExpression ; multiSelectList : '[' expression (',' expression)* ']' ; multiSelectHash : '{' keyvalExpr (',' keyvalExpr)* '}' ; keyvalExpr : identifier ':' expression ; bracketSpecifier : '[' SIGNED_INT ']' # bracketIndex | '[' '*' ']' # bracketStar | '[' slice ']' # bracketSlice | '[' ']' # bracketFlatten | '[?' expression ']' # select ; slice : start=SIGNED_INT? ':' stop=SIGNED_INT? (':' step=SIGNED_INT?)? ; COMPARATOR : '<' | '<=' | '==' | '>=' | '>' | '!=' ; functionExpression : NAME (noArgs | oneOrMoreArgs) ; noArgs : '(' ')' ; oneOrMoreArgs : '(' functionArg (',' functionArg)* ')' ; functionArg : expression | expressionType ; currentNode : '@' ; expressionType : '&' expression ; RAW_STRING : '\'' (RAW_ESC | ~['\\])* '\'' ; fragment RAW_ESC : '\\' ['\\] ; literal : '`' value '`' ; identifier : NAME | STRING ; NAME : [a-zA-Z] ([a-zA-Z] | [0-9] | '_')* ; json : object | array ; object : '{' pair (',' pair)* '}' | '{' '}' ; pair : STRING ':' value ; array : '[' value (',' value)* ']' | '[' ']' ; value : STRING | (REAL_OR_EXPONENT_NUMBER | SIGNED_INT) | object | array | 'true' | 'false' | 'null' ; STRING : '"' (ESC | ~ ["\\])* '"' ; fragment ESC : '\\' (["\\/bfnrt] | UNICODE) ; fragment UNICODE : 'u' HEX HEX HEX HEX ; fragment HEX : [0-9a-fA-F] ; REAL_OR_EXPONENT_NUMBER : '-'? INT '.' [0-9] + EXP? | '-'? INT EXP ; SIGNED_INT : '-'? INT ; fragment INT : '0' | [1-9] [0-9]* ; fragment EXP : [Ee] [+\-]? INT ; WS : [ \t\n\r] + -> skip ;
grammar JmesPath; query : expression EOF ; expression : expression '.' (identifier | multiSelectList | multiSelectHash | functionExpression | wildcard='*') # chainExpression | expression bracketSpecifier # bracketedExpression | bracketSpecifier # bracketExpression | expression COMPARATOR expression # comparisonExpression | expression '&&' expression # andExpression | expression '||' expression # orExpression | identifier # identifierExpression | '!' expression # notExpression | '(' expression ')' # parenExpression | '*' # wildcardExpression | multiSelectList # multiSelectListExpression | multiSelectHash # multiSelectHashExpression | literal # literalExpression | functionExpression # functionCallExpression | expression '|' expression # pipeExpression | RAW_STRING # rawStringExpression | currentNode # currentNodeExpression ; multiSelectList : '[' expression (',' expression)* ']' ; multiSelectHash : '{' keyvalExpr (',' keyvalExpr)* '}' ; keyvalExpr : identifier ':' expression ; bracketSpecifier : '[' SIGNED_INT ']' # bracketIndex | '[' '*' ']' # bracketStar | '[' slice ']' # bracketSlice | '[' ']' # bracketFlatten | '[?' expression ']' # select ; slice : start=SIGNED_INT? ':' stop=SIGNED_INT? (':' step=SIGNED_INT?)? ; COMPARATOR : '<' | '<=' | '==' | '>=' | '>' | '!=' ; functionExpression : NAME (noArgs | oneOrMoreArgs) ; noArgs : '(' ')' ; oneOrMoreArgs : '(' functionArg (',' functionArg)* ')' ; functionArg : expression | expressionType ; currentNode : '@' ; expressionType : '&' expression ; RAW_STRING : '\'' (RAW_ESC | ~['\\])* '\'' ; fragment RAW_ESC : '\\' ['\\] ; literal : '`' value '`' ; identifier : NAME | STRING ; NAME : [a-zA-Z_] [a-zA-Z0-9_]* ; json : object | array ; object : '{' pair (',' pair)* '}' | '{' '}' ; pair : STRING ':' value ; array : '[' value (',' value)* ']' | '[' ']' ; value : STRING | (REAL_OR_EXPONENT_NUMBER | SIGNED_INT) | object | array | 'true' | 'false' | 'null' ; STRING : '"' (ESC | ~ ["\\])* '"' ; fragment ESC : '\\' (["\\/bfnrt] | UNICODE) ; fragment UNICODE : 'u' HEX HEX HEX HEX ; fragment HEX : [0-9a-fA-F] ; REAL_OR_EXPONENT_NUMBER : '-'? INT '.' [0-9] + EXP? | '-'? INT EXP ; SIGNED_INT : '-'? INT ; fragment INT : '0' | [1-9] [0-9]* ; fragment EXP : [Ee] [+\-]? INT ; WS : [ \t\n\r] + -> skip ;
Allow names to start with underscore
Allow names to start with underscore
ANTLR
bsd-3-clause
burtcorp/jmespath-java
b34316ee5bc7299a6612e2a704d24efc25ad3a00
mini-projeto/Cymbol.g4
mini-projeto/Cymbol.g4
grammar Cymbol; //Lexer fragment NUMBER : [0-9]; fragment LETTER : [a-zA-Z]; TYPEINT : 'int'; TYPEFLOAT : 'float'; TYPEBOOLEAN : 'boolean'; IF : 'if'; ELSE : 'else'; RETURN : 'return'; LP : '('; RP : ')'; COMMA : ','; SEMICOLON : ';'; LB : '{'; RB : '}'; AS : '='; EQ : '=='; NE : '!='; NOT : '!'; GT : '>'; LT : '<'; GE : '>='; LE : '<='; MUL : '*'; DIV : '/'; PLUS : '+'; MINUS : '-'; AND : '&&'; OR : '||'; BOOLEAN: 'true' | 'false'; ID : (LETTER) (LETTER | NUMBER)*; INT : NUMBER+; FLOAT: NUMBER+ '.' NUMBER+; BLOCKCOMMENT : '/*' .*? '*/' -> skip; LINECOMMENT : '//' .*? '\n' -> skip; WS : [ \t\n\r]+ -> skip; //Parser fiile : (funcDecl | varDecl)+ EOF? ; varDecl : type ID ('=' expr)? ';' ; tyype : TYPEINT | TYPEFLOAT | TYPEBOOLEAN ; funcDecl : type ID '(' paramTypeList? ')' block ; paramTypeList : paramType (',' paramType)* ; paramType : tyype ID ; block : '{' stat* '}' ; assignStat : ID '=' expr ';' ; returnStat : 'return' expr? ';' ; ifElseStat : ifStat (elseStat)? ; ifElseExprStat : block | ifElseStat | returnStat | assignStat | exprStat ; ifStat : 'if' '(' expr ')' ifElseExprStat ; elseStat : 'else' ifElseExprStat ; exprStat : expr ';' ; exprList : expr (',' expr)* ; stat : varDecl | ifElseStat | returnStat | assignStat | exprStat ; expr : ID '(' exprList? ')' | op=('+' | '-') expr | '!' expr | expr op=('<' | '>' | '<=' | '>=') expr | expr op=('*' | '/') expr | expr op=('+' | '-') expr | expr op=("&&"|"||") expr | expr op=("=="|"!=") expr | ID | INT | FLOAT | BOOLEAN | '(' expr ')' ;
grammar Cymbol; //Lexer fragment NUMBER : [0-9]; fragment LETTER : [a-zA-Z]; TYPEINT : 'int'; TYPEFLOAT : 'float'; TYPEBOOLEAN : 'boolean'; IF : 'if'; ELSE : 'else'; RETURN : 'return'; LP : '('; RP : ')'; COMMA : ','; SEMICOLON : ';'; LB : '{'; RB : '}'; AS : '='; EQ : '=='; NE : '!='; NOT : '!'; GT : '>'; LT : '<'; GE : '>='; LE : '<='; MUL : '*'; DIV : '/'; PLUS : '+'; MINUS : '-'; AND : '&&'; OR : '||'; BOOLEAN: 'true' | 'false'; ID : (LETTER) (LETTER | NUMBER)*; INT : NUMBER+; FLOAT: NUMBER+ '.' NUMBER+; BLOCKCOMMENT : '/*' .*? '*/' -> skip; LINECOMMENT : '//' .*? '\n' -> skip; WS : [ \t\n\r]+ -> skip; //Parser fiile : (funcDecl | varDecl)+ EOF? ; varDecl : tyype ID ('=' expr)? ';' ; tyype : TYPEINT | TYPEFLOAT | TYPEBOOLEAN ; funcDecl : tyype ID '(' paramTypeList? ')' block ; paramTypeList : paramType (',' paramType)* ; paramType : tyype ID ; block : '{' stat* '}' ; assignStat : ID '=' expr ';' ; returnStat : 'return' expr? ';' ; ifElseStat : ifStat (elseStat)? ; ifElseExprStat : block | ifElseStat | returnStat | assignStat | exprStat ; ifStat : 'if' '(' expr ')' ifElseExprStat ; elseStat : 'else' ifElseExprStat ; exprStat : expr ';' ; exprList : expr (',' expr)* ; stat : varDecl | ifElseStat | returnStat | assignStat | exprStat ; expr : ID '(' exprList? ')' | op=('+' | '-') expr | '!' expr | expr op=('<' | '>' | '<=' | '>=') expr | expr op=('*' | '/') expr | expr op=('+' | '-') expr | expr op=('&&'| '||') expr | expr op=('=='| '!=') expr | ID | INT | FLOAT | BOOLEAN | '(' expr ')' ;
Adjust grammar from project
Adjust grammar from project * Fix 'type' calls for 'tyype' * Fix wrong ' " '
ANTLR
mit
damorim/compilers-cin,damorim/compilers-cin,damorim/compilers-cin,damorim/compilers-cin
b52ddd9b328eebcfeed427ecacc5fbfbb8b8e642
graphstream-dgs/DGSLexer.g4
graphstream-dgs/DGSLexer.g4
/* BSD License Copyright (c) 2017, Tim Hemel 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 Tim Hemel 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. */ /* * Graphstream DGS grammar. * * Adapted from http://graphstream-project.org/doc/Advanced-Concepts/The-DGS-File-Format/ * */ lexer grammar DGSLexer; MAGIC : 'DGS004' | 'DGS003'; AN : 'an'; CN : 'cn'; DN : 'dn'; AE : 'ae'; CE : 'ce'; DE : 'de'; CG : 'cg'; ST : 'st'; CL : 'cl'; INT : ('+'|'-')? ( '0' | ( [1-9] ([0-9])* ) ); REAL : INT ( '.' [0-9]*)? ( [Ee] ('+'|'-')? [0-9]*[1-9] )?; PLUS : '+'; MINUS : '-'; COMMA : ','; LBRACE : '{'; RBRACE : '}'; LBRACK : '['; RBRACK : ']'; DOT : '.'; LANGLE : '<'; RANGLE : '>'; EQUALS : '='; COLON : ':'; EOL : '\r'|'\n'|'\r\n'; WORD : ( 'a'..'z' | 'A'..'Z' ) ( 'a'..'z' | 'A'..'Z' | '0'..'9' | '-' | '_' )* ; STRING : SQSTRING | DQSTRING; fragment DQSTRING : '"' (DQESC|.)*? '"'; fragment DQESC : '\\"' | '\\\\' ; fragment SQSTRING : '\'' (SQESC|.)*? '\''; fragment SQESC : '\\\'' | '\\\\' ; fragment HEXBYTE : ([0-9a-fA-F]) ([0-9a-fA-F]) ; COLOR : '#' HEXBYTE HEXBYTE HEXBYTE HEXBYTE? ; START_COMMENT : '#' -> pushMode(CMT), skip; WS : [ \t]+ -> skip; // identifier : STRING | INT | WORD ( '.' WORD )* ; mode CMT; COMMENT: .*? EOL -> popMode;
/* BSD License Copyright (c) 2017, Tim Hemel 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 Tim Hemel 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. */ /* * Graphstream DGS grammar. * * Adapted from http://graphstream-project.org/doc/Advanced-Concepts/The-DGS-File-Format/ * */ lexer grammar DGSLexer; MAGIC : 'DGS004' | 'DGS003'; AN : 'an'; CN : 'cn'; DN : 'dn'; AE : 'ae'; CE : 'ce'; DE : 'de'; CG : 'cg'; ST : 'st'; CL : 'cl'; INT : ('+'|'-')? ( '0' | ( [1-9] ([0-9])* ) ); REAL : INT ( '.' [0-9]*)? ( [Ee] ('+'|'-')? [0-9]*[1-9] )?; PLUS : '+'; MINUS : '-'; COMMA : ','; LBRACE : '{'; RBRACE : '}'; LBRACK : '['; RBRACK : ']'; DOT : '.'; LANGLE : '<'; RANGLE : '>'; EQUALS : '='; COLON : ':'; EOL : '\r'|'\n'|'\r\n'; WORD : ( 'a'..'z' | 'A'..'Z' ) ( 'a'..'z' | 'A'..'Z' | '0'..'9' | '-' | '_' )* ; STRING : SQSTRING | DQSTRING; fragment DQSTRING : '"' (DQESC|.)*? '"'; fragment DQESC : '\\"' | '\\\\' ; fragment SQSTRING : '\'' (SQESC|.)*? '\''; fragment SQESC : '\\\'' | '\\\\' ; fragment HEXBYTE : ([0-9a-fA-F]) ([0-9a-fA-F]) ; COLOR : '#' HEXBYTE HEXBYTE HEXBYTE HEXBYTE? ; START_COMMENT : '#' -> pushMode(CMT), skip; WS : [ \t]+ -> skip; mode CMT; COMMENT: .*? EOL -> popMode;
clean up code
clean up 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
50cf6acb3f14d5b317636f4c162562410f2c58d3
Solidity.g4
Solidity.g4
// 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 ';' ; NatSpecSingleLine : ('///' .*? [\r\n]) + ; NatSpecMultiLine : '/**' .*? '*/' ; natSpec : NatSpecSingleLine | NatSpecMultiLine ; contractDefinition : natSpec? ( 'contract' | 'interface' | 'library' ) identifier ( 'is' inheritanceSpecifier (',' inheritanceSpecifier )* )? '{' contractPart* '}' ; inheritanceSpecifier : userDefinedTypeName ( '(' expressionList? ')' )? ; 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 : natSpec? 'function' identifier? parameterList modifierList returnParameters? ( ';' | block ) ; returnParameters : 'returns' parameterList ; modifierList : ( modifierInvocation | stateMutability | ExternalKeyword | PublicKeyword | InternalKeyword | PrivateKeyword )* ; eventDefinition : natSpec? '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 ('[' ']')? | TypeKeyword | 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 : ( DecimalDigits | (DecimalDigits? '.' DecimalDigits) ) ( [eE] DecimalDigits )? ; fragment DecimalDigits : [0-9] ( '_'? [0-9] )* ; HexNumber : '0' [xX] HexDigits ; fragment HexDigits : HexCharacter ( '_'? 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' | 'typeof' ; AnonymousKeyword : 'anonymous' ; BreakKeyword : 'break' ; ConstantKeyword : 'constant' ; ContinueKeyword : 'continue' ; ExternalKeyword : 'external' ; IndexedKeyword : 'indexed' ; InternalKeyword : 'internal' ; PayableKeyword : 'payable' ; PrivateKeyword : 'private' ; PublicKeyword : 'public' ; PureKeyword : 'pure' ; TypeKeyword : 'type' ; 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 ';' ; NatSpecSingleLine : ('///' .*? [\r\n]) + ; NatSpecMultiLine : '/**' .*? '*/' ; natSpec : NatSpecSingleLine | NatSpecMultiLine ; contractDefinition : natSpec? ( 'contract' | 'interface' | 'library' ) identifier ( 'is' inheritanceSpecifier (',' inheritanceSpecifier )* )? '{' contractPart* '}' ; inheritanceSpecifier : userDefinedTypeName ( '(' expressionList? ')' )? ; 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 : natSpec? 'function' identifier? parameterList modifierList returnParameters? ( ';' | block ) ; returnParameters : 'returns' parameterList ; modifierList : ( modifierInvocation | stateMutability | ExternalKeyword | PublicKeyword | InternalKeyword | PrivateKeyword )* ; eventDefinition : natSpec? '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 ('[' ']')? | TypeKeyword | tupleExpression | typeNameExpression ('[' ']')? ; 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 )* )? ']' ; typeNameExpression : elementaryTypeName | userDefinedTypeName ; numberLiteral : (DecimalNumber | HexNumber) NumberUnit? ; identifier : ('from' | 'calldata' | Identifier) ; VersionLiteral : [0-9]+ '.' [0-9]+ '.' [0-9]+ ; BooleanLiteral : 'true' | 'false' ; DecimalNumber : ( DecimalDigits | (DecimalDigits? '.' DecimalDigits) ) ( [eE] DecimalDigits )? ; fragment DecimalDigits : [0-9] ( '_'? [0-9] )* ; HexNumber : '0' [xX] HexDigits ; fragment HexDigits : HexCharacter ( '_'? 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' | 'typeof' ; AnonymousKeyword : 'anonymous' ; BreakKeyword : 'break' ; ConstantKeyword : 'constant' ; ContinueKeyword : 'continue' ; ExternalKeyword : 'external' ; IndexedKeyword : 'indexed' ; InternalKeyword : 'internal' ; PayableKeyword : 'payable' ; PrivateKeyword : 'private' ; PublicKeyword : 'public' ; PureKeyword : 'pure' ; TypeKeyword : 'type' ; 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) ;
Allow user defined typenames in typename expressions
Allow user defined typenames in typename expressions
ANTLR
mit
solidityj/solidity-antlr4,federicobond/solidity-antlr4
92c7c16a6d572fd5ed882c1c26bece307aeb1375
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 (optionFor_? classPrivilegesClause_ | classTypePrivilegesClause_) ; deny : DENY (classPrivilegesClause_ | classTypePrivilegesClause_) ; classPrivilegesClause_ : classPrivileges_ (ON onClassClause_)? ; classTypePrivilegesClause_ : classTypePrivileges_ (ON onClassTypeClause_)? ; optionFor_ : GRANT OPTION FOR ; classPrivileges_ : (ALL PRIVILEGES? | (privilegeType_ columnNames? (COMMA_ privilegeType_ columnNames?)*)) ; onClassClause_ : class_? tableName ; classTypePrivileges_ : privilegeType_ (COMMA_ privilegeType_)* ; onClassTypeClause_ : classType_? tableName ; privilegeType_ : 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? | 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 ;
modify privilegeType_
modify privilegeType_
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
c12ee45a88f90d40359b6c5032646cfd3ccf13c8
Src/grammar/cql.g4
Src/grammar/cql.g4
grammar cql; /* * Clinical Quality Language Grammar Specification * Version 1.3 - May 2018 STU3 Ballot */ import fhirpath; /* * Parser Rules */ library : libraryDefinition? usingDefinition* includeDefinition* codesystemDefinition* valuesetDefinition* codeDefinition* conceptDefinition* parameterDefinition* statement* ; /* * Definitions */ libraryDefinition : 'library' identifier ('version' versionSpecifier)? ; usingDefinition : 'using' modelIdentifier ('version' versionSpecifier)? ; includeDefinition : 'include' identifier ('version' versionSpecifier)? ('called' localIdentifier)? ; localIdentifier : identifier ; accessModifier : 'public' | 'private' ; parameterDefinition : accessModifier? 'parameter' identifier (typeSpecifier)? ('default' expression)? ; codesystemDefinition : accessModifier? 'codesystem' identifier ':' codesystemId ('version' versionSpecifier)? ; valuesetDefinition : accessModifier? 'valueset' identifier ':' valuesetId ('version' versionSpecifier)? codesystems? ; codesystems : 'codesystems' '{' codesystemIdentifier (',' codesystemIdentifier)* '}' ; codesystemIdentifier : (libraryIdentifier '.')? identifier ; libraryIdentifier : identifier ; codeDefinition : accessModifier? 'code' identifier ':' codeId 'from' codesystemIdentifier displayClause? ; conceptDefinition : accessModifier? 'concept' identifier ':' '{' codeIdentifier (',' codeIdentifier)* '}' displayClause? ; codeIdentifier : (libraryIdentifier '.')? identifier ; codesystemId : STRING ; valuesetId : STRING ; versionSpecifier : STRING ; codeId : STRING ; /* * Type Specifiers */ typeSpecifier : namedTypeSpecifier | listTypeSpecifier | intervalTypeSpecifier | tupleTypeSpecifier | choiceTypeSpecifier ; namedTypeSpecifier : (qualifier '.')* identifier ; modelIdentifier : identifier ; listTypeSpecifier : 'List' '<' typeSpecifier '>' ; intervalTypeSpecifier : 'Interval' '<' typeSpecifier '>' ; tupleTypeSpecifier : 'Tuple' '{' tupleElementDefinition (',' tupleElementDefinition)* '}' ; tupleElementDefinition : identifier typeSpecifier ; choiceTypeSpecifier : 'Choice' '<' typeSpecifier (',' typeSpecifier)* '>' ; /* * Statements */ statement : expressionDefinition | contextDefinition | functionDefinition ; expressionDefinition : 'define' accessModifier? identifier ':' expression ; contextDefinition : 'context' identifier ; functionDefinition : 'define' accessModifier? 'function' identifier '(' (operandDefinition (',' operandDefinition)*)? ')' ('returns' typeSpecifier)? ':' (functionBody | 'external') ; operandDefinition : identifier typeSpecifier ; functionBody : expression ; /* * Expressions */ querySource : retrieve | qualifiedIdentifier | '(' expression ')' ; aliasedQuerySource : querySource alias ; alias : identifier ; queryInclusionClause : withClause | withoutClause ; withClause : 'with' aliasedQuerySource 'such that' expression ; withoutClause : 'without' aliasedQuerySource 'such that' expression ; retrieve : '[' namedTypeSpecifier (':' (codePath 'in')? terminology)? ']' ; codePath : identifier ; terminology : qualifiedIdentifier | expression ; qualifier : identifier ; query : sourceClause letClause? queryInclusionClause* whereClause? returnClause? sortClause? ; sourceClause : 'from'? aliasedQuerySource (',' aliasedQuerySource)* ; letClause : 'let' letClauseItem (',' letClauseItem)* ; letClauseItem : identifier ':' expression ; whereClause : 'where' expression ; returnClause : 'return' ('all' | 'distinct')? expression ; sortClause : 'sort' ( sortDirection | ('by' sortByItem (',' sortByItem)*) ) ; sortDirection : 'asc' | 'ascending' | 'desc' | 'descending' ; sortByItem : expressionTerm sortDirection? ; qualifiedIdentifier : (qualifier '.')* identifier ; expression : expressionTerm #termExpression | retrieve #retrieveExpression | query #queryExpression | expression 'is' 'not'? ('null' | 'true' | 'false') #booleanExpression | expression ('is' | 'as') typeSpecifier #typeExpression | 'cast' expression 'as' typeSpecifier #castExpression | 'not' expression #notExpression | 'exists' expression #existenceExpression | expression 'properly'? 'between' expressionTerm 'and' expressionTerm #betweenExpression | ('duration' 'in')? pluralDateTimePrecision 'between' expressionTerm 'and' expressionTerm #durationBetweenExpression | 'difference' 'in' pluralDateTimePrecision 'between' expressionTerm 'and' expressionTerm #differenceBetweenExpression | expression ('<=' | '<' | '>' | '>=') expression #inequalityExpression | expression intervalOperatorPhrase expression #timingExpression | expression ('=' | '!=' | '~' | '!~') expression #equalityExpression | expression ('in' | 'contains') dateTimePrecisionSpecifier? expression #membershipExpression | expression 'and' expression #andExpression | expression ('or' | 'xor') expression #orExpression | expression 'implies' expression #impliesExpression | expression ('|' | 'union' | 'intersect' | 'except') expression #inFixSetExpression ; dateTimePrecision : 'year' | 'month' | 'week' | 'day' | 'hour' | 'minute' | 'second' | 'millisecond' ; dateTimeComponent : dateTimePrecision | 'date' | 'time' | 'timezone' ; pluralDateTimePrecision : 'years' | 'months' | 'weeks' | 'days' | 'hours' | 'minutes' | 'seconds' | 'milliseconds' ; expressionTerm : term #termExpressionTerm | expressionTerm '.' invocation #invocationExpressionTerm | expressionTerm '[' expression ']' #indexedExpressionTerm | 'convert' expression 'to' typeSpecifier #conversionExpressionTerm | ('+' | '-') expressionTerm #polarityExpressionTerm | ('start' | 'end') 'of' expressionTerm #timeBoundaryExpressionTerm | dateTimeComponent 'from' expressionTerm #timeUnitExpressionTerm | 'duration' 'in' pluralDateTimePrecision 'of' expressionTerm #durationExpressionTerm | 'difference' 'in' pluralDateTimePrecision 'of' expressionTerm #differenceExpressionTerm | 'width' 'of' expressionTerm #widthExpressionTerm | 'successor' 'of' expressionTerm #successorExpressionTerm | 'predecessor' 'of' expressionTerm #predecessorExpressionTerm | 'singleton' 'from' expressionTerm #elementExtractorExpressionTerm | 'point' 'from' expressionTerm #pointExtractorExpressionTerm | ('minimum' | 'maximum') namedTypeSpecifier #typeExtentExpressionTerm | expressionTerm '^' expressionTerm #powerExpressionTerm | expressionTerm ('*' | '/' | 'div' | 'mod') expressionTerm #multiplicationExpressionTerm | expressionTerm ('+' | '-' | '&') expressionTerm #additionExpressionTerm | 'if' expression 'then' expression 'else' expression #ifThenElseExpressionTerm | 'case' expression? caseExpressionItem+ 'else' expression 'end' #caseExpressionTerm | ('distinct' | 'flatten') expression #aggregateExpressionTerm | ('expand' | 'collapse') expression ('per' (dateTimePrecision | expression))? #setAggregateExpressionTerm ; caseExpressionItem : 'when' expression 'then' expression ; dateTimePrecisionSpecifier : dateTimePrecision 'of' ; relativeQualifier : 'or before' | 'or after' ; offsetRelativeQualifier : 'or more' | 'or less' ; exclusiveRelativeQualifier : 'less than' | 'more than' ; quantityOffset : (quantity offsetRelativeQualifier?) | (exclusiveRelativeQualifier quantity) ; temporalRelationship : ('on or'? ('before' | 'after')) | (('before' | 'after') 'or on'?) ; intervalOperatorPhrase : ('starts' | 'ends' | 'occurs')? 'same' dateTimePrecision? (relativeQualifier | 'as') ('start' | 'end')? #concurrentWithIntervalOperatorPhrase | 'properly'? 'includes' dateTimePrecisionSpecifier? ('start' | 'end')? #includesIntervalOperatorPhrase | ('starts' | 'ends' | 'occurs')? 'properly'? ('during' | 'included in') dateTimePrecisionSpecifier? #includedInIntervalOperatorPhrase | ('starts' | 'ends' | 'occurs')? quantityOffset? temporalRelationship dateTimePrecisionSpecifier? ('start' | 'end')? #beforeOrAfterIntervalOperatorPhrase | ('starts' | 'ends' | 'occurs')? 'properly'? 'within' quantity 'of' ('start' | 'end')? #withinIntervalOperatorPhrase | 'meets' ('before' | 'after')? dateTimePrecisionSpecifier? #meetsIntervalOperatorPhrase | 'overlaps' ('before' | 'after')? dateTimePrecisionSpecifier? #overlapsIntervalOperatorPhrase | 'starts' dateTimePrecisionSpecifier? #startsIntervalOperatorPhrase | 'ends' dateTimePrecisionSpecifier? #endsIntervalOperatorPhrase ; term : invocation #invocationTerm | literal #literalTerm | externalConstant #externalConstantTerm | intervalSelector #intervalSelectorTerm | tupleSelector #tupleSelectorTerm | instanceSelector #instanceSelectorTerm | listSelector #listSelectorTerm | codeSelector #codeSelectorTerm | conceptSelector #conceptSelectorTerm | '(' expression ')' #parenthesizedTerm ; ratio : quantity ':' quantity ; literal : ('true' | 'false') #booleanLiteral | 'null' #nullLiteral | STRING #stringLiteral | NUMBER #numberLiteral | DATETIME #dateTimeLiteral | TIME #timeLiteral | quantity #quantityLiteral | ratio #ratioLiteral ; intervalSelector : // TODO: Consider this as an alternative syntax for intervals... (would need to be moved up to expression to make it work) //expression ( '..' | '*.' | '.*' | '**' ) expression; 'Interval' ('['|'(') expression ',' expression (']'|')') ; tupleSelector : 'Tuple'? '{' (':' | (tupleElementSelector (',' tupleElementSelector)*)) '}' ; tupleElementSelector : identifier ':' expression ; instanceSelector : namedTypeSpecifier '{' (':' | (instanceElementSelector (',' instanceElementSelector)*)) '}' ; instanceElementSelector : identifier ':' expression ; listSelector : ('List' ('<' typeSpecifier '>')?)? '{' (expression (',' expression)*)? '}' ; displayClause : 'display' STRING ; codeSelector : 'Code' STRING 'from' codesystemIdentifier displayClause? ; conceptSelector : 'Concept' '{' codeSelector (',' codeSelector)* '}' displayClause? ; identifier : IDENTIFIER | DELIMITEDIDENTIFIER | QUOTEDIDENTIFIER | 'all' | 'Code' | 'code' | 'Concept' | 'concept' | 'contains' | 'date' | 'display' | 'distinct' | 'end' // | 'exists' NOTE: This is excluded because including it causes a significant performance degradation in the ANTLR parser, still looking into a fix for this | 'not' | 'start' | 'time' | 'timezone' | 'version' | 'where' ; QUOTEDIDENTIFIER : '"' (ESC | .)*? '"' ; fragment ESC : '\\' ([`'"\\/fnrt] | UNICODE) // allow \`, \', \", \\, \/, \f, etc. and \uXXX ;
grammar cql; /* * Clinical Quality Language Grammar Specification * Version 1.3 - STU3 Publication */ import fhirpath; /* * Parser Rules */ library : libraryDefinition? usingDefinition* includeDefinition* codesystemDefinition* valuesetDefinition* codeDefinition* conceptDefinition* parameterDefinition* statement* ; /* * Definitions */ libraryDefinition : 'library' identifier ('version' versionSpecifier)? ; usingDefinition : 'using' modelIdentifier ('version' versionSpecifier)? ; includeDefinition : 'include' identifier ('version' versionSpecifier)? ('called' localIdentifier)? ; localIdentifier : identifier ; accessModifier : 'public' | 'private' ; parameterDefinition : accessModifier? 'parameter' identifier (typeSpecifier)? ('default' expression)? ; codesystemDefinition : accessModifier? 'codesystem' identifier ':' codesystemId ('version' versionSpecifier)? ; valuesetDefinition : accessModifier? 'valueset' identifier ':' valuesetId ('version' versionSpecifier)? codesystems? ; codesystems : 'codesystems' '{' codesystemIdentifier (',' codesystemIdentifier)* '}' ; codesystemIdentifier : (libraryIdentifier '.')? identifier ; libraryIdentifier : identifier ; codeDefinition : accessModifier? 'code' identifier ':' codeId 'from' codesystemIdentifier displayClause? ; conceptDefinition : accessModifier? 'concept' identifier ':' '{' codeIdentifier (',' codeIdentifier)* '}' displayClause? ; codeIdentifier : (libraryIdentifier '.')? identifier ; codesystemId : STRING ; valuesetId : STRING ; versionSpecifier : STRING ; codeId : STRING ; /* * Type Specifiers */ typeSpecifier : namedTypeSpecifier | listTypeSpecifier | intervalTypeSpecifier | tupleTypeSpecifier | choiceTypeSpecifier ; namedTypeSpecifier : (qualifier '.')* identifier ; modelIdentifier : identifier ; listTypeSpecifier : 'List' '<' typeSpecifier '>' ; intervalTypeSpecifier : 'Interval' '<' typeSpecifier '>' ; tupleTypeSpecifier : 'Tuple' '{' tupleElementDefinition (',' tupleElementDefinition)* '}' ; tupleElementDefinition : identifier typeSpecifier ; choiceTypeSpecifier : 'Choice' '<' typeSpecifier (',' typeSpecifier)* '>' ; /* * Statements */ statement : expressionDefinition | contextDefinition | functionDefinition ; expressionDefinition : 'define' accessModifier? identifier ':' expression ; contextDefinition : 'context' identifier ; functionDefinition : 'define' accessModifier? 'function' identifier '(' (operandDefinition (',' operandDefinition)*)? ')' ('returns' typeSpecifier)? ':' (functionBody | 'external') ; operandDefinition : identifier typeSpecifier ; functionBody : expression ; /* * Expressions */ querySource : retrieve | qualifiedIdentifier | '(' expression ')' ; aliasedQuerySource : querySource alias ; alias : identifier ; queryInclusionClause : withClause | withoutClause ; withClause : 'with' aliasedQuerySource 'such that' expression ; withoutClause : 'without' aliasedQuerySource 'such that' expression ; retrieve : '[' namedTypeSpecifier (':' (codePath 'in')? terminology)? ']' ; codePath : identifier ; terminology : qualifiedIdentifier | expression ; qualifier : identifier ; query : sourceClause letClause? queryInclusionClause* whereClause? returnClause? sortClause? ; sourceClause : 'from'? aliasedQuerySource (',' aliasedQuerySource)* ; letClause : 'let' letClauseItem (',' letClauseItem)* ; letClauseItem : identifier ':' expression ; whereClause : 'where' expression ; returnClause : 'return' ('all' | 'distinct')? expression ; sortClause : 'sort' ( sortDirection | ('by' sortByItem (',' sortByItem)*) ) ; sortDirection : 'asc' | 'ascending' | 'desc' | 'descending' ; sortByItem : expressionTerm sortDirection? ; qualifiedIdentifier : (qualifier '.')* identifier ; expression : expressionTerm #termExpression | retrieve #retrieveExpression | query #queryExpression | expression 'is' 'not'? ('null' | 'true' | 'false') #booleanExpression | expression ('is' | 'as') typeSpecifier #typeExpression | 'cast' expression 'as' typeSpecifier #castExpression | 'not' expression #notExpression | 'exists' expression #existenceExpression | expression 'properly'? 'between' expressionTerm 'and' expressionTerm #betweenExpression | ('duration' 'in')? pluralDateTimePrecision 'between' expressionTerm 'and' expressionTerm #durationBetweenExpression | 'difference' 'in' pluralDateTimePrecision 'between' expressionTerm 'and' expressionTerm #differenceBetweenExpression | expression ('<=' | '<' | '>' | '>=') expression #inequalityExpression | expression intervalOperatorPhrase expression #timingExpression | expression ('=' | '!=' | '~' | '!~') expression #equalityExpression | expression ('in' | 'contains') dateTimePrecisionSpecifier? expression #membershipExpression | expression 'and' expression #andExpression | expression ('or' | 'xor') expression #orExpression | expression 'implies' expression #impliesExpression | expression ('|' | 'union' | 'intersect' | 'except') expression #inFixSetExpression ; dateTimePrecision : 'year' | 'month' | 'week' | 'day' | 'hour' | 'minute' | 'second' | 'millisecond' ; dateTimeComponent : dateTimePrecision | 'date' | 'time' | 'timezone' ; pluralDateTimePrecision : 'years' | 'months' | 'weeks' | 'days' | 'hours' | 'minutes' | 'seconds' | 'milliseconds' ; expressionTerm : term #termExpressionTerm | expressionTerm '.' invocation #invocationExpressionTerm | expressionTerm '[' expression ']' #indexedExpressionTerm | 'convert' expression 'to' typeSpecifier #conversionExpressionTerm | ('+' | '-') expressionTerm #polarityExpressionTerm | ('start' | 'end') 'of' expressionTerm #timeBoundaryExpressionTerm | dateTimeComponent 'from' expressionTerm #timeUnitExpressionTerm | 'duration' 'in' pluralDateTimePrecision 'of' expressionTerm #durationExpressionTerm | 'difference' 'in' pluralDateTimePrecision 'of' expressionTerm #differenceExpressionTerm | 'width' 'of' expressionTerm #widthExpressionTerm | 'successor' 'of' expressionTerm #successorExpressionTerm | 'predecessor' 'of' expressionTerm #predecessorExpressionTerm | 'singleton' 'from' expressionTerm #elementExtractorExpressionTerm | 'point' 'from' expressionTerm #pointExtractorExpressionTerm | ('minimum' | 'maximum') namedTypeSpecifier #typeExtentExpressionTerm | expressionTerm '^' expressionTerm #powerExpressionTerm | expressionTerm ('*' | '/' | 'div' | 'mod') expressionTerm #multiplicationExpressionTerm | expressionTerm ('+' | '-' | '&') expressionTerm #additionExpressionTerm | 'if' expression 'then' expression 'else' expression #ifThenElseExpressionTerm | 'case' expression? caseExpressionItem+ 'else' expression 'end' #caseExpressionTerm | ('distinct' | 'flatten') expression #aggregateExpressionTerm | ('expand' | 'collapse') expression ('per' (dateTimePrecision | expression))? #setAggregateExpressionTerm ; caseExpressionItem : 'when' expression 'then' expression ; dateTimePrecisionSpecifier : dateTimePrecision 'of' ; relativeQualifier : 'or before' | 'or after' ; offsetRelativeQualifier : 'or more' | 'or less' ; exclusiveRelativeQualifier : 'less than' | 'more than' ; quantityOffset : (quantity offsetRelativeQualifier?) | (exclusiveRelativeQualifier quantity) ; temporalRelationship : ('on or'? ('before' | 'after')) | (('before' | 'after') 'or on'?) ; intervalOperatorPhrase : ('starts' | 'ends' | 'occurs')? 'same' dateTimePrecision? (relativeQualifier | 'as') ('start' | 'end')? #concurrentWithIntervalOperatorPhrase | 'properly'? 'includes' dateTimePrecisionSpecifier? ('start' | 'end')? #includesIntervalOperatorPhrase | ('starts' | 'ends' | 'occurs')? 'properly'? ('during' | 'included in') dateTimePrecisionSpecifier? #includedInIntervalOperatorPhrase | ('starts' | 'ends' | 'occurs')? quantityOffset? temporalRelationship dateTimePrecisionSpecifier? ('start' | 'end')? #beforeOrAfterIntervalOperatorPhrase | ('starts' | 'ends' | 'occurs')? 'properly'? 'within' quantity 'of' ('start' | 'end')? #withinIntervalOperatorPhrase | 'meets' ('before' | 'after')? dateTimePrecisionSpecifier? #meetsIntervalOperatorPhrase | 'overlaps' ('before' | 'after')? dateTimePrecisionSpecifier? #overlapsIntervalOperatorPhrase | 'starts' dateTimePrecisionSpecifier? #startsIntervalOperatorPhrase | 'ends' dateTimePrecisionSpecifier? #endsIntervalOperatorPhrase ; term : invocation #invocationTerm | literal #literalTerm | externalConstant #externalConstantTerm | intervalSelector #intervalSelectorTerm | tupleSelector #tupleSelectorTerm | instanceSelector #instanceSelectorTerm | listSelector #listSelectorTerm | codeSelector #codeSelectorTerm | conceptSelector #conceptSelectorTerm | '(' expression ')' #parenthesizedTerm ; ratio : quantity ':' quantity ; literal : ('true' | 'false') #booleanLiteral | 'null' #nullLiteral | STRING #stringLiteral | NUMBER #numberLiteral | DATETIME #dateTimeLiteral | TIME #timeLiteral | quantity #quantityLiteral | ratio #ratioLiteral ; intervalSelector : // TODO: Consider this as an alternative syntax for intervals... (would need to be moved up to expression to make it work) //expression ( '..' | '*.' | '.*' | '**' ) expression; 'Interval' ('['|'(') expression ',' expression (']'|')') ; tupleSelector : 'Tuple'? '{' (':' | (tupleElementSelector (',' tupleElementSelector)*)) '}' ; tupleElementSelector : identifier ':' expression ; instanceSelector : namedTypeSpecifier '{' (':' | (instanceElementSelector (',' instanceElementSelector)*)) '}' ; instanceElementSelector : identifier ':' expression ; listSelector : ('List' ('<' typeSpecifier '>')?)? '{' (expression (',' expression)*)? '}' ; displayClause : 'display' STRING ; codeSelector : 'Code' STRING 'from' codesystemIdentifier displayClause? ; conceptSelector : 'Concept' '{' codeSelector (',' codeSelector)* '}' displayClause? ; identifier : IDENTIFIER | DELIMITEDIDENTIFIER | QUOTEDIDENTIFIER | 'all' | 'Code' | 'code' | 'Concept' | 'concept' | 'contains' | 'date' | 'display' | 'distinct' | 'end' // | 'exists' NOTE: This is excluded because including it causes a significant performance degradation in the ANTLR parser, still looking into a fix for this | 'not' | 'start' | 'time' | 'timezone' | 'version' | 'where' ; QUOTEDIDENTIFIER : '"' (ESC | .)*? '"' ; fragment ESC : '\\' ([`'"\\/fnrt] | UNICODE) // allow \`, \', \", \\, \/, \f, etc. and \uXXX ;
Document required from keyword option
STU3#218: Document required from keyword option
ANTLR
apache-2.0
cqframework/clinical_quality_language,cqframework/clinical_quality_language
fc46ac2d1908918cde6b4afe9cc9a2ebe8d887bc
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 : 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? ; concurrentlyClause_ : CONCURRENTLY? ; indexNotExistClause_ : (IF NOT EXISTS)? ; onlyClause_ : ONLY ; 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_ INDEX concurrentlyClause_ (indexNotExistClause_ indexName)? ON onlyClause_ 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? ; concurrentlyClause_ : CONCURRENTLY? ; indexNotExistClause_ : (IF NOT EXISTS)? ; onlyClause_ : ONLY? ; 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))? ;
modify onlyClause_
modify onlyClause_
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
86213b6f0701be9a346c827f2f5afe2f19e3414c
src/grammar/La.g4
src/grammar/La.g4
/* * Gramatica da linguagem LA. * * Grupo: * Arieh Cangiani Fabbro * Felipe Fantoni * Lucas Hauptmann Pereira * Lucas Oliveira David * Rafael Silveira */ grammar La; @members { infrastructure.PilhaDeTabelas pilhaDeTabelas = new infrastructure.PilhaDeTabelas(); } programa : { pilhaDeTabelas.empilhar(new infrastructure.TabelaDeSimbolos("global")); } declaracoes { infrastructure.Mensagens.addText("#include <stdio.h\n#include <stdlib.h>\n\nint main {\n"); } 'algoritmo' corpo 'fim_algoritmo' { infrastructure.Mensagens.addText("return 0\n}"); pilhaDeTabelas.desempilhar(); } ; declaracoes : (decl_local_global)* ; decl_local_global : declaracao_local | declaracao_global ; declaracao_local : 'declare' variavel | 'constante' IDENT ':' tipo_basico { // A constant has been consumed: // if it has been declared before, logs semantic error. // Otherwise, add it to the current simbol table. if(pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { infrastructure.ErrorListeners.SemanticErrorListener.VariableAlreadyExists($IDENT.line, $IDENT.getText()); } else { pilhaDeTabelas.topo().adicionarSimbolo($IDENT.getText(), "constante", $tipo_basico.nomeTipo); } } '=' valor_constante | 'tipo' IDENT ':' tipo { // A type has been consumed: // if it has been declared before, logs semantic error. // Otherwise, add it to the current simbol table. if (pilhaDeTabelas.existeSimbolo($tipo.nomeTipo.toLowerCase())) { infrastructure.ErrorListeners.SemanticErrorListener.TypeDoesntExist($IDENT.getLine(), $tipo.nomeTipo); } else { pilhaDeTabelas.topo().adicionarSimbolo($tipo.nomeTipo.toLowerCase(), "tipo", $tipo.nomeTipo.toLowerCase()); } } ; variavel : IDENT { // Stores a list of consumed identifiers List<String> declared = new ArrayList<>(); if(pilhaDeTabelas.topo().existeSimbolo($IDENT.getText().toLowerCase())) { infrastructure.ErrorListeners.SemanticErrorListener.VariableAlreadyExists($IDENT.line, $IDENT.getText()); } else { declared.add($IDENT.getText().toLowerCase()); } } dimensao (',' IDENT { // if any of these were declared already, logs a semantic error. if(pilhaDeTabelas.topo().existeSimbolo($IDENT.getText().toLowerCase()) || declared.contains($IDENT.getText().toLowerCase())) { infrastructure.ErrorListeners.SemanticErrorListener.VariableAlreadyExists($IDENT.line, $IDENT.getText()); } else { declared.add($IDENT.getText().toLowerCase()); } } dimensao)* ':' tipo { for (String current : declared) { if ($tipo.nomeTipo.equals("inteiro")) infrastructure.Mensagens.addText("int " + current + ";\n"); else if ($tipo.nomeTipo.equals("real")) infrastructure.Mensagens.addText("float " + current + ";\n"); else if ($tipo.nomeTipo.equals("literal")) infrastructure.Mensagens.addText("char " + current + ";\n"); else if ($tipo.nomeTipo.equals("logico")) infrastructure.Mensagens.addText("int " + current + ";\n"); } // Add all variables to the nearest simbol table for (String current : declared) { pilhaDeTabelas.topo().adicionarSimbolo(current, "variavel", $tipo.nomeTipo); } } ; identificador returns [String name, int line] : ponteiros_opcionais IDENT { $name = $IDENT.getText(); $line = $IDENT.getLine(); } ('.' IDENT)* dimensao outros_ident ; ponteiros_opcionais : '^'* ; outros_ident : ('.' identificador)? ; dimensao : ('[' exp_aritmetica ']' dimensao)? ; tipo returns [ String nomeTipo ] : registro { $nomeTipo = "registro"; } | tipo_estendido { $nomeTipo = $tipo_estendido.nomeTipo; } ; tipo_estendido returns [ String nomeTipo ] : ponteiros_opcionais tipo_basico_ident { $nomeTipo = $tipo_basico_ident.nomeTipo; } ; mais_ident returns [List<String> identifiers] : { $identifiers = new ArrayList<>(); } (',' identificador { $identifiers.add($identificador.name); })* ; tipo_basico returns [ String nomeTipo, int linha ] : 'literal' { $nomeTipo = "literal"; } | 'inteiro' { $nomeTipo = "inteiro"; } | 'real' { $nomeTipo = "real"; } | 'logico' { $nomeTipo = "logico"; } ; tipo_basico_ident returns [ String nomeTipo ] : tipo_basico { $nomeTipo = $tipo_basico.nomeTipo; } | IDENT { $nomeTipo = $IDENT.getText(); if (!pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { infrastructure.ErrorListeners.SemanticErrorListener.TypeDoesntExist($IDENT.line, $IDENT.getText()); } } ; valor_constante : CADEIA | NUM_INT | NUM_REAL | 'verdadeiro' | 'falso' ; registro : 'registro' variavel+ 'fim_registro' ; declaracao_global : { pilhaDeTabelas.empilhar(new infrastructure.TabelaDeSimbolos("procedimento")); } 'procedimento' IDENT '(' parametros_opcional ')' declaracoes_locais comandos 'fim_procedimento' { pilhaDeTabelas.desempilhar(); } | { pilhaDeTabelas.empilhar(new infrastructure.TabelaDeSimbolos("funcao")); } 'funcao' IDENT '(' parametros_opcional '):' tipo_estendido declaracoes_locais comandos 'fim_funcao' { pilhaDeTabelas.desempilhar(); } ; parametros_opcional : (parametro)? ; parametro : var_opcional identificador mais_ident ':' tipo_estendido (',' parametro)? ; var_opcional : 'var'? ; declaracoes_locais : (declaracao_local declaracoes_locais)? ; corpo : declaracoes_locais comandos ; comandos : (cmd comandos)? ; cmd : 'leia' '(' identificador { if (!pilhaDeTabelas.existeSimbolo($identificador.name.toLowerCase())) { infrastructure.ErrorListeners.SemanticErrorListener.VariableDoesntExist($identificador.line, $identificador.name); } } mais_ident { for (String ident : $mais_ident.identifiers) { if (!pilhaDeTabelas.existeSimbolo(ident.toLowerCase())) { infrastructure.ErrorListeners.SemanticErrorListener.VariableDoesntExist($identificador.line, ident); } } String variavel = $identificador.name; String tipo2 = pilhaDeTabelas.retornaTipo(variavel); if (tipo2.equals("inteiro")) infrastructure.Mensagens.addText("scanf(\"%d\",&"+variavel+");\n"); else if (tipo2.equals("real")) infrastructure.Mensagens.addText("scanf(\"%f\",&"+variavel+");\n"); else if (tipo2.equals("literal")) infrastructure.Mensagens.addText("scanf(\"%s\",&"+variavel+");\n"); else if (tipo2.equals("logico")) infrastructure.Mensagens.addText("scanf(\"%d\",&"+variavel+");\n"); } ')' | 'escreva' '(' expressao mais_expressao ')' | 'se' expressao 'entao' comandos senao_opcional 'fim_se' | 'caso' exp_aritmetica 'seja' selecao senao_opcional 'fim_caso' | 'para' { //Empilha (Cria) um novo escopo para o FOR pilhaDeTabelas.empilhar(new infrastructure.TabelaDeSimbolos("para")); } IDENT { // Logs semantic error if variable wasnt found in any of the simbol tables if (!pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { infrastructure.ErrorListeners.SemanticErrorListener.VariableDoesntExist($IDENT.line,$IDENT.getText()); } } '<-' exp_aritmetica 'ate' exp_aritmetica 'faca' comandos 'fim_para' { //Desempilha o escopo do FOR pilhaDeTabelas.desempilhar(); } | 'enquanto' expressao 'faca' comandos 'fim_enquanto' | 'faca' comandos 'ate' expressao | '^' IDENT { // Logs semantic error if variable wasnt found in any of the simbol tables if (!pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { infrastructure.ErrorListeners.SemanticErrorListener.VariableDoesntExist($IDENT.line,$IDENT.getText()); } } outros_ident dimensao '<-' expressao | IDENT { // Logs semantic error if variable wasnt found in any of the simbol tables if (!pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { infrastructure.ErrorListeners.SemanticErrorListener.VariableDoesntExist($IDENT.line,$IDENT.getText()); } } chamada_atribuicao | RETORNAR expressao { String escopo = pilhaDeTabelas.topo().getEscopo(); if (!escopo.equals("funcao")) { infrastructure.ErrorListeners.SemanticErrorListener.ScopeNotAllowed($RETORNAR.line); } } ; mais_expressao : (',' expressao mais_expressao)? ; senao_opcional : ('senao' comandos)? ; chamada_atribuicao : '(' argumentos_opcional ')' | outros_ident dimensao '<-' expressao ; argumentos_opcional : (expressao mais_expressao)? ; selecao : constantes ':' comandos mais_selecao ; mais_selecao : (selecao)? ; constantes : numero_intervalo mais_constantes ; mais_constantes : (',' constantes)? ; numero_intervalo : op_unario NUM_INT intervalo_opcional ; intervalo_opcional : ('..' op_unario NUM_INT)? ; op_unario : '-'? ; exp_aritmetica : termo (op_adicao termo)* ; op_multiplicacao : '*' | '/' ; op_adicao : '+' | '-' ; termo : fator (op_multiplicacao fator)* ; fator : parcela ('%' parcela)* ; parcela : op_unario parcela_unario | parcela_nao_unario ; parcela_unario : '^' IDENT { if (!pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { infrastructure.ErrorListeners.SemanticErrorListener.VariableDoesntExist($IDENT.line,$IDENT.getText()); } } outros_ident dimensao | IDENT { if (!pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { infrastructure.ErrorListeners.SemanticErrorListener.VariableDoesntExist($IDENT.line,$IDENT.getText()); } } outros_ident dimensao | IDENT { if (!pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { infrastructure.ErrorListeners.SemanticErrorListener.VariableDoesntExist($IDENT.line,$IDENT.getText()); } } '(' expressao mais_expressao ')' | NUM_INT | NUM_REAL | '(' expressao ')' ; parcela_nao_unario : '&' IDENT { if (!pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { infrastructure.ErrorListeners.SemanticErrorListener.VariableDoesntExist($IDENT.line,$IDENT.getText()); } } outros_ident dimensao | CADEIA ; op_opcional : (op_relacional exp_aritmetica)? ; op_relacional : '=' | '<>' | '>=' | '<=' | '>' | '<' ; expressao : termo_logico ('ou' termo_logico)* ; termo_logico : fator_logico ('e' fator_logico)* ; fator_logico : op_nao parcela_logica ; op_nao : ('nao')? ; parcela_logica : 'verdadeiro' | 'falso' | exp_relacional ; exp_relacional : exp_aritmetica op_opcional ; RETORNAR : 'retorne' ; IDENT : ('a'..'z' | 'A'..'Z' | '_') ('a'..'z' | 'A'..'Z' | '0'..'9' | '_')* ; CADEIA : '"' ~('\n' | '\r' | '"')* '"' ; NUM_INT : ('0'..'9')+ ; NUM_REAL : ('0'..'9')+ '.' ('0'..'9')+ ; COMENTARIO : '{' ~('\n' | '\r' | '}')* '}' {skip();} ; WS : (' ' | '\t' | '\r' | '\n') {skip();} ;
/* * Gramatica da linguagem LA. * * Grupo: * Arieh Cangiani Fabbro * Felipe Fantoni * Lucas Hauptmann Pereira * Lucas Oliveira David * Rafael Silveira */ grammar La; @members { PilhaDeTabelas pilhaDeTabelas = new PilhaDeTabelas(); } programa : { pilhaDeTabelas.empilhar(new TabelaDeSimbolos("global")); } declaracoes { Mensagens.addText("#include <stdio.h\n#include <stdlib.h>\n\nint main {\n"); } 'algoritmo' corpo 'fim_algoritmo' { Mensagens.addText("return 0\n}"); pilhaDeTabelas.desempilhar(); } ; declaracoes : (decl_local_global)* ; decl_local_global : declaracao_local | declaracao_global ; declaracao_local : 'declare' variavel | 'constante' IDENT ':' tipo_basico { // A constant has been consumed: // if it has been declared before, logs semantic error. // Otherwise, add it to the current simbol table. if(pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { SemanticErrorListener.VariableAlreadyExists($IDENT.line, $IDENT.getText()); } else { pilhaDeTabelas.topo().adicionarSimbolo($IDENT.getText(), "constante", $tipo_basico.type); } } '=' valor_constante | 'tipo' IDENT ':' tipo { // A type has been consumed: // if it has been declared before, logs semantic error. // Otherwise, add it to the current simbol table. if (pilhaDeTabelas.existeSimbolo($tipo.type.toLowerCase())) { SemanticErrorListener.TypeDoesntExist($IDENT.getLine(), $tipo.type); } else { pilhaDeTabelas.topo().adicionarSimbolo($tipo.type.toLowerCase(), "tipo", $tipo.type.toLowerCase()); } } ; variavel : IDENT { // Stores a list of consumed identifiers List<String> declared = new ArrayList<>(); if(pilhaDeTabelas.topo().existeSimbolo($IDENT.getText().toLowerCase())) { SemanticErrorListener.VariableAlreadyExists($IDENT.line, $IDENT.getText()); } else { declared.add($IDENT.getText().toLowerCase()); } } dimensao (',' IDENT { // if any of these were declared already, logs a semantic error. if(pilhaDeTabelas.topo().existeSimbolo($IDENT.getText().toLowerCase()) || declared.contains($IDENT.getText().toLowerCase())) { SemanticErrorListener.VariableAlreadyExists($IDENT.line, $IDENT.getText()); } else { declared.add($IDENT.getText().toLowerCase()); } } dimensao)* ':' tipo { for (String current : declared) { if ($tipo.type == null) { continue; } else if ($tipo.type.equals("inteiro")) Mensagens.addText("int " + current + ";\n"); else if ($tipo.type.equals("real")) Mensagens.addText("float " + current + ";\n"); else if ($tipo.type.equals("literal")) Mensagens.addText("char " + current + ";\n"); else if ($tipo.type.equals("logico")) Mensagens.addText("int " + current + ";\n"); } // Add all variables to the nearest simbol table for (String current : declared) { pilhaDeTabelas.topo().adicionarSimbolo(current, "variavel", $tipo.type); } } ; identificador returns [String name, int line] : ponteiros_opcionais IDENT { $name = $IDENT.getText(); $line = $IDENT.getLine(); } ('.' IDENT)* dimensao outros_ident ; ponteiros_opcionais : '^'* ; outros_ident : ('.' identificador)? ; dimensao : ('[' exp_aritmetica ']' dimensao)? ; tipo returns [ String type ] : registro { $type = "registro"; } | tipo_estendido { $type = $tipo_estendido.type; } ; tipo_estendido returns [ String type ] : ponteiros_opcionais tipo_basico_ident { $type = $tipo_basico_ident.type; } ; mais_ident returns [List<String> identifiers] : { $identifiers = new ArrayList<>(); } (',' identificador { $identifiers.add($identificador.name); })* ; tipo_basico returns [ String type, int linha ] : 'literal' { $type = "literal"; } | 'inteiro' { $type = "inteiro"; } | 'real' { $type = "real"; } | 'logico' { $type = "logico"; } ; tipo_basico_ident returns [ String type ] : tipo_basico { $type = $tipo_basico.type; } | IDENT { $type = $IDENT.getText(); if (!pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { SemanticErrorListener.TypeDoesntExist($IDENT.line, $IDENT.getText()); } } ; valor_constante : CADEIA | NUM_INT | NUM_REAL | 'verdadeiro' | 'falso' ; registro : 'registro' variavel+ 'fim_registro' ; declaracao_global : { pilhaDeTabelas.empilhar(new TabelaDeSimbolos("procedimento")); } 'procedimento' IDENT '(' parametros_opcional ')' declaracoes_locais comandos 'fim_procedimento' { pilhaDeTabelas.desempilhar(); } | { pilhaDeTabelas.empilhar(new TabelaDeSimbolos("funcao")); } 'funcao' IDENT '(' parametros_opcional '):' tipo_estendido declaracoes_locais comandos 'fim_funcao' { pilhaDeTabelas.desempilhar(); } ; parametros_opcional : (parametro)? ; parametro : var_opcional identificador mais_ident ':' tipo_estendido (',' parametro)? ; var_opcional : 'var'? ; declaracoes_locais : (declaracao_local declaracoes_locais)? ; corpo : declaracoes_locais comandos ; comandos : (cmd comandos)? ; cmd : 'leia' '(' identificador { if (!pilhaDeTabelas.existeSimbolo($identificador.name.toLowerCase())) { SemanticErrorListener.VariableDoesntExist($identificador.line, $identificador.name); } } mais_ident { for (String ident : $mais_ident.identifiers) { if (!pilhaDeTabelas.existeSimbolo(ident.toLowerCase())) { SemanticErrorListener.VariableDoesntExist($identificador.line, ident); } } String variavel = $identificador.name; String tipo2 = pilhaDeTabelas.retornaTipo(variavel); if (tipo2.equals("inteiro")) Mensagens.addText("scanf(\"%d\",&"+variavel+");\n"); else if (tipo2.equals("real")) Mensagens.addText("scanf(\"%f\",&"+variavel+");\n"); else if (tipo2.equals("literal")) Mensagens.addText("scanf(\"%s\",&"+variavel+");\n"); else if (tipo2.equals("logico")) Mensagens.addText("scanf(\"%d\",&"+variavel+");\n"); } ')' | 'escreva' '(' expressao mais_expressao ')' | 'se' expressao 'entao' comandos senao_opcional 'fim_se' | 'caso' exp_aritmetica 'seja' selecao senao_opcional 'fim_caso' | 'para' { //Empilha (Cria) um novo escopo para o FOR pilhaDeTabelas.empilhar(new TabelaDeSimbolos("para")); } IDENT { // Logs semantic error if variable wasnt found in any of the simbol tables if (!pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { SemanticErrorListener.VariableDoesntExist($IDENT.line,$IDENT.getText()); } } '<-' exp_aritmetica 'ate' exp_aritmetica 'faca' comandos 'fim_para' { //Desempilha o escopo do FOR pilhaDeTabelas.desempilhar(); } | 'enquanto' expressao 'faca' comandos 'fim_enquanto' | 'faca' comandos 'ate' expressao | '^' IDENT { // Logs semantic error if variable wasnt found in any of the simbol tables if (!pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { SemanticErrorListener.VariableDoesntExist($IDENT.line,$IDENT.getText()); } } outros_ident dimensao '<-' expressao | IDENT { // Logs semantic error if variable wasnt found in any of the simbol tables if (!pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { SemanticErrorListener.VariableDoesntExist($IDENT.line,$IDENT.getText()); } } chamada_atribuicao | RETORNAR expressao { String escopo = pilhaDeTabelas.topo().getEscopo(); if (!escopo.equals("funcao")) { SemanticErrorListener.ScopeNotAllowed($RETORNAR.line); } } ; mais_expressao : (',' expressao mais_expressao)? ; senao_opcional : ('senao' comandos)? ; chamada_atribuicao : '(' argumentos_opcional ')' | outros_ident dimensao '<-' expressao ; argumentos_opcional : (expressao mais_expressao)? ; selecao : constantes ':' comandos mais_selecao ; mais_selecao : (selecao)? ; constantes : numero_intervalo mais_constantes ; mais_constantes : (',' constantes)? ; numero_intervalo : op_unario NUM_INT intervalo_opcional ; intervalo_opcional : ('..' op_unario NUM_INT)? ; op_unario : '-'? ; exp_aritmetica : termo (op_adicao termo)* ; op_multiplicacao : '*' | '/' ; op_adicao : '+' | '-' ; termo : fator (op_multiplicacao fator)* ; fator : parcela ('%' parcela)* ; parcela : op_unario parcela_unario | parcela_nao_unario ; parcela_unario : '^' IDENT { if (!pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { SemanticErrorListener.VariableDoesntExist($IDENT.line,$IDENT.getText()); } } outros_ident dimensao | IDENT { if (!pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { SemanticErrorListener.VariableDoesntExist($IDENT.line,$IDENT.getText()); } } outros_ident dimensao | IDENT { if (!pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { SemanticErrorListener.VariableDoesntExist($IDENT.line,$IDENT.getText()); } } '(' expressao mais_expressao ')' | NUM_INT | NUM_REAL | '(' expressao ')' ; parcela_nao_unario : '&' IDENT { if (!pilhaDeTabelas.existeSimbolo($IDENT.getText().toLowerCase())) { SemanticErrorListener.VariableDoesntExist($IDENT.line,$IDENT.getText()); } } outros_ident dimensao | CADEIA ; op_opcional : (op_relacional exp_aritmetica)? ; op_relacional : '=' | '<>' | '>=' | '<=' | '>' | '<' ; expressao : termo_logico ('ou' termo_logico)* ; termo_logico : fator_logico ('e' fator_logico)* ; fator_logico : op_nao parcela_logica ; op_nao : ('nao')? ; parcela_logica : 'verdadeiro' | 'falso' | exp_relacional ; exp_relacional : exp_aritmetica op_opcional ; RETORNAR : 'retorne' ; IDENT : ('a'..'z' | 'A'..'Z' | '_') ('a'..'z' | 'A'..'Z' | '0'..'9' | '_')* ; CADEIA : '"' ~('\n' | '\r' | '"')* '"' ; NUM_INT : ('0'..'9')+ ; NUM_REAL : ('0'..'9')+ '.' ('0'..'9')+ ; COMENTARIO : '{' ~('\n' | '\r' | '}')* '}' {skip();} ; WS : (' ' | '\t' | '\r' | '\n') {skip();} ;
Fix semantic error thrown
Fix semantic error thrown
ANTLR
mit
lucasdavid/Compilers-2-assignment-2,lucasdavid/Compilers-2-assignment-2,lucasdavid/Compilers-2-assignment-2,lucasdavid/Compilers-2-assignment-2,lucasdavid/Compilers-2-assignment-2
2662f2abd4518fe0086bd324cee1fb7baba4bbfc
shardingsphere-sql-parser/shardingsphere-sql-parser-dialect/shardingsphere-sql-parser-postgresql/src/main/antlr4/imports/postgresql/DALStatement.g4
shardingsphere-sql-parser/shardingsphere-sql-parser-dialect/shardingsphere-sql-parser-postgresql/src/main/antlr4/imports/postgresql/DALStatement.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 DALStatement; import Symbol, Keyword, PostgreSQLKeyword, Literals, BaseRule, DMLStatement, DDLStatement; show : SHOW (varName | TIME ZONE | TRANSACTION ISOLATION LEVEL | SESSION AUTHORIZATION | ALL) ; set : SET runtimeScope_? (timeZoneClause_ | configurationParameterClause | varName FROM CURRENT | TIME ZONE zoneValue | CATALOG STRING_ | SCHEMA STRING_ | NAMES encoding? | ROLE nonReservedWordOrSconst | SESSION AUTHORIZATION nonReservedWordOrSconst | SESSION AUTHORIZATION DEFAULT | XML OPTION documentOrContent) ; runtimeScope_ : SESSION | LOCAL ; timeZoneClause_ : TIME ZONE (numberLiterals | LOCAL | DEFAULT) ; configurationParameterClause : identifier (TO | EQ_) (identifier | STRING_ | DEFAULT) ; resetParameter : RESET (ALL | identifier) ; explain : EXPLAIN (analyzeKeyword VERBOSE? | VERBOSE | LP_ explainOptionList RP_)? explainableStmt ; explainableStmt : select | insert | update | delete | declare | execute | createMaterializedView | refreshMatViewStmt ; explainOptionList : explainOptionElem (COMMA_ explainOptionElem)* ; explainOptionElem : explainOptionName explainOptionArg? ; explainOptionArg : booleanOrString | numericOnly ; explainOptionName : nonReservedWord | analyzeKeyword ; analyzeKeyword : ANALYZE | ANALYSE ; setConstraints : SET CONSTRAINTS constraintsSetList constraintsSetMode ; constraintsSetMode : DEFERRED | IMMEDIATE ; constraintsSetList : ALL | qualifiedNameList ; analyze : analyzeKeyword (VERBOSE? | LP_ vacAnalyzeOptionList RP_) vacuumRelationList? ; vacuumRelationList : vacuumRelation (COMMA_ vacuumRelation)* ; vacuumRelation : qualifiedName optNameList ; vacAnalyzeOptionList : vacAnalyzeOptionElem (COMMA_ vacAnalyzeOptionElem)* ; vacAnalyzeOptionElem : vacAnalyzeOptionName vacAnalyzeOptionArg? ; vacAnalyzeOptionArg : booleanOrString | numericOnly ; vacAnalyzeOptionName : nonReservedWord | analyzeKeyword ; load : LOAD fileName ;
/* * 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 DALStatement; import Symbol, Keyword, PostgreSQLKeyword, Literals, BaseRule, DMLStatement, DDLStatement; show : SHOW (varName | TIME ZONE | TRANSACTION ISOLATION LEVEL | SESSION AUTHORIZATION | ALL) ; set : SET runtimeScope_? (timeZoneClause_ | configurationParameterClause | varName FROM CURRENT | TIME ZONE zoneValue | CATALOG STRING_ | SCHEMA STRING_ | NAMES encoding? | ROLE nonReservedWordOrSconst | SESSION AUTHORIZATION nonReservedWordOrSconst | SESSION AUTHORIZATION DEFAULT | XML OPTION documentOrContent) ; runtimeScope_ : SESSION | LOCAL ; timeZoneClause_ : TIME ZONE (numberLiterals | LOCAL | DEFAULT) ; configurationParameterClause : identifier (TO | EQ_) (identifier | STRING_ | DEFAULT) ; resetParameter : RESET (ALL | identifier) ; explain : EXPLAIN (analyzeKeyword VERBOSE? | VERBOSE | LP_ explainOptionList RP_)? explainableStmt ; explainableStmt : select | insert | update | delete | declare | execute | createMaterializedView | refreshMatViewStmt ; explainOptionList : explainOptionElem (COMMA_ explainOptionElem)* ; explainOptionElem : explainOptionName explainOptionArg? ; explainOptionArg : booleanOrString | numericOnly ; explainOptionName : nonReservedWord | analyzeKeyword ; analyzeKeyword : ANALYZE | ANALYSE ; setConstraints : SET CONSTRAINTS constraintsSetList constraintsSetMode ; constraintsSetMode : DEFERRED | IMMEDIATE ; constraintsSetList : ALL | qualifiedNameList ; analyze : analyzeKeyword (VERBOSE? | LP_ vacAnalyzeOptionList RP_) vacuumRelationList? ; vacuumRelationList : vacuumRelation (COMMA_ vacuumRelation)* ; vacuumRelation : qualifiedName optNameList ; vacAnalyzeOptionList : vacAnalyzeOptionElem (COMMA_ vacAnalyzeOptionElem)* ; vacAnalyzeOptionElem : vacAnalyzeOptionName vacAnalyzeOptionArg? ; vacAnalyzeOptionArg : booleanOrString | numericOnly ; vacAnalyzeOptionName : nonReservedWord | analyzeKeyword ; load : LOAD fileName ;
add new line
add new line
ANTLR
apache-2.0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
2c7b657272822e2fc4b7a45112b6572ba6f2207d
clu/clu.g4
clu/clu.g4
/* BSD License Copyright (c) 2018, 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 clu; module : equate* (procedure | iterator | cluster) ; procedure : idn '=' 'proc' parms? args returnz? signals? where? routine_body 'end' idn ; iterator : idn '=' 'iter' parms? args yields? signals? where? routine_body 'end' idn ; cluster : idn '=' 'cluster' parms? 'is' idn_list where? cluster_body 'end' idn ; parms : param (',' param)* ; param : idn_list ':' ('type' | type_spec) ; args : '(' decl_list? ')' ; decl_list : decl (',' decl)* ; decl : idn_list ':' type_spec ; returnz : 'returns' '(' type_spec_list ')' ; yields : 'yields' '(' type_spec_list ')' ; signals : 'signals' '(' exception (',' exception)* ')' ; exception : name type_spec_list? ; type_spec_list : type_spec (',' type_spec)* ; where : 'where' restriction (',' restriction)* ; restriction : idn ('has' oper_decl_list | 'in' type_set) ; type_set : (idn | (idn 'has' oper_decl_list equate*))* | idn ; oper_decl_list : oper_decl (',' oper_decl)* ; oper_decl : op_name_list ':' type_spec ; op_name_list : op_name (',' op_name)* ; op_name : name '[' constant_list? ']' ; constant_list : constant (',' constant)* ; constant : expression | type_spec ; routine_body : equate* own_var* statement* ; cluster_body : equate* 'rep' '=' type_spec equate* own_var* 'routine' routine* ; routine : procedure | iterator ; equate : idn '=' (constant | type_set) ; own_var : 'own' ((decl) | (idn ':' type_spec ':=' expression) | (decl_list ':=' invocation)) ; type_spec : 'null' | 'bool' | 'int' | 'real' | 'char' | 'string' | 'any' | 'rep' | 'cvt' | ('array' | 'sequence' type_spec?) | ('record' | 'struct' | 'oneof' | 'variant') field_spec_list? | ('proctype' | 'itertype') field_spec_list? returnz? signals? | (idn (constant_list)?) ; field_spec_list : (field_spec (',' field_spec)*) ; field_spec : name_list ':' type_spec ; statement : decl | idn ':' type_spec ':=' expression | decl_list ':=' invocation | idn_list ':=' (invocation | expression_list) | primary '.' name ':=' expression | invocation | 'while' expression 'do' body 'end' | 'for' (decl_list | idn_list)? 'in' invocation 'do' body 'end' | ('if' expression 'then' body ('elseif' expression 'then' body)* ('else' body)? 'end') | ('tagcase' expression tag_arm* ('others' ':' body)? 'end') | (('return' | 'yield') (expression_list)?) | ('signal' name (expression_list)?) | ('exit' name (expression_list)?) | 'break' | ('begin' body 'end') | statement (('resignal' name_list) | ('except' when_handler* others_handler? 'end')) ; tag_arm : 'tag' name_list ('(' idn ':' type_spec ')')? ':' body ; when_handler : 'when' name_list ('(' '*' ')' | (decl_list)?) ':' body ; others_handler : 'others' ('(' idn ':' type_spec ')')? ':' body ; body : equate* statement* ; expression_list : expression (',' expression)* ; expression : primary | '(' 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 '~<=' expression | expression '~=' expression | expression '~>=' expression | expression '~>' expression | expression '&' expression | expression 'cand' expression | expression '|' expression | expression 'cor' expression ; primary : 'nil' | 'true' | 'false' | int_literal | real_literal | string_literal | idn (constant_list)? | primary '.' name | primary expression | primary '(' expression_list ')' | type_spec '$' (field_list | ('[' (((expression ':')? expression_list) | constant_list) ']')) | ('force' type_spec?) | (('up' | 'down') '(' expression ')') ; invocation : primary '(' expression_list ')' ; field_list : field (',' field)* ; field : name_list ':' expression ; idn_list : idn (',' idn)* ; idn : STRING ; name_list : name (',' name)* ; name : STRING ; int_literal : INT ; real_literal : FLOAT ; string_literal : STRINGLITERAL ; STRINGLITERAL : '"' ~ '"'* '"' ; STRING : [a-zA-Z] [a-zA-Z0-9_]* ; INT : [0-9]+ ; FLOAT : [0-9]+ '.' [0-9]* ; COMMENT : ';' ~ [\r\n]* -> skip ; WS : [ \t\r\n] -> skip ;
/* BSD License Copyright (c) 2018, 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 clu; module : equate* (procedure | iterator | cluster) ; procedure : idn '=' 'proc' parms? args returnz? signals? where? routine_body 'end' idn ; iterator : idn '=' 'iter' parms? args yields? signals? where? routine_body 'end' idn ; cluster : idn '=' 'cluster' parms? 'is' idn_list where? cluster_body 'end' idn ; parms : param (',' param)* ; param : idn_list ':' ('type' | type_spec) ; args : '(' decl_list? ')' ; decl_list : decl (',' decl)* ; decl : idn_list ':' type_spec ; returnz : 'returns' '(' type_spec_list ')' ; yields : 'yields' '(' type_spec_list ')' ; signals : 'signals' '(' exception (',' exception)* ')' ; exception : name type_spec_list? ; type_spec_list : type_spec (',' type_spec)* ; where : 'where' restriction (',' restriction)* ; restriction : idn ('has' oper_decl_list | 'in' type_set) ; type_set : (idn | (idn 'has' oper_decl_list equate*))* | idn ; oper_decl_list : oper_decl (',' oper_decl)* ; oper_decl : op_name_list ':' type_spec ; op_name_list : op_name (',' op_name)* ; op_name : name '[' constant_list? ']' ; constant_list : constant (',' constant)* ; constant : expression | type_spec ; routine_body : equate* own_var* statement* ; cluster_body : equate* 'rep' '=' type_spec equate* own_var* 'routine' routine* ; routine : procedure | iterator ; equate : idn '=' (constant | type_set) ; own_var : 'own' ((decl) | (idn ':' type_spec ':=' expression) | (decl_list ':=' invocation)) ; type_spec : 'null' | 'bool' | 'int' | 'real' | 'char' | 'string' | 'any' | 'rep' | 'cvt' | ('array' | 'sequence' type_spec?) | ('record' | 'struct' | 'oneof' | 'variant') field_spec_list? | ('proctype' | 'itertype') field_spec_list? returnz? signals? | (idn (constant_list)?) ; field_spec_list : (field_spec (',' field_spec)*) ; field_spec : name_list ':' type_spec ; statement : decl | idn ':' type_spec ':=' expression | decl_list ':=' invocation | idn_list ':=' (invocation | expression_list) | primary '.' name ':=' expression | invocation | 'while' expression 'do' body 'end' | 'for' (decl_list | idn_list)? 'in' invocation 'do' body 'end' | ('if' expression 'then' body ('elseif' expression 'then' body)* ('else' body)? 'end') | ('tagcase' expression tag_arm* ('others' ':' body)? 'end') | (('return' | 'yield') (expression_list)?) | ('signal' name (expression_list)?) | ('exit' name (expression_list)?) | 'break' | ('begin' body 'end') | statement (('resignal' name_list) | ('except' when_handler* others_handler? 'end')) ; tag_arm : 'tag' name_list ('(' idn ':' type_spec ')')? ':' body ; when_handler : 'when' name_list ('(' '*' ')' | (decl_list)?) ':' body ; others_handler : 'others' ('(' idn ':' type_spec ')')? ':' body ; body : equate* statement* ; expression_list : expression (',' expression)* ; expression : primary | '(' 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 '~<=' expression | expression '~=' expression | expression '~>=' expression | expression '~>' expression | expression '&' expression | expression 'cand' expression | expression '|' expression | expression 'cor' expression ; primary : 'nil' | 'true' | 'false' | int_literal | real_literal | string_literal | idn (constant_list)? | primary '.' name | primary expression | primary '(' expression_list ')' | type_spec '$' (field_list | ('[' (((expression ':')? expression_list) | constant_list) ']')) | ('force' type_spec?) | (('up' | 'down') '(' expression ')') ; invocation : primary '(' expression_list ')' ; field_list : field (',' field)* ; field : name_list ':' expression ; idn_list : idn (',' idn)* ; idn : STRING ; name_list : name (',' name)* ; name : STRING ; int_literal : INT ; real_literal : FLOAT ; string_literal : STRINGLITERAL ; STRINGLITERAL : '"' ~ '"'* '"' ; STRING : [a-zA-Z] [a-zA-Z0-9_]* ; INT : [0-9]+ ; FLOAT : [0-9]+ '.' [0-9]* ; COMMENT : '%' ~ [\r\n]* -> skip ; WS : [ \t\r\n] -> skip ;
comment is % not ;
comment is % not ;
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
5abb252da4d87c2242bab2435e26d199c145cd53
core/src/main/antlr4/org/jdbi/v3/core/internal/lexer/DefineStatementLexer.g4
core/src/main/antlr4/org/jdbi/v3/core/internal/lexer/DefineStatementLexer.g4
/* * 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. */ lexer grammar DefineStatementLexer; fragment ESCAPE_IN_QUOTE: '\\' ['\\] ; fragment DOUBLE_QUOTE: '"' ; fragment LT: '<' ; fragment GT: '>' ; fragment NAME: JAVA_LETTER | [0-9]; /* Lovingly lifted from https://github.com/antlr/grammars-v4/blob/master/java/JavaLexer.g4 */ fragment JAVA_LETTER : [a-zA-Z$_] | ~[\u0000-\u007F\uD800-\uDBFF] | [\uD800-\uDBFF] [\uDC00-\uDFFF]; COMMENT: '/*' .*? '*/' | '--' ~('\r' | '\n')* | '//' ~('\r' | '\n')*; QUOTED_TEXT: '\'' (~['\\\r\n] | ESCAPE_IN_QUOTE)* '\''; DOUBLE_QUOTED_TEXT: DOUBLE_QUOTE (~'"')+ DOUBLE_QUOTE; ESCAPED_TEXT : '\\' . ; DEFINE: LT (NAME)+ GT; LITERAL: .;
/* * 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. */ lexer grammar DefineStatementLexer; fragment ESCAPE_IN_QUOTE: '\\' ['\\] ; fragment DOUBLE_QUOTE: '"' ; fragment LT: '<' ; fragment GT: '>' ; fragment NAME: JAVA_LETTER | [0-9]; /* Lovingly lifted from https://github.com/antlr/grammars-v4/blob/master/java/java/JavaLexer.g4 */ fragment JAVA_LETTER : [a-zA-Z$_] | ~[\u0000-\u007F\uD800-\uDBFF] | [\uD800-\uDBFF] [\uDC00-\uDFFF]; COMMENT: '/*' .*? '*/' | '--' ~('\r' | '\n')* | '//' ~('\r' | '\n')*; QUOTED_TEXT: '\'' (~['\\\r\n] | ESCAPE_IN_QUOTE)* '\''; DOUBLE_QUOTED_TEXT: DOUBLE_QUOTE (~'"')+ DOUBLE_QUOTE; ESCAPED_TEXT : '\\' . ; DEFINE: LT (NAME)+ GT; LITERAL: .;
Fix outdated lexer url
Fix outdated lexer url
ANTLR
apache-2.0
hgschmie/jdbi,jdbi/jdbi,hgschmie/jdbi,hgschmie/jdbi,jdbi/jdbi,jdbi/jdbi
28905d787ec3713e6d29a5b59146e81f3b8e58c7
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 tokAtom : TokAtom ; TokAtom : [a-z@][0-9a-zA-Z_@]* | '\'' ( '\\' (~'\\'|'\\') | ~[\\'] )* '\'' ; tokVar : TokVar ; TokVar : [A-Z_][0-9a-zA-Z_]* ; tokFloat : TokFloat ; TokFloat : '-'? [0-9]+ '.' [0-9]+ ([Ee] [+-]? [0-9]+)? ; tokInteger : TokInteger ; TokInteger : '-'? [0-9]+ ('#' [0-9a-zA-Z]+)? ; tokChar : TokChar ; TokChar : '$' ('\\'? ~[\r\n] | '\\' [0-9] [0-9] [0-9]) ; tokString : TokString ; TokString : '"' ( '\\' (~'\\'|'\\') | ~[\\"] )* '"' ; // antlr4 would not accept spec as an Atom otherwise. AttrName : '-' ('spec' | 'callback') ; Comment : '%' ~[\r\n]* '\r'? '\n' -> skip ; WS : [ \t\r\n]+ -> 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 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 ;
Update Erlang lexer rule
Update Erlang lexer rule
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
df81c3f6c6036f8771ededffa73512793cdf3015
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; } /*---------------------------------------------------------------------------- * 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] ; index_list returns [List<String> indexes] @init{ $indexes = new ArrayList(); } : i=IDENTIFIER { $indexes.add($i.text); } | i=IDENTIFIER { $indexes.add($i.text); } COMMA index_list ; directive[ClawLanguage language]: LFUSION { $language.setDirective(ClawDirective.LOOP_FUSION); } group_option | LINTERCHANGE { $language.setDirective(ClawDirective.LOOP_INTERCHANGE); } '(' index_list ')' | LEXTRACT { $language.setDirective(ClawDirective.LOOP_EXTRACT); } | REMOVE { $language.setDirective(ClawDirective.REMOVE); } | END REMOVE { $language.setDirective(ClawDirective.END_REMOVE); } ; group_option: GROUP '(' IDENTIFIER ')' | /* empty */ ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // Directives LFUSION : 'loop-fusion'; LINTERCHANGE : 'loop-interchange'; LEXTRACT : 'loop-extract'; REMOVE : 'remove'; END : 'end'; // Options GROUP : 'group'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9]*; COMMA : ','; // 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; } /*---------------------------------------------------------------------------- * 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] ; index_list returns [List<String> indexes] @init{ $indexes = new ArrayList(); } : i=IDENTIFIER { $indexes.add($i.text); } | i=IDENTIFIER { $indexes.add($i.text); } COMMA index_list ; directive[ClawLanguage language]: LFUSION { $language.setDirective(ClawDirective.LOOP_FUSION); } group_option | LINTERCHANGE { $language.setDirective(ClawDirective.LOOP_INTERCHANGE); } '(' index_list ')' | LEXTRACT { $language.setDirective(ClawDirective.LOOP_EXTRACT); } | REMOVE { $language.setDirective(ClawDirective.REMOVE); } | END REMOVE { $language.setDirective(ClawDirective.END_REMOVE); } ; group_option: GROUP '(' IDENTIFIER ')' | /* empty */ ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // Directives LFUSION : 'loop-fusion'; LINTERCHANGE : 'loop-interchange'; LEXTRACT : 'loop-extract'; REMOVE : 'remove'; END : 'end'; // Options GROUP : 'group'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9]* ; COMMA : ',' ; NUMBER : (DIGIT)+ ; fragment DIGIT : '0'..'9' ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
Add lexer rules for digit and numbers
Add lexer rules for digit and numbers
ANTLR
bsd-2-clause
clementval/claw-compiler,clementval/claw-compiler
ba5fadc4712fbc2316a4be54683e1e9cf1e24a4c
projects/batfish/src/org/batfish/grammar/flatjuniper/FlatJuniper_policy_options.g4
projects/batfish/src/org/batfish/grammar/flatjuniper/FlatJuniper_policy_options.g4
parser grammar FlatJuniper_policy_options; import FlatJuniper_common; options { tokenVocab = FlatJuniperLexer; } base_community_regex : ~( COLON | NEWLINE )+ COLON ~( COLON | NEWLINE )+ ; colort_apply_groups : s_apply_groups ; colort_color : color = DEC ; community_regex : ( base_community_regex PIPE )* base_community_regex ; ct_members : MEMBERS ( extended_community | named_community // community_regex intentionally on bottom | community_regex ) ; fromt_area : AREA area = IP_ADDRESS ; fromt_as_path : AS_PATH name = variable ; fromt_color : COLOR color = DEC ; fromt_community : COMMUNITY name = variable ; fromt_family : FAMILY ( INET | INET6 ) ; fromt_interface : INTERFACE id = interface_id ; fromt_neighbor : NEIGHBOR ( IP_ADDRESS | IPV6_ADDRESS ) ; fromt_null : PREFIX_LIST_FILTER s_null_filler ; fromt_policy : POLICY name = variable ; fromt_prefix_list : PREFIX_LIST name = variable ; fromt_protocol : PROTOCOL protocol = routing_protocol ; fromt_route_filter : ROUTE_FILTER ( IP_PREFIX | IPV6_PREFIX ) fromt_route_filter_tail then = fromt_route_filter_then? ; fromt_route_filter_tail : rft_exact | rft_longer | rft_orlonger | rft_prefix_length_range | rft_through | rft_upto ; fromt_route_filter_then : tt_then_tail ; fromt_route_type : ROUTE_TYPE EXTERNAL ; fromt_source_address_filter : // reference to router filter tail is intentional SOURCE_ADDRESS_FILTER ( IP_PREFIX | IPV6_PREFIX ) fromt_route_filter_tail ; fromt_tag : TAG DEC ; metric_expression : ( METRIC | METRIC2 ) MULTIPLIER multiplier = DEC ( OFFSET offset = DEC )? ; named_community : NO_ADVERTISE ; plt_apply_path : APPLY_PATH path = DOUBLE_QUOTED_STRING ; plt_network : network = IP_PREFIX ; plt_network6 : network = IPV6_PREFIX ; pot_apply_groups : s_apply_groups ; pot_as_path : AS_PATH name = variable pot_as_path_tail ; pot_as_path_tail : regex = AS_PATH_REGEX ; pot_community : COMMUNITY name = variable pot_community_tail ; pot_community_tail : ct_members ; pot_policy_statement : POLICY_STATEMENT ( WILDCARD | name = variable ) pot_policy_statement_tail ; pot_policy_statement_tail : pst_term | pst_term_tail ; pot_prefix_list : PREFIX_LIST name = variable pot_prefix_list_tail ; pot_prefix_list_tail : // intentional blank | plt_apply_path | plt_network | plt_network6 ; pst_term : TERM ( WILDCARD | name = variable ) pst_term_tail ; pst_term_tail : tt_apply_groups | tt_from | tt_then ; rft_exact : EXACT ; rft_longer : LONGER ; rft_orlonger : ORLONGER ; rft_prefix_length_range : PREFIX_LENGTH_RANGE FORWARD_SLASH low = DEC DASH FORWARD_SLASH high = DEC ; rft_through : THROUGH ( IP_PREFIX | IPV6_PREFIX ) ; rft_upto : UPTO FORWARD_SLASH high = DEC ; s_policy_options : POLICY_OPTIONS s_policy_options_tail ; s_policy_options_tail : pot_apply_groups | pot_as_path | pot_community | pot_policy_statement | pot_prefix_list ; tht_accept : ACCEPT ; tht_as_path_expand : AS_PATH_EXPAND LAST_AS COUNT DEC ; tht_as_path_prepend : AS_PATH_PREPEND ( DEC | DOUBLE_QUOTED_STRING ) ; tht_color : COLOR tht_color_tail ; tht_color_tail : colort_apply_groups | colort_color ; tht_community_add : COMMUNITY ADD name = variable ; tht_community_delete : COMMUNITY DELETE name = variable ; tht_community_set : COMMUNITY SET name = variable ; tht_cos_next_hop_map : COS_NEXT_HOP_MAP name = variable ; tht_default_action_accept : DEFAULT_ACTION ACCEPT ; tht_default_action_reject : DEFAULT_ACTION REJECT ; tht_external : EXTERNAL TYPE DEC ; tht_install_nexthop : INSTALL_NEXTHOP s_null_filler ; tht_local_preference : LOCAL_PREFERENCE localpref = DEC ; tht_metric : METRIC metric = DEC ; tht_metric2 : METRIC2 metric2 = DEC ; tht_metric_expression : METRIC EXPRESSION metric_expression ; tht_metric_igp : METRIC IGP ; tht_metric2_expression : METRIC2 EXPRESSION metric_expression ; tht_next_policy : NEXT POLICY ; tht_next_term : NEXT TERM ; tht_next_hop : NEXT_HOP ( IP_ADDRESS | IPV6_ADDRESS | PEER_ADDRESS | SELF ) ; tht_null : LOAD_BALANCE s_null_filler ; tht_origin : ORIGIN IGP ; tht_reject : REJECT ; tht_tag : TAG DEC ; tt_apply_groups : s_apply_groups ; tt_from : FROM tt_from_tail ; tt_from_tail : fromt_area | fromt_as_path | fromt_color | fromt_community | fromt_family | fromt_interface | fromt_neighbor | fromt_null | fromt_policy | fromt_prefix_list | fromt_protocol | fromt_route_filter | fromt_route_type | fromt_source_address_filter | fromt_tag ; tt_then : THEN tt_then_tail ; tt_then_tail : tht_accept | tht_as_path_expand | tht_as_path_prepend | tht_color | tht_community_add | tht_community_delete | tht_community_set | tht_cos_next_hop_map | tht_default_action_accept | tht_default_action_reject | tht_external | tht_install_nexthop | tht_local_preference | tht_metric | tht_metric_expression | tht_metric_igp | tht_metric2 | tht_metric2_expression | tht_next_hop | tht_next_policy | tht_next_term | tht_null | tht_origin | tht_reject | tht_tag ;
parser grammar FlatJuniper_policy_options; import FlatJuniper_common; options { tokenVocab = FlatJuniperLexer; } base_community_regex : ~( COLON | NEWLINE )+ COLON ~( COLON | NEWLINE )+ ; colort_apply_groups : s_apply_groups ; colort_color : color = DEC ; community_regex : ( base_community_regex PIPE )* base_community_regex ; ct_members : MEMBERS ( extended_community | named_community // community_regex intentionally on bottom | community_regex ) ; fromt_area : AREA area = IP_ADDRESS ; fromt_as_path : AS_PATH name = variable ; fromt_color : COLOR color = DEC ; fromt_community : COMMUNITY name = variable ; fromt_family : FAMILY ( INET | INET6 ) ; fromt_interface : INTERFACE id = interface_id ; fromt_neighbor : NEIGHBOR ( IP_ADDRESS | IPV6_ADDRESS ) ; fromt_null : PREFIX_LIST_FILTER s_null_filler ; fromt_policy : POLICY name = variable ; fromt_prefix_list : PREFIX_LIST name = variable ; fromt_protocol : PROTOCOL protocol = routing_protocol ; fromt_route_filter : ROUTE_FILTER ( IP_PREFIX | IPV6_PREFIX ) fromt_route_filter_tail then = fromt_route_filter_then? ; fromt_route_filter_tail : rft_exact | rft_longer | rft_orlonger | rft_prefix_length_range | rft_through | rft_upto ; fromt_route_filter_then : tt_then_tail ; fromt_route_type : ROUTE_TYPE EXTERNAL ; fromt_source_address_filter : // reference to router filter tail is intentional SOURCE_ADDRESS_FILTER ( IP_PREFIX | IPV6_PREFIX ) fromt_route_filter_tail ; fromt_tag : TAG DEC ; metric_expression : ( METRIC | METRIC2 ) MULTIPLIER multiplier = DEC ( OFFSET offset = DEC )? ; named_community : NO_ADVERTISE ; plt_apply_path : APPLY_PATH path = DOUBLE_QUOTED_STRING ; plt_ip6 : ip6 = IPV6_ADDRESS ; plt_network : network = IP_PREFIX ; plt_network6 : network = IPV6_PREFIX ; pot_apply_groups : s_apply_groups ; pot_as_path : AS_PATH name = variable pot_as_path_tail ; pot_as_path_tail : regex = AS_PATH_REGEX ; pot_community : COMMUNITY name = variable pot_community_tail ; pot_community_tail : ct_members ; pot_policy_statement : POLICY_STATEMENT ( WILDCARD | name = variable ) pot_policy_statement_tail ; pot_policy_statement_tail : pst_term | pst_term_tail ; pot_prefix_list : PREFIX_LIST name = variable pot_prefix_list_tail ; pot_prefix_list_tail : // intentional blank | plt_apply_path | plt_network | plt_network6 ; pst_term : TERM ( WILDCARD | name = variable ) pst_term_tail ; pst_term_tail : tt_apply_groups | tt_from | tt_then ; rft_exact : EXACT ; rft_longer : LONGER ; rft_orlonger : ORLONGER ; rft_prefix_length_range : PREFIX_LENGTH_RANGE FORWARD_SLASH low = DEC DASH FORWARD_SLASH high = DEC ; rft_through : THROUGH ( IP_PREFIX | IPV6_PREFIX ) ; rft_upto : UPTO FORWARD_SLASH high = DEC ; s_policy_options : POLICY_OPTIONS s_policy_options_tail ; s_policy_options_tail : pot_apply_groups | pot_as_path | pot_community | pot_policy_statement | pot_prefix_list ; tht_accept : ACCEPT ; tht_as_path_expand : AS_PATH_EXPAND LAST_AS COUNT DEC ; tht_as_path_prepend : AS_PATH_PREPEND ( DEC | DOUBLE_QUOTED_STRING ) ; tht_color : COLOR tht_color_tail ; tht_color_tail : colort_apply_groups | colort_color ; tht_community_add : COMMUNITY ADD name = variable ; tht_community_delete : COMMUNITY DELETE name = variable ; tht_community_set : COMMUNITY SET name = variable ; tht_cos_next_hop_map : COS_NEXT_HOP_MAP name = variable ; tht_default_action_accept : DEFAULT_ACTION ACCEPT ; tht_default_action_reject : DEFAULT_ACTION REJECT ; tht_external : EXTERNAL TYPE DEC ; tht_install_nexthop : INSTALL_NEXTHOP s_null_filler ; tht_local_preference : LOCAL_PREFERENCE localpref = DEC ; tht_metric : METRIC metric = DEC ; tht_metric2 : METRIC2 metric2 = DEC ; tht_metric_expression : METRIC EXPRESSION metric_expression ; tht_metric_igp : METRIC IGP ; tht_metric2_expression : METRIC2 EXPRESSION metric_expression ; tht_next_policy : NEXT POLICY ; tht_next_term : NEXT TERM ; tht_next_hop : NEXT_HOP ( IP_ADDRESS | IPV6_ADDRESS | PEER_ADDRESS | SELF ) ; tht_null : LOAD_BALANCE s_null_filler ; tht_origin : ORIGIN IGP ; tht_reject : REJECT ; tht_tag : TAG DEC ; tt_apply_groups : s_apply_groups ; tt_from : FROM tt_from_tail ; tt_from_tail : fromt_area | fromt_as_path | fromt_color | fromt_community | fromt_family | fromt_interface | fromt_neighbor | fromt_null | fromt_policy | fromt_prefix_list | fromt_protocol | fromt_route_filter | fromt_route_type | fromt_source_address_filter | fromt_tag ; tt_then : THEN tt_then_tail ; tt_then_tail : tht_accept | tht_as_path_expand | tht_as_path_prepend | tht_color | tht_community_add | tht_community_delete | tht_community_set | tht_cos_next_hop_map | tht_default_action_accept | tht_default_action_reject | tht_external | tht_install_nexthop | tht_local_preference | tht_metric | tht_metric_expression | tht_metric_igp | tht_metric2 | tht_metric2_expression | tht_next_hop | tht_next_policy | tht_next_term | tht_null | tht_origin | tht_reject | tht_tag ;
revert allowing ipv6 in juniper prefix list
revert allowing ipv6 in juniper prefix list
ANTLR
apache-2.0
dhalperi/batfish,intentionet/batfish,intentionet/batfish,arifogel/batfish,batfish/batfish,arifogel/batfish,arifogel/batfish,dhalperi/batfish,intentionet/batfish,batfish/batfish,batfish/batfish,intentionet/batfish,dhalperi/batfish,intentionet/batfish
d371fb6d8240a6fb2d19a22e3d3a4a458b9534d4
graphstream-dgs/DGSParser.g4
graphstream-dgs/DGSParser.g4
/* * Graphstream DGS grammar. * * Adapted from http://graphstream-project.org/doc/Advanced-Concepts/The-DGS-File-Format/ * */ parser grammar DGSParser; options { tokenVocab=DGSLexer; } dgs : header ( event | COMMENT | EOL )* ; header : MAGIC EOL identifier INT INT EOL; event : ( an | cn | dn | ae | ce | de | cg | st | cl ) ( COMMENT | EOL ) ; an : AN identifier attributes; cn : CN identifier attributes; dn : DN identifier; ae : AE identifier identifier direction? identifier attributes; ce : CE identifier attributes; de : DE identifier; cg : CG attributes; st : ST REAL; cl : CL; attributes : attribute*; attribute : (PLUS|MINUS)? identifier ( assign value ( COMMA value )* )? ; value : STRING | INT| REAL | COLOR | array | a_map | identifier; // 'string' and #334455 colors // identifier array : LBRACE ( value ( COMMA value )* )? RBRACE; a_map : LBRACK ( mapping ( COMMA mapping )* )? RBRACK; mapping : identifier assign value; direction : LANGLE | RANGLE ; assign : EQUALS | COLON ; identifier : STRING | INT | WORD ( DOT WORD )* ;
/* * Graphstream DGS grammar. * * Adapted from http://graphstream-project.org/doc/Advanced-Concepts/The-DGS-File-Format/ * */ parser grammar DGSParser; options { tokenVocab=DGSLexer; } dgs : header ( event | COMMENT | EOL )* ; header : MAGIC EOL identifier INT INT EOL; event : ( an | cn | dn | ae | ce | de | cg | st | cl ) ( COMMENT | EOL ) ; an : AN identifier attributes; cn : CN identifier attributes; dn : DN identifier; ae : AE identifier identifier direction? identifier attributes; ce : CE identifier attributes; de : DE identifier; cg : CG attributes; st : ST REAL; cl : CL; attributes : attribute*; attribute : (PLUS|MINUS)? identifier ( assign value ( COMMA value )* )? ; value : STRING | INT| REAL | COLOR | array | a_map | identifier; array : LBRACE ( value ( COMMA value )* )? RBRACE; a_map : LBRACK ( mapping ( COMMA mapping )* )? RBRACK; mapping : identifier assign value; direction : LANGLE | RANGLE ; assign : EQUALS | COLON ; identifier : STRING | INT | WORD ( DOT WORD )* ;
clean up code
clean up 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
dd290eabdc219ba5e725e0364cddcd2210fa169b
src/main/antlr/GraphqlCommon.g4
src/main/antlr/GraphqlCommon.g4
grammar GraphqlCommon; operationType : SUBSCRIPTION | MUTATION | QUERY; description : StringValue; enumValue : enumValueName ; arrayValue: '[' value* ']'; arrayValueWithVariable: '[' valueWithVariable* ']'; objectValue: '{' objectField* '}'; objectValueWithVariable: '{' objectFieldWithVariable* '}'; objectField : name ':' value; objectFieldWithVariable : name ':' valueWithVariable; directives : directive+; directive :'@' name arguments?; arguments : '(' argument+ ')'; argument : name ':' valueWithVariable; baseName: NAME | FRAGMENT | QUERY | MUTATION | SUBSCRIPTION | SCHEMA | SCALAR | TYPE | INTERFACE | IMPLEMENTS | ENUM | UNION | INPUT | EXTEND | DIRECTIVE | REPEATABLE; fragmentName: baseName | BooleanValue | NullValue; enumValueName: baseName | ON_KEYWORD; name: baseName | BooleanValue | NullValue | ON_KEYWORD; value : StringValue | IntValue | FloatValue | BooleanValue | NullValue | enumValue | arrayValue | objectValue; valueWithVariable : variable | StringValue | IntValue | FloatValue | BooleanValue | NullValue | enumValue | arrayValueWithVariable | objectValueWithVariable; variable : '$' name; defaultValue : '=' value; type : typeName | listType | nonNullType; typeName : name; listType : '[' type ']'; nonNullType: typeName '!' | listType '!'; BooleanValue: 'true' | 'false'; NullValue: 'null'; FRAGMENT: 'fragment'; QUERY: 'query'; MUTATION: 'mutation'; SUBSCRIPTION: 'subscription'; SCHEMA: 'schema'; SCALAR: 'scalar'; TYPE: 'type'; INTERFACE: 'interface'; IMPLEMENTS: 'implements'; ENUM: 'enum'; UNION: 'union'; INPUT: 'input'; EXTEND: 'extend'; DIRECTIVE: 'directive'; ON_KEYWORD: 'on'; REPEATABLE: 'repeatable'; NAME: [_A-Za-z][_0-9A-Za-z]*; // Int Value IntValue : IntegerPart { !isDigit(_input.LA(1)) && !isDot(_input.LA(1)) && !isNameStart(_input.LA(1)) }?; fragment IntegerPart : NegativeSign? '0' | NegativeSign? NonZeroDigit Digit*; fragment NegativeSign : '-'; fragment NonZeroDigit: '1'..'9'; // Float Value FloatValue : ((IntegerPart FractionalPart ExponentPart) { !isDigit(_input.LA(1)) && !isDot(_input.LA(1)) && !isNameStart(_input.LA(1)) }?) | ((IntegerPart FractionalPart ) { !isDigit(_input.LA(1)) && !isDot(_input.LA(1)) && !isNameStart(_input.LA(1)) }?) | ((IntegerPart ExponentPart) { !isDigit(_input.LA(1)) && !isDot(_input.LA(1)) && !isNameStart(_input.LA(1)) }?); fragment FractionalPart: '.' Digit+; fragment ExponentPart : ExponentIndicator Sign? Digit+; fragment ExponentIndicator: 'e' | 'E'; fragment Sign: '+'|'-'; fragment Digit : '0'..'9'; // StringValue StringValue: '""' { _input.LA(1) != '"'}? | '"' StringCharacter+ '"' | '"""' BlockStringCharacter*? '"""'; fragment BlockStringCharacter: '\\"""'| ExtendedSourceCharacter; fragment StringCharacter: ([\u0009\u0020\u0021] | [\u0023-\u005b] | [\u005d-\u{10FFFF}]) | // this is SourceCharacter without '"' and '\' '\\u' EscapedUnicode | '\\' EscapedCharacter; fragment EscapedCharacter : ["\\/bfnrt]; fragment EscapedUnicode : Hex Hex Hex Hex | '{' Hex+ '}'; fragment Hex : [0-9a-fA-F]; // this is currently not covered by the spec because we allow all unicode chars // u0009 = \t Horizontal tab // u000a = \n line feed // u000d = \r carriage return // u0020 = space fragment ExtendedSourceCharacter :[\u0009\u000A\u000D\u0020-\u{10FFFF}]; fragment ExtendedSourceCharacterWithoutLineFeed :[\u0009\u0020-\u{10FFFF}]; // this is the spec definition // fragment SourceCharacter :[\u0009\u000A\u000D\u0020-\uFFFF]; Comment: '#' ExtendedSourceCharacterWithoutLineFeed* -> channel(2); LF: [\n] -> channel(3); CR: [\r] -> channel(3); LineTerminator: [\u2028\u2029] -> channel(3); Space : [\u0020] -> channel(3); Tab : [\u0009] -> channel(3); Comma : ',' -> channel(3); UnicodeBOM : [\ufeff] -> channel(3);
grammar GraphqlCommon; operationType : SUBSCRIPTION | MUTATION | QUERY; description : StringValue; enumValue : enumValueName ; arrayValue: '[' value* ']'; arrayValueWithVariable: '[' valueWithVariable* ']'; objectValue: '{' objectField* '}'; objectValueWithVariable: '{' objectFieldWithVariable* '}'; objectField : name ':' value; objectFieldWithVariable : name ':' valueWithVariable; directives : directive+; directive :'@' name arguments?; arguments : '(' argument+ ')'; argument : name ':' valueWithVariable; baseName: NAME | FRAGMENT | QUERY | MUTATION | SUBSCRIPTION | SCHEMA | SCALAR | TYPE | INTERFACE | IMPLEMENTS | ENUM | UNION | INPUT | EXTEND | DIRECTIVE | REPEATABLE; fragmentName: baseName | BooleanValue | NullValue; enumValueName: baseName | ON_KEYWORD; name: baseName | BooleanValue | NullValue | ON_KEYWORD; value : StringValue | IntValue | FloatValue | BooleanValue | NullValue | enumValue | arrayValue | objectValue; valueWithVariable : variable | StringValue | IntValue | FloatValue | BooleanValue | NullValue | enumValue | arrayValueWithVariable | objectValueWithVariable; variable : '$' name; defaultValue : '=' value; type : typeName | listType | nonNullType; typeName : name; listType : '[' type ']'; nonNullType: typeName '!' | listType '!'; BooleanValue: 'true' | 'false'; NullValue: 'null'; FRAGMENT: 'fragment'; QUERY: 'query'; MUTATION: 'mutation'; SUBSCRIPTION: 'subscription'; SCHEMA: 'schema'; SCALAR: 'scalar'; TYPE: 'type'; INTERFACE: 'interface'; IMPLEMENTS: 'implements'; ENUM: 'enum'; UNION: 'union'; INPUT: 'input'; EXTEND: 'extend'; DIRECTIVE: 'directive'; ON_KEYWORD: 'on'; REPEATABLE: 'repeatable'; NAME: [_A-Za-z][_0-9A-Za-z]*; // Int Value IntValue : IntegerPart { !isDigit(_input.LA(1)) && !isDot(_input.LA(1)) && !isNameStart(_input.LA(1)) }?; fragment IntegerPart : NegativeSign? '0' | NegativeSign? NonZeroDigit Digit*; fragment NegativeSign : '-'; fragment NonZeroDigit: '1'..'9'; // Float Value FloatValue : ((IntegerPart FractionalPart ExponentPart) { !isDigit(_input.LA(1)) && !isDot(_input.LA(1)) && !isNameStart(_input.LA(1)) }?) | ((IntegerPart FractionalPart ) { !isDigit(_input.LA(1)) && !isDot(_input.LA(1)) && !isNameStart(_input.LA(1)) }?) | ((IntegerPart ExponentPart) { !isDigit(_input.LA(1)) && !isDot(_input.LA(1)) && !isNameStart(_input.LA(1)) }?); fragment FractionalPart: '.' Digit+; fragment ExponentPart : ExponentIndicator Sign? Digit+; fragment ExponentIndicator: 'e' | 'E'; fragment Sign: '+'|'-'; fragment Digit : '0'..'9'; // StringValue StringValue: '""' { _input.LA(1) != '"'}? | '"' StringCharacter+ '"' | '"""' BlockStringCharacter*? '"""'; fragment BlockStringCharacter: '\\"""'| SourceCharacter; // this is SourceCharacter without // \u000a New line // \u000d Carriage return // \u0022 '"' // \u005c '\' fragment StringCharacter: ([\u0000-\u0009] | [\u000b\u000c\u000e-\u0021] | [\u0023-\u005b] | [\u005d-\ud7ff] | [\ue000-\u{10ffff}]) | '\\u' EscapedUnicode | '\\' EscapedCharacter; fragment EscapedCharacter : ["\\/bfnrt]; fragment EscapedUnicode : Hex Hex Hex Hex | '{' Hex+ '}'; fragment Hex : [0-9a-fA-F]; // this is the spec definition. Excludes surrogate leading and trailing values. fragment SourceCharacter : [\u0000-\ud7ff] | [\ue000-\u{10ffff}]; // CommentChar fragment SourceCharacterWithoutLineFeed : [\u0000-\u0009] | [\u000b\u000c\u000e-\ud7ff] | [\ue000-\u{10ffff}]; Comment: '#' SourceCharacterWithoutLineFeed* -> channel(2); LF: [\n] -> channel(3); CR: [\r] -> channel(3); LineTerminator: [\u2028\u2029] -> channel(3); Space : [\u0020] -> channel(3); Tab : [\u0009] -> channel(3); Comma : ',' -> channel(3); UnicodeBOM : [\ufeff] -> channel(3);
Update ANTLR grammar with new SourceCharacter definition
Update ANTLR grammar with new SourceCharacter definition
ANTLR
mit
graphql-java/graphql-java,graphql-java/graphql-java
65fc87eca3c02bd80c10aa4d839ec1e520c83aeb
aileenc/grammar/Aileen.g4
aileenc/grammar/Aileen.g4
grammar Aileen; // Parser rules compilation_unit : function_definition* ; function_definition : KEYWORD_FUNCTION IDENTIFIER '(' parameters? ')' ('->' return_type)? block ; parameters : parameter (',' parameter)* ; parameter : IDENTIFIER ':' parameter_type ; return_type : primitive_type ; parameter_type : primitive_type ; block : '{' binding_declaration_list statement_list '}' ; binding_declaration_list : (binding_declaration)* ; statement_list : (statement)* ; statement : return_statement ; return_statement : KEYWORD_RETURN expression? ';' ; binding_declaration : constant_binding_declaration | variable_binding_declaration ; constant_binding_declaration : 'const' IDENTIFIER (':' parameter_type)? KEYWORD_ASSIGNMENT expression ';' ; variable_binding_declaration : 'var' (':' parameter_type)? KEYWORD_ASSIGNMENT expression ';' ; expression : literal ; literal : BOOLEAN_LITERAL | CHARACTER_LITERAL | INTEGER_LITERAL | FLOAT_LITERAL ; primitive_type : KEYWORD_BOOLEAN | KEYWORD_CHARACTER | KEYWORD_I8 | KEYWORD_I16 | KEYWORD_I32 | KEYWORD_I64 | KEYWORD_U8 | KEYWORD_U16 | KEYWORD_U32 | KEYWORD_U64 | KEYWORD_F32 | KEYWORD_F64 ; // Lexer rules KEYWORD_FUNCTION : 'function'; KEYWORD_RETURN : 'return'; KEYWORD_BOOLEAN : 'bool'; KEYWORD_CHARACTER : 'char'; KEYWORD_I8 : 'i8'; KEYWORD_I16 : 'i16'; KEYWORD_I32 : 'i32'; KEYWORD_I64 : 'i64'; KEYWORD_U8 : 'u8'; KEYWORD_U16 : 'u16'; KEYWORD_U32 : 'u32'; KEYWORD_U64 : 'u64'; KEYWORD_F32 : 'f32'; KEYWORD_F64 : 'f64'; KEYWORD_ASSIGNMENT : '='; BOOLEAN_LITERAL : 'true' | 'false' ; CHARACTER_LITERAL : '\'' SINGLE_CHARACTER '\'' ; INTEGER_LITERAL : DECIMAL_INTEGER_LITERAL | HEXADECIMAL_INTEGER_LITERAL | BINARY_INTEGER_LITERAL ; DECIMAL_INTEGER_LITERAL : '-'? NONNEGATIVE_INTEGER EXPONENT | '-'? NONNEGATIVE_INTEGER ; HEXADECIMAL_INTEGER_LITERAL : '0x' (HEXADECIMAL_DIGIT HEXADECIMAL_DIGIT)+ ; BINARY_INTEGER_LITERAL : '0b' [01]+ ; FLOAT_LITERAL : '0.0' | '-'? NONNEGATIVE_INTEGER '.' [0-9]+ EXPONENT? ; STRING_LITERAL : '"' (ESCAPED_CHARACTER | ~ ["\\])* '"' ; IDENTIFIER : LETTER (LETTER | [0-9])* ; BLOCK_COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ; WHITE_SPACES : [ \t\n\r]+ -> skip ; fragment SINGLE_CHARACTER : ~['\\\r\n] ; fragment ESCAPED_CHARACTER : '\\' (["\\/bfnrt] | UNICODE_CHARACTER) ; fragment UNICODE_CHARACTER : 'u' HEXADECIMAL_DIGIT HEXADECIMAL_DIGIT HEXADECIMAL_DIGIT HEXADECIMAL_DIGIT ; fragment HEXADECIMAL_DIGIT : [0-9a-f] ; fragment LETTER : [a-zA-Z] ; fragment NONNEGATIVE_INTEGER : '0' | [1-9] [0-9]* ; fragment EXPONENT : [e] [+-]? NONNEGATIVE_INTEGER ;
grammar Aileen; // Parser rules compilation_unit : function_definition* ; function_definition : KEYWORD_FUNCTION IDENTIFIER '(' parameters? ')' ('->' return_type)? block ; parameters : parameter (',' parameter)* ; parameter : IDENTIFIER ':' parameter_type ; return_type : primitive_type ; parameter_type : primitive_type ; block : '{' binding_declaration_list statement_list '}' ; binding_declaration_list : (binding_declaration)* ; statement_list : (statement)* ; statement : return_statement ; return_statement : KEYWORD_RETURN expression? ';' ; binding_declaration : constant_binding_declaration | variable_binding_declaration ; constant_binding_declaration : KEYWORD_CONST_BINDING IDENTIFIER (':' parameter_type)? OPERATOR_ASSIGNMENT expression ';' ; variable_binding_declaration : KEYWORD_VARIABLE_BINDING IDENTIFIER (':' parameter_type)? OPERATOR_ASSIGNMENT expression ';' ; expression : literal ; literal : BOOLEAN_LITERAL | CHARACTER_LITERAL | INTEGER_LITERAL | FLOAT_LITERAL ; primitive_type : KEYWORD_BOOLEAN | KEYWORD_CHARACTER | KEYWORD_I8 | KEYWORD_I16 | KEYWORD_I32 | KEYWORD_I64 | KEYWORD_U8 | KEYWORD_U16 | KEYWORD_U32 | KEYWORD_U64 | KEYWORD_F32 | KEYWORD_F64 ; // Lexer rules KEYWORD_FUNCTION : 'function'; KEYWORD_RETURN : 'return'; KEYWORD_CONST_BINDING : 'const'; KEYWORD_VARIABLE_BINDING : 'var'; KEYWORD_BOOLEAN : 'bool'; KEYWORD_CHARACTER : 'char'; KEYWORD_I8 : 'i8'; KEYWORD_I16 : 'i16'; KEYWORD_I32 : 'i32'; KEYWORD_I64 : 'i64'; KEYWORD_U8 : 'u8'; KEYWORD_U16 : 'u16'; KEYWORD_U32 : 'u32'; KEYWORD_U64 : 'u64'; KEYWORD_F32 : 'f32'; KEYWORD_F64 : 'f64'; OPERATOR_ASSIGNMENT : '='; BOOLEAN_LITERAL : 'true' | 'false' ; CHARACTER_LITERAL : '\'' SINGLE_CHARACTER '\'' ; INTEGER_LITERAL : DECIMAL_INTEGER_LITERAL | HEXADECIMAL_INTEGER_LITERAL | BINARY_INTEGER_LITERAL ; DECIMAL_INTEGER_LITERAL : '-'? NONNEGATIVE_INTEGER EXPONENT | '-'? NONNEGATIVE_INTEGER ; HEXADECIMAL_INTEGER_LITERAL : '0x' (HEXADECIMAL_DIGIT HEXADECIMAL_DIGIT)+ ; BINARY_INTEGER_LITERAL : '0b' [01]+ ; FLOAT_LITERAL : '0.0' | '-'? NONNEGATIVE_INTEGER '.' [0-9]+ EXPONENT? ; STRING_LITERAL : '"' (ESCAPED_CHARACTER | ~ ["\\])* '"' ; IDENTIFIER : LETTER (LETTER | [0-9])* ; BLOCK_COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ; WHITE_SPACES : [ \t\n\r]+ -> skip ; fragment SINGLE_CHARACTER : ~['\\\r\n] ; fragment ESCAPED_CHARACTER : '\\' (["\\/bfnrt] | UNICODE_CHARACTER) ; fragment UNICODE_CHARACTER : 'u' HEXADECIMAL_DIGIT HEXADECIMAL_DIGIT HEXADECIMAL_DIGIT HEXADECIMAL_DIGIT ; fragment HEXADECIMAL_DIGIT : [0-9a-f] ; fragment LETTER : [a-zA-Z] ; fragment NONNEGATIVE_INTEGER : '0' | [1-9] [0-9]* ; fragment EXPONENT : [e] [+-]? NONNEGATIVE_INTEGER ;
Update aileenlang grammar.
Update aileenlang grammar.
ANTLR
mit
alejandroclaro/aileenlang
aa5ddd7603a0e86a75d2e5f96355b78ae9542c13
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/BaseRule.g4
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/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 Symbol, Keyword, MySQLKeyword, Literals; parameterMarker : QUESTION_ ; literals : stringLiterals | numberLiterals | dateTimeLiterals | hexadecimalLiterals | bitValueLiterals | booleanLiterals | nullValueLiterals ; stringLiterals : characterSetName_? STRING_ collateClause_? ; numberLiterals : MINUS_? NUMBER_ ; dateTimeLiterals : (DATE | TIME | TIMESTAMP) STRING_ | LBE_ identifier_ STRING_ RBE_ ; hexadecimalLiterals : characterSetName_? HEX_DIGIT_ collateClause_? ; bitValueLiterals : characterSetName_? BIT_NUM_ collateClause_? ; booleanLiterals : TRUE | FALSE ; nullValueLiterals : NULL ; identifier_ : IDENTIFIER_ | unreservedWord_ ; variable_ : (AT_? AT_)? (GLOBAL | PERSIST | PERSIST_ONLY | SESSION)? DOT_? identifier_ ; scope_ : (GLOBAL | PERSIST | PERSIST_ONLY | SESSION) | AT_ AT_ (GLOBAL | PERSIST | PERSIST_ONLY | SESSION) DOT_ ; unreservedWord_ : ACCOUNT | ACTION | AFTER | ALGORITHM | ALWAYS | ANY | AUTO_INCREMENT | AVG_ROW_LENGTH | BEGIN | BTREE | CHAIN | CHARSET | CHECKSUM | CIPHER | CLIENT | COALESCE | COLUMNS | COLUMN_FORMAT | COMMENT | COMMIT | COMMITTED | COMPACT | COMPRESSED | COMPRESSION | CONNECTION | CONSISTENT | CURRENT | DATA | DATE | DELAY_KEY_WRITE | DISABLE | DISCARD | DISK | DUPLICATE | ENABLE | ENCRYPTION | ENFORCED | END | ENGINE | ESCAPE | EVENT | EXCHANGE | EXECUTE | FILE | FIRST | FIXED | FOLLOWING | GLOBAL | HASH | IMPORT_ | INSERT_METHOD | INVISIBLE | KEY_BLOCK_SIZE | LAST | LESS | LEVEL | MAX_ROWS | MEMORY | MIN_ROWS | MODIFY | NO | NONE | OFFSET | PACK_KEYS | PARSER | PARTIAL | PARTITIONING | PASSWORD | PERSIST | PERSIST_ONLY | PRECEDING | PRIVILEGES | PROCESS | PROXY | QUICK | REBUILD | REDUNDANT | RELOAD | REMOVE | REORGANIZE | REPAIR | REVERSE | ROLLBACK | ROLLUP | ROW_FORMAT | SAVEPOINT | SESSION | SHUTDOWN | SIMPLE | SLAVE | SOUNDS | SQL_BIG_RESULT | SQL_BUFFER_RESULT | SQL_CACHE | SQL_NO_CACHE | START | STATS_AUTO_RECALC | STATS_PERSISTENT | STATS_SAMPLE_PAGES | STORAGE | SUBPARTITION | SUPER | TABLES | TABLESPACE | TEMPORARY | THAN | TIME | TIMESTAMP | TRANSACTION | TRUNCATE | UNBOUNDED | UNKNOWN | UPGRADE | VALIDATION | VALUE | VIEW | VISIBLE | WEIGHT_STRING | WITHOUT | MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH | QUARTER | YEAR | AGAINST | LANGUAGE | MODE | QUERY | EXPANSION | BOOLEAN | MAX | MIN | SUM | COUNT | AVG | BIT_AND | BIT_OR | BIT_XOR | GROUP_CONCAT | JSON_ARRAYAGG | JSON_OBJECTAGG | STD | STDDEV | STDDEV_POP | STDDEV_SAMP | VAR_POP | VAR_SAMP | VARIANCE | EXTENDED | STATUS | FIELDS | INDEXES | USER | ROLE | OJ | AUTOCOMMIT | OFF | ROTATE | INSTANCE | MASTER | BINLOG |ERROR | SCHEDULE | COMPLETION | DO | DEFINER | START | EVERY | HOST | SOCKET | OWNER | PORT | RETURNS | CONTAINS | SECURITY | INVOKER | UNDEFINED | MERGE | TEMPTABLE | CASCADED | LOCAL | SERVER | WRAPPER | OPTIONS | DATAFILE | FILE_BLOCK_SIZE | EXTENT_SIZE | INITIAL_SIZE | AUTOEXTEND_SIZE | MAX_SIZE | NODEGROUP | WAIT | LOGFILE | UNDOFILE | UNDO_BUFFER_SIZE | REDO_BUFFER_SIZE | DEFINITION | ORGANIZATION | DESCRIPTION | REFERENCE | FOLLOWS | PRECEDES | NAME |CLOSE | OPEN | NEXT | HANDLER | PREV | IMPORT | CONCURRENT | XML ; schemaName : identifier_ ; tableName : (owner DOT_)? name ; columnName : (owner DOT_)? name ; userName : (STRING_ | IDENTIFIER_) AT_ (STRING_ IDENTIFIER_) | identifier_ | STRING_ ; eventName : (STRING_ | IDENTIFIER_) AT_ (STRING_ IDENTIFIER_) | identifier_ | STRING_ ; serverName : identifier_ | STRING_ ; wrapperName : identifier_ | STRING_ ; functionName : identifier_ | (owner DOT_)? identifier_ ; viewName : identifier_ | (owner DOT_)? identifier_ ; owner : identifier_ ; name : identifier_ ; columnNames : LP_? columnName (COMMA_ columnName)* RP_? ; tableNames : LP_? tableName (COMMA_ tableName)* RP_? ; indexName : identifier_ ; characterSetName_ : IDENTIFIER_ ; collationName_ : IDENTIFIER_ ; expr : expr logicalOperator expr | expr XOR expr | notOperator_ expr | LP_ expr RP_ | booleanPrimary_ ; logicalOperator : OR | OR_ | AND | AND_ ; notOperator_ : NOT | NOT_ ; 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_ expr (COMMA_ expr)* RP_ | bitExpr NOT? BETWEEN bitExpr AND predicate | bitExpr SOUNDS LIKE bitExpr | bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)? | bitExpr NOT? (REGEXP | RLIKE) bitExpr | 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 DIV bitExpr | bitExpr MOD bitExpr | bitExpr MOD_ bitExpr | bitExpr CARET_ bitExpr | bitExpr PLUS_ intervalExpression_ | bitExpr MINUS_ intervalExpression_ | simpleExpr ; simpleExpr : functionCall | parameterMarker | literals | columnName | simpleExpr COLLATE (STRING_ | identifier_) | variable_ | simpleExpr OR_ simpleExpr | (PLUS_ | MINUS_ | TILDE_ | NOT_ | BINARY) simpleExpr | ROW? LP_ expr (COMMA_ expr)* RP_ | EXISTS? subquery | LBE_ identifier_ expr RBE_ | matchExpression_ | caseExpression_ | intervalExpression_ ; functionCall : aggregationFunction | specialFunction_ | regularFunction_ ; aggregationFunction : aggregationFunctionName_ LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? RP_ overClause_? ; aggregationFunctionName_ : MAX | MIN | SUM | COUNT | AVG | BIT_AND | BIT_OR | BIT_XOR | JSON_ARRAYAGG | JSON_OBJECTAGG | STD | STDDEV | STDDEV_POP | STDDEV_SAMP | VAR_POP | VAR_SAMP | VARIANCE ; distinct : DISTINCT ; overClause_ : OVER (LP_ windowSpecification_ RP_ | identifier_) ; windowSpecification_ : identifier_? partitionClause_? orderByClause? frameClause_? ; partitionClause_ : PARTITION BY expr (COMMA_ expr)* ; frameClause_ : (ROWS | RANGE) (frameStart_ | frameBetween_) ; frameStart_ : CURRENT ROW | UNBOUNDED PRECEDING | UNBOUNDED FOLLOWING | expr PRECEDING | expr FOLLOWING ; frameEnd_ : frameStart_ ; frameBetween_ : BETWEEN frameStart_ AND frameEnd_ ; specialFunction_ : groupConcatFunction_ | windowFunction_ | castFunction_ | convertFunction_ | positionFunction_ | substringFunction_ | extractFunction_ | charFunction_ | trimFunction_ | weightStringFunction_ ; groupConcatFunction_ : GROUP_CONCAT LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? (orderByClause (SEPARATOR expr)?)? RP_ ; windowFunction_ : identifier_ LP_ expr (COMMA_ expr)* RP_ overClause_ ; castFunction_ : CAST LP_ expr AS dataType RP_ ; convertFunction_ : CONVERT LP_ expr COMMA_ dataType RP_ | CONVERT LP_ expr USING identifier_ RP_ ; positionFunction_ : POSITION LP_ expr IN expr RP_ ; substringFunction_ : (SUBSTRING | SUBSTR) LP_ expr FROM NUMBER_ (FOR NUMBER_)? RP_ ; extractFunction_ : EXTRACT LP_ identifier_ FROM expr RP_ ; charFunction_ : CHAR LP_ expr (COMMA_ expr)* (USING ignoredIdentifier_)? RP_ ; trimFunction_ : TRIM LP_ (LEADING | BOTH | TRAILING) STRING_ FROM STRING_ RP_ ; weightStringFunction_ : WEIGHT_STRING LP_ expr (AS dataType)? levelClause_? RP_ ; levelClause_ : LEVEL (levelInWeightListElement_ (COMMA_ levelInWeightListElement_)* | NUMBER_ MINUS_ NUMBER_) ; levelInWeightListElement_ : NUMBER_ (ASC | DESC)? REVERSE? ; regularFunction_ : regularFunctionName_ LP_ (expr (COMMA_ expr)* | ASTERISK_)? RP_ ; regularFunctionName_ : identifier_ | IF | CURRENT_TIMESTAMP | LOCALTIME | LOCALTIMESTAMP | NOW | REPLACE | INTERVAL | SUBSTRING ; matchExpression_ : MATCH columnNames AGAINST (expr matchSearchModifier_?) ; matchSearchModifier_ : IN NATURAL LANGUAGE MODE | IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION | IN BOOLEAN MODE | WITH QUERY EXPANSION ; caseExpression_ : CASE simpleExpr? caseWhen_+ caseElse_? END ; caseWhen_ : WHEN expr THEN expr ; caseElse_ : ELSE expr ; intervalExpression_ : INTERVAL expr intervalUnit_ ; intervalUnit_ : MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH | QUARTER | YEAR | SECOND_MICROSECOND | MINUTE_MICROSECOND | MINUTE_SECOND | HOUR_MICROSECOND | HOUR_SECOND | HOUR_MINUTE | DAY_MICROSECOND | DAY_SECOND | DAY_MINUTE | DAY_HOUR | YEAR_MONTH ; subquery : 'Default does not match anything' ; orderByClause : ORDER BY orderByItem (COMMA_ orderByItem)* ; orderByItem : (columnName | numberLiterals | expr) (ASC | DESC)? ; dataType : dataTypeName_ dataTypeLength? characterSet_? collateClause_? UNSIGNED? ZEROFILL? | dataTypeName_ LP_ STRING_ (COMMA_ STRING_)* RP_ characterSet_? collateClause_? ; dataTypeName_ : identifier_ identifier_? ; dataTypeLength : LP_ NUMBER_ (COMMA_ NUMBER_)? RP_ ; characterSet_ : (CHARACTER | CHAR) SET EQ_? ignoredIdentifier_ ; collateClause_ : COLLATE EQ_? (STRING_ | ignoredIdentifier_) ; ignoredIdentifier_ : identifier_ (DOT_ identifier_)? ; ignoredIdentifiers_ : ignoredIdentifier_ (COMMA_ ignoredIdentifier_)* ;
/* * 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 Symbol, Keyword, MySQLKeyword, Literals; parameterMarker : QUESTION_ ; literals : stringLiterals | numberLiterals | dateTimeLiterals | hexadecimalLiterals | bitValueLiterals | booleanLiterals | nullValueLiterals ; stringLiterals : characterSetName_? STRING_ collateClause_? ; numberLiterals : MINUS_? NUMBER_ ; dateTimeLiterals : (DATE | TIME | TIMESTAMP) STRING_ | LBE_ identifier_ STRING_ RBE_ ; hexadecimalLiterals : characterSetName_? HEX_DIGIT_ collateClause_? ; bitValueLiterals : characterSetName_? BIT_NUM_ collateClause_? ; booleanLiterals : TRUE | FALSE ; nullValueLiterals : NULL ; identifier_ : IDENTIFIER_ | unreservedWord_ ; variable_ : (AT_? AT_)? (GLOBAL | PERSIST | PERSIST_ONLY | SESSION)? DOT_? identifier_ ; scope_ : (GLOBAL | PERSIST | PERSIST_ONLY | SESSION) | AT_ AT_ (GLOBAL | PERSIST | PERSIST_ONLY | SESSION) DOT_ ; unreservedWord_ : ACCOUNT | ACTION | AFTER | ALGORITHM | ALWAYS | ANY | AUTO_INCREMENT | AVG_ROW_LENGTH | BEGIN | BTREE | CHAIN | CHARSET | CHECKSUM | CIPHER | CLIENT | COALESCE | COLUMNS | COLUMN_FORMAT | COMMENT | COMMIT | COMMITTED | COMPACT | COMPRESSED | COMPRESSION | CONNECTION | CONSISTENT | CURRENT | DATA | DATE | DELAY_KEY_WRITE | DISABLE | DISCARD | DISK | DUPLICATE | ENABLE | ENCRYPTION | ENFORCED | END | ENGINE | ESCAPE | EVENT | EXCHANGE | EXECUTE | FILE | FIRST | FIXED | FOLLOWING | GLOBAL | HASH | IMPORT_ | INSERT_METHOD | INVISIBLE | KEY_BLOCK_SIZE | LAST | LESS | LEVEL | MAX_ROWS | MEMORY | MIN_ROWS | MODIFY | NO | NONE | OFFSET | PACK_KEYS | PARSER | PARTIAL | PARTITIONING | PASSWORD | PERSIST | PERSIST_ONLY | PRECEDING | PRIVILEGES | PROCESS | PROXY | QUICK | REBUILD | REDUNDANT | RELOAD | REMOVE | REORGANIZE | REPAIR | REVERSE | ROLLBACK | ROLLUP | ROW_FORMAT | SAVEPOINT | SESSION | SHUTDOWN | SIMPLE | SLAVE | SOUNDS | SQL_BIG_RESULT | SQL_BUFFER_RESULT | SQL_CACHE | SQL_NO_CACHE | START | STATS_AUTO_RECALC | STATS_PERSISTENT | STATS_SAMPLE_PAGES | STORAGE | SUBPARTITION | SUPER | TABLES | TABLESPACE | TEMPORARY | THAN | TIME | TIMESTAMP | TRANSACTION | TRUNCATE | UNBOUNDED | UNKNOWN | UPGRADE | VALIDATION | VALUE | VIEW | VISIBLE | WEIGHT_STRING | WITHOUT | MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH | QUARTER | YEAR | AGAINST | LANGUAGE | MODE | QUERY | EXPANSION | BOOLEAN | MAX | MIN | SUM | COUNT | AVG | BIT_AND | BIT_OR | BIT_XOR | GROUP_CONCAT | JSON_ARRAYAGG | JSON_OBJECTAGG | STD | STDDEV | STDDEV_POP | STDDEV_SAMP | VAR_POP | VAR_SAMP | VARIANCE | EXTENDED | STATUS | FIELDS | INDEXES | USER | ROLE | OJ | AUTOCOMMIT | OFF | ROTATE | INSTANCE | MASTER | BINLOG |ERROR | SCHEDULE | COMPLETION | DO | DEFINER | START | EVERY | HOST | SOCKET | OWNER | PORT | RETURNS | CONTAINS | SECURITY | INVOKER | UNDEFINED | MERGE | TEMPTABLE | CASCADED | LOCAL | SERVER | WRAPPER | OPTIONS | DATAFILE | FILE_BLOCK_SIZE | EXTENT_SIZE | INITIAL_SIZE | AUTOEXTEND_SIZE | MAX_SIZE | NODEGROUP | WAIT | LOGFILE | UNDOFILE | UNDO_BUFFER_SIZE | REDO_BUFFER_SIZE | DEFINITION | ORGANIZATION | DESCRIPTION | REFERENCE | FOLLOWS | PRECEDES | NAME |CLOSE | OPEN | NEXT | HANDLER | PREV | IMPORT | CONCURRENT | XML | POSITION ; schemaName : identifier_ ; tableName : (owner DOT_)? name ; columnName : (owner DOT_)? name ; userName : (STRING_ | IDENTIFIER_) AT_ (STRING_ IDENTIFIER_) | identifier_ | STRING_ ; eventName : (STRING_ | IDENTIFIER_) AT_ (STRING_ IDENTIFIER_) | identifier_ | STRING_ ; serverName : identifier_ | STRING_ ; wrapperName : identifier_ | STRING_ ; functionName : identifier_ | (owner DOT_)? identifier_ ; viewName : identifier_ | (owner DOT_)? identifier_ ; owner : identifier_ ; name : identifier_ ; columnNames : LP_? columnName (COMMA_ columnName)* RP_? ; tableNames : LP_? tableName (COMMA_ tableName)* RP_? ; indexName : identifier_ ; characterSetName_ : IDENTIFIER_ ; collationName_ : IDENTIFIER_ ; expr : expr logicalOperator expr | expr XOR expr | notOperator_ expr | LP_ expr RP_ | booleanPrimary_ ; logicalOperator : OR | OR_ | AND | AND_ ; notOperator_ : NOT | NOT_ ; 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_ expr (COMMA_ expr)* RP_ | bitExpr NOT? BETWEEN bitExpr AND predicate | bitExpr SOUNDS LIKE bitExpr | bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)? | bitExpr NOT? (REGEXP | RLIKE) bitExpr | 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 DIV bitExpr | bitExpr MOD bitExpr | bitExpr MOD_ bitExpr | bitExpr CARET_ bitExpr | bitExpr PLUS_ intervalExpression_ | bitExpr MINUS_ intervalExpression_ | simpleExpr ; simpleExpr : functionCall | parameterMarker | literals | columnName | simpleExpr COLLATE (STRING_ | identifier_) | variable_ | simpleExpr OR_ simpleExpr | (PLUS_ | MINUS_ | TILDE_ | NOT_ | BINARY) simpleExpr | ROW? LP_ expr (COMMA_ expr)* RP_ | EXISTS? subquery | LBE_ identifier_ expr RBE_ | matchExpression_ | caseExpression_ | intervalExpression_ ; functionCall : aggregationFunction | specialFunction_ | regularFunction_ ; aggregationFunction : aggregationFunctionName_ LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? RP_ overClause_? ; aggregationFunctionName_ : MAX | MIN | SUM | COUNT | AVG | BIT_AND | BIT_OR | BIT_XOR | JSON_ARRAYAGG | JSON_OBJECTAGG | STD | STDDEV | STDDEV_POP | STDDEV_SAMP | VAR_POP | VAR_SAMP | VARIANCE ; distinct : DISTINCT ; overClause_ : OVER (LP_ windowSpecification_ RP_ | identifier_) ; windowSpecification_ : identifier_? partitionClause_? orderByClause? frameClause_? ; partitionClause_ : PARTITION BY expr (COMMA_ expr)* ; frameClause_ : (ROWS | RANGE) (frameStart_ | frameBetween_) ; frameStart_ : CURRENT ROW | UNBOUNDED PRECEDING | UNBOUNDED FOLLOWING | expr PRECEDING | expr FOLLOWING ; frameEnd_ : frameStart_ ; frameBetween_ : BETWEEN frameStart_ AND frameEnd_ ; specialFunction_ : groupConcatFunction_ | windowFunction_ | castFunction_ | convertFunction_ | positionFunction_ | substringFunction_ | extractFunction_ | charFunction_ | trimFunction_ | weightStringFunction_ ; groupConcatFunction_ : GROUP_CONCAT LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? (orderByClause (SEPARATOR expr)?)? RP_ ; windowFunction_ : identifier_ LP_ expr (COMMA_ expr)* RP_ overClause_ ; castFunction_ : CAST LP_ expr AS dataType RP_ ; convertFunction_ : CONVERT LP_ expr COMMA_ dataType RP_ | CONVERT LP_ expr USING identifier_ RP_ ; positionFunction_ : POSITION LP_ expr IN expr RP_ ; substringFunction_ : (SUBSTRING | SUBSTR) LP_ expr FROM NUMBER_ (FOR NUMBER_)? RP_ ; extractFunction_ : EXTRACT LP_ identifier_ FROM expr RP_ ; charFunction_ : CHAR LP_ expr (COMMA_ expr)* (USING ignoredIdentifier_)? RP_ ; trimFunction_ : TRIM LP_ (LEADING | BOTH | TRAILING) STRING_ FROM STRING_ RP_ ; weightStringFunction_ : WEIGHT_STRING LP_ expr (AS dataType)? levelClause_? RP_ ; levelClause_ : LEVEL (levelInWeightListElement_ (COMMA_ levelInWeightListElement_)* | NUMBER_ MINUS_ NUMBER_) ; levelInWeightListElement_ : NUMBER_ (ASC | DESC)? REVERSE? ; regularFunction_ : regularFunctionName_ LP_ (expr (COMMA_ expr)* | ASTERISK_)? RP_ ; regularFunctionName_ : identifier_ | IF | CURRENT_TIMESTAMP | LOCALTIME | LOCALTIMESTAMP | NOW | REPLACE | INTERVAL | SUBSTRING ; matchExpression_ : MATCH columnNames AGAINST (expr matchSearchModifier_?) ; matchSearchModifier_ : IN NATURAL LANGUAGE MODE | IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION | IN BOOLEAN MODE | WITH QUERY EXPANSION ; caseExpression_ : CASE simpleExpr? caseWhen_+ caseElse_? END ; caseWhen_ : WHEN expr THEN expr ; caseElse_ : ELSE expr ; intervalExpression_ : INTERVAL expr intervalUnit_ ; intervalUnit_ : MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH | QUARTER | YEAR | SECOND_MICROSECOND | MINUTE_MICROSECOND | MINUTE_SECOND | HOUR_MICROSECOND | HOUR_SECOND | HOUR_MINUTE | DAY_MICROSECOND | DAY_SECOND | DAY_MINUTE | DAY_HOUR | YEAR_MONTH ; subquery : 'Default does not match anything' ; orderByClause : ORDER BY orderByItem (COMMA_ orderByItem)* ; orderByItem : (columnName | numberLiterals | expr) (ASC | DESC)? ; dataType : dataTypeName_ dataTypeLength? characterSet_? collateClause_? UNSIGNED? ZEROFILL? | dataTypeName_ LP_ STRING_ (COMMA_ STRING_)* RP_ characterSet_? collateClause_? ; dataTypeName_ : identifier_ identifier_? ; dataTypeLength : LP_ NUMBER_ (COMMA_ NUMBER_)? RP_ ; characterSet_ : (CHARACTER | CHAR) SET EQ_? ignoredIdentifier_ ; collateClause_ : COLLATE EQ_? (STRING_ | ignoredIdentifier_) ; ignoredIdentifier_ : identifier_ (DOT_ identifier_)? ; ignoredIdentifiers_ : ignoredIdentifier_ (COMMA_ ignoredIdentifier_)* ;
fix #2868
fix #2868
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
61e436ec03ef63b89f88a990c40ed6f5dede72af
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 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] ; 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_clause_optional[$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); } // parallelize directive | define_option[$l]* PARALLELIZE data_clause_optional[$l] over_clause_optional[$l] { $l.setDirective(ClawDirective.PARALLELIZE); } | PARALLELIZE FORWARD { $l.setDirective(ClawDirective.PARALLELIZE); $l.setForwardClause(); } ; // 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] ; // over clause over_clause_optional[ClawLanguage l] @init{ List<String> s = new ArrayList<>(); } : OVER '(' ids_or_colon_list[s] ')' { $l.setOverClause(s); } | /* empty */ ; // group clause group_clause_optional[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupClause($group_name.text); } | /* empty */ ; // collapse clause collapse_optional[ClawLanguage l]: COLLAPSE '(' n=NUMBER ')' { $l.setCollapseClause($n.text); } | /* empty */ ; // fusion clause fusion_optional[ClawLanguage l]: FUSION group_clause_optional[$l] { $l.setFusionClause(); } | /* empty */ ; // parallel clause parallel_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); } ; // data clause or empty data_clause_optional[ClawLanguage l]: data_clause[$l] | /* empty */ ; // 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(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] ; 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); } ; /*---------------------------------------------------------------------------- * 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'; 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'; // 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.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] ; 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_clause_optional[$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); } // parallelize directive | define_option[$l]* PARALLELIZE data_clause_optional[$l] over_clause_optional[$l] { $l.setDirective(ClawDirective.PARALLELIZE); } | PARALLELIZE FORWARD { $l.setDirective(ClawDirective.PARALLELIZE); $l.setForwardClause(); } | END PARALLELIZE { $l.setDirective(ClawDirective.PARALLELIZE); $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] ; // over clause over_clause_optional[ClawLanguage l] @init{ List<String> s = new ArrayList<>(); } : OVER '(' ids_or_colon_list[s] ')' { $l.setOverClause(s); } | /* empty */ ; // group clause group_clause_optional[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupClause($group_name.text); } | /* empty */ ; // collapse clause collapse_optional[ClawLanguage l]: COLLAPSE '(' n=NUMBER ')' { $l.setCollapseClause($n.text); } | /* empty */ ; // fusion clause fusion_optional[ClawLanguage l]: FUSION group_clause_optional[$l] { $l.setFusionClause(); } | /* empty */ ; // parallel clause parallel_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); } ; // data clause or empty data_clause_optional[ClawLanguage l]: data_clause[$l] | /* empty */ ; // 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(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] ; 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); } ; /*---------------------------------------------------------------------------- * 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'; 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'; // 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 grammar for "end parallelize"
Add grammar for "end parallelize"
ANTLR
bsd-2-clause
clementval/claw-compiler,clementval/claw-compiler
7c9f6034388e8cf530e412138cd02f84a7db31f8
antlr/antlr4/LexBasic.g4
antlr/antlr4/LexBasic.g4
/* * [The "BSD license"] * Copyright (c) 2014-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 generally reusable set of fragments for import in to Lexer grammars. * * Modified 2015.06.16 gbr - * -- generalized for inclusion into the ANTLRv4 grammar distribution * */ lexer grammar LexBasic; // ====================================================== // Lexer fragments // // ----------------------------------- // Whitespace & Comments fragment Ws : Hws | Vws ; fragment Hws : [ \t] ; fragment Vws : [\r\n\f] ; fragment BlockComment : '/*' .*? ('*/' | EOF) ; fragment DocComment : '/**' .*? ('*/' | EOF) ; fragment LineComment : '//' ~ [\r\n]* ; // ----------------------------------- // Escapes // Any kind of escaped character that we can embed within ANTLR literal strings. fragment EscSeq : Esc ([btnfr"'\\] | UnicodeEsc | . | EOF) ; fragment EscAny : Esc . ; fragment UnicodeEsc : 'u' (HexDigit (HexDigit (HexDigit HexDigit?)?)?)? ; // ----------------------------------- // Numerals fragment DecimalNumeral : '0' | [1-9] DecDigit* ; // ----------------------------------- // Digits fragment HexDigit : [0-9a-fA-F] ; fragment DecDigit : [0-9] ; // ----------------------------------- // Literals fragment BoolLiteral : 'true' | 'false' ; fragment CharLiteral : SQuote (EscSeq | ~ ['\r\n\\]) SQuote ; fragment SQuoteLiteral : SQuote (EscSeq | ~ ['\r\n\\])* SQuote ; fragment DQuoteLiteral : DQuote (EscSeq | ~ ["\r\n\\])* DQuote ; fragment USQuoteLiteral : SQuote (EscSeq | ~ ['\r\n\\])* ; // ----------------------------------- // Character ranges fragment NameChar : NameStartChar | '0' .. '9' | Underscore | '\u00B7' | '\u0300' .. '\u036F' | '\u203F' .. '\u2040' ; fragment NameStartChar : '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' ; // ignores | ['\u10000-'\uEFFFF] ; // ----------------------------------- // Types fragment Int : 'int' ; // ----------------------------------- // Symbols fragment Esc : '\\' ; fragment Colon : ':' ; fragment DColon : '::' ; fragment SQuote : '\'' ; fragment DQuote : '"' ; fragment LParen : '(' ; fragment RParen : ')' ; fragment LBrace : '{' ; fragment RBrace : '}' ; fragment LBrack : '[' ; fragment RBrack : ']' ; fragment RArrow : '->' ; fragment Lt : '<' ; fragment Gt : '>' ; fragment Equal : '=' ; fragment Question : '?' ; fragment Star : '*' ; fragment Plus : '+' ; fragment PlusAssign : '+=' ; fragment Underscore : '_' ; fragment Pipe : '|' ; fragment Dollar : '$' ; fragment Comma : ',' ; fragment Semi : ';' ; fragment Dot : '.' ; fragment Range : '..' ; fragment At : '@' ; fragment Pound : '#' ; fragment Tilde : '~' ;
/* * [The "BSD license"] * Copyright (c) 2014-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 generally reusable set of fragments for import in to Lexer grammars. * * Modified 2015.06.16 gbr - * -- generalized for inclusion into the ANTLRv4 grammar distribution * */ lexer grammar LexBasic; // ====================================================== // Lexer fragments // // ----------------------------------- // Whitespace & Comments fragment Ws : Hws | Vws ; fragment Hws : [ \t] ; fragment Vws : [\r\n\f] ; fragment BlockComment : '/*' .*? ('*/' | EOF) ; fragment DocComment : '/**' .*? ('*/' | EOF) ; fragment LineComment : '//' ~ [\r\n]* ; // ----------------------------------- // Escapes // Any kind of escaped character that we can embed within ANTLR literal strings. fragment EscSeq : Esc ([btnfr"'\\] | UnicodeEsc | . | EOF) ; fragment EscAny : Esc . ; fragment UnicodeEsc : 'u' (HexDigit (HexDigit (HexDigit HexDigit?)?)?)? ; // ----------------------------------- // Numerals fragment DecimalNumeral : '0' | [1-9] DecDigit* ; // ----------------------------------- // Digits fragment HexDigit : [0-9a-fA-F] ; fragment DecDigit : [0-9] ; // ----------------------------------- // Literals fragment BoolLiteral : 'true' | 'false' ; fragment CharLiteral : SQuote (EscSeq | ~ ['\r\n\\]) SQuote ; fragment SQuoteLiteral : SQuote (EscSeq | ~ ['\r\n\\])* SQuote ; fragment DQuoteLiteral : DQuote (EscSeq | ~ ["\r\n\\])* DQuote ; fragment USQuoteLiteral : SQuote (EscSeq | ~ ['\r\n\\])* ; // ----------------------------------- // Character ranges fragment NameChar : NameStartChar | '0' .. '9' | Underscore | '\u00B7' | '\u0300' .. '\u036F' | '\u203F' .. '\u2040' ; fragment NameStartChar : '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' ; // ignores | ['\u10000-'\uEFFFF] ; // ----------------------------------- // Types fragment Int : 'int' ; // ----------------------------------- // Symbols fragment Esc : '\\' ; fragment Colon : ':' ; fragment DColon : '::' ; fragment SQuote : '\'' ; fragment DQuote : '"' ; fragment LParen : '(' ; fragment RParen : ')' ; fragment LBrace : '{' ; fragment RBrace : '}' ; fragment LBrack : '[' ; fragment RBrack : ']' ; fragment RArrow : '->' ; fragment Lt : '<' ; fragment Gt : '>' ; fragment Equal : '=' ; fragment Question : '?' ; fragment Star : '*' ; fragment Plus : '+' ; fragment PlusAssign : '+=' ; fragment Underscore : '_' ; fragment Pipe : '|' ; fragment Dollar : '$' ; fragment Comma : ',' ; fragment Semi : ';' ; fragment Dot : '.' ; fragment Range : '..' ; fragment At : '@' ; fragment Pound : '#' ; fragment Tilde : '~' ;
Update LexBasic.g4
Update LexBasic.g4
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
f200a1d6b0294c8f3835a441ac5733467ac379f4
src/main/antlr/ActionLanguage.g4
src/main/antlr/ActionLanguage.g4
grammar ActionLanguage; @header { package pl.edu.pw.mini.msi.knowledgerepresentation.grammar; } programm: instruction* EOF; instruction : initialization | entry | scenario | query ; entry : causes | TYPICALLY? invokes | TYPICALLY? releases | TYPICALLY? triggers | TYPICALLY? occurs | impossible ; initialization: INITIALLY logicalExpression; causes: action CAUSES logicalExpression afterTime? underCondition?; invokes: action INVOKES action afterTime? underCondition?; releases: action RELEASES logicalExpression afterTime? underCondition?; triggers: logicalExpression TRIGGERS action; occurs: action OCCURS AT time; impossible: IMPOSSIBLE action AT time underCondition?; underCondition: IF logicalExpression; afterTime: AFTER time; action: '('actor ',' task ')'; fluentsList: fluent | fluentsList ',' fluent; scenario: IDENTIFIER '{' actions ',' observations '}'; actions: ACS '=' '{' eventsList? '}'; eventsList: event | eventsList ',' event; event: '(' action ',' time ')'; observations: OBS '=' '{' observationsList? '}'; observationsList: observation | observationsList ',' observation; observation: '(' fluentsList ',' time ')'; logicalExpression: fluent | '(' logicalExpression logicalOperator logicalExpression ')'; query : state | performed | involved ; state: question logicalExpression AT time WHEN scenarioId; performed: question PERFORMED action AT time WHEN scenarioId; involved: basicQuestion INVOLVED actorsList WHEN scenarioId; question : basicQuestion | TYPICALLY ; basicQuestion : EVER ; actorsList: actors; actors: actor | actors ',' actor; fluent: IDENTIFIER | NOT IDENTIFIER; actor: IDENTIFIER; task: IDENTIFIER; time: DecimalConstant; scenarioId: IDENTIFIER; logicalOperator: LOGICAL_AND | LOGICAL_IF | LOGICAL_OR; WS: [ \n\t\r]+ -> skip; ACS: 'ACS'; AFTER: 'after'; AT: 'at'; CAUSES: 'causes'; EVER: 'ever'; IF: 'if'; IMPOSSIBLE: 'impossible'; INITIALLY: 'initially'; INVOKES: 'invokes'; INVOLVED: 'involved'; NOT: '-'; OBS: 'OBS'; OCCURS: 'occurs'; PERFORMED: 'performed'; RELEASES: 'releases'; TRIGGERS: 'triggers'; TYPICALLY: 'typically'; WHEN: 'when'; IDENTIFIER : [a-zA-Z]+; DecimalConstant: [0-9]+; LOGICAL_OR: '||'; LOGICAL_IF: '=>'; LOGICAL_AND: '&&';
grammar ActionLanguage; @header { package pl.edu.pw.mini.msi.knowledgerepresentation.grammar; } programm: instruction* EOF; instruction : initialization | entry | scenario | query ; entry : causes | TYPICALLY? invokes | TYPICALLY? releases | TYPICALLY? triggers | TYPICALLY? occurs | impossible ; initialization: INITIALLY logicalExpression; causes: action CAUSES logicalExpression afterTime? underCondition?; invokes: action INVOKES action afterTime? underCondition?; releases: action RELEASES fluent afterTime? underCondition?; triggers: logicalExpression TRIGGERS action; occurs: action OCCURS AT time; impossible: IMPOSSIBLE action AT time underCondition?; underCondition: IF logicalExpression; afterTime: AFTER time; action: '('actor ',' task ')'; fluentsList: fluent | fluentsList ',' fluent; scenario: IDENTIFIER '{' actions ',' observations '}'; actions: ACS '=' '{' eventsList? '}'; eventsList: event | eventsList ',' event; event: '(' action ',' time ')'; observations: OBS '=' '{' observationsList? '}'; observationsList: observation | observationsList ',' observation; observation: '(' fluentsList ',' time ')'; logicalExpression: fluent | '(' logicalExpression logicalOperator logicalExpression ')'; query : state | performed | involved ; state: question logicalExpression AT time WHEN scenarioId; performed: question PERFORMED action AT time WHEN scenarioId; involved: basicQuestion INVOLVED actorsList WHEN scenarioId; question : basicQuestion | TYPICALLY ; basicQuestion : EVER ; actorsList: actors; actors: actor | actors ',' actor; fluent: IDENTIFIER | NOT IDENTIFIER; actor: IDENTIFIER; task: IDENTIFIER; time: DecimalConstant; scenarioId: IDENTIFIER; logicalOperator: LOGICAL_AND | LOGICAL_IF | LOGICAL_OR; WS: [ \n\t\r]+ -> skip; ACS: 'ACS'; AFTER: 'after'; AT: 'at'; CAUSES: 'causes'; EVER: 'ever'; IF: 'if'; IMPOSSIBLE: 'impossible'; INITIALLY: 'initially'; INVOKES: 'invokes'; INVOLVED: 'involved'; NOT: '-'; OBS: 'OBS'; OCCURS: 'occurs'; PERFORMED: 'performed'; RELEASES: 'releases'; TRIGGERS: 'triggers'; TYPICALLY: 'typically'; WHEN: 'when'; IDENTIFIER : [a-zA-Z]+; DecimalConstant: [0-9]+; LOGICAL_OR: '||'; LOGICAL_IF: '=>'; LOGICAL_AND: '&&';
allow only fluent in releases
allow only fluent in releases
ANTLR
isc
janisz/knowledge-representation,janisz/knowledge-representation
f5e3ff96925b015a87b6dd28c7eedd585a3ee299
client/src/main/antlr4/com/metamx/druid/sql/antlr4/DruidSQL.g4
client/src/main/antlr4/com/metamx/druid/sql/antlr4/DruidSQL.g4
grammar DruidSQL; @header { import com.metamx.druid.aggregation.post.*; import com.metamx.druid.aggregation.*; import com.metamx.druid.query.filter.*; import com.metamx.druid.query.dimension.*; import com.metamx.druid.*; import com.google.common.base.*; import com.google.common.collect.Lists; import org.joda.time.*; import java.text.*; import java.util.*; } @parser::members { public Map<String, AggregatorFactory> aggregators = new LinkedHashMap<String, AggregatorFactory>(); public List<PostAggregator> postAggregators = new LinkedList<PostAggregator>(); public DimFilter filter; public List<org.joda.time.Interval> intervals; public QueryGranularity granularity = QueryGranularity.ALL; public Map<String, DimensionSpec> groupByDimensions = new LinkedHashMap<String, DimensionSpec>(); String dataSourceName = null; public String getDataSource() { return dataSourceName; } public String unescape(String quoted) { String unquote = quoted.trim().replaceFirst("^'(.*)'\$", "\$1"); return unquote.replace("''", "'"); } AggregatorFactory evalAgg(String name, int fn) { switch (fn) { case SUM: return new DoubleSumAggregatorFactory("sum("+name+")", name); case MIN: return new MinAggregatorFactory("min("+name+")", name); case MAX: return new MaxAggregatorFactory("max("+name+")", name); case COUNT: return new CountAggregatorFactory(name); } throw new IllegalArgumentException("Unknown function [" + fn + "]"); } PostAggregator evalArithmeticPostAggregator(PostAggregator a, List<Token> ops, List<PostAggregator> b) { if(b.isEmpty()) return a; else { int i = 0; PostAggregator root = a; while(i < ops.size()) { List<PostAggregator> list = new LinkedList<PostAggregator>(); List<String> names = new LinkedList<String>(); names.add(root.getName()); list.add(root); Token op = ops.get(i); while(i < ops.size() && ops.get(i).getType() == op.getType()) { PostAggregator e = b.get(i); list.add(e); names.add(e.getName()); i++; } root = new ArithmeticPostAggregator("("+Joiner.on(op.getText()).join(names)+")", op.getText(), list); } return root; } } } AND: 'and'; OR: 'or'; SUM: 'sum'; MIN: 'min'; MAX: 'max'; COUNT: 'count'; AS: 'as'; OPEN: '('; CLOSE: ')'; STAR: '*'; NOT: '!' ; PLUS: '+'; MINUS: '-'; DIV: '/'; COMMA: ','; GROUP: 'group'; IDENT : (LETTER)(LETTER | DIGIT | '_')* ; QUOTED_STRING : '\'' ( ESC | ~'\'' )*? '\'' ; ESC : '\'' '\''; NUMBER: ('+'|'-')?DIGIT*'.'?DIGIT+(EXPONENT)?; EXPONENT: ('e') ('+'|'-')? ('0'..'9')+; fragment DIGIT : '0'..'9'; fragment LETTER : 'a'..'z' | 'A'..'Z'; LINE_COMMENT : '--' .*? '\r'? '\n' -> skip ; COMMENT : '/*' .*? '*/' -> skip ; WS : (' '| '\t' | '\r' '\n' | '\n' | '\r')+ -> skip; query : select_stmt where_stmt (groupby_stmt)? ; select_stmt : 'select' e+=aliasedExpression (',' e+=aliasedExpression)* 'from' datasource { for(AliasedExpressionContext a : $e) { postAggregators.add(a.p); } this.dataSourceName = $datasource.text; } ; where_stmt : 'where' f=timeAndDimFilter { if($f.filter != null) this.filter = $f.filter; this.intervals = Lists.newArrayList($f.interval); } ; groupby_stmt : GROUP 'by' groupByExpression ( COMMA! groupByExpression )* ; groupByExpression : gran=granularityFn {this.granularity = $gran.granularity;} | dim=IDENT { this.groupByDimensions.put($dim.text, new DefaultDimensionSpec($dim.text, $dim.text)); } ; datasource : IDENT ; aliasedExpression returns [PostAggregator p] : expression ( AS^ name=IDENT )? { if($name != null) { postAggregators.add($expression.p); $p = new FieldAccessPostAggregator($name.text, $expression.p.getName()); } else $p = $expression.p; } ; expression returns [PostAggregator p] : additiveExpression { $p = $additiveExpression.p; } ; additiveExpression returns [PostAggregator p] : a=multiplyExpression (( ops+=PLUS^ | ops+=MINUS^ ) b+=multiplyExpression)* { List<PostAggregator> rhs = new LinkedList<PostAggregator>(); for(MultiplyExpressionContext e : $b) rhs.add(e.p); $p = evalArithmeticPostAggregator($a.p, $ops, rhs); } ; multiplyExpression returns [PostAggregator p] : a=unaryExpression ((ops+= STAR | ops+=DIV ) b+=unaryExpression)* { List<PostAggregator> rhs = new LinkedList<PostAggregator>(); for(UnaryExpressionContext e : $b) rhs.add(e.p); $p = evalArithmeticPostAggregator($a.p, $ops, rhs); } ; unaryExpression returns [PostAggregator p] : MINUS e=unaryExpression { $p = new ArithmeticPostAggregator( "-"+$e.p.getName(), "*", Lists.newArrayList($e.p, new ConstantPostAggregator("-1", -1.0)) ); } | PLUS e=unaryExpression { $p = $e.p; } | primaryExpression { $p = $primaryExpression.p; } ; primaryExpression returns [PostAggregator p] : constant { $p = $constant.c; } | aggregate { aggregators.put($aggregate.agg.getName(), $aggregate.agg); $p = new FieldAccessPostAggregator($aggregate.agg.getName(), $aggregate.agg.getName()); } | OPEN! e=expression CLOSE! { $p = $e.p; } ; aggregate returns [AggregatorFactory agg] : fn=( SUM^ | MIN^ | MAX^ ) OPEN! name=(IDENT|COUNT) CLOSE! { $agg = evalAgg($name.text, $fn.type); } | fn=COUNT OPEN! STAR CLOSE! { $agg = evalAgg("count(*)", $fn.type); } ; constant returns [ConstantPostAggregator c] : value=NUMBER { double v = Double.parseDouble($value.text); $c = new ConstantPostAggregator(Double.toString(v), v); } ; /* time filters must be top level filters */ timeAndDimFilter returns [DimFilter filter, org.joda.time.Interval interval] : t=timeFilter (AND f=dimFilter)? { if($f.ctx != null) $filter = $f.filter; $interval = $t.interval; } | (f=dimFilter)? AND t=timeFilter { if($f.ctx != null) $filter = $f.filter; $interval = $t.interval; } ; dimFilter returns [DimFilter filter] : e=orDimFilter { $filter = $e.filter; } ; orDimFilter returns [DimFilter filter] : a=andDimFilter (OR^ b+=andDimFilter)* { if($b.isEmpty()) $filter = $a.filter; else { List<DimFilter> rest = new ArrayList<DimFilter>(); for(AndDimFilterContext e : $b) rest.add(e.filter); $filter = new OrDimFilter(Lists.asList($a.filter, rest.toArray(new DimFilter[]{}))); } } ; andDimFilter returns [DimFilter filter] : a=primaryDimFilter (AND^ b+=primaryDimFilter)* { if($b.isEmpty()) $filter = $a.filter; else { List<DimFilter> rest = new ArrayList<DimFilter>(); for(PrimaryDimFilterContext e : $b) rest.add(e.filter); $filter = new AndDimFilter(Lists.asList($a.filter, rest.toArray(new DimFilter[]{}))); } } ; primaryDimFilter returns [DimFilter filter] : e=selectorDimFilter { $filter = $e.filter; } | NOT f=dimFilter { $filter = new NotDimFilter($f.filter); } | OPEN! f=dimFilter CLOSE! { $filter = $f.filter; } ; selectorDimFilter returns [SelectorDimFilter filter] : dimension=IDENT '=' value=QUOTED_STRING { $filter = new SelectorDimFilter($dimension.text, unescape($value.text)); } ; timeFilter returns [org.joda.time.Interval interval, QueryGranularity granularity] : 'timestamp' 'between' s=timestamp AND e=timestamp { $interval = new org.joda.time.Interval($s.t, $e.t); } ; granularityFn returns [QueryGranularity granularity] : 'granularity' OPEN! 'timestamp' ',' str=QUOTED_STRING CLOSE! { String granStr = unescape($str.text); try { $granularity = QueryGranularity.fromString(granStr); } catch(IllegalArgumentException e) { $granularity = new PeriodGranularity(new Period(granStr), null, null); } } ; timestamp returns [DateTime t] : NUMBER { String str = $NUMBER.text.trim(); try { $t = new DateTime(NumberFormat.getInstance().parse(str)); } catch(ParseException e) { throw new IllegalArgumentException("Unable to parse number [" + str + "]"); } } | QUOTED_STRING { $t = new DateTime(unescape($QUOTED_STRING.text)); } ;
grammar DruidSQL; @header { import com.metamx.druid.aggregation.post.*; import com.metamx.druid.aggregation.*; import com.metamx.druid.query.filter.*; import com.metamx.druid.query.dimension.*; import com.metamx.druid.*; import com.google.common.base.*; import com.google.common.collect.Lists; import org.joda.time.*; import java.text.*; import java.util.*; } @parser::members { public Map<String, AggregatorFactory> aggregators = new LinkedHashMap<String, AggregatorFactory>(); public List<PostAggregator> postAggregators = new LinkedList<PostAggregator>(); public DimFilter filter; public List<org.joda.time.Interval> intervals; public QueryGranularity granularity = QueryGranularity.ALL; public Map<String, DimensionSpec> groupByDimensions = new LinkedHashMap<String, DimensionSpec>(); String dataSourceName = null; public String getDataSource() { return dataSourceName; } public String unescape(String quoted) { String unquote = quoted.trim().replaceFirst("^'(.*)'\$", "\$1"); return unquote.replace("''", "'"); } AggregatorFactory evalAgg(String name, int fn) { switch (fn) { case SUM: return new DoubleSumAggregatorFactory("sum("+name+")", name); case MIN: return new MinAggregatorFactory("min("+name+")", name); case MAX: return new MaxAggregatorFactory("max("+name+")", name); case COUNT: return new CountAggregatorFactory(name); } throw new IllegalArgumentException("Unknown function [" + fn + "]"); } PostAggregator evalArithmeticPostAggregator(PostAggregator a, List<Token> ops, List<PostAggregator> b) { if(b.isEmpty()) return a; else { int i = 0; PostAggregator root = a; while(i < ops.size()) { List<PostAggregator> list = new LinkedList<PostAggregator>(); List<String> names = new LinkedList<String>(); names.add(root.getName()); list.add(root); Token op = ops.get(i); while(i < ops.size() && ops.get(i).getType() == op.getType()) { PostAggregator e = b.get(i); list.add(e); names.add(e.getName()); i++; } root = new ArithmeticPostAggregator("("+Joiner.on(op.getText()).join(names)+")", op.getText(), list); } return root; } } } AND: 'and'; OR: 'or'; SUM: 'sum'; MIN: 'min'; MAX: 'max'; COUNT: 'count'; AS: 'as'; OPEN: '('; CLOSE: ')'; STAR: '*'; NOT: '!' ; PLUS: '+'; MINUS: '-'; DIV: '/'; COMMA: ','; EQ: '='; NEQ: '!='; GROUP: 'group'; IDENT : (LETTER)(LETTER | DIGIT | '_')* ; QUOTED_STRING : '\'' ( ESC | ~'\'' )*? '\'' ; ESC : '\'' '\''; NUMBER: ('+'|'-')?DIGIT*'.'?DIGIT+(EXPONENT)?; EXPONENT: ('e') ('+'|'-')? ('0'..'9')+; fragment DIGIT : '0'..'9'; fragment LETTER : 'a'..'z' | 'A'..'Z'; LINE_COMMENT : '--' .*? '\r'? '\n' -> skip ; COMMENT : '/*' .*? '*/' -> skip ; WS : (' '| '\t' | '\r' '\n' | '\n' | '\r')+ -> skip; query : select_stmt where_stmt (groupby_stmt)? ; select_stmt : 'select' e+=aliasedExpression (',' e+=aliasedExpression)* 'from' datasource { for(AliasedExpressionContext a : $e) { postAggregators.add(a.p); } this.dataSourceName = $datasource.text; } ; where_stmt : 'where' f=timeAndDimFilter { if($f.filter != null) this.filter = $f.filter; this.intervals = Lists.newArrayList($f.interval); } ; groupby_stmt : GROUP 'by' groupByExpression ( COMMA! groupByExpression )* ; groupByExpression : gran=granularityFn {this.granularity = $gran.granularity;} | dim=IDENT { this.groupByDimensions.put($dim.text, new DefaultDimensionSpec($dim.text, $dim.text)); } ; datasource : IDENT ; aliasedExpression returns [PostAggregator p] : expression ( AS^ name=IDENT )? { if($name != null) { postAggregators.add($expression.p); $p = new FieldAccessPostAggregator($name.text, $expression.p.getName()); } else $p = $expression.p; } ; expression returns [PostAggregator p] : additiveExpression { $p = $additiveExpression.p; } ; additiveExpression returns [PostAggregator p] : a=multiplyExpression (( ops+=PLUS^ | ops+=MINUS^ ) b+=multiplyExpression)* { List<PostAggregator> rhs = new LinkedList<PostAggregator>(); for(MultiplyExpressionContext e : $b) rhs.add(e.p); $p = evalArithmeticPostAggregator($a.p, $ops, rhs); } ; multiplyExpression returns [PostAggregator p] : a=unaryExpression ((ops+= STAR | ops+=DIV ) b+=unaryExpression)* { List<PostAggregator> rhs = new LinkedList<PostAggregator>(); for(UnaryExpressionContext e : $b) rhs.add(e.p); $p = evalArithmeticPostAggregator($a.p, $ops, rhs); } ; unaryExpression returns [PostAggregator p] : MINUS e=unaryExpression { $p = new ArithmeticPostAggregator( "-"+$e.p.getName(), "*", Lists.newArrayList($e.p, new ConstantPostAggregator("-1", -1.0)) ); } | PLUS e=unaryExpression { $p = $e.p; } | primaryExpression { $p = $primaryExpression.p; } ; primaryExpression returns [PostAggregator p] : constant { $p = $constant.c; } | aggregate { aggregators.put($aggregate.agg.getName(), $aggregate.agg); $p = new FieldAccessPostAggregator($aggregate.agg.getName(), $aggregate.agg.getName()); } | OPEN! e=expression CLOSE! { $p = $e.p; } ; aggregate returns [AggregatorFactory agg] : fn=( SUM^ | MIN^ | MAX^ ) OPEN! name=(IDENT|COUNT) CLOSE! { $agg = evalAgg($name.text, $fn.type); } | fn=COUNT OPEN! STAR CLOSE! { $agg = evalAgg("count(*)", $fn.type); } ; constant returns [ConstantPostAggregator c] : value=NUMBER { double v = Double.parseDouble($value.text); $c = new ConstantPostAggregator(Double.toString(v), v); } ; /* time filters must be top level filters */ timeAndDimFilter returns [DimFilter filter, org.joda.time.Interval interval] : t=timeFilter (AND f=dimFilter)? { if($f.ctx != null) $filter = $f.filter; $interval = $t.interval; } | (f=dimFilter)? AND t=timeFilter { if($f.ctx != null) $filter = $f.filter; $interval = $t.interval; } ; dimFilter returns [DimFilter filter] : e=orDimFilter { $filter = $e.filter; } ; orDimFilter returns [DimFilter filter] : a=andDimFilter (OR^ b+=andDimFilter)* { if($b.isEmpty()) $filter = $a.filter; else { List<DimFilter> rest = new ArrayList<DimFilter>(); for(AndDimFilterContext e : $b) rest.add(e.filter); $filter = new OrDimFilter(Lists.asList($a.filter, rest.toArray(new DimFilter[]{}))); } } ; andDimFilter returns [DimFilter filter] : a=primaryDimFilter (AND^ b+=primaryDimFilter)* { if($b.isEmpty()) $filter = $a.filter; else { List<DimFilter> rest = new ArrayList<DimFilter>(); for(PrimaryDimFilterContext e : $b) rest.add(e.filter); $filter = new AndDimFilter(Lists.asList($a.filter, rest.toArray(new DimFilter[]{}))); } } ; primaryDimFilter returns [DimFilter filter] : e=selectorDimFilter { $filter = $e.filter; } | l=inListDimFilter { $filter = $l.filter; } | NOT f=dimFilter { $filter = new NotDimFilter($f.filter); } | OPEN! f=dimFilter CLOSE! { $filter = $f.filter; } ; selectorDimFilter returns [DimFilter filter] : dimension=IDENT op=(EQ|NEQ) value=QUOTED_STRING { DimFilter f = new SelectorDimFilter($dimension.text, unescape($value.text)); switch($op.type) { case(EQ): $filter = f; break; case(NEQ): $filter = new NotDimFilter(f); break; } } ; inListDimFilter returns [DimFilter filter] : dimension=IDENT 'in' (OPEN! ( (list+=QUOTED_STRING (COMMA! list+=QUOTED_STRING)*) ) CLOSE!) { List<DimFilter> filterList = new LinkedList<DimFilter>(); for(Token e : $list) filterList.add(new SelectorDimFilter($dimension.text, unescape(e.getText()))); $filter = new OrDimFilter(filterList); } ; timeFilter returns [org.joda.time.Interval interval, QueryGranularity granularity] : 'timestamp' 'between' s=timestamp AND e=timestamp { $interval = new org.joda.time.Interval($s.t, $e.t); } ; granularityFn returns [QueryGranularity granularity] : 'granularity' OPEN! 'timestamp' ',' str=QUOTED_STRING CLOSE! { String granStr = unescape($str.text); try { $granularity = QueryGranularity.fromString(granStr); } catch(IllegalArgumentException e) { $granularity = new PeriodGranularity(new Period(granStr), null, null); } } ; timestamp returns [DateTime t] : NUMBER { String str = $NUMBER.text.trim(); try { $t = new DateTime(NumberFormat.getInstance().parse(str)); } catch(ParseException e) { throw new IllegalArgumentException("Unable to parse number [" + str + "]"); } } | QUOTED_STRING { $t = new DateTime(unescape($QUOTED_STRING.text)); } ;
add support for `!=` operator and `in ('a','b',...) expressions
add support for `!=` operator and `in ('a','b',...) expressions
ANTLR
apache-2.0
pdeva/druid,deltaprojects/druid,smartpcr/druid,qix/druid,jon-wei/druid,pjain1/druid,lcp0578/druid,dclim/druid,mghosh4/druid,tubemogul/druid,winval/druid,elijah513/druid,milimetric/druid,nvoron23/druid,noddi/druid,winval/druid,Fokko/druid,authbox-lib/druid,milimetric/druid,friedhardware/druid,pjain1/druid,pombredanne/druid,nishantmonu51/druid,premc/druid,OttoOps/druid,milimetric/druid,redBorder/druid,liquidm/druid,zhiqinghuang/druid,nvoron23/druid,andy256/druid,taochaoqiang/druid,rasahner/druid,michaelschiff/druid,pjain1/druid,druid-io/druid,potto007/druid-avro,zhihuij/druid,eshen1991/druid,himanshug/druid,Fokko/druid,dkhwangbo/druid,wenjixin/druid,winval/druid,noddi/druid,nishantmonu51/druid,implydata/druid,nishantmonu51/druid,mghosh4/druid,deltaprojects/druid,druid-io/druid,Fokko/druid,nishantmonu51/druid,erikdubbelboer/druid,dkhwangbo/druid,potto007/druid-avro,monetate/druid,calliope7/druid,zhihuij/druid,winval/druid,noddi/druid,eshen1991/druid,leventov/druid,b-slim/druid,michaelschiff/druid,liquidm/druid,fjy/druid,Deebs21/druid,Fokko/druid,minewhat/druid,authbox-lib/druid,knoguchi/druid,gianm/druid,druid-io/druid,pjain1/druid,redBorder/druid,solimant/druid,cocosli/druid,penuel-leo/druid,guobingkun/druid,smartpcr/druid,fjy/druid,yaochitc/druid-dev,lcp0578/druid,implydata/druid,zengzhihai110/druid,amikey/druid,qix/druid,se7entyse7en/druid,fjy/druid,andy256/druid,qix/druid,deltaprojects/druid,pjain1/druid,dclim/druid,dkhwangbo/druid,liquidm/druid,implydata/druid,nvoron23/druid,gianm/druid,Kleagleguo/druid,penuel-leo/druid,michaelschiff/druid,jon-wei/druid,leventov/druid,mghosh4/druid,pombredanne/druid,elijah513/druid,mangeshpardeshiyahoo/druid,potto007/druid-avro,minewhat/druid,lcp0578/druid,OttoOps/druid,b-slim/druid,OttoOps/druid,praveev/druid,michaelschiff/druid,tubemogul/druid,skyportsystems/druid,zhaown/druid,andy256/druid,elijah513/druid,b-slim/druid,authbox-lib/druid,wenjixin/druid,haoch/druid,tubemogul/druid,qix/druid,solimant/druid,zxs/druid,zhiqinghuang/druid,Deebs21/druid,amikey/druid,metamx/druid,zhiqinghuang/druid,zxs/druid,implydata/druid,praveev/druid,cocosli/druid,friedhardware/druid,Kleagleguo/druid,guobingkun/druid,pdeva/druid,lizhanhui/data_druid,rasahner/druid,zxs/druid,optimizely/druid,praveev/druid,Kleagleguo/druid,wenjixin/druid,knoguchi/druid,yaochitc/druid-dev,Deebs21/druid,elijah513/druid,deltaprojects/druid,kevintvh/druid,zengzhihai110/druid,monetate/druid,767326791/druid,skyportsystems/druid,dkhwangbo/druid,zhihuij/druid,Fokko/druid,redBorder/druid,lcp0578/druid,leventov/druid,jon-wei/druid,friedhardware/druid,optimizely/druid,calliope7/druid,wenjixin/druid,mghosh4/druid,pjain1/druid,implydata/druid,KurtYoung/druid,knoguchi/druid,fjy/druid,monetate/druid,calliope7/druid,pdeva/druid,jon-wei/druid,yaochitc/druid-dev,guobingkun/druid,nishantmonu51/druid,pdeva/druid,rasahner/druid,milimetric/druid,michaelschiff/druid,pombredanne/druid,optimizely/druid,wenjixin/druid,lcp0578/druid,liquidm/druid,nishantmonu51/druid,winval/druid,kevintvh/druid,zhiqinghuang/druid,KurtYoung/druid,zhaown/druid,dkhwangbo/druid,metamx/druid,lizhanhui/data_druid,himanshug/druid,anupkumardixit/druid,skyportsystems/druid,taochaoqiang/druid,Fokko/druid,anupkumardixit/druid,penuel-leo/druid,qix/druid,anupkumardixit/druid,rasahner/druid,KurtYoung/druid,metamx/druid,taochaoqiang/druid,du00cs/druid,michaelschiff/druid,jon-wei/druid,jon-wei/druid,yaochitc/druid-dev,haoch/druid,smartpcr/druid,leventov/druid,mghosh4/druid,gianm/druid,smartpcr/druid,Deebs21/druid,redBorder/druid,premc/druid,cocosli/druid,penuel-leo/druid,b-slim/druid,guobingkun/druid,tubemogul/druid,noddi/druid,mrijke/druid,friedhardware/druid,OttoOps/druid,milimetric/druid,pombredanne/druid,zengzhihai110/druid,monetate/druid,kevintvh/druid,dclim/druid,lizhanhui/data_druid,mghosh4/druid,amikey/druid,gianm/druid,zxs/druid,mangeshpardeshiyahoo/druid,deltaprojects/druid,zhaown/druid,pjain1/druid,dclim/druid,liquidm/druid,authbox-lib/druid,solimant/druid,zhaown/druid,du00cs/druid,monetate/druid,noddi/druid,pombredanne/druid,potto007/druid-avro,se7entyse7en/druid,lizhanhui/data_druid,andy256/druid,gianm/druid,mrijke/druid,metamx/druid,zhihuij/druid,dclim/druid,taochaoqiang/druid,767326791/druid,zengzhihai110/druid,liquidm/druid,amikey/druid,Kleagleguo/druid,knoguchi/druid,gianm/druid,OttoOps/druid,yaochitc/druid-dev,optimizely/druid,optimizely/druid,guobingkun/druid,se7entyse7en/druid,zhiqinghuang/druid,erikdubbelboer/druid,praveev/druid,druid-io/druid,se7entyse7en/druid,michaelschiff/druid,kevintvh/druid,taochaoqiang/druid,himanshug/druid,monetate/druid,KurtYoung/druid,friedhardware/druid,minewhat/druid,Deebs21/druid,KurtYoung/druid,druid-io/druid,eshen1991/druid,leventov/druid,premc/druid,premc/druid,eshen1991/druid,minewhat/druid,zxs/druid,mrijke/druid,skyportsystems/druid,erikdubbelboer/druid,mangeshpardeshiyahoo/druid,767326791/druid,amikey/druid,minewhat/druid,skyportsystems/druid,se7entyse7en/druid,kevintvh/druid,metamx/druid,haoch/druid,monetate/druid,Kleagleguo/druid,implydata/druid,cocosli/druid,eshen1991/druid,du00cs/druid,mrijke/druid,haoch/druid,b-slim/druid,lizhanhui/data_druid,himanshug/druid,smartpcr/druid,mghosh4/druid,cocosli/druid,solimant/druid,fjy/druid,andy256/druid,penuel-leo/druid,nishantmonu51/druid,redBorder/druid,calliope7/druid,solimant/druid,nvoron23/druid,jon-wei/druid,anupkumardixit/druid,knoguchi/druid,deltaprojects/druid,pdeva/druid,erikdubbelboer/druid,tubemogul/druid,767326791/druid,rasahner/druid,nvoron23/druid,anupkumardixit/druid,elijah513/druid,mrijke/druid,himanshug/druid,zengzhihai110/druid,premc/druid,du00cs/druid,767326791/druid,du00cs/druid,calliope7/druid,authbox-lib/druid,zhihuij/druid,zhaown/druid,deltaprojects/druid,mangeshpardeshiyahoo/druid,haoch/druid,praveev/druid,Fokko/druid,erikdubbelboer/druid,gianm/druid,mangeshpardeshiyahoo/druid,potto007/druid-avro
6c1be79698d54e68152602a20502499ddafb2ec4
sharding-parser/sharding-parser-mysql/src/main/antlr4/imports/mysql/MySQLDDLStatement.g4
sharding-parser/sharding-parser-mysql/src/main/antlr4/imports/mysql/MySQLDDLStatement.g4
grammar MySQLDDLStatement; import MySQLKeyword, Keyword, Symbol, MySQLDQLStatement, DataType, MySQLBase, BaseRule; createTable : CREATE TEMPORARY? TABLE (IF NOT EXISTS)? tableName (LP_ createDefinitions_ RP_ | createLike_) ; createDefinitions_ : createDefinition_ (COMMA_ createDefinition_)* ; createDefinition_ : columnDefinition | constraintDefinition | indexDefinition_ | checkConstraintDefinition_ ; columnDefinition : columnName dataType (dataTypeOption_* | dataTypeGenerated_?) ; dataType : dataTypeName_ dataTypeLength? characterSet_? collateClause_? UNSIGNED? ZEROFILL? | dataTypeName_ LP_ STRING_ (COMMA_ STRING_)* RP_ characterSet_? collateClause_? ; dataTypeName_ : ID ID? ; characterSet_ : (CHARACTER | CHAR) SET EQ_? ignoredIdentifier_ | CHARSET EQ_? ignoredIdentifier_ ; collateClause_ : COLLATE EQ_? (STRING_ | ignoredIdentifier_) ; dataTypeOption_ : dataTypeGeneratedOption_ | DEFAULT? defaultValue_ | AUTO_INCREMENT | COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT) | STORAGE (DISK | MEMORY | DEFAULT) | referenceDefinition_ ; dataTypeGeneratedOption_ : NULL | NOT NULL | UNIQUE KEY? | primaryKey | COMMENT STRING_ ; dataTypeGenerated_ : (GENERATED ALWAYS)? AS expr (VIRTUAL | STORED)? dataTypeGeneratedOption_* ; defaultValue_ : NULL | NUMBER_ | STRING_ | currentTimestampType_ (ON UPDATE currentTimestampType_)? | ON UPDATE currentTimestampType_ ; currentTimestampType_ : (CURRENT_TIMESTAMP | LOCALTIME | LOCALTIMESTAMP | NOW | NUMBER_) dataTypeLength? ; referenceDefinition_ : REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? referenceType_* ; referenceType_ : ON (UPDATE | DELETE) referenceOption_ ; referenceOption_ : RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT ; constraintDefinition : (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_) ; primaryKeyOption_ : primaryKey indexType? columnNames indexOption* ; uniqueOption_ : UNIQUE (INDEX | KEY)? indexName? indexType? keyParts_ indexOption* ; foreignKeyOption_ : FOREIGN KEY indexName? columnNames referenceDefinition_ ; indexDefinition_ : (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType? keyParts_ indexOption* ; keyParts_ : LP_ keyPart_ (COMMA_ keyPart_)* RP_ ; keyPart_ : columnName (LP_ NUMBER_ RP_)? (ASC | DESC)? ; checkConstraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)? ; createLike_ : LIKE tableName | LP_ LIKE tableName RP_ ; alterTable : ALTER TABLE tableName alterSpecifications_? ; alterSpecifications_ : alterSpecification_ (COMMA_ alterSpecification_)* ; alterSpecification_ : tableOptions_ | addColumn | addIndex | addConstraint | ALGORITHM EQ_? (DEFAULT | INPLACE | COPY) | ALTER COLUMN? columnName (SET DEFAULT | DROP DEFAULT) | changeColumn | DEFAULT? characterSet_ collateClause_? | CONVERT TO characterSet_ collateClause_? | (DISABLE | ENABLE) KEYS | (DISCARD | IMPORT_) TABLESPACE | dropColumn | dropIndexDef | dropPrimaryKey | DROP FOREIGN KEY ignoredIdentifier_ | FORCE | LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE) | modifyColumn | ORDER BY columnName (COMMA_ columnName)* | renameIndex | renameTable | (WITHOUT | WITH) VALIDATION | ADD PARTITION partitionDefinitions_ | 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 ; singleColumn : columnDefinition firstOrAfterColumn? ; firstOrAfterColumn : FIRST | AFTER columnName ; multiColumn : LP_ columnDefinition (COMMA_ columnDefinition)* RP_ ; addConstraint : ADD constraintDefinition ; addIndex : ADD indexDefinition_ ; addColumn : ADD COLUMN? (singleColumn | multiColumn) ; changeColumn : changeColumnOp columnName columnDefinition firstOrAfterColumn? ; changeColumnOp : CHANGE COLUMN? ; dropColumn : DROP COLUMN? columnName ; dropIndexDef : DROP (INDEX | KEY) indexName ; dropPrimaryKey : DROP primaryKey ; modifyColumn : MODIFY COLUMN? columnDefinition firstOrAfterColumn? ; renameIndex : RENAME (INDEX | KEY) indexName TO indexName ; renameTable : RENAME (TO | AS)? tableName ; 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_? tableNames_ ; tableNames_ : LP_ tableName (COMMA_ tableName)* RP_ ; partitionOptions_ : PARTITION BY (linearPartition_ | rangeOrListPartition_) (PARTITIONS NUMBER_)? (SUBPARTITION BY linearPartition_ (SUBPARTITIONS NUMBER_)?)? (LP_ partitionDefinitions_ RP_)? ; linearPartition_ : LINEAR? (HASH (yearFunctionExpr_ | expr) | KEY (ALGORITHM EQ_ NUMBER_)? columnNames) ; yearFunctionExpr_ : LP_ YEAR expr RP_ ; rangeOrListPartition_ : (RANGE | LIST) (expr | COLUMNS columnNames) ; partitionDefinitions_ : partitionDefinition_ (COMMA_ partitionDefinition_)* ; partitionDefinition_ : PARTITION ignoredIdentifier_ (VALUES (lessThanPartition_ | IN assignmentValueList))? partitionDefinitionOption_* (LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)? ; partitionDefinitionOption_ : STORAGE? ENGINE EQ_? ignoredIdentifier_ | COMMENT EQ_? STRING_ | DATA DIRECTORY EQ_? STRING_ | INDEX DIRECTORY EQ_? STRING_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | TABLESPACE EQ_? ignoredIdentifier_ ; lessThanPartition_ : LESS THAN (LP_ (expr | assignmentValues) RP_ | MAXVALUE) ; subpartitionDefinition_ : SUBPARTITION ignoredIdentifier_ partitionDefinitionOption_* ; dropTable : DROP TEMPORARY? TABLE (IF EXISTS)? tableName (COMMA_ tableName)* ; truncateTable : TRUNCATE TABLE? tableName ; createIndex : CREATE (UNIQUE | FULLTEXT | SPATIAL)? INDEX indexName indexType? ON tableName ; dropIndex : DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName ;
grammar MySQLDDLStatement; import MySQLKeyword, Keyword, Symbol, MySQLDQLStatement, DataType, MySQLBase, BaseRule; createTable : CREATE TEMPORARY? TABLE (IF NOT EXISTS)? tableName (LP_ createDefinitions_ RP_ | createLike_) ; createDefinitions_ : createDefinition_ (COMMA_ createDefinition_)* ; createDefinition_ : columnDefinition | constraintDefinition_ | indexDefinition_ | checkConstraintDefinition_ ; columnDefinition : columnName dataType (inlineDataType_* | generatedDataType_*) ; dataType : dataTypeName_ dataTypeLength? characterSet_? collateClause_? UNSIGNED? ZEROFILL? | dataTypeName_ LP_ STRING_ (COMMA_ STRING_)* RP_ characterSet_? collateClause_? ; dataTypeName_ : ID ID? ; characterSet_ : (CHARACTER | CHAR) SET EQ_? ignoredIdentifier_ | CHARSET EQ_? ignoredIdentifier_ ; collateClause_ : COLLATE EQ_? (STRING_ | ignoredIdentifier_) ; inlineDataType_ : commonDataTypeOption_ | AUTO_INCREMENT | DEFAULT (literal | expr) | COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT) | STORAGE (DISK | MEMORY | DEFAULT) ; generatedDataType_ : commonDataTypeOption_ | (GENERATED ALWAYS)? AS expr | (VIRTUAL | STORED) ; commonDataTypeOption_ : primaryKey | UNIQUE KEY? | NOT? NULL | collateClause_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_ ; referenceDefinition_ : REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)* ; referenceOption_ : RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT ; constraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_) ; primaryKeyOption_ : primaryKey indexType? columnNames indexOption* ; uniqueOption_ : UNIQUE (INDEX | KEY)? indexName? indexType? keyParts_ indexOption* ; foreignKeyOption_ : FOREIGN KEY indexName? columnNames referenceDefinition_ ; indexDefinition_ : (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType? keyParts_ indexOption* ; keyParts_ : LP_ keyPart_ (COMMA_ keyPart_)* RP_ ; keyPart_ : columnName (LP_ NUMBER_ RP_)? (ASC | DESC)? ; checkConstraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)? ; createLike_ : LIKE tableName | LP_ LIKE tableName RP_ ; alterTable : ALTER TABLE tableName alterSpecifications_? ; alterSpecifications_ : alterSpecification_ (COMMA_ alterSpecification_)* ; alterSpecification_ : tableOptions_ | addColumn | addIndex | addConstraint | ALGORITHM EQ_? (DEFAULT | INPLACE | COPY) | ALTER COLUMN? columnName (SET DEFAULT | DROP DEFAULT) | changeColumn | DEFAULT? characterSet_ collateClause_? | CONVERT TO characterSet_ collateClause_? | (DISABLE | ENABLE) KEYS | (DISCARD | IMPORT_) TABLESPACE | dropColumn | dropIndexDef | dropPrimaryKey | DROP FOREIGN KEY ignoredIdentifier_ | FORCE | LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE) | modifyColumn | ORDER BY columnName (COMMA_ columnName)* | renameIndex | renameTable | (WITHOUT | WITH) VALIDATION | ADD PARTITION partitionDefinitions_ | 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 ; singleColumn : columnDefinition firstOrAfterColumn? ; firstOrAfterColumn : FIRST | AFTER columnName ; multiColumn : LP_ columnDefinition (COMMA_ columnDefinition)* RP_ ; addConstraint : ADD constraintDefinition_ ; addIndex : ADD indexDefinition_ ; addColumn : ADD COLUMN? (singleColumn | multiColumn) ; changeColumn : changeColumnOp columnName columnDefinition firstOrAfterColumn? ; changeColumnOp : CHANGE COLUMN? ; dropColumn : DROP COLUMN? columnName ; dropIndexDef : DROP (INDEX | KEY) indexName ; dropPrimaryKey : DROP primaryKey ; modifyColumn : MODIFY COLUMN? columnDefinition firstOrAfterColumn? ; renameIndex : RENAME (INDEX | KEY) indexName TO indexName ; renameTable : RENAME (TO | AS)? tableName ; 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_? tableNames_ ; tableNames_ : LP_ tableName (COMMA_ tableName)* RP_ ; partitionOptions_ : PARTITION BY (linearPartition_ | rangeOrListPartition_) (PARTITIONS NUMBER_)? (SUBPARTITION BY linearPartition_ (SUBPARTITIONS NUMBER_)?)? (LP_ partitionDefinitions_ RP_)? ; linearPartition_ : LINEAR? (HASH (yearFunctionExpr_ | expr) | KEY (ALGORITHM EQ_ NUMBER_)? columnNames) ; yearFunctionExpr_ : LP_ YEAR expr RP_ ; rangeOrListPartition_ : (RANGE | LIST) (expr | COLUMNS columnNames) ; partitionDefinitions_ : partitionDefinition_ (COMMA_ partitionDefinition_)* ; partitionDefinition_ : PARTITION ignoredIdentifier_ (VALUES (lessThanPartition_ | IN assignmentValueList))? partitionDefinitionOption_* (LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)? ; partitionDefinitionOption_ : STORAGE? ENGINE EQ_? ignoredIdentifier_ | COMMENT EQ_? STRING_ | DATA DIRECTORY EQ_? STRING_ | INDEX DIRECTORY EQ_? STRING_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | TABLESPACE EQ_? ignoredIdentifier_ ; lessThanPartition_ : LESS THAN (LP_ (expr | assignmentValues) RP_ | MAXVALUE) ; subpartitionDefinition_ : SUBPARTITION ignoredIdentifier_ partitionDefinitionOption_* ; dropTable : DROP TEMPORARY? TABLE (IF EXISTS)? tableName (COMMA_ tableName)* ; truncateTable : TRUNCATE TABLE? tableName ; createIndex : CREATE (UNIQUE | FULLTEXT | SPATIAL)? INDEX indexName indexType? ON tableName ; dropIndex : DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName ;
refactor dataType
refactor dataType
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
4347fadb027299a32fd61a18d0a34bb082523775
newton.g4
newton.g4
grammar newton; tokens { INDENT, DEDENT } @lexer::header { import com.yuvalshavit.antlr4.DenterHelper; } @lexer::members { private final DenterHelper newtonDenter = new DenterHelper(NL, newtonParser.INDENT, newtonParser.DEDENT) { @Override public Token pullToken() { return newtonLexer.super.nextToken(); } }; @Override public Token nextToken() { return newtonDenter.nextToken(); } } file : structures | COMMENT ; structures : array | object ; array : ( DASH value )+ ; value : ( ID | INT ) NL | object ; object : ( pair NL? )+ ; pair : ID COLON ( ID | INDENT? array+ DEDENT? | CLOSED_PAR | INDENT? ( object ) DEDENT? ) ; DASH : '-' ; COLON : ': ' ; CLOSED_PAR : '{}' ; COMMENT : '#' .*? NL -> skip ; ID : [a-zA-Z]+ ; INT : [0-9]+ ; NL : ('\r'?'\n''\t'*) ; WS : ' ' -> skip ;
grammar newton; tokens { INDENT, DEDENT } @lexer::header { import com.yuvalshavit.antlr4.DenterHelper; } @lexer::members { private final DenterHelper newtonDenter = new DenterHelper(NL, newtonParser.INDENT, newtonParser.DEDENT) { @Override public Token pullToken() { return newtonLexer.super.nextToken(); } }; @Override public Token nextToken() { return newtonDenter.nextToken(); } } file : structures | COMMENT ; structures : array | object ; array : ( DASH value )+ ; value : ( ID | NUMBER ) NL | object ; object : ( pair NL? )+ ; pair : ID COLON ( ( ID | NUMBER ) | INDENT? array+ DEDENT? | CLOSED_PAR | INDENT? ( object ) DEDENT? ) ; DASH : '-' ; COLON : ': ' ; CLOSED_PAR : '{}' ; COMMENT : '#' .*? NL -> skip ; ID : [a-z_A-Z' ']+ ; NUMBER : REAL | HEX | OCTAL ; REAL : [0-9]+ ( '.' [0-9]+ )* ; HEX : '0x' [0-9A-Fa-f]+ ; OCTAL : '0c' [0-7]+ ; NL : ('\r'?'\n''\t'*) ; WS : ' ' -> skip ;
support for real, octal and hex numbers
support for real, octal and hex numbers
ANTLR
mit
Khushmeet/newton,Khushmeet/newton
83dac658158a88e90cb5e75ab75669b419406309
jkind/src/jkind/lustre/parsing/Lustre.g4
jkind/src/jkind/lustre/parsing/Lustre.g4
grammar Lustre; program: (typedef | constant | node)* EOF; typedef: 'type' ID '=' topLevelType ';'; constant: 'const' ID (':' type)? '=' expr ';'; node: 'node' ID '(' input=varDeclList? ')' 'returns' '(' output=varDeclList? ')' ';' ('var' local=varDeclList ';')? 'let' (equation | property | assertion | main)* 'tel' ';'? ; varDeclList: varDeclGroup (';' varDeclGroup)*; varDeclGroup: ID (',' ID)* ':' type; topLevelType: type # plainType | 'struct' '{' (ID ':' type) (';' ID ':' type)* '}' # recordType ; type: 'int' # intType | 'subrange' '[' bound ',' bound ']' 'of' 'int' # subrangeType | 'bool' # boolType | 'real' # realType | type '[' INT ']' # arrayType | ID # userType ; bound: '-'? INT; property: '--%PROPERTY' ID ';'; main: '--%MAIN' ';'?; assertion: 'assert' expr ';'; equation: (lhs | '(' lhs ')') '=' expr ';' | expr ';' ; lhs: ID (',' ID)*; expr: ID # idExpr | INT # intExpr | REAL # realExpr | BOOL # boolExpr | op=('real' | 'floor') '(' expr ')' # castExpr | ID '(' (expr (',' expr)*)? ')' # nodeCallExpr | 'condact' '(' expr (',' expr)+ ')' # condactExpr | expr '.' ID # recordAccessExpr | expr '{' ID ':=' expr '}' # recordUpdateExpr | expr '[' expr ']' # arrayAccessExpr | expr '[' expr ':=' expr ']' # arrayUpdateExpr | 'pre' expr # preExpr | 'not' expr # notExpr | '-' expr # negateExpr | expr op=('*' | '/' | 'div' | 'mod') expr # binaryExpr | expr op=('+' | '-') expr # binaryExpr | expr op=('<' | '<=' | '>' | '>=' | '=' | '<>') expr # binaryExpr | expr op='and' expr # binaryExpr | expr op=('or' | 'xor') expr # binaryExpr | expr op='=>'<assoc=right> expr # binaryExpr | expr op='->'<assoc=right> expr # binaryExpr | 'if' expr 'then' expr 'else' expr # ifThenElseExpr | ID '{' ID '=' expr (';' ID '=' expr)* '}' # recordExpr | '[' expr (',' expr)* ']' # arrayExpr | '(' expr (',' expr)+ ')' # tupleExpr | '(' expr ')' # parenExpr ; REAL: INT '.' INT; BOOL: 'true' | 'false'; INT: [0-9]+; ID: [a-zA-Z_][a-zA-Z_0-9]*; WS: [ \t\n\r\f]+ -> skip; SL_COMMENT: '--' (~[%\n\r] ~[\n\r]* | /* empty */) ('\r'? '\n')? -> skip; ML_COMMENT: '/*' .*? '*/' -> skip; ERROR: .;
grammar Lustre; program: (typedef | constant | node)* EOF; typedef: 'type' ID '=' topLevelType ';'; constant: 'const' ID (':' type)? '=' expr ';'; node: 'node' ID '(' input=varDeclList? ')' 'returns' '(' output=varDeclList? ')' ';' ('var' local=varDeclList ';')? 'let' (equation | property | assertion | main)* 'tel' ';'? ; varDeclList: varDeclGroup (';' varDeclGroup)*; varDeclGroup: ID (',' ID)* ':' type; topLevelType: type # plainType | 'struct' '{' (ID ':' type) (';' ID ':' type)* '}' # recordType ; type: 'int' # intType | 'subrange' '[' bound ',' bound ']' 'of' 'int' # subrangeType | 'bool' # boolType | 'real' # realType | type '[' INT ']' # arrayType | ID # userType ; bound: '-'? INT; property: '--%PROPERTY' ID ';'; main: '--%MAIN' ';'?; assertion: 'assert' expr ';'; equation: (lhs | '(' lhs ')') '=' expr ';' | expr ';' ; lhs: ID (',' ID)*; expr: ID # idExpr | INT # intExpr | REAL # realExpr | BOOL # boolExpr | op=('real' | 'floor') '(' expr ')' # castExpr | ID '(' (expr (',' expr)*)? ')' # nodeCallExpr | 'condact' '(' expr (',' expr)+ ')' # condactExpr | expr '.' ID # recordAccessExpr | expr '{' ID ':=' expr '}' # recordUpdateExpr | expr '[' expr ']' # arrayAccessExpr | expr '[' expr ':=' expr ']' # arrayUpdateExpr | 'pre' expr # preExpr | 'not' expr # notExpr | '-' expr # negateExpr | expr op=('*' | '/' | 'div' | 'mod') expr # binaryExpr | expr op=('+' | '-') expr # binaryExpr | expr op=('<' | '<=' | '>' | '>=' | '=' | '<>') expr # binaryExpr | expr op='and' expr # binaryExpr | expr op=('or' | 'xor') expr # binaryExpr | expr op='=>'<assoc=right> expr # binaryExpr | expr op='->'<assoc=right> expr # binaryExpr | 'if' expr 'then' expr 'else' expr # ifThenElseExpr | ID '{' ID '=' expr (';' ID '=' expr)* '}' # recordExpr | '[' expr (',' expr)* ']' # arrayExpr | '(' expr (',' expr)+ ')' # tupleExpr | '(' expr ')' # parenExpr ; REAL: INT '.' INT; BOOL: 'true' | 'false'; INT: [0-9]+; ID: [a-zA-Z_][a-zA-Z_0-9]*; WS: [ \t\n\r\f]+ -> skip; SL_COMMENT: '--' (~[%\n\r] ~[\n\r]* | /* empty */) ('\r'? '\n')? -> skip; ML_COMMENT: '/*' .*? '*/' -> skip; ERROR: .;
Change tabs to spaces
Change tabs to spaces
ANTLR
bsd-3-clause
backesj/jkind,lgwagner/jkind,andrewkatis/jkind-1,agacek/jkind,agacek/jkind,lgwagner/jkind,backesj/jkind,andrewkatis/jkind-1
072f93e6feb86b55fc4151a6d9585e41688d0d0c
sharding-core/src/main/antlr4/io/shardingsphere/core/parsing/antlr/autogen/PostgreSQLStatement.g4
sharding-core/src/main/antlr4/io/shardingsphere/core/parsing/antlr/autogen/PostgreSQLStatement.g4
grammar PostgreSQLStatement; import PostgreSQLKeyword, Keyword, PostgreSQLBase, PostgreSQLCreateIndex, PostgreSQLAlterIndex , PostgreSQLDropIndex, PostgreSQLCreateTable, PostgreSQLAlterTable, PostgreSQLDropTable, PostgreSQLTruncateTable , PostgreSQLTCLStatement, PostgreSQLDCLStatement ; execute : createIndex | alterIndex | dropIndex | createTable | alterTable | dropTable | truncateTable | setTransaction | commit | rollback | savepoint | beginWork | grant | grantRole | revoke | revokeRole | createUser | alterUser | renameUser | alterUserSetConfig | alterUserResetConfig | dropUser | createRole | alterRole | renameRole | alterRoleSetConfig | alterRoleResetConfig ;
grammar PostgreSQLStatement; import PostgreSQLKeyword, Keyword, PostgreSQLBase, PostgreSQLCreateIndex, PostgreSQLAlterIndex , PostgreSQLDropIndex, PostgreSQLCreateTable, PostgreSQLAlterTable, PostgreSQLDropTable, PostgreSQLTruncateTable , PostgreSQLTCLStatement, PostgreSQLDCLStatement ; execute : createIndex | alterIndex | dropIndex | createTable | alterTable | dropTable | truncateTable | setTransaction | commit | rollback | savepoint | beginWork | grant | grantRole | revoke | revokeRole | createUser | alterUser | renameUser | alterUserSetConfig | alterUserResetConfig | dropUser | createRole | alterRole | renameRole | alterRoleSetConfig | alterRoleResetConfig | dropRole ;
add postgre drop role rule
add postgre drop role rule
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
15d842d5b51d9f34c104aee0a600732666552d6d
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 ;
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 ; revokeObjectPrivileges : objectPrivilege (COMMA objectPrivilege)* onObjectClause FROM grantees (CASCADE CONSTRAINTS | FORCE)? ;
add revokeObjectPrivileges
add revokeObjectPrivileges
ANTLR
apache-2.0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
bed06b8418dac00dcb24d6d12628ed6d6dc864d8
pattern_grammar/STIXPattern.g4
pattern_grammar/STIXPattern.g4
// This is an ANTLR4 grammar for the STIX Patterning Language. // // http://docs.oasis-open.org/cti/stix/v2.0/stix-v2.0-part5-stix-patterning.html grammar STIXPattern; pattern : observationExpressions ; observationExpressions : <assoc=left> observationExpressions FOLLOWEDBY observationExpressions | observationExpressionOr ; observationExpressionOr : <assoc=left> observationExpressionOr OR observationExpressionOr | observationExpressionAnd ; observationExpressionAnd : <assoc=left> observationExpressionAnd AND observationExpressionAnd | observationExpression ; observationExpression : LBRACK comparisonExpression RBRACK # observationExpressionSimple | LPAREN observationExpressions RPAREN # observationExpressionCompound | observationExpression startStopQualifier # observationExpressionStartStop | observationExpression withinQualifier # observationExpressionWithin | observationExpression repeatedQualifier # observationExpressionRepeated ; comparisonExpression : <assoc=left> comparisonExpression OR comparisonExpression | comparisonExpressionAnd ; comparisonExpressionAnd : <assoc=left> comparisonExpressionAnd AND comparisonExpressionAnd | propTest ; propTest : objectPath NOT? (EQ|NEQ) primitiveLiteral # propTestEqual | objectPath NOT? (GT|LT|GE|LE) orderableLiteral # propTestOrder | objectPath NOT? IN setLiteral # propTestSet | objectPath NOT? LIKE StringLiteral # propTestLike | objectPath NOT? MATCHES StringLiteral # propTestRegex | objectPath NOT? ISSUBSET StringLiteral # propTestIsSubset | objectPath NOT? ISSUPERSET StringLiteral # propTestIsSuperset | LPAREN comparisonExpression RPAREN # propTestParen ; startStopQualifier : START StringLiteral STOP StringLiteral ; withinQualifier : WITHIN (IntLiteral|FloatLiteral) SECONDS ; repeatedQualifier : REPEATS IntLiteral TIMES ; objectPath : objectType COLON firstPathComponent objectPathComponent? ; objectType : IdentifierWithoutHyphen | IdentifierWithHyphen ; firstPathComponent : IdentifierWithoutHyphen | StringLiteral ; objectPathComponent : <assoc=left> objectPathComponent objectPathComponent # pathStep | '.' (IdentifierWithoutHyphen | StringLiteral) # keyPathStep | LBRACK (IntLiteral|ASTERISK) RBRACK # indexPathStep ; setLiteral : LPAREN RPAREN | LPAREN primitiveLiteral (COMMA primitiveLiteral)* RPAREN ; primitiveLiteral : orderableLiteral | BoolLiteral ; orderableLiteral : IntLiteral | FloatLiteral | StringLiteral | BinaryLiteral | HexLiteral | TimestampLiteral ; IntLiteral : [+-]? ('0' | [1-9] [0-9]*) ; FloatLiteral : [+-]? [0-9]* '.' [0-9]+ ; HexLiteral : 'h' QUOTE TwoHexDigits* QUOTE ; BinaryLiteral : 'b' QUOTE Base64Char* QUOTE ; StringLiteral : QUOTE ( ~['\\] | '\\\'' | '\\\\' )* QUOTE ; BoolLiteral : TRUE | FALSE ; TimestampLiteral : 't' QUOTE [0-9] [0-9] [0-9] [0-9] HYPHEN [0-9] [0-9] HYPHEN [0-9] [0-9] 'T' [0-9] [0-9] COLON [0-9] [0-9] COLON [0-9] [0-9] (DOT [0-9]+)? 'Z' QUOTE ; ////////////////////////////////////////////// // Keywords AND: A N D; OR: O R; NOT: N O T; FOLLOWEDBY: F O L L O W E D B Y; LIKE: L I K E ; MATCHES: M A T C H E S ; ISSUPERSET: I S S U P E R S E T ; ISSUBSET: I S S U B S E T ; LAST: L A S T ; IN: I N; START: S T A R T ; STOP: S T O P ; SECONDS: S E C O N D S; TRUE: T R U E; FALSE: F A L S E; WITHIN: W I T H I N; REPEATS: R E P E A T S; TIMES: T I M E S; // After keywords, so the lexer doesn't tokenize them as identifiers. // Object types may have unquoted hyphens, but property names // (in object paths) cannot. IdentifierWithoutHyphen : [a-zA-Z_] [a-zA-Z0-9_]* ; IdentifierWithHyphen : [a-zA-Z_] [a-zA-Z0-9_-]* ; EQ : '=' | '=='; NEQ : '!=' | '<>'; LT : '<'; LE : '<='; GT : '>'; GE : '>='; QUOTE : '\''; COLON : ':' ; DOT : '.' ; COMMA : ',' ; RPAREN : ')' ; LPAREN : '(' ; RBRACK : ']' ; LBRACK : '[' ; PLUS : '+' ; HYPHEN : MINUS ; MINUS : '-' ; POWER_OP : '^' ; DIVIDE : '/' ; ASTERISK : '*'; fragment A: [aA]; fragment B: [bB]; fragment C: [cC]; fragment D: [dD]; fragment E: [eE]; fragment F: [fF]; fragment G: [gG]; fragment H: [hH]; fragment I: [iI]; fragment J: [jJ]; fragment K: [kK]; fragment L: [lL]; fragment M: [mM]; fragment N: [nN]; fragment O: [oO]; fragment P: [pP]; fragment Q: [qQ]; fragment R: [rR]; fragment S: [sS]; fragment T: [tT]; fragment U: [uU]; fragment V: [vV]; fragment W: [wW]; fragment X: [xX]; fragment Y: [yY]; fragment Z: [zZ]; fragment HexDigit: [A-Fa-f0-9]; fragment TwoHexDigits: HexDigit HexDigit; fragment Base64Char: [A-Za-z0-9+/=]; // Whitespace and comments // WS : [ \t\r\n\u000B\u000C\u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+ -> skip ; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '//' ~[\r\n]* -> skip ;
// This is an ANTLR4 grammar for the STIX Patterning Language. // // http://docs.oasis-open.org/cti/stix/v2.0/stix-v2.0-part5-stix-patterning.html grammar STIXPattern; pattern : observationExpressions ; observationExpressions : <assoc=left> observationExpressions FOLLOWEDBY observationExpressions | observationExpressionOr ; observationExpressionOr : <assoc=left> observationExpressionOr OR observationExpressionOr | observationExpressionAnd ; observationExpressionAnd : <assoc=left> observationExpressionAnd AND observationExpressionAnd | observationExpression ; observationExpression : LBRACK comparisonExpression RBRACK # observationExpressionSimple | LPAREN observationExpressions RPAREN # observationExpressionCompound | observationExpression startStopQualifier # observationExpressionStartStop | observationExpression withinQualifier # observationExpressionWithin | observationExpression repeatedQualifier # observationExpressionRepeated ; comparisonExpression : <assoc=left> comparisonExpression OR comparisonExpression | comparisonExpressionAnd ; comparisonExpressionAnd : <assoc=left> comparisonExpressionAnd AND comparisonExpressionAnd | propTest ; propTest : objectPath NOT? (EQ|NEQ) primitiveLiteral # propTestEqual | objectPath NOT? (GT|LT|GE|LE) orderableLiteral # propTestOrder | objectPath NOT? IN setLiteral # propTestSet | objectPath NOT? LIKE StringLiteral # propTestLike | objectPath NOT? MATCHES StringLiteral # propTestRegex | objectPath NOT? ISSUBSET StringLiteral # propTestIsSubset | objectPath NOT? ISSUPERSET StringLiteral # propTestIsSuperset | LPAREN comparisonExpression RPAREN # propTestParen ; startStopQualifier : START StringLiteral STOP StringLiteral ; withinQualifier : WITHIN (IntLiteral|FloatLiteral) SECONDS ; repeatedQualifier : REPEATS IntLiteral TIMES ; objectPath : objectType COLON firstPathComponent objectPathComponent? ; objectType : IdentifierWithoutHyphen | IdentifierWithHyphen ; firstPathComponent : IdentifierWithoutHyphen | StringLiteral ; objectPathComponent : <assoc=left> objectPathComponent objectPathComponent # pathStep | '.' (IdentifierWithoutHyphen | StringLiteral) # keyPathStep | LBRACK (IntLiteral|ASTERISK) RBRACK # indexPathStep ; setLiteral : LPAREN RPAREN | LPAREN primitiveLiteral (COMMA primitiveLiteral)* RPAREN ; primitiveLiteral : orderableLiteral | BoolLiteral ; orderableLiteral : IntLiteral | FloatLiteral | StringLiteral | BinaryLiteral | HexLiteral | TimestampLiteral ; IntLiteral : [+-]? ('0' | [1-9] [0-9]*) ; FloatLiteral : [+-]? [0-9]* '.' [0-9]+ ; HexLiteral : 'h' QUOTE TwoHexDigits* QUOTE ; BinaryLiteral : 'b' QUOTE Base64Char* QUOTE ; StringLiteral : QUOTE ( ~['\\] | '\\\'' | '\\\\' )* QUOTE ; BoolLiteral : TRUE | FALSE ; TimestampLiteral : 't' QUOTE [0-9] [0-9] [0-9] [0-9] HYPHEN [0-9] [0-9] HYPHEN [0-9] [0-9] 'T' [0-9] [0-9] COLON [0-9] [0-9] COLON [0-9] [0-9] (DOT [0-9]+)? 'Z' QUOTE ; ////////////////////////////////////////////// // Keywords AND: A N D; OR: O R; NOT: N O T; FOLLOWEDBY: F O L L O W E D B Y; LIKE: L I K E ; MATCHES: M A T C H E S ; ISSUPERSET: I S S U P E R S E T ; ISSUBSET: I S S U B S E T ; LAST: L A S T ; IN: I N; START: S T A R T ; STOP: S T O P ; SECONDS: S E C O N D S; TRUE: T R U E; FALSE: F A L S E; WITHIN: W I T H I N; REPEATS: R E P E A T S; TIMES: T I M E S; // After keywords, so the lexer doesn't tokenize them as identifiers. // Object types may have unquoted hyphens, but property names // (in object paths) cannot. IdentifierWithoutHyphen : [a-zA-Z_] [a-zA-Z0-9_]* ; IdentifierWithHyphen : [a-zA-Z_] [a-zA-Z0-9_-]* ; EQ : '=' | '=='; NEQ : '!=' | '<>'; LT : '<'; LE : '<='; GT : '>'; GE : '>='; QUOTE : '\''; COLON : ':' ; DOT : '.' ; COMMA : ',' ; RPAREN : ')' ; LPAREN : '(' ; RBRACK : ']' ; LBRACK : '[' ; PLUS : '+' ; HYPHEN : MINUS ; MINUS : '-' ; POWER_OP : '^' ; DIVIDE : '/' ; ASTERISK : '*'; fragment A: [aA]; fragment B: [bB]; fragment C: [cC]; fragment D: [dD]; fragment E: [eE]; fragment F: [fF]; fragment G: [gG]; fragment H: [hH]; fragment I: [iI]; fragment J: [jJ]; fragment K: [kK]; fragment L: [lL]; fragment M: [mM]; fragment N: [nN]; fragment O: [oO]; fragment P: [pP]; fragment Q: [qQ]; fragment R: [rR]; fragment S: [sS]; fragment T: [tT]; fragment U: [uU]; fragment V: [vV]; fragment W: [wW]; fragment X: [xX]; fragment Y: [yY]; fragment Z: [zZ]; fragment HexDigit: [A-Fa-f0-9]; fragment TwoHexDigits: HexDigit HexDigit; fragment Base64Char: [A-Za-z0-9+/=]; // Whitespace and comments // WS : [ \t\r\n\u000B\u000C\u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+ -> skip ; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '//' ~[\r\n]* -> skip ; // Catch-all to prevent lexer from silently eating unusable characters. InvalidCharacter : . ;
Add catch-all for unusable characters
Add catch-all for unusable characters
ANTLR
bsd-3-clause
oasis-open/cti-stix2-json-schemas
c3a16ad164120028bbd5cfb395d5ef169fb5d5d8
ShExDoc.g4
ShExDoc.g4
// ANTLR4 Equivalent of accompanying bnf, developed in // http://www.w3.org/2005/01/yacker/uploads/ShEx3 // Updated to Jul 27 AM ShEx3 // Updated to Aug 23 AM ShEx3 (last change was EGP 20150820) // Sept 21 AM disallow single internal unary (e.g. {(:p .{2}){3}} // Change (non-standard) "codeLabel" to "productionName" // Oct 26 - change annotation predicate to include rdftype (how did this slip in to the production rules? // Dec 30 - update to match http://www.w3.org/2005/01/yacker/uploads/ShEx2/bnf with last change "EGP 20151120" // May 23, 2016 - Update to match http://www.w3.org/2005/01/yacker/uploads/ShEx2/bnf with last change "EGP20160520" AND ';' separator and '//' for annotations // May 24, 2016 - EGP20150424 // Aug 11, 2016 - EGP20160708 // Sep 14, 2016 - Revised to match Eric's latest reshuffle // Sep 24, 2016 - Switched to TT grammar (vs inner and outer shapes) // Sep 26, 2016 - Refactored to match https://raw.githubusercontent.com/shexSpec/shex.js/7eb770fe2b5bab9edfe9558dc07bb6f6dcdf5d23/doc/bnf // Oct 27, 2016 - Added comments to '*', '*' and '?' to facilitate parsing // Oct 27, 2016 - Added qualifier rule to be reused by shapeDefinition and inlineShapeDefinition // Oct 27, 2016 - Added negation rule // Mar 03, 2017 - removed ^^-style facet arguments per shex#41 // Mar 03, 2017 - switch to ~/regexp/ // Apr 09, 2017 - removed WS fragment (unused) // Apr 09, 2017 - revise REGEXP definition // Apr 09, 2017 - factor out REGEXP_FLAGS so we don't have to parse them out // Apr 09, 2017 - literalRange / languageRange additions // Apr 09, 2017 - factor out shapeRef to match spec // Apr 09, 2017 - update repeatRange to allow differentiation of {INTEGER} and {INTEGER,} // Apr 09, 2017 - add STEM_MARK and UNBOUNDED tokens to eliminate lex token parsing grammar ShExDoc; shExDoc : directive* ((notStartAction | startActions) statement*)? EOF; // leading CODE directive : baseDecl | prefixDecl ; baseDecl : KW_BASE IRIREF ; prefixDecl : KW_PREFIX PNAME_NS IRIREF ; notStartAction : start | shapeExprDecl ; start : KW_START '=' shapeExpression ; startActions : codeDecl+ ; statement : directive | notStartAction ; shapeExprDecl : shapeExprLabel (shapeExpression | KW_EXTERNAL) ; shapeExpression : shapeOr ; shapeOr : shapeAnd (KW_OR shapeAnd)* ; shapeAnd : shapeNot (KW_AND shapeNot)* ; shapeNot : negation? shapeAtom ; negation : KW_NOT | '!' ; inlineShapeExpression : inlineShapeOr ; inlineShapeOr : inlineShapeAnd (KW_OR inlineShapeAnd)* ; inlineShapeAnd : inlineShapeNot (KW_AND inlineShapeNot)* ; inlineShapeNot : negation? inlineShapeAtom ; inlineShapeDefinition : qualifier* '{' oneOfShape? '}' ; shapeDefinition : qualifier* '{' oneOfShape? '}' annotation* semanticActions ; qualifier : includeSet | extraPropertySet | KW_CLOSED ; extraPropertySet : KW_EXTRA predicate+ ; oneOfShape : groupShape | multiElementOneOf ; multiElementOneOf : groupShape ( '|' groupShape)+ ; innerShape : multiElementGroup | multiElementOneOf ; groupShape : singleElementGroup | multiElementGroup ; singleElementGroup : unaryShape ';'? ; multiElementGroup : unaryShape (';' unaryShape)+ ';'? ; unaryShape : ('$' tripleExprLabel)? (tripleConstraint | encapsulatedShape) | include ; encapsulatedShape : '(' innerShape ')' cardinality? annotation* semanticActions ; shapeAtom : nodeConstraint shapeOrRef? # shapeAtomNodeConstraint | shapeOrRef # shapeAtomShapeOrRef | '(' shapeExpression ')' # shapeAtomShapeExpression | '.' # shapeAtomAny // no constraint ; inlineShapeAtom : nodeConstraint inlineShapeOrRef? # inlineShapeAtomNodeConstraint | inlineShapeOrRef nodeConstraint? # inlineShapeAtomShapeOrRef | '(' shapeExpression ')' # inlineShapeAtomShapeExpression | '.' # inlineShapeAtomAny // no constraint ; nodeConstraint : KW_LITERAL xsFacet* # nodeConstraintLiteral | nonLiteralKind stringFacet* # nodeConstraintNonLiteral | datatype xsFacet* # nodeConstraintDatatype | valueSet xsFacet* # nodeConstraintValueSet | xsFacet+ # nodeConstraintFacet ; nonLiteralKind : KW_IRI | KW_BNODE | KW_NONLITERAL ; xsFacet : stringFacet | numericFacet; stringFacet : stringLength INTEGER | REGEXP REGEXP_FLAGS? ; stringLength : KW_LENGTH | KW_MINLENGTH | KW_MAXLENGTH; numericFacet : numericRange numericLiteral | numericLength INTEGER ; numericRange : KW_MININCLUSIVE | KW_MINEXCLUSIVE | KW_MAXINCLUSIVE | KW_MAXEXCLUSIVE ; numericLength : KW_TOTALDIGITS | KW_FRACTIONDIGITS ; tripleConstraint : senseFlags? predicate inlineShapeExpression cardinality? annotation* semanticActions ; senseFlags : '!' '^'? | '^' '!'? // inverse not ; valueSet : '[' valueSetValue* ']' ; valueSetValue : iriRange | literalRange | languageRange | '.' (iriExclusion+ | literalExclusion+ | languageExclusion+) ; iriRange : iri (STEM_MARK iriExclusion*)? ; iriExclusion : '-' iri STEM_MARK? ; literalRange : literal (STEM_MARK literalExclusion*)? ; literalExclusion : '-' literal STEM_MARK? ; languageRange : LANGTAG (STEM_MARK languageExclusion*)? ; languageExclusion : '-' LANGTAG STEM_MARK? ; literal : rdfLiteral | numericLiteral | booleanLiteral ; shapeOrRef : shapeDefinition | shapeRef ; inlineShapeOrRef : inlineShapeDefinition | shapeRef ; shapeRef : ATPNAME_LN | ATPNAME_NS | '@' shapeExprLabel ; include : '&' tripleExprLabel ; semanticActions : codeDecl* ; annotation : '//' predicate (iri | literal) ; // BNF: predicate ::= iri | RDF_TYPE predicate : iri | rdfType ; rdfType : RDF_TYPE ; datatype : iri ; cardinality : '*' # starCardinality | '+' # plusCardinality | '?' # optionalCardinality | repeatRange # repeatCardinality ; // BNF: REPEAT_RANGE ::= '{' INTEGER (',' (INTEGER | '*')?)? '}' repeatRange : '{' INTEGER '}' # exactRange | '{' INTEGER ',' (INTEGER | UNBOUNDED)? '}' # minMaxRange ; shapeExprLabel : iri | blankNode ; tripleExprLabel : iri | blankNode ; numericLiteral : INTEGER | DECIMAL | DOUBLE ; rdfLiteral : string (LANGTAG | '^^' datatype)? ; booleanLiteral : KW_TRUE | KW_FALSE ; string : STRING_LITERAL_LONG1 | STRING_LITERAL_LONG2 | STRING_LITERAL1 | STRING_LITERAL2 ; iri : IRIREF | prefixedName ; prefixedName : PNAME_LN | PNAME_NS ; blankNode : BLANK_NODE_LABEL ; codeDecl : '%' iri (CODE | '%') ; // Reserved for future use includeSet : '&' tripleExprLabel+ ; // Keywords KW_BASE : B A S E ; KW_EXTERNAL : E X T E R N A L ; KW_PREFIX : P R E F I X ; KW_START : S T A R T ; KW_VIRTUAL : V I R T U A L ; KW_CLOSED : C L O S E D ; KW_EXTRA : E X T R A ; KW_LITERAL : L I T E R A L ; KW_IRI : I R I ; KW_NONLITERAL : N O N L I T E R A L ; KW_BNODE : B N O D E ; KW_AND : A N D ; KW_OR : O R ; KW_MININCLUSIVE : M I N I N C L U S I V E ; KW_MINEXCLUSIVE : M I N E X C L U S I V E ; KW_MAXINCLUSIVE : M A X I N C L U S I V E ; KW_MAXEXCLUSIVE : M A X E X C L U S I V E ; KW_LENGTH : L E N G T H ; KW_MINLENGTH : M I N L E N G T H ; KW_MAXLENGTH : M A X L E N G T H ; KW_TOTALDIGITS : T O T A L D I G I T S ; KW_FRACTIONDIGITS : F R A C T I O N D I G I T S ; KW_NOT : N O T ; KW_TRUE : 'true' ; KW_FALSE : 'false' ; // terminals PASS : [ \t\r\n]+ -> skip; COMMENT : ('#' ~[\r\n]* | '/*' (~[*] | '*' ('\\/' | ~[/]))* '*/') -> skip; CODE : '{' (~[%\\] | '\\' [%\\] | UCHAR)* '%' '}' ; RDF_TYPE : 'a' ; IRIREF : '<' (~[\u0000-\u0020=<>"{}|^`\\] | UCHAR)* '>' ; /* #x00=NULL #01-#x1F=control codes #x20=space */ PNAME_NS : PN_PREFIX? ':' ; PNAME_LN : PNAME_NS PN_LOCAL ; ATPNAME_NS : '@' PN_PREFIX? ':' ; ATPNAME_LN : '@' PNAME_NS PN_LOCAL ; REGEXP : '/' (~[/\n\r\\] | '\\' [/nrt\\|.?*+(){}[\]$^-] | UCHAR)+ '/' ; REGEXP_FLAGS : [smix]+ ; 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) ; STEM_MARK : '~' ; UNBOUNDED : '*' ; fragment EXPONENT : [eE] [+-]? [0-9]+ ; STRING_LITERAL1 : '\'' (~[\u0027\u005C\u000A\u000D] | ECHAR | UCHAR)* '\'' ; /* #x27=' #x5C=\ #xA=new line #xD=carriage return */ STRING_LITERAL2 : '"' (~[\u0022\u005C\u000A\u000D] | ECHAR | UCHAR)* '"' ; /* #x22=" #x5C=\ #xA=new line #xD=carriage return */ STRING_LITERAL_LONG1 : '\'\'\'' (('\'' | '\'\'')? (~['\\] | ECHAR | UCHAR))* '\'\'\'' ; STRING_LITERAL_LONG2 : '"""' (('"' | '""')? (~["\\] | ECHAR | UCHAR))* '"""' ; fragment UCHAR : '\\u' HEX HEX HEX HEX | '\\U' HEX HEX HEX HEX HEX HEX HEX HEX ; fragment ECHAR : '\\' [tbnrf\\"'] ; fragment 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] ; fragment PN_CHARS_U : PN_CHARS_BASE | '_' ; fragment PN_CHARS : PN_CHARS_U | '-' | [0-9] | [\u00B7] | [\u0300-\u036F] | [\u203F-\u2040] ; fragment PN_PREFIX : PN_CHARS_BASE ((PN_CHARS | '.')* PN_CHARS)? ; fragment PN_LOCAL : (PN_CHARS_U | ':' | [0-9] | PLX) ((PN_CHARS | '.' | ':' | PLX)* (PN_CHARS | ':' | PLX))? ; fragment PLX : PERCENT | PN_LOCAL_ESC ; fragment PERCENT : '%' HEX HEX ; fragment HEX : [0-9] | [A-F] | [a-f] ; fragment PN_LOCAL_ESC : '\\' ('_' | '~' | '.' | '-' | '!' | '$' | '&' | '\'' | '(' | ')' | '*' | '+' | ',' | ';' | '=' | '/' | '?' | '#' | '@' | '%') ; 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');
// ANTLR4 Equivalent of accompanying bnf, developed in // http://www.w3.org/2005/01/yacker/uploads/ShEx3 // Updated to Jul 27 AM ShEx3 // Updated to Aug 23 AM ShEx3 (last change was EGP 20150820) // Sept 21 AM disallow single internal unary (e.g. {(:p .{2}){3}} // Change (non-standard) "codeLabel" to "productionName" // Oct 26 - change annotation predicate to include rdftype (how did this slip in to the production rules? // Dec 30 - update to match http://www.w3.org/2005/01/yacker/uploads/ShEx2/bnf with last change "EGP 20151120" // May 23, 2016 - Update to match http://www.w3.org/2005/01/yacker/uploads/ShEx2/bnf with last change "EGP20160520" AND ';' separator and '//' for annotations // May 24, 2016 - EGP20150424 // Aug 11, 2016 - EGP20160708 // Sep 14, 2016 - Revised to match Eric's latest reshuffle // Sep 24, 2016 - Switched to TT grammar (vs inner and outer shapes) // Sep 26, 2016 - Refactored to match https://raw.githubusercontent.com/shexSpec/shex.js/7eb770fe2b5bab9edfe9558dc07bb6f6dcdf5d23/doc/bnf // Oct 27, 2016 - Added comments to '*', '*' and '?' to facilitate parsing // Oct 27, 2016 - Added qualifier rule to be reused by shapeDefinition and inlineShapeDefinition // Oct 27, 2016 - Added negation rule // Mar 03, 2017 - removed ^^-style facet arguments per shex#41 // Mar 03, 2017 - switch to ~/regexp/ // Apr 09, 2017 - removed WS fragment (unused) // Apr 09, 2017 - revise REGEXP definition // Apr 09, 2017 - factor out REGEXP_FLAGS so we don't have to parse them out // Apr 09, 2017 - literalRange / languageRange additions // Apr 09, 2017 - factor out shapeRef to match spec // Apr 09, 2017 - update repeatRange to allow differentiation of {INTEGER} and {INTEGER,} // Apr 09, 2017 - add STEM_MARK and UNBOUNDED tokens to eliminate lex token parsing // Jun 10, 2018 - add empty language stem grammar ShExDoc; shExDoc : directive* ((notStartAction | startActions) statement*)? EOF; // leading CODE directive : baseDecl | prefixDecl ; baseDecl : KW_BASE IRIREF ; prefixDecl : KW_PREFIX PNAME_NS IRIREF ; notStartAction : start | shapeExprDecl ; start : KW_START '=' shapeExpression ; startActions : codeDecl+ ; statement : directive | notStartAction ; shapeExprDecl : shapeExprLabel (shapeExpression | KW_EXTERNAL) ; shapeExpression : shapeOr ; shapeOr : shapeAnd (KW_OR shapeAnd)* ; shapeAnd : shapeNot (KW_AND shapeNot)* ; shapeNot : negation? shapeAtom ; negation : KW_NOT | '!' ; inlineShapeExpression : inlineShapeOr ; inlineShapeOr : inlineShapeAnd (KW_OR inlineShapeAnd)* ; inlineShapeAnd : inlineShapeNot (KW_AND inlineShapeNot)* ; inlineShapeNot : negation? inlineShapeAtom ; inlineShapeDefinition : qualifier* '{' oneOfShape? '}' ; shapeDefinition : qualifier* '{' oneOfShape? '}' annotation* semanticActions ; qualifier : includeSet | extraPropertySet | KW_CLOSED ; extraPropertySet : KW_EXTRA predicate+ ; oneOfShape : groupShape | multiElementOneOf ; multiElementOneOf : groupShape ( '|' groupShape)+ ; innerShape : multiElementGroup | multiElementOneOf ; groupShape : singleElementGroup | multiElementGroup ; singleElementGroup : unaryShape ';'? ; multiElementGroup : unaryShape (';' unaryShape)+ ';'? ; unaryShape : ('$' tripleExprLabel)? (tripleConstraint | encapsulatedShape) | include ; encapsulatedShape : '(' innerShape ')' cardinality? annotation* semanticActions ; shapeAtom : nodeConstraint shapeOrRef? # shapeAtomNodeConstraint | shapeOrRef # shapeAtomShapeOrRef | '(' shapeExpression ')' # shapeAtomShapeExpression | '.' # shapeAtomAny // no constraint ; inlineShapeAtom : nodeConstraint inlineShapeOrRef? # inlineShapeAtomNodeConstraint | inlineShapeOrRef nodeConstraint? # inlineShapeAtomShapeOrRef | '(' shapeExpression ')' # inlineShapeAtomShapeExpression | '.' # inlineShapeAtomAny // no constraint ; nodeConstraint : KW_LITERAL xsFacet* # nodeConstraintLiteral | nonLiteralKind stringFacet* # nodeConstraintNonLiteral | datatype xsFacet* # nodeConstraintDatatype | valueSet xsFacet* # nodeConstraintValueSet | xsFacet+ # nodeConstraintFacet ; nonLiteralKind : KW_IRI | KW_BNODE | KW_NONLITERAL ; xsFacet : stringFacet | numericFacet; stringFacet : stringLength INTEGER | REGEXP REGEXP_FLAGS? ; stringLength : KW_LENGTH | KW_MINLENGTH | KW_MAXLENGTH; numericFacet : numericRange numericLiteral | numericLength INTEGER ; numericRange : KW_MININCLUSIVE | KW_MINEXCLUSIVE | KW_MAXINCLUSIVE | KW_MAXEXCLUSIVE ; numericLength : KW_TOTALDIGITS | KW_FRACTIONDIGITS ; tripleConstraint : senseFlags? predicate inlineShapeExpression cardinality? annotation* semanticActions ; senseFlags : '!' '^'? | '^' '!'? // inverse not ; valueSet : '[' valueSetValue* ']' ; valueSetValue : iriRange | literalRange | languageRange | '.' (iriExclusion+ | literalExclusion+ | languageExclusion+) ; iriRange : iri (STEM_MARK iriExclusion*)? ; iriExclusion : '-' iri STEM_MARK? ; literalRange : literal (STEM_MARK literalExclusion*)? ; literalExclusion : '-' literal STEM_MARK? ; languageRange : LANGTAG (STEM_MARK languageExclusion*)? | '@' '~' languageExclusion* ; languageExclusion : '-' LANGTAG STEM_MARK? ; literal : rdfLiteral | numericLiteral | booleanLiteral ; shapeOrRef : shapeDefinition | shapeRef ; inlineShapeOrRef : inlineShapeDefinition | shapeRef ; shapeRef : ATPNAME_LN | ATPNAME_NS | '@' shapeExprLabel ; include : '&' tripleExprLabel ; semanticActions : codeDecl* ; annotation : '//' predicate (iri | literal) ; // BNF: predicate ::= iri | RDF_TYPE predicate : iri | rdfType ; rdfType : RDF_TYPE ; datatype : iri ; cardinality : '*' # starCardinality | '+' # plusCardinality | '?' # optionalCardinality | repeatRange # repeatCardinality ; // BNF: REPEAT_RANGE ::= '{' INTEGER (',' (INTEGER | '*')?)? '}' repeatRange : '{' INTEGER '}' # exactRange | '{' INTEGER ',' (INTEGER | UNBOUNDED)? '}' # minMaxRange ; shapeExprLabel : iri | blankNode ; tripleExprLabel : iri | blankNode ; numericLiteral : INTEGER | DECIMAL | DOUBLE ; rdfLiteral : string (LANGTAG | '^^' datatype)? ; booleanLiteral : KW_TRUE | KW_FALSE ; string : STRING_LITERAL_LONG1 | STRING_LITERAL_LONG2 | STRING_LITERAL1 | STRING_LITERAL2 ; iri : IRIREF | prefixedName ; prefixedName : PNAME_LN | PNAME_NS ; blankNode : BLANK_NODE_LABEL ; codeDecl : '%' iri (CODE | '%') ; // Reserved for future use includeSet : '&' tripleExprLabel+ ; // Keywords KW_BASE : B A S E ; KW_EXTERNAL : E X T E R N A L ; KW_PREFIX : P R E F I X ; KW_START : S T A R T ; KW_VIRTUAL : V I R T U A L ; KW_CLOSED : C L O S E D ; KW_EXTRA : E X T R A ; KW_LITERAL : L I T E R A L ; KW_IRI : I R I ; KW_NONLITERAL : N O N L I T E R A L ; KW_BNODE : B N O D E ; KW_AND : A N D ; KW_OR : O R ; KW_MININCLUSIVE : M I N I N C L U S I V E ; KW_MINEXCLUSIVE : M I N E X C L U S I V E ; KW_MAXINCLUSIVE : M A X I N C L U S I V E ; KW_MAXEXCLUSIVE : M A X E X C L U S I V E ; KW_LENGTH : L E N G T H ; KW_MINLENGTH : M I N L E N G T H ; KW_MAXLENGTH : M A X L E N G T H ; KW_TOTALDIGITS : T O T A L D I G I T S ; KW_FRACTIONDIGITS : F R A C T I O N D I G I T S ; KW_NOT : N O T ; KW_TRUE : 'true' ; KW_FALSE : 'false' ; // terminals PASS : [ \t\r\n]+ -> skip; COMMENT : ('#' ~[\r\n]* | '/*' (~[*] | '*' ('\\/' | ~[/]))* '*/') -> skip; CODE : '{' (~[%\\] | '\\' [%\\] | UCHAR)* '%' '}' ; RDF_TYPE : 'a' ; IRIREF : '<' (~[\u0000-\u0020=<>"{}|^`\\] | UCHAR)* '>' ; /* #x00=NULL #01-#x1F=control codes #x20=space */ PNAME_NS : PN_PREFIX? ':' ; PNAME_LN : PNAME_NS PN_LOCAL ; ATPNAME_NS : '@' PN_PREFIX? ':' ; ATPNAME_LN : '@' PNAME_NS PN_LOCAL ; REGEXP : '/' (~[/\n\r\\] | '\\' [/nrt\\|.?*+(){}[\]$^-] | UCHAR)+ '/' ; REGEXP_FLAGS : [smix]+ ; 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) ; STEM_MARK : '~' ; UNBOUNDED : '*' ; fragment EXPONENT : [eE] [+-]? [0-9]+ ; STRING_LITERAL1 : '\'' (~[\u0027\u005C\u000A\u000D] | ECHAR | UCHAR)* '\'' ; /* #x27=' #x5C=\ #xA=new line #xD=carriage return */ STRING_LITERAL2 : '"' (~[\u0022\u005C\u000A\u000D] | ECHAR | UCHAR)* '"' ; /* #x22=" #x5C=\ #xA=new line #xD=carriage return */ STRING_LITERAL_LONG1 : '\'\'\'' (('\'' | '\'\'')? (~['\\] | ECHAR | UCHAR))* '\'\'\'' ; STRING_LITERAL_LONG2 : '"""' (('"' | '""')? (~["\\] | ECHAR | UCHAR))* '"""' ; fragment UCHAR : '\\u' HEX HEX HEX HEX | '\\U' HEX HEX HEX HEX HEX HEX HEX HEX ; fragment ECHAR : '\\' [tbnrf\\"'] ; fragment 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] ; fragment PN_CHARS_U : PN_CHARS_BASE | '_' ; fragment PN_CHARS : PN_CHARS_U | '-' | [0-9] | [\u00B7] | [\u0300-\u036F] | [\u203F-\u2040] ; fragment PN_PREFIX : PN_CHARS_BASE ((PN_CHARS | '.')* PN_CHARS)? ; fragment PN_LOCAL : (PN_CHARS_U | ':' | [0-9] | PLX) ((PN_CHARS | '.' | ':' | PLX)* (PN_CHARS | ':' | PLX))? ; fragment PLX : PERCENT | PN_LOCAL_ESC ; fragment PERCENT : '%' HEX HEX ; fragment HEX : [0-9] | [A-F] | [a-f] ; fragment PN_LOCAL_ESC : '\\' ('_' | '~' | '.' | '-' | '!' | '$' | '&' | '\'' | '(' | ')' | '*' | '+' | ',' | ';' | '=' | '/' | '?' | '#' | '@' | '%') ; 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');
add empty language stem
add empty language stem
ANTLR
mit
shexSpec/grammar,shexSpec/grammar,shexSpec/grammar
20ecd4ce119cd69c9d24f6c8e39f55e8a3c2abf1
golang/GoParser.g4
golang/GoParser.g4
/* [The "BSD licence"] Copyright (c) 2017 Sasa Coh, Michał Błotniak Copyright (c) 2019 Ivan Kochurkin, [email protected], Positive Technologies Copyright (c) 2019 Dmitry Rassadin, [email protected],Positive Technologies All rights reserved. Copyright (c) 2021 Martin Mirchev, [email protected] 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 Go grammar for ANTLR 4 derived from the Go Language Specification https://golang.org/ref/spec */ parser grammar GoParser; options { tokenVocab = GoLexer; superClass = GoParserBase; } sourceFile: packageClause eos (importDecl eos)* ( (functionDecl | methodDecl | declaration) eos )* EOF; packageClause: PACKAGE packageName = IDENTIFIER; importDecl: IMPORT (importSpec | L_PAREN (importSpec eos)* R_PAREN); importSpec: alias = (DOT | IDENTIFIER)? importPath; importPath: string_; declaration: constDecl | typeDecl | varDecl; constDecl: CONST (constSpec | L_PAREN (constSpec eos)* R_PAREN); constSpec: identifierList (type_? ASSIGN expressionList)?; identifierList: IDENTIFIER (COMMA IDENTIFIER)*; expressionList: expression (COMMA expression)*; typeDecl: TYPE (typeSpec | L_PAREN (typeSpec eos)* R_PAREN); typeSpec: IDENTIFIER ASSIGN? type_; // Function declarations functionDecl: FUNC IDENTIFIER (signature block?); methodDecl: FUNC receiver IDENTIFIER ( signature block?); receiver: parameters; varDecl: VAR (varSpec | L_PAREN (varSpec eos)* R_PAREN); varSpec: identifierList ( type_ (ASSIGN expressionList)? | ASSIGN expressionList ); block: L_CURLY statementList? R_CURLY; statementList: (eos? statement eos)+; statement: declaration | labeledStmt | simpleStmt | goStmt | returnStmt | breakStmt | continueStmt | gotoStmt | fallthroughStmt | block | ifStmt | switchStmt | selectStmt | forStmt | deferStmt; simpleStmt: sendStmt | incDecStmt | assignment | expressionStmt | shortVarDecl; expressionStmt: expression; sendStmt: channel = expression RECEIVE expression; incDecStmt: expression (PLUS_PLUS | MINUS_MINUS); assignment: expressionList assign_op expressionList; assign_op: ( PLUS | MINUS | OR | CARET | STAR | DIV | MOD | LSHIFT | RSHIFT | AMPERSAND | BIT_CLEAR )? ASSIGN; shortVarDecl: identifierList DECLARE_ASSIGN expressionList; emptyStmt: EOS | SEMI; labeledStmt: IDENTIFIER COLON statement?; returnStmt: RETURN expressionList?; breakStmt: BREAK IDENTIFIER?; continueStmt: CONTINUE IDENTIFIER?; gotoStmt: GOTO IDENTIFIER; fallthroughStmt: FALLTHROUGH; deferStmt: DEFER expression; ifStmt: IF ( expression | eos expression | simpleStmt eos expression ) block ( ELSE (ifStmt | block) )?; switchStmt: exprSwitchStmt | typeSwitchStmt; exprSwitchStmt: SWITCH (expression | ((simpleStmt? eos)? expression?)) L_CURLY exprCaseClause* R_CURLY; exprCaseClause: exprSwitchCase COLON statementList?; exprSwitchCase: CASE expressionList | DEFAULT; typeSwitchStmt: SWITCH ( typeSwitchGuard | eos typeSwitchGuard | simpleStmt eos typeSwitchGuard) L_CURLY typeCaseClause* R_CURLY; typeSwitchGuard: (IDENTIFIER DECLARE_ASSIGN)? primaryExpr DOT L_PAREN TYPE R_PAREN; typeCaseClause: typeSwitchCase COLON statementList?; typeSwitchCase: CASE typeList | DEFAULT; typeList: (type_ | NIL_LIT) (COMMA (type_ | NIL_LIT))*; selectStmt: SELECT L_CURLY commClause* R_CURLY; commClause: commCase COLON statementList?; commCase: CASE (sendStmt | recvStmt) | DEFAULT; recvStmt: (expressionList ASSIGN | identifierList DECLARE_ASSIGN)? recvExpr = expression; forStmt: FOR (expression | forClause | rangeClause)? block; forClause: initStmt = simpleStmt? eos expression? eos postStmt = simpleStmt?; rangeClause: ( expressionList ASSIGN | identifierList DECLARE_ASSIGN )? RANGE expression; goStmt: GO expression; type_: typeName | typeLit | L_PAREN type_ R_PAREN; typeName: qualifiedIdent | IDENTIFIER; typeLit: arrayType | structType | pointerType | functionType | interfaceType | sliceType | mapType | channelType; arrayType: L_BRACKET arrayLength R_BRACKET elementType; arrayLength: expression; elementType: type_; pointerType: STAR type_; interfaceType: INTERFACE L_CURLY ((methodSpec | typeName) eos)* R_CURLY; sliceType: L_BRACKET R_BRACKET elementType; // It's possible to replace `type` with more restricted typeLit list and also pay attention to nil maps mapType: MAP L_BRACKET type_ R_BRACKET elementType; channelType: (CHAN | CHAN RECEIVE | RECEIVE CHAN) elementType; methodSpec: {noTerminatorAfterParams(2)}? IDENTIFIER parameters result | IDENTIFIER parameters; functionType: FUNC signature; signature: {noTerminatorAfterParams(1)}? parameters result | parameters; result: parameters | type_; parameters: L_PAREN (parameterDecl (COMMA parameterDecl)* COMMA?)? R_PAREN; parameterDecl: identifierList? ELLIPSIS? type_; expression: primaryExpr | unaryExpr | expression mul_op = ( STAR | DIV | MOD | LSHIFT | RSHIFT | AMPERSAND | BIT_CLEAR ) expression | expression add_op = (PLUS | MINUS | OR | CARET) expression | expression rel_op = ( EQUALS | NOT_EQUALS | LESS | LESS_OR_EQUALS | GREATER | GREATER_OR_EQUALS ) expression | expression LOGICAL_AND expression | expression LOGICAL_OR expression; primaryExpr: operand | conversion | methodExpr | primaryExpr ( (DOT IDENTIFIER) | index | slice_ | typeAssertion | arguments ); unaryExpr: primaryExpr | unary_op = ( PLUS | MINUS | EXCLAMATION | CARET | STAR | AMPERSAND | RECEIVE ) expression; conversion: type_ L_PAREN expression COMMA? R_PAREN; operand: literal | operandName | L_PAREN expression R_PAREN; literal: basicLit | compositeLit | functionLit; basicLit: NIL_LIT | integer | string_ | FLOAT_LIT | IMAGINARY_LIT | RUNE_LIT; integer: DECIMAL_LIT | BINARY_LIT | OCTAL_LIT | HEX_LIT | IMAGINARY_LIT | RUNE_LIT; operandName: IDENTIFIER (DOT IDENTIFIER)?; qualifiedIdent: IDENTIFIER DOT IDENTIFIER; compositeLit: literalType literalValue; literalType: structType | arrayType | L_BRACKET ELLIPSIS R_BRACKET elementType | sliceType | mapType | typeName; literalValue: L_CURLY (elementList COMMA?)? R_CURLY; elementList: keyedElement (COMMA keyedElement)*; keyedElement: (key COLON)? element; key: IDENTIFIER | expression | literalValue; element: expression | literalValue; structType: STRUCT L_CURLY (fieldDecl eos)* R_CURLY; fieldDecl: ( {noTerminatorBetween(2)}? identifierList type_ | embeddedField ) tag = string_?; string_: RAW_STRING_LIT | INTERPRETED_STRING_LIT; embeddedField: STAR? typeName; functionLit: FUNC signature block; // function index: L_BRACKET expression R_BRACKET; slice_: L_BRACKET ( expression? COLON expression? | expression? COLON expression COLON expression ) R_BRACKET; typeAssertion: DOT L_PAREN type_ R_PAREN; arguments: L_PAREN ( (expressionList | type_ (COMMA expressionList)?) ELLIPSIS? COMMA? )? R_PAREN; methodExpr: receiverType DOT IDENTIFIER; //receiverType: typeName | '(' ('*' typeName | receiverType) ')'; receiverType: type_; eos: SEMI | EOF | EOS | {checkPreviousTokenText(")")}? | {checkPreviousTokenText("}")}? ;
/* [The "BSD licence"] Copyright (c) 2017 Sasa Coh, Michał Błotniak Copyright (c) 2019 Ivan Kochurkin, [email protected], Positive Technologies Copyright (c) 2019 Dmitry Rassadin, [email protected],Positive Technologies All rights reserved. Copyright (c) 2021 Martin Mirchev, [email protected] 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 Go grammar for ANTLR 4 derived from the Go Language Specification https://golang.org/ref/spec */ parser grammar GoParser; options { tokenVocab = GoLexer; superClass = GoParserBase; } sourceFile: packageClause eos (importDecl eos)* ( (functionDecl | methodDecl | declaration) eos )* EOF; packageClause: PACKAGE packageName = IDENTIFIER; importDecl: IMPORT (importSpec | L_PAREN (importSpec eos)* R_PAREN); importSpec: alias = (DOT | IDENTIFIER)? importPath; importPath: string_; declaration: constDecl | typeDecl | varDecl; constDecl: CONST (constSpec | L_PAREN (constSpec eos)* R_PAREN); constSpec: identifierList (type_? ASSIGN expressionList)?; identifierList: IDENTIFIER (COMMA IDENTIFIER)*; expressionList: expression (COMMA expression)*; typeDecl: TYPE (typeSpec | L_PAREN (typeSpec eos)* R_PAREN); typeSpec: IDENTIFIER ASSIGN? type_; // Function declarations functionDecl: FUNC IDENTIFIER (signature block?); methodDecl: FUNC receiver IDENTIFIER ( signature block?); receiver: parameters; varDecl: VAR (varSpec | L_PAREN (varSpec eos)* R_PAREN); varSpec: identifierList ( type_ (ASSIGN expressionList)? | ASSIGN expressionList ); block: L_CURLY statementList? R_CURLY; statementList: (eos? statement eos)+; statement: declaration | labeledStmt | simpleStmt | goStmt | returnStmt | breakStmt | continueStmt | gotoStmt | fallthroughStmt | block | ifStmt | switchStmt | selectStmt | forStmt | deferStmt; simpleStmt: sendStmt | incDecStmt | assignment | expressionStmt | shortVarDecl; expressionStmt: expression; sendStmt: channel = expression RECEIVE expression; incDecStmt: expression (PLUS_PLUS | MINUS_MINUS); assignment: expressionList assign_op expressionList; assign_op: ( PLUS | MINUS | OR | CARET | STAR | DIV | MOD | LSHIFT | RSHIFT | AMPERSAND | BIT_CLEAR )? ASSIGN; shortVarDecl: identifierList DECLARE_ASSIGN expressionList; emptyStmt: EOS | SEMI; labeledStmt: IDENTIFIER COLON statement?; returnStmt: RETURN expressionList?; breakStmt: BREAK IDENTIFIER?; continueStmt: CONTINUE IDENTIFIER?; gotoStmt: GOTO IDENTIFIER; fallthroughStmt: FALLTHROUGH; deferStmt: DEFER expression; ifStmt: IF ( expression | eos expression | simpleStmt eos expression ) block ( ELSE (ifStmt | block) )?; switchStmt: exprSwitchStmt | typeSwitchStmt; exprSwitchStmt: SWITCH (expression? | simpleStmt? eos expression? ) L_CURLY exprCaseClause* R_CURLY; exprCaseClause: exprSwitchCase COLON statementList?; exprSwitchCase: CASE expressionList | DEFAULT; typeSwitchStmt: SWITCH ( typeSwitchGuard | eos typeSwitchGuard | simpleStmt eos typeSwitchGuard) L_CURLY typeCaseClause* R_CURLY; typeSwitchGuard: (IDENTIFIER DECLARE_ASSIGN)? primaryExpr DOT L_PAREN TYPE R_PAREN; typeCaseClause: typeSwitchCase COLON statementList?; typeSwitchCase: CASE typeList | DEFAULT; typeList: (type_ | NIL_LIT) (COMMA (type_ | NIL_LIT))*; selectStmt: SELECT L_CURLY commClause* R_CURLY; commClause: commCase COLON statementList?; commCase: CASE (sendStmt | recvStmt) | DEFAULT; recvStmt: (expressionList ASSIGN | identifierList DECLARE_ASSIGN)? recvExpr = expression; forStmt: FOR (expression | forClause | rangeClause)? block; forClause: initStmt = simpleStmt? eos expression? eos postStmt = simpleStmt?; rangeClause: ( expressionList ASSIGN | identifierList DECLARE_ASSIGN )? RANGE expression; goStmt: GO expression; type_: typeName | typeLit | L_PAREN type_ R_PAREN; typeName: qualifiedIdent | IDENTIFIER; typeLit: arrayType | structType | pointerType | functionType | interfaceType | sliceType | mapType | channelType; arrayType: L_BRACKET arrayLength R_BRACKET elementType; arrayLength: expression; elementType: type_; pointerType: STAR type_; interfaceType: INTERFACE L_CURLY ((methodSpec | typeName) eos)* R_CURLY; sliceType: L_BRACKET R_BRACKET elementType; // It's possible to replace `type` with more restricted typeLit list and also pay attention to nil maps mapType: MAP L_BRACKET type_ R_BRACKET elementType; channelType: (CHAN | CHAN RECEIVE | RECEIVE CHAN) elementType; methodSpec: {noTerminatorAfterParams(2)}? IDENTIFIER parameters result | IDENTIFIER parameters; functionType: FUNC signature; signature: {noTerminatorAfterParams(1)}? parameters result | parameters; result: parameters | type_; parameters: L_PAREN (parameterDecl (COMMA parameterDecl)* COMMA?)? R_PAREN; parameterDecl: identifierList? ELLIPSIS? type_; expression: primaryExpr | unary_op = ( PLUS | MINUS | EXCLAMATION | CARET | STAR | AMPERSAND | RECEIVE ) expression | expression mul_op = ( STAR | DIV | MOD | LSHIFT | RSHIFT | AMPERSAND | BIT_CLEAR ) expression | expression add_op = (PLUS | MINUS | OR | CARET) expression | expression rel_op = ( EQUALS | NOT_EQUALS | LESS | LESS_OR_EQUALS | GREATER | GREATER_OR_EQUALS ) expression | expression LOGICAL_AND expression | expression LOGICAL_OR expression; primaryExpr: operand | conversion | methodExpr | primaryExpr ( (DOT IDENTIFIER) | index | slice_ | typeAssertion | arguments ); conversion: nonNamedType L_PAREN expression COMMA? R_PAREN; nonNamedType: typeLit | L_PAREN nonNamedType R_PAREN; operand: literal | operandName | L_PAREN expression R_PAREN; literal: basicLit | compositeLit | functionLit; basicLit: NIL_LIT | integer | string_ | FLOAT_LIT; integer: DECIMAL_LIT | BINARY_LIT | OCTAL_LIT | HEX_LIT | IMAGINARY_LIT | RUNE_LIT; operandName: IDENTIFIER; qualifiedIdent: IDENTIFIER DOT IDENTIFIER; compositeLit: literalType literalValue; literalType: structType | arrayType | L_BRACKET ELLIPSIS R_BRACKET elementType | sliceType | mapType | typeName; literalValue: L_CURLY (elementList COMMA?)? R_CURLY; elementList: keyedElement (COMMA keyedElement)*; keyedElement: (key COLON)? element; key: expression | literalValue; element: expression | literalValue; structType: STRUCT L_CURLY (fieldDecl eos)* R_CURLY; fieldDecl: ( identifierList type_ | embeddedField ) tag = string_?; string_: RAW_STRING_LIT | INTERPRETED_STRING_LIT; embeddedField: STAR? typeName; functionLit: FUNC signature block; // function index: L_BRACKET expression R_BRACKET; slice_: L_BRACKET ( expression? COLON expression? | expression? COLON expression COLON expression ) R_BRACKET; typeAssertion: DOT L_PAREN type_ R_PAREN; arguments: L_PAREN ( (expressionList | nonNamedType (COMMA expressionList)?) ELLIPSIS? COMMA? )? R_PAREN; methodExpr: nonNamedType DOT IDENTIFIER; //receiverType: typeName | '(' ('*' typeName | receiverType) ')'; receiverType: type_; eos: SEMI | EOF | EOS | {checkPreviousTokenText(")")}? | {checkPreviousTokenText("}")}? ;
remove ambiguous rules
remove ambiguous rules
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
2e52c6cca26f4702be5d2b0ef6a16f21da287006
src/main/antlr4/YokohamaUnitLexer.g4
src/main/antlr4/YokohamaUnitLexer.g4
lexer grammar YokohamaUnitLexer; STAR_LBRACKET: '*[' -> skip, mode(ABBREVIATION); HASH1: '#' ; HASH2: '##' ; HASH3: '###' ; HASH4: '####' ; HASH5: '#####' ; HASH6: '######' ; TEST: 'Test:' [ \t]* -> mode(TEST_NAME); TABLE_CAPTION: '[' -> 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: '|' ; 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: ',' ; RULES: 'rules' ; IN: 'in' ; UTABLE: 'Table' ; CSV: 'CSV' Spaces? '\'' -> mode(IN_FILE_NAME) ; TSV: 'TSV' Spaces? '\''-> mode(IN_FILE_NAME) ; EXCEL: 'Excel' Spaces? '\'' -> mode(IN_BOOK_NAME) ; WHERE: 'where' ; EQ: '=' ; LET: 'Let' ; BE: 'be' ; DO: 'Do' ; A_STUB_OF: 'a' Spaces 'stub' Spaces 'of' Spaces? '`' -> mode(CLASS) ; SUCH: 'such' ; METHOD: 'method' Spaces? '`' -> mode(METHOD_PATTERN) ; RETURNS: 'returns' ; AN_INSTANCE_OF: 'an' Spaces 'instance' Spaces 'of' Spaces? '`' -> mode(CLASS) ; AN_INSTANCE: 'an' Spaces 'instance' -> mode(AFTER_AN_INSTANCE) ; AN_INVOCATION_OF: 'an' Spaces 'invocation' Spaces 'of' Spaces? '`' -> mode(METHOD_PATTERN) ; ON: 'on' ; WITH: 'with' ; NULL: 'null' ; NOTHING: 'nothing' ; TRUE: 'true' ; FALSE: 'false' ; Identifier: IdentStart IdentPart* ; Integer: IntegerLiteral ; FloatingPoint: FloatingPointLiteral ; MINUS: '-' ; EMPTY_STRING: '""' ; OPEN_BACK_TICK: '`' -> skip, mode(IN_BACK_TICK) ; OPEN_DOUBLE_QUOTE: '"' -> skip, mode(IN_DOUBLE_QUOTE) ; OPEN_SINGLE_QUOTE: '\'' -> skip, mode(IN_SINGLE_QUOTE) ; WS : Spaces -> skip ; mode ABBREVIATION; ShortName: ~[\]\r\n]* ; RBRACKET_COLON: ']:' Spaces? -> skip, mode(LONG_NAME) ; mode LONG_NAME; LongName: ~[\r\n]* ; EXIT_LONG_NAME: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode TEST_NAME; TestName: ~[\r\n]+ ; NEW_LINE_TEST_NAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode TABLE_NAME; TableName: ~[\]\r\n]+ ; RBRACKET_TABLE_NAME: ']' -> skip, mode(DEFAULT_MODE) ; mode PHASE_LEADING; COLON: ':' [ \t]* -> skip, mode(PHASE_DESCRIPTION) ; NEW_LINE_PHASE_LEADING: [ \t]* '\r'? '\n' -> skip, mode(DEFAULT_MODE) ; mode PHASE_DESCRIPTION; PhaseDescription: ~[\r\n]+ ; NEW_LINE_PHASE_DESCRIPTION: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode AFTER_AN_INSTANCE; OF: 'of' ; Identifier5 : IdentStart IdentPart* -> type(Identifier) ; OPEN_BACK_TICK5: '`' -> skip, mode(CLASS) ; WS_AFTER_AN_INSTANCE: Spaces -> skip ; mode IN_DOUBLE_QUOTE; Str: (~["\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_DOUBLE_QUOTE: '"' -> skip, mode(DEFAULT_MODE) ; mode IN_SINGLE_QUOTE; Char: (~['\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_SINGLE_QUOTE: '\'' -> skip, mode(DEFAULT_MODE) ; mode IN_BACK_TICK; Expr: ~[`]+ ; CLOSE_BACK_TICK: '`' -> skip, mode(DEFAULT_MODE) ; 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); WS_METHOD_PATTERN: Spaces -> skip ; CLOSE_BACK_TICK2: '`' -> skip, mode(DEFAULT_MODE) ; mode CLASS; DOT2: '.' -> type(DOT) ; Identifier4 : IdentStart IdentPart* -> type(Identifier) ; WS_CLASS: Spaces -> skip ; CLOSE_BACK_TICK3: '`' -> skip, mode(DEFAULT_MODE) ; mode IN_FILE_NAME; SingleQuoteName: (~['\r\n]|'\'\'')* ; CLOSE_SINGLE_QUOTE2: '\'' -> skip, mode(DEFAULT_MODE) ; mode IN_BOOK_NAME; SingleQuoteName3: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ; CLOSE_SINGLE_QUOTE3: '\'' -> skip, mode(DEFAULT_MODE) ; 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: '*[' -> skip, mode(ABBREVIATION); HASH1: '#' ; HASH2: '##' ; HASH3: '###' ; HASH4: '####' ; HASH5: '#####' ; HASH6: '######' ; TEST: 'Test:' [ \t]* -> mode(TEST_NAME); TABLE_CAPTION: '[' -> 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: '|' ; 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: 'CSV' Spaces? '\'' -> mode(IN_FILE_NAME) ; TSV: 'TSV' Spaces? '\''-> mode(IN_FILE_NAME) ; EXCEL: 'Excel' Spaces? '\'' -> mode(IN_BOOK_NAME) ; WHERE: 'where' ; EQ: '=' ; LET: 'Let' ; BE: 'be' ; DO: 'Do' ; A_STUB_OF: 'a' Spaces 'stub' Spaces 'of' Spaces? '`' -> mode(CLASS) ; SUCH: 'such' ; METHOD: 'method' Spaces? '`' -> mode(METHOD_PATTERN) ; RETURNS: 'returns' ; AN_INSTANCE_OF: 'an' Spaces 'instance' Spaces 'of' Spaces? '`' -> mode(CLASS) ; AN_INSTANCE: 'an' Spaces 'instance' -> mode(AFTER_AN_INSTANCE) ; AN_INVOCATION_OF: 'an' Spaces 'invocation' Spaces 'of' Spaces? '`' -> mode(METHOD_PATTERN) ; ON: 'on' ; WITH: 'with' ; NULL: 'null' ; NOTHING: 'nothing' ; TRUE: 'true' ; FALSE: 'false' ; Identifier: IdentStart IdentPart* ; Integer: IntegerLiteral ; FloatingPoint: FloatingPointLiteral ; MINUS: '-' ; EMPTY_STRING: '""' ; OPEN_BACK_TICK: '`' -> skip, mode(IN_BACK_TICK) ; OPEN_DOUBLE_QUOTE: '"' -> skip, mode(IN_DOUBLE_QUOTE) ; OPEN_SINGLE_QUOTE: '\'' -> skip, mode(IN_SINGLE_QUOTE) ; WS : Spaces -> skip ; mode ABBREVIATION; ShortName: ~[\]\r\n]* ; RBRACKET_COLON: ']:' Spaces? -> skip, mode(LONG_NAME) ; mode LONG_NAME; LongName: ~[\r\n]* ; EXIT_LONG_NAME: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode TEST_NAME; TestName: ~[\r\n]+ ; NEW_LINE_TEST_NAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode TABLE_NAME; TableName: ~[\]\r\n]+ ; RBRACKET_TABLE_NAME: ']' -> skip, mode(DEFAULT_MODE) ; mode PHASE_LEADING; COLON: ':' [ \t]* -> skip, mode(PHASE_DESCRIPTION) ; NEW_LINE_PHASE_LEADING: [ \t]* '\r'? '\n' -> skip, mode(DEFAULT_MODE) ; mode PHASE_DESCRIPTION; PhaseDescription: ~[\r\n]+ ; NEW_LINE_PHASE_DESCRIPTION: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode AFTER_AN_INSTANCE; OF: 'of' ; Identifier5 : IdentStart IdentPart* -> type(Identifier) ; OPEN_BACK_TICK5: '`' -> skip, mode(CLASS) ; WS_AFTER_AN_INSTANCE: Spaces -> skip ; mode IN_DOUBLE_QUOTE; Str: (~["\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_DOUBLE_QUOTE: '"' -> skip, mode(DEFAULT_MODE) ; mode IN_SINGLE_QUOTE; Char: (~['\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_SINGLE_QUOTE: '\'' -> skip, mode(DEFAULT_MODE) ; mode IN_BACK_TICK; Expr: ~[`]+ ; CLOSE_BACK_TICK: '`' -> skip, mode(DEFAULT_MODE) ; 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); WS_METHOD_PATTERN: Spaces -> skip ; CLOSE_BACK_TICK2: '`' -> skip, mode(DEFAULT_MODE) ; mode CLASS; DOT2: '.' -> type(DOT) ; Identifier4 : IdentStart IdentPart* -> type(Identifier) ; WS_CLASS: Spaces -> skip ; CLOSE_BACK_TICK3: '`' -> skip, mode(DEFAULT_MODE) ; mode IN_FILE_NAME; SingleQuoteName: (~['\r\n]|'\'\'')* ; CLOSE_SINGLE_QUOTE2: '\'' -> skip, mode(DEFAULT_MODE) ; mode IN_BOOK_NAME; SingleQuoteName3: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ; CLOSE_SINGLE_QUOTE3: '\'' -> skip, mode(DEFAULT_MODE) ; 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] ;
Remove unused token RULES
Remove unused token RULES
ANTLR
mit
tkob/yokohamaunit,tkob/yokohamaunit
d3ec97a8c9b95117d4c37aeb823b6258668eb5f7
container-search/src/main/antlr4/com/yahoo/search/yql/yqlplus.g4
container-search/src/main/antlr4/com/yahoo/search/yql/yqlplus.g4
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. grammar yqlplus; options { superClass = ParserBase; language = Java; } @header { import java.util.Stack; import com.yahoo.search.yql.*; } @parser::members { protected static class expression_scope { boolean in_select; } protected Stack<expression_scope> expression_stack = new Stack(); } // tokens SELECT : 'select'; LIMIT : 'limit'; OFFSET : 'offset'; WHERE : 'where'; ORDERBY : 'order by'; DESC : 'desc'; ASC :; FROM : 'from'; SOURCES : 'sources'; AS : 'as'; COMMA : ','; OUTPUT : 'output'; COUNT : 'count'; TRUE : 'true'; FALSE : 'false'; // brackets and other tokens in literals LPAREN : '('; RPAREN : ')'; LBRACKET : '['; RBRACKET : ']'; LBRACE : '{'; RBRACE : '}'; COLON : ':'; PIPE : '|'; // operators AND : 'and'; OR : 'or'; NOT_IN : 'not in'; IN : 'in'; QUERY_ARRAY :; LT : '<'; GT : '>'; LTEQ : '<='; GTEQ : '>='; NEQ : '!='; STAR : '*'; EQ : '='; LIKE : 'like'; CONTAINS : 'contains'; NOTLIKE : 'not like'; MATCHES : 'matches'; NOTMATCHES : 'not matches'; // effectively unary operators IS_NULL : 'is null'; IS_NOT_NULL : 'is not null'; // dereference DOT : '.'; AT : '@'; // quotes SQ : '\''; DQ : '"'; // statement delimiter SEMI : ';'; TIMEOUT : 'timeout'; /*------------------------------------------------------------------ * LEXER RULES *------------------------------------------------------------------*/ ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_'|':'|'-')* ; LONG_INT : '-'?'0'..'9'+ ('L'|'l') ; INT : '-'?'0'..'9'+ ; FLOAT : ('-')?('0'..'9')+ '.' ('0'..'9')* EXPONENT? | ('-')?'.' ('0'..'9')+ EXPONENT? | ('-')?('0'..'9')+ EXPONENT ; fragment EXPONENT : ('e'|'E') ('+'|'-')? ('0'..'9')+ ; fragment DIGIT : '0'..'9' ; fragment LETTER : 'a'..'z' | 'A'..'Z' ; STRING : '"' ( ESC_SEQ | ~('\\'| '"') )* '"' | '\'' ( ESC_SEQ | ~('\\' | '\'') )* '\'' ; fragment HEX_DIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ; fragment ESC_SEQ : '\\' ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\'|'/') | UNICODE_ESC ; fragment UNICODE_ESC : '\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ; WS : ( ' ' | '\t' | '\r' | '\n' ) -> channel(HIDDEN) ; COMMENT : ( ('//') ~('\n'|'\r')* '\r'? '\n'? | '/*' .*? '*/' ) -> channel(HIDDEN) ; VESPA_GROUPING : ('all' | 'each') WS* VESPA_GROUPING_ARG WS* ('as' WS* VESPA_GROUPING_ARG WS*)? ('where' WS* VESPA_GROUPING_ARG)? ; fragment VESPA_GROUPING_ARG : ('(' | '[' | '<') ( ~('(' | '[' | '<' | ')' | ']' | '>') | VESPA_GROUPING_ARG )* (')' | ']' | '>') ; // --------- parser rules ------------ ident : keyword_as_ident //{addChild(new TerminalNodeImpl(keyword_as_ident.getText()));} | ID ; keyword_as_ident : SELECT | LIMIT | OFFSET | WHERE | 'order' | 'by' | DESC | OUTPUT | COUNT | SOURCES | MATCHES | LIKE ; program : (statement SEMI)* EOF ; moduleId : ID ; moduleName : literalString | namespaced_name ; statement : output_statement ; output_statement : source_statement output_spec? ; source_statement : query_statement (PIPE pipeline_step)* ; pipeline_step : namespaced_name arguments[false]? | vespa_grouping ; vespa_grouping : VESPA_GROUPING | annotation VESPA_GROUPING ; output_spec : (OUTPUT AS ident) | (OUTPUT COUNT AS ident) ; query_statement : select_statement ; select_statement : SELECT select_field_spec select_source? where? orderby? limit? offset? timeout? ; select_field_spec : project_spec | STAR ; project_spec : field_def (COMMA field_def)* ; timeout : TIMEOUT fixed_or_parameter ; select_source : select_source_all | select_source_multi | select_source_from ; select_source_all : FROM SOURCES STAR ; select_source_multi : FROM SOURCES source_list ; select_source_from : FROM source_spec ; source_list : namespaced_name (COMMA namespaced_name )* ; source_spec : ( data_source (alias_def { ($data_source.ctx).addChild($alias_def.ctx); })? ) ; alias_def : (AS? ID) ; data_source : call_source | LPAREN source_statement RPAREN | sequence_source ; call_source : namespaced_name arguments[true]? ; sequence_source : AT ident ; namespaced_name : (ident (DOT ident)* (DOT STAR)?) ; orderby : ORDERBY orderby_fields ; orderby_fields : orderby_field (COMMA orderby_field)* ; orderby_field : expression[true] DESC | expression[true] ('asc')? ; limit : LIMIT fixed_or_parameter ; offset : OFFSET fixed_or_parameter ; where : WHERE expression[true] ; field_def : expression[true] alias_def? ; mapExpression : LBRACE propertyNameAndValue? (COMMA propertyNameAndValue)* RBRACE ; constantMapExpression : LBRACE constantPropertyNameAndValue? (COMMA constantPropertyNameAndValue)* RBRACE ; arguments[boolean in_select] : LPAREN RPAREN | LPAREN (argument[$in_select] (COMMA argument[$in_select])*) RPAREN ; argument[boolean in_select] : expression[$in_select] ; // --------- expressions ------------ expression [boolean select] @init { expression_stack.push(new expression_scope()); expression_stack.peek().in_select = select; } @after { expression_stack.pop(); } : annotateExpression | logicalORExpression | nullOperator ; nullOperator : 'null' ; annotateExpression : annotation logicalORExpression ; annotation : LBRACKET constantMapExpression RBRACKET ; logicalORExpression : logicalANDExpression (OR logicalANDExpression)+ | logicalANDExpression ; logicalANDExpression : equalityExpression (AND equalityExpression)* ; equalityExpression : relationalExpression ( ((IN | NOT_IN) inNotInTarget) | (IS_NULL | IS_NOT_NULL) | (equalityOp relationalExpression) ) | relationalExpression ; inNotInTarget : {expression_stack.peek().in_select}? LPAREN select_statement RPAREN | literal_list ; equalityOp : (EQ | NEQ | LIKE | NOTLIKE | MATCHES | NOTMATCHES | CONTAINS) ; relationalExpression : additiveExpression (relationalOp additiveExpression)? ; relationalOp : (LT | GT | LTEQ | GTEQ) ; additiveExpression : multiplicativeExpression (additiveOp additiveExpression)? ; additiveOp : '+' | '-' ; multiplicativeExpression : unaryExpression (multOp multiplicativeExpression)? ; multOp : '*' | '/' | '%' ; unaryOp : '-' | '!' ; unaryExpression : dereferencedExpression | unaryOp dereferencedExpression ; dereferencedExpression @init{ boolean in_select = expression_stack.peek().in_select; } : primaryExpression ( indexref[in_select] | propertyref )* ; indexref[boolean in_select] : LBRACKET idx=expression[in_select] RBRACKET ; propertyref : DOT nm=ID ; operatorCall @init{ boolean in_select = expression_stack.peek().in_select; } : multOp arguments[in_select] | additiveOp arguments[in_select] | AND arguments[in_select] | OR arguments[in_select] ; primaryExpression @init { boolean in_select = expression_stack.peek().in_select; } : callExpresion[in_select] | parameter | fieldref | scalar_literal | arrayLiteral | mapExpression | LPAREN expression[in_select] RPAREN ; callExpresion[boolean in_select] : namespaced_name arguments[in_select] ; fieldref : namespaced_name ; arrayLiteral @init { boolean in_select = expression_stack.peek().in_select; } : LBRACKET expression[in_select]? (COMMA expression[in_select])* RBRACKET ; // a parameter is an argument from outside the YQL statement parameter : AT ident ; propertyNameAndValue : propertyName ':' expression[{expression_stack.peek().in_select}] //{return (PROPERTY propertyName expression);} ; constantPropertyNameAndValue : propertyName ':' constantExpression ; propertyName : ID | literalString ; constantExpression : scalar_literal | constantMapExpression | constantArray | parameter ; constantArray : LBRACKET i+=constantExpression? (COMMA i+=constantExpression)* RBRACKET ; scalar_literal : TRUE | FALSE | STRING | LONG_INT | INT | FLOAT ; literalString : STRING ; array_parameter : AT i=ident {isArrayParameter($i.ctx)}? ; literal_list : LPAREN literal_element (COMMA literal_element)* RPAREN ; literal_element : scalar_literal | parameter ; fixed_or_parameter : INT | parameter ;
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. grammar yqlplus; options { superClass = ParserBase; language = Java; } @header { import java.util.Stack; import com.yahoo.search.yql.*; } @parser::members { protected static class expression_scope { boolean in_select; } protected Stack<expression_scope> expression_stack = new Stack(); } // tokens SELECT : 'select'; LIMIT : 'limit'; OFFSET : 'offset'; WHERE : 'where'; ORDERBY : 'order by'; DESC : 'desc'; ASC :; FROM : 'from'; SOURCES : 'sources'; AS : 'as'; COMMA : ','; OUTPUT : 'output'; COUNT : 'count'; TRUE : 'true'; FALSE : 'false'; // brackets and other tokens in literals LPAREN : '('; RPAREN : ')'; LBRACKET : '['; RBRACKET : ']'; LBRACE : '{'; RBRACE : '}'; COLON : ':'; PIPE : '|'; // operators AND : 'and'; OR : 'or'; NOT_IN : 'not in'; IN : 'in'; QUERY_ARRAY :; LT : '<'; GT : '>'; LTEQ : '<='; GTEQ : '>='; NEQ : '!='; STAR : '*'; EQ : '='; LIKE : 'like'; CONTAINS : 'contains'; NOTLIKE : 'not like'; MATCHES : 'matches'; NOTMATCHES : 'not matches'; // effectively unary operators IS_NULL : 'is null'; IS_NOT_NULL : 'is not null'; // dereference DOT : '.'; AT : '@'; // quotes SQ : '\''; DQ : '"'; // statement delimiter SEMI : ';'; TIMEOUT : 'timeout'; /*------------------------------------------------------------------ * LEXER RULES *------------------------------------------------------------------*/ ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_'|':'|'-')* ; LONG_INT : '-'?'0'..'9'+ ('L'|'l') ; INT : '-'?'0'..'9'+ ; FLOAT : ('-')?('0'..'9')+ '.' ('0'..'9')* EXPONENT? | ('-')?'.' ('0'..'9')+ EXPONENT? | ('-')?('0'..'9')+ EXPONENT ; fragment EXPONENT : ('e'|'E') ('+'|'-')? ('0'..'9')+ ; fragment DIGIT : '0'..'9' ; fragment LETTER : 'a'..'z' | 'A'..'Z' ; STRING : '"' ( ESC_SEQ | ~('\\'| '"') )* '"' | '\'' ( ESC_SEQ | ~('\\' | '\'') )* '\'' ; fragment HEX_DIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ; fragment ESC_SEQ : '\\' ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\'|'/') | UNICODE_ESC ; fragment UNICODE_ESC : '\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ; WS : ( ' ' | '\t' | '\r' | '\n' ) -> channel(HIDDEN) ; COMMENT : ( ('//') ~('\n'|'\r')* '\r'? '\n'? | '/*' .*? '*/' ) -> channel(HIDDEN) ; VESPA_GROUPING : ('all' | 'each') WS* VESPA_GROUPING_ARG WS* ('as' WS* VESPA_GROUPING_ARG WS*)? ('where' WS* VESPA_GROUPING_ARG)? ; fragment VESPA_GROUPING_ARG : ('(' | '[' | '<') ( ~('(' | '[' | '<' | ')' | ']' | '>') | VESPA_GROUPING_ARG )* (')' | ']' | '>') ; // --------- parser rules ------------ ident : keyword_as_ident //{addChild(new TerminalNodeImpl(keyword_as_ident.getText()));} | ID ; keyword_as_ident : SELECT | LIMIT | OFFSET | WHERE | 'order' | 'by' | DESC | OUTPUT | COUNT | SOURCES | MATCHES | LIKE ; program : (statement SEMI)* EOF ; moduleId : ID ; moduleName : literalString | namespaced_name ; statement : output_statement ; output_statement : source_statement output_spec? ; source_statement : query_statement (PIPE pipeline_step)* ; pipeline_step : namespaced_name arguments[false]? | vespa_grouping ; vespa_grouping : VESPA_GROUPING | annotation VESPA_GROUPING ; output_spec : (OUTPUT AS ident) | (OUTPUT COUNT AS ident) ; query_statement : select_statement ; select_statement : SELECT select_field_spec select_source? where? orderby? limit? offset? timeout? ; select_field_spec : project_spec | STAR ; project_spec : field_def (COMMA field_def)* ; timeout : TIMEOUT fixed_or_parameter ; select_source : select_source_all | select_source_multi | select_source_from ; select_source_all : FROM SOURCES STAR ; select_source_multi : FROM SOURCES source_list ; select_source_from : FROM source_spec ; source_list : namespaced_name (COMMA namespaced_name )* ; source_spec : ( data_source (alias_def { ($data_source.ctx).addChild($alias_def.ctx); })? ) ; alias_def : (AS? ID) ; data_source : call_source | LPAREN source_statement RPAREN | sequence_source ; call_source : namespaced_name arguments[true]? ; sequence_source : AT ident ; namespaced_name : (ident (DOT ident)* (DOT STAR)?) ; orderby : ORDERBY orderby_fields ; orderby_fields : orderby_field (COMMA orderby_field)* ; orderby_field : expression[true] DESC | expression[true] ('asc')? ; limit : LIMIT fixed_or_parameter ; offset : OFFSET fixed_or_parameter ; where : WHERE expression[true] ; field_def : expression[true] alias_def? ; mapExpression : LBRACE propertyNameAndValue? (COMMA propertyNameAndValue)* RBRACE ; constantMapExpression : LBRACE constantPropertyNameAndValue? (COMMA constantPropertyNameAndValue)* RBRACE ; arguments[boolean in_select] : LPAREN RPAREN | LPAREN (argument[$in_select] (COMMA argument[$in_select])*) RPAREN ; argument[boolean in_select] : expression[$in_select] ; // --------- expressions ------------ expression [boolean select] @init { expression_stack.push(new expression_scope()); expression_stack.peek().in_select = select; } @after { expression_stack.pop(); } : annotateExpression | logicalORExpression | nullOperator ; nullOperator : 'null' ; annotateExpression : annotation logicalORExpression ; annotation : LBRACKET constantMapExpression RBRACKET ; logicalORExpression : logicalANDExpression (OR logicalANDExpression)+ | logicalANDExpression ; logicalANDExpression : equalityExpression (AND equalityExpression)* ; equalityExpression : relationalExpression ( ((IN | NOT_IN) inNotInTarget) | (IS_NULL | IS_NOT_NULL) | (equalityOp relationalExpression) ) | relationalExpression ; inNotInTarget : {expression_stack.peek().in_select}? LPAREN select_statement RPAREN | literal_list ; equalityOp : (EQ | NEQ | LIKE | NOTLIKE | MATCHES | NOTMATCHES | CONTAINS) ; relationalExpression : additiveExpression (relationalOp additiveExpression)? ; relationalOp : (LT | GT | LTEQ | GTEQ) ; additiveExpression : multiplicativeExpression (additiveOp additiveExpression)? ; additiveOp : '+' | '-' ; multiplicativeExpression : unaryExpression (multOp multiplicativeExpression)? ; multOp : '*' | '/' | '%' ; unaryOp : '-' | '!' ; unaryExpression : dereferencedExpression | unaryOp dereferencedExpression ; dereferencedExpression @init{ boolean in_select = expression_stack.peek().in_select; } : primaryExpression ( indexref[in_select] | propertyref )* ; indexref[boolean in_select] : LBRACKET idx=expression[in_select] RBRACKET ; propertyref : DOT nm=ID ; primaryExpression @init { boolean in_select = expression_stack.peek().in_select; } : callExpresion[in_select] | parameter | fieldref | scalar_literal | arrayLiteral | mapExpression | LPAREN expression[in_select] RPAREN ; callExpresion[boolean in_select] : namespaced_name arguments[in_select] ; fieldref : namespaced_name ; arrayLiteral @init { boolean in_select = expression_stack.peek().in_select; } : LBRACKET expression[in_select]? (COMMA expression[in_select])* RBRACKET ; // a parameter is an argument from outside the YQL statement parameter : AT ident ; propertyNameAndValue : propertyName ':' expression[{expression_stack.peek().in_select}] //{return (PROPERTY propertyName expression);} ; constantPropertyNameAndValue : propertyName ':' constantExpression ; propertyName : ID | literalString ; constantExpression : scalar_literal | constantMapExpression | constantArray | parameter ; constantArray : LBRACKET i+=constantExpression? (COMMA i+=constantExpression)* RBRACKET ; scalar_literal : TRUE | FALSE | STRING | LONG_INT | INT | FLOAT ; literalString : STRING ; array_parameter : AT i=ident {isArrayParameter($i.ctx)}? ; literal_list : LPAREN literal_element (COMMA literal_element)* RPAREN ; literal_element : scalar_literal | parameter ; fixed_or_parameter : INT | parameter ;
Remove unsupported constructs
Remove unsupported constructs
ANTLR
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
0ca9d1588de6f511dbfab971741417ceb7d46371
javascript/jsx/JavaScriptLexer.g4
javascript/jsx/JavaScriptLexer.g4
/* * The MIT License (MIT) * * Copyright (c) 2014 by Bart Kiers (original author) and Alexandre Vitorelli (contributor -> ported to CSharp) * Copyright (c) 2017-2020 by Ivan Kochurkin (Positive Technologies): added ECMAScript 6 support, cleared and transformed to the universal grammar. * Copyright (c) 2018 by Juan Alvarez (contributor -> ported to Go) * Copyright (c) 2019 by Student Main (contributor -> ES2020) * * 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. */ lexer grammar JavaScriptLexer; channels { ERROR } options { superClass=JavaScriptLexerBase; } HashBangLine: { this.IsStartOfFile()}? '#!' ~[\r\n\u2028\u2029]*; // only allowed at start OpenBracket: '['; CloseBracket: ']'; OpenParen: '('; CloseParen: ')'; OpenBrace: '{' {this.ProcessOpenBrace();}; CloseBrace: '}' {this.ProcessCloseBrace();}; SemiColon: ';'; Comma: ','; Assign: '='; QuestionMark: '?'; Colon: ':'; Ellipsis: '...'; Dot: '.'; PlusPlus: '++'; MinusMinus: '--'; Plus: '+'; Minus: '-'; BitNot: '~'; Not: '!'; Multiply: '*'; Divide: '/'; Modulus: '%'; Power: '**'; NullCoalesce: '??'; Hashtag: '#'; RightShiftArithmetic: '>>'; LeftShiftArithmetic: '<<'; RightShiftLogical: '>>>'; LessThan: '<'; MoreThan: '>'; LessThanEquals: '<='; GreaterThanEquals: '>='; Equals_: '=='; NotEquals: '!='; IdentityEquals: '==='; IdentityNotEquals: '!=='; BitAnd: '&'; BitXOr: '^'; BitOr: '|'; And: '&&'; Or: '||'; MultiplyAssign: '*='; DivideAssign: '/='; ModulusAssign: '%='; PlusAssign: '+='; MinusAssign: '-='; LeftShiftArithmeticAssign: '<<='; RightShiftArithmeticAssign: '>>='; RightShiftLogicalAssign: '>>>='; BitAndAssign: '&='; BitXorAssign: '^='; BitOrAssign: '|='; PowerAssign: '**='; ARROW: '=>'; /// Null Literals NullLiteral: 'null'; /// Boolean Literals BooleanLiteral: 'true' | 'false'; /// Numeric Literals DecimalLiteral: DecimalIntegerLiteral '.' [0-9] [0-9_]* ExponentPart? | '.' [0-9] [0-9_]* ExponentPart? | DecimalIntegerLiteral ExponentPart? ; /// Numeric Literals HexIntegerLiteral: '0' [xX] [0-9a-fA-F] HexDigit*; OctalIntegerLiteral: '0' [0-7]+ {!this.IsStrictMode()}?; OctalIntegerLiteral2: '0' [oO] [0-7] [_0-7]*; BinaryIntegerLiteral: '0' [bB] [01] [_01]*; BigHexIntegerLiteral: '0' [xX] [0-9a-fA-F] HexDigit* 'n'; BigOctalIntegerLiteral: '0' [oO] [0-7] [_0-7]* 'n'; BigBinaryIntegerLiteral: '0' [bB] [01] [_01]* 'n'; BigDecimalIntegerLiteral: DecimalIntegerLiteral 'n'; /// Keywords Break: 'break'; Do: 'do'; Instanceof: 'instanceof'; Typeof: 'typeof'; Case: 'case'; Else: 'else'; New: 'new'; Var: 'var'; Catch: 'catch'; Finally: 'finally'; Return: 'return'; Void: 'void'; Continue: 'continue'; For: 'for'; Switch: 'switch'; While: 'while'; Debugger: 'debugger'; Function: 'function'; This: 'this'; With: 'with'; Default: 'default'; If: 'if'; Throw: 'throw'; Delete: 'delete'; In: 'in'; Try: 'try'; As: 'as'; From: 'from'; /// Future Reserved Words Class: 'class'; Enum: 'enum'; Extends: 'extends'; Super: 'super'; Const: 'const'; Export: 'export'; Import: 'import'; Async: 'async'; Await: 'await'; /// The following tokens are also considered to be FutureReservedWords /// when parsing strict mode Implements: 'implements' {this.IsStrictMode()}?; StrictLet: 'let' {this.IsStrictMode()}?; NonStrictLet: 'let' {!this.IsStrictMode()}?; Private: 'private' {this.IsStrictMode()}?; Public: 'public' {this.IsStrictMode()}?; Interface: 'interface' {this.IsStrictMode()}?; Package: 'package' {this.IsStrictMode()}?; Protected: 'protected' {this.IsStrictMode()}?; Static: 'static' {this.IsStrictMode()}?; Yield: 'yield' {this.IsStrictMode()}?; /// Identifier Names and Identifiers Identifier: IdentifierStart IdentifierPart*; /// String Literals StringLiteral: ('"' DoubleStringCharacter* '"' | '\'' SingleStringCharacter* '\'') {this.ProcessStringLiteral();} ; LinkLiteral: ('http' | 'https' | 'ftp' | 'file') '://' [a-zA-Z0-9./?=]+; // TODO Could be more precise // TODO: `${`tmp`}` TemplateStringLiteral: '`' ('\\`' | ~'`')* '`'; WhiteSpaces: [\t\u000B\u000C\u0020\u00A0]+ -> channel(HIDDEN); LineTerminator: [\r\n\u2028\u2029] -> channel(HIDDEN); /// Comments JsxComment: '{/*' .*? '*/}' -> channel(HIDDEN); MultiLineComment: '/*' .*? '*/' -> channel(HIDDEN); SingleLineComment: '//' ~[\r\n\u2028\u2029]* -> channel(HIDDEN); RegularExpressionLiteral: '/' RegularExpressionFirstChar RegularExpressionChar* {this.IsRegexPossible()}? '/' IdentifierPart*; HtmlComment: '<!--' .*? '-->' -> channel(HIDDEN); CDataComment: '<![CDATA[' .*? ']]>' -> channel(HIDDEN); UnexpectedCharacter: . -> channel(ERROR); CDATA: '<![CDATA[' .*? ']]>' -> channel(HIDDEN); // // html tag declarations // mode TAG; TagOpen : LessThan -> pushMode(TAG) ; TagClose : MoreThan -> popMode ; TagSlashClose : '/>' -> popMode ; TagSlash : Divide ; TagName : TagNameStartChar TagNameChar* ; // an attribute value may have spaces b/t the '=' and the value AttributeValue : [ ]* Attribute -> popMode ; Attribute : DoubleQuoteString | SingleQuoteString | AttributeChar | HexChars | DecChars ; // // lexing mode for attribute values // mode ATTVALUE; TagEquals : Assign -> pushMode(ATTVALUE) ; // Fragment rules fragment AttributeChar : '-' | '_' | '.' | '/' | '+' | ',' | '?' | '=' | ':' | ';' | '#' | [0-9a-zA-Z] ; fragment AttributeChars : AttributeChar+ ' '? ; fragment HexChars : '#' [0-9a-fA-F]+ ; fragment DecChars : [0-9]+ '%'? ; fragment DoubleQuoteString : '"' ~[<"]* '"' ; fragment SingleQuoteString : '\'' ~[<']* '\'' ; fragment TagNameStartChar : [:a-zA-Z] | '\u2070'..'\u218F' | '\u2C00'..'\u2FEF' | '\u3001'..'\uD7FF' | '\uF900'..'\uFDCF' | '\uFDF0'..'\uFFFD' ; fragment TagNameChar : TagNameStartChar | '-' | '_' | '.' | Digit | '\u00B7' | '\u0300'..'\u036F' | '\u203F'..'\u2040' ; fragment Digit : [0-9] ; fragment DoubleStringCharacter : ~["\\] | '\\' EscapeSequence | LineContinuation ; fragment SingleStringCharacter : ~['\\] | '\\' EscapeSequence | LineContinuation ; fragment EscapeSequence : CharacterEscapeSequence | '0' // no digit ahead! TODO | HexEscapeSequence | UnicodeEscapeSequence | ExtendedUnicodeEscapeSequence ; fragment CharacterEscapeSequence : SingleEscapeCharacter | NonEscapeCharacter ; fragment HexEscapeSequence : 'x' HexDigit HexDigit ; fragment UnicodeEscapeSequence : 'u' HexDigit HexDigit HexDigit HexDigit | 'u' '{' HexDigit HexDigit+ '}' ; fragment ExtendedUnicodeEscapeSequence : 'u' '{' HexDigit+ '}' ; fragment SingleEscapeCharacter : ['"\\bfnrtv] ; fragment NonEscapeCharacter : ~['"\\bfnrtv0-9xu\r\n] ; fragment EscapeCharacter : SingleEscapeCharacter | [0-9] | [xu] ; fragment LineContinuation : '\\' [\r\n\u2028\u2029] ; fragment HexDigit : [_0-9a-fA-F] ; fragment DecimalIntegerLiteral : '0' | [1-9] [0-9_]* ; fragment ExponentPart : [eE] [+-]? [0-9_]+ ; fragment IdentifierPart : IdentifierStart | [\p{Mn}] | [\p{Nd}] | [\p{Pc}] | '\u200C' | '\u200D' ; fragment IdentifierStart : [\p{L}] | [$_] | '\\' UnicodeEscapeSequence ; fragment RegularExpressionFirstChar : ~[*\r\n\u2028\u2029\\/[] | RegularExpressionBackslashSequence | '[' RegularExpressionClassChar* ']' ; fragment RegularExpressionChar : ~[\r\n\u2028\u2029\\/[] | RegularExpressionBackslashSequence | '[' RegularExpressionClassChar* ']' ; fragment RegularExpressionClassChar : ~[\r\n\u2028\u2029\]\\] | RegularExpressionBackslashSequence ; fragment RegularExpressionBackslashSequence : '\\' ~[\r\n\u2028\u2029] ;
/* * The MIT License (MIT) * * Copyright (c) 2014 by Bart Kiers (original author) and Alexandre Vitorelli (contributor -> ported to CSharp) * Copyright (c) 2017-2020 by Ivan Kochurkin (Positive Technologies): added ECMAScript 6 support, cleared and transformed to the universal grammar. * Copyright (c) 2018 by Juan Alvarez (contributor -> ported to Go) * Copyright (c) 2019 by Student Main (contributor -> ES2020) * * 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. */ lexer grammar JavaScriptLexer; channels { ERROR } options { superClass=JavaScriptLexerBase; } HashBangLine: { this.IsStartOfFile()}? '#!' ~[\r\n\u2028\u2029]*; // only allowed at start OpenBracket: '['; CloseBracket: ']'; OpenParen: '('; CloseParen: ')'; OpenBrace: '{' {this.ProcessOpenBrace();}; CloseBrace: '}' {this.ProcessCloseBrace();}; SemiColon: ';'; Comma: ','; Assign: '='; QuestionMark: '?'; Colon: ':'; Ellipsis: '...'; Dot: '.'; PlusPlus: '++'; MinusMinus: '--'; Plus: '+'; Minus: '-'; BitNot: '~'; Not: '!'; Multiply: '*'; Divide: '/'; Modulus: '%'; Power: '**'; NullCoalesce: '??'; Hashtag: '#'; RightShiftArithmetic: '>>'; LeftShiftArithmetic: '<<'; RightShiftLogical: '>>>'; LessThan: '<'; MoreThan: '>'; LessThanEquals: '<='; GreaterThanEquals: '>='; Equals_: '=='; NotEquals: '!='; IdentityEquals: '==='; IdentityNotEquals: '!=='; BitAnd: '&'; BitXOr: '^'; BitOr: '|'; And: '&&'; Or: '||'; MultiplyAssign: '*='; DivideAssign: '/='; ModulusAssign: '%='; PlusAssign: '+='; MinusAssign: '-='; LeftShiftArithmeticAssign: '<<='; RightShiftArithmeticAssign: '>>='; RightShiftLogicalAssign: '>>>='; BitAndAssign: '&='; BitXorAssign: '^='; BitOrAssign: '|='; PowerAssign: '**='; ARROW: '=>'; /// Null Literals NullLiteral: 'null'; /// Boolean Literals BooleanLiteral: 'true' | 'false'; /// Numeric Literals DecimalLiteral: DecimalIntegerLiteral '.' [0-9] [0-9_]* ExponentPart? | '.' [0-9] [0-9_]* ExponentPart? | DecimalIntegerLiteral ExponentPart? ; /// Numeric Literals HexIntegerLiteral: '0' [xX] [0-9a-fA-F] HexDigit*; OctalIntegerLiteral: '0' [0-7]+ {!this.IsStrictMode()}?; OctalIntegerLiteral2: '0' [oO] [0-7] [_0-7]*; BinaryIntegerLiteral: '0' [bB] [01] [_01]*; BigHexIntegerLiteral: '0' [xX] [0-9a-fA-F] HexDigit* 'n'; BigOctalIntegerLiteral: '0' [oO] [0-7] [_0-7]* 'n'; BigBinaryIntegerLiteral: '0' [bB] [01] [_01]* 'n'; BigDecimalIntegerLiteral: DecimalIntegerLiteral 'n'; /// Keywords Break: 'break'; Do: 'do'; Instanceof: 'instanceof'; Typeof: 'typeof'; Case: 'case'; Else: 'else'; New: 'new'; Var: 'var'; Catch: 'catch'; Finally: 'finally'; Return: 'return'; Void: 'void'; Continue: 'continue'; For: 'for'; Switch: 'switch'; While: 'while'; Debugger: 'debugger'; Function: 'function'; This: 'this'; With: 'with'; Default: 'default'; If: 'if'; Throw: 'throw'; Delete: 'delete'; In: 'in'; Try: 'try'; As: 'as'; From: 'from'; /// Future Reserved Words Class: 'class'; Enum: 'enum'; Extends: 'extends'; Super: 'super'; Const: 'const'; Export: 'export'; Import: 'import'; Async: 'async'; Await: 'await'; /// The following tokens are also considered to be FutureReservedWords /// when parsing strict mode Implements: 'implements' {this.IsStrictMode()}?; StrictLet: 'let' {this.IsStrictMode()}?; NonStrictLet: 'let' {!this.IsStrictMode()}?; Private: 'private' {this.IsStrictMode()}?; Public: 'public' {this.IsStrictMode()}?; Interface: 'interface' {this.IsStrictMode()}?; Package: 'package' {this.IsStrictMode()}?; Protected: 'protected' {this.IsStrictMode()}?; Static: 'static' {this.IsStrictMode()}?; Yield: 'yield' {this.IsStrictMode()}?; /// Identifier Names and Identifiers Identifier: IdentifierStart IdentifierPart*; /// String Literals StringLiteral: ('"' DoubleStringCharacter* '"' | '\'' SingleStringCharacter* '\'') {this.ProcessStringLiteral();} ; LinkLiteral: ('http' 's'? | 'ftp' | 'file') '://' [a-zA-Z0-9./?=]+; // TODO Could be more precise // TODO: `${`tmp`}` TemplateStringLiteral: '`' ('\\`' | ~'`')* '`'; WhiteSpaces: [\t\u000B\u000C\u0020\u00A0]+ -> channel(HIDDEN); LineTerminator: [\r\n\u2028\u2029] -> channel(HIDDEN); /// Comments JsxComment: '{/*' .*? '*/}' -> channel(HIDDEN); MultiLineComment: '/*' .*? '*/' -> channel(HIDDEN); SingleLineComment: '//' ~[\r\n\u2028\u2029]* -> channel(HIDDEN); RegularExpressionLiteral: '/' RegularExpressionFirstChar RegularExpressionChar* {this.IsRegexPossible()}? '/' IdentifierPart*; HtmlComment: '<!--' .*? '-->' -> channel(HIDDEN); CDataComment: '<![CDATA[' .*? ']]>' -> channel(HIDDEN); UnexpectedCharacter: . -> channel(ERROR); CDATA: '<![CDATA[' .*? ']]>' -> channel(HIDDEN); // // html tag declarations // mode TAG; TagOpen : LessThan -> pushMode(TAG) ; TagClose : MoreThan -> popMode ; TagSlashClose : '/>' -> popMode ; TagSlash : Divide ; TagName : TagNameStartChar TagNameChar* ; // an attribute value may have spaces b/t the '=' and the value AttributeValue : [ ]* Attribute -> popMode ; Attribute : DoubleQuoteString | SingleQuoteString | AttributeChar | HexChars | DecChars ; // // lexing mode for attribute values // mode ATTVALUE; TagEquals : Assign -> pushMode(ATTVALUE) ; // Fragment rules fragment AttributeChar : '-' | '_' | '.' | '/' | '+' | ',' | '?' | '=' | ':' | ';' | '#' | [0-9a-zA-Z] ; fragment AttributeChars : AttributeChar+ ' '? ; fragment HexChars : '#' [0-9a-fA-F]+ ; fragment DecChars : [0-9]+ '%'? ; fragment DoubleQuoteString : '"' ~[<"]* '"' ; fragment SingleQuoteString : '\'' ~[<']* '\'' ; fragment TagNameStartChar : [:a-zA-Z] | '\u2070'..'\u218F' | '\u2C00'..'\u2FEF' | '\u3001'..'\uD7FF' | '\uF900'..'\uFDCF' | '\uFDF0'..'\uFFFD' ; fragment TagNameChar : TagNameStartChar | '-' | '_' | '.' | Digit | '\u00B7' | '\u0300'..'\u036F' | '\u203F'..'\u2040' ; fragment Digit : [0-9] ; fragment DoubleStringCharacter : ~["\\] | '\\' EscapeSequence | LineContinuation ; fragment SingleStringCharacter : ~['\\] | '\\' EscapeSequence | LineContinuation ; fragment EscapeSequence : CharacterEscapeSequence | '0' // no digit ahead! TODO | HexEscapeSequence | UnicodeEscapeSequence | ExtendedUnicodeEscapeSequence ; fragment CharacterEscapeSequence : SingleEscapeCharacter | NonEscapeCharacter ; fragment HexEscapeSequence : 'x' HexDigit HexDigit ; fragment UnicodeEscapeSequence : 'u' HexDigit HexDigit HexDigit HexDigit | 'u' '{' HexDigit HexDigit+ '}' ; fragment ExtendedUnicodeEscapeSequence : 'u' '{' HexDigit+ '}' ; fragment SingleEscapeCharacter : ['"\\bfnrtv] ; fragment NonEscapeCharacter : ~['"\\bfnrtv0-9xu\r\n] ; fragment EscapeCharacter : SingleEscapeCharacter | [0-9] | [xu] ; fragment LineContinuation : '\\' [\r\n\u2028\u2029] ; fragment HexDigit : [_0-9a-fA-F] ; fragment DecimalIntegerLiteral : '0' | [1-9] [0-9_]* ; fragment ExponentPart : [eE] [+-]? [0-9_]+ ; fragment IdentifierPart : IdentifierStart | [\p{Mn}] | [\p{Nd}] | [\p{Pc}] | '\u200C' | '\u200D' ; fragment IdentifierStart : [\p{L}] | [$_] | '\\' UnicodeEscapeSequence ; fragment RegularExpressionFirstChar : ~[*\r\n\u2028\u2029\\/[] | RegularExpressionBackslashSequence | '[' RegularExpressionClassChar* ']' ; fragment RegularExpressionChar : ~[\r\n\u2028\u2029\\/[] | RegularExpressionBackslashSequence | '[' RegularExpressionClassChar* ']' ; fragment RegularExpressionClassChar : ~[\r\n\u2028\u2029\]\\] | RegularExpressionBackslashSequence ; fragment RegularExpressionBackslashSequence : '\\' ~[\r\n\u2028\u2029] ;
Simplify LinkLiteral
Simplify LinkLiteral 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
b903c8c70fa3891d239633919c7cf3b6d19717a6
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<>(); 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 '(' ')' OVER '(' ')' ; 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_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(); };
Define parallelize directive grammar
Define parallelize directive grammar
ANTLR
bsd-2-clause
clementval/claw-compiler,clementval/claw-compiler
da609d92951e84bf37d951f4354e0f8ce7a2d0e9
shardingsphere-sql-parser/shardingsphere-sql-parser-dialect/shardingsphere-sql-parser-sqlserver/src/main/antlr4/imports/sqlserver/BaseRule.g4
shardingsphere-sql-parser/shardingsphere-sql-parser-dialect/shardingsphere-sql-parser-sqlserver/src/main/antlr4/imports/sqlserver/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 Symbol, Keyword, SQLServerKeyword, Literals; parameterMarker : QUESTION_ ; literals : stringLiterals | numberLiterals | dateTimeLiterals | hexadecimalLiterals | bitValueLiterals | booleanLiterals | nullValueLiterals ; stringLiterals : STRING_ ; numberLiterals : MINUS_? NUMBER_ ; dateTimeLiterals : (DATE | TIME | TIMESTAMP) STRING_ | LBE_ identifier STRING_ RBE_ ; hexadecimalLiterals : HEX_DIGIT_ ; bitValueLiterals : BIT_NUM_ ; booleanLiterals : TRUE | FALSE ; nullValueLiterals : NULL ; identifier : IDENTIFIER_ | unreservedWord ; unreservedWord : TRUNCATE | FUNCTION | TRIGGER | LIMIT | OFFSET | SAVEPOINT | BOOLEAN | ARRAY | LOCALTIME | LOCALTIMESTAMP | QUARTER | WEEK | MICROSECOND | ENABLE | DISABLE | BINARY | HIDDEN_ | MOD | PARTITION | TOP | ROW | XOR | ALWAYS | ROLE | START | ALGORITHM | AUTO | BLOCKERS | CLUSTERED | COLUMNSTORE | CONTENT | DATABASE | DAYS | DENY | DETERMINISTIC | DISTRIBUTION | DOCUMENT | DURABILITY | ENCRYPTED | FILESTREAM | FILETABLE | FOLLOWING | HASH | HEAP | INBOUND | INFINITE | LOGIN | MASKED | MAXDOP | MINUTES | MONTHS | MOVE | NOCHECK | NONCLUSTERED | OBJECT | OFF | ONLINE | OUTBOUND | OVER | PAGE | PARTITIONS | PAUSED | PERIOD | PERSISTED | PRECEDING | RANDOMIZED | RANGE | REBUILD | REPLICATE | REPLICATION | RESUMABLE | ROWGUIDCOL | SAVE | SELF | SPARSE | SWITCH | TRAN | TRANCOUNT | UNBOUNDED | YEARS | WEEKS | ABORT_AFTER_WAIT | ALLOW_PAGE_LOCKS | ALLOW_ROW_LOCKS | ALL_SPARSE_COLUMNS | BUCKET_COUNT | COLUMNSTORE_ARCHIVE | COLUMN_ENCRYPTION_KEY | COLUMN_SET | COMPRESSION_DELAY | DATABASE_DEAULT | DATA_COMPRESSION | DATA_CONSISTENCY_CHECK | ENCRYPTION_TYPE | SYSTEM_TIME | SYSTEM_VERSIONING | TEXTIMAGE_ON | WAIT_AT_LOW_PRIORITY | STATISTICS_INCREMENTAL | STATISTICS_NORECOMPUTE | ROUND_ROBIN | SCHEMA_AND_DATA | SCHEMA_ONLY | SORT_IN_TEMPDB | IGNORE_DUP_KEY | IMPLICIT_TRANSACTIONS | MAX_DURATION | MEMORY_OPTIMIZED | MIGRATION_STATE | PAD_INDEX | REMOTE_DATA_ARCHIVE | FILESTREAM_ON | FILETABLE_COLLATE_FILENAME | FILETABLE_DIRECTORY | FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME | FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME | FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME | FILLFACTOR | FILTER_PREDICATE | HISTORY_RETENTION_PERIOD | HISTORY_TABLE | LOCK_ESCALATION | DROP_EXISTING | ROW_NUMBER | CONTROL | TAKE | OWNERSHIP | DEFINITION | APPLICATION | ASSEMBLY | SYMMETRIC | ASYMMETRIC | SERVER | RECEIVE | CHANGE | TRACE | TRACKING | RESOURCES | SETTINGS | STATE | AVAILABILITY | CREDENTIAL | ENDPOINT | EVENT | NOTIFICATION | LINKED | AUDIT | DDL | SQL | XML | IMPERSONATE | SECURABLES | AUTHENTICATE | EXTERNAL | ACCESS | ADMINISTER | BULK | OPERATIONS | UNSAFE | SHUTDOWN | SCOPED | CONFIGURATION |DATASPACE | SERVICE | CERTIFICATE | CONTRACT | ENCRYPTION | MASTER | DATA | SOURCE | FILE | FORMAT | LIBRARY | FULLTEXT | MASK | UNMASK | MESSAGE | TYPE | REMOTE | BINDING | ROUTE | SECURITY | POLICY | AGGREGATE | QUEUE | RULE | SYNONYM | COLLECTION | SCRIPT | KILL | BACKUP | LOG | SHOWPLAN | SUBSCRIBE | QUERY | NOTIFICATIONS | CHECKPOINT | SEQUENCE | INSTANCE | DO | DEFINER | LOCAL | CASCADED | NEXT | NAME | INTEGER | TYPE | MAX | MIN | SUM | COUNT | AVG | FIRST | DATETIME2 ; schemaName : identifier ; tableName : (owner DOT_)? name ; columnName : (owner DOT_)? name ; owner : identifier ; name : identifier ; columnNames : LP_ columnName (COMMA_ columnName)* RP_ ; columnNamesWithSort : LP_ columnNameWithSort (COMMA_ columnNameWithSort)* RP_ ; tableNames : LP_? tableName (COMMA_ tableName)* RP_? ; indexName : identifier ; collationName : STRING_ | IDENTIFIER_ ; alias : IDENTIFIER_ ; dataTypeLength : LP_ (NUMBER_ (COMMA_ NUMBER_)?)? RP_ ; primaryKey : PRIMARY? KEY ; // TODO comb expr expr : expr logicalOperator expr | notOperator_ expr | LP_ expr RP_ | booleanPrimary ; logicalOperator : OR | OR_ | AND | AND_ ; notOperator_ : NOT | NOT_ ; 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_ expr (COMMA_ expr)* RP_ | bitExpr NOT? BETWEEN bitExpr AND predicate | bitExpr NOT? LIKE simpleExpr (ESCAPE 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 CARET_ bitExpr | simpleExpr ; simpleExpr : functionCall | parameterMarker | literals | columnName | simpleExpr OR_ simpleExpr | (PLUS_ | MINUS_ | TILDE_ | NOT_ | BINARY) simpleExpr | ROW? LP_ expr (COMMA_ expr)* RP_ | EXISTS? subquery | LBE_ identifier expr RBE_ | caseExpression | privateExprOfDb ; functionCall : aggregationFunction | specialFunction | regularFunction ; aggregationFunction : aggregationFunctionName LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? RP_ ; aggregationFunctionName : MAX | MIN | SUM | COUNT | AVG ; distinct : DISTINCT ; specialFunction : castFunction | charFunction ; castFunction : CAST LP_ expr AS dataType RP_ ; charFunction : CHAR LP_ expr (COMMA_ expr)* (USING ignoredIdentifier_)? RP_ ; regularFunction : regularFunctionName_ LP_ (expr (COMMA_ expr)* | ASTERISK_)? RP_ ; regularFunctionName_ : identifier | IF | LOCALTIME | LOCALTIMESTAMP | INTERVAL ; caseExpression : CASE simpleExpr? caseWhen_+ caseElse_? ; caseWhen_ : WHEN expr THEN expr ; caseElse_ : ELSE expr ; privateExprOfDb : windowedFunction | atTimeZoneExpr | castExpr | convertExpr ; subquery : matchNone ; orderByClause : ORDER BY orderByItem (COMMA_ orderByItem)* (OFFSET expr (ROW | ROWS) (FETCH (FIRST | NEXT) expr (ROW | ROWS) ONLY)?)? ; orderByItem : (columnName | numberLiterals | expr) (ASC | DESC)? ; dataType : dataTypeName (dataTypeLength | LP_ MAX RP_ | LP_ (CONTENT | DOCUMENT)? ignoredIdentifier_ RP_)? ; dataTypeName : BIGINT | NUMERIC | BIT | SMALLINT | DECIMAL | SMALLMONEY | INT | TINYINT | MONEY | FLOAT | REAL | DATE | DATETIMEOFFSET | SMALLDATETIME | DATETIME | DATETIME2 | TIME | CHAR | VARCHAR | TEXT | NCHAR | NVARCHAR | NTEXT | BINARY | VARBINARY | IMAGE | SQL_VARIANT | XML | UNIQUEIDENTIFIER | HIERARCHYID | GEOMETRY | GEOGRAPHY | IDENTIFIER_ ; atTimeZoneExpr : IDENTIFIER_ (WITH TIME ZONE)? STRING_ ; castExpr : CAST LP_ expr AS dataType (LP_ NUMBER_ RP_)? RP_ ; convertExpr : CONVERT (dataType (LP_ NUMBER_ RP_)? COMMA_ expr (COMMA_ NUMBER_)?) ; windowedFunction : functionCall overClause ; overClause : OVER LP_ partitionByClause? orderByClause? rowRangeClause? RP_ ; partitionByClause : PARTITION BY expr (COMMA_ expr)* ; rowRangeClause : (ROWS | RANGE) windowFrameExtent ; windowFrameExtent : windowFramePreceding | windowFrameBetween ; windowFrameBetween : BETWEEN windowFrameBound AND windowFrameBound ; windowFrameBound : windowFramePreceding | windowFrameFollowing ; windowFramePreceding : UNBOUNDED PRECEDING | NUMBER_ PRECEDING | CURRENT ROW ; windowFrameFollowing : UNBOUNDED FOLLOWING | NUMBER_ FOLLOWING | CURRENT ROW ; columnNameWithSort : columnName (ASC | DESC)? ; indexOption : FILLFACTOR EQ_ NUMBER_ | eqOnOffOption | (COMPRESSION_DELAY | MAX_DURATION) eqTime | MAXDOP EQ_ NUMBER_ | compressionOption onPartitionClause? ; compressionOption : DATA_COMPRESSION EQ_ (NONE | ROW | PAGE | COLUMNSTORE | COLUMNSTORE_ARCHIVE) ; eqTime : EQ_ NUMBER_ (MINUTES)? ; eqOnOffOption : eqKey eqOnOff ; eqKey : PAD_INDEX | SORT_IN_TEMPDB | IGNORE_DUP_KEY | STATISTICS_NORECOMPUTE | STATISTICS_INCREMENTAL | DROP_EXISTING | ONLINE | RESUMABLE | ALLOW_ROW_LOCKS | ALLOW_PAGE_LOCKS | COMPRESSION_DELAY | SORT_IN_TEMPDB ; eqOnOff : EQ_ (ON | OFF) ; onPartitionClause : ON PARTITIONS LP_ partitionExpressions RP_ ; partitionExpressions : partitionExpression (COMMA_ partitionExpression)* ; partitionExpression : NUMBER_ | numberRange ; numberRange : NUMBER_ TO NUMBER_ ; lowPriorityLockWait : WAIT_AT_LOW_PRIORITY LP_ MAX_DURATION EQ_ NUMBER_ (MINUTES)? COMMA_ ABORT_AFTER_WAIT EQ_ (NONE | SELF | BLOCKERS) RP_ ; onLowPriorLockWait : ON (LP_ lowPriorityLockWait 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 Symbol, Keyword, SQLServerKeyword, Literals; parameterMarker : QUESTION_ ; literals : stringLiterals | numberLiterals | dateTimeLiterals | hexadecimalLiterals | bitValueLiterals | booleanLiterals | nullValueLiterals ; stringLiterals : STRING_ ; numberLiterals : MINUS_? NUMBER_ ; dateTimeLiterals : (DATE | TIME | TIMESTAMP) STRING_ | LBE_ identifier STRING_ RBE_ ; hexadecimalLiterals : HEX_DIGIT_ ; bitValueLiterals : BIT_NUM_ ; booleanLiterals : TRUE | FALSE ; nullValueLiterals : NULL ; identifier : IDENTIFIER_ | unreservedWord ; unreservedWord : TRUNCATE | FUNCTION | TRIGGER | LIMIT | OFFSET | SAVEPOINT | BOOLEAN | ARRAY | LOCALTIME | LOCALTIMESTAMP | QUARTER | WEEK | MICROSECOND | ENABLE | DISABLE | BINARY | HIDDEN_ | MOD | PARTITION | TOP | ROW | XOR | ALWAYS | ROLE | START | ALGORITHM | AUTO | BLOCKERS | CLUSTERED | COLUMNSTORE | CONTENT | DATABASE | DAYS | DENY | DETERMINISTIC | DISTRIBUTION | DOCUMENT | DURABILITY | ENCRYPTED | FILESTREAM | FILETABLE | FOLLOWING | HASH | HEAP | INBOUND | INFINITE | LOGIN | MASKED | MAXDOP | MINUTES | MONTHS | MOVE | NOCHECK | NONCLUSTERED | OBJECT | OFF | ONLINE | OUTBOUND | OVER | PAGE | PARTITIONS | PAUSED | PERIOD | PERSISTED | PRECEDING | RANDOMIZED | RANGE | REBUILD | REPLICATE | REPLICATION | RESUMABLE | ROWGUIDCOL | SAVE | SELF | SPARSE | SWITCH | TRAN | TRANCOUNT | UNBOUNDED | YEARS | WEEKS | ABORT_AFTER_WAIT | ALLOW_PAGE_LOCKS | ALLOW_ROW_LOCKS | ALL_SPARSE_COLUMNS | BUCKET_COUNT | COLUMNSTORE_ARCHIVE | COLUMN_ENCRYPTION_KEY | COLUMN_SET | COMPRESSION_DELAY | DATABASE_DEAULT | DATA_COMPRESSION | DATA_CONSISTENCY_CHECK | ENCRYPTION_TYPE | SYSTEM_TIME | SYSTEM_VERSIONING | TEXTIMAGE_ON | WAIT_AT_LOW_PRIORITY | STATISTICS_INCREMENTAL | STATISTICS_NORECOMPUTE | ROUND_ROBIN | SCHEMA_AND_DATA | SCHEMA_ONLY | SORT_IN_TEMPDB | IGNORE_DUP_KEY | IMPLICIT_TRANSACTIONS | MAX_DURATION | MEMORY_OPTIMIZED | MIGRATION_STATE | PAD_INDEX | REMOTE_DATA_ARCHIVE | FILESTREAM_ON | FILETABLE_COLLATE_FILENAME | FILETABLE_DIRECTORY | FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME | FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME | FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME | FILLFACTOR | FILTER_PREDICATE | HISTORY_RETENTION_PERIOD | HISTORY_TABLE | LOCK_ESCALATION | DROP_EXISTING | ROW_NUMBER | CONTROL | TAKE | OWNERSHIP | DEFINITION | APPLICATION | ASSEMBLY | SYMMETRIC | ASYMMETRIC | SERVER | RECEIVE | CHANGE | TRACE | TRACKING | RESOURCES | SETTINGS | STATE | AVAILABILITY | CREDENTIAL | ENDPOINT | EVENT | NOTIFICATION | LINKED | AUDIT | DDL | SQL | XML | IMPERSONATE | SECURABLES | AUTHENTICATE | EXTERNAL | ACCESS | ADMINISTER | BULK | OPERATIONS | UNSAFE | SHUTDOWN | SCOPED | CONFIGURATION |DATASPACE | SERVICE | CERTIFICATE | CONTRACT | ENCRYPTION | MASTER | DATA | SOURCE | FILE | FORMAT | LIBRARY | FULLTEXT | MASK | UNMASK | MESSAGE | TYPE | REMOTE | BINDING | ROUTE | SECURITY | POLICY | AGGREGATE | QUEUE | RULE | SYNONYM | COLLECTION | SCRIPT | KILL | BACKUP | LOG | SHOWPLAN | SUBSCRIBE | QUERY | NOTIFICATIONS | CHECKPOINT | SEQUENCE | INSTANCE | DO | DEFINER | LOCAL | CASCADED | NEXT | NAME | INTEGER | TYPE | MAX | MIN | SUM | COUNT | AVG | FIRST | DATETIME2 | OUTPUT | INSERTED | DELETED ; schemaName : identifier ; tableName : (owner DOT_)? name ; columnName : (owner DOT_)? name ; owner : identifier ; name : identifier ; columnNames : LP_ columnName (COMMA_ columnName)* RP_ ; columnNamesWithSort : LP_ columnNameWithSort (COMMA_ columnNameWithSort)* RP_ ; tableNames : LP_? tableName (COMMA_ tableName)* RP_? ; indexName : identifier ; collationName : STRING_ | IDENTIFIER_ ; alias : IDENTIFIER_ ; dataTypeLength : LP_ (NUMBER_ (COMMA_ NUMBER_)?)? RP_ ; primaryKey : PRIMARY? KEY ; // TODO comb expr expr : expr logicalOperator expr | notOperator_ expr | LP_ expr RP_ | booleanPrimary ; logicalOperator : OR | OR_ | AND | AND_ ; notOperator_ : NOT | NOT_ ; 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_ expr (COMMA_ expr)* RP_ | bitExpr NOT? BETWEEN bitExpr AND predicate | bitExpr NOT? LIKE simpleExpr (ESCAPE 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 CARET_ bitExpr | simpleExpr ; simpleExpr : functionCall | parameterMarker | literals | columnName | simpleExpr OR_ simpleExpr | (PLUS_ | MINUS_ | TILDE_ | NOT_ | BINARY) simpleExpr | ROW? LP_ expr (COMMA_ expr)* RP_ | EXISTS? subquery | LBE_ identifier expr RBE_ | caseExpression | privateExprOfDb ; functionCall : aggregationFunction | specialFunction | regularFunction ; aggregationFunction : aggregationFunctionName LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? RP_ ; aggregationFunctionName : MAX | MIN | SUM | COUNT | AVG ; distinct : DISTINCT ; specialFunction : castFunction | charFunction ; castFunction : CAST LP_ expr AS dataType RP_ ; charFunction : CHAR LP_ expr (COMMA_ expr)* (USING ignoredIdentifier_)? RP_ ; regularFunction : regularFunctionName_ LP_ (expr (COMMA_ expr)* | ASTERISK_)? RP_ ; regularFunctionName_ : identifier | IF | LOCALTIME | LOCALTIMESTAMP | INTERVAL ; caseExpression : CASE simpleExpr? caseWhen_+ caseElse_? ; caseWhen_ : WHEN expr THEN expr ; caseElse_ : ELSE expr ; privateExprOfDb : windowedFunction | atTimeZoneExpr | castExpr | convertExpr ; subquery : matchNone ; orderByClause : ORDER BY orderByItem (COMMA_ orderByItem)* (OFFSET expr (ROW | ROWS) (FETCH (FIRST | NEXT) expr (ROW | ROWS) ONLY)?)? ; orderByItem : (columnName | numberLiterals | expr) (ASC | DESC)? ; dataType : dataTypeName (dataTypeLength | LP_ MAX RP_ | LP_ (CONTENT | DOCUMENT)? ignoredIdentifier_ RP_)? ; dataTypeName : BIGINT | NUMERIC | BIT | SMALLINT | DECIMAL | SMALLMONEY | INT | TINYINT | MONEY | FLOAT | REAL | DATE | DATETIMEOFFSET | SMALLDATETIME | DATETIME | DATETIME2 | TIME | CHAR | VARCHAR | TEXT | NCHAR | NVARCHAR | NTEXT | BINARY | VARBINARY | IMAGE | SQL_VARIANT | XML | UNIQUEIDENTIFIER | HIERARCHYID | GEOMETRY | GEOGRAPHY | IDENTIFIER_ ; atTimeZoneExpr : IDENTIFIER_ (WITH TIME ZONE)? STRING_ ; castExpr : CAST LP_ expr AS dataType (LP_ NUMBER_ RP_)? RP_ ; convertExpr : CONVERT (dataType (LP_ NUMBER_ RP_)? COMMA_ expr (COMMA_ NUMBER_)?) ; windowedFunction : functionCall overClause ; overClause : OVER LP_ partitionByClause? orderByClause? rowRangeClause? RP_ ; partitionByClause : PARTITION BY expr (COMMA_ expr)* ; rowRangeClause : (ROWS | RANGE) windowFrameExtent ; windowFrameExtent : windowFramePreceding | windowFrameBetween ; windowFrameBetween : BETWEEN windowFrameBound AND windowFrameBound ; windowFrameBound : windowFramePreceding | windowFrameFollowing ; windowFramePreceding : UNBOUNDED PRECEDING | NUMBER_ PRECEDING | CURRENT ROW ; windowFrameFollowing : UNBOUNDED FOLLOWING | NUMBER_ FOLLOWING | CURRENT ROW ; columnNameWithSort : columnName (ASC | DESC)? ; indexOption : FILLFACTOR EQ_ NUMBER_ | eqOnOffOption | (COMPRESSION_DELAY | MAX_DURATION) eqTime | MAXDOP EQ_ NUMBER_ | compressionOption onPartitionClause? ; compressionOption : DATA_COMPRESSION EQ_ (NONE | ROW | PAGE | COLUMNSTORE | COLUMNSTORE_ARCHIVE) ; eqTime : EQ_ NUMBER_ (MINUTES)? ; eqOnOffOption : eqKey eqOnOff ; eqKey : PAD_INDEX | SORT_IN_TEMPDB | IGNORE_DUP_KEY | STATISTICS_NORECOMPUTE | STATISTICS_INCREMENTAL | DROP_EXISTING | ONLINE | RESUMABLE | ALLOW_ROW_LOCKS | ALLOW_PAGE_LOCKS | COMPRESSION_DELAY | SORT_IN_TEMPDB ; eqOnOff : EQ_ (ON | OFF) ; onPartitionClause : ON PARTITIONS LP_ partitionExpressions RP_ ; partitionExpressions : partitionExpression (COMMA_ partitionExpression)* ; partitionExpression : NUMBER_ | numberRange ; numberRange : NUMBER_ TO NUMBER_ ; lowPriorityLockWait : WAIT_AT_LOW_PRIORITY LP_ MAX_DURATION EQ_ NUMBER_ (MINUTES)? COMMA_ ABORT_AFTER_WAIT EQ_ (NONE | SELF | BLOCKERS) RP_ ; onLowPriorLockWait : ON (LP_ lowPriorityLockWait RP_)? ; ignoredIdentifier_ : IDENTIFIER_ ; ignoredIdentifiers_ : ignoredIdentifier_ (COMMA_ ignoredIdentifier_)* ; matchNone : 'Default does not match anything' ;
add SQLServer output keywords to unreserved word.
add SQLServer output keywords to unreserved word.
ANTLR
apache-2.0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
de2a1fd38d1ed61dd65653b47c8317599a8744b9
graphene/parser/GQL.g4
graphene/parser/GQL.g4
grammar GQL; @header { from graphene.commands import * from graphene.expressions import * } // General parsing, including statement lists parse : stmt_list EOF; stmt_list returns [stmts] : s1=stmt {$stmts = [$s1.ctx]} (';' (si=stmt {$stmts.append($si.ctx)})? )* ; stmt : ( c=match_stmt | c=create_stmt | c=delete_stmt | c=exit_stmt | c=show_stmt | c=desc_stmt | c=insert_stmt ) ; // EXIT command exit_stmt returns [cmd] : (K_EXIT | K_QUIT) {$cmd = ExitCommand()} ; // MATCH command match_stmt returns [cmd] @init {$cmd = None} : K_MATCH (nc=node_chain) (K_WHERE (qc=query_chain))? (K_RETURN (rc=return_chain))? {$cmd = MatchCommand($nc.ctx, $qc.ctx, $rc.ctx)} ; node_chain returns [chain] @init {$chain = []} : (n1=node {$chain.append($n1.ctx)}) (ri=relation {$chain.append($ri.ctx)} ni=node {$chain.append($ni.ctx)})* {return $chain} ; node : '(' (nn=I_NAME ':')? (nt=I_TYPE) ')' {return MatchNode($nn.text, $nt.text)} ; ident : ((ii=I_NAME) '.')? ni=I_NAME {return ($ii.text, $ni.text)} ; return_chain returns [chain] @init {$chain = []} : (i1=ident {$chain.append($i1.ctx)}) (',' ii=ident {$chain.append($ii.ctx)})* {return $chain} ; // Queries logic_op : (K_AND | K_OR) ; logic_test : (('!' | '>' | '<')? '=' | '<' | '>') ; query_chain returns [queries] @init {$queries = []} : ('(' {$queries.append("(")})? (q1=query {$queries.append($q1.ctx)}) (op=logic_op {$queries.append($op.text)} qi=query_chain {$queries += $qi.ctx})* (')' {$queries.append(")")})? {return $queries} ; query : name=ident test=logic_test (name2=ident | val=(Literal | '[]')) { if $name2.ctx is not None: return ($name.ctx, $test.text, $name2.ctx) else: return ($name.ctx, $test.text, $val.text) } ; node_query : (t=I_TYPE {$t=$t.text}) ('(' (qc=query_chain) ')')? {return ($t, $qc.ctx or ())} ; relation_query : '-' '[' (rel=(I_RELATION|I_TYPE) {$rel.text.isupper()}? {$rel = $rel.text}) ('(' (qc=query_chain) ')')? ']' '->' {return ($rel, $qc.ctx or ())} ; /* * I_RELATION matches all totally uppercase strings, and I_TYPE matches all * strings that start with a capital letter... but if the string is one * character long, this is ambiguous. Hence we allow both identifier * possibilities, but ensure they pass the fully uppercase predicate. */ relation : '-' '[' (rn=I_NAME ':')? (rel=(I_RELATION|I_TYPE) {$rel.text.isupper()}?) ']' '->' {return MatchRelation($rn.text, $rel.text)} ; // CREATE command create_stmt returns [cmd] @init {$cmd = None} : K_CREATE ( ct=create_type | cr=create_relation ) { if $ct.ctx is not None: $cmd = CreateTypeCommand($ct.ctx) else: $cmd = CreateRelationCommand($cr.ctx) } ; create_type : K_TYPE (t=I_TYPE {$t=$t.text}) '(' (tl=type_list) ')' ; type_list returns [tds] : td1=type_decl {$tds = [$td1.ctx]} (',' (tdi=type_decl {$tds.append($tdi.ctx)}))* {return $tds} ; prop_type : (T_INT | T_LONG | T_BOOL | T_SHORT | T_CHAR | T_FLOAT | T_DOUBLE | T_STRING) ('[]')? ; type_decl : (n=I_NAME) ':' (t=prop_type) {return ($n.text, $t.text)} ; create_relation : K_RELATION (r=(I_RELATION|I_TYPE) {$r.text.isupper()}? {$r=$r.text}) ('(' (tl=type_list)? ')')?; // DELETE command delete_stmt returns [cmd] @init {$cmd = None} : K_DELETE ( dt=delete_type | dr=delete_relation ) { if $dt.ctx is not None: $cmd = DeleteTypeCommand($dt.ctx) if $dr.ctx is not None: $cmd = DeleteRelationCommand($dr.ctx) } ; delete_type : K_TYPE (t=I_TYPE {$t=$t.text}) ; delete_relation : K_RELATION (t=(I_RELATION|I_TYPE) {$t.text.isupper()}? {$t=$t.text}) ; // SHOW command show_stmt returns [cmd] @init {$cmd = None} : K_SHOW (K_TYPES {t = ShowCommand.ShowType.TYPES} | K_RELATIONS {t = ShowCommand.ShowType.RELATIONS}) {$cmd = ShowCommand(t)} ; // DESC command desc_stmt returns [cmd] @init {$cmd = None} : K_DESC (K_TYPE (t=I_TYPE {$t=$t.text})) {$cmd = DescTypeCommand($t)} ; // INSERT command insert_stmt returns [cmd] @init {$cmd = None} : K_INSERT ( inode=insert_node | irel=insert_relation //| igraph=insert_graph ) { if $inode.ctx is not None: $cmd = InsertNodeCommand($inode.ctx) if $irel.ctx is not None: $cmd = InsertRelationCommand($irel.ctx) } ; insert_node returns [nodeprops] : K_NODE np1=node_with_props {$nodeprops = [$np1.ctx]} (',' (npi=node_with_props {$nodeprops.append($npi.ctx)}))* {return $nodeprops} ; node_with_props : (t=I_TYPE {$t=$t.text}) '(' (pl=prop_list) ')' ; relation_with_props : '-' '[' (rel=(I_RELATION|I_TYPE) {$rel.text.isupper()}? {$rel = $rel.text}) ('(' (pl=prop_list) ')')? ']' '->' {return ($rel, $pl.ctx)} ; prop_list returns [props] : p1=prop_value {$props = [$p1.ctx]} (',' (pi=prop_value {$props.append($pi.ctx)}))* {return $props} ; prop_value : (v=(Literal | '[]')) {return $v.text} ; insert_relation : K_RELATION (n1=node_query) (r=relation_with_props) (n2=node_query) {return ($r.ctx, $n1.ctx, $n2.ctx)} ; // Literals Literal : (ArrayLiteral | SingleLiteral); IntLiteral : ('-' | '+')? DIGIT+; FloatLiteral : ('-' | '+')? DIGIT+ '.' DIGIT* ; StringLiteral : '"' StringChars? '"' ; BooleanLiteral : (T R U E | F A L S E) ; StringArrayLiteral : StringLiteral (',' StringLiteral)*; IntArrayLiteral : IntLiteral (',' IntLiteral)*; BooleanArrayLiteral : BooleanLiteral (',' BooleanLiteral)*; FloatArrayLiteral : FloatLiteral (',' FloatLiteral)*; ArrayLiteral : '[' ( StringArrayLiteral | IntArrayLiteral | BooleanArrayLiteral | FloatArrayLiteral ) ']'; SingleLiteral : (StringLiteral | IntLiteral | BooleanLiteral | FloatLiteral) ; // Keywords K_MATCH : M A T C H ; K_CREATE : C R E A T E ; K_DELETE : D E L E T E ; K_EXIT : E X I T ; K_QUIT : Q U I T ; K_SHOW : S H O W ; K_DESC : D E S C ; K_INSERT : I N S E R T ; K_TYPE : T Y P E ; K_RELATION : R E L A T I O N ; K_NODE : N O D E ; K_TYPES : T Y P E S ; K_RELATIONS : R E L A T I O N S ; K_WHERE : W H E R E ; K_RETURN : R E T U R N; K_AND : A N D ; K_OR : O R ; // Types T_INT : I N T ; T_LONG : L O N G ; T_BOOL : B O O L ; T_SHORT : S H O R T ; T_CHAR : C H A R ; T_FLOAT : F L O A T ; T_DOUBLE : D O U B L E ; T_STRING : S T R I N G ; // Identifiers I_NAME : LCASE (LCASE | DIGIT | OTHER_VALID)* ; I_TYPE : UCASE LETTER*; I_RELATION : UCASE (UCASE | OTHER_VALID)+ {self.text.isupper()}?; // Other tokens SPACES : [ \u000B\u000C\t\r\n] -> channel(HIDDEN) ; BLOCK_COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ; fragment OTHER_VALID : [_\-]; fragment DIGIT : [0-9]; fragment LETTER : [A-Za-z]; fragment UCASE : [A-Z]; fragment LCASE : [a-z]; fragment A : [aA]; fragment B : [bB]; fragment C : [cC]; fragment D : [dD]; fragment E : [eE]; fragment F : [fF]; fragment G : [gG]; fragment H : [hH]; fragment I : [iI]; fragment J : [jJ]; fragment K : [kK]; fragment L : [lL]; fragment M : [mM]; fragment N : [nN]; fragment O : [oO]; fragment P : [pP]; fragment Q : [qQ]; fragment R : [rR]; fragment S : [sS]; fragment T : [tT]; fragment U : [uU]; fragment V : [vV]; fragment W : [wW]; fragment X : [xX]; fragment Y : [yY]; fragment Z : [zZ]; fragment StringChars : StringChar+ ; fragment StringChar : ~["\\] | EscapeSeq ; fragment EscapeSeq : '\\' [btnfr"'\\] ;
grammar GQL; @header { from graphene.commands import * from graphene.expressions import * } // General parsing, including statement lists parse : stmt_list EOF; stmt_list returns [stmts] : s1=stmt {$stmts = [$s1.ctx]} (';' (si=stmt {$stmts.append($si.ctx)})? )* ; stmt : ( c=match_stmt | c=create_stmt | c=delete_stmt | c=exit_stmt | c=show_stmt | c=desc_stmt | c=insert_stmt ) ; // EXIT command exit_stmt returns [cmd] : (K_EXIT | K_QUIT) {$cmd = ExitCommand()} ; // MATCH command match_stmt returns [cmd] @init {$cmd = None} : K_MATCH (nc=node_chain) (K_WHERE (qc=query_chain))? (K_RETURN (rc=return_chain))? {$cmd = MatchCommand($nc.ctx, $qc.ctx, $rc.ctx)} ; node_chain returns [chain] @init {$chain = []} : (n1=node {$chain.append($n1.ctx)}) (ri=relation {$chain.append($ri.ctx)} ni=node {$chain.append($ni.ctx)})* {return $chain} ; node : '(' (nn=I_NAME ':')? (nt=I_TYPE) ')' {return MatchNode($nn.text, $nt.text)} ; ident : ((ii=I_NAME) '.')? ni=I_NAME {return ($ii.text, $ni.text)} ; return_chain returns [chain] @init {$chain = []} : (i1=ident {$chain.append($i1.ctx)}) (',' ii=ident {$chain.append($ii.ctx)})* {return $chain} ; // Queries logic_op : (K_AND | K_OR) ; logic_test : (('!' | '>' | '<')? '=' | '<' | '>') ; query_chain returns [queries] @init {$queries = []} : ('(' {$queries.append("(")})? (q1=query {$queries.append($q1.ctx)}) (op=logic_op {$queries.append($op.text)} qi=query_chain {$queries += $qi.ctx})* (')' {$queries.append(")")})? {return $queries} ; query : name=ident test=logic_test (name2=ident | val=literal) { if $name2.ctx is not None: return ($name.ctx, $test.text, $name2.ctx) else: return ($name.ctx, $test.text, $val.text) } ; node_query : (t=I_TYPE {$t=$t.text}) ('(' (qc=query_chain) ')')? {return ($t, $qc.ctx or ())} ; relation_query : '-' '[' (rel=(I_RELATION|I_TYPE) {$rel.text.isupper()}? {$rel = $rel.text}) ('(' (qc=query_chain) ')')? ']' '->' {return ($rel, $qc.ctx or ())} ; /* * I_RELATION matches all totally uppercase strings, and I_TYPE matches all * strings that start with a capital letter... but if the string is one * character long, this is ambiguous. Hence we allow both identifier * possibilities, but ensure they pass the fully uppercase predicate. */ relation : '-' '[' (rn=I_NAME ':')? (rel=(I_RELATION|I_TYPE) {$rel.text.isupper()}?) ']' '->' {return MatchRelation($rn.text, $rel.text)} ; // CREATE command create_stmt returns [cmd] @init {$cmd = None} : K_CREATE ( ct=create_type | cr=create_relation ) { if $ct.ctx is not None: $cmd = CreateTypeCommand($ct.ctx) else: $cmd = CreateRelationCommand($cr.ctx) } ; create_type : K_TYPE (t=I_TYPE {$t=$t.text}) '(' (tl=type_list) ')' ; type_list returns [tds] : td1=type_decl {$tds = [$td1.ctx]} (',' (tdi=type_decl {$tds.append($tdi.ctx)}))* {return $tds} ; prop_type : (T_INT | T_LONG | T_BOOL | T_SHORT | T_CHAR | T_FLOAT | T_DOUBLE | T_STRING) ('[]')? ; type_decl : (n=I_NAME) ':' (t=prop_type) {return ($n.text, $t.text)} ; create_relation : K_RELATION (r=(I_RELATION|I_TYPE) {$r.text.isupper()}? {$r=$r.text}) ('(' (tl=type_list)? ')')?; // DELETE command delete_stmt returns [cmd] @init {$cmd = None} : K_DELETE ( dt=delete_type | dr=delete_relation ) { if $dt.ctx is not None: $cmd = DeleteTypeCommand($dt.ctx) if $dr.ctx is not None: $cmd = DeleteRelationCommand($dr.ctx) } ; delete_type : K_TYPE (t=I_TYPE {$t=$t.text}) ; delete_relation : K_RELATION (t=(I_RELATION|I_TYPE) {$t.text.isupper()}? {$t=$t.text}) ; // SHOW command show_stmt returns [cmd] @init {$cmd = None} : K_SHOW (K_TYPES {t = ShowCommand.ShowType.TYPES} | K_RELATIONS {t = ShowCommand.ShowType.RELATIONS}) {$cmd = ShowCommand(t)} ; // DESC command desc_stmt returns [cmd] @init {$cmd = None} : K_DESC (K_TYPE (t=I_TYPE {$t=$t.text})) {$cmd = DescTypeCommand($t)} ; // INSERT command insert_stmt returns [cmd] @init {$cmd = None} : K_INSERT ( inode=insert_node | irel=insert_relation //| igraph=insert_graph ) { if $inode.ctx is not None: $cmd = InsertNodeCommand($inode.ctx) if $irel.ctx is not None: $cmd = InsertRelationCommand($irel.ctx) } ; insert_node returns [nodeprops] : K_NODE np1=node_with_props {$nodeprops = [$np1.ctx]} (',' (npi=node_with_props {$nodeprops.append($npi.ctx)}))* {return $nodeprops} ; node_with_props : (t=I_TYPE {$t=$t.text}) '(' (pl=prop_list) ')' ; relation_with_props : '-' '[' (rel=(I_RELATION|I_TYPE) {$rel.text.isupper()}? {$rel = $rel.text}) ('(' (pl=prop_list) ')')? ']' '->' {return ($rel, $pl.ctx)} ; prop_list returns [props] : p1=prop_value {$props = [$p1.ctx]} (',' (pi=prop_value {$props.append($pi.ctx)}))* {return $props} ; prop_value : v=literal {return $v.text} ; insert_relation : K_RELATION (n1=node_query) (r=relation_with_props) (n2=node_query) {return ($r.ctx, $n1.ctx, $n2.ctx)} ; // Literals array_literal : '[' literal (',' literal)* ']' | '[' ']' ; literal : IntLiteral | FloatLiteral | StringLiteral | BooleanLiteral | array_literal // recursion ; IntLiteral : ('-' | '+')? DIGIT+; FloatLiteral : ('-' | '+')? DIGIT+ '.' DIGIT* ; StringLiteral : '"' StringChars? '"' ; BooleanLiteral : (T R U E | F A L S E) ; // Keywords K_MATCH : M A T C H ; K_CREATE : C R E A T E ; K_DELETE : D E L E T E ; K_EXIT : E X I T ; K_QUIT : Q U I T ; K_SHOW : S H O W ; K_DESC : D E S C ; K_INSERT : I N S E R T ; K_TYPE : T Y P E ; K_RELATION : R E L A T I O N ; K_NODE : N O D E ; K_TYPES : T Y P E S ; K_RELATIONS : R E L A T I O N S ; K_WHERE : W H E R E ; K_RETURN : R E T U R N; K_AND : A N D ; K_OR : O R ; // Types T_INT : I N T ; T_LONG : L O N G ; T_BOOL : B O O L ; T_SHORT : S H O R T ; T_CHAR : C H A R ; T_FLOAT : F L O A T ; T_DOUBLE : D O U B L E ; T_STRING : S T R I N G ; // Identifiers I_NAME : LCASE (LCASE | DIGIT | OTHER_VALID)* ; I_TYPE : UCASE LETTER*; I_RELATION : UCASE (UCASE | OTHER_VALID)+ {self.text.isupper()}?; // Other tokens SPACES : [ \u000B\u000C\t\r\n] -> channel(HIDDEN) ; BLOCK_COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ; fragment OTHER_VALID : [_\-]; fragment DIGIT : [0-9]; fragment LETTER : [A-Za-z]; fragment UCASE : [A-Z]; fragment LCASE : [a-z]; fragment A : [aA]; fragment B : [bB]; fragment C : [cC]; fragment D : [dD]; fragment E : [eE]; fragment F : [fF]; fragment G : [gG]; fragment H : [hH]; fragment I : [iI]; fragment J : [jJ]; fragment K : [kK]; fragment L : [lL]; fragment M : [mM]; fragment N : [nN]; fragment O : [oO]; fragment P : [pP]; fragment Q : [qQ]; fragment R : [rR]; fragment S : [sS]; fragment T : [tT]; fragment U : [uU]; fragment V : [vV]; fragment W : [wW]; fragment X : [xX]; fragment Y : [yY]; fragment Z : [zZ]; fragment StringChars : StringChar+ ; fragment StringChar : ~["\\] | EscapeSeq ; fragment EscapeSeq : '\\' [btnfr"'\\] ;
Fix literals in parser
Fix literals in parser
ANTLR
apache-2.0
PHB-CS123/graphene,PHB-CS123/graphene,PHB-CS123/graphene
167dc98b3e8da40426736a4e3ca8acb37250d562
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; grantObjectPrivileges : objectPrivilege (COMMA objectPrivilege)* ; grantObjectPrivilege : (objectPrivilege | ALL PRIVILEGES?)( LEFT_PAREN columnName (COMMA columnName)* RIGHT_PAREN)? ; objectPrivilege : ID *? ; grantRolesToPrograms : roleName (COMMA roleName)* TO programUnit ( COMMA programUnit )* ; programUnit : (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID ;
grammar OracleDCLStatement; import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol; granteeIdentifiedBy : userName (COMMA userName)* IDENTIFIED BY STRING (COMMA STRING)* ; grantObjectPrivileges : objectPrivilege (COMMA objectPrivilege)* ; grantObjectPrivilege : (objectPrivilege | ALL PRIVILEGES?)( LEFT_PAREN columnName (COMMA columnName)* RIGHT_PAREN)? ; objectPrivilege : ID *? ; grantRolesToPrograms : roleName (COMMA roleName)* TO programUnit ( COMMA programUnit )* ; programUnit : (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID ;
add granteeIdentifiedBy
add granteeIdentifiedBy
ANTLR
apache-2.0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
2bbdfeb8d64d4c1766bae7b9e63536f41c36da8d
src/Track.g4
src/Track.g4
grammar Track; track: track_decl decl* ; track_decl: TRACK track_body ; track_body: channel_list_line+ ; channel_list_line: endline (SPACE channel_name)+ SPACE? ; channel_name: ID ; decl: channel_decl | block_decl | endline ; channel_decl: ID SPACE COLON SPACE CHANNEL SPACE WAVE channel_body ; channel_body: block_list_line+ ; block_list_line: endline (SPACE block_name)+ SPACE? ; block_name: ID ; block_decl: ID SPACE COLON SPACE BLOCK block_body ; block_body: note_list_line+ ; note_list_line: endline (SPACE note)+ SPACE? ; note: NOTENAME OCTAVE? LENGTH? ; endline : SPACE? NEWLINE ; ID : [a-z][a-zA-Z0-9_]+ ; COLON : ':' ; CHANNEL : 'CHANNEL'; BLOCK : 'BLOCK' ; TRACK : 'TRACK' ; WAVE : 'TRIANGLE' | 'SQUARE' | 'SAWTOOTH' | 'NOISE' ; NOTENAME: 'Ab' | 'A' | 'A#' | 'Bb' | 'B' | 'C' | 'C#' | 'Db' | 'D' | 'D#' | 'Eb' | 'E' | 'F' | 'F#' | 'Gb' | 'G' | 'G#' | '^' // rest ; OCTAVE : [0-9]+ ; LENGTH : ('+' | '-' | '.')+ ; NEWLINE : '\r\n' | '\n' ; SPACE : (' ' | '\t')+ ; COMMENT : '--' .*? NEWLINE -> skip ;
grammar Track; track: track_decl decl* ; track_decl: TRACK track_body ; track_body: channel_list_line+ ; channel_list_line: endline (SPACE channel_name)+ SPACE? ; channel_name: ID ; decl: channel_decl | block_decl | endline ; channel_decl: ID SPACE COLON SPACE CHANNEL SPACE WAVE channel_body ; channel_body: block_list_line+ ; block_list_line: endline (SPACE block_name)+ SPACE? ; block_name: ID ; block_decl: ID SPACE COLON SPACE BLOCK block_body ; block_body: note_list_line+ ; note_list_line: endline (SPACE note)+ SPACE? ; note: NOTENAME OCTAVE? LENGTH? ; endline : SPACE? NEWLINE ; ID : [a-z][a-zA-Z0-9_]* ; COLON : ':' ; CHANNEL : 'CHANNEL'; BLOCK : 'BLOCK' ; TRACK : 'TRACK' ; WAVE : 'TRIANGLE' | 'SQUARE' | 'SAWTOOTH' | 'NOISE' ; NOTENAME: 'Ab' | 'A' | 'A#' | 'Bb' | 'B' | 'C' | 'C#' | 'Db' | 'D' | 'D#' | 'Eb' | 'E' | 'F' | 'F#' | 'Gb' | 'G' | 'G#' | '^' // rest ; OCTAVE : [0-9]+ ; LENGTH : ('+' | '-' | '.')+ ; NEWLINE : '\r\n' | '\n' ; SPACE : (' ' | '\t')+ ; COMMENT : '--' .*? NEWLINE -> skip ;
Allow single-char identifiers
Allow single-char identifiers
ANTLR
mit
hdgarrood/klasma
9bc39853494acd06fc40ee27d618692e7034891d
kquery/KQuery.g4
kquery/KQuery.g4
/* [The "BSD licence"] Copyright (c) 2013 Sumit Lahiri 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. */ // Grammar for KLEE KQuery parsing. (A bit more verbose with richer parsing) // Ported to Antlr4 by Sumit Lahiri. grammar KQuery; kqueryExpression : ktranslationUnit* EOF ; ktranslationUnit : arrayDeclaration | queryCommand ; queryCommand : LeftParen Query evalExprList queryExpr RightParen ; queryExpr : expression | expression evalExprList | expression evalExprList evalArrayList ; evalExprList : LeftBracket expression* RightBracket ; evalArrayList : LeftBracket Identifier* RightBracket ; arrayDeclaration : Array arrName LeftBracket numArrayElements RightBracket Colon domain Arrow rangeLimit Equal arrayInitializer ; numArrayElements : Constant ; arrayInitializer : Symbolic | LeftBracket numberList RightBracket ; expression : varName | namedConstant Colon fullyQualifiedExpression | LeftParen widthOrSizeExpr number RightParen | LeftParen arithmeticExpr widthOrSizeExpr leftExpr rightExpr RightParen | LeftParen notExpr LeftBracket widthOrSizeExpr RightBracket expression RightParen | LeftParen bitwiseExpr widthOrSizeExpr leftExpr rightExpr RightParen | LeftParen comparisonExpr widthOrSizeExpr leftExpr rightExpr RightParen | LeftParen comparisonExpr leftExpr rightExpr RightParen | LeftParen concatExpr widthOrSizeExpr leftExpr rightExpr RightParen | LeftParen concatExpr leftExpr rightExpr RightParen | LeftParen arrExtractExpr widthOrSizeExpr number expression RightParen | LeftParen bitExtractExpr widthOrSizeExpr expression RightParen | LeftParen genericBitRead widthOrSizeExpr expression version RightParen | LeftParen selectExpr widthOrSizeExpr leftExpr rightExpr expression RightParen | LeftParen exprNegation widthOrSizeExpr expression RightParen | LeftParen exprNegation expression RightParen | LeftParen genericBitRead widthOrSizeExpr expression RightParen | version | number ; genericBitRead : READ | READLSB | READMSB ; bitExtractExpr : ZEXT | SEXT ; version : varName | namedConstant Colon fullyQualifiedExpression | LeftBracket updateList RightBracket ATR version | LeftBracket RightBracket ATR version ; fullyQualifiedExpression : expression ; notExpr : NOT ; concatExpr : CONCAT ; exprNegation : NEGETION ; selectExpr : SELECT ; arrExtractExpr : EXTRACT ; varName : Identifier ; leftExpr : expression ; rightExpr : expression ; namedConstant : Identifier ; updateList : expression Equal expression COMMA updateList | expression Equal expression ; bitwiseExpr : BITWISEAND | BITWISEOR | BITWISEXOR | SHL | LSHR | ASHR ; comparisonExpr : EQ | NEQ | ULT | UGT | ULE | UGE | SLT | SLE | SGT | SGE ; arithmeticExpr : ADD | SUB | MUL | UDIV | UREM | SDIV | SREM ; domain : widthOrSizeExpr ; rangeLimit : widthOrSizeExpr ; arrName : Identifier ; numberList : number | number numberList ; number : boolnum | signedConstant | constant ; constant: Constant; boolnum: Boolean; signedConstant: SignedConstant; Boolean : TrueMatch | FalseMatch ; SignedConstant : (PLUS | MINUS)Constant ; Constant : DIGIT+ | BinConstant | OctConstant | HexConstant ; BinConstant : BinId BIN_DIGIT+ ; OctConstant : OctId OCTAL_DIGIT+ ; HexConstant : HexId HEX_DIGIT+ ; FloatingPointType : FP DIGIT ((.).*?)? ; IntegerType : INT DIGIT+ ; widthOrSizeExpr : WidthType ; WidthType : WIDTH DIGIT+ ; BinId : '0b'; OctId : '0o'; WIDTH : 'w'; HexId : '0x'; TrueMatch : 'true'; FalseMatch : 'false'; Query : 'query'; Array : 'array'; Symbolic : 'symbolic'; Colon : ':'; Arrow : '->'; Equal : '='; COMMA : ','; NOT : 'Not'; SHL : 'Shl'; LSHR : 'LShr'; ASHR : 'AShr'; CONCAT : 'Concat'; EXTRACT: 'Extract'; ZEXT: 'ZExt'; SEXT: 'SExt'; READ: 'Read'; SELECT: 'Select'; NEGETION: 'Neg'; READLSB: 'ReadLSB'; READMSB: 'ReadMSB'; PLUS : '+'; MINUS : '-'; INT : 'i'; ATR : '@'; FP : 'fp'; BITWISEAND : 'And'; BITWISEOR : 'Or'; BITWISEXOR : 'Xor'; EQ : 'Eq'; NEQ : 'Ne' ; ULT : 'Ult' ; ULE : 'Ule' ; UGT : 'Ugt' ; UGE : 'Uge' ; SLT : 'Slt' ; SLE : 'Sle' ; SGT : 'Sgt' ; SGE : 'Sge' ; ADD : 'Add' ; SUB : 'Sub' ; MUL : 'Mul' ; UDIV : 'UDiv'; UREM : 'URem'; SDIV : 'SDiv'; SREM : 'SRem'; fragment DIGIT : ('0'..'9') ; fragment BIN_DIGIT : ('0' | '1' | '_') ; fragment OCTAL_DIGIT : ('0'..'7' | '_') ; fragment HEX_DIGIT : ('0'..'9'|'a'..'f'|'A'..'F'|'_') ; Identifier : ('a'..'z' | 'A'..'Z' | '_')('a'..'z' | 'A'..'Z' | '_' | '0'..'9' | '.' )* ; Whitespace : [ \t]+ -> skip ; Newline : ( '\r' '\n'? | '\n' ) -> skip ; BlockComment : '/*' .*? '*/' -> skip ; LineComment : '#' ~[\r\n]* -> skip ; LeftParen : '('; RightParen : ')'; LeftBracket : '['; RightBracket : ']'; LeftBrace : '{'; RightBrace : '}';
/* [The "BSD licence"] Copyright (c) 2013 Sumit Lahiri 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. */ // Grammar for KLEE KQuery parsing. (A bit more verbose with richer parsing) // Ported to Antlr4 by Sumit Lahiri. grammar KQuery; kqueryExpression : ktranslationUnit* EOF ; ktranslationUnit : arrayDeclaration | queryCommand ; queryCommand : LeftParen Query evalExprList queryExpr RightParen ; queryExpr : expression | expression evalExprList | expression evalExprList evalArrayList ; evalExprList : LeftBracket expression* RightBracket ; evalArrayList : LeftBracket Identifier* RightBracket ; arrayDeclaration : Array arrName LeftBracket numArrayElements RightBracket Colon domain Arrow rangeLimit Equal arrayInitializer ; numArrayElements : Constant ; arrayInitializer : Symbolic | LeftBracket numberList RightBracket ; expression : varName | namedConstant Colon fullyQualifiedExpression | LeftParen widthOrSizeExpr number RightParen | LeftParen arithmeticExpr widthOrSizeExpr leftExpr rightExpr RightParen | LeftParen notExpr LeftBracket widthOrSizeExpr RightBracket expression RightParen | LeftParen bitwiseExpr widthOrSizeExpr leftExpr rightExpr RightParen | LeftParen comparisonExpr widthOrSizeExpr leftExpr rightExpr RightParen | LeftParen comparisonExpr leftExpr rightExpr RightParen | LeftParen concatExpr widthOrSizeExpr leftExpr rightExpr RightParen | LeftParen concatExpr leftExpr rightExpr RightParen | LeftParen arrExtractExpr widthOrSizeExpr number expression RightParen | LeftParen bitExtractExpr widthOrSizeExpr expression RightParen | LeftParen genericBitRead widthOrSizeExpr expression version RightParen | LeftParen selectExpr widthOrSizeExpr leftExpr rightExpr expression RightParen | LeftParen exprNegation widthOrSizeExpr expression RightParen | LeftParen exprNegation expression RightParen | LeftParen genericBitRead widthOrSizeExpr expression RightParen | version | number ; genericBitRead : READ | READLSB | READMSB ; bitExtractExpr : ZEXT | SEXT ; version : varName | namedConstant Colon fullyQualifiedExpression | LeftBracket updateList RightBracket ATR version | LeftBracket RightBracket ATR version ; fullyQualifiedExpression : expression ; notExpr : NOT ; concatExpr : CONCAT ; exprNegation : NEGETION ; selectExpr : SELECT ; arrExtractExpr : EXTRACT ; varName : Identifier ; leftExpr : expression ; rightExpr : expression ; namedConstant : Identifier ; updateList : expression Equal expression COMMA updateList | expression Equal expression ; bitwiseExpr : BITWISEAND | BITWISEOR | BITWISEXOR | SHL | LSHR | ASHR ; comparisonExpr : EQ | NEQ | ULT | UGT | ULE | UGE | SLT | SLE | SGT | SGE ; arithmeticExpr : ADD | SUB | MUL | UDIV | UREM | SDIV | SREM ; domain : widthOrSizeExpr ; rangeLimit : widthOrSizeExpr ; arrName : Identifier ; numberList : number | number numberList ; number : boolnum | signedConstant | constant ; constant: Constant; boolnum: Boolean; signedConstant: SignedConstant; Boolean : TrueMatch | FalseMatch ; SignedConstant : (PLUS | MINUS)Constant ; Constant : DIGIT+ | BinConstant | OctConstant | HexConstant ; BinConstant : BinId BIN_DIGIT+ ; OctConstant : OctId OCTAL_DIGIT+ ; HexConstant : HexId HEX_DIGIT+ ; FloatingPointType : FP DIGIT ((.).*?)? ; IntegerType : INT DIGIT+ ; widthOrSizeExpr : WidthType ; WidthType : WIDTH DIGIT+ ; BinId : '0b'; OctId : '0o'; WIDTH : 'w'; HexId : '0x'; TrueMatch : 'true'; FalseMatch : 'false'; Query : 'query'; Array : 'array'; Symbolic : 'symbolic'; Colon : ':'; Arrow : '->'; Equal : '='; COMMA : ','; NOT : 'Not'; SHL : 'Shl'; LSHR : 'LShr'; ASHR : 'AShr'; CONCAT : 'Concat'; EXTRACT: 'Extract'; ZEXT: 'ZExt'; SEXT: 'SExt'; READ: 'Read'; SELECT: 'Select'; NEGETION: 'Neg'; READLSB: 'ReadLSB'; READMSB: 'ReadMSB'; PLUS : '+'; MINUS : '-'; ATR : '@'; FP : 'fp'; BITWISEAND : 'And'; BITWISEOR : 'Or'; BITWISEXOR : 'Xor'; EQ : 'Eq'; NEQ : 'Ne' ; ULT : 'Ult' ; ULE : 'Ule' ; UGT : 'Ugt' ; UGE : 'Uge' ; SLT : 'Slt' ; SLE : 'Sle' ; SGT : 'Sgt' ; SGE : 'Sge' ; ADD : 'Add' ; SUB : 'Sub' ; MUL : 'Mul' ; UDIV : 'UDiv'; UREM : 'URem'; SDIV : 'SDiv'; SREM : 'SRem'; fragment DIGIT : ('0'..'9') ; fragment BIN_DIGIT : ('0' | '1' | '_') ; fragment OCTAL_DIGIT : ('0'..'7' | '_') ; fragment HEX_DIGIT : ('0'..'9'|'a'..'f'|'A'..'F'|'_') ; Identifier : ('a'..'z' | 'A'..'Z' | '_')('a'..'z' | 'A'..'Z' | '_' | '0'..'9' | '.' )* ; INT : 'i'; Whitespace : [ \t]+ -> skip ; Newline : ( '\r' '\n'? | '\n' ) -> skip ; BlockComment : '/*' .*? '*/' -> skip ; LineComment : '#' ~[\r\n]* -> skip ; LeftParen : '('; RightParen : ')'; LeftBracket : '['; RightBracket : ']'; LeftBrace : '{'; RightBrace : '}';
Update KQuery.g4
Update KQuery.g4
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
cd590b5ec01069bb2f4987cad8b87a9a38db5a6e
smiles/smiles.g4
smiles/smiles.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 smiles; smiles: chain terminator?; atom: bracket_atom | aliphatic_organic | aromatic_organic | '*'; aliphatic_organic: UB | UC | UN | UO | US | UP | UF | (UC LL) | (UB LR) | UI; aromatic_organic: LB | LC | LN | LO | LS | LP; bracket_atom: '[' isotope? symbol chiral? hcount? charge? class_? ']'; isotope: DIGIT+; symbol: element_symbols | aromatic_symbol | '*'; element_symbols: (UH) | (UH LE) | (UL LI) | (UB LE) | (UB) | (UC) | (UN) | (UO) | (UF) | (UN LE) | (UN LA) | (UM LG) | (UA LL) | (US LI) | (UP) | (US) | (UC LL) | (UA LR) | (UK) | (UC LA) | (US LC) | (UT LI) | (UV) | (UC LR) | (UM LN) | (UF LE) | (UC LO) | (UN LI) | (UC LU) | (UZ LN) | (UG LA) | (UG LE) | (UA LS) | (US LE) | (UB LR) | (UK LR) | (UR LB) | (US LR) | (UY) | (UZ LR) | (UN LB) | (UM LO) | (UT LC) | (UR LU) | (UR LH) | (UP LD) | (UA LG) | (UC LD) | (UI LN) | (US LN) | (US LB) | (UT LE) | (UI) | (UX LE) | (UC LS) | (UB LA) | (UH LF) | (UT LA) | (UW) | (UR LE) | (UO LS) | (UI LR) | (UP LT) | (UA LU) | (UH LG) | (UT LL) | (UP LB) | (UB LI) | (UP LO) | (UA LT) | (UR LN) | (UF LR) | (UR LA) | (UR LF) | (UD LB) | (US LG) | (UB LH) | (UH LS) | (UM LT) | (UD LS) | (UR LG) | (UC LN) | (UF LL) | (UL LV) | (UL LA) | (UC LE) | (UP LR) | (UN LD) | (UP LM) | (US LM) | (UE LU) | (UG LD) | (UT LB) | (UD LY) | (UH LO) | (UE LR) | (UT LM) | (UY LB) | (UL LU) | (UA LC) | (UT LH) | (UP LA) | (UU) | (UN LP) | (UP LU) | (UA LM) | (UC LM) | (UB LK) | (UC LF) | (UE LS) | (UF LM) | (UM LD) | (UN LO) | (UL LR); aromatic_symbol: LC | LN | LO | LP | LS | (LS LE) | (LA LS); chiral: '@' | '@@' | '@TH1' | '@TH2' | '@AL1' | '@AL2' | '@SP1' | '@SP2' | '@SP3' | '@TB1' | '@TB2' | '@TB3' | '@TB3' | '@TB4' | '@TB5' | '@TB6' | '@TB7' | '@TB8' | '@TB9' | '@TB10' | '@TB11' | '@TB12' | '@TB13' | '@TB14' | '@TB15' | '@TB16' | '@TB17' | '@TB18' | '@TB19' | '@TB20' | '@TB21' | '@TB22' | '@TB23' | '@TB24' | '@TB25' | '@TB26' | '@TB27' | '@TB28' | '@TB29' | '@TB30' | '@OH1' | '@OH2' | '@OH3' | '@OH4' | '@OH5' | '@OH6' | '@OH7' | '@OH8' | '@OH9' | '@OH10' | '@OH11' | '@OH12' | '@OH13' | '@OH14' | '@OH15' | '@OH16' | '@OH17' | '@OH18' | '@OH19' | '@OH20' | '@OH21' | '@OH22' | '@OH23' | '@OH24' | '@OH25' | '@OH26' | '@OH27' | '@OH28' | '@OH29' | '@OH30' | ('@TB' | '@OH') DIGIT DIGIT; hcount: UH DIGIT?; charge: ('+' | '-') DIGIT? DIGIT? | '--' | '++'; class_: ':' DIGIT+; bond: '-' | '=' | '#' | '$' | ':' | '/' | '\\'; ringbond: bond? DIGIT | bond? '%' DIGIT DIGIT; branched_atom: atom ringbond* branch*; branch: '(' (bond | DOT)? chain ')'; chain: branched_atom ( (bond | DOT)? branched_atom)*; terminator: SPACE TAB | LINEFEED | CARRIAGE_RETURN; LA: ('a'); LB: ('b'); LC: ('c'); LD: ('d'); LE: ('e'); LF: ('f'); LG: ('g'); LH: ('h'); LI: ('i'); LJ: ('j'); LK: ('k'); LL: ('l'); LM: ('m'); LN: ('n'); LO: ('o'); LP: ('p'); LQ: ('q'); LR: ('r'); LS: ('s'); LT: ('t'); LU: ('u'); LV: ('v'); LW: ('w'); LX: ('x'); LY: ('y'); LZ: ('z'); UA: ('A'); UB: ('B'); UC: ('C'); UD: ('D'); UE: ('E'); UF: ('F'); UG: ('G'); UH: ('H'); UI: ('I'); UJ: ('J'); UK: ('K'); UL: ('L'); UM: ('M'); UN: ('N'); UO: ('O'); UP: ('P'); UQ: ('Q'); UR: ('R'); US: ('S'); UT: ('T'); UU: ('U'); UV: ('V'); UW: ('W'); UX: ('X'); UY: ('Y'); UZ: ('Z'); DOT: '.'; LINEFEED: '\r'; CARRIAGE_RETURN: '\n'; SPACE: ' '; DIGIT: '0' .. '9'; TAB: '\t';
/* 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 smiles; smiles: chain terminator?; atom: bracket_atom | aliphatic_organic | aromatic_organic | '*'; aliphatic_organic: UB | UC | UN | UO | US | UP | UF | (UC LL) | (UB LR) | UI; aromatic_organic: LB | LC | LN | LO | LS | LP; bracket_atom: '[' isotope? symbol chiral? hcount? charge? class_? ']'; isotope: DIGIT+; symbol: element_symbols | aromatic_symbol | '*'; element_symbols: (UH) | UH LE | UL LI | UB LE ... | (UB) | (UC) | (UN) | (UO) | (UF) | (UN LE) | (UN LA) | (UM LG) | (UA LL) | (US LI) | (UP) | (US) | (UC LL) | (UA LR) | (UK) | (UC LA) | (US LC) | (UT LI) | (UV) | (UC LR) | (UM LN) | (UF LE) | (UC LO) | (UN LI) | (UC LU) | (UZ LN) | (UG LA) | (UG LE) | (UA LS) | (US LE) | (UB LR) | (UK LR) | (UR LB) | (US LR) | (UY) | (UZ LR) | (UN LB) | (UM LO) | (UT LC) | (UR LU) | (UR LH) | (UP LD) | (UA LG) | (UC LD) | (UI LN) | (US LN) | (US LB) | (UT LE) | (UI) | (UX LE) | (UC LS) | (UB LA) | (UH LF) | (UT LA) | (UW) | (UR LE) | (UO LS) | (UI LR) | (UP LT) | (UA LU) | (UH LG) | (UT LL) | (UP LB) | (UB LI) | (UP LO) | (UA LT) | (UR LN) | (UF LR) | (UR LA) | (UR LF) | (UD LB) | (US LG) | (UB LH) | (UH LS) | (UM LT) | (UD LS) | (UR LG) | (UC LN) | (UF LL) | (UL LV) | (UL LA) | (UC LE) | (UP LR) | (UN LD) | (UP LM) | (US LM) | (UE LU) | (UG LD) | (UT LB) | (UD LY) | (UH LO) | (UE LR) | (UT LM) | (UY LB) | (UL LU) | (UA LC) | (UT LH) | (UP LA) | (UU) | (UN LP) | (UP LU) | (UA LM) | (UC LM) | (UB LK) | (UC LF) | (UE LS) | (UF LM) | (UM LD) | (UN LO) | (UL LR); aromatic_symbol: LC | LN | LO | LP | LS | (LS LE) | (LA LS); chiral: '@' | '@@' | '@TH1' | '@TH2' | '@AL1' | '@AL2' | '@SP1' | '@SP2' | '@SP3' | '@TB1' | '@TB2' | '@TB3' | '@TB3' | '@TB4' | '@TB5' | '@TB6' | '@TB7' | '@TB8' | '@TB9' | '@TB10' | '@TB11' | '@TB12' | '@TB13' | '@TB14' | '@TB15' | '@TB16' | '@TB17' | '@TB18' | '@TB19' | '@TB20' | '@TB21' | '@TB22' | '@TB23' | '@TB24' | '@TB25' | '@TB26' | '@TB27' | '@TB28' | '@TB29' | '@TB30' | '@OH1' | '@OH2' | '@OH3' | '@OH4' | '@OH5' | '@OH6' | '@OH7' | '@OH8' | '@OH9' | '@OH10' | '@OH11' | '@OH12' | '@OH13' | '@OH14' | '@OH15' | '@OH16' | '@OH17' | '@OH18' | '@OH19' | '@OH20' | '@OH21' | '@OH22' | '@OH23' | '@OH24' | '@OH25' | '@OH26' | '@OH27' | '@OH28' | '@OH29' | '@OH30' | ('@TB' | '@OH') DIGIT DIGIT; hcount: UH DIGIT?; charge: ('+' | '-') DIGIT? DIGIT? | '--' | '++'; class_: ':' DIGIT+; bond: '-' | '=' | '#' | '$' | ':' | '/' | '\\'; ringbond: bond? DIGIT | bond? '%' DIGIT DIGIT; branched_atom: atom ringbond* branch*; branch: '(' (bond | DOT)? chain ')'; chain: branched_atom ( (bond | DOT)? branched_atom)*; terminator: SPACE TAB | LINEFEED | CARRIAGE_RETURN; LA: ('a'); LB: ('b'); LC: ('c'); LD: ('d'); LE: ('e'); LF: ('f'); LG: ('g'); LH: ('h'); LI: ('i'); LJ: ('j'); LK: ('k'); LL: ('l'); LM: ('m'); LN: ('n'); LO: ('o'); LP: ('p'); LQ: ('q'); LR: ('r'); LS: ('s'); LT: ('t'); LU: ('u'); LV: ('v'); LW: ('w'); LX: ('x'); LY: ('y'); LZ: ('z'); UA: ('A'); UB: ('B'); UC: ('C'); UD: ('D'); UE: ('E'); UF: ('F'); UG: ('G'); UH: ('H'); UI: ('I'); UJ: ('J'); UK: ('K'); UL: ('L'); UM: ('M'); UN: ('N'); UO: ('O'); UP: ('P'); UQ: ('Q'); UR: ('R'); US: ('S'); UT: ('T'); UU: ('U'); UV: ('V'); UW: ('W'); UX: ('X'); UY: ('Y'); UZ: ('Z'); DOT: '.'; LINEFEED: '\r'; CARRIAGE_RETURN: '\n'; SPACE: ' '; DIGIT: '0' .. '9'; TAB: '\t';
Update smiles/smiles.g4
Update smiles/smiles.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
bc29ab044d0de7fab495fc25b45de696fc1cc178
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; 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? ; alterUser : ALTER USER ( userName ( IDENTIFIED (BY STRING (REPLACE 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 (FOR ids)? FORCE? | CONTAINER EQ_ (CURRENT | ALL) | DEFAULT ROLE (roleNames| ALL (EXCEPT roleNames)?| NONE) | ID )* | userNames proxyClause ) ; containerDataClause : ( SET CONTAINER_DATA EQ_ ( ALL | DEFAULT | idList ) | (ADD |REMOVE) CONTAINER_DATA EQ_ idList ) (FOR schemaName? ID)? ; proxyClause : (GRANT | REVOKE) CONNECT THROUGH ( ENTERPRISE USERS | userName dbUserProxyClauses?) ; dbUserProxyClauses : (WITH (ROLE (ALL EXCEPT)? roleNames | NO ROLES))? (AUTHENTICATION REQUIRED )? ; dropUser : DROP USER userName CASCADE? ; createRole : CREATE ROLE roleName ( NOT IDENTIFIED | IDENTIFIED (BY STRING| USING schemaName? ID| EXTERNALLY | GLOBALLY) )? (CONTAINER EQ_ (CURRENT | ALL))? ; alterRole : ALTER ROLE roleName (NOT IDENTIFIED | IDENTIFIED (BY STRING | USING schemaName? ID | EXTERNALLY | GLOBALLY)) (CONTAINER EQ_ (CURRENT | ALL))? ; dropRole : DROP ROLE roleName ;
grammar OracleDCLStatement; import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol; 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 ID | (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? ; alterUser : ALTER USER ( userName ( IDENTIFIED (BY ID (REPLACE 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 (FOR ids)? FORCE? | CONTAINER EQ_ (CURRENT | ALL) | DEFAULT ROLE (roleNames| ALL (EXCEPT roleNames)?| NONE) | ID )* | userNames proxyClause ) ; containerDataClause : ( SET CONTAINER_DATA EQ_ ( ALL | DEFAULT | idList ) | (ADD |REMOVE) CONTAINER_DATA EQ_ idList ) (FOR schemaName? ID)? ; proxyClause : (GRANT | REVOKE) CONNECT THROUGH ( ENTERPRISE USERS | userName dbUserProxyClauses?) ; dbUserProxyClauses : (WITH (ROLE (ALL EXCEPT)? roleNames | NO ROLES))? (AUTHENTICATION REQUIRED )? ; dropUser : DROP USER userName CASCADE? ; createRole : CREATE ROLE roleName ( NOT IDENTIFIED | IDENTIFIED (BY ID | USING schemaName? ID | EXTERNALLY | GLOBALLY) )? (CONTAINER EQ_ (CURRENT | ALL))? ; alterRole : ALTER ROLE roleName (NOT IDENTIFIED | IDENTIFIED (BY ID | USING schemaName? ID | EXTERNALLY | GLOBALLY)) (CONTAINER EQ_ (CURRENT | ALL))? ; dropRole : DROP ROLE roleName ;
change oracle password rule from STRING to ID
change oracle password rule from STRING to ID
ANTLR
apache-2.0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
1ca9ed61d62b529aa403229b0a23dac69a091fe3
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, 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 ;
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_BYTE, LIT_INTEGER, LIT_FLOAT, LIT_STR, LIT_STR_RAW, LIT_BINARY, LIT_BINARY_RAW, QUESTION, IDENT, LIFETIME, WHITESPACE, DOC_COMMENT, COMMENT, SHEBANG, UTF8_BOM } 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 ;
Declare other tokens used later in the reference grammar
Declare other tokens used later in the reference grammar There were some tokens used in the grammar but not declared. Antlr doesn't really seem to care and happily uses them, but they appear in RustLexer.tokens in a potentially-unexpected order.
ANTLR
apache-2.0
jroesch/rust,jroesch/rust,aidancully/rust,seanrivera/rust,krzysz00/rust,aidancully/rust,graydon/rust,sae-bom/rust,l0kod/rust,XMPPwocky/rust,nwin/rust,carols10cents/rust,KokaKiwi/rust,zubron/rust,carols10cents/rust,mvdnes/rust,mihneadb/rust,philyoon/rust,pelmers/rust,jashank/rust,jashank/rust,TheNeikos/rust,pshc/rust,jroesch/rust,victorvde/rust,krzysz00/rust,ejjeong/rust,aneeshusa/rust,zubron/rust,zachwick/rust,gifnksm/rust,mihneadb/rust,mdinger/rust,nwin/rust,pshc/rust,pelmers/rust,mvdnes/rust,reem/rust,sae-bom/rust,sae-bom/rust,andars/rust,jroesch/rust,philyoon/rust,KokaKiwi/rust,dwillmer/rust,KokaKiwi/rust,zubron/rust,cllns/rust,omasanori/rust,zachwick/rust,reem/rust,jashank/rust,sae-bom/rust,robertg/rust,KokaKiwi/rust,pshc/rust,aneeshusa/rust,pelmers/rust,krzysz00/rust,mihneadb/rust,mdinger/rust,aepsil0n/rust,TheNeikos/rust,aepsil0n/rust,KokaKiwi/rust,andars/rust,kwantam/rust,jroesch/rust,zubron/rust,nwin/rust,ejjeong/rust,ejjeong/rust,seanrivera/rust,zachwick/rust,jroesch/rust,victorvde/rust,zachwick/rust,kwantam/rust,jashank/rust,kwantam/rust,cllns/rust,vhbit/rust,aepsil0n/rust,omasanori/rust,zachwick/rust,zubron/rust,zachwick/rust,mdinger/rust,mdinger/rust,philyoon/rust,zubron/rust,TheNeikos/rust,seanrivera/rust,TheNeikos/rust,robertg/rust,mvdnes/rust,krzysz00/rust,dwillmer/rust,philyoon/rust,vhbit/rust,jroesch/rust,vhbit/rust,GBGamer/rust,aneeshusa/rust,l0kod/rust,reem/rust,philyoon/rust,pelmers/rust,rohitjoshi/rust,carols10cents/rust,aepsil0n/rust,l0kod/rust,jashank/rust,kwantam/rust,dwillmer/rust,cllns/rust,XMPPwocky/rust,krzysz00/rust,omasanori/rust,TheNeikos/rust,gifnksm/rust,aepsil0n/rust,graydon/rust,nwin/rust,cllns/rust,nwin/rust,mihneadb/rust,XMPPwocky/rust,mihneadb/rust,sae-bom/rust,GBGamer/rust,jashank/rust,omasanori/rust,XMPPwocky/rust,l0kod/rust,GBGamer/rust,graydon/rust,graydon/rust,cllns/rust,aneeshusa/rust,andars/rust,victorvde/rust,andars/rust,nwin/rust,pelmers/rust,jashank/rust,GBGamer/rust,sae-bom/rust,l0kod/rust,l0kod/rust,mdinger/rust,XMPPwocky/rust,aneeshusa/rust,zubron/rust,GBGamer/rust,robertg/rust,victorvde/rust,rohitjoshi/rust,mvdnes/rust,aidancully/rust,reem/rust,pshc/rust,GBGamer/rust,cllns/rust,vhbit/rust,rohitjoshi/rust,gifnksm/rust,victorvde/rust,dwillmer/rust,l0kod/rust,dwillmer/rust,andars/rust,andars/rust,robertg/rust,pshc/rust,vhbit/rust,l0kod/rust,carols10cents/rust,ejjeong/rust,reem/rust,graydon/rust,ejjeong/rust,pelmers/rust,victorvde/rust,vhbit/rust,aidancully/rust,pshc/rust,kwantam/rust,GBGamer/rust,carols10cents/rust,robertg/rust,omasanori/rust,mihneadb/rust,ejjeong/rust,dwillmer/rust,nwin/rust,rohitjoshi/rust,TheNeikos/rust,XMPPwocky/rust,seanrivera/rust,gifnksm/rust,vhbit/rust,GBGamer/rust,aepsil0n/rust,krzysz00/rust,zubron/rust,aidancully/rust,seanrivera/rust,vhbit/rust,nwin/rust,graydon/rust,gifnksm/rust,reem/rust,carols10cents/rust,mdinger/rust,jroesch/rust,jashank/rust,gifnksm/rust,dwillmer/rust,aidancully/rust,rohitjoshi/rust,omasanori/rust,mvdnes/rust,dwillmer/rust,KokaKiwi/rust,pshc/rust,kwantam/rust,robertg/rust,aneeshusa/rust,rohitjoshi/rust,philyoon/rust,seanrivera/rust,pshc/rust,mvdnes/rust
6f878cd8033fadc5f072ef65726f0130a080df53
sharding-core/src/main/antlr4/imports/MySQLKeyword.g4
sharding-core/src/main/antlr4/imports/MySQLKeyword.g4
lexer grammar MySQLKeyword; import Symbol; ACTION : A C T I O N ; ADMIN : A D M I N ; AFTER : A F T E R ; ALGORITHM : A L G O R I T H M ; ANALYZE : A N A L Y Z E ; AT_ : A T UL_ ; AUDIT_ADMIN : A U D I T UL_ A D M I N ; AUTO_INCREMENT : A U T O UL_ I N C R E M E N T ; AVG_ROW_LENGTH : A V G UL_ R O W UL_ L E N G T H ; BEGIN : B E G I N ; BINLOG_ADMIN : B I N L O G UL_ A D M I N ; BTREE : B T R E E ; CASE : C A S E ; CHAIN : C H A I N ; CHANGE : C H A N G E ; CHAR : C H A R ; CHARACTER : C H A R A C T E R ; CHARSET : C H A R S E T ; CHECKSUM : C H E C K S U M ; CLIENT : C L I E N T ; COALESCE : C O A L E S C E ; COLLATE : C O L L A T E ; COLUMNS : C O L U M N S ; COLUMN_FORMAT : C O L U M N UL_ F O R M A T ; COMMENT : C O M M E N T ; COMPACT : C O M P A C T ; COMPRESSED : C O M P R E S S E D ; COMPRESSION : C O M P R E S S I O N ; CONNECTION : C O N N E C T I O N ; CONNECTION_ADMIN : C O N N E C T I O N UL_ A D M I N ; CONSISTENT : C O N S I S T E N T ; CONVERT : C O N V E R T ; COPY : C O P Y ; CROSS : C R O S S ; CURRENT_TIMESTAMP : C U R R E N T UL_ T I M E S T A M P ; DATA : D A T A ; DATABASES : D A T A B A S E S ; DELAYED : D E L A Y E D ; DELAY_KEY_WRITE : D E L A Y UL_ K E Y UL_ W R I T E ; DIRECTORY : D I R E C T O R Y ; DISCARD : D I S C A R D ; DISK : D I S K ; DISTINCT : D I S T I N C T ; DISTINCTROW : D I S T I N C T R O W ; DOUBLE : D O U B L E ; DUPLICATE : D U P L I C A T E ; DYNAMIC : D Y N A M I C ; ELSE : E L S E ; ENCRYPTION : E N C R Y P T I O N ; ENCRYPTION_KEY_ADMIN : E N C R Y P T I O N UL_ K E Y UL_ A D M I N ; END : E N D ; ENGINE : E N G I N E ; EVENT : E V E N T ; EXCHANGE : E X C H A N G E ; EXCLUSIVE : E X C L U S I V E ; EXECUTE : E X E C U T E ; FILE : F I L E ; FIREWALL_ADMIN : F I R E W A L L UL_ A D M I N ; FIREWALL_USER : F I R E W A L L UL_ U S E R ; FIRST : F I R S T ; FIXED : F I X E D ; FOR : F O R ; FORCE : F O R C E ; FULL : F U L L ; FULLTEXT : F U L L T E X T ; FUNCTION : F U N C T I O N ; GLOBAL : G L O B A L ; GRANT : G R A N T ; GROUP_REPLICATION_ADMIN : G R O U P UL_ R E P L I C A T I O N UL_ A D M I N ; HASH : H A S H ; HIGH_PRIORITY : H I G H UL_ P R I O R I T Y ; IGNORE : I G N O R E ; IMPORT_ : I M P O R T UL_ ; INNER : I N N E R ; INPLACE : I N P L A C E ; INSERT : I N S E R T ; INSERT_METHOD : I N S E R T UL_ M E T H O D ; INTO : I N T O ; JOIN : J O I N ; KEYS : K E Y S ; KEY_BLOCK_SIZE : K E Y UL_ B L O C K UL_ S I Z E ; LAST : L A S T ; LEFT : L E F T ; LESS : L E S S ; LINEAR : L I N E A R ; LIST : L I S T ; LOCALTIME : L O C A L T I M E ; LOCALTIMESTAMP : L O C A L T I M E S T A M P ; LOCK : L O C K ; LOW_PRIORITY : L O W UL_ P R I O R I T Y ; MATCH : M A T C H ; MAXVALUE : M A X V A L U E ; MAX_ROWS : M A X UL_ R O W S ; MEMORY : M E M O R Y ; MIN_ROWS : M I N UL_ R O W S ; MODIFY : M O D I F Y ; NATURAL : N A T U R A L ; NONE : N O N E ; NOW : N O W ; OFFLINE : O F F L I N E ; ONLINE : O N L I N E ; ONLY : O N L Y ; OPTIMIZE : O P T I M I Z E ; OPTION : O P T I O N ; OUTER : O U T E R ; PACK_KEYS : P A C K UL_ K E Y S ; PARSER : P A R S E R ; PARTIAL : P A R T I A L ; PARTITIONING : P A R T I T I O N I N G ; PARTITIONS : P A R T I T I O N S ; PASSWORD : P A S S W O R D ; PERSIST : P E R S I S T ; PERSIST_ONLY : P E R S I S T UL_ O N L Y ; PRECISION : P R E C I S I O N ; PRIVILEGES : P R I V I L E G E S ; PROCEDURE : P R O C E D U R E ; PROCESS : P R O C E S S ; PROXY : P R O X Y ; QUICK : Q U I C K ; RANGE : R A N G E ; REBUILD : R E B U I L D ; REDUNDANT : R E D U N D A N T ; RELEASE : R E L E A S E ; RELOAD : R E L O A D ; REMOVE : R E M O V E ; RENAME : R E N A M E ; REORGANIZE : R E O R G A N I Z E ; REPAIR : R E P A I R ; REPEATABLE : R E P E A T A B L E ; REPLACE : R E P L A C E ; REPLICATION : R E P L I C A T I O N ; REPLICATION_SLAVE_ADMIN : R E P L I C A T I O N UL_ S L A V E UL_ A D M I N ; RESTRICT : R E S T R I C T ; REVOKE : R E V O K E ; RIGHT : R I G H T ; ROLE_ADMIN : R O L E UL_ A D M I N ; ROUTINE : R O U T I N E ; ROW_FORMAT : R O W UL_ F O R M A T ; SAVEPOINT : S A V E P O I N T ; SESSION : S E S S I O N ; SET_USER_ID : S E T UL_ U S E R UL_ I D ; SHARED : S H A R E D ; SHOW : S H O W ; SHUTDOWN : S H U T D O W N ; SIMPLE : S I M P L E ; SLAVE : S L A V E ; SNAPSHOT : S N A P S H O T ; SPATIAL : S P A T I A L ; SQLDML : S Q L D M L ; SQLDQL : S Q L D Q L ; SQL_BIG_RESULT : S Q L UL_ B I G UL_ R E S U L T ; SQL_BUFFER_RESULT : S Q L UL_ B U F F E R UL_ R E S U L T ; SQL_CACHE : S Q L UL_ C A C H E ; SQL_CALC_FOUND_ROWS : S Q L UL_ C A L C UL_ F O U N D UL_ R O W S ; SQL_NO_CACHE : S Q L UL_ N O UL_ C A C H E ; SQL_SMALL_RESULT : S Q L UL_ S M A L L UL_ R E S U L T ; STATS_AUTO_RECALC : S T A T S UL_ A U T O UL_ R E C A L C ; STATS_PERSISTENT : S T A T S UL_ P E R S I S T E N T ; STATS_SAMPLE_PAGES : S T A T S UL_ S A M P L E UL_ P A G E S ; STORAGE : S T O R A G E ; STORED : S T O R E D ; STRAIGHT_JOIN : S T R A I G H T UL_ J O I N ; SUBPARTITION : S U B P A R T I T I O N ; SUBPARTITIONS : S U B P A R T I T I O N S ; SUPER : S U P E R ; SYSTEM_VARIABLES_ADMIN : S Y S T E M UL_ V A R I A B L E S UL_ A D M I N ; TABLES : T A B L E S ; TABLESPACE : T A B L E S P A C E ; TEMPORARY : T E M P O R A R Y ; THAN : T H A N ; THEN : T H E N ; TRIGGER : T R I G G E R ; UNCOMMITTED : U N C O M M I T T E D ; UNSIGNED : U N S I G N E D ; UPDATE : U P D A T E ; UPGRADE : U P G R A D E ; USAGE : U S A G E ; USE : U S E ; USER : U S E R ; USING : U S I N G ; VALIDATION : V A L I D A T I O N ; VALUE : V A L U E ; VALUES : V A L U E S ; VERSION_TOKEN_ADMIN : V E R S I O N UL_ T O K E N UL_ A D M I N ; VIEW : V I E W ; VIRTUAL : V I R T U A L ; WHEN : W H E N ; WITHOUT : W I T H O U T ; WRITE : W R I T E ; ZEROFILL : Z E R O F I L L ;
lexer grammar MySQLKeyword; import Symbol; ACTION : A C T I O N ; ADMIN : A D M I N ; AFTER : A F T E R ; ALGORITHM : A L G O R I T H M ; ANALYZE : A N A L Y Z E ; AUDIT_ADMIN : A U D I T UL_ A D M I N ; AUTO_INCREMENT : A U T O UL_ I N C R E M E N T ; AVG_ROW_LENGTH : A V G UL_ R O W UL_ L E N G T H ; BEGIN : B E G I N ; BINLOG_ADMIN : B I N L O G UL_ A D M I N ; BTREE : B T R E E ; CASE : C A S E ; CHAIN : C H A I N ; CHANGE : C H A N G E ; CHAR : C H A R ; CHARACTER : C H A R A C T E R ; CHARSET : C H A R S E T ; CHECKSUM : C H E C K S U M ; CLIENT : C L I E N T ; COALESCE : C O A L E S C E ; COLLATE : C O L L A T E ; COLUMNS : C O L U M N S ; COLUMN_FORMAT : C O L U M N UL_ F O R M A T ; COMMENT : C O M M E N T ; COMPACT : C O M P A C T ; COMPRESSED : C O M P R E S S E D ; COMPRESSION : C O M P R E S S I O N ; CONNECTION : C O N N E C T I O N ; CONNECTION_ADMIN : C O N N E C T I O N UL_ A D M I N ; CONSISTENT : C O N S I S T E N T ; CONVERT : C O N V E R T ; COPY : C O P Y ; CROSS : C R O S S ; CURRENT_TIMESTAMP : C U R R E N T UL_ T I M E S T A M P ; DATA : D A T A ; DATABASES : D A T A B A S E S ; DELAYED : D E L A Y E D ; DELAY_KEY_WRITE : D E L A Y UL_ K E Y UL_ W R I T E ; DIRECTORY : D I R E C T O R Y ; DISCARD : D I S C A R D ; DISK : D I S K ; DISTINCT : D I S T I N C T ; DISTINCTROW : D I S T I N C T R O W ; DOUBLE : D O U B L E ; DUPLICATE : D U P L I C A T E ; DYNAMIC : D Y N A M I C ; ELSE : E L S E ; ENCRYPTION : E N C R Y P T I O N ; ENCRYPTION_KEY_ADMIN : E N C R Y P T I O N UL_ K E Y UL_ A D M I N ; END : E N D ; ENGINE : E N G I N E ; EVENT : E V E N T ; EXCHANGE : E X C H A N G E ; EXCLUSIVE : E X C L U S I V E ; EXECUTE : E X E C U T E ; FILE : F I L E ; FIREWALL_ADMIN : F I R E W A L L UL_ A D M I N ; FIREWALL_USER : F I R E W A L L UL_ U S E R ; FIRST : F I R S T ; FIXED : F I X E D ; FOR : F O R ; FORCE : F O R C E ; FULL : F U L L ; FULLTEXT : F U L L T E X T ; FUNCTION : F U N C T I O N ; GLOBAL : G L O B A L ; GRANT : G R A N T ; GROUP_REPLICATION_ADMIN : G R O U P UL_ R E P L I C A T I O N UL_ A D M I N ; HASH : H A S H ; HIGH_PRIORITY : H I G H UL_ P R I O R I T Y ; IGNORE : I G N O R E ; IMPORT_ : I M P O R T UL_ ; INNER : I N N E R ; INPLACE : I N P L A C E ; INSERT : I N S E R T ; INSERT_METHOD : I N S E R T UL_ M E T H O D ; INTO : I N T O ; JOIN : J O I N ; KEYS : K E Y S ; KEY_BLOCK_SIZE : K E Y UL_ B L O C K UL_ S I Z E ; LAST : L A S T ; LEFT : L E F T ; LESS : L E S S ; LINEAR : L I N E A R ; LIST : L I S T ; LOCALTIME : L O C A L T I M E ; LOCALTIMESTAMP : L O C A L T I M E S T A M P ; LOCK : L O C K ; LOW_PRIORITY : L O W UL_ P R I O R I T Y ; MATCH : M A T C H ; MAXVALUE : M A X V A L U E ; MAX_ROWS : M A X UL_ R O W S ; MEMORY : M E M O R Y ; MIN_ROWS : M I N UL_ R O W S ; MODIFY : M O D I F Y ; NATURAL : N A T U R A L ; NONE : N O N E ; NOW : N O W ; OFFLINE : O F F L I N E ; ONLINE : O N L I N E ; ONLY : O N L Y ; OPTIMIZE : O P T I M I Z E ; OPTION : O P T I O N ; OUTER : O U T E R ; PACK_KEYS : P A C K UL_ K E Y S ; PARSER : P A R S E R ; PARTIAL : P A R T I A L ; PARTITIONING : P A R T I T I O N I N G ; PARTITIONS : P A R T I T I O N S ; PASSWORD : P A S S W O R D ; PERSIST : P E R S I S T ; PERSIST_ONLY : P E R S I S T UL_ O N L Y ; PRECISION : P R E C I S I O N ; PRIVILEGES : P R I V I L E G E S ; PROCEDURE : P R O C E D U R E ; PROCESS : P R O C E S S ; PROXY : P R O X Y ; QUICK : Q U I C K ; RANGE : R A N G E ; REBUILD : R E B U I L D ; REDUNDANT : R E D U N D A N T ; RELEASE : R E L E A S E ; RELOAD : R E L O A D ; REMOVE : R E M O V E ; RENAME : R E N A M E ; REORGANIZE : R E O R G A N I Z E ; REPAIR : R E P A I R ; REPEATABLE : R E P E A T A B L E ; REPLACE : R E P L A C E ; REPLICATION : R E P L I C A T I O N ; REPLICATION_SLAVE_ADMIN : R E P L I C A T I O N UL_ S L A V E UL_ A D M I N ; RESTRICT : R E S T R I C T ; REVOKE : R E V O K E ; RIGHT : R I G H T ; ROLE_ADMIN : R O L E UL_ A D M I N ; ROUTINE : R O U T I N E ; ROW_FORMAT : R O W UL_ F O R M A T ; SAVEPOINT : S A V E P O I N T ; SESSION : S E S S I O N ; SET_USER_ID : S E T UL_ U S E R UL_ I D ; SHARED : S H A R E D ; SHOW : S H O W ; SHUTDOWN : S H U T D O W N ; SIMPLE : S I M P L E ; SLAVE : S L A V E ; SNAPSHOT : S N A P S H O T ; SPATIAL : S P A T I A L ; SQLDML : S Q L D M L ; SQLDQL : S Q L D Q L ; SQL_BIG_RESULT : S Q L UL_ B I G UL_ R E S U L T ; SQL_BUFFER_RESULT : S Q L UL_ B U F F E R UL_ R E S U L T ; SQL_CACHE : S Q L UL_ C A C H E ; SQL_CALC_FOUND_ROWS : S Q L UL_ C A L C UL_ F O U N D UL_ R O W S ; SQL_NO_CACHE : S Q L UL_ N O UL_ C A C H E ; SQL_SMALL_RESULT : S Q L UL_ S M A L L UL_ R E S U L T ; STATS_AUTO_RECALC : S T A T S UL_ A U T O UL_ R E C A L C ; STATS_PERSISTENT : S T A T S UL_ P E R S I S T E N T ; STATS_SAMPLE_PAGES : S T A T S UL_ S A M P L E UL_ P A G E S ; STORAGE : S T O R A G E ; STORED : S T O R E D ; STRAIGHT_JOIN : S T R A I G H T UL_ J O I N ; SUBPARTITION : S U B P A R T I T I O N ; SUBPARTITIONS : S U B P A R T I T I O N S ; SUPER : S U P E R ; SYSTEM_VARIABLES_ADMIN : S Y S T E M UL_ V A R I A B L E S UL_ A D M I N ; TABLES : T A B L E S ; TABLESPACE : T A B L E S P A C E ; TEMPORARY : T E M P O R A R Y ; THAN : T H A N ; THEN : T H E N ; TRIGGER : T R I G G E R ; UNCOMMITTED : U N C O M M I T T E D ; UNSIGNED : U N S I G N E D ; UPDATE : U P D A T E ; UPGRADE : U P G R A D E ; USAGE : U S A G E ; USE : U S E ; USER : U S E R ; USING : U S I N G ; VALIDATION : V A L I D A T I O N ; VALUE : V A L U E ; VALUES : V A L U E S ; VERSION_TOKEN_ADMIN : V E R S I O N UL_ T O K E N UL_ A D M I N ; VIEW : V I E W ; VIRTUAL : V I R T U A L ; WHEN : W H E N ; WITHOUT : W I T H O U T ; WRITE : W R I T E ; ZEROFILL : Z E R O F I L L ;
remove symbol AT_
remove symbol AT_
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
799cc2c7a57d8f107f7973478ba3034449204c5d
analyzer/src/main/antlr4/nl/basjes/parse/useragent/parser/UserAgentTreeWalker.g4
analyzer/src/main/antlr4/nl/basjes/parse/useragent/parser/UserAgentTreeWalker.g4
/* * Yet Another UserAgent Analyzer * Copyright (C) 2013-2017 Niels Basjes * * 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 UserAgentTreeWalker; // =============================================================== VALUENAME : [a-zA-Z][a-zA-Z0-9]+ ; VALUE : DOUBLEQUOTE ( '\\' [btnfr"'\\] | ~[\\"] )* DOUBLEQUOTE ; UP : '^' ; NEXT : '>' ; NEXT2 : '>>' ; NEXT3 : '>>>' ; NEXT4 : '>>>>' ; PREV : '<' ; PREV2 : '<<' ; PREV3 : '<<<' ; PREV4 : '<<<<' ; DOT : '.' ; MINUS : '-' ; STAR : '*' ; IN : '?' ; NUMBER : [0-9]+ ; BLOCKOPEN : '[' ; BLOCKCLOSE : ']' ; BRACEOPEN : '(' ; BRACECLOSE : ')' ; DOUBLEQUOTE : '"' ; COLON : ':' ; SEMICOLON : ';' ; SPACE : (' '|'\t')+ -> skip; NOTEQUALS : '!=' ; EQUALS : '=' ; CONTAINS : '~' ; STARTSWITH : '{' ; ENDSWITH : '}' ; 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"] matcherRequire : matcher #matcherBase // | '__SyntaxError__' EQUALS value=VALUE #isSyntaxError | 'IsNull' BLOCKOPEN matcher BLOCKCLOSE #matcherPathIsNull ; matcher : basePath #matcherPath | 'Concat' BLOCKOPEN prefix=VALUE SEMICOLON matcher SEMICOLON postfix=VALUE BLOCKCLOSE #matcherConcat | 'Concat' BLOCKOPEN prefix=VALUE SEMICOLON matcher BLOCKCLOSE #matcherConcatPrefix | 'Concat' BLOCKOPEN matcher SEMICOLON postfix=VALUE BLOCKCLOSE #matcherConcatPostfix | 'NormalizeBrand' BLOCKOPEN matcher BLOCKCLOSE #matcherNormalizeBrand | 'CleanVersion' BLOCKOPEN matcher BLOCKCLOSE #matcherCleanVersion | 'LookUp' BLOCKOPEN lookup=VALUENAME SEMICOLON matcher (SEMICOLON defaultValue=VALUE )? BLOCKCLOSE #matcherPathLookup | matcher wordRange #matcherWordRange ; basePath : value=VALUE #pathFixedValue // | 'agent' #pathNoWalk | '@' variable=VALUENAME (nextStep=path)? #pathVariable | 'agent' (nextStep=path)? #pathWalk ; path : DOT numberRange name=VALUENAME (nextStep=path)? #stepDown | UP (nextStep=path)? #stepUp | NEXT (nextStep=path)? #stepNext | NEXT2 (nextStep=path)? #stepNext2 | NEXT3 (nextStep=path)? #stepNext3 | NEXT4 (nextStep=path)? #stepNext4 | PREV (nextStep=path)? #stepPrev | PREV2 (nextStep=path)? #stepPrev2 | PREV3 (nextStep=path)? #stepPrev3 | PREV4 (nextStep=path)? #stepPrev4 | 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 | IN set=VALUENAME (nextStep=path)? #stepIsInSet | wordRange (nextStep=path)? #stepWordRange | BACKTOFULL (nextStep=path)? #stepBackToFull ; numberRange : ( BRACEOPEN rangeStart=NUMBER MINUS rangeEnd=NUMBER BRACECLOSE ) #numberRangeStartToEnd | ( BRACEOPEN count=NUMBER BRACECLOSE ) #numberRangeSingleValue | ( BRACEOPEN STAR BRACECLOSE ) #numberRangeAll | ( ) #numberRangeEmpty ; wordRange : ( BLOCKOPEN firstWord=NUMBER MINUS lastWord=NUMBER BLOCKCLOSE ) #wordRangeStartToEnd | ( BLOCKOPEN MINUS lastWord=NUMBER BLOCKCLOSE ) #wordRangeFirstWords | ( BLOCKOPEN firstWord=NUMBER MINUS BLOCKCLOSE ) #wordRangeLastWords | ( BLOCKOPEN singleWord=NUMBER BLOCKCLOSE ) #wordRangeSingleWord ;
/* * Yet Another UserAgent Analyzer * Copyright (C) 2013-2017 Niels Basjes * * 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 UserAgentTreeWalker; // =============================================================== VALUENAME : [a-zA-Z][a-zA-Z0-9]+ ; VALUE : DOUBLEQUOTE ( '\\' [btnfr"'\\] | ~[\\"] )* DOUBLEQUOTE ; UP : '^' ; NEXT : '>' ; NEXT2 : '>>' ; NEXT3 : '>>>' ; NEXT4 : '>>>>' ; PREV : '<' ; PREV2 : '<<' ; PREV3 : '<<<' ; PREV4 : '<<<<' ; DOT : '.' ; MINUS : '-' ; STAR : '*' ; IN : '?' ; NUMBER : [0-9]+ ; BLOCKOPEN : '[' ; BLOCKCLOSE : ']' ; BRACEOPEN : '(' ; BRACECLOSE : ')' ; DOUBLEQUOTE : '"' ; COLON : ':' ; SEMICOLON : ';' ; SPACE : (' '|'\t')+ -> skip; NOTEQUALS : '!=' ; EQUALS : '=' ; CONTAINS : '~' ; STARTSWITH : '{' ; ENDSWITH : '}' ; 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"] matcherRequire : matcher #matcherBase // | '__SyntaxError__' EQUALS value=VALUE #isSyntaxError | 'IsNull' BLOCKOPEN matcher BLOCKCLOSE #matcherPathIsNull ; matcher : basePath #matcherPath | 'Concat' BLOCKOPEN prefix=VALUE SEMICOLON matcher SEMICOLON postfix=VALUE BLOCKCLOSE #matcherConcat | 'Concat' BLOCKOPEN prefix=VALUE SEMICOLON matcher BLOCKCLOSE #matcherConcatPrefix | 'Concat' BLOCKOPEN matcher SEMICOLON postfix=VALUE BLOCKCLOSE #matcherConcatPostfix | 'NormalizeBrand' BLOCKOPEN matcher BLOCKCLOSE #matcherNormalizeBrand | 'CleanVersion' BLOCKOPEN matcher BLOCKCLOSE #matcherCleanVersion | 'LookUp' BLOCKOPEN lookup=VALUENAME SEMICOLON matcher (SEMICOLON defaultValue=VALUE )? BLOCKCLOSE #matcherPathLookup | matcher wordRange #matcherWordRange ; basePath : value=VALUE #pathFixedValue | '@' variable=VALUENAME (nextStep=path)? #pathVariable | 'agent' (nextStep=path)? #pathWalk ; path : DOT numberRange name=VALUENAME (nextStep=path)? #stepDown | UP (nextStep=path)? #stepUp | NEXT (nextStep=path)? #stepNext | NEXT2 (nextStep=path)? #stepNext2 | NEXT3 (nextStep=path)? #stepNext3 | NEXT4 (nextStep=path)? #stepNext4 | PREV (nextStep=path)? #stepPrev | PREV2 (nextStep=path)? #stepPrev2 | PREV3 (nextStep=path)? #stepPrev3 | PREV4 (nextStep=path)? #stepPrev4 | 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 | IN set=VALUENAME (nextStep=path)? #stepIsInSet | wordRange (nextStep=path)? #stepWordRange | BACKTOFULL (nextStep=path)? #stepBackToFull ; numberRange : ( BRACEOPEN rangeStart=NUMBER MINUS rangeEnd=NUMBER BRACECLOSE ) #numberRangeStartToEnd | ( BRACEOPEN count=NUMBER BRACECLOSE ) #numberRangeSingleValue | ( BRACEOPEN STAR BRACECLOSE ) #numberRangeAll | ( ) #numberRangeEmpty ; wordRange : ( BLOCKOPEN firstWord=NUMBER MINUS lastWord=NUMBER BLOCKCLOSE ) #wordRangeStartToEnd | ( BLOCKOPEN MINUS lastWord=NUMBER BLOCKCLOSE ) #wordRangeFirstWords | ( BLOCKOPEN firstWord=NUMBER MINUS BLOCKCLOSE ) #wordRangeLastWords | ( BLOCKOPEN singleWord=NUMBER BLOCKCLOSE ) #wordRangeSingleWord ;
Remove useless comment
Remove useless comment
ANTLR
apache-2.0
nielsbasjes/yauaa,nielsbasjes/yauaa,nielsbasjes/yauaa,nielsbasjes/yauaa
a097d4ec0dc48b5fd788afaada2a93950660e794
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 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: 'extend' '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 typo in GraphQL.g4
Fix typo in GraphQL.g4 The terminal 'extends' is incorrect, it should be 'extend'. See https://spec.graphql.org/June2018/#sec-Scalar-Extensions
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
0d90c6a39ec31e45e8d4adfcc27af990a758c254
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 | KW_USING columnParenthesesList)?)* ; 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 ; //-----------------------------------------------------------------------------------
remove v3 validating semantic predicates in rule joinSource
remove v3 validating semantic predicates in rule joinSource
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
0bf84fba6502cb4bc86f9e558a4a928e6397a793
yang/yang-parser-antlr/src/main/antlr4/org/opendaylight/yangtools/yang/parser/antlr/YangStatementLexer.g4
yang/yang-parser-antlr/src/main/antlr4/org/opendaylight/yangtools/yang/parser/antlr/YangStatementLexer.g4
// // Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License v1.0 which accompanies this distribution, // and is available at http://www.eclipse.org/legal/epl-v10.html // lexer grammar YangStatementLexer; tokens { SEMICOLON, LEFT_BRACE, RIGHT_BRACE, SEP, IDENTIFIER, COLON, PLUS } SEMICOLON : ';' -> type(SEMICOLON); LEFT_BRACE : '{' -> type(LEFT_BRACE); RIGHT_BRACE : '}' -> type(RIGHT_BRACE); COLON : ':' -> type(COLON); PLUS : '+' -> type(PLUS); LINE_COMMENT : [ \n\r\t]* ('//' (~[\r\n]*)) [ \n\r\t]* -> skip; START_BLOCK_COMMENT : '/*' ->pushMode(BLOCK_COMMENT_MODE), skip; SEP: [ \n\r\t]+ -> type(SEP); IDENTIFIER : [a-zA-Z_/][a-zA-Z0-9_\-.:/]* -> type(IDENTIFIER); fragment SUB_STRING : ('"' (ESC | ~["])*? '"') | ('\'' (ESC | ~['])* '\''); fragment ESC : '\\' (["\\/bfnrt] | UNICODE); fragment UNICODE : 'u' HEX HEX HEX HEX; fragment HEX : [0-9a-fA-F] ; STRING: ((~( '\r' | '\n' | '\t' | ' ' | ';' | '{' | '"' | '\'' | '}' | '/' | '+')~( '\r' | '\n' | '\t' | ' ' | ';' | '{' | '}' )* ) | SUB_STRING ); mode BLOCK_COMMENT_MODE; END_BLOCK_COMMENT : '*/' -> popMode, skip; BLOCK_COMMENT : . -> skip;
// // Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License v1.0 which accompanies this distribution, // and is available at http://www.eclipse.org/legal/epl-v10.html // lexer grammar YangStatementLexer; tokens { SEMICOLON, LEFT_BRACE, RIGHT_BRACE, SEP, IDENTIFIER, COLON, PLUS } SEMICOLON : ';' -> type(SEMICOLON); LEFT_BRACE : '{' -> type(LEFT_BRACE); RIGHT_BRACE : '}' -> type(RIGHT_BRACE); COLON : ':' -> type(COLON); PLUS : '+' -> type(PLUS); LINE_COMMENT : [ \n\r\t]* ('//' (~[\r\n]*)) [ \n\r\t]* -> skip; BLOCK_COMMENT : '/*' .*? '*/' -> skip; SEP: [ \n\r\t]+ -> type(SEP); IDENTIFIER : [a-zA-Z_/][a-zA-Z0-9_\-.:/]* -> type(IDENTIFIER); fragment SUB_STRING : ('"' (ESC | ~["])*? '"') | ('\'' (ESC | ~['])* '\''); fragment ESC : '\\' (["\\/bfnrt] | UNICODE); fragment UNICODE : 'u' HEX HEX HEX HEX; fragment HEX : [0-9a-fA-F] ; STRING: ((~( '\r' | '\n' | '\t' | ' ' | ';' | '{' | '"' | '\'' | '}' | '/' | '+')~( '\r' | '\n' | '\t' | ' ' | ';' | '{' | '}' )* ) | SUB_STRING );
Replace block comment with a non-greedy rule
Replace block comment with a non-greedy rule We do not need an explicit mode here, we can just use a non-greedy match and move on. This simplifies things a bit. Change-Id: Ieab6d9cec1b17c8d86cda49cfc46a258a569e5e0 Signed-off-by: Robert Varga <[email protected]>
ANTLR
epl-1.0
opendaylight/yangtools,opendaylight/yangtools
f06d26d9e37fc650141cff308e5cb552c300b7d8
shardingsphere-sql-parser/shardingsphere-sql-parser-dialect/shardingsphere-sql-parser-sqlserver/src/main/antlr4/imports/sqlserver/BaseRule.g4
shardingsphere-sql-parser/shardingsphere-sql-parser-dialect/shardingsphere-sql-parser-sqlserver/src/main/antlr4/imports/sqlserver/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 Symbol, Keyword, SQLServerKeyword, Literals; parameterMarker : QUESTION_ ; literals : stringLiterals | numberLiterals | dateTimeLiterals | hexadecimalLiterals | bitValueLiterals | booleanLiterals | nullValueLiterals ; stringLiterals : STRING_ ; numberLiterals : MINUS_? NUMBER_ ; dateTimeLiterals : (DATE | TIME | TIMESTAMP) STRING_ | LBE_ identifier STRING_ RBE_ ; hexadecimalLiterals : HEX_DIGIT_ ; bitValueLiterals : BIT_NUM_ ; booleanLiterals : TRUE | FALSE ; nullValueLiterals : NULL ; identifier : IDENTIFIER_ | unreservedWord ; unreservedWord : TRUNCATE | FUNCTION | TRIGGER | LIMIT | OFFSET | SAVEPOINT | BOOLEAN | ARRAY | LOCALTIME | LOCALTIMESTAMP | QUARTER | WEEK | MICROSECOND | ENABLE | DISABLE | BINARY | HIDDEN_ | MOD | PARTITION | TOP | ROW | XOR | ALWAYS | ROLE | START | ALGORITHM | AUTO | BLOCKERS | CLUSTERED | COLUMNSTORE | CONTENT | CONCAT | DATABASE | DAYS | DENY | DETERMINISTIC | DISTRIBUTION | DOCUMENT | DURABILITY | ENCRYPTED | FILESTREAM | FILETABLE | FOLLOWING | HASH | HEAP | INBOUND | INFINITE | LOGIN | MASKED | MAXDOP | MINUTES | MONTHS | MOVE | NOCHECK | NONCLUSTERED | OBJECT | OFF | ONLINE | OUTBOUND | OVER | PAGE | PARTITIONS | PAUSED | PERIOD | PERSISTED | PRECEDING | RANDOMIZED | RANGE | REBUILD | REPLICATE | REPLICATION | RESUMABLE | ROWGUIDCOL | SAVE | SELF | SPARSE | SWITCH | TRAN | TRANCOUNT | UNBOUNDED | YEARS | WEEKS | ABORT_AFTER_WAIT | ALLOW_PAGE_LOCKS | ALLOW_ROW_LOCKS | ALL_SPARSE_COLUMNS | BUCKET_COUNT | COLUMNSTORE_ARCHIVE | COLUMN_ENCRYPTION_KEY | COLUMN_SET | COMPRESSION_DELAY | DATABASE_DEAULT | DATA_COMPRESSION | DATA_CONSISTENCY_CHECK | ENCRYPTION_TYPE | SYSTEM_TIME | SYSTEM_VERSIONING | TEXTIMAGE_ON | WAIT_AT_LOW_PRIORITY | STATISTICS_INCREMENTAL | STATISTICS_NORECOMPUTE | ROUND_ROBIN | SCHEMA_AND_DATA | SCHEMA_ONLY | SORT_IN_TEMPDB | IGNORE_DUP_KEY | IMPLICIT_TRANSACTIONS | MAX_DURATION | MEMORY_OPTIMIZED | MIGRATION_STATE | PAD_INDEX | REMOTE_DATA_ARCHIVE | FILESTREAM_ON | FILETABLE_COLLATE_FILENAME | FILETABLE_DIRECTORY | FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME | FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME | FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME | FILLFACTOR | FILTER_PREDICATE | HISTORY_RETENTION_PERIOD | HISTORY_TABLE | LOCK_ESCALATION | DROP_EXISTING | ROW_NUMBER | CONTROL | TAKE | OWNERSHIP | DEFINITION | APPLICATION | ASSEMBLY | SYMMETRIC | ASYMMETRIC | SERVER | RECEIVE | CHANGE | TRACE | TRACKING | RESOURCES | SETTINGS | STATE | AVAILABILITY | CREDENTIAL | ENDPOINT | EVENT | NOTIFICATION | LINKED | AUDIT | DDL | SQL | XML | IMPERSONATE | SECURABLES | AUTHENTICATE | EXTERNAL | ACCESS | ADMINISTER | BULK | OPERATIONS | UNSAFE | SHUTDOWN | SCOPED | CONFIGURATION |DATASPACE | SERVICE | CERTIFICATE | CONTRACT | ENCRYPTION | MASTER | DATA | SOURCE | FILE | FORMAT | LIBRARY | FULLTEXT | MASK | UNMASK | MESSAGE | TYPE | REMOTE | BINDING | ROUTE | SECURITY | POLICY | AGGREGATE | QUEUE | RULE | SYNONYM | COLLECTION | SCRIPT | KILL | BACKUP | LOG | SHOWPLAN | SUBSCRIBE | QUERY | NOTIFICATIONS | CHECKPOINT | SEQUENCE | INSTANCE | DO | DEFINER | LOCAL | CASCADED | NEXT | NAME | INTEGER | TYPE | MAX | MIN | SUM | COUNT | AVG | FIRST | DATETIME2 | OUTPUT | INSERTED | DELETED ; schemaName : identifier ; tableName : (owner DOT_)? name ; columnName : (owner DOT_)? name ; owner : identifier ; name : identifier ; columnNames : LP_ columnName (COMMA_ columnName)* RP_ ; columnNamesWithSort : LP_ columnNameWithSort (COMMA_ columnNameWithSort)* RP_ ; tableNames : LP_? tableName (COMMA_ tableName)* RP_? ; indexName : identifier ; collationName : STRING_ | IDENTIFIER_ ; alias : IDENTIFIER_ ; dataTypeLength : LP_ (NUMBER_ (COMMA_ NUMBER_)?)? RP_ ; primaryKey : PRIMARY? KEY ; // TODO comb expr expr : expr logicalOperator expr | notOperator expr | LP_ expr RP_ | booleanPrimary ; logicalOperator : OR | OR_ | AND | AND_ ; notOperator : NOT | NOT_ ; 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_ expr (COMMA_ expr)* RP_ | bitExpr NOT? BETWEEN bitExpr AND predicate | bitExpr NOT? LIKE simpleExpr (ESCAPE 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 CARET_ bitExpr | simpleExpr ; simpleExpr : functionCall | parameterMarker | literals | columnName | simpleExpr OR_ simpleExpr | (PLUS_ | MINUS_ | TILDE_ | NOT_ | BINARY) simpleExpr | ROW? LP_ expr (COMMA_ expr)* RP_ | EXISTS? subquery | LBE_ identifier expr RBE_ | caseExpression | privateExprOfDb ; functionCall : aggregationFunction | specialFunction | regularFunction ; aggregationFunction : aggregationFunctionName LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? RP_ ; aggregationFunctionName : MAX | MIN | SUM | COUNT | AVG ; distinct : DISTINCT ; specialFunction : castFunction | charFunction ; castFunction : CAST LP_ expr AS dataType RP_ ; charFunction : CHAR LP_ expr (COMMA_ expr)* (USING ignoredIdentifier)? RP_ ; regularFunction : regularFunctionName LP_ (expr (COMMA_ expr)* | ASTERISK_)? RP_ ; regularFunctionName : identifier | IF | LOCALTIME | LOCALTIMESTAMP | INTERVAL ; caseExpression : CASE simpleExpr? caseWhen+ caseElse? ; caseWhen : WHEN expr THEN expr ; caseElse : ELSE expr ; privateExprOfDb : windowedFunction | atTimeZoneExpr | castExpr | convertExpr ; subquery : matchNone ; orderByClause : ORDER BY orderByItem (COMMA_ orderByItem)* (OFFSET expr (ROW | ROWS) (FETCH (FIRST | NEXT) expr (ROW | ROWS) ONLY)?)? ; orderByItem : (columnName | numberLiterals | expr) (ASC | DESC)? ; dataType : dataTypeName (dataTypeLength | LP_ MAX RP_ | LP_ (CONTENT | DOCUMENT)? ignoredIdentifier RP_)? ; dataTypeName : BIGINT | NUMERIC | BIT | SMALLINT | DECIMAL | SMALLMONEY | INT | TINYINT | MONEY | FLOAT | REAL | DATE | DATETIMEOFFSET | SMALLDATETIME | DATETIME | DATETIME2 | TIME | CHAR | VARCHAR | TEXT | NCHAR | NVARCHAR | NTEXT | BINARY | VARBINARY | IMAGE | SQL_VARIANT | XML | UNIQUEIDENTIFIER | HIERARCHYID | GEOMETRY | GEOGRAPHY | IDENTIFIER_ ; atTimeZoneExpr : IDENTIFIER_ (WITH TIME ZONE)? STRING_ ; castExpr : CAST LP_ expr AS dataType (LP_ NUMBER_ RP_)? RP_ ; convertExpr : CONVERT (dataType (LP_ NUMBER_ RP_)? COMMA_ expr (COMMA_ NUMBER_)?) ; windowedFunction : functionCall overClause ; overClause : OVER LP_ partitionByClause? orderByClause? rowRangeClause? RP_ ; partitionByClause : PARTITION BY expr (COMMA_ expr)* ; rowRangeClause : (ROWS | RANGE) windowFrameExtent ; windowFrameExtent : windowFramePreceding | windowFrameBetween ; windowFrameBetween : BETWEEN windowFrameBound AND windowFrameBound ; windowFrameBound : windowFramePreceding | windowFrameFollowing ; windowFramePreceding : UNBOUNDED PRECEDING | NUMBER_ PRECEDING | CURRENT ROW ; windowFrameFollowing : UNBOUNDED FOLLOWING | NUMBER_ FOLLOWING | CURRENT ROW ; columnNameWithSort : columnName (ASC | DESC)? ; indexOption : FILLFACTOR EQ_ NUMBER_ | eqOnOffOption | (COMPRESSION_DELAY | MAX_DURATION) eqTime | MAXDOP EQ_ NUMBER_ | compressionOption onPartitionClause? ; compressionOption : DATA_COMPRESSION EQ_ (NONE | ROW | PAGE | COLUMNSTORE | COLUMNSTORE_ARCHIVE) ; eqTime : EQ_ NUMBER_ (MINUTES)? ; eqOnOffOption : eqKey eqOnOff ; eqKey : PAD_INDEX | SORT_IN_TEMPDB | IGNORE_DUP_KEY | STATISTICS_NORECOMPUTE | STATISTICS_INCREMENTAL | DROP_EXISTING | ONLINE | RESUMABLE | ALLOW_ROW_LOCKS | ALLOW_PAGE_LOCKS | COMPRESSION_DELAY | SORT_IN_TEMPDB ; eqOnOff : EQ_ (ON | OFF) ; onPartitionClause : ON PARTITIONS LP_ partitionExpressions RP_ ; partitionExpressions : partitionExpression (COMMA_ partitionExpression)* ; partitionExpression : NUMBER_ | numberRange ; numberRange : NUMBER_ TO NUMBER_ ; lowPriorityLockWait : WAIT_AT_LOW_PRIORITY LP_ MAX_DURATION EQ_ NUMBER_ (MINUTES)? COMMA_ ABORT_AFTER_WAIT EQ_ (NONE | SELF | BLOCKERS) RP_ ; onLowPriorLockWait : ON (LP_ lowPriorityLockWait 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 Symbol, Keyword, SQLServerKeyword, Literals; parameterMarker : QUESTION_ ; literals : stringLiterals | numberLiterals | dateTimeLiterals | hexadecimalLiterals | bitValueLiterals | booleanLiterals | nullValueLiterals ; stringLiterals : STRING_ ; numberLiterals : MINUS_? NUMBER_ ; dateTimeLiterals : (DATE | TIME | TIMESTAMP) STRING_ | LBE_ identifier STRING_ RBE_ ; hexadecimalLiterals : HEX_DIGIT_ ; bitValueLiterals : BIT_NUM_ ; booleanLiterals : TRUE | FALSE ; nullValueLiterals : NULL ; identifier : IDENTIFIER_ | unreservedWord ; unreservedWord : TRUNCATE | FUNCTION | TRIGGER | LIMIT | OFFSET | SAVEPOINT | BOOLEAN | ARRAY | LOCALTIME | LOCALTIMESTAMP | QUARTER | WEEK | MICROSECOND | ENABLE | DISABLE | BINARY | HIDDEN_ | MOD | PARTITION | TOP | ROW | XOR | ALWAYS | ROLE | START | ALGORITHM | AUTO | BLOCKERS | CLUSTERED | COLUMNSTORE | CONTENT | CONCAT | DATABASE | DAYS | DENY | DETERMINISTIC | DISTRIBUTION | DOCUMENT | DURABILITY | ENCRYPTED | FILESTREAM | FILETABLE | FOLLOWING | HASH | HEAP | INBOUND | INFINITE | LOGIN | MASKED | MAXDOP | MINUTES | MONTHS | MOVE | NOCHECK | NONCLUSTERED | OBJECT | OFF | ONLINE | OUTBOUND | OVER | PAGE | PARTITIONS | PAUSED | PERIOD | PERSISTED | PRECEDING | RANDOMIZED | RANGE | REBUILD | REPLICATE | REPLICATION | RESUMABLE | ROWGUIDCOL | SAVE | SELF | SPARSE | SWITCH | TRAN | TRANCOUNT | UNBOUNDED | YEARS | WEEKS | ABORT_AFTER_WAIT | ALLOW_PAGE_LOCKS | ALLOW_ROW_LOCKS | ALL_SPARSE_COLUMNS | BUCKET_COUNT | COLUMNSTORE_ARCHIVE | COLUMN_ENCRYPTION_KEY | COLUMN_SET | COMPRESSION_DELAY | DATABASE_DEAULT | DATA_COMPRESSION | DATA_CONSISTENCY_CHECK | ENCRYPTION_TYPE | SYSTEM_TIME | SYSTEM_VERSIONING | TEXTIMAGE_ON | WAIT_AT_LOW_PRIORITY | STATISTICS_INCREMENTAL | STATISTICS_NORECOMPUTE | ROUND_ROBIN | SCHEMA_AND_DATA | SCHEMA_ONLY | SORT_IN_TEMPDB | IGNORE_DUP_KEY | IMPLICIT_TRANSACTIONS | MAX_DURATION | MEMORY_OPTIMIZED | MIGRATION_STATE | PAD_INDEX | REMOTE_DATA_ARCHIVE | FILESTREAM_ON | FILETABLE_COLLATE_FILENAME | FILETABLE_DIRECTORY | FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME | FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME | FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME | FILLFACTOR | FILTER_PREDICATE | HISTORY_RETENTION_PERIOD | HISTORY_TABLE | LOCK_ESCALATION | DROP_EXISTING | ROW_NUMBER | CONTROL | TAKE | OWNERSHIP | DEFINITION | APPLICATION | ASSEMBLY | SYMMETRIC | ASYMMETRIC | SERVER | RECEIVE | CHANGE | TRACE | TRACKING | RESOURCES | SETTINGS | STATE | AVAILABILITY | CREDENTIAL | ENDPOINT | EVENT | NOTIFICATION | LINKED | AUDIT | DDL | SQL | XML | IMPERSONATE | SECURABLES | AUTHENTICATE | EXTERNAL | ACCESS | ADMINISTER | BULK | OPERATIONS | UNSAFE | SHUTDOWN | SCOPED | CONFIGURATION |DATASPACE | SERVICE | CERTIFICATE | CONTRACT | ENCRYPTION | MASTER | DATA | SOURCE | FILE | FORMAT | LIBRARY | FULLTEXT | MASK | UNMASK | MESSAGE | TYPE | REMOTE | BINDING | ROUTE | SECURITY | POLICY | AGGREGATE | QUEUE | RULE | SYNONYM | COLLECTION | SCRIPT | KILL | BACKUP | LOG | SHOWPLAN | SUBSCRIBE | QUERY | NOTIFICATIONS | CHECKPOINT | SEQUENCE | INSTANCE | DO | DEFINER | LOCAL | CASCADED | NEXT | NAME | INTEGER | TYPE | MAX | MIN | SUM | COUNT | AVG | FIRST | DATETIME2 | OUTPUT | INSERTED | DELETED ; schemaName : identifier ; tableName : (owner DOT_)? name ; columnName : (owner DOT_)? name ; owner : identifier ; name : identifier ; columnNames : LP_ columnName (COMMA_ columnName)* RP_ ; columnNamesWithSort : LP_ columnNameWithSort (COMMA_ columnNameWithSort)* RP_ ; tableNames : LP_? tableName (COMMA_ tableName)* RP_? ; indexName : identifier ; collationName : STRING_ | IDENTIFIER_ ; alias : IDENTIFIER_ ; dataTypeLength : LP_ (NUMBER_ (COMMA_ NUMBER_)?)? RP_ ; primaryKey : PRIMARY? KEY ; // TODO comb expr expr : expr logicalOperator expr | notOperator expr | LP_ expr RP_ | booleanPrimary ; logicalOperator : OR | OR_ | AND | AND_ ; notOperator : NOT | NOT_ ; 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_ expr (COMMA_ expr)* RP_ | bitExpr NOT? BETWEEN bitExpr AND predicate | bitExpr NOT? LIKE simpleExpr (ESCAPE 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 CARET_ bitExpr | simpleExpr ; simpleExpr : functionCall | parameterMarker | literals | columnName | simpleExpr OR_ simpleExpr | (PLUS_ | MINUS_ | TILDE_ | NOT_ | BINARY) simpleExpr | ROW? LP_ expr (COMMA_ expr)* RP_ | EXISTS? subquery | LBE_ identifier expr RBE_ | caseExpression | privateExprOfDb ; functionCall : aggregationFunction | specialFunction | regularFunction ; aggregationFunction : aggregationFunctionName LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? RP_ ; aggregationFunctionName : MAX | MIN | SUM | COUNT | AVG ; distinct : DISTINCT ; specialFunction : castFunction | charFunction ; castFunction : CAST LP_ expr AS dataType RP_ ; charFunction : CHAR LP_ expr (COMMA_ expr)* (USING ignoredIdentifier)? RP_ ; regularFunction : regularFunctionName LP_ (expr (COMMA_ expr)* | ASTERISK_)? RP_ ; regularFunctionName : identifier | IF | LOCALTIME | LOCALTIMESTAMP | INTERVAL ; caseExpression : CASE simpleExpr? caseWhen+ caseElse? ; caseWhen : WHEN expr THEN expr ; caseElse : ELSE expr ; privateExprOfDb : windowedFunction | atTimeZoneExpr | castExpr | convertExpr ; subquery : matchNone ; orderByClause : ORDER BY orderByItem (COMMA_ orderByItem)* (OFFSET expr (ROW | ROWS) (FETCH (FIRST | NEXT) expr (ROW | ROWS) ONLY)?)? ; orderByItem : (columnName | numberLiterals | expr) (COLLATE identifier)? (ASC | DESC)? ; dataType : dataTypeName (dataTypeLength | LP_ MAX RP_ | LP_ (CONTENT | DOCUMENT)? ignoredIdentifier RP_)? ; dataTypeName : BIGINT | NUMERIC | BIT | SMALLINT | DECIMAL | SMALLMONEY | INT | TINYINT | MONEY | FLOAT | REAL | DATE | DATETIMEOFFSET | SMALLDATETIME | DATETIME | DATETIME2 | TIME | CHAR | VARCHAR | TEXT | NCHAR | NVARCHAR | NTEXT | BINARY | VARBINARY | IMAGE | SQL_VARIANT | XML | UNIQUEIDENTIFIER | HIERARCHYID | GEOMETRY | GEOGRAPHY | IDENTIFIER_ ; atTimeZoneExpr : IDENTIFIER_ (WITH TIME ZONE)? STRING_ ; castExpr : CAST LP_ expr AS dataType (LP_ NUMBER_ RP_)? RP_ ; convertExpr : CONVERT (dataType (LP_ NUMBER_ RP_)? COMMA_ expr (COMMA_ NUMBER_)?) ; windowedFunction : functionCall overClause ; overClause : OVER LP_ partitionByClause? orderByClause? rowRangeClause? RP_ ; partitionByClause : PARTITION BY expr (COMMA_ expr)* ; rowRangeClause : (ROWS | RANGE) windowFrameExtent ; windowFrameExtent : windowFramePreceding | windowFrameBetween ; windowFrameBetween : BETWEEN windowFrameBound AND windowFrameBound ; windowFrameBound : windowFramePreceding | windowFrameFollowing ; windowFramePreceding : UNBOUNDED PRECEDING | NUMBER_ PRECEDING | CURRENT ROW ; windowFrameFollowing : UNBOUNDED FOLLOWING | NUMBER_ FOLLOWING | CURRENT ROW ; columnNameWithSort : columnName (ASC | DESC)? ; indexOption : FILLFACTOR EQ_ NUMBER_ | eqOnOffOption | (COMPRESSION_DELAY | MAX_DURATION) eqTime | MAXDOP EQ_ NUMBER_ | compressionOption onPartitionClause? ; compressionOption : DATA_COMPRESSION EQ_ (NONE | ROW | PAGE | COLUMNSTORE | COLUMNSTORE_ARCHIVE) ; eqTime : EQ_ NUMBER_ (MINUTES)? ; eqOnOffOption : eqKey eqOnOff ; eqKey : PAD_INDEX | SORT_IN_TEMPDB | IGNORE_DUP_KEY | STATISTICS_NORECOMPUTE | STATISTICS_INCREMENTAL | DROP_EXISTING | ONLINE | RESUMABLE | ALLOW_ROW_LOCKS | ALLOW_PAGE_LOCKS | COMPRESSION_DELAY | SORT_IN_TEMPDB ; eqOnOff : EQ_ (ON | OFF) ; onPartitionClause : ON PARTITIONS LP_ partitionExpressions RP_ ; partitionExpressions : partitionExpression (COMMA_ partitionExpression)* ; partitionExpression : NUMBER_ | numberRange ; numberRange : NUMBER_ TO NUMBER_ ; lowPriorityLockWait : WAIT_AT_LOW_PRIORITY LP_ MAX_DURATION EQ_ NUMBER_ (MINUTES)? COMMA_ ABORT_AFTER_WAIT EQ_ (NONE | SELF | BLOCKERS) RP_ ; onLowPriorLockWait : ON (LP_ lowPriorityLockWait RP_)? ; ignoredIdentifier : IDENTIFIER_ ; ignoredIdentifiers : ignoredIdentifier (COMMA_ ignoredIdentifier)* ; matchNone : 'Default does not match anything' ;
add SQLServer order by collate support. (#9493)
add SQLServer order by collate support. (#9493) Co-authored-by: Zonglei Dong <[email protected]>
ANTLR
apache-2.0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
c5d468badc8a69bb389ca133ffa0828024c1f755
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 ; 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 : 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)? ;
add revokeSystemPrivileges
add revokeSystemPrivileges
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
c70ea782e88178c60fa2ca3d426a21b5fcb6520b
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; document: description* definition+; definition: execDefinition | typeSystemDefinition | typeSystemExtension; // https://graphql.github.io/graphql-spec/June2018/#TypeSystemDefinition typeSystemDefinition: schemaDefinition | typeDefinition | directiveDefinition; // https://graphql.github.io/graphql-spec/June2018/#sec-Schema schemaDefinition: 'schema' directives? rootOperationTypeDefinitionList; rootOperationTypeDefinitionList: '{' rootOperationTypeDefinition ( ','? rootOperationTypeDefinition )* '}'; rootOperationTypeDefinition: operationType ':' namedType; namedType: NAME; //https://graphql.github.io/graphql-spec/June2018/#TypeDefinition typeDefinition: scalarTypeDefinition | objectTypeDefinition | interfaceTypeDefinition | unionTypeDefinition | enumTypeDefinition | inputObjectTypeDefinition; scalarTypeDefinition: description? 'scalar' NAME directives; description: String_; // https://graphql.github.io/graphql-spec/June2018/#sec-Objects objectTypeDefinition : description? 'type' NAME implementsInterfaces? directives? fieldsDefinitions?; implementsInterfaces: 'implements' '&'? type_ | implementsInterfaces '&' type_; fieldsDefinitions: '{' fieldsDefinition+'}'; fieldsDefinition: description? NAME argumentsDefinition? ':' type_ directives? ; argumentsDefinition: '(' inputValueDefinition (',' inputValueDefinition)* ')'; inputValueDefinition: description? NAME ':' type_ defaultValue? directives?; //https://graphql.github.io/graphql-spec/June2018/#sec-Interfaces interfaceTypeDefinition : description? 'interface' NAME directives? fieldsDefinitions?; // https://graphql.github.io/graphql-spec/June2018/#sec-Unions unionTypeDefinition: description? 'union' NAME directives? unionMemberTypes?; unionMemberTypes: '=' type_ ('|' type_)* ; unionTypeExtension : 'extend' unionTypeDefinition; enumTypeDefinition: description? 'enum' NAME directives? enumValuesDefinitions?; enumValuesDefinitions: '{' ( description? enumElementValue directives?)+ '}'; enumElementValue: NAME ;// not (nullValue | booleanValue) enumTypeExtension: 'extend' enumTypeDefinition; //https://graphql.github.io/graphql-spec/June2018/#InputObjectTypeDefinition inputObjectTypeDefinition: description? 'input' NAME directives? inputFieldsDefinition?; inputFieldsDefinition: '{' inputValueDefinition+ '}'; directiveDefinition: description? 'directive' '@' NAME argumentsDefinition? 'on' directiveLocations; directiveLocations: directiveLocation ('|' directiveLocations)*; 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'; // https://graphql.github.io/graphql-spec/June2018/#sec-Type-System-Extensions typeSystemExtension: schemaExtension | typeExtension; schemaExtension: 'extend' schemaDefinition ; typeExtension: 'extend' typeDefinition; // original code: execution definitions // GraphQL Draft Specification - July 2015 execDefinition: operationDefinition | fragmentDefinition; operationDefinition: selectionSet | operationType NAME variableDefinitions? directives? selectionSet; selectionSet: '{' selection ( ','? selection)* '}'; operationType: 'query' | 'mutation' | 'subscription'; selection: field | fragmentSpread | inlineFragment; field: fieldName arguments? directives? selectionSet?; fieldName: alias | NAME; alias: NAME ':' NAME; arguments: '(' argument ( ',' argument)* ')'; argument: NAME ':' valueOrVariable; fragmentSpread: '...' fragmentName directives?; inlineFragment: '...' 'on' typeCondition directives? selectionSet; fragmentDefinition: 'fragment' fragmentName 'on' typeCondition directives? selectionSet; fragmentName: NAME; directives: directive+; directive: '@' NAME ':' valueOrVariable | '@' NAME | '@' NAME '(' argument ')'; typeCondition: typeName; variableDefinitions: '(' variableDefinition (',' variableDefinition)* ')'; variableDefinition: variable ':' type_ defaultValue?; variable: '$' NAME; defaultValue: '=' value; valueOrVariable: value | variable; value: String_ # stringValue | NAME # enumValue | NUMBER # numberValue | BooleanLiteral # booleanValue | array # arrayValue | ID # idValue //The ID scalar type represents a unique identifier, often used to refetch an object or as the key for a cache. The ID type is serialized in the same way as a String; however, defining it as an ID signifies that it is not intended to be human‐readable. | 'null' # nullValue ; BooleanLiteral : 'true' | 'false' ; type_: typeName nonNullType? | listType nonNullType?; typeName: NAME; listType: '[' type_ ']'; nonNullType: '!'; array: '[' value ( ',' value)* ']' | '[' ']'; NAME: [_A-Za-z] [_0-9A-Za-z]*; String_ : STRING | BLOCK_STRING; STRING: '"' ( ESC | ~ ["\\])* '"'; BLOCK_STRING : '"""' .*? '"""' ; ID: STRING; 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; LineComment : '#' ~[\r\n]* -> skip ;
/* 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; document: definition+; definition: execDefinition | typeSystemDefinition | typeSystemExtension; // https://graphql.github.io/graphql-spec/June2018/#TypeSystemDefinition typeSystemDefinition: schemaDefinition | typeDefinition | directiveDefinition; // https://graphql.github.io/graphql-spec/June2018/#sec-Schema schemaDefinition: 'schema' directives? '{' rootOperationTypeDefinition+ '}'; rootOperationTypeDefinition: operationType ':' namedType; namedType: NAME; //https://graphql.github.io/graphql-spec/June2018/#TypeDefinition typeDefinition: scalarTypeDefinition | objectTypeDefinition | interfaceTypeDefinition | unionTypeDefinition | enumTypeDefinition | inputObjectTypeDefinition; scalarTypeDefinition: description? 'scalar' NAME directives?; description: String_; // 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? ; argumentsDefinition: '(' inputValueDefinition+ ')'; inputValueDefinition: description? NAME ':' type_ defaultValue? directives?; //https://graphql.github.io/graphql-spec/June2018/#sec-Interfaces interfaceTypeDefinition : description? 'interface' NAME directives? fieldsDefinition?; // https://graphql.github.io/graphql-spec/June2018/#sec-Unions unionTypeDefinition: description? 'union' NAME directives? unionMemberTypes?; unionMemberTypes: '=' '|'? type_ ('|' type_)* ; unionTypeExtension : 'extend' unionTypeDefinition; enumTypeDefinition: description? 'enum' NAME directives? enumValuesDefinition?; enumValuesDefinition: '{' ( description? enumValue directives?)+ '}'; enumValue: NAME; //{ not (nullValue | booleanValue) }; enumTypeExtension: 'extend' enumTypeDefinition; //https://graphql.github.io/graphql-spec/June2018/#InputObjectTypeDefinition inputObjectTypeDefinition: description? 'input' NAME directives? inputFieldsDefinition?; inputFieldsDefinition: '{' inputValueDefinition+ '}'; directiveDefinition: description? 'directive' '@' NAME argumentsDefinition? 'on' directiveLocations; directiveLocations: directiveLocation ('|' directiveLocations)*; 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'; // https://graphql.github.io/graphql-spec/June2018/#sec-Type-System-Extensions typeSystemExtension: schemaExtension | typeExtension; schemaExtension: 'extend' schemaDefinition ; typeExtension: 'extend' typeDefinition; // original code: execution definitions // GraphQL Draft Specification - July 2015 execDefinition: operationDefinition | fragmentDefinition; operationDefinition: selectionSet | operationType NAME? variableDefinitions? directives? selectionSet; selectionSet: '{' selection+ '}'; operationType: 'query' | 'mutation' | 'subscription'; selection: field | fragmentSpread | inlineFragment; field: alias? fieldName arguments? directives? selectionSet?; fieldName: NAME; alias: NAME ':'; arguments: '(' argument+ ')'; argument: NAME ':' value; fragmentSpread: '...' fragmentName directives?; inlineFragment: '...' 'on' typeCondition directives? selectionSet; fragmentDefinition: 'fragment' fragmentName 'on' typeCondition directives? selectionSet; fragmentName: NAME; directives: directive+; directive: '@' NAME arguments?; typeCondition: typeName; variableDefinitions: '(' variableDefinition+ ')'; variableDefinition: variable ':' type_ defaultValue?; variable: '$' NAME; defaultValue: '=' value; value: variable # variableValue | NUMBER # numberValue | String_ # stringValue | BooleanLiteral # booleanValue | 'null' # nullValue | enumValue # constValue | array # arrayValue | object # objectValue ; object: '{' '}' | '{' objectField '}' ; objectField: NAME ':' value; BooleanLiteral : 'true' | 'false' ; type_: typeName nonNull? | listType nonNull?; typeName: NAME; listType: '[' type_ ']'; nonNull: '!'; array: '[' value+ ']' | '[' ']' ; NAME: [_A-Za-z] [_0-9A-Za-z]*; String_ : STRING | BLOCK_STRING; STRING: '"' ( ESC | ~ ["\\])* '"'; BLOCK_STRING : '"""' .*? '"""' ; ID: STRING; 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; PUNCTUATOR: '!' | '$' | '(' | ')' | '...' | ':' | '=' | '@' | '[' | ']' | '{' | '}' | '|' ; fragment INT: '0' | [1-9] [0-9]*; // 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';
Update to June 2018 schema
Update to June 2018 schema Update the grammar to June 2018 schema
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
cf0776d7ce91743c832114e73c9ba6b3d5e00c00
turin-parser/src/main/antlr4/me/tomassetti/parser/antlr/TurinParser.g4
turin-parser/src/main/antlr4/me/tomassetti/parser/antlr/TurinParser.g4
parser grammar TurinParser; options { tokenVocab = TurinLexer; } @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 | allPackageImportDeclaration; typeImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TID (AS_KW alternativeName=TID)? nls ; singleFieldImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TID POINT fieldName=qualifiedId (AS_KW alternativeName=ID)? nls; allFieldsImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TID POINT ASTERISK nls; allPackageImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT ASTERISK nls; // typeUsage: ref=TID | arrayBase=typeUsage LSQUARE RSQUARE | primitiveType = PRIMITIVE_TYPE | basicType = BASIC_TYPE; // method definition methodDefinition: type=returnType name=ID LPAREN (params+=formalParam (COMMA params+=formalParam)*)? RPAREN methodBody; returnType: isVoid=VOID_KW | type=typeUsage; methodBody: ASSIGNMENT value=expression nls | LBRACKET nls (statements += statement)* RBRACKET nls; // 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 | methodDefinition; typeDeclaration: TYPE_KW name=TID LBRACKET nls (typeMembers += typeMember)* RBRACKET nls; // actualParam: expression | name=ID ASSIGNMENT expression; parenExpression: LPAREN internal=expression RPAREN; basicExpression: booleanLiteral | stringLiteral | intLiteral | interpolatedStringLiteral | valueReference | parenExpression; booleanLiteral: negative=FALSE_KW | positive=TRUE_KW; expression: invokation | creation | basicExpression | fieldAccess | staticFieldReference | left=expression operator=ASTERISK right=expression | left=expression operator=SLASH right=expression | left=expression operator=PLUS right=expression | left=expression operator=MINUS right=expression ; invokation: function=basicExpression LPAREN (params+=actualParam (COMMA params+=actualParam)*)? RPAREN ; fieldAccess: subject=basicExpression POINT name=ID; staticFieldReference: typeReference POINT name=ID; valueReference: name=ID; typeReference: (packag=qualifiedId)? POINT name=TID; stringLiteral: STRING_START (content=STRING_CONTENT)? STRING_STOP; interpolatedStringLiteral: STRING_START (elements+=stringElement)+ STRING_STOP; stringElement: STRING_CONTENT | stringInterpolationElement; stringInterpolationElement: INTERPOLATION_START value=expression INTERPOLATION_END; intLiteral: INT; creation: (pakage=qualifiedId POINT)? name=TID LPAREN (params+=actualParam (COMMA params+=actualParam)*)? RPAREN ; varDecl : VAL_KW (type=typeUsage)? name=ID ASSIGNMENT value=expression nls; expressionStmt: expression nls; returnStmt: RETURN_KW value=expression nls; statement : varDecl | expressionStmt | returnStmt; // 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;
parser grammar TurinParser; options { tokenVocab = TurinLexer; } @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 | allPackageImportDeclaration; typeImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TID (AS_KW alternativeName=TID)? nls ; singleFieldImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TID POINT fieldName=qualifiedId (AS_KW alternativeName=ID)? nls; allFieldsImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TID POINT ASTERISK nls; allPackageImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT ASTERISK nls; // typeUsage: ref=TID | arrayBase=typeUsage LSQUARE RSQUARE | primitiveType = PRIMITIVE_TYPE | basicType = BASIC_TYPE; commaNl: COMMA NL?; // method definition methodDefinition: type=returnType name=ID LPAREN (params+=formalParam (commaNl params+=formalParam)*)? RPAREN methodBody; returnType: isVoid=VOID_KW | type=typeUsage; methodBody: ASSIGNMENT value=expression nls | LBRACKET nls (statements += statement)* RBRACKET nls; // 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 | methodDefinition; typeDeclaration: TYPE_KW name=TID LBRACKET nls (typeMembers += typeMember)* RBRACKET nls; // actualParam: expression | name=ID ASSIGNMENT expression; parenExpression: LPAREN internal=expression RPAREN; basicExpression: booleanLiteral | stringLiteral | intLiteral | interpolatedStringLiteral | valueReference | parenExpression; booleanLiteral: negative=FALSE_KW | positive=TRUE_KW; expression: invokation | creation | basicExpression | fieldAccess | staticFieldReference | left=expression operator=ASTERISK right=expression | left=expression operator=SLASH right=expression | left=expression operator=PLUS right=expression | left=expression operator=MINUS right=expression ; invokation: function=basicExpression LPAREN (params+=actualParam (commaNl params+=actualParam)*)? RPAREN ; fieldAccess: subject=basicExpression POINT name=ID; staticFieldReference: typeReference POINT name=ID; valueReference: name=ID; typeReference: (packag=qualifiedId)? POINT name=TID; stringLiteral: STRING_START (content=STRING_CONTENT)? STRING_STOP; interpolatedStringLiteral: STRING_START (elements+=stringElement)+ STRING_STOP; stringElement: STRING_CONTENT | stringInterpolationElement; stringInterpolationElement: INTERPOLATION_START value=expression INTERPOLATION_END; intLiteral: INT; creation: (pakage=qualifiedId POINT)? name=TID LPAREN (params+=actualParam (commaNl params+=actualParam)*)? RPAREN ; varDecl : VAL_KW (type=typeUsage)? name=ID ASSIGNMENT value=expression nls; expressionStmt: expression nls; returnStmt: RETURN_KW value=expression nls; statement : varDecl | expressionStmt | returnStmt; // formalParam : type=typeUsage name=ID; // program: PROGRAM_KW name=TID LPAREN params+=formalParam (commaNl params+=formalParam)* RPAREN LBRACKET nls (statements += statement)* RBRACKET nls; // fileMember: topLevelPropertyDeclaration | typeDeclaration | program;
support newlines after commas
support newlines after commas
ANTLR
apache-2.0
ftomassetti/turin-programming-language,ftomassetti/turin-programming-language
93b174f7366be6d9d22e4c0305fad369629a3a94
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_]*; //变量 VAR : [A-Z][a-zA-Z0-9_]*; //加号 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; //关系运算符(comparison predicates) relation_op : LESS_THAN | LEQ | GREATER_THAN | GEQ | EQUAL | DOUBLE_EQUAL | NEQ; //简单四则运算算术表达式,不加括号 simple_arithmetic_expr : integer | (MINUS)? VAR | (integer | (MINUS)? VAR) (arithmetic_op (natural_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; //项 term : VAR | CONSTANT | integer | arithmethic_expr | function | STRING; //原子 atom : CONSTANT | CONSTANT LPAREN term (COMMA term)* RPAREN; //范围整数枚举原子 range_atom : CONSTANT LPAREN integer RANGE integer RPAREN; //文字 literal : atom | MINUS atom | NAF_NOT 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)? VAR relation_op (MINUS)? VAR | VAR relation_op STRING | ((MINUS)? VAR | arithmethic_expr) relation_op ((MINUS)? VAR | arithmethic_expr); //规则头部 head : head_literal (DISJUNCTION head_literal)*; //头部文字 head_literal : literal | head_aggregate | NAF_NOT head_literal; //规则体部 body : body_literal (COMMA body_literal)*; //体部文字 body_literal : literal | relation_expr | body_aggregate | NAF_NOT body_literal; //事实 fact : (head | range_atom) 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'; //常量 CONSTANT : [a-z][a-zA-Z0-9_]*; //变量 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 | DOUBLE_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; //项 term : VAR | CONSTANT | integer | arithmethic_expr | function | STRING; //原子 atom : CONSTANT | CONSTANT LPAREN term (COMMA term)* RPAREN; //范围整数枚举原子 range_atom : CONSTANT LPAREN integer RANGE integer RPAREN; //文字 literal : atom | MINUS atom | NAF_NOT 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)? VAR relation_op (MINUS)? VAR | VAR relation_op STRING | ((MINUS)? VAR | arithmethic_expr) relation_op ((MINUS)? VAR | arithmethic_expr); //规则头部 head : head_literal (DISJUNCTION head_literal)*; //头部文字 head_literal : literal | head_aggregate | NAF_NOT head_literal; //规则体部 body : body_literal (COMMA body_literal)*; //体部文字 body_literal : literal | relation_expr | body_aggregate | NAF_NOT body_literal; //事实 fact : (head | range_atom) 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)*;
添加位运算,指数运算
添加位运算,指数运算 Signed-off-by: 许鸿翔 <[email protected]>
ANTLR
agpl-3.0
wangbiu/lpmlnmodels
bdaa71194f5eb407bbb0b021dd7cbfdf99e7381e
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 ALNUM+ {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 upper-case letters in file extensions
Allow upper-case letters in file extensions
ANTLR
apache-2.0
ashirley/reviki,ashirley/reviki,CoreFiling/reviki,strr/reviki,CoreFiling/reviki,ashirley/reviki,CoreFiling/reviki,strr/reviki,strr/reviki,strr/reviki,CoreFiling/reviki,strr/reviki,CoreFiling/reviki,ashirley/reviki,ashirley/reviki
d665ead3680fbb28cc5bd75347d8e4f35bcaaa42
pattern_grammar/STIXPattern.g4
pattern_grammar/STIXPattern.g4
// This is an ANTLR4 grammar for the STIX Patterning Language. // // http://docs.oasis-open.org/cti/stix/v2.0/stix-v2.0-part5-stix-patterning.html grammar STIXPattern; pattern : observationExpressions EOF ; observationExpressions : <assoc=left> observationExpressions FOLLOWEDBY observationExpressions | observationExpressionOr ; observationExpressionOr : <assoc=left> observationExpressionOr OR observationExpressionOr | observationExpressionAnd ; observationExpressionAnd : <assoc=left> observationExpressionAnd AND observationExpressionAnd | observationExpression ; observationExpression : LBRACK comparisonExpression RBRACK # observationExpressionSimple | LPAREN observationExpressions RPAREN # observationExpressionCompound | observationExpression startStopQualifier # observationExpressionStartStop | observationExpression withinQualifier # observationExpressionWithin | observationExpression repeatedQualifier # observationExpressionRepeated ; comparisonExpression : <assoc=left> comparisonExpression OR comparisonExpression | comparisonExpressionAnd ; comparisonExpressionAnd : <assoc=left> comparisonExpressionAnd AND comparisonExpressionAnd | propTest ; propTest : objectPath NOT? (EQ|NEQ) primitiveLiteral # propTestEqual | objectPath NOT? (GT|LT|GE|LE) orderableLiteral # propTestOrder | objectPath NOT? IN setLiteral # propTestSet | objectPath NOT? LIKE StringLiteral # propTestLike | objectPath NOT? MATCHES StringLiteral # propTestRegex | objectPath NOT? ISSUBSET StringLiteral # propTestIsSubset | objectPath NOT? ISSUPERSET StringLiteral # propTestIsSuperset | LPAREN comparisonExpression RPAREN # propTestParen ; startStopQualifier : START TimestampLiteral STOP TimestampLiteral ; withinQualifier : WITHIN (IntPosLiteral|FloatPosLiteral) SECONDS ; repeatedQualifier : REPEATS IntPosLiteral TIMES ; objectPath : objectType COLON firstPathComponent objectPathComponent? ; objectType : IdentifierWithoutHyphen | IdentifierWithHyphen ; firstPathComponent : IdentifierWithoutHyphen | StringLiteral ; objectPathComponent : <assoc=left> objectPathComponent objectPathComponent # pathStep | '.' (IdentifierWithoutHyphen | StringLiteral) # keyPathStep | LBRACK (IntPosLiteral|IntNegLiteral|ASTERISK) RBRACK # indexPathStep ; setLiteral : LPAREN RPAREN | LPAREN primitiveLiteral (COMMA primitiveLiteral)* RPAREN ; primitiveLiteral : orderableLiteral | BoolLiteral ; orderableLiteral : IntPosLiteral | IntNegLiteral | FloatPosLiteral | FloatNegLiteral | StringLiteral | BinaryLiteral | HexLiteral | TimestampLiteral ; IntNegLiteral : '-' ('0' | [1-9] [0-9]*) ; IntPosLiteral : '+'? ('0' | [1-9] [0-9]*) ; FloatNegLiteral : '-' [0-9]* '.' [0-9]+ ; FloatPosLiteral : '+'? [0-9]* '.' [0-9]+ ; HexLiteral : 'h' QUOTE TwoHexDigits* QUOTE ; BinaryLiteral : 'b' QUOTE ( Base64Char Base64Char Base64Char Base64Char )* ( (Base64Char Base64Char Base64Char Base64Char ) | (Base64Char Base64Char Base64Char ) '=' | (Base64Char Base64Char ) '==' ) QUOTE ; StringLiteral : QUOTE ( ~['\\] | '\\\'' | '\\\\' )* QUOTE ; BoolLiteral : TRUE | FALSE ; TimestampLiteral : 't' QUOTE [0-9] [0-9] [0-9] [0-9] HYPHEN ( ('0' [1-9]) | ('1' [012]) ) HYPHEN ( ('0' [1-9]) | ([12] [0-9]) | ('3' [01]) ) 'T' ( ([01] [0-9]) | ('2' [0-3]) ) COLON [0-5] [0-9] COLON ([0-5] [0-9] | '60') (DOT [0-9]+)? 'Z' QUOTE ; ////////////////////////////////////////////// // Keywords AND: 'AND' ; OR: 'OR' ; NOT: 'NOT' ; FOLLOWEDBY: 'FOLLOWEDBY'; LIKE: 'LIKE' ; MATCHES: 'MATCHES' ; ISSUPERSET: 'ISSUPERSET' ; ISSUBSET: 'ISSUBSET' ; LAST: 'LAST' ; IN: 'IN' ; START: 'START' ; STOP: 'STOP' ; SECONDS: 'SECONDS' ; TRUE: 'true' ; FALSE: 'false' ; WITHIN: 'WITHIN' ; REPEATS: 'REPEATS' ; TIMES: 'TIMES' ; // After keywords, so the lexer doesn't tokenize them as identifiers. // Object types may have unquoted hyphens, but property names // (in object paths) cannot. IdentifierWithoutHyphen : [a-zA-Z_] [a-zA-Z0-9_]* ; IdentifierWithHyphen : [a-zA-Z_] [a-zA-Z0-9_-]* ; EQ : '=' | '=='; NEQ : '!=' | '<>'; LT : '<'; LE : '<='; GT : '>'; GE : '>='; QUOTE : '\''; COLON : ':' ; DOT : '.' ; COMMA : ',' ; RPAREN : ')' ; LPAREN : '(' ; RBRACK : ']' ; LBRACK : '[' ; PLUS : '+' ; HYPHEN : MINUS ; MINUS : '-' ; POWER_OP : '^' ; DIVIDE : '/' ; ASTERISK : '*'; fragment HexDigit: [A-Fa-f0-9]; fragment TwoHexDigits: HexDigit HexDigit; fragment Base64Char: [A-Za-z0-9+/]; // Whitespace and comments // WS : [ \t\r\n\u000B\u000C\u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+ -> skip ; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '//' ~[\r\n]* -> skip ; // Catch-all to prevent lexer from silently eating unusable characters. InvalidCharacter : . ;
// This is an ANTLR4 grammar for the STIX Patterning Language. // // http://docs.oasis-open.org/cti/stix/v2.0/stix-v2.0-part5-stix-patterning.html grammar STIXPattern; pattern : observationExpressions EOF ; observationExpressions : <assoc=left> observationExpressions FOLLOWEDBY observationExpressions | observationExpressionOr ; observationExpressionOr : <assoc=left> observationExpressionOr OR observationExpressionOr | observationExpressionAnd ; observationExpressionAnd : <assoc=left> observationExpressionAnd AND observationExpressionAnd | observationExpression ; observationExpression : LBRACK comparisonExpression RBRACK # observationExpressionSimple | LPAREN observationExpressions RPAREN # observationExpressionCompound | observationExpression startStopQualifier # observationExpressionStartStop | observationExpression withinQualifier # observationExpressionWithin | observationExpression repeatedQualifier # observationExpressionRepeated ; comparisonExpression : <assoc=left> comparisonExpression OR comparisonExpression | comparisonExpressionAnd ; comparisonExpressionAnd : <assoc=left> comparisonExpressionAnd AND comparisonExpressionAnd | propTest ; propTest : objectPath NOT? (EQ|NEQ) primitiveLiteral # propTestEqual | objectPath NOT? (GT|LT|GE|LE) orderableLiteral # propTestOrder | objectPath NOT? IN setLiteral # propTestSet | objectPath NOT? LIKE StringLiteral # propTestLike | objectPath NOT? MATCHES StringLiteral # propTestRegex | objectPath NOT? ISSUBSET StringLiteral # propTestIsSubset | objectPath NOT? ISSUPERSET StringLiteral # propTestIsSuperset | LPAREN comparisonExpression RPAREN # propTestParen | EXISTS objectPath # propTestExists ; startStopQualifier : START TimestampLiteral STOP TimestampLiteral ; withinQualifier : WITHIN (IntPosLiteral|FloatPosLiteral) SECONDS ; repeatedQualifier : REPEATS IntPosLiteral TIMES ; objectPath : objectType COLON firstPathComponent objectPathComponent? ; objectType : IdentifierWithoutHyphen | IdentifierWithHyphen ; firstPathComponent : IdentifierWithoutHyphen | StringLiteral ; objectPathComponent : <assoc=left> objectPathComponent objectPathComponent # pathStep | '.' (IdentifierWithoutHyphen | StringLiteral) # keyPathStep | LBRACK (IntPosLiteral|IntNegLiteral|ASTERISK) RBRACK # indexPathStep ; setLiteral : LPAREN RPAREN | LPAREN primitiveLiteral (COMMA primitiveLiteral)* RPAREN ; primitiveLiteral : orderableLiteral | BoolLiteral ; orderableLiteral : IntPosLiteral | IntNegLiteral | FloatPosLiteral | FloatNegLiteral | StringLiteral | BinaryLiteral | HexLiteral | TimestampLiteral ; IntNegLiteral : '-' ('0' | [1-9] [0-9]*) ; IntPosLiteral : '+'? ('0' | [1-9] [0-9]*) ; FloatNegLiteral : '-' [0-9]* '.' [0-9]+ ; FloatPosLiteral : '+'? [0-9]* '.' [0-9]+ ; HexLiteral : 'h' QUOTE TwoHexDigits* QUOTE ; BinaryLiteral : 'b' QUOTE ( Base64Char Base64Char Base64Char Base64Char )* ( (Base64Char Base64Char Base64Char Base64Char ) | (Base64Char Base64Char Base64Char ) '=' | (Base64Char Base64Char ) '==' ) QUOTE ; StringLiteral : QUOTE ( ~['\\] | '\\\'' | '\\\\' )* QUOTE ; BoolLiteral : TRUE | FALSE ; TimestampLiteral : 't' QUOTE [0-9] [0-9] [0-9] [0-9] HYPHEN ( ('0' [1-9]) | ('1' [012]) ) HYPHEN ( ('0' [1-9]) | ([12] [0-9]) | ('3' [01]) ) 'T' ( ([01] [0-9]) | ('2' [0-3]) ) COLON [0-5] [0-9] COLON ([0-5] [0-9] | '60') (DOT [0-9]+)? 'Z' QUOTE ; ////////////////////////////////////////////// // Keywords AND: 'AND' ; OR: 'OR' ; NOT: 'NOT' ; FOLLOWEDBY: 'FOLLOWEDBY'; LIKE: 'LIKE' ; MATCHES: 'MATCHES' ; ISSUPERSET: 'ISSUPERSET' ; ISSUBSET: 'ISSUBSET' ; EXISTS: 'EXISTS' ; LAST: 'LAST' ; IN: 'IN' ; START: 'START' ; STOP: 'STOP' ; SECONDS: 'SECONDS' ; TRUE: 'true' ; FALSE: 'false' ; WITHIN: 'WITHIN' ; REPEATS: 'REPEATS' ; TIMES: 'TIMES' ; // After keywords, so the lexer doesn't tokenize them as identifiers. // Object types may have unquoted hyphens, but property names // (in object paths) cannot. IdentifierWithoutHyphen : [a-zA-Z_] [a-zA-Z0-9_]* ; IdentifierWithHyphen : [a-zA-Z_] [a-zA-Z0-9_-]* ; EQ : '=' | '=='; NEQ : '!=' | '<>'; LT : '<'; LE : '<='; GT : '>'; GE : '>='; QUOTE : '\''; COLON : ':' ; DOT : '.' ; COMMA : ',' ; RPAREN : ')' ; LPAREN : '(' ; RBRACK : ']' ; LBRACK : '[' ; PLUS : '+' ; HYPHEN : MINUS ; MINUS : '-' ; POWER_OP : '^' ; DIVIDE : '/' ; ASTERISK : '*'; fragment HexDigit: [A-Fa-f0-9]; fragment TwoHexDigits: HexDigit HexDigit; fragment Base64Char: [A-Za-z0-9+/]; // Whitespace and comments // WS : [ \t\r\n\u000B\u000C\u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+ -> skip ; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '//' ~[\r\n]* -> skip ; // Catch-all to prevent lexer from silently eating unusable characters. InvalidCharacter : . ;
Add EXISTS operator
Add EXISTS operator
ANTLR
bsd-3-clause
oasis-open/cti-stix2-json-schemas
3ccc3d7d81ac8620cf02d77dae018271616196e8
python3-cs/Python3Parser.g4
python3-cs/Python3Parser.g4
/* * The MIT License (MIT) * * Copyright (c) 2014 by Bart Kiers * * 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. * * Project : python3-parser; an ANTLR4 grammar for Python 3 * https://github.com/bkiers/python3-parser * Developed by : Bart Kiers, [email protected] */ parser grammar Python3Parser; options { tokenVocab=Python3Lexer; } 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; decorators: decorator+; decorated: decorators (classdef | funcdef | async_funcdef); async_funcdef: ASYNC funcdef; funcdef: DEF NAME parameters (ARROW test)? COLON suite; parameters: OPEN_PAREN (typedargslist)? CLOSE_PAREN; typedargslist: (tfpdef (ASSIGN test)? (COMMA tfpdef (ASSIGN test)?)* (COMMA ( '*' (tfpdef)? (',' tfpdef ('=' test)?)* (',' ('**' tfpdef (',')?)?)? | '**' tfpdef (',')?)?)? | '*' (tfpdef)? (',' tfpdef ('=' test)?)* (',' ('**' tfpdef (',')?)?)? | '**' tfpdef (',')?); tfpdef: NAME (':' test)?; varargslist: (vfpdef ('=' test)? (',' vfpdef ('=' test)?)* (',' ( '*' (vfpdef)? (',' vfpdef ('=' test)?)* (',' ('**' vfpdef (',')?)?)? | '**' vfpdef (',')?)?)? | '*' (vfpdef)? (',' vfpdef ('=' test)?)* (',' ('**' vfpdef (',')?)?)? | '**' vfpdef (',')? ); vfpdef: NAME; stmt: simple_stmt | compound_stmt; simple_stmt: small_stmt (';' small_stmt)* (';')? NEWLINE; small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | nonlocal_stmt | assert_stmt); expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) | ('=' (yield_expr|testlist_star_expr))*); annassign: ':' test ('=' test)?; testlist_star_expr: (test|star_expr) (',' (test|star_expr))* (',')?; augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '**=' | '//='); // For normal and annotated assignments, additional restrictions enforced by the interpreter 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 ('from' test)?)?; import_stmt: import_name | import_from; import_name: 'import' dotted_as_names; // note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS import_from: ('from' (('.' | '...')* dotted_name | ('.' | '...')+) 'import' ('*' | '(' import_as_names ')' | import_as_names)); import_as_name: NAME ('as' NAME)?; dotted_as_name: dotted_name ('as' NAME)?; import_as_names: import_as_name (',' import_as_name)* (',')?; dotted_as_names: dotted_as_name (',' dotted_as_name)*; dotted_name: NAME ('.' NAME)*; global_stmt: 'global' NAME (',' NAME)*; nonlocal_stmt: 'nonlocal' NAME (',' NAME)*; assert_stmt: 'assert' test (',' 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 ':' suite ('elif' test ':' suite)* ('else' ':' suite)?; while_stmt: 'while' test ':' suite ('else' ':' suite)?; for_stmt: 'for' exprlist 'in' testlist ':' suite ('else' ':' suite)?; try_stmt: ('try' ':' suite ((except_clause ':' suite)+ ('else' ':' suite)? ('finally' ':' suite)? | 'finally' ':' suite)); with_stmt: 'with' with_item (',' with_item)* ':' suite; with_item: test ('as' expr)?; // NB compile.c makes sure that the default except clause is last except_clause: 'except' (test ('as' NAME)?)?; suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT; test: or_test ('if' or_test 'else' test)? | lambdef; test_nocond: or_test | lambdef_nocond; lambdef: 'lambda' (varargslist)? ':' test; lambdef_nocond: 'lambda' (varargslist)? ':' test_nocond; or_test: and_test ('or' and_test)*; and_test: not_test ('and' not_test)*; not_test: 'not' not_test | comparison; comparison: expr (comp_op expr)*; // <> 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 :-) comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'; star_expr: '*' expr; expr: xor_expr ('|' xor_expr)*; xor_expr: and_expr ('^' and_expr)*; and_expr: shift_expr ('&' shift_expr)*; shift_expr: arith_expr (('<<'|'>>') arith_expr)*; arith_expr: term (('+'|'-') term)*; term: factor (('*'|'@'|'/'|'%'|'//') factor)*; factor: ('+'|'-'|'~') factor | power; power: atom_expr ('**' factor)?; atom_expr: (AWAIT)? atom trailer*; atom: ('(' (yield_expr|testlist_comp)? ')' | '[' (testlist_comp)? ']' | '{' (dictorsetmaker)? '}' | NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False'); testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* (',')? ); trailer: '(' (arglist)? ')' | '[' subscriptlist ']' | '.' NAME; subscriptlist: subscript (',' subscript)* (',')?; subscript: test | (test)? ':' (test)? (sliceop)?; sliceop: ':' (test)?; exprlist: (expr|star_expr) (',' (expr|star_expr))* (',')?; testlist: test (',' test)* (',')?; dictorsetmaker: ( ((test ':' test | '**' expr) (comp_for | (',' (test ':' test | '**' expr))* (',')?)) | ((test | star_expr) (comp_for | (',' (test | star_expr))* (',')?)) ); classdef: 'class' NAME ('(' (arglist)? ')')? ':' suite; arglist: argument (',' argument)* (',')?; // 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. // "test '=' test" is really "keyword '=' test", but we have no such token. // These need to be in a single rule to avoid grammar that is ambiguous // to our LL(1) parser. Even though 'test' includes '*expr' in star_expr, // we explicitly match '*' here, too, to give it proper precedence. // Illegal combinations and orderings are blocked in ast.c: // multiple (test comp_for) arguments are blocked; keyword unpackings // that precede iterable unpackings are blocked; etc. argument: ( test (comp_for)? | test '=' test | '**' test | '*' test ); comp_iter: comp_for | comp_if; comp_for: (ASYNC)? 'for' exprlist 'in' or_test (comp_iter)?; comp_if: 'if' test_nocond (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;
/* * The MIT License (MIT) * * Copyright (c) 2014 by Bart Kiers * * 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. * * Project : python3-parser; an ANTLR4 grammar for Python 3 * https://github.com/bkiers/python3-parser * Developed by : Bart Kiers, [email protected] */ parser grammar Python3Parser; options { tokenVocab=Python3Lexer; } 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; decorators: decorator+; decorated: decorators (classdef | funcdef | async_funcdef); async_funcdef: ASYNC funcdef; funcdef: DEF NAME parameters (ARROW test)? COLON suite; parameters: OPEN_PAREN (typedargslist)? CLOSE_PAREN; typedargslist: (tfpdef (ASSIGN test)? (COMMA tfpdef (ASSIGN test)?)* (COMMA ( STAR (tfpdef)? (COMMA tfpdef (ASSIGN test)?)* (COMMA (POWER tfpdef (COMMA)?)?)? | POWER tfpdef (COMMA)?)?)? | STAR (tfpdef)? (COMMA tfpdef (ASSIGN test)?)* (COMMA (POWER tfpdef (COMMA)?)?)? | POWER tfpdef (COMMA)?); tfpdef: NAME (COLON test)?; varargslist: (vfpdef (ASSIGN test)? (COMMA vfpdef (ASSIGN test)?)* (COMMA ( STAR (vfpdef)? (COMMA vfpdef (ASSIGN test)?)* (COMMA (POWER vfpdef (COMMA)?)?)? | POWER vfpdef (COMMA)?)?)? | STAR (vfpdef)? (COMMA vfpdef (ASSIGN test)?)* (COMMA (POWER vfpdef (COMMA)?)?)? | POWER vfpdef (COMMA)? ); vfpdef: NAME; stmt: simple_stmt | compound_stmt; simple_stmt: small_stmt (SEMI_COLON small_stmt)* (SEMI_COLON)? NEWLINE; small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | nonlocal_stmt | assert_stmt); expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) | (ASSIGN (yield_expr|testlist_star_expr))*); annassign: COLON test (ASSIGN test)?; testlist_star_expr: (test|star_expr) (COMMA (test|star_expr))* (COMMA)?; augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '**=' | '//='); // For normal and annotated assignments, additional restrictions enforced by the interpreter 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 (FROM test)?)?; import_stmt: import_name | import_from; import_name: IMPORT dotted_as_names; // note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS 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: NAME ('.' NAME)*; global_stmt: GLOBAL NAME (COMMA NAME)*; nonlocal_stmt: NONLOCAL NAME (COMMA NAME)*; 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 test COLON suite)* (ELSE COLON suite)?; while_stmt: WHILE test COLON suite (ELSE COLON suite)?; for_stmt: FOR exprlist IN testlist COLON suite (ELSE COLON suite)?; try_stmt: (TRY COLON suite ((except_clause COLON suite)+ (ELSE COLON suite)? (FINALLY COLON suite)? | FINALLY COLON suite)); with_stmt: WITH with_item (COMMA with_item)* COLON suite; with_item: test (AS expr)?; // NB compile.c makes sure that the default except clause is last except_clause: EXCEPT (test (AS NAME)?)?; suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT; test: or_test (IF or_test ELSE test)? | lambdef; test_nocond: or_test | lambdef_nocond; lambdef: LAMBDA (varargslist)? COLON test; lambdef_nocond: LAMBDA (varargslist)? COLON test_nocond; or_test: and_test (OR and_test)*; and_test: not_test (AND not_test)*; not_test: NOT not_test | comparison; comparison: expr (comp_op expr)*; // <> 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 :-) comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|IN|NOT IN|IS|IS NOT; star_expr: STAR expr; expr: xor_expr (OR_OP xor_expr)*; xor_expr: and_expr ('^' and_expr)*; and_expr: shift_expr ('&' shift_expr)*; shift_expr: arith_expr (('<<'|'>>') arith_expr)*; arith_expr: term (('+'|'-') term)*; term: factor ((STAR|'@'|'/'|'%'|'//') factor)*; factor: ('+'|'-'|'~') factor | power; power: atom_expr (POWER factor)?; atom_expr: (AWAIT)? atom trailer*; atom: (OPEN_PAREN (yield_expr|testlist_comp)? CLOSE_PAREN | OPEN_BRACK (testlist_comp)? CLOSE_BRACK | OPEN_BRACE (dictorsetmaker)? CLOSE_BRACE | NAME | NUMBER | STRING+ | ELLIPSIS | NONE | TRUE | FALSE); testlist_comp: (test|star_expr) ( comp_for | (COMMA (test|star_expr))* (COMMA)? ); trailer: OPEN_PAREN (arglist)? CLOSE_PAREN | OPEN_BRACK subscriptlist CLOSE_BRACK | '.' NAME; subscriptlist: subscript (COMMA subscript)* (COMMA)?; subscript: test | (test)? COLON (test)? (sliceop)?; sliceop: COLON (test)?; exprlist: (expr|star_expr) (COMMA (expr|star_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: argument (COMMA argument)* (COMMA)?; // 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. // "test ASSIGN test" is really "keyword ASSIGN test", but we have no such token. // These need to be in a single rule to avoid grammar that is ambiguous // to our LL(1) parser. Even though 'test' includes '*expr' in star_expr, // we explicitly match STAR here, too, to give it proper precedence. // Illegal combinations and orderings are blocked in ast.c: // multiple (test comp_for) arguments are blocked; keyword unpackings // that precede iterable unpackings are blocked; etc. argument: ( test (comp_for)? | test ASSIGN test | POWER test | STAR test ); comp_iter: comp_for | comp_if; comp_for: (ASYNC)? FOR exprlist IN or_test (comp_iter)?; comp_if: IF test_nocond (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;
replace token literals with token keywords from lexer rules
replace token literals with token keywords from lexer rules
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
7b3778a11694aa2c22956127328c86205f6fd1bd
json/JSON.g4
json/JSON.g4
/** Taken from "The Definitive ANTLR 4 Reference" by Terence Parr */ // Derived from http://json.org grammar JSON; json : value ; object : '{' pair (',' pair)* '}' | '{' '}' ; pair : STRING ':' value ; array : '[' value (',' value)* ']' | '[' ']' ; value : STRING | NUMBER | object | 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 ;
/** Taken from "The Definitive ANTLR 4 Reference" by Terence Parr */ // Derived from http://json.org grammar JSON; json : 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 ;
Make JSON grammar Python compatible.
Make JSON grammar Python compatible. The 'object' parser rule was renamed to 'obj' to avoid symbol conflict with Python's builtin object.
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
5fbbec3b37d77abcefd89ab1750003158eceee24
turin-parser/src/main/antlr4/me/tomassetti/parser/antlr/TurinParser.g4
turin-parser/src/main/antlr4/me/tomassetti/parser/antlr/TurinParser.g4
parser grammar TurinParser; options { tokenVocab = TurinLexer; } @header { } turinFile: namespace=namespaceDecl nls (imports+=importDeclaration)* (members+=fileMember)* EOF; // Base nls: NL+; qualifiedId: (parts+=VALUE_ID POINT)* parts+=VALUE_ID; // Namespace namespaceDecl: NAMESPACE_KW name=qualifiedId; // Imports importDeclaration: typeImportDeclaration | singleFieldImportDeclaration | allFieldsImportDeclaration | allPackageImportDeclaration; typeImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TYPE_ID (AS_KW alternativeName=TYPE_ID)? nls ; singleFieldImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TYPE_ID POINT fieldName=qualifiedId (AS_KW alternativeName=VALUE_ID)? nls; allFieldsImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TYPE_ID POINT ASTERISK nls; allPackageImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT ASTERISK nls; // typeUsage: ref=TYPE_ID | arrayBase=typeUsage LSQUARE RSQUARE | primitiveType = PRIMITIVE_TYPE | basicType = BASIC_TYPE; // we permit to insert a newline after the comma to break long lists commaNl: COMMA NL?; // method definition methodDefinition: type=returnType name=VALUE_ID LPAREN (params+=formalParam (commaNl params+=formalParam)*)? RPAREN methodBody; returnType: isVoid=VOID_KW | type=typeUsage; methodBody: ASSIGNMENT value=expression nls | LBRACKET nls (statements += statement)* RBRACKET nls; // topLevelPropertyDeclaration: PROPERTY_KW (type=typeUsage)? name=VALUE_ID (DEFAULT_KW defaultValue=expression |ASSIGNMENT initialValue=expression)? (NL? COLON constraint+=constraintDeclaration (commaNl constraint+=constraintDeclaration)*)? nls; topLevelFunctionDeclaration: type=returnType name=VALUE_ID LPAREN (params+=formalParam (commaNl params+=formalParam)*)? RPAREN methodBody; constraintDeclaration: condition=expression (LPAREN message=expression RPAREN)?; inTypePropertyDeclaration: (type=typeUsage)? name=VALUE_ID (DEFAULT_KW defaultValue=expression |ASSIGNMENT initialValue=expression)? (NL? COLON constraint+=constraintDeclaration (commaNl constraint+=constraintDeclaration)*)? nls; propertyReference: HAS_KW name=VALUE_ID nls; typeMember: inTypePropertyDeclaration | propertyReference | methodDefinition; typeDeclaration: TYPE_KW name=TYPE_ID LBRACKET nls (typeMembers += typeMember)* RBRACKET nls; // actualParam: expression | name=VALUE_ID ASSIGNMENT expression; parenExpression: LPAREN internal=expression RPAREN; placeholderUsage: PLACEHOLDER; placeholderNameUsage: PLACEHOLDER_NAME; basicExpression: booleanLiteral | stringLiteral | intLiteral | interpolatedStringLiteral | valueReference | parenExpression | staticFieldReference | placeholderUsage | placeholderNameUsage; booleanLiteral: negative=FALSE_KW | positive=TRUE_KW; expression: creation | basicExpression | container=expression POINT methodName=VALUE_ID LPAREN (params+=actualParam (commaNl params+=actualParam)*)? RPAREN | container=expression POINT fieldName=VALUE_ID | array=expression LSQUARE index=expression RSQUARE | function=expression LPAREN (params+=actualParam (commaNl params+=actualParam)*)? RPAREN | left=expression mathOperator=ASTERISK right=expression | left=expression mathOperator=SLASH right=expression | left=expression mathOperator=PLUS right=expression | left=expression mathOperator=MINUS right=expression | left=expression logicOperator=AND_KW right=expression | left=expression logicOperator=OR_KW right=expression | left=expression relOp=RELOP right=expression | not=NOT_KW value=expression ; fieldAccess: subject=basicExpression POINT name=VALUE_ID; staticFieldReference: typeReference POINT name=VALUE_ID; valueReference: name=VALUE_ID; typeReference: (packag=qualifiedId POINT)? name=TYPE_ID; stringLiteral: STRING_START (content=STRING_CONTENT)? STRING_STOP; interpolatedStringLiteral: STRING_START (elements+=stringElement)+ STRING_STOP; stringElement: STRING_CONTENT | stringInterpolationElement; stringInterpolationElement: INTERPOLATION_START value=expression INTERPOLATION_END; intLiteral: INT; creation: (pakage=qualifiedId POINT)? name=TYPE_ID LPAREN (params+=actualParam (commaNl params+=actualParam)*)? RPAREN ; varDecl: VAL_KW (type=typeUsage)? name=VALUE_ID ASSIGNMENT value=expression nls; expressionStmt: expression nls; returnStmt: RETURN_KW value=expression nls; elifStmt: ELIF_KW condition=expression LBRACKET nls (body+=statement)* RBRACKET; ifStmt: IF_KW condition=expression LBRACKET nls (ifBody+=statement)* RBRACKET (elifs+=elifStmt)* (ELSE_KW LBRACKET nls (elseBody+=statement)* RBRACKET)? nls; throwStmt: THROW_KW exc=expression nls; catchClause: CATCH_KW type=typeReference varName=VALUE_ID LBRACKET nls (body+=statement)*; tryCatchStmt: TRY_KW LBRACKET nls (body+=statement)* (RBRACKET catches+=catchClause)+ RBRACKET nls; statement: varDecl | expressionStmt | returnStmt | ifStmt | throwStmt | tryCatchStmt; // formalParam: type=typeUsage name=VALUE_ID; // program: PROGRAM_KW name=TYPE_ID LPAREN params+=formalParam (commaNl params+=formalParam)* RPAREN LBRACKET nls (statements += statement)* RBRACKET nls; // fileMember: topLevelPropertyDeclaration | topLevelFunctionDeclaration | typeDeclaration | program;
parser grammar TurinParser; options { tokenVocab = TurinLexer; } @header { } turinFile: namespace=namespaceDecl nls (imports+=importDeclaration)* (members+=fileMember)* EOF; // Base nls: NL+; qualifiedId: (parts+=VALUE_ID POINT)* parts+=VALUE_ID; // Namespace namespaceDecl: NAMESPACE_KW name=qualifiedId; // Imports importDeclaration: typeImportDeclaration | singleFieldImportDeclaration | allFieldsImportDeclaration | allPackageImportDeclaration; typeImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TYPE_ID (AS_KW alternativeName=TYPE_ID)? nls ; singleFieldImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TYPE_ID POINT fieldName=qualifiedId (AS_KW alternativeName=VALUE_ID)? nls; allFieldsImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TYPE_ID POINT ASTERISK nls; allPackageImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT ASTERISK nls; // typeUsage: ref=TYPE_ID | arrayBase=typeUsage LSQUARE RSQUARE | primitiveType = PRIMITIVE_TYPE | basicType = BASIC_TYPE; // we permit to insert a newline after the comma to break long lists commaNl: COMMA NL?; // method definition methodDefinition: type=returnType name=VALUE_ID LPAREN (params+=formalParam (commaNl params+=formalParam)*)? RPAREN methodBody; returnType: isVoid=VOID_KW | type=typeUsage; methodBody: ASSIGNMENT value=expression nls | LBRACKET nls (statements += statement)* RBRACKET nls; // topLevelPropertyDeclaration: PROPERTY_KW (type=typeUsage)? name=VALUE_ID (DEFAULT_KW defaultValue=expression |ASSIGNMENT initialValue=expression)? (NL? COLON constraint+=constraintDeclaration (commaNl constraint+=constraintDeclaration)*)? nls; topLevelFunctionDeclaration: type=returnType name=VALUE_ID LPAREN (params+=formalParam (commaNl params+=formalParam)*)? RPAREN methodBody; constraintDeclaration: condition=expression (LPAREN message=expression RPAREN)?; inTypePropertyDeclaration: (type=typeUsage)? name=VALUE_ID (DEFAULT_KW defaultValue=expression |ASSIGNMENT initialValue=expression)? (NL? COLON constraint+=constraintDeclaration (commaNl constraint+=constraintDeclaration)*)? nls; propertyReference: HAS_KW name=VALUE_ID nls; typeMember: inTypePropertyDeclaration | propertyReference | methodDefinition; typeDeclaration: TYPE_KW name=TYPE_ID LBRACKET nls (typeMembers += typeMember)* RBRACKET nls; // actualParam: expression | name=VALUE_ID ASSIGNMENT expression | asterisk=ASTERISK ASSIGNMENT expression; parenExpression: LPAREN internal=expression RPAREN; placeholderUsage: PLACEHOLDER; placeholderNameUsage: PLACEHOLDER_NAME; basicExpression: booleanLiteral | stringLiteral | intLiteral | interpolatedStringLiteral | valueReference | parenExpression | staticFieldReference | placeholderUsage | placeholderNameUsage; booleanLiteral: negative=FALSE_KW | positive=TRUE_KW; expression: creation | basicExpression | container=expression POINT methodName=VALUE_ID LPAREN (params+=actualParam (commaNl params+=actualParam)*)? RPAREN | container=expression POINT fieldName=VALUE_ID | array=expression LSQUARE index=expression RSQUARE | function=expression LPAREN (params+=actualParam (commaNl params+=actualParam)*)? RPAREN | left=expression mathOperator=ASTERISK right=expression | left=expression mathOperator=SLASH right=expression | left=expression mathOperator=PLUS right=expression | left=expression mathOperator=MINUS right=expression | left=expression logicOperator=AND_KW right=expression | left=expression logicOperator=OR_KW right=expression | left=expression relOp=RELOP right=expression | not=NOT_KW value=expression ; fieldAccess: subject=basicExpression POINT name=VALUE_ID; staticFieldReference: typeReference POINT name=VALUE_ID; valueReference: name=VALUE_ID; typeReference: (packag=qualifiedId POINT)? name=TYPE_ID; stringLiteral: STRING_START (content=STRING_CONTENT)? STRING_STOP; interpolatedStringLiteral: STRING_START (elements+=stringElement)+ STRING_STOP; stringElement: STRING_CONTENT | stringInterpolationElement; stringInterpolationElement: INTERPOLATION_START value=expression INTERPOLATION_END; intLiteral: INT; creation: (pakage=qualifiedId POINT)? name=TYPE_ID LPAREN (params+=actualParam (commaNl params+=actualParam)*)? RPAREN ; varDecl: VAL_KW (type=typeUsage)? name=VALUE_ID ASSIGNMENT value=expression nls; expressionStmt: expression nls; returnStmt: RETURN_KW value=expression nls; elifStmt: ELIF_KW condition=expression LBRACKET nls (body+=statement)* RBRACKET; ifStmt: IF_KW condition=expression LBRACKET nls (ifBody+=statement)* RBRACKET (elifs+=elifStmt)* (ELSE_KW LBRACKET nls (elseBody+=statement)* RBRACKET)? nls; throwStmt: THROW_KW exc=expression nls; catchClause: CATCH_KW type=typeReference varName=VALUE_ID LBRACKET nls (body+=statement)*; tryCatchStmt: TRY_KW LBRACKET nls (body+=statement)* (RBRACKET catches+=catchClause)+ RBRACKET nls; statement: varDecl | expressionStmt | returnStmt | ifStmt | throwStmt | tryCatchStmt; // formalParam: type=typeUsage name=VALUE_ID; // program: PROGRAM_KW name=TYPE_ID LPAREN params+=formalParam (commaNl params+=formalParam)* RPAREN LBRACKET nls (statements += statement)* RBRACKET nls; // fileMember: topLevelPropertyDeclaration | topLevelFunctionDeclaration | typeDeclaration | program;
add the asterisk param
add the asterisk param
ANTLR
apache-2.0
ftomassetti/turin-programming-language,ftomassetti/turin-programming-language
a08198444720e6127c50100c52587c4cba08fb32
MATLAB.g4
MATLAB.g4
grammar MATLAB; fileDecl : (functionDecl | classDecl)? (functionDecl* | partialFunctionDecl*) | partialFunctionDecl* | stat* // Script ; endStat : (NL|COMMA|SEMI) ; endStatNL : NL ; // Function declaration without the closing end partialFunctionDecl : 'function' outArgs? ID inArgs? endStat (stat endStat NL*)* ; // Normal function declaration including closing end functionDecl : partialFunctionDecl 'end' endStatNL NL* ; // Functions inside method blocks can be comma or semi separated methodDecl : partialFunctionDecl 'end' endStat NL* ; classDecl : 'classdef' ID endStat NL* (propBlockDecl|methodBlockDecl)* 'end' (EOF|endStat) NL* ; propBlockDecl : 'properties' endStat NL* prop* 'end' endStat NL* ; methodBlockDecl : 'methods' endStat NL* methodDecl* 'end' endStat NL* ; outArgs : ID '=' | '[' ID (',' ID)* ']' '=' ; inArgs : '(' ID (',' ID)* ')' | '(' ')' ; prop : ID ('=' expr)? endStat ; dotRef : ID ('.' ID)* ; stat : dotRef '=' expr | 'if' expr endStat (stat endStat NL*)* ('elseif' expr endStat (stat endStat NL*)*)* ('else' endStat (stat endStat NL*)*)* 'end' | ID | NL ; expr : expr '==' expr | expr ('>'|'<'|'>='|'<=') expr | dotRef | NUMBER ; fragment DIGIT : [0-9] ; NL : '\r'?'\n' ; WS : [ \t]+ -> skip ; COMMA : ',' ; SEMI : ';' ; fragment LETTER : [a-zA-Z] ; ID : LETTER (LETTER|DIGIT|'_')* ; NUMBER : DIGIT+ ;
grammar MATLAB; fileDecl : (functionDecl | classDecl)? (functionDecl* | partialFunctionDecl*) | partialFunctionDecl* | stat* // Script ; endStat : (NL|COMMA|SEMI) NL* ; endStatNL : NL+ ; // Function declaration without the closing end partialFunctionDecl : 'function' outArgs? ID inArgs? endStat (stat endStat)* ; // Normal function declaration including closing end functionDecl : partialFunctionDecl 'end' endStatNL NL* ; // Functions inside method blocks can be comma or semi separated methodDecl : partialFunctionDecl 'end' endStat ; classDecl : 'classdef' ID endStat (propBlockDecl|methodBlockDecl)* 'end' (EOF|endStat) NL* ; propBlockDecl : 'properties' endStat prop* 'end' endStat ; methodBlockDecl : 'methods' endStat methodDecl* 'end' endStat ; outArgs : ID '=' | '[' ID (',' ID)* ']' '=' ; inArgs : '(' ID (',' ID)* ')' | '(' ')' ; prop : ID ('=' expr)? endStat ; dotRef : ID ('.' ID)* ; stat : dotRef '=' expr | 'if' expr endStat (stat endStat)* ('elseif' expr endStat (stat endStat)*)* ('else' endStat (stat endStat)*)* 'end' | ID | NL ; expr : expr '==' expr | expr ('>'|'<'|'>='|'<=') expr | dotRef | NUMBER ; fragment DIGIT : [0-9] ; NL : '\r'?'\n' ; WS : [ \t]+ -> skip ; COMMA : ',' ; SEMI : ';' ; fragment LETTER : [a-zA-Z] ; ID : LETTER (LETTER|DIGIT|'_')* ; NUMBER : DIGIT+ ;
Refactor endStat rule to include NL*
Refactor endStat rule to include NL*
ANTLR
apache-2.0
mattmcd/ParseMATLAB,mattmcd/ParseMATLAB
87716fccfdbb1968c40cbaf4942bfcb9a294e648
watertemplate-engine/grammar.g4
watertemplate-engine/grammar.g4
prop_name_head : [a-zA-Z] ; prop_name_body_char : '_' | [0-9] | prop_name_head ; prop_name_body : prop_name_body_char | prop_name_body_char prop_name_body ; prop_name : prop_name_head | prop_name_head prop_name_body ; id : prop_name | prop_name '.' id ; // --------------------------------------------- prop_eval : '~' id '~' ; if : '~if' id ':' statements ':~' | '~if' id ':' statements ':else:' statements ':~' ; for : '~for' prop_name 'in' id ':' statements ':~' | '~for' prop_name 'in' id ':' statements ':else:' statements ':~' ; text : Any string ; // --------------------------------------------- statement : prop_eval | if | for | text | ε ; statements : statement | statement statements ;
prop_name_head : [a-zA-Z] ; prop_name_body_char : '_' | [0-9] | prop_name_head ; prop_name_body : prop_name_body_char | prop_name_body_char prop_name_body ; prop_name : prop_name_head | prop_name_head prop_name_body ; id : prop_name | prop_name '.' id ; // --------------------------------------------- id_eval : '~' id '~' ; if : '~if' id ':' statements ':~' | '~if' id ':' statements ':else:' statements ':~' ; for : '~for' prop_name 'in' id ':' statements ':~' | '~for' prop_name 'in' id ':' statements ':else:' statements ':~' ; text : Any string ; // --------------------------------------------- statement : id_eval | if | for | text | ε ; statements : statement | statement statements ;
Update grammar.g4
Update grammar.g4
ANTLR
apache-2.0
tiagobento/watertemplate-engine,codefacts/watertemplate-engine,codefacts/watertemplate-engine,tiagobento/watertemplate-engine
c5cf8570a2e80813f5b9089666279d217616fb8b
VineScript/Compiler/VineLexer.g4
VineScript/Compiler/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 '/* .. */' // Escaped commands, eg: \<< this is text >> TXT_ESC : ('\\\\' | '\\{' | '\\/' | '\\<' | '\\[') -> type(TXT) ; LOUTPUT: '{{' -> pushMode(VineCode) ; LSTMT: '<<' -> pushMode(VineCode) ; LLINK: '[[' -> pushMode(LinkMode) ; BLOCK_COMMENT: '/*' .*? '*/' ; LINE_COMMENT: '//' ~[\r\n]* ; 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 // * '\u001E': marks the start of the output of the display command // * '\u001F': marks the end of the output of the display command RESERVED_CHARS: [\u000B\u001E\u001F]+ ; TXT_SPECIALS : [\\/[<{] -> type(TXT) ; TXT : ~[\\<\[{/\r\n\u000B\u001E\u001F]+ ; ERROR_CHAR: . ; // ---------------------------------------------------------- mode LinkMode; LINK_ESC : ( '\\\\' // [[my \\ title|mylink]] | '\\]' // [[my [[own\]] title|mylink]] | '\\|' // [[my \| title|mylink]] | '\\<' // [[mylink<-my \<- title]] | '\\-' // [[my \-> title->mylink]] ) -> type(LINK_TEXT) ; RLINK: ']]' -> popMode ; LINK_PIPE: '|' ; LINK_LEFT: '<-' ; LINK_RIGHT: '->' ; LINK_TEXT_SPECIALS: [\\<\]-] -> type(LINK_TEXT) ; LINK_TEXT: ~[\\|<\]\r\n-]+ ; // ---------------------------------------------------------- mode VineCode; ROUTPUT: '}}' -> popMode ; RSTMT: '>>' -> popMode ; // Parentheses, square brackets, curly braces LPAREN: '(' ; RPAREN: ')' ; LBRACK: '[' ; RBRACK: ']' ; LBRACE: '{' ; RBRACE: '}' ; // Reserved keywords IF: 'if' ; ELIF: 'elif' ; ELSE: 'else' ; ENDIF: 'endif' ; FOR: 'for' ; IN: 'in' ; ENDFOR: 'endfor' ; KW_AND: 'and' ; KW_OR: 'or' ; TO: 'to' ; SET: 'set' ; UNSET: 'unset' ; // Separators INTERVAL_SEP: '...' ; DOT: '.' ; COMMA: ',' ; COLON: ':' ; // Assign ADDASSIGN: '+=' ; SUBASSIGN: '-=' ; MULASSIGN: '*=' ; DIVASSIGN: '/=' ; MODASSIGN: '%=' ; ASSIGN: '=' ; // Unary op MINUS: '-' ; NOT: '!' ; POW: '^' ; // right assoc // Arithmetic op MUL: '*' ; DIV: '/' ; ADD: '+' ; MOD: '%' ; // Equality op EQ: '==' ; NEQ: '!=' ; // Logical op AND: '&&' ; OR: '||' ; // Comparison op LT: '<' ; GT: '>' ; LTE: '<=' ; GTE: '>=' ; // TODO complete list. Commands are built-in functions COMMAND: 'array' | 'TODO' ; // Atoms TRUE: 'true' ; FALSE: 'false' ; NULL: 'null' ; STRING: '"' (ESC | ~('\u000B'))*? '"' ; // catches strings containing '\u000B': ILLEGAL_STRING: '"' (ESC | .)*? '"' ; //tokens { STRING } //DOUBLE : '"' .*? '"' -> type(STRING) ; //SINGLE : '\'' .*? '\'' -> type(STRING) ; //STRING_SQUOTE: '\'' (ESC_SQUOTE|.)*? '\'' ; //STRING_DQUOTE: '"' (ESC_DQUOTE|.)*? '"' ; // 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 // list : https://en.wikipedia.org/wiki/Whitespace_character //UNICODE_WS : [\p{White_Space}] -> skip; // match all Unicode whitespace WS: [ \t\f]+ -> channel(HIDDEN) ; 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+ ; 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 '/* .. */' // Escaped commands, eg: \<< this is text >> TXT_ESC : ('\\\\' | '\\{' | '\\/' | '\\<' | '\\[') -> type(TXT) ; LOUTPUT: '{{' -> pushMode(VineCode) ; LSTMT: '<<' -> pushMode(VineCode) ; LLINK: '[[' -> pushMode(LinkMode) ; BLOCK_COMMENT: '/*' .*? '*/' ; LINE_COMMENT: '//' ~[\r\n]* ; 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 // * '\u001E': marks the start of the output of the display command // * '\u001F': marks the end of the output of the display command RESERVED_CHARS: [\u000B\u001E\u001F]+ ; TXT_SPECIALS : [\\/[<{] -> type(TXT) ; TXT : ~[\\<\[{/\r\n\u000B\u001E\u001F]+ ; ERROR_CHAR: . ; // ---------------------------------------------------------- mode LinkMode; LINK_ESC : ( '\\\\' // [[my \\ title|mylink]] | '\\]' // [[my [[own\]] title|mylink]] | '\\|' // [[my \| title|mylink]] | '\\<' // [[mylink<-my \<- title]] | '\\-' // [[my \-> title->mylink]] ) -> type(LINK_TEXT) ; RLINK: ']]' -> popMode ; LINK_PIPE: '|' ; LINK_LEFT: '<-' ; LINK_RIGHT: '->' ; LINK_TEXT_SPECIALS: [\\<\]-] -> type(LINK_TEXT) ; LINK_TEXT: ~[\\|<\]\r\n-]+ ; // ---------------------------------------------------------- mode VineCode; ROUTPUT: '}}' -> popMode ; RSTMT: '>>' -> popMode ; // Parentheses, square brackets, curly braces LPAREN: '(' ; RPAREN: ')' ; LBRACK: '[' ; RBRACK: ']' ; LBRACE: '{' ; RBRACE: '}' ; // Reserved keywords IF: 'if' ; ELIF: 'elif' ; ELSE: 'else' ; ENDIF: 'endif' ; FOR: 'for' ; IN: 'in' ; ENDFOR: 'endfor' ; KW_AND: 'and' ; KW_OR: 'or' ; TO: 'to' ; SET: 'set' ; UNSET: 'unset' ; // Separators INTERVAL_SEP: '...' ; DOT: '.' ; COMMA: ',' ; COLON: ':' ; // Assign ADDASSIGN: '+=' ; SUBASSIGN: '-=' ; MULASSIGN: '*=' ; DIVASSIGN: '/=' ; MODASSIGN: '%=' ; ASSIGN: '=' ; // Unary op MINUS: '-' ; NOT: '!' ; POW: '^' ; // right assoc // Arithmetic op MUL: '*' ; DIV: '/' ; ADD: '+' ; MOD: '%' ; // Equality op EQ: '==' ; NEQ: '!=' ; // Logical op AND: '&&' ; OR: '||' ; // Comparison op LT: '<' ; GT: '>' ; LTE: '<=' ; GTE: '>=' ; // TODO complete list. Commands are built-in functions COMMAND: 'array' | 'TODO' ; // Atoms TRUE: 'true' ; FALSE: 'false' ; NULL: 'null' ; STRING: '"' (ESC | ~('\u000B'))*? '"' ; // catches strings containing '\u000B': ILLEGAL_STRING: '"' (ESC | .)*? '"' ; //tokens { STRING } //DOUBLE : '"' .*? '"' -> type(STRING) ; //SINGLE : '\'' .*? '\'' -> type(STRING) ; //STRING_SQUOTE: '\'' (ESC_SQUOTE|.)*? '\'' ; //STRING_DQUOTE: '"' (ESC_DQUOTE|.)*? '"' ; // 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 // list : https://en.wikipedia.org/wiki/Whitespace_character //UNICODE_WS : [\p{White_Space}] -> skip; // match all Unicode whitespace WS: [ \t\f\r\n]+ -> channel(HIDDEN) ; 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+ ; 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)
Allow line returns in statements This is now allowed for example: << for i in [ "foo", "bar", "very long string ..." ] >> {{ i }} << endfor >>
Allow line returns in statements This is now allowed for example: << for i in [ "foo", "bar", "very long string ..." ] >> {{ i }} << endfor >>
ANTLR
mit
julsam/VineScript
e3a1106a19bf014811acdd347e2ad31b663fb5a8
lang/src/main/antlr4/org/kaazing/k3po/lang/parser/v2/Robot.g4
lang/src/main/antlr4/org/kaazing/k3po/lang/parser/v2/Robot.g4
/** * Copyright (c) 2007-2014, Kaazing Corporation. All rights reserved. */ grammar Robot; /* Parser rules */ // A robot script is comprised of a list of commands, events and barriers for // each stream. Note that we deliberately allow empty scripts, in order to // handle scripts which are comprised of nothing but empty lines and comments. scriptNode : (propertyNode | streamNode)* EOF ; propertyNode : PropertyKeyword name=propertyName value=propertyValue ; propertyName : Name ; propertyValue : writeValue ; optionName : QualifiedName | Name ; streamNode : acceptNode | acceptableNode | connectNode ; acceptNode : AcceptKeyword (AwaitKeyword await=Name)? acceptURI=location (AsKeyword as=Name)? (NotifyKeyword notify=Name)? acceptOption* serverStreamableNode* ; acceptOption : OptionKeyword optionName writeValue ; acceptableNode : AcceptedKeyword ( text=Name )? streamableNode+ ; connectNode : ConnectKeyword (AwaitKeyword await=Name)? connectURI=location connectOption* streamableNode+ ; connectOption : OptionKeyword optionName writeValue ; serverStreamableNode : barrierNode | serverEventNode | serverCommandNode | optionNode ; optionNode : readOptionNode | writeOptionNode ; readOptionNode : ReadKeyword OptionKeyword optionName writeValue ; writeOptionNode : WriteKeyword OptionKeyword optionName writeValue ; serverCommandNode : unbindNode | closeNode ; serverEventNode : openedNode | boundNode | childOpenedNode | childClosedNode | unboundNode | closedNode ; streamableNode : barrierNode | eventNode | commandNode | optionNode ; commandNode : writeConfigNode | writeNode | writeFlushNode | writeCloseNode | closeNode | abortNode ; eventNode : openedNode | boundNode | readConfigNode | readNode | readClosedNode | disconnectedNode | unboundNode | closedNode | connectedNode | abortedNode ; barrierNode : readAwaitNode | readNotifyNode | writeAwaitNode | writeNotifyNode ; closeNode : CloseKeyword ; writeFlushNode : WriteKeyword FlushKeyword ; writeCloseNode : WriteKeyword CloseKeyword ; disconnectNode : DisconnectKeyword ; unbindNode : UnbindKeyword ; writeConfigNode : WriteKeyword QualifiedName writeValue* ; writeNode : WriteKeyword writeValue+ ; childOpenedNode : ChildKeyword OpenedKeyword ; childClosedNode : ChildKeyword ClosedKeyword ; boundNode : BoundKeyword ; closedNode : ClosedKeyword ; connectedNode : ConnectedKeyword ; disconnectedNode : DisconnectedKeyword ; openedNode : OpenedKeyword ; abortNode : AbortKeyword ; abortedNode : AbortedKeyword ; readClosedNode : ReadKeyword ClosedKeyword ; readConfigNode : ReadKeyword QualifiedName matcher* MissingKeyword? ; readNode : ReadKeyword matcher+ ; unboundNode : UnboundKeyword ; readAwaitNode : ReadKeyword AwaitKeyword Name ; readNotifyNode : ReadKeyword NotifyKeyword Name ; writeAwaitNode : WriteKeyword AwaitKeyword Name ; writeNotifyNode : WriteKeyword NotifyKeyword Name ; matcher : exactTextMatcher | exactBytesMatcher | regexMatcher | expressionMatcher | fixedLengthBytesMatcher | variableLengthBytesMatcher ; exactTextMatcher : text=TextLiteral ; exactBytesMatcher : bytes=BytesLiteral | byteLiteral=ByteLiteral | shortLiteral=TwoByteLiteral | intLiteral=(SignedDecimalLiteral | DecimalLiteral) | longLiteral=(SignedDecimalLiteral | DecimalLiteral) 'L' ; regexMatcher : regex=RegexLiteral ; expressionMatcher : expression=ExpressionLiteral ; fixedLengthBytesMatcher : '[0..' lastIndex=DecimalLiteral ']' | '([0..' lastIndex=DecimalLiteral ']' capture=CaptureLiteral ')' | '[(' capture=CaptureLiteral '){' lastIndex=DecimalLiteral '}]' | '(byte' byteCapture=CaptureLiteral ')' | '(short' shortCapture=CaptureLiteral ')' | '(int' intCapture=CaptureLiteral ')' | '(long' longCapture=CaptureLiteral ')' ; variableLengthBytesMatcher : '[0..' length=ExpressionLiteral ']' | '([0..' length=ExpressionLiteral ']' capture=CaptureLiteral ')' ; writeValue : literalText | literalBytes | literalByte | literalShort | literalInteger | literalLong | expressionValue ; literalText : literal=TextLiteral ; literalBytes : literal=BytesLiteral ; literalByte : literal=ByteLiteral ; literalShort : literal=TwoByteLiteral ; literalInteger : literal=(SignedDecimalLiteral | DecimalLiteral) ; literalLong : literal=(SignedDecimalLiteral | DecimalLiteral) 'L' ; expressionValue : expression=ExpressionLiteral ; location : literalText | expressionValue ; SignedDecimalLiteral : Plus DecimalLiteral | Minus DecimalLiteral // | DecimalLiteral ; AbortKeyword : 'abort' ; AbortedKeyword : 'aborted' ; AcceptKeyword : 'accept' ; AcceptedKeyword : 'accepted' ; AsKeyword : 'as' ; AwaitKeyword : 'await' ; BindKeyword : 'bind' ; BoundKeyword : 'bound' ; ByteKeyword : 'byte' ; ChildKeyword : 'child' ; CloseKeyword : 'close' ; ClosedKeyword : 'closed' ; ConfigKeyword : 'config' ; ConnectKeyword : 'connect' ; ConnectedKeyword : 'connected' ; DisconnectKeyword : 'disconnect' ; DisconnectedKeyword : 'disconnected' ; IntKeyword : 'int' ; FlushKeyword : 'flush' ; LongKeyword : 'long' ; MissingKeyword : 'missing' ; NotifyKeyword : 'notify' ; OpenedKeyword : 'opened' ; OptionKeyword : 'option' ; PropertyKeyword : 'property' ; ReadKeyword : 'read' ; ShortKeyword : 'short' ; UnbindKeyword : 'unbind' ; UnboundKeyword : 'unbound' ; WriteKeyword : 'write' ; // URI cannot begin with any of our data type delimiters, and MUST contain a colon. URILiteral : Letter (Letter | '+')+ ':' '/' (Letter | ':' | ';' | '/' | '=' | '.' | DecimalLiteral | '?' | '&' | '%' | '-' | ',' | '*')+ // ~('"' | '/' | ']' | '}') ; CaptureLiteral : ':' Identifier ; ExpressionLiteral : '${' ~('}' | '\r' | '\n')+ '}' ; RegexLiteral : '/' PatternLiteral '/' // ( RegexNamedGroups+ '/' )? ; //RegexNamedGroups // : '(' CaptureLiteral RegexNamedGroups* ')' // ; fragment PatternLiteral : (~('/' | '\r' | '\n') | '\\' '/')+ ; BytesLiteral : '[' (' ')? (ByteLiteral (' ')*)+ ']' ; ByteLiteral : HexPrefix HexDigit HexDigit ; TwoByteLiteral : HexPrefix HexDigit HexDigit HexDigit HexDigit ; fragment HexLiteral : HexPrefix HexDigit+ ; fragment HexPrefix : '0' ('x' | 'X') ; fragment HexDigit : (Digit | 'a'..'f' | 'A'..'F') ; Plus : '+' ; Minus : '-' ; DecimalLiteral : Number ; fragment Number : Digit+ ; fragment Digit : '0'..'9' ; TextLiteral : '"' (EscapeSequence | ~('\\' | '\r' | '\n' | '"'))+ '"' | '\'' (EscapeSequence | ~('\\' | '\r' | '\n' | '\''))+ '\'' ; // Any additions to the escaping need to be accounted for in // org.kaazing.k3po.lang.parserScriptParseStrategy.escapeString(String toEscape); fragment EscapeSequence : '\\' ('b' | 'f' | 'r' | 'n' | 't' | '\"' | '\'' | '\\' ) ; Name : Identifier ; QualifiedName : Identifier ':' Identifier ; fragment Identifier : Letter (Digit | Minus | Letter)* ; fragment Letter : '\u0024' | '\u0041'..'\u005a' | '\u005f' | '\u0061'..'\u007a' | '\u00c0'..'\u00d6' | '\u00d8'..'\u00f6' | '\u00f8'..'\u00ff' | '\u0100'..'\u1fff' | '\u3040'..'\u318f' | '\u3300'..'\u337f' | '\u3400'..'\u3d2d' | '\u4e00'..'\u9fff' | '\uf900'..'\ufaff' ; WS : (' ' | '\r' | '\n' | '\t' | '\u000C')+ -> skip; LineComment : '#' ~('\n' | '\r')* '\r'? '\n' -> skip;
/** * Copyright (c) 2007-2014, Kaazing Corporation. All rights reserved. */ grammar Robot; /* Parser rules */ // A robot script is comprised of a list of commands, events and barriers for // each stream. Note that we deliberately allow empty scripts, in order to // handle scripts which are comprised of nothing but empty lines and comments. scriptNode : (propertyNode | streamNode)* EOF ; propertyNode : PropertyKeyword name=propertyName value=propertyValue ; propertyName : Name ; propertyValue : writeValue ; optionName : QualifiedName | Name ; streamNode : acceptNode | acceptableNode | connectNode ; acceptNode : AcceptKeyword (AwaitKeyword await=Name)? acceptURI=location (AsKeyword as=Name)? (NotifyKeyword notify=Name)? acceptOption* serverStreamableNode* ; acceptOption : OptionKeyword optionName writeValue ; acceptableNode : AcceptedKeyword ( text=Name )? streamableNode+ ; connectNode : ConnectKeyword (AwaitKeyword await=Name)? connectURI=location connectOption* streamableNode+ ; connectOption : OptionKeyword optionName writeValue ; serverStreamableNode : barrierNode | serverEventNode | serverCommandNode | optionNode ; optionNode : readOptionNode | writeOptionNode ; readOptionNode : ReadKeyword OptionKeyword optionName writeValue ; writeOptionNode : WriteKeyword OptionKeyword optionName writeValue ; serverCommandNode : unbindNode | closeNode ; serverEventNode : openedNode | boundNode | childOpenedNode | childClosedNode | unboundNode | closedNode ; streamableNode : barrierNode | eventNode | commandNode | optionNode ; commandNode : writeConfigNode | writeNode | writeFlushNode | writeCloseNode | closeNode | abortNode ; eventNode : openedNode | boundNode | readConfigNode | readNode | readClosedNode | disconnectedNode | unboundNode | closedNode | connectedNode | abortedNode ; barrierNode : readAwaitNode | readNotifyNode | writeAwaitNode | writeNotifyNode ; closeNode : CloseKeyword ; writeFlushNode : WriteKeyword FlushKeyword ; writeCloseNode : WriteKeyword CloseKeyword ; disconnectNode : DisconnectKeyword ; unbindNode : UnbindKeyword ; writeConfigNode : WriteKeyword QualifiedName writeValue* ; writeNode : WriteKeyword writeValue+ ; childOpenedNode : ChildKeyword OpenedKeyword ; childClosedNode : ChildKeyword ClosedKeyword ; boundNode : BoundKeyword ; closedNode : ClosedKeyword ; connectedNode : ConnectedKeyword ; disconnectedNode : DisconnectedKeyword ; openedNode : OpenedKeyword ; abortNode : AbortKeyword ; abortedNode : AbortedKeyword ; readClosedNode : ReadKeyword ClosedKeyword ; readConfigNode : ReadKeyword QualifiedName matcher* MissingKeyword? ; readNode : ReadKeyword matcher+ ; unboundNode : UnboundKeyword ; readAwaitNode : ReadKeyword AwaitKeyword Name ; readNotifyNode : ReadKeyword NotifyKeyword Name ; writeAwaitNode : WriteKeyword AwaitKeyword Name ; writeNotifyNode : WriteKeyword NotifyKeyword Name ; matcher : exactTextMatcher | exactBytesMatcher | regexMatcher | expressionMatcher | fixedLengthBytesMatcher | variableLengthBytesMatcher ; exactTextMatcher : text=TextLiteral ; exactBytesMatcher : bytes=BytesLiteral | byteLiteral=ByteLiteral | shortLiteral=TwoByteLiteral | intLiteral=(SignedDecimalLiteral | DecimalLiteral) | longLiteral=(SignedDecimalLiteral | DecimalLiteral) 'L' ; regexMatcher : regex=RegexLiteral ; expressionMatcher : expression=ExpressionLiteral ; fixedLengthBytesMatcher : '[0..' lastIndex=DecimalLiteral ']' | '([0..' lastIndex=DecimalLiteral ']' capture=CaptureLiteral ')' | '[(' capture=CaptureLiteral '){' lastIndex=DecimalLiteral '}]' | '(byte' byteCapture=CaptureLiteral ')' | '(short' shortCapture=CaptureLiteral ')' | '(int' intCapture=CaptureLiteral ')' | '(long' longCapture=CaptureLiteral ')' ; variableLengthBytesMatcher : '[0..' length=ExpressionLiteral ']' | '([0..' length=ExpressionLiteral ']' capture=CaptureLiteral ')' ; writeValue : literalText | literalBytes | literalByte | literalShort | literalInteger | literalLong | expressionValue ; literalText : literal=TextLiteral ; literalBytes : literal=BytesLiteral ; literalByte : literal=ByteLiteral ; literalShort : literal=TwoByteLiteral ; literalInteger : literal=(SignedDecimalLiteral | DecimalLiteral) ; literalLong : literal=(SignedDecimalLiteral | DecimalLiteral) 'L' ; expressionValue : expression=ExpressionLiteral ; location : literalText | expressionValue ; SignedDecimalLiteral : Plus DecimalLiteral | Minus DecimalLiteral // | DecimalLiteral ; AbortKeyword : 'abort' ; AbortedKeyword : 'aborted' ; AcceptKeyword : 'accept' ; AcceptedKeyword : 'accepted' ; AsKeyword : 'as' ; AwaitKeyword : 'await' ; BindKeyword : 'bind' ; BoundKeyword : 'bound' ; ByteKeyword : 'byte' ; ChildKeyword : 'child' ; CloseKeyword : 'close' ; ClosedKeyword : 'closed' ; ConfigKeyword : 'config' ; ConnectKeyword : 'connect' ; ConnectedKeyword : 'connected' ; DisconnectKeyword : 'disconnect' ; DisconnectedKeyword : 'disconnected' ; IntKeyword : 'int' ; FlushKeyword : 'flush' ; LongKeyword : 'long' ; MissingKeyword : 'missing' ; NotifyKeyword : 'notify' ; OpenedKeyword : 'opened' ; OptionKeyword : 'option' ; PropertyKeyword : 'property' ; ReadKeyword : 'read' ; ShortKeyword : 'short' ; UnbindKeyword : 'unbind' ; UnboundKeyword : 'unbound' ; WriteKeyword : 'write' ; // URI cannot begin with any of our data type delimiters, and MUST contain a colon. URILiteral : Letter (Letter | '+')+ ':' '/' (Letter | ':' | ';' | '/' | '=' | '.' | DecimalLiteral | '?' | '&' | '%' | '-' | ',' | '*')+ // ~('"' | '/' | ']' | '}') ; CaptureLiteral : ':' Identifier ; ExpressionLiteral : '${' ~('}' | '\r' | '\n')+ '}' ; RegexLiteral : '/' PatternLiteral '/' // ( RegexNamedGroups+ '/' )? ; //RegexNamedGroups // : '(' CaptureLiteral RegexNamedGroups* ')' // ; fragment PatternLiteral : (~('/' | '\r' | '\n') | '\\' '/')+ ; BytesLiteral : '[' (' ')? (ByteLiteral (' ')*)+ ']' ; ByteLiteral : HexPrefix HexDigit HexDigit ; TwoByteLiteral : HexPrefix HexDigit HexDigit HexDigit HexDigit ; fragment HexLiteral : HexPrefix HexDigit+ ; fragment HexPrefix : '0' ('x' | 'X') ; fragment HexDigit : (Digit | 'a'..'f' | 'A'..'F') ; Plus : '+' ; Minus : '-' ; DecimalLiteral : Number ; fragment Number : Digit+ ; fragment Digit : '0'..'9' ; TextLiteral : '"' (EscapeSequence | ~('\\' | '\r' | '\n' | '"'))+ '"' | '\'' (EscapeSequence | ~('\\' | '\r' | '\n' | '\''))+ '\'' ; // Any additions to the escaping need to be accounted for in // org.kaazing.k3po.lang.parserScriptParseStrategy.escapeString(String toEscape); fragment EscapeSequence : '\\' ('b' | 'f' | 'r' | 'n' | 't' | '\"' | '\'' | '\\' ) ; Name : Identifier ; QualifiedName : Identifier ':' Identifier ('.' Identifier)* ; fragment Identifier : Letter (Digit | Minus | Letter)* ; fragment Letter : '\u0024' | '\u0041'..'\u005a' | '\u005f' | '\u0061'..'\u007a' | '\u00c0'..'\u00d6' | '\u00d8'..'\u00f6' | '\u00f8'..'\u00ff' | '\u0100'..'\u1fff' | '\u3040'..'\u318f' | '\u3300'..'\u337f' | '\u3400'..'\u3d2d' | '\u4e00'..'\u9fff' | '\uf900'..'\ufaff' ; WS : (' ' | '\r' | '\n' | '\t' | '\u000C')+ -> skip; LineComment : '#' ~('\n' | '\r')* '\r'? '\n' -> skip;
Support . in qualified config names
Support . in qualified config names
ANTLR
apache-2.0
cmebarrow/k3po,StCostea/k3po,jfallows/k3po,k3po/k3po,cmebarrow/k3po,jfallows/k3po,StCostea/k3po,k3po/k3po
11e95d3bfc304679f3f5902c8f50e81137440e19
sharding-jdbc-ddl-parser/src/main/antlr4/imports/OracleAlterTable.g4
sharding-jdbc-ddl-parser/src/main/antlr4/imports/OracleAlterTable.g4
grammar OracleAlterTable; import OracleKeyword, DataType, Keyword,OracleCreateIndex, OracleTableBase,OracleBase,BaseRule,Symbol; alterTable : ALTER TABLE tableName ( alterTableProperties | columnClauses | constraintClauses | alterExternalTable )? ; alterTableProperties : renameTable | REKEY encryptionSpec ; renameTable: RENAME TO tableName ; columnClauses : opColumnClause+ | renameColumn ; opColumnClause : addColumn | modifyColumn | dropColumnClause ; addColumn : ADD columnOrVirtualDefinitions columnProperties? ; columnOrVirtualDefinitions : LEFT_PAREN columnOrVirtualDefinition (COMMA columnOrVirtualDefinition)* RIGHT_PAREN | columnOrVirtualDefinition ; columnOrVirtualDefinition: columnDefinition | virtualColumnDefinition ; modifyColumn : MODIFY ( LEFT_PAREN modifyColProperties (COMMA modifyColProperties)* RIGHT_PAREN | modifyColSubstitutable ) ; modifyColProperties : columnName dataType? (DEFAULT expr)? (ENCRYPT encryptionSpec | DECRYPT)? inlineConstraint* ; modifyColSubstitutable : COLUMN columnName NOT? SUBSTITUTABLE AT ALL LEVELS FORCE? ; dropColumnClause : SET UNUSED columnOrColumnList cascadeOrInvalidate* | dropColumn ; dropColumn : DROP columnOrColumnList cascadeOrInvalidate* checkpointNumber? ; columnOrColumnList : COLUMN columnName | LEFT_PAREN columnName ( COMMA columnName )* RIGHT_PAREN ; cascadeOrInvalidate : CASCADE CONSTRAINTS | INVALIDATE ; checkpointNumber : CHECKPOINT NUMBER ; renameColumn : RENAME COLUMN columnName TO columnName ; constraintClauses : addConstraintClause | modifyConstraintClause | renameConstraintClause | dropConstraintClause+ ; addConstraintClause : ADD (outOfLineConstraint+ | outOfLineRefConstraint) ; modifyConstraintClause: MODIFY constraintOption constraintState CASCADE? ; constraintWithName: CONSTRAINT constraintName ; constraintOption: constraintWithName | constraintPrimaryOrUnique ; constraintPrimaryOrUnique: primaryKey | (UNIQUE columnList) ; renameConstraintClause: RENAME constraintWithName TO constraintName ; dropConstraintClause: DROP ( (constraintPrimaryOrUnique CASCADE? (( KEEP | DROP) INDEX)?) | (CONSTRAINT constraintName ( CASCADE )?) ) ; alterExternalTable: ( addColumn | modifyColumn | dropColumn )+ ;
grammar OracleAlterTable; import OracleKeyword, DataType, Keyword,OracleCreateIndex, OracleTableBase,OracleBase,BaseRule,Symbol; alterTable : ALTER TABLE tableName ( alterTableProperties | columnClauses | constraintClauses | alterExternalTable )? ; alterTableProperties : renameTable | REKEY encryptionSpec ; renameTable: RENAME TO tableName ; columnClauses : opColumnClause+ | renameColumn ; opColumnClause : addColumn | modifyColumn | dropColumnClause ; addColumn : ADD columnOrVirtualDefinitions columnProperties? ; columnOrVirtualDefinitions : LEFT_PAREN columnOrVirtualDefinition (COMMA columnOrVirtualDefinition)* RIGHT_PAREN | columnOrVirtualDefinition ; columnOrVirtualDefinition: columnDefinition | virtualColumnDefinition ; modifyColumn : MODIFY ( LEFT_PAREN modifyColProperties (COMMA modifyColProperties)* RIGHT_PAREN | modifyColSubstitutable ) ; modifyColProperties : columnName dataType? (DEFAULT expr)? (ENCRYPT encryptionSpec | DECRYPT)? inlineConstraint* ; modifyColSubstitutable : COLUMN columnName NOT? SUBSTITUTABLE AT ALL LEVELS FORCE? ; dropColumnClause : SET UNUSED columnOrColumnList cascadeOrInvalidate* | dropColumn ; dropColumn : DROP columnOrColumnList cascadeOrInvalidate* checkpointNumber? ; columnOrColumnList : COLUMN columnName | LEFT_PAREN columnName ( COMMA columnName )* RIGHT_PAREN ; cascadeOrInvalidate : CASCADE CONSTRAINTS | INVALIDATE ; checkpointNumber : CHECKPOINT NUMBER ; renameColumn : RENAME COLUMN columnName TO columnName ; constraintClauses : addConstraintClause | modifyConstraintClause | renameConstraintClause | dropConstraintClause+ ; addConstraintClause : ADD (outOfLineConstraint+ | outOfLineRefConstraint) ; modifyConstraintClause : MODIFY constraintOption constraintState CASCADE? ; constraintWithName : CONSTRAINT constraintName ; constraintOption : constraintWithName | constraintPrimaryOrUnique ; constraintPrimaryOrUnique : primaryKey | UNIQUE columnList ; renameConstraintClause : RENAME constraintWithName TO constraintName ; dropConstraintClause : DROP ( (constraintPrimaryOrUnique CASCADE? (( KEEP | DROP) INDEX)?) | (CONSTRAINT constraintName ( CASCADE )?) ) ; alterExternalTable : ( addColumn | modifyColumn | dropColumn )+ ;
Format rules
Format rules
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
48eb8a600b4d5e6e469cab33b79a4b63c1e60114
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[5]; if(inHeader || intr || listLevel > 0) { 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"; 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 LineBreak+ {breakOut();} ; LineBreak : '\r'? '\n' ; /* ***** Links ***** */ RawUrl : PROTOCOL (~(' '|'\t'|'\r'|'\n'|'|'|'['|']')+ '/'?)+ {doUrl();} ; fragment PROTOCOL : ('http' 's'? | 'file' | 'ftp') '://' | 'mailto:' ; Attachment : UPPER ALNUM* ALPHA ALNUM+ '.' LOWER 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 LineBreak+ {breakOut();} ; LineBreak : '\r'? '\n' ; /* ***** Links ***** */ RawUrl : PROTOCOL (~(' '|'\t'|'\r'|'\n'|'|'|'['|']')+ '/'?)+ {doUrl();} ; fragment PROTOCOL : ('http' 's'? | 'file' | 'ftp') '://' | 'mailto:' ; Attachment : UPPER ALNUM* ALPHA ALNUM+ '.' LOWER 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) ;
Break inline formatting in lists at the start of the next item, not at all newlines
Break inline formatting in lists at the start of the next item, not at all newlines
ANTLR
apache-2.0
strr/reviki,strr/reviki,ashirley/reviki,strr/reviki,CoreFiling/reviki,CoreFiling/reviki,ashirley/reviki,ashirley/reviki,strr/reviki,ashirley/reviki,CoreFiling/reviki,ashirley/reviki,strr/reviki,CoreFiling/reviki,CoreFiling/reviki