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
|
---|---|---|---|---|---|---|---|---|---|
87d886380744b6276165c6012a8b32877a9459b5
|
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
|
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
|
grammar SQLServerDCLStatement;
import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol;
grantGeneral
: GRANT (ALL PRIVILEGES? | permissionOnColumns ( COMMA permissionOnColumns)*)
(ON (ID COLONCOLON)? ID )? TO ids
(WITH GRANT OPTION)? (AS ID)?
;
permissionOnColumns
: permission columnList?
;
permission
: ID *?
;
classType
: LOGIN
| DATABASE
| OBJECT
| ROLE
| SCHEMA
| USER
;
|
grammar SQLServerDCLStatement;
import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol;
grantGeneral
: GRANT (ALL PRIVILEGES? | permissionOnColumns ( COMMA permissionOnColumns)*)
(ON (ID COLONCOLON)? ID )? TO ids
(WITH GRANT OPTION)? (AS ID)?
;
permissionOnColumns
: permission columnList?
;
permission
: ID *?
;
grantDW
: GRANT permission (COMMA permission)*
(ON (classType COLONCOLON)? ID)?
TO ids (WITH GRANT OPTION)?
;
classType
: LOGIN
| DATABASE
| OBJECT
| ROLE
| SCHEMA
| USER
;
|
add grantDW
|
add grantDW
|
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
|
e5c467c0abe1f33295d600093910fe10ddb31a57
|
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
|
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
|
grammar SQLServerDCLStatement;
import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol;
grant
: grantGeneral | grantDW
;
grantGeneral
: GRANT (ALL PRIVILEGES? | permissionOnColumns ( COMMA permissionOnColumns)*)
(ON (ID COLON COLON)? ID)? TO ids (WITH GRANT OPTION)? (AS ID)?
;
permissionOnColumns
: permission columnList?
;
permission
: ID *?
;
grantDW
: GRANT permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
TO ids (WITH GRANT OPTION)?
;
classType
: LOGIN | DATABASE | OBJECT | ROLE | SCHEMA | USER
;
revoke
: revokeGeneral | revokeDW
;
revokeGeneral
: REVOKE (GRANT OPTION FOR)? ((ALL PRIVILEGES?)? | permissionOnColumns)
(ON (ID COLON COLON)? ID)? (TO | FROM) ids (CASCADE)? (AS ID)?
;
revokeDW
: REVOKE permissionWithClass (FROM | TO)? ids CASCADE?
;
permissionWithClass
: permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
;
deny
: DENY permissionWithClass TO ids CASCADE? (AS ID)?
;
createUser3
: CREATE USER userName
(
ID (( FOR | FROM ) LOGIN ID)?
| userName ( FOR | FROM ) LOGIN ID
)
;
createUser4
: CREATE USER userName
(
WITHOUT LOGIN (WITH limitedOptionsList (COMMA limitedOptionsList)*)?
| (FOR | FROM ) CERTIFICATE ID
| (FOR | FROM) ASYMMETRIC KEY ID
)
;
optionsList
: DEFAU_SCHEMA EQ_ schemaName
| DEFAU_LANGUAGE EQ_ ( NONE | ID)
| SID EQ_ ID
| ALLOW_ENCRYPTED_VALUE_MODIFICATIONS EQ_ (ON | OFF)
;
limitedOptionsList
: DEFAU_SCHEMA EQ_ schemaName | ALLOW_ENCRYPTED_VALUE_MODIFICATIONS EQ_ (ON | OFF)?
;
|
grammar SQLServerDCLStatement;
import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol;
grant
: grantGeneral | grantDW
;
grantGeneral
: GRANT (ALL PRIVILEGES? | permissionOnColumns ( COMMA permissionOnColumns)*)
(ON (ID COLON COLON)? ID)? TO ids (WITH GRANT OPTION)? (AS ID)?
;
permissionOnColumns
: permission columnList?
;
permission
: ID *?
;
grantDW
: GRANT permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
TO ids (WITH GRANT OPTION)?
;
classType
: LOGIN | DATABASE | OBJECT | ROLE | SCHEMA | USER
;
revoke
: revokeGeneral | revokeDW
;
revokeGeneral
: REVOKE (GRANT OPTION FOR)? ((ALL PRIVILEGES?)? | permissionOnColumns)
(ON (ID COLON COLON)? ID)? (TO | FROM) ids (CASCADE)? (AS ID)?
;
revokeDW
: REVOKE permissionWithClass (FROM | TO)? ids CASCADE?
;
permissionWithClass
: permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
;
deny
: DENY permissionWithClass TO ids CASCADE? (AS ID)?
;
createUser2
: CREATE USER userName
(
windowsPrincipal (WITH optionsList (COMMA optionsList)*)?
| userName WITH PASSWORD EQ_ STRING (COMMA optionsList)*
| ID FROM EXTERNAL PROVIDER
)
;
createUser3
: CREATE USER userName
(
ID (( FOR | FROM ) LOGIN ID)?
| userName ( FOR | FROM ) LOGIN ID
)
;
createUser4
: CREATE USER userName
(
WITHOUT LOGIN (WITH limitedOptionsList (COMMA limitedOptionsList)*)?
| (FOR | FROM ) CERTIFICATE ID
| (FOR | FROM) ASYMMETRIC KEY ID
)
;
optionsList
: DEFAU_SCHEMA EQ_ schemaName
| DEFAU_LANGUAGE EQ_ ( NONE | ID)
| SID EQ_ ID
| ALLOW_ENCRYPTED_VALUE_MODIFICATIONS EQ_ (ON | OFF)
;
limitedOptionsList
: DEFAU_SCHEMA EQ_ schemaName | ALLOW_ENCRYPTED_VALUE_MODIFICATIONS EQ_ (ON | OFF)?
;
|
add createUser2
|
add createUser2
|
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
|
cac1967df081f90ea76ac162b4e1b4bc54cd2d9c
|
src/aa.g4
|
src/aa.g4
|
grammar aa;
@header {
package pt.up.fe.comp.aa.parser;
}
stmt_list : stmt*
;
stmt : (((attribution | operation) SEMICOLON) | control_expr)
;
attribution : attribution_lhs EQUAL attribution_rhs
;
attribution_lhs : IDENTIFIER
;
attribution_rhs : IDENTIFIER
| operation
| STRING
;
operation : operator=IDENTIFIER arg_list
;
IF : 'if';
ELSE : 'else';
control_expr : IF OPEN_PR predicate=operation CLOSE_PR OPEN_BR trueCase=stmt_list CLOSE_BR (ELSE OPEN_BR falseCase=stmt_list CLOSE_BR)?
;
arg_list : arg*
;
arg : IDENTIFIER
| STRING
| OPEN_PR operation CLOSE_PR
;
// UNION : 'union';
// INTERSECTION : 'intersect';
// CARTESIAN_PRODUCT : 'cartesian';
// DIFFERENCE : 'diff';
// CLOSURE : 'closure';
// COMPLEMENT : 'complement';
// MINIMIZE : 'min';
// TO_DFA : 'to_dfa';
// INCLUDED : 'in';
// EQUIVALENT : 'equi';
// EQUALS : 'equals';
// ENFA_TO_NFA : 'remove_e'; //TODO rename
// TOTALIZE : 'totalize';
// REMOVE_UNREACHABLE : 'remove_unreachable';
// REMOVE_USELESS : 'remove_useless';
// WRITE_DOT : 'write_dot';
// WRITE_REGEX : 'write_regex';
// WRITE_CODE : 'write_code';
// SHOW : 'show';
// PRINT : 'print';
IDENTIFIER : [_a-zA-Z][_a-zA-Z0-9-]*;
STRING : '"' .+? '"';
OPEN_PR : '(';
CLOSE_PR : ')';
OPEN_BR : '{';
CLOSE_BR : '}';
EQUAL : '=';
SEMICOLON : ';';
WS : [ \t\r\n]+ -> skip;
COMMENT : '/*' .*? '*/' -> skip;
LINE_COMMENT : '//' .*? '\r'? '\n' -> skip;
|
grammar aa;
@header {
package pt.up.fe.comp.aa.parser;
}
stmt_list : stmt*
;
stmt : (((attribution | operation) SEMICOLON) | control_expr)
;
attribution : attribution_lhs EQUAL attribution_rhs
;
attribution_lhs : IDENTIFIER
;
attribution_rhs : IDENTIFIER
| operation
| STRING
;
operation : operator=IDENTIFIER arg_list
;
IF : 'if';
ELSE : 'else';
control_expr : IF OPEN_PR predicate=operation CLOSE_PR OPEN_BR trueCase=stmt_list CLOSE_BR (ELSE OPEN_BR falseCase=stmt_list CLOSE_BR)?
;
arg_list : arg*
;
arg : IDENTIFIER
| STRING
| OPEN_PR operation CLOSE_PR
;
IDENTIFIER : [_a-zA-Z][_a-zA-Z0-9-]*;
STRING : '"' .+? '"';
OPEN_PR : '(';
CLOSE_PR : ')';
OPEN_BR : '{';
CLOSE_BR : '}';
EQUAL : '=';
SEMICOLON : ';';
WS : [ \t\r\n]+ -> skip;
COMMENT : '/*' .*? '*/' -> skip;
LINE_COMMENT : '//' .*? '\r'? '\n' -> skip;
|
Clean aa.g4 grammar.
|
Clean aa.g4 grammar.
|
ANTLR
|
mit
|
migulorama/AutoAnalyze,migulorama/AutoAnalyze
|
d67b900b10fab222f6f96e7ff5e17eab9cc88a32
|
pascal/pascal.g4
|
pascal/pascal.g4
|
/*
BSD License
Copyright (c) 2013, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Adapted from pascal.g by Hakki Dogusan, Piet Schoutteten and Marton Papp
*/
grammar pascal;
program
: programHeading (INTERFACE)? block DOT
;
programHeading
: PROGRAM identifier (LPAREN identifierList RPAREN)? SEMI
| UNIT identifier SEMI
;
identifier
: IDENT
;
block
: (labelDeclarationPart | constantDefinitionPart | typeDefinitionPart | variableDeclarationPart | procedureAndFunctionDeclarationPart | usesUnitsPart | IMPLEMENTATION)* compoundStatement
;
usesUnitsPart
: USES identifierList SEMI
;
labelDeclarationPart
: LABEL label (COMMA label)* SEMI
;
label
: unsignedInteger
;
constantDefinitionPart
: CONST constantDefinition (SEMI constantDefinition)* SEMI
;
constantDefinition
: identifier EQUAL constant
;
constantChr
: CHR LPAREN unsignedInteger RPAREN
;
constant
: unsignedNumber
| sign unsignedNumber
| identifier
| sign identifier
| string
| constantChr
;
unsignedNumber
: unsignedInteger
| unsignedReal
;
unsignedInteger
: NUM_INT
;
unsignedReal
: NUM_INT
;
sign
: PLUS
| MINUS
;
string
: STRING_LITERAL
;
typeDefinitionPart
: TYPE typeDefinition (SEMI typeDefinition)* SEMI
;
typeDefinition
: identifier EQUAL (type | functionType | procedureType)
;
functionType
: FUNCTION (formalParameterList)? COLON resultType
;
procedureType
: PROCEDURE (formalParameterList)?
;
type
: simpleType
| structuredType
| pointerType
;
simpleType
: scalarType
| subrangeType
| typeIdentifier
| stringtype
;
scalarType
: LPAREN identifierList RPAREN
;
subrangeType
: constant DOTDOT constant
;
typeIdentifier
: identifier
| (CHAR | BOOLEAN | INTEGER | REAL | STRING)
;
structuredType
: PACKED unpackedStructuredType
| unpackedStructuredType
;
unpackedStructuredType
: arrayType
| recordType
| setType
| fileType
;
stringtype
: STRING LBRACK (identifier | unsignedNumber) RBRACK
;
arrayType
: ARRAY LBRACK typeList RBRACK OF componentType
| ARRAY LBRACK2 typeList RBRACK2 OF componentType
;
typeList
: indexType (COMMA indexType)*
;
indexType
: simpleType
;
componentType
: type
;
recordType
: RECORD fieldList END
;
fieldList
: (fixedPart (SEMI variantPart | SEMI)? | variantPart)
;
fixedPart
: recordSection (SEMI recordSection)*
;
recordSection
: identifierList COLON type
;
variantPart
: CASE tag OF variant (SEMI variant | SEMI)*
;
tag
: identifier COLON typeIdentifier
| typeIdentifier
;
variant
: constList COLON LPAREN fieldList RPAREN
;
setType
: SET OF baseType
;
baseType
: simpleType
;
fileType
: FILE OF type
| FILE
;
pointerType
: POINTER typeIdentifier
;
variableDeclarationPart
: VAR variableDeclaration (SEMI variableDeclaration)* SEMI
;
variableDeclaration
: identifierList COLON type
;
procedureAndFunctionDeclarationPart
: procedureOrFunctionDeclaration SEMI
;
procedureOrFunctionDeclaration
: procedureDeclaration
| functionDeclaration
;
procedureDeclaration
: PROCEDURE identifier (formalParameterList)? SEMI block
;
formalParameterList
: LPAREN formalParameterSection (SEMI formalParameterSection)* RPAREN
;
formalParameterSection
: parameterGroup
| VAR parameterGroup
| FUNCTION parameterGroup
| PROCEDURE parameterGroup
;
parameterGroup
: identifierList COLON typeIdentifier
;
identifierList
: identifier (COMMA identifier)*
;
constList
: constant (COMMA constant)*
;
functionDeclaration
: FUNCTION identifier (formalParameterList)? COLON resultType SEMI block
;
resultType
: typeIdentifier
;
statement
: label COLON unlabelledStatement
| unlabelledStatement
;
unlabelledStatement
: simpleStatement
| structuredStatement
;
simpleStatement
: assignmentStatement
| procedureStatement
| gotoStatement
| emptyStatement
;
assignmentStatement
: variable ASSIGN expression
;
variable
: (AT identifier | identifier) (LBRACK expression (COMMA expression)* RBRACK | LBRACK2 expression (COMMA expression)* RBRACK2 | DOT identifier | POINTER)*
;
expression
: simpleExpression ((EQUAL | NOT_EQUAL | LT | LE | GE | GT | IN) simpleExpression)*
;
simpleExpression
: term ((PLUS | MINUS | OR) term)*
;
term
: signedFactor ((STAR | SLASH | DIV | MOD | AND) signedFactor)*
;
signedFactor
: (PLUS | MINUS)? factor
;
factor
: variable
| LPAREN expression RPAREN
| functionDesignator
| unsignedConstant
| set
| NOT factor
;
unsignedConstant
: unsignedNumber
| constantChr
| string
| NIL
;
functionDesignator
: identifier LPAREN parameterList RPAREN
;
parameterList
: actualParameter (COMMA actualParameter)*
;
set
: LBRACK elementList RBRACK
| LBRACK2 elementList RBRACK2
;
elementList
: element (COMMA element)*
|
;
element
: expression (DOTDOT expression)?
;
procedureStatement
: identifier (LPAREN parameterList RPAREN)?
;
actualParameter
: expression
;
gotoStatement
: GOTO label
;
emptyStatement
:
;
empty
:/* empty */
;
structuredStatement
: compoundStatement
| conditionalStatement
| repetetiveStatement
| withStatement
;
compoundStatement
: BEGIN statements END
;
statements
: statement (SEMI statement)*
;
conditionalStatement
: ifStatement
| caseStatement
;
ifStatement
: IF expression THEN statement (: ELSE statement)?
;
caseStatement
: CASE expression OF caseListElement (SEMI caseListElement)* (SEMI ELSE statements)? END
;
caseListElement
: constList COLON statement
;
repetetiveStatement
: whileStatement
| repeatStatement
| forStatement
;
whileStatement
: WHILE expression DO statement
;
repeatStatement
: REPEAT statements UNTIL expression
;
forStatement
: FOR identifier ASSIGN forList DO statement
;
forList
: initialValue (TO | DOWNTO) finalValue
;
initialValue
: expression
;
finalValue
: expression
;
withStatement
: WITH recordVariableList DO statement
;
recordVariableList
: variable (COMMA variable)*
;
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')
;
AND
: A N D
;
ARRAY
: A R R A Y
;
BEGIN
: B E G I N
;
BOOLEAN
: B O O L E A N
;
CASE
: C A S E
;
CHAR
: C H A R
;
CHR
: C H R
;
CONST
: C O N S T
;
DIV
: D I V
;
DO
: D O
;
DOWNTO
: D O W N T O
;
ELSE
: E L S E
;
END
: E N D
;
FILE
: F I L E
;
FOR
: F O R
;
FUNCTION
: F U N C T I O N
;
GOTO
: G O T O
;
IF
: I F
;
IN
: I N
;
INTEGER
: I N T E G E R
;
LABEL
: L A B E L
;
MOD
: M O D
;
NIL
: N I L
;
NOT
: N O T
;
OF
: O F
;
OR
: O R
;
PACKED
: P A C K E D
;
PROCEDURE
: P R O C E D U R E
;
PROGRAM
: P R O G R A M
;
REAL
: R E A L
;
RECORD
: R E C O R D
;
REPEAT
: R E P E A T
;
SET
: S E T
;
THEN
: T H E N
;
TO
: T O
;
TYPE
: T Y P E
;
UNTIL
: U N T I L
;
VAR
: V A R
;
WHILE
: W H I L E
;
WITH
: W I T H
;
PLUS
: '+'
;
MINUS
: '-'
;
STAR
: '*'
;
SLASH
: '/'
;
ASSIGN
: ':='
;
COMMA
: ','
;
SEMI
: ';'
;
COLON
: ':'
;
EQUAL
: '='
;
NOT_EQUAL
: '<>'
;
LT
: '<'
;
LE
: '<='
;
GE
: '>='
;
GT
: '>'
;
LPAREN
: '('
;
RPAREN
: ')'
;
LBRACK
: '['
;
LBRACK2
: '(.'
;
RBRACK
: ']'
;
RBRACK2
: '.)'
;
POINTER
: '^'
;
AT
: '@'
;
DOT
: '.'
;
DOTDOT
: '..'
;
LCURLY
: '{'
;
RCURLY
: '}'
;
UNIT
: U N I T
;
INTERFACE
: I N T E R F A C E
;
USES
: U S E S
;
STRING
: S T R I N G
;
IMPLEMENTATION
: I M P L E M E N T A T I O N
;
WS
: [ \t\r\n] -> skip
;
COMMENT_1
: '(*' .*? '*)' -> skip
;
COMMENT_2
: '{' .*? '}' -> skip
;
IDENT
: ('a' .. 'z' | 'A' .. 'Z') ('a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_')*
;
STRING_LITERAL
: '\'' ('\'\'' | ~ ('\''))* '\''
;
NUM_INT
: ('0' .. '9') + (('.' ('0' .. '9') + (EXPONENT)?)? | EXPONENT)
;
fragment EXPONENT
: ('e') ('+' | '-')? ('0' .. '9') +
;
|
/*
BSD License
Copyright (c) 2013, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Adapted from pascal.g by Hakki Dogusan, Piet Schoutteten and Marton Papp
*/
grammar pascal;
program
: programHeading (INTERFACE)? block DOT
;
programHeading
: PROGRAM identifier (LPAREN identifierList RPAREN)? SEMI
| UNIT identifier SEMI
;
identifier
: IDENT
;
block
: (labelDeclarationPart | constantDefinitionPart | typeDefinitionPart | variableDeclarationPart | procedureAndFunctionDeclarationPart | usesUnitsPart | IMPLEMENTATION)* compoundStatement
;
usesUnitsPart
: USES identifierList SEMI
;
labelDeclarationPart
: LABEL label (COMMA label)* SEMI
;
label
: unsignedInteger
;
constantDefinitionPart
: CONST (constantDefinition SEMI)+
;
constantDefinition
: identifier EQUAL constant
;
constantChr
: CHR LPAREN unsignedInteger RPAREN
;
constant
: unsignedNumber
| sign unsignedNumber
| identifier
| sign identifier
| string
| constantChr
;
unsignedNumber
: unsignedInteger
| unsignedReal
;
unsignedInteger
: NUM_INT
;
unsignedReal
: NUM_INT
;
sign
: PLUS
| MINUS
;
string
: STRING_LITERAL
;
typeDefinitionPart
: TYPE (typeDefinition SEMI)+
;
typeDefinition
: identifier EQUAL (type | functionType | procedureType)
;
functionType
: FUNCTION (formalParameterList)? COLON resultType
;
procedureType
: PROCEDURE (formalParameterList)?
;
type
: simpleType
| structuredType
| pointerType
;
simpleType
: scalarType
| subrangeType
| typeIdentifier
| stringtype
;
scalarType
: LPAREN identifierList RPAREN
;
subrangeType
: constant DOTDOT constant
;
typeIdentifier
: identifier
| (CHAR | BOOLEAN | INTEGER | REAL | STRING)
;
structuredType
: PACKED unpackedStructuredType
| unpackedStructuredType
;
unpackedStructuredType
: arrayType
| recordType
| setType
| fileType
;
stringtype
: STRING LBRACK (identifier | unsignedNumber) RBRACK
;
arrayType
: ARRAY LBRACK typeList RBRACK OF componentType
| ARRAY LBRACK2 typeList RBRACK2 OF componentType
;
typeList
: indexType (COMMA indexType)*
;
indexType
: simpleType
;
componentType
: type
;
recordType
: RECORD fieldList END
;
fieldList
: fixedPart (SEMI variantPart)?
| variantPart
;
fixedPart
: recordSection (SEMI recordSection)*
;
recordSection
: identifierList COLON type
;
variantPart
: CASE tag OF variant (SEMI variant)*
;
tag
: identifier COLON typeIdentifier
| typeIdentifier
;
variant
: constList COLON LPAREN fieldList RPAREN
;
setType
: SET OF baseType
;
baseType
: simpleType
;
fileType
: FILE OF type
| FILE
;
pointerType
: POINTER typeIdentifier
;
variableDeclarationPart
: VAR variableDeclaration (SEMI variableDeclaration)* SEMI
;
variableDeclaration
: identifierList COLON type
;
procedureAndFunctionDeclarationPart
: procedureOrFunctionDeclaration SEMI
;
procedureOrFunctionDeclaration
: procedureDeclaration
| functionDeclaration
;
procedureDeclaration
: PROCEDURE identifier (formalParameterList)? SEMI block
;
formalParameterList
: LPAREN formalParameterSection (SEMI formalParameterSection)* RPAREN
;
formalParameterSection
: parameterGroup
| VAR parameterGroup
| FUNCTION parameterGroup
| PROCEDURE parameterGroup
;
parameterGroup
: identifierList COLON typeIdentifier
;
identifierList
: identifier (COMMA identifier)*
;
constList
: constant (COMMA constant)*
;
functionDeclaration
: FUNCTION identifier (formalParameterList)? COLON resultType SEMI block
;
resultType
: typeIdentifier
;
statement
: label COLON unlabelledStatement
| unlabelledStatement
;
unlabelledStatement
: simpleStatement
| structuredStatement
;
simpleStatement
: assignmentStatement
| procedureStatement
| gotoStatement
| emptyStatement
;
assignmentStatement
: variable ASSIGN expression
;
variable
: (AT identifier | identifier) (LBRACK expression (COMMA expression)* RBRACK | LBRACK2 expression (COMMA expression)* RBRACK2 | DOT identifier | POINTER)*
;
expression
: simpleExpression ((EQUAL | NOT_EQUAL | LT | LE | GE | GT | IN) simpleExpression)*
;
simpleExpression
: term ((PLUS | MINUS | OR) term)*
;
term
: signedFactor ((STAR | SLASH | DIV | MOD | AND) signedFactor)*
;
signedFactor
: (PLUS | MINUS)? factor
;
factor
: variable
| LPAREN expression RPAREN
| functionDesignator
| unsignedConstant
| set
| NOT factor
;
unsignedConstant
: unsignedNumber
| constantChr
| string
| NIL
;
functionDesignator
: identifier LPAREN parameterList RPAREN
;
parameterList
: actualParameter (COMMA actualParameter)*
;
set
: LBRACK elementList RBRACK
| LBRACK2 elementList RBRACK2
;
elementList
: element (COMMA element)*
|
;
element
: expression (DOTDOT expression)?
;
procedureStatement
: identifier (LPAREN parameterList RPAREN)?
;
actualParameter
: expression
;
gotoStatement
: GOTO label
;
emptyStatement
:
;
empty
:/* empty */
;
structuredStatement
: compoundStatement
| conditionalStatement
| repetetiveStatement
| withStatement
;
compoundStatement
: BEGIN statements END
;
statements
: statement (SEMI statement)*
;
conditionalStatement
: ifStatement
| caseStatement
;
ifStatement
: IF expression THEN statement (: ELSE statement)?
;
caseStatement
: CASE expression OF caseListElement (SEMI caseListElement)* (SEMI ELSE statements)? END
;
caseListElement
: constList COLON statement
;
repetetiveStatement
: whileStatement
| repeatStatement
| forStatement
;
whileStatement
: WHILE expression DO statement
;
repeatStatement
: REPEAT statements UNTIL expression
;
forStatement
: FOR identifier ASSIGN forList DO statement
;
forList
: initialValue (TO | DOWNTO) finalValue
;
initialValue
: expression
;
finalValue
: expression
;
withStatement
: WITH recordVariableList DO statement
;
recordVariableList
: variable (COMMA variable)*
;
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')
;
AND
: A N D
;
ARRAY
: A R R A Y
;
BEGIN
: B E G I N
;
BOOLEAN
: B O O L E A N
;
CASE
: C A S E
;
CHAR
: C H A R
;
CHR
: C H R
;
CONST
: C O N S T
;
DIV
: D I V
;
DO
: D O
;
DOWNTO
: D O W N T O
;
ELSE
: E L S E
;
END
: E N D
;
FILE
: F I L E
;
FOR
: F O R
;
FUNCTION
: F U N C T I O N
;
GOTO
: G O T O
;
IF
: I F
;
IN
: I N
;
INTEGER
: I N T E G E R
;
LABEL
: L A B E L
;
MOD
: M O D
;
NIL
: N I L
;
NOT
: N O T
;
OF
: O F
;
OR
: O R
;
PACKED
: P A C K E D
;
PROCEDURE
: P R O C E D U R E
;
PROGRAM
: P R O G R A M
;
REAL
: R E A L
;
RECORD
: R E C O R D
;
REPEAT
: R E P E A T
;
SET
: S E T
;
THEN
: T H E N
;
TO
: T O
;
TYPE
: T Y P E
;
UNTIL
: U N T I L
;
VAR
: V A R
;
WHILE
: W H I L E
;
WITH
: W I T H
;
PLUS
: '+'
;
MINUS
: '-'
;
STAR
: '*'
;
SLASH
: '/'
;
ASSIGN
: ':='
;
COMMA
: ','
;
SEMI
: ';'
;
COLON
: ':'
;
EQUAL
: '='
;
NOT_EQUAL
: '<>'
;
LT
: '<'
;
LE
: '<='
;
GE
: '>='
;
GT
: '>'
;
LPAREN
: '('
;
RPAREN
: ')'
;
LBRACK
: '['
;
LBRACK2
: '(.'
;
RBRACK
: ']'
;
RBRACK2
: '.)'
;
POINTER
: '^'
;
AT
: '@'
;
DOT
: '.'
;
DOTDOT
: '..'
;
LCURLY
: '{'
;
RCURLY
: '}'
;
UNIT
: U N I T
;
INTERFACE
: I N T E R F A C E
;
USES
: U S E S
;
STRING
: S T R I N G
;
IMPLEMENTATION
: I M P L E M E N T A T I O N
;
WS
: [ \t\r\n] -> skip
;
COMMENT_1
: '(*' .*? '*)' -> skip
;
COMMENT_2
: '{' .*? '}' -> skip
;
IDENT
: ('a' .. 'z' | 'A' .. 'Z') ('a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_')*
;
STRING_LITERAL
: '\'' ('\'\'' | ~ ('\''))* '\''
;
NUM_INT
: ('0' .. '9') + (('.' ('0' .. '9') + (EXPONENT)?)? | EXPONENT)
;
fragment EXPONENT
: ('e') ('+' | '-')? ('0' .. '9') +
;
|
clean up pascal
|
clean up pascal
|
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
|
fcbdb241316e9bc7dbadc61eea7373831b100975
|
turin-parser/src/main/antlr4/me/tomassetti/parser/antlr/Turin.g4
|
turin-parser/src/main/antlr4/me/tomassetti/parser/antlr/Turin.g4
|
grammar Turin;
@header {
}
turinFile:
namespace=namespaceDecl nls
(members=fileMember)+
EOF;
// Base
nls: NL+;
qualifiedId:
(parts+=ID '.')* parts+=ID;
//
namespaceDecl:
'namespace' name=qualifiedId;
//
typeUsage:
ref=TID
| arrayBase=typeUsage '[]';
//
propertyDeclaration:
'property' type=typeUsage ':' name=ID nls;
propertyReference:
'property' name=ID nls;
typeMember:
propertyDeclaration | propertyReference;
typeDeclaration:
'type' name=TID '{' nls
(typeMembers += typeMember)*
'}' nls;
//
actualParam:
expression | name='ID' '=' expression;
functionCall:
name=ID '(' params+=actualParam (',' params+=actualParam)* ')' ;
expression:
functionCall | creation | stringLiteral | intLiteral;
stringLiteral:
STRING;
intLiteral:
INT;
fragment
StringCharacters
: StringCharacter+
;
fragment
StringCharacter
: ~["]
;
creation:
name=TID '(' params+=actualParam (',' params+=actualParam)* ')' ;
varDecl :
'val' (type=typeUsage ':')? name=ID '=' value=expression nls;
expressionStmt:
expression nls;
statement :
varDecl | expressionStmt ;
//
formalParam :
type=typeUsage name=ID;
//
program:
'program' name=TID '(' params+=formalParam (',' params+=formalParam)* ')' '{' nls
(statements += statement)*
'}' nls;
//
fileMember:
propertyDeclaration | typeDeclaration | program;
ID: 'a'..'z' ('A'..'Z' | 'a'..'z' | '_')*;
// Only for types
TID: 'A'..'Z' ('A'..'Z' | 'a'..'z' | '_')*;
INT: '0'|('1'..'9')('0'..'9')*;
STRING: '"' ~["]* '"';
STRING_START: '"';
WS: (' ' | '\t')+ -> skip;
NL: '\r'? '\n';
COMMENT
: '/*' .*? '*/' -> skip
;
LINE_COMMENT
: '//' ~[\r\n]* -> skip
;
|
grammar Turin;
@header {
}
turinFile:
namespace=namespaceDecl nls
(members=fileMember)+
EOF;
// Base
nls: NL+;
qualifiedId:
(parts+=ID POINT)* parts+=ID;
//
namespaceDecl:
NAMESPACE_KW name=qualifiedId;
//
typeUsage:
ref=TID
| arrayBase=typeUsage LSQUARE RSQUARE;
//
propertyDeclaration:
PROPERTY_KW type=typeUsage COLON name=ID nls;
propertyReference:
PROPERTY_KW name=ID nls;
typeMember:
propertyDeclaration | propertyReference;
typeDeclaration:
TYPE_KW name=TID LBRACKET nls
(typeMembers += typeMember)*
RBRACKET nls;
//
actualParam:
expression | name=ID ASSIGNMENT expression;
functionCall:
name=ID LPAREN params+=actualParam (COMMA params+=actualParam)* RPAREN ;
expression:
functionCall | creation | stringLiteral | intLiteral;
stringLiteral:
STRING;
intLiteral:
INT;
fragment
StringCharacters
: StringCharacter+
;
fragment
StringCharacter
: ~["]
;
creation:
name=TID LPAREN params+=actualParam (COMMA params+=actualParam)* RPAREN ;
varDecl :
VAL_KW (type=typeUsage COLON)? name=ID ASSIGNMENT value=expression nls;
expressionStmt:
expression nls;
statement :
varDecl | expressionStmt ;
//
formalParam :
type=typeUsage name=ID;
//
program:
PROGRAM_KW name=TID LPAREN params+=formalParam (COMMA params+=formalParam)* RPAREN LBRACKET nls
(statements += statement)*
RBRACKET nls;
//
fileMember:
propertyDeclaration | typeDeclaration | program;
NAMESPACE_KW: 'namespace';
PROGRAM_KW: 'program';
PROPERTY_KW: 'property';
TYPE_KW: 'type';
VAL_KW: 'val';
LPAREN: '(';
RPAREN: ')';
LBRACKET: '{';
RBRACKET: '}';
LSQUARE: '[';
RSQUARE: ']';
COMMA: ',';
POINT: '.';
COLON: ':';
EQUAL: '==';
ASSIGNMENT: '=';
ID: 'a'..'z' ('A'..'Z' | 'a'..'z' | '_')*;
// Only for types
TID: 'A'..'Z' ('A'..'Z' | 'a'..'z' | '_')*;
INT: '0'|('1'..'9')('0'..'9')*;
STRING: '"' ~["]* '"';
STRING_START: '"';
WS: (' ' | '\t')+ -> skip;
NL: '\r'? '\n';
COMMENT
: '/*' .*? '*/' -> skip
;
LINE_COMMENT
: '//' ~[\r\n]* -> skip
;
|
declare all tokens
|
declare all tokens
|
ANTLR
|
apache-2.0
|
ftomassetti/turin-programming-language,ftomassetti/turin-programming-language
|
fd577f3e157ff022746ca131bb94d53dd29a5564
|
sharding-jdbc-ddl-parser/src/main/antlr4/io/shardingsphere/parser/antlr/mysql/MySQLDML.g4
|
sharding-jdbc-ddl-parser/src/main/antlr4/io/shardingsphere/parser/antlr/mysql/MySQLDML.g4
|
grammar MySQLDML;
import MySQLKeyword, DataType, Keyword, BaseRule, MySQLDQL, DQLBase, DMLBase,Symbol;
selectSpec:
(ALL | DISTINCT | DISTINCTROW)?
HIGH_PRIORITY?
STRAIGHT_JOIN?
SQL_SMALL_RESULT?
SQL_BIG_RESULT?
SQL_BUFFER_RESULT?
(SQL_CACHE | SQL_NO_CACHE)?
SQL_CALC_FOUND_ROWS?
;
caseExpress:
caseCond
|caseComp
;
caseComp:
CASE simpleExpr caseWhenComp+ elseResult? END
;
caseWhenComp:
WHEN simpleExpr THEN caseResult
;
caseCond:
CASE whenResult+ elseResult? END
;
whenResult:
WHEN booleanPrimary THEN caseResult
;
elseResult:
ELSE caseResult
;
caseResult:
expr
;
selectExpr:
(bitExpr| caseExpress) AS? alias?
;
//delete
deleteClause:
DELETE deleteSpec (fromMulti| fromSingle)
;
fromSingle:
FROM ID partitionClause?
;
fromMulti:
(ID ('.*')? (COMMA ID ('.*')?)* FROM tableReferences)
|FROM (ID ('.*')? (COMMA ID ('.*')?)* USING tableReferences)
;
deleteSpec:
LOW_PRIORITY?
|QUICK?
|IGNORE?
;
// define insert rule
insert:
insertClause INTO? ID partitionClause?
(setClause | columnClause) onDuplicateClause?
;
insertClause:
INSERT insertSpec?
;
insertSpec:
LOW_PRIORITY
| DELAYED
| HIGH_PRIORITY IGNORE
;
columnClause:
idListWithEmpty? (valueClause | select)
;
valueClause:
(VALUES | VALUE) valueListWithParen (COMMA valueListWithParen)*
;
setClause:
SET assignmentList
;
onDuplicateClause:
ON DUPLICATE KEY UPDATE assignmentList
;
itemListWithEmpty:
(LEFT_PAREN RIGHT_PAREN)
|idList
;
assignmentList:
assignment (COMMA assignment)*
;
assignment:
columnName EQ_OR_ASSIGN value;
//override update rule
updateClause:
UPDATE updateSpec tableReferences
;
updateSpec:
LOW_PRIORITY? IGNORE?
;
|
grammar MySQLDML;
import MySQLKeyword, DataType, Keyword, BaseRule, MySQLDQL, DQLBase, DMLBase,Symbol;
caseExpress:
caseCond
|caseComp
;
caseComp:
CASE simpleExpr caseWhenComp+ elseResult? END
;
caseWhenComp:
WHEN simpleExpr THEN caseResult
;
caseCond:
CASE whenResult+ elseResult? END
;
whenResult:
WHEN booleanPrimary THEN caseResult
;
elseResult:
ELSE caseResult
;
caseResult:
expr
;
selectExpr:
(bitExpr| caseExpress) AS? alias?
;
//delete
deleteClause:
DELETE deleteSpec (fromMulti| fromSingle)
;
fromSingle:
FROM ID partitionClause?
;
fromMulti:
(ID ('.*')? (COMMA ID ('.*')?)* FROM tableReferences)
|FROM (ID ('.*')? (COMMA ID ('.*')?)* USING tableReferences)
;
deleteSpec:
LOW_PRIORITY?
|QUICK?
|IGNORE?
;
// define insert rule
insert:
insertClause INTO? ID partitionClause?
(setClause | columnClause) onDuplicateClause?
;
insertClause:
INSERT insertSpec?
;
insertSpec:
LOW_PRIORITY
| DELAYED
| HIGH_PRIORITY IGNORE
;
columnClause:
idListWithEmpty? (valueClause | select)
;
valueClause:
(VALUES | VALUE) valueListWithParen (COMMA valueListWithParen)*
;
setClause:
SET assignmentList
;
onDuplicateClause:
ON DUPLICATE KEY UPDATE assignmentList
;
itemListWithEmpty:
(LEFT_PAREN RIGHT_PAREN)
|idList
;
assignmentList:
assignment (COMMA assignment)*
;
assignment:
columnName EQ_OR_ASSIGN value;
//override update rule
updateClause:
UPDATE updateSpec tableReferences
;
updateSpec:
LOW_PRIORITY? IGNORE?
;
|
Remove repeat rule
|
Remove repeat rule
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
f4158db161e344ebea17096cbde9f3ee380c148f
|
projects/batfish/src/org/batfish/grammar/cisco/Cisco_aaa.g4
|
projects/batfish/src/org/batfish/grammar/cisco/Cisco_aaa.g4
|
parser grammar Cisco_aaa;
import Cisco_common;
options {
tokenVocab = CiscoLexer;
}
aaa_accounting
:
ACCOUNTING
(
aaa_accounting_commands
| aaa_accounting_connection
| aaa_accounting_default
| aaa_accounting_delay_start
| aaa_accounting_exec
| aaa_accounting_nested
| aaa_accounting_network
| aaa_accounting_send
| aaa_accounting_system
| aaa_accounting_update
)
;
aaa_accounting_commands
:
COMMANDS
(
level = DEC
)?
(
DEFAULT
| list = variable
) aaa_accounting_method NEWLINE
;
aaa_accounting_connection
:
CONNECTION
(
DEFAULT
| list = variable
) aaa_accounting_method NEWLINE
;
aaa_accounting_default
:
DEFAULT
(
aaa_accounting_default_group
| aaa_accounting_default_local
)
;
aaa_accounting_default_group
:
GROUP
(
groups += variable
)+ NEWLINE
;
aaa_accounting_default_local
:
LOCAL NEWLINE
;
aaa_accounting_delay_start
:
DELAY_START
(
ALL
| VRF name = variable
)?
(
EXTENDED_DELAY DEC
)? NEWLINE
;
aaa_accounting_exec
:
EXEC
(
DEFAULT
| list = variable
) aaa_accounting_method NEWLINE
;
aaa_accounting_method
:
aaa_accounting_method_none
| aaa_accounting_method_start_stop
| aaa_accounting_method_stop_only
| aaa_accounting_method_wait_start
;
aaa_accounting_method_none
:
NONE
;
aaa_accounting_method_start_stop
:
START_STOP aaa_accounting_method_target
;
aaa_accounting_method_stop_only
:
STOP_ONLY aaa_accounting_method_target
;
aaa_accounting_method_wait_start
:
WAIT_START aaa_accounting_method_target
;
aaa_accounting_method_target
:
BROADCAST?
(
GROUP
(
RADIUS
| TAC_PLUS
(
NONE
)?
| TACACS_PLUS
| groups += variable
)
)+
;
aaa_accounting_nested
:
NESTED NEWLINE
;
aaa_accounting_network
:
NETWORK
(
DEFAULT
| list = variable
) aaa_accounting_method NEWLINE
;
aaa_accounting_send
:
SEND
(
aaa_accounting_send_counters
| aaa_accounting_send_stop_record
)
;
aaa_accounting_send_counters
:
COUNTERS IPV6 NEWLINE
;
aaa_accounting_send_stop_record
:
STOP_RECORD
(
ALWAYS
|
(
AUTHENTICATION
(
(
FAILURE
|
(
SUCCESS REMOTE_SERVER
)
)
(
VRF name = variable
)?
)
)
) NEWLINE
;
aaa_accounting_system
:
SYSTEM
(
DEFAULT
| list = variable
) aaa_accounting_method NEWLINE
;
aaa_accounting_update
:
UPDATE NEWINFO NEWLINE
;
aaa_authentication
:
AUTHENTICATION
(
aaa_authentication_banner
| aaa_authentication_dot1x
| aaa_authentication_enable
| aaa_authentication_http
| aaa_authentication_include
| aaa_authentication_login
| aaa_authentication_ppp
| aaa_authentication_serial
| aaa_authentication_ssh
| aaa_authentication_telnet
)
;
aaa_authentication_asa_console
:
CONSOLE group = variable? TACACS_PLUS_ASA? LOCAL_ASA? NEWLINE
;
aaa_authentication_banner
:
BANNER banner
;
aaa_authentication_dot1x
:
DOT1X
(
DEFAULT
| list = variable
) aaa_authentication_list_method+ NEWLINE
;
aaa_authentication_enable
:
ENABLE
(
(
DEFAULT aaa_authentication_list_method+
| IMPLICIT_USER
) NEWLINE
| aaa_authentication_asa_console
)
;
aaa_authentication_http
:
HTTP aaa_authentication_asa_console
;
aaa_authentication_include
:
INCLUDE name = variable
(
FORWARD_SLASH DEC
)? iface = variable srcip = IP_ADDRESS srcmask = IP_ADDRESS
(
dstip = IP_ADDRESS dstmask = IP_ADDRESS
)? group = variable NEWLINE
;
aaa_authentication_list_method
:
(
aaa_authentication_list_method_enable
| aaa_authentication_list_method_fallback
| aaa_authentication_list_method_group
| aaa_authentication_list_method_if_needed
| aaa_authentication_list_method_line
| aaa_authentication_list_method_local
| aaa_authentication_list_method_none
| aaa_authentication_list_method_tacacs_local
| aaa_authentication_list_method_tacacs_plus
)
;
aaa_authentication_list_method_enable
:
ENABLE
;
aaa_authentication_list_method_fallback
:
FALLBACK ERROR LOCAL
;
aaa_authentication_list_method_group
:
GROUP groups += ~NEWLINE
(
groups += ~( NEWLINE | ENABLE | FALLBACK | GROUP | IF_NEEDED | LINE |
LOCAL | NONE | TACACS_PLUS )
)*
;
aaa_authentication_list_method_if_needed
:
IF_NEEDED
;
aaa_authentication_list_method_line
:
LINE
;
aaa_authentication_list_method_local
:
LOCAL
;
aaa_authentication_list_method_none
:
NONE
;
aaa_authentication_list_method_tacacs_local
:
TACACS LOCAL
;
aaa_authentication_list_method_tacacs_plus
:
TACACS_PLUS
;
aaa_authentication_login
:
LOGIN
(
aaa_authentication_login_ascii_authentication
| aaa_authentication_login_chap
| aaa_authentication_login_error_enable
| aaa_authentication_login_invalid_username_log
| aaa_authentication_login_list
| aaa_authentication_login_mschap
| aaa_authentication_login_mschapv2
| aaa_authentication_login_privilege_mode
)
;
aaa_authentication_login_ascii_authentication
:
ASCII_AUTHENTICATION NEWLINE
;
aaa_authentication_login_chap
:
CHAP ENABLE NEWLINE
;
aaa_authentication_login_error_enable
:
ERROR_ENABLE NEWLINE
;
aaa_authentication_login_invalid_username_log
:
INVALID_USERNAME_LOG NEWLINE
;
aaa_authentication_login_list
:
(
DEFAULT
| name = variable
) aaa_authentication_list_method+ NEWLINE
;
aaa_authentication_login_mschap
:
MSCHAP ENABLE NEWLINE
;
aaa_authentication_login_mschapv2
:
MSCHAPV2 ENABLE NEWLINE
;
aaa_authentication_login_privilege_mode
:
PRIVILEGE_MODE NEWLINE
;
aaa_authentication_ppp
:
PPP
(
DEFAULT
| list = variable
) aaa_authentication_list_method+ NEWLINE
;
aaa_authentication_serial
:
SERIAL aaa_authentication_asa_console
;
aaa_authentication_ssh
:
SSH aaa_authentication_asa_console
;
aaa_authentication_telnet
:
TELNET aaa_authentication_asa_console
;
aaa_authorization
:
AUTHORIZATION
(
aaa_authorization_commands
| aaa_authorization_config_commands
| aaa_authorization_console
| aaa_authorization_exec
| aaa_authorization_include
| aaa_authorization_network
| aaa_authorization_ssh_certificate
| aaa_authorization_ssh_publickey
)
;
aaa_authorization_commands
:
COMMANDS level = DEC?
(
CONSOLE
| DEFAULT
| list = variable
) aaa_authorization_method
;
aaa_authorization_config_commands
:
CONFIG_COMMANDS
(
(
(
CONSOLE
| DEFAULT
) aaa_authorization_method
)
| NEWLINE
)
;
aaa_authorization_console
:
CONSOLE NEWLINE
;
aaa_authorization_exec
:
EXEC
(
DEFAULT
| list = variable
) aaa_authorization_method
;
aaa_authorization_include
:
INCLUDE name = variable
(
FORWARD_SLASH DEC
)? iface = variable srcip = IP_ADDRESS srcmask = IP_ADDRESS
(
dstip = IP_ADDRESS dstmask = IP_ADDRESS
)? group = variable NEWLINE
;
aaa_authorization_network
:
NETWORK
(
DEFAULT
| list = variable
) aaa_authorization_method
;
aaa_authorization_ssh_certificate
:
SSH_CERTIFICATE DEFAULT aaa_authorization_method
;
aaa_authorization_method
:
(
(
GROUP?
(
groups += variable
)+
)
| LOCAL
| NONE
) NEWLINE
;
aaa_authorization_ssh_publickey
:
SSH_PUBLICKEY DEFAULT aaa_authorization_method
;
aaa_default_taskgroup
:
DEFAULT_TASKGROUP ~NEWLINE* NEWLINE
;
aaa_group
:
GROUP SERVER
(
LDAP
| RADIUS
| TACACS_PLUS
) name = variable NEWLINE
(
aaa_group_deadtime
| aaa_group_ip_tacacs
| aaa_group_server
| aaa_group_server_private
| aaa_group_source_interface
| aaa_group_use_vrf
| aaa_group_vrf
)*
;
aaa_group_deadtime
:
DEADTIME minutes = DEC NEWLINE
;
aaa_group_ip_tacacs
:
IP TACACS SOURCE_INTERFACE interface_name NEWLINE
;
aaa_group_server
:
SERVER
(
IP_ADDRESS
| IPV6_ADDRESS
| name = variable
)
(
PORT DEC
)? NEWLINE
;
aaa_group_server_private
:
SERVER_PRIVATE
(
IP_ADDRESS
| IPV6_ADDRESS
| name = variable
)
(
PORT DEC
)? NEWLINE
;
aaa_group_source_interface
:
SOURCE_INTERFACE interface_name DEC? NEWLINE
;
aaa_group_use_vrf
:
USE_VRF
(
DEFAULT
| MANAGEMENT
| name = variable
) NEWLINE
;
aaa_group_vrf
:
VRF
(
DEFAULT
| MANAGEMENT
| name = variable
) NEWLINE
;
aaa_new_model
:
NEW_MODEL NEWLINE
;
aaa_session_id
:
SESSION_ID
(
COMMON
| UNIQUE
) NEWLINE
;
aaa_user
:
USER DEFAULT_ROLE NEWLINE
;
null_aaa_substanza
:
aaa_default_taskgroup
;
s_aaa
:
AAA
(
aaa_accounting
| aaa_authentication
| aaa_authorization
| aaa_group
| aaa_new_model
| aaa_session_id
| aaa_user
| null_aaa_substanza
)
;
|
parser grammar Cisco_aaa;
import Cisco_common;
options {
tokenVocab = CiscoLexer;
}
aaa_accounting
:
ACCOUNTING
(
aaa_accounting_commands
| aaa_accounting_connection
| aaa_accounting_default
| aaa_accounting_delay_start
| aaa_accounting_exec
| aaa_accounting_nested
| aaa_accounting_network
| aaa_accounting_send
| aaa_accounting_system
| aaa_accounting_update
)
;
aaa_accounting_commands
:
COMMANDS
(
level = DEC
)?
(
DEFAULT
| list = variable
) aaa_accounting_method NEWLINE
;
aaa_accounting_connection
:
CONNECTION
(
DEFAULT
| list = variable
) aaa_accounting_method NEWLINE
;
aaa_accounting_default
:
DEFAULT
(
aaa_accounting_default_group
| aaa_accounting_default_local
)
;
aaa_accounting_default_group
:
GROUP
(
groups += variable
)+ NEWLINE
;
aaa_accounting_default_local
:
LOCAL NEWLINE
;
aaa_accounting_delay_start
:
DELAY_START
(
ALL
| VRF name = variable
)?
(
EXTENDED_DELAY DEC
)? NEWLINE
;
aaa_accounting_exec
:
EXEC
(
DEFAULT
| list = variable
) aaa_accounting_method NEWLINE
;
aaa_accounting_method
:
aaa_accounting_method_none
| aaa_accounting_method_start_stop
| aaa_accounting_method_stop_only
| aaa_accounting_method_wait_start
;
aaa_accounting_method_none
:
NONE
;
aaa_accounting_method_start_stop
:
START_STOP aaa_accounting_method_target
;
aaa_accounting_method_stop_only
:
STOP_ONLY aaa_accounting_method_target
;
aaa_accounting_method_wait_start
:
WAIT_START aaa_accounting_method_target
;
aaa_accounting_method_target
:
BROADCAST?
(
GROUP
(
RADIUS
| TAC_PLUS
(
NONE
)?
| TACACS_PLUS
| groups += variable
)
)+
;
aaa_accounting_nested
:
NESTED NEWLINE
;
aaa_accounting_network
:
NETWORK
(
DEFAULT
| list = variable
) aaa_accounting_method NEWLINE
;
aaa_accounting_send
:
SEND
(
aaa_accounting_send_counters
| aaa_accounting_send_stop_record
)
;
aaa_accounting_send_counters
:
COUNTERS IPV6 NEWLINE
;
aaa_accounting_send_stop_record
:
STOP_RECORD
(
ALWAYS
|
(
AUTHENTICATION
(
(
FAILURE
|
(
SUCCESS REMOTE_SERVER
)
)
(
VRF name = variable
)?
)
)
) NEWLINE
;
aaa_accounting_system
:
SYSTEM
(
DEFAULT
| list = variable
) aaa_accounting_method NEWLINE
;
aaa_accounting_update
:
UPDATE NEWINFO NEWLINE
;
aaa_authentication
:
AUTHENTICATION
(
aaa_authentication_banner
| aaa_authentication_dot1x
| aaa_authentication_enable
| aaa_authentication_http
| aaa_authentication_include
| aaa_authentication_login
| aaa_authentication_ppp
| aaa_authentication_serial
| aaa_authentication_ssh
| aaa_authentication_telnet
)
;
aaa_authentication_asa_console
:
CONSOLE group = variable? TACACS_PLUS_ASA? LOCAL_ASA? NEWLINE
;
aaa_authentication_banner
:
BANNER banner
;
aaa_authentication_dot1x
:
DOT1X
(
DEFAULT
| list = variable
) aaa_authentication_list_method+ NEWLINE
;
aaa_authentication_enable
:
ENABLE
(
(
DEFAULT aaa_authentication_list_method+
| IMPLICIT_USER
) NEWLINE
| aaa_authentication_asa_console
)
;
aaa_authentication_http
:
HTTP aaa_authentication_asa_console
;
aaa_authentication_include
:
INCLUDE name = variable
(
FORWARD_SLASH DEC
)? iface = variable srcip = IP_ADDRESS srcmask = IP_ADDRESS
(
dstip = IP_ADDRESS dstmask = IP_ADDRESS
)? group = variable NEWLINE
;
aaa_authentication_list_method
:
(
aaa_authentication_list_method_enable
| aaa_authentication_list_method_fallback
| aaa_authentication_list_method_group
| aaa_authentication_list_method_if_needed
| aaa_authentication_list_method_line
| aaa_authentication_list_method_local
| aaa_authentication_list_method_none
| aaa_authentication_list_method_tacacs_local
| aaa_authentication_list_method_tacacs_plus
)
;
aaa_authentication_list_method_enable
:
ENABLE
;
aaa_authentication_list_method_fallback
:
FALLBACK ERROR LOCAL
;
aaa_authentication_list_method_group
:
GROUP groups += ~NEWLINE
(
groups += ~( NEWLINE | ENABLE | FALLBACK | GROUP | IF_NEEDED | LINE |
LOCAL | NONE | TACACS_PLUS )
)*
;
aaa_authentication_list_method_if_needed
:
IF_NEEDED
;
aaa_authentication_list_method_line
:
LINE
;
aaa_authentication_list_method_local
:
LOCAL
;
aaa_authentication_list_method_none
:
NONE
;
aaa_authentication_list_method_tacacs_local
:
TACACS LOCAL
;
aaa_authentication_list_method_tacacs_plus
:
TACACS_PLUS
;
aaa_authentication_login
:
LOGIN
(
aaa_authentication_login_ascii_authentication
| aaa_authentication_login_chap
| aaa_authentication_login_error_enable
| aaa_authentication_login_invalid_username_log
| aaa_authentication_login_list
| aaa_authentication_login_mschap
| aaa_authentication_login_mschapv2
| aaa_authentication_login_privilege_mode
)
;
aaa_authentication_login_ascii_authentication
:
ASCII_AUTHENTICATION NEWLINE
;
aaa_authentication_login_chap
:
CHAP ENABLE NEWLINE
;
aaa_authentication_login_error_enable
:
ERROR_ENABLE NEWLINE
;
aaa_authentication_login_invalid_username_log
:
INVALID_USERNAME_LOG NEWLINE
;
aaa_authentication_login_list
:
(
DEFAULT
| name = variable
) aaa_authentication_list_method+ NEWLINE
;
aaa_authentication_login_mschap
:
MSCHAP ENABLE NEWLINE
;
aaa_authentication_login_mschapv2
:
MSCHAPV2 ENABLE NEWLINE
;
aaa_authentication_login_privilege_mode
:
PRIVILEGE_MODE NEWLINE
;
aaa_authentication_ppp
:
PPP
(
DEFAULT
| list = variable
) aaa_authentication_list_method+ NEWLINE
;
aaa_authentication_serial
:
SERIAL aaa_authentication_asa_console
;
aaa_authentication_ssh
:
SSH aaa_authentication_asa_console
;
aaa_authentication_telnet
:
TELNET aaa_authentication_asa_console
;
aaa_authorization
:
AUTHORIZATION
(
aaa_authorization_commands
| aaa_authorization_config_commands
| aaa_authorization_console
| aaa_authorization_exec
| aaa_authorization_include
| aaa_authorization_network
| aaa_authorization_ssh_certificate
| aaa_authorization_ssh_publickey
)
;
aaa_authorization_commands
:
COMMANDS level = DEC?
(
CONSOLE
| DEFAULT
| list = variable
) aaa_authorization_method
;
aaa_authorization_config_commands
:
CONFIG_COMMANDS
(
(
(
CONSOLE
| DEFAULT
) aaa_authorization_method
)
| NEWLINE
)
;
aaa_authorization_console
:
CONSOLE NEWLINE
;
aaa_authorization_exec
:
EXEC
(
DEFAULT
| list = variable
) aaa_authorization_method
;
aaa_authorization_include
:
INCLUDE name = variable
(
FORWARD_SLASH DEC
)? iface = variable srcip = IP_ADDRESS srcmask = IP_ADDRESS
(
dstip = IP_ADDRESS dstmask = IP_ADDRESS
)? group = variable NEWLINE
;
aaa_authorization_method
:
(
(
GROUP?
(
groups += ~( NEWLINE | LOCAL | NONE )
)+
)
| LOCAL
| NONE
)* NEWLINE
;
aaa_authorization_network
:
NETWORK
(
DEFAULT
| list = variable
) aaa_authorization_method
;
aaa_authorization_ssh_certificate
:
SSH_CERTIFICATE DEFAULT aaa_authorization_method
;
aaa_authorization_ssh_publickey
:
SSH_PUBLICKEY DEFAULT aaa_authorization_method
;
aaa_default_taskgroup
:
DEFAULT_TASKGROUP ~NEWLINE* NEWLINE
;
aaa_group
:
GROUP SERVER
(
LDAP
| RADIUS
| TACACS_PLUS
) name = variable NEWLINE
(
aaa_group_deadtime
| aaa_group_ip_tacacs
| aaa_group_server
| aaa_group_server_private
| aaa_group_source_interface
| aaa_group_use_vrf
| aaa_group_vrf
)*
;
aaa_group_deadtime
:
DEADTIME minutes = DEC NEWLINE
;
aaa_group_ip_tacacs
:
IP TACACS SOURCE_INTERFACE interface_name NEWLINE
;
aaa_group_server
:
SERVER
(
IP_ADDRESS
| IPV6_ADDRESS
| name = variable
)
(
PORT DEC
)? NEWLINE
;
aaa_group_server_private
:
SERVER_PRIVATE
(
IP_ADDRESS
| IPV6_ADDRESS
| name = variable
)
(
PORT DEC
)? NEWLINE
;
aaa_group_source_interface
:
SOURCE_INTERFACE interface_name DEC? NEWLINE
;
aaa_group_use_vrf
:
USE_VRF
(
DEFAULT
| MANAGEMENT
| name = variable
) NEWLINE
;
aaa_group_vrf
:
VRF
(
DEFAULT
| MANAGEMENT
| name = variable
) NEWLINE
;
aaa_new_model
:
NEW_MODEL NEWLINE
;
aaa_session_id
:
SESSION_ID
(
COMMON
| UNIQUE
) NEWLINE
;
aaa_user
:
USER DEFAULT_ROLE NEWLINE
;
null_aaa_substanza
:
aaa_default_taskgroup
;
s_aaa
:
AAA
(
aaa_accounting
| aaa_authentication
| aaa_authorization
| aaa_group
| aaa_new_model
| aaa_session_id
| aaa_user
| null_aaa_substanza
)
;
|
fix aaa_authorization_method
|
fix aaa_authorization_method
|
ANTLR
|
apache-2.0
|
arifogel/batfish,dhalperi/batfish,dhalperi/batfish,intentionet/batfish,arifogel/batfish,intentionet/batfish,dhalperi/batfish,intentionet/batfish,intentionet/batfish,arifogel/batfish,batfish/batfish,batfish/batfish,intentionet/batfish,batfish/batfish
|
b22b2ae4e7c660f25988f6b7a021c3d264670b79
|
src/main/antlr/BrygParser.g4
|
src/main/antlr/BrygParser.g4
|
parser grammar BrygParser;
// TODO: Find a way to do: if (...) a else b
options {
tokenVocab = BrygLexer;
}
@header {
package io.collap.bryg.parser;
}
start
: (inDeclaration | NEWLINE)*
(statement | NEWLINE)*
(fragmentFunction | NEWLINE)*
EOF // EOF is needed for SLL(*) parsing! Otherwise no exception is thrown, which is needed to induce LL(*) parsing.
;
inDeclaration
: qualifier=(IN | OPT) type id
NEWLINE
;
statement
: ifStatement
| eachStatement
| whileStatement
| variableDeclaration
NEWLINE
| blockFunctionCall
| expression
NEWLINE
| statementFunctionCall /* This rule has to be placed after expression, because otherwise an expression
like a - 7 would be interpreted as a statementFunctionCall with an arithmetic
negation (that leads to the number -7) instead of a binary subtraction. */
| templateFragmentCall
;
/**
* This rule is executed separately when the compiler finds an unescaped interpolation sequence (\{...}) in a string.
*/
interpolation
: expression NEWLINE
;
fragmentFunction
: FRAG id NEWLINE
fragmentBlock
;
fragmentBlock
: INDENT
(inDeclaration | NEWLINE)*
(statement | NEWLINE)*
DEDENT
;
closure
: INDENT
(inDeclaration | NEWLINE)*
(statement | NEWLINE)*
DEDENT
;
expression
: literal # literalExpression
| '(' expression ')' # expressionPrecedenceOrder
| expression '.' id # accessExpression
| expression '.' functionCall # methodCallExpression
| functionCall # functionCallExpression
| variable # variableExpression
| '(' type ')' expression # castExpression
| expression op=('++' | '--') # unaryPostfixExpression
| ( op=('++' | '--') expression
| '(' op='-' expression ')'
) # unaryPrefixExpression
| op=('~' | NOT) expression # unaryOperationExpression
| expression op=('*' | '/' | '%') expression # binaryMulDivRemExpression
| expression op=('+' | '-') expression # binaryAddSubExpression
| expression op=('<<' | '>>>' | '>>') expression # binaryShiftExpression
| expression op=('<=' | '>=' | '>' | '<') expression # binaryRelationalExpression
| expression 'is' type # binaryIsExpression // TODO: Implement (Before 1.0); Possibly change 'is' back to 'instanceof'.
| expression op=('==' | '!=') expression # binaryEqualityExpression
| expression op=('===' | '!==') expression # binaryReferenceEqualityExpression
| expression '&' expression # binaryBitwiseAndExpression
| expression '^' expression # binaryBitwiseXorExpression
| expression '|' expression # binaryBitwiseOrExpression
| expression AND expression # binaryLogicalAndExpression
| expression OR expression # binaryLogicalOrExpression
| <assoc=right> expression
op=
( '='
| '+='
| '-='
| '*='
| '/='
| '%='
| '&='
| '|='
| '^='
| '>>='
| '>>>='
| '<<='
)
expression # binaryAssignmentExpression
;
ifStatement
: IF
( '(' expression ')' statement // This has to be statement, otherwise an ambiguity is created
// in conjunction with normal parentheses in expressions!
| expression NEWLINE block
)
(ELSE statementOrBlock)?
;
eachStatement
: EACH
( '(' eachHead ')' statementOrBlock
| eachHead NEWLINE block
)
;
eachHead
: type? element=id (',' index=id)? IN expression
;
whileStatement
: WHILE
( '(' condition=expression ')' statement
| condition=expression NEWLINE block
)
;
block
: INDENT
statement*
DEDENT
;
statementOrBlock
: NEWLINE block
| statement
;
variable
: id // Note that it is possible for a recognized variable to be a trivial function.
;
variableDeclaration
: mutability=(MUT | VAL)
type? id
('=' expression)?
;
functionCall
: id argumentList
;
blockFunctionCall
: id argumentList?
NEWLINE block
;
statementFunctionCall
: id argumentList?
statement
;
/* Calls functions of other templates. By default, 'render' is called. */
templateFragmentCall
: templateId frag=id? argumentList?
NEWLINE closure?
;
templateId
: '@' currentPackage='.'? (id '.')* id
;
argumentList
: '(' (argument (',' argument)*)? ')'
;
argument
: argumentId? expression argumentPredicate?
;
argumentId
: id ('-' id)*
;
argumentPredicate
: IF expression
;
literal
: String # stringLiteral
| Integer # integerLiteral
| Long # longLiteral
| Double # doubleLiteral
| Float # floatLiteral
| NULL # nullLiteral
| value=(TRUE | FALSE) # booleanLiteral
;
type
: id
('<' type (',' type)* '>')?
;
id
: Identifier
| '`'
( Identifier
| NOT
| AND
| OR
| IN
| OPT
| IS
| EACH
| WHILE
| ELSE
| IF
| MUT
| VAL
| NULL
| TRUE
| FALSE
)
'`'
;
|
parser grammar BrygParser;
// TODO: Find a way to do: if (...) a else b
options {
tokenVocab = BrygLexer;
}
@header {
package io.collap.bryg.parser;
}
start
: (inDeclaration | NEWLINE)*
(statement | NEWLINE)*
(fragmentFunction | NEWLINE)*
EOF // EOF is needed for SLL(*) parsing! Otherwise no exception is thrown, which is needed to induce LL(*) parsing.
;
inDeclaration
: qualifier=(IN | OPT) type id
NEWLINE
;
statement
: ifStatement
| eachStatement
| whileStatement
| variableDeclaration
NEWLINE
| blockFunctionCall
| expression
NEWLINE
| statementFunctionCall /* This rule has to be placed after expression, because otherwise an expression
like a - 7 would be interpreted as a statementFunctionCall with an arithmetic
negation (that leads to the number -7) instead of a binary subtraction. */
| templateFragmentCall
;
/**
* This rule is executed separately when the compiler finds an unescaped interpolation sequence (\{...}) in a string.
*/
interpolation
: expression NEWLINE
;
fragmentFunction
: FRAG id NEWLINE
fragmentBlock
;
fragmentBlock
: INDENT
(inDeclaration | NEWLINE)*
(statement | NEWLINE)*
DEDENT
;
closure
: INDENT
(inDeclaration | NEWLINE)*
(statement | NEWLINE)*
DEDENT
;
expression
: literal # literalExpression
| '(' expression ')' # expressionPrecedenceOrder
| expression '.' id # accessExpression
| expression '.' functionCall # methodCallExpression
| functionCall # functionCallExpression
| variable # variableExpression
| '(' type ')' expression # castExpression
| expression op=('++' | '--') # unaryPostfixExpression
| ( op=('++' | '--') expression
| '(' op='-' expression ')'
) # unaryPrefixExpression
| op=('~' | NOT) expression # unaryOperationExpression
| expression op=('*' | '/' | '%') expression # binaryMulDivRemExpression
| expression op=('+' | '-') expression # binaryAddSubExpression
| expression op=('<<' | '>>>' | '>>') expression # binaryShiftExpression
| expression op=('<=' | '>=' | '>' | '<') expression # binaryRelationalExpression
| expression 'is' type # binaryIsExpression // TODO: Implement (Before 1.0); Possibly change 'is' back to 'instanceof'.
| expression op=('==' | '!=') expression # binaryEqualityExpression
| expression op=('===' | '!==') expression # binaryReferenceEqualityExpression
| expression '&' expression # binaryBitwiseAndExpression
| expression '^' expression # binaryBitwiseXorExpression
| expression '|' expression # binaryBitwiseOrExpression
| expression AND expression # binaryLogicalAndExpression
| expression OR expression # binaryLogicalOrExpression
| <assoc=right> expression
op=
( '='
| '+='
| '-='
| '*='
| '/='
| '%='
| '&='
| '|='
| '^='
| '>>='
| '>>>='
| '<<='
)
expression # binaryAssignmentExpression
;
ifStatement
: IF
( '(' expression ')' statement // This has to be statement, otherwise an ambiguity is created
// in conjunction with normal parentheses in expressions!
| expression NEWLINE block
)
(ELSE statementOrBlock)?
;
eachStatement
: EACH
( '(' eachHead ')' statementOrBlock
| eachHead NEWLINE block
)
;
eachHead
: type? element=id (',' index=id)? IN expression
;
whileStatement
: WHILE
( '(' condition=expression ')' statement
| condition=expression NEWLINE block
)
;
block
: INDENT
statement*
DEDENT
;
statementOrBlock
: NEWLINE block
| statement
;
variable
: id // Note that it is possible for a recognized variable to be a trivial function.
;
variableDeclaration
: mutability=(MUT | VAL)
type? id
('=' expression)?
;
functionCall
: id argumentList
;
blockFunctionCall
: id argumentList?
NEWLINE block
;
statementFunctionCall
: id argumentList?
statement
;
/* Calls functions of other templates. By default, 'render' is called. */
templateFragmentCall
: templateId frag=id? argumentList?
NEWLINE closure?
;
templateId
: '@' currentPackage='.'? (id '.')* id
;
argumentList
: '(' (argument (',' argument)*)? ')'
;
argument
: argumentId? expression argumentPredicate?
;
argumentId
: id ('-' id)*
;
argumentPredicate
: IF expression
;
literal
: String # stringLiteral
| Integer # integerLiteral
| Long # longLiteral
| Double # doubleLiteral
| Float # floatLiteral
| NULL # nullLiteral
| value=(TRUE | FALSE) # booleanLiteral
;
type
: id
('<' type (',' type)* '>')?
;
id
: Identifier
| '`'
( Identifier
| NOT
| AND
| OR
| IN
| OPT
| IS
| EACH
| WHILE
| ELSE
| IF
| MUT
| VAL
| NULL
| TRUE
| FALSE
| FRAG
)
'`'
;
|
Add 'frag' keyword to id.
|
Add 'frag' keyword to id.
|
ANTLR
|
mit
|
Collap/bryg
|
758340458facc479b4c85063620827a51a18a07e
|
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 *?
;
systemPrivilege
:
;
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
;
|
remove systemPrivilege
|
remove systemPrivilege
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
|
1a3a979189c7adbe29aaf94d41d5973d4c2d8402
|
sharding-jdbc-ddl-parser/src/main/antlr4/imports/MySQLTableBase.g4
|
sharding-jdbc-ddl-parser/src/main/antlr4/imports/MySQLTableBase.g4
|
grammar MySQLTableBase;
import MySQLKeyword,MySQLBase, DataType, Keyword, BaseRule, Symbol;
tableOptions:
tableOption (COMMA? tableOption)*
;
tableOption:
AUTO_INCREMENT EQ_OR_ASSIGN? NUMBER
|AVG_ROW_LENGTH EQ_OR_ASSIGN? NUMBER
| DEFAULT? characterSetWithEqual
| CHECKSUM EQ_OR_ASSIGN? NUMBER
| DEFAULT? collateClauseWithEqual
| COMMENT EQ_OR_ASSIGN? STRING
| COMPRESSION EQ_OR_ASSIGN? (ZLIB|STRING|NONE)
| CONNECTION EQ_OR_ASSIGN? STRING
| (DATA|INDEX) DIRECTORY EQ_OR_ASSIGN? STRING
| DELAY_KEY_WRITE EQ_OR_ASSIGN? NUMBER
| ENCRYPTION EQ_OR_ASSIGN? STRING
| ENGINE EQ_OR_ASSIGN? engineName
| INSERT_METHOD EQ_OR_ASSIGN? ( NO | FIRST | LAST )
| KEY_BLOCK_SIZE EQ_OR_ASSIGN? NUMBER
| MAX_ROWS EQ_OR_ASSIGN? NUMBER
| MIN_ROWS EQ_OR_ASSIGN? NUMBER
| PACK_KEYS EQ_OR_ASSIGN? (NUMBER | DEFAULT)
| PASSWORD EQ_OR_ASSIGN? STRING
| ROW_FORMAT EQ_OR_ASSIGN? (DEFAULT|DYNAMIC|FIXED|COMPRESSED|REDUNDANT|COMPACT)
| STATS_AUTO_RECALC EQ_OR_ASSIGN? (DEFAULT|NUMBER)
| STATS_PERSISTENT EQ_OR_ASSIGN? (DEFAULT|NUMBER)
| STATS_SAMPLE_PAGES EQ_OR_ASSIGN? NUMBER
| TABLESPACE tablespaceName (STORAGE (DISK|MEMORY|DEFAULT))?
| UNION EQ_OR_ASSIGN? idList
;
engineName:
ID
|MEMORY
;
columnDefinition:
columnName dataType (dataTypeOption* | dataTypeGenerated)?
;
dataType:
((INTEGER | INT | TINYINT | SMALLINT | MEDIUMINT | BIGINT) dataTypeLength? UNSIGNED? ZEROFILL?)
| ((DECIMAL | DEC | NUMERIC | FIXED) dataTypeLength? UNSIGNED? ZEROFILL?)
| ((FLOAT | DOUBLE | DOUBLE PRECISION) dataTypeLength? UNSIGNED? ZEROFILL?)
| BIT dataTypeLength?
| (BOOL | BOOLEAN)
| DATE
| ((DATETIME | TIMESTAMP | TIME | YEAR) dataTypeLength?)
| (((NATIONAL? CHAR) | (NATIONAL? VARCHAR) | TEXT) dataTypeLength? characterSet? collateClause?)
| ((BINARY | VARBINARY | BLOB) dataTypeLength?)
| (TINYBLOB | MEDIUMBLOB | LONGBLOB)
| ((TINYTEXT | MEDIUMTEXT | LONGTEXT) characterSet? collateClause?)
| ((ENUM | SET) (LEFT_PAREN STRING (COMMA STRING)* RIGHT_PAREN characterSet? collateClause?))
| (GEOMETRY | POINT | LINESTRING | POLYGON | MULTIPOINT | MULTILINESTRING | MULTIPOLYGON | GEOMETRYCOLLECTION | JSON)
;
dataTypeOption:
(NOT? NULL)
| (DEFAULT defaultValue)
| AUTO_INCREMENT
| (UNIQUE KEY?)
| (PRIMARY? KEY)
| (COMMENT STRING)
| (COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT))
| (STORAGE (DISK|MEMORY|DEFAULT))
| referenceDefinition
;
defaultValue:
NULL
| NUMBER
| STRING
| (currentTimestampType (ON UPDATE currentTimestampType)?)
;
currentTimestampType:
(CURRENT_TIMESTAMP | LOCALTIME | LOCALTIMESTAMP | NOW) dataTypeLength?
;
referenceDefinition:
REFERENCES tableName keyParts
(MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)?
(((ON UPDATE referenceOption)? (ON DELETE referenceOption)?)
|((ON DELETE referenceOption)? (ON UPDATE referenceOption)?)
)
;
referenceOption:
(RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT)
;
dataTypeGenerated:
(GENERATED ALWAYS)? AS LEFT_PAREN expr RIGHT_PAREN
(VIRTUAL | STORED)? (NOT NULL | NULL)?
(UNIQUE (KEY)?)? ((PRIMARY)? KEY)?
(COMMENT STRING)?
;
partitionOptions:
PARTITION BY (linearPartition | rangeOrListPartition)
(PARTITIONS NUMBER)?
(SUBPARTITION BY linearPartition (SUBPARTITIONS NUMBER)? )?
partitionDefinitions?
;
//hash(YEAR(col)) YEAR is keyword which does not match expr
linearPartition:
LINEAR? ((HASH (yearFunctionExpr | exprWithParen)) |keyColumnList)
;
yearFunctionExpr:
LEFT_PAREN YEAR exprWithParen RIGHT_PAREN
;
keyColumnList:
KEY (ALGORITHM EQ_OR_ASSIGN NUMBER)? columnList
;
exprWithParen:
LEFT_PAREN expr RIGHT_PAREN
;
rangeOrListPartition:
(RANGE | LIST ) exprOrColumns
;
exprOrColumns:
LEFT_PAREN expr RIGHT_PAREN | COLUMNS columnList
;
partitionDefinitions:
LEFT_PAREN partitionDefinition (COMMA partitionDefinition)* RIGHT_PAREN
;
partitionDefinition:
PARTITION partitionName
(VALUES (lessThanPartition | IN valueListWithParen))?
(STORAGE? ENGINE EQ_OR_ASSIGN? engineName)?
(COMMENT EQ_OR_ASSIGN? STRING )?
(DATA DIRECTORY EQ_OR_ASSIGN? STRING)?
(INDEX DIRECTORY EQ_OR_ASSIGN? STRING)?
(MAX_ROWS EQ_OR_ASSIGN? NUMBER)?
(MIN_ROWS EQ_OR_ASSIGN? NUMBER)?
(TABLESPACE EQ_OR_ASSIGN? tablespaceName)?
(subpartitionDefinition (COMMA subpartitionDefinition)*)?
;
lessThanPartition:
LESS THAN ((LEFT_PAREN (expr | valueList) RIGHT_PAREN) | MAXVALUE)
;
subpartitionDefinition:
SUBPARTITION partitionName
((STORAGE)? ENGINE EQ_OR_ASSIGN? engineName)?
(COMMENT EQ_OR_ASSIGN? STRING )?
(DATA DIRECTORY EQ_OR_ASSIGN? STRING)?
(INDEX DIRECTORY EQ_OR_ASSIGN? STRING)?
(MAX_ROWS EQ_OR_ASSIGN? NUMBER)?
(MIN_ROWS EQ_OR_ASSIGN? NUMBER)?
(TABLESPACE EQ_OR_ASSIGN? tablespaceName)?
;
indexDefinition:
(((FULLTEXT | SPATIAL) indexAndKey?)|indexAndKey) indexDefOption
;
indexDefOption:
indexName? indexType? keyParts indexOption?
;
constraintDefinition:
(CONSTRAINT symbol?)? (primaryKeyOption | uniqueOption | foreignKeyOption)
;
primaryKeyOption:
primaryKey indexType? keyParts indexOption?
;
uniqueOption:
UNIQUE (INDEX|KEY)? indexName? indexType? keyParts indexOption?
;
foreignKeyOption:
FOREIGN KEY indexName? LEFT_PAREN columnName (COMMA columnName)* RIGHT_PAREN referenceDefinition
;
|
grammar MySQLTableBase;
import MySQLKeyword,MySQLBase, DataType, Keyword, BaseRule, Symbol;
tableOptions:
tableOption (COMMA? tableOption)*
;
tableOption:
AUTO_INCREMENT EQ_OR_ASSIGN? NUMBER
|AVG_ROW_LENGTH EQ_OR_ASSIGN? NUMBER
| DEFAULT? characterSetWithEqual
| CHECKSUM EQ_OR_ASSIGN? NUMBER
| DEFAULT? collateClauseWithEqual
| COMMENT EQ_OR_ASSIGN? STRING
| COMPRESSION EQ_OR_ASSIGN? (ZLIB|STRING|NONE)
| CONNECTION EQ_OR_ASSIGN? STRING
| (DATA|INDEX) DIRECTORY EQ_OR_ASSIGN? STRING
| DELAY_KEY_WRITE EQ_OR_ASSIGN? NUMBER
| ENCRYPTION EQ_OR_ASSIGN? STRING
| ENGINE EQ_OR_ASSIGN? engineName
| INSERT_METHOD EQ_OR_ASSIGN? ( NO | FIRST | LAST )
| KEY_BLOCK_SIZE EQ_OR_ASSIGN? NUMBER
| MAX_ROWS EQ_OR_ASSIGN? NUMBER
| MIN_ROWS EQ_OR_ASSIGN? NUMBER
| PACK_KEYS EQ_OR_ASSIGN? (NUMBER | DEFAULT)
| PASSWORD EQ_OR_ASSIGN? STRING
| ROW_FORMAT EQ_OR_ASSIGN? (DEFAULT|DYNAMIC|FIXED|COMPRESSED|REDUNDANT|COMPACT)
| STATS_AUTO_RECALC EQ_OR_ASSIGN? (DEFAULT|NUMBER)
| STATS_PERSISTENT EQ_OR_ASSIGN? (DEFAULT|NUMBER)
| STATS_SAMPLE_PAGES EQ_OR_ASSIGN? NUMBER
| TABLESPACE tablespaceName (STORAGE (DISK|MEMORY|DEFAULT))?
| UNION EQ_OR_ASSIGN? idList
;
engineName:
ID
|MEMORY
;
columnDefinition:
columnName dataType (dataTypeOption* | dataTypeGenerated)?
;
dataType:
((INTEGER | INT | TINYINT | SMALLINT | MEDIUMINT | BIGINT) dataTypeLength? UNSIGNED? ZEROFILL?)
| ((DECIMAL | DEC | NUMERIC | FIXED) dataTypeLength? UNSIGNED? ZEROFILL?)
| ((FLOAT | DOUBLE | DOUBLE PRECISION) dataTypeLength? UNSIGNED? ZEROFILL?)
| BIT dataTypeLength?
| (BOOL | BOOLEAN)
| DATE
| ((DATETIME | TIMESTAMP | TIME | YEAR) dataTypeLength?)
| (((NATIONAL? CHAR) | (NATIONAL? VARCHAR) | TEXT) dataTypeLength? characterSet? collateClause?)
| ((BINARY | VARBINARY | BLOB) dataTypeLength?)
| (TINYBLOB | MEDIUMBLOB | LONGBLOB)
| ((TINYTEXT | MEDIUMTEXT | LONGTEXT) characterSet? collateClause?)
| ((ENUM | SET) (LEFT_PAREN STRING (COMMA STRING)* RIGHT_PAREN characterSet? collateClause?))
| (GEOMETRY | POINT | LINESTRING | POLYGON | MULTIPOINT | MULTILINESTRING | MULTIPOLYGON | GEOMETRYCOLLECTION | JSON)
;
dataTypeOption:
(NOT? NULL)
| (DEFAULT defaultValue)
| AUTO_INCREMENT
| (UNIQUE KEY?)
| (PRIMARY? KEY)
| (COMMENT STRING)
| (COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT))
| (STORAGE (DISK|MEMORY|DEFAULT))
| referenceDefinition
;
defaultValue:
NULL
| NUMBER
| STRING
| (currentTimestampType (ON UPDATE currentTimestampType)?)
;
currentTimestampType:
(CURRENT_TIMESTAMP | LOCALTIME | LOCALTIMESTAMP | NOW) dataTypeLength?
;
referenceDefinition:
REFERENCES tableName keyParts
(MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)?
(((ON UPDATE referenceOption)? (ON DELETE referenceOption)?)
|((ON DELETE referenceOption)? (ON UPDATE referenceOption)?)
)
;
referenceOption:
(RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT)
;
dataTypeGenerated:
(GENERATED ALWAYS)? AS LEFT_PAREN expr RIGHT_PAREN
(VIRTUAL | STORED)? (NOT NULL | NULL)?
(UNIQUE (KEY)?)? ((PRIMARY)? KEY)?
(COMMENT STRING)?
;
partitionOptions:
PARTITION BY (linearPartition | rangeOrListPartition)
(PARTITIONS NUMBER)?
(SUBPARTITION BY linearPartition (SUBPARTITIONS NUMBER)? )?
partitionDefinitions?
;
//hash(YEAR(col)) YEAR is keyword which does not match expr
linearPartition:
LINEAR? ((HASH (yearFunctionExpr | exprWithParen)) |keyColumnList)
;
yearFunctionExpr:
LEFT_PAREN YEAR exprWithParen RIGHT_PAREN
;
keyColumnList:
KEY (ALGORITHM EQ_OR_ASSIGN NUMBER)? columnList
;
exprWithParen:
LEFT_PAREN expr RIGHT_PAREN
;
rangeOrListPartition:
(RANGE | LIST ) exprOrColumns
;
exprOrColumns:
LEFT_PAREN expr RIGHT_PAREN | COLUMNS columnList
;
partitionDefinitions:
LEFT_PAREN partitionDefinition (COMMA partitionDefinition)* RIGHT_PAREN
;
partitionDefinition:
PARTITION partitionName
(VALUES (lessThanPartition | IN valueListWithParen))?
partitionDefinitionOption*
(subpartitionDefinition (COMMA subpartitionDefinition)*)?
;
partitionDefinitionOption:
(STORAGE)? ENGINE EQ_OR_ASSIGN? engineName
| COMMENT EQ_OR_ASSIGN? STRING
| DATA DIRECTORY EQ_OR_ASSIGN? STRING
| INDEX DIRECTORY EQ_OR_ASSIGN? STRING
| MAX_ROWS EQ_OR_ASSIGN? NUMBER
| MIN_ROWS EQ_OR_ASSIGN? NUMBER
| TABLESPACE EQ_OR_ASSIGN? tablespaceName
;
lessThanPartition:
LESS THAN ((LEFT_PAREN (expr | valueList) RIGHT_PAREN) | MAXVALUE)
;
subpartitionDefinition:
SUBPARTITION partitionName
partitionDefinitionOption*
;
indexDefinition:
(((FULLTEXT | SPATIAL) indexAndKey?)|indexAndKey) indexDefOption
;
indexDefOption:
indexName? indexType? keyParts indexOption?
;
constraintDefinition:
(CONSTRAINT symbol?)? (primaryKeyOption | uniqueOption | foreignKeyOption)
;
primaryKeyOption:
primaryKey indexType? keyParts indexOption?
;
uniqueOption:
UNIQUE (INDEX|KEY)? indexName? indexType? keyParts indexOption?
;
foreignKeyOption:
FOREIGN KEY indexName? LEFT_PAREN columnName (COMMA columnName)* RIGHT_PAREN referenceDefinition
;
|
add partitionDefinitionOption
|
add partitionDefinitionOption
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
|
2d21618ac50b9c86cda18c923ee53f741a1628f7
|
mumps/mumps.g4
|
mumps/mumps.g4
|
/*
BSD License
Copyright (c) 2013, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar mumps;
program
: routine+ eof
;
eof
: SPACE* CR?
;
routine
: routinename routinebody
;
routinename
: PERCENT? identifier (LPAREN paramlist? RPAREN)? (SPACE+ comment)? CR
;
paramlist
: param (COMMA param)*
;
param
: variable
;
routinebody
: line+
;
line
: SPACE+ (label SPACE*)? (command* | if_ | subproc) (SPACE+ comment)? CR
;
label
: identifier
;
subproc
: identifier (LPAREN paramlist? RPAREN)? (SPACE* command)+
;
command
: set_
| for_
| write_
| quit_
| halt_
| hang_
| new_
| break_
| do_
| kill_
| (CLOSE | ELSE | GOTO | JOB
| LOCK | MERGE | OPEN | READ | TCOMMIT
| TRESTART | TROLLBACK | TSTART | USE | VIEW | XECUTE)
;
expression
: term (SPACE* (ADD | MULTIPLY | SUBTRACT | DIVIDE) expression)*
;
term
: variable
| NUMBER
| LPAREN expression RPAREN
;
condition
: term
| (term (LT | GT | EQUALS) term)
;
comment
: SEMICOLON ~(CR)*
;
identifier
: IDENTIFIER
;
variable
: (CARAT | DOLLAR | AMPERSAND)* identifier
;
if_
: IF SPACE* condition SPACE* command
;
set_
: (SET) SPACE+ assign (',' assign)*
;
for_
: FOR SPACE+ term EQUALS term COLON term SPACE* (command SPACE?)* COLON SPACE* condition
;
halt_
: (HALT)
;
hang_
: HANG term
;
kill_
: KILL arglist
;
write_
: (WRITE1 | WRITE2) SPACE* arglist
;
quit_
: (QUIT) (SPACE* term)?
;
new_
: (NEW) SPACE* arglist
;
break_
: (BREAK)
;
do_
: (DO) SPACE* identifier (LPAREN paramlist? RPAREN)?
;
assign
: (LPAREN? arglist RPAREN?)? SPACE* EQUALS SPACE* arg
;
arglist
: arg (SPACE* COMMA arg)*
;
arg
: expression
| (BANG
| STRING_LITERAL)
;
BREAK
: B R E A K
;
CLOSE
: C L O S E
;
DO
: D O
;
ELSE
: E L S E
;
FOR
: F O R
;
GOTO
: G O T O
;
HALT
: H A L T
;
HANG
: H A N G
;
IF
: I F
;
JOB
: J O B
;
KILL
: K I L L
;
LOCK
: L O C K
;
MERGE
: M E R G E
;
NEW
: N E W
;
OPEN
: O P E N
;
QUIT
: Q U I T
;
READ
: R E A D
;
SET
: S E T
;
TCOMMIT
: T C O M M I T
;
TRESTART
: T R E S T A R T
;
TROLLBACK
: T R O L L B A C K
;
TSTART
: T S T A R T
;
USE
: U S E
;
VIEW
: V I E W
;
WRITE1
: W R I T E
;
WRITE2
: W
;
XECUTE
: X E C U T E
;
SEMICOLON
: ';'
;
COLON
: ':'
;
COMMA
: ','
;
DOLLAR
: '$'
;
PERCENT
: '%'
;
AMPERSAND
: '&'
;
INDIRECT
: '@'
;
CARAT
: '^'
;
BANG
: '!'
;
LPAREN
: '('
;
RPAREN
: ')'
;
GT
: '>'
;
LT
: '<'
;
ADD
: '+'
;
SUBTRACT
: '-'
;
MULTIPLY
: '*'
;
DIVIDE
: '/'
;
EQUALS
: '='
;
IDENTIFIER
: ('a'..'z' | 'A'..'Z') ('a'..'z'|'A'..'Z'|'0'..'9')*
;
STRING_LITERAL
: '\"' ('\"\"' | ~('\"'))* '\"'
;
NUMBER
: ('0'..'9')+ ('.' ('0'..'9')+)?
;
SPACE
: ' '
;
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');
CR
: '\n'
;
WS
: [\t]->skip
;
|
/*
BSD License
Copyright (c) 2013, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar mumps;
program
: routine+ eof
;
eof
: SPACE* CR?
;
routine
: routinename routinebody
;
routinename
: PERCENT? identifier (LPAREN paramlist? RPAREN)? (SPACE+ comment)? CR
;
paramlist
: param (COMMA param)*
;
param
: variable
;
routinebody
: line+
;
line
: SPACE+ (label SPACE*)? (command* | if_ | subproc) (SPACE+ comment)? CR
;
label
: identifier
;
subproc
: identifier (LPAREN paramlist? RPAREN)? (SPACE* command)+
;
command
: set_
| for_
| write_
| quit_
| halt_
| hang_
| new_
| break_
| do_
| kill_
| (CLOSE | ELSE | GOTO | JOB
| LOCK | MERGE | OPEN | READ | TCOMMIT
| TRESTART | TROLLBACK | TSTART | USE | VIEW | XECUTE)
;
expression
: term (SPACE* (ADD | MULTIPLY | SUBTRACT | DIVIDE) expression)*
;
term
: variable
| NUMBER
| LPAREN expression RPAREN
;
condition
: term
| (term (LT | GT | EQUALS) term)
;
comment
: SEMICOLON ~(CR)*
;
identifier
: IDENTIFIER
;
variable
: (CARAT | DOLLAR | AMPERSAND)* identifier
;
if_
: IF SPACE* condition SPACE* command
;
set_
: (SET) SPACE+ assign (',' assign)*
;
for_
: FOR SPACE+ term EQUALS term COLON term SPACE* (command SPACE?)* COLON SPACE* condition
;
halt_
: (HALT)
;
hang_
: HANG term
;
kill_
: KILL arglist
;
write_
: (WRITE | 'W') SPACE* arglist
;
quit_
: (QUIT) (SPACE* term)?
;
new_
: (NEW) SPACE* arglist
;
break_
: (BREAK)
;
do_
: (DO) SPACE* identifier (LPAREN paramlist? RPAREN)?
;
assign
: (LPAREN? arglist RPAREN?)? SPACE* EQUALS SPACE* arg
;
arglist
: arg (SPACE* COMMA arg)*
;
arg
: expression
| (BANG
| STRING_LITERAL)
;
BREAK
: B R E A K
;
CLOSE
: C L O S E
;
DO
: D O
;
ELSE
: E L S E
;
FOR
: F O R
;
GOTO
: G O T O
;
HALT
: H A L T
;
HANG
: H A N G
;
IF
: I F
;
JOB
: J O B
;
KILL
: K I L L
;
LOCK
: L O C K
;
MERGE
: M E R G E
;
NEW
: N E W
;
OPEN
: O P E N
;
QUIT
: Q U I T
;
READ
: R E A D
;
SET
: S E T
;
TCOMMIT
: T C O M M I T
;
TRESTART
: T R E S T A R T
;
TROLLBACK
: T R O L L B A C K
;
TSTART
: T S T A R T
;
USE
: U S E
;
VIEW
: V I E W
;
WRITE
: W R I T E
;
XECUTE
: X E C U T E
;
SEMICOLON
: ';'
;
COLON
: ':'
;
COMMA
: ','
;
DOLLAR
: '$'
;
PERCENT
: '%'
;
AMPERSAND
: '&'
;
INDIRECT
: '@'
;
CARAT
: '^'
;
BANG
: '!'
;
LPAREN
: '('
;
RPAREN
: ')'
;
GT
: '>'
;
LT
: '<'
;
ADD
: '+'
;
SUBTRACT
: '-'
;
MULTIPLY
: '*'
;
DIVIDE
: '/'
;
EQUALS
: '='
;
IDENTIFIER
: ('a'..'z' | 'A'..'Z') ('a'..'z'|'A'..'Z'|'0'..'9')*
;
STRING_LITERAL
: '\"' ('\"\"' | ~('\"'))* '\"'
;
NUMBER
: ('0'..'9')+ ('.' ('0'..'9')+)?
;
SPACE
: ' '
;
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');
CR
: '\n'
;
WS
: [\t]->skip
;
|
write fix
|
write fix
|
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
|
64a49986b46c49960a2fb37e088e35504e2b9a80
|
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
|
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
|
grammar SQLServerDCLStatement;
import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol;
grantGeneral
: GRANT (ALL PRIVILEGES? | permissionOnColumns ( COMMA permissionOnColumns)*)
(ON (ID COLONCOLON)? ID )? TO ids
(WITH GRANT OPTION)? (AS ID)?
;
permissionOnColumns
: permission columnList?
;
permission
: ID *?
;
|
grammar SQLServerDCLStatement;
import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol;
grantGeneral
: GRANT (ALL PRIVILEGES? | permissionOnColumns ( COMMA permissionOnColumns)*)
(ON (ID COLONCOLON)? ID )? TO ids
(WITH GRANT OPTION)? (AS ID)?
;
permissionOnColumns
: permission columnList?
;
permission
: ID *?
;
classType
: LOGIN
| DATABASE
| OBJECT
| ROLE
| SCHEMA
| USER
;
|
add classType
|
add classType
|
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
|
8a6da5bc7e410cd18a035b66c8d4635e69d3e902
|
src/main/antlr4/JmesPath.g4
|
src/main/antlr4/JmesPath.g4
|
grammar JmesPath;
import JSON;
query : expression EOF ;
expression
: expression '.' (IDENTIFIER | multiSelectList | multiSelectHash | functionExpression | '*') # chainExpression
| expression bracketSpecifier # bracketedExpression
| bracketSpecifier # bracketExpression
| expression '||' expression # orExpression
| IDENTIFIER # identifierExpression
| expression '&&' expression # andExpression
| expression COMPARATOR expression # comparisonExpression
| '!' 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 | '*' | SLICE_EXPRESSION) ']'
| '[]'
| '[' '?' expression ']'
;
SLICE_EXPRESSION : SIGNED_INT? ':' SIGNED_INT? (':' SIGNED_INT?)? ;
COMPARATOR
: '<'
| '<='
| '=='
| '>='
| '>'
| '!='
;
// TODO: should be NAME and not IDENTIFIER, but that doesn't work
functionExpression : IDENTIFIER (noArgs | oneOrMoreArgs) ;
noArgs : '(' ')' ;
oneOrMoreArgs : '(' functionArg (',' functionArg)* ')' ;
functionArg
: expression
| expressionType
;
currentNode : '@' ;
expressionType : '&' expression ;
RAW_STRING : '\'' (RAW_ESC | ~['\\])* '\'' ;
fragment RAW_ESC : '\\' ['\\] ;
literal : '`' value '`' ;
SIGNED_INT : '-'? DIGIT+ ;
DIGIT : [0-9] ;
LETTER : [a-zA-Z] ;
IDENTIFIER
: NAME
| STRING
;
NAME : LETTER (LETTER | DIGIT | '_')* ;
|
grammar JmesPath;
import JSON;
query : expression EOF ;
expression
: expression '.' (identifier | multiSelectList | multiSelectHash | functionExpression | '*') # chainExpression
| expression bracketSpecifier # bracketedExpression
| bracketSpecifier # bracketExpression
| expression '||' expression # orExpression
| identifier # identifierExpression
| expression '&&' expression # andExpression
| expression COMPARATOR expression # comparisonExpression
| '!' 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 | '*' | SLICE_EXPRESSION) ']'
| '[]'
| '[' '?' expression ']'
;
SLICE_EXPRESSION : SIGNED_INT? ':' SIGNED_INT? (':' SIGNED_INT?)? ;
COMPARATOR
: '<'
| '<='
| '=='
| '>='
| '>'
| '!='
;
// TODO: should be NAME and not IDENTIFIER, but that doesn't work
functionExpression : IDENTIFIER (noArgs | oneOrMoreArgs) ;
noArgs : '(' ')' ;
oneOrMoreArgs : '(' functionArg (',' functionArg)* ')' ;
functionArg
: expression
| expressionType
;
currentNode : '@' ;
expressionType : '&' expression ;
RAW_STRING : '\'' (RAW_ESC | ~['\\])* '\'' ;
fragment RAW_ESC : '\\' ['\\] ;
literal : '`' value '`' ;
SIGNED_INT : '-'? DIGIT+ ;
DIGIT : [0-9] ;
LETTER : [a-zA-Z] ;
identifier
: NAME
| STRING
;
NAME : LETTER (LETTER | DIGIT | '_')* ;
|
Make IDENTIFIER a parser rule to fix the `"foo"` problem
|
Make IDENTIFIER a parser rule to fix the `"foo"` problem
The string in `"foo"` matched both IDENTIFIER and STRING, but IDENTIFIER won, which was not what we wanted.
|
ANTLR
|
bsd-3-clause
|
burtcorp/jmespath-java
|
18f1d838b545cbf3f3527b071651c5617aacfc87
|
sharding-core/src/main/antlr4/imports/OracleCreateTable.g4
|
sharding-core/src/main/antlr4/imports/OracleCreateTable.g4
|
grammar OracleCreateTable;
import OracleKeyword, Keyword, DataType, OracleCreateIndex, OracleTableBase, OracleBase, BaseRule, Symbol;
createTable
: CREATE (GLOBAL TEMPORARY)? TABLE tableName relationalTable
;
relationalTable
: LEFT_PAREN relationalProperties RIGHT_PAREN
(ON COMMIT (DELETE | PRESERVE) ROWS)?
tableProperties
;
relationalProperties
: relationalProperty (COMMA relationalProperty)*
;
relationalProperty
: columnDefinition
| virtualColumnDefinition
| outOfLineConstraint
| outOfLineRefConstraint
;
tableProperties
: columnProperties?
(AS subquery)?
;
|
grammar OracleCreateTable;
import OracleKeyword, Keyword, DataType, OracleCreateIndex, OracleTableBase, DQLBase, OracleBase, BaseRule, Symbol;
createTable
: CREATE (GLOBAL TEMPORARY)? TABLE tableName relationalTable
;
relationalTable
: (LEFT_PAREN relationalProperties RIGHT_PAREN)?
(ON COMMIT (DELETE | PRESERVE) ROWS)?
tableProperties
;
relationalProperties
: relationalProperty (COMMA relationalProperty)*
;
relationalProperty
: columnDefinition
| virtualColumnDefinition
| outOfLineConstraint
| outOfLineRefConstraint
;
tableProperties
: columnProperties?
(AS unionSelect)?
;
|
fix oracle create table ... as select rule
|
fix oracle create table ... as select rule
|
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
|
b03bcf256518d421adf6266c3f94d8e46527ae3a
|
engine/src/main/antlr4/com/impossibl/stencil/engine/parsing/StencilLexer.g4
|
engine/src/main/antlr4/com/impossibl/stencil/engine/parsing/StencilLexer.g4
|
lexer grammar StencilLexer;
@members {
public static final int STEXTS = DEFAULT_MODE;
public static final int KEYWORD_FIRST=EXPORT;
public static final int KEYWORD_LAST=FALSE;
private int statementBlocks=-1;
void resetStatementBlocks() {
statementBlocks=-1;
}
void incStatementBlocks() {
statementBlocks+=1;
}
void decStatementBlocks() {
statementBlocks-=1;
}
@Override
public int popMode() {
if ( _modeStack.isEmpty() ) {
pushMode(STEXTS);
}
return super.popMode();
}
}
tokens {
TEXT,
TEXTWS,
OUTPUTS_MODE,
TEXTS_MODE,
TEXTS_END
}
SCOMMENT: '$*' .*? '*$' -> channel(HIDDEN);
HEADERS_MODE: '$$' -> pushMode(OUTPUTS);
SOUTPUTS_MODE: '$' -> pushMode(OUTPUTS), type(OUTPUTS_MODE);
STEXTS_END: '}' -> popMode, type(TEXTS_END);
STEXTWS: [ \t\r\n]+ -> type(TEXTWS);
STEXT: (STEXTESC|~[$}])+ -> type(TEXT);
fragment STEXTESC: '\\{' | '\\}';
mode DTEXTS;
DCOMMENT: '$*' .*? '*$' -> channel(HIDDEN);
DOUTPUTS_MODE: '$$' -> pushMode(OUTPUTS), type(OUTPUTS_MODE);
DTEXTS_END: '}}' -> popMode, type(TEXTS_END);
DTEXTWS: [ \t\r\n]+ -> type(TEXTWS);
DTEXT_KEY1: '$' -> type(TEXT);
DTEXT_KEY2: '}' -> type(TEXT);
DTEXT: (DTEXTESC|~[$}])+ -> type(TEXT);
fragment DTEXTESC: '\\{{' | '\\}}';
mode OUTPUTS;
COMMENT: '$*' .*? '*$' -> channel(HIDDEN);
DTEXTS_MODE: '{{' -> pushMode(DTEXTS), type(TEXTS_MODE);
STEXTS_MODE: {statementBlocks<0}? '{' -> pushMode(STEXTS), type(TEXTS_MODE);
OUTPUTS_END: {statementBlocks<=0}? ';' {resetStatementBlocks(); popMode();};
EXPORT: 'export';
MACRO: 'macro';
FUNC: 'func' {incStatementBlocks();};
IF: 'if';
ELSE: 'else';
FOREACH: 'foreach';
IN: 'in';
WHILE: 'while';
BREAK: 'break';
CONTINUE: 'continue';
SWITCH: 'switch';
CASE: 'case';
DEFAULT: 'default';
ISA: 'isa';
INSTANCEOF: 'instanceof';
VAR: 'var';
RETURN: 'return';
WITH: 'with';
ASSIGN: 'assign';
BEFORE: 'before';
AFTER: 'after';
REPLACE: 'replace';
INCLUDE: 'include';
IMPORT: 'import';
GLOBAL: 'global';
AS: 'as';
NULL: 'null';
TRUE: 'true';
FALSE: 'false';
QUESTDOT: '?.';
DOTDOT: '..';
DOT: '.';
SEMI: ';';
COLON: ':';
COMMA: ',';
QUEST: '?';
IDENTICAL: '===';
NIDENTICAL: '!==';
LSHIFT_ASSIGN: '<<=';
RSHIFT_ASSIGN: '>>=';
ADD_ASSIGN: '+=';
SUB_ASSIGN: '-=';
MUL_ASSIGN: '*=';
DIV_ASSIGN: '/=';
MOD_ASSIGN: '%=';
AND_ASSIGN: '&=';
XOR_ASSIGN: '^=';
OR_ASSIGN: '|=';
INC: '++';
DEC: '--';
LSHIFT: '<<';
RSHIFT: '>>';
EQUAL: '==';
NEQUAL: '!=';
GTEQUAL: '>=';
LTEQUAL: '<=';
LOG_OR: '||';
LOG_AND: '&&';
ADD: '+';
SUB: '-';
MUL: '*';
DIV: '/';
MOD: '%';
LOG_NEG: '!';
BIT_NEG: '~';
BIT_OR: '|';
BIT_XOR: '^';
BIT_AND: '&';
GT: '>';
LT: '<';
EQL_ASSIGN: '=';
PAREN_OPEN: '(';
PAREN_CLOSE: ')';
SQUARE_OPEN: '[';
SQUARE_CLOSE: ']';
BLOCK_OPEN: '{' {incStatementBlocks();};
BLOCK_CLOSE: '}' {decStatementBlocks();};
ID: [a-zA-Z_] [a-zA-Z0-9_]*;
SSTRING: '\'' (SSTRINGESC|.)*? '\'';
DSTRING: '\"' (DSTRINGESC|.)*? '\"';
fragment SSTRINGESC: '\\\'' | '\\\\';
fragment DSTRINGESC: '\\\"' | '\\\\';
INTEGER: INT [sil]?;
FLOAT: (INT '.' INT EXP? | INT EXP) [fd]?;
fragment INT: [0-9]+;
fragment EXP: [Ee] [+\-]? INT;
WS: [ \t\r\n]+ -> channel(HIDDEN);
|
lexer grammar StencilLexer;
@members {
public static final int STEXTS = DEFAULT_MODE;
public static final int KEYWORD_FIRST=EXPORT;
public static final int KEYWORD_LAST=FALSE;
private int statementBlocks=-1;
void resetStatementBlocks() {
statementBlocks=-1;
}
void incStatementBlocks() {
statementBlocks+=1;
}
void decStatementBlocks() {
statementBlocks-=1;
}
@Override
public int popMode() {
if ( _modeStack.isEmpty() ) {
pushMode(STEXTS);
}
return super.popMode();
}
}
tokens {
TEXT,
TEXTWS,
OUTPUTS_MODE,
TEXTS_MODE,
TEXTS_END
}
SCOMMENT: '$*' .*? '*$' -> channel(HIDDEN);
STEXTESC_OUTS: '\\$' { setText("$"); setType(TEXT); };
STEXTESC_OPEN: '\\{' { setText("{"); setType(TEXT); };
STEXTESC_CLOS: '\\}' { setText("}"); setType(TEXT); };
HEADERS_MODE: '$$' -> pushMode(OUTPUTS);
SOUTPUTS_MODE: '$' -> pushMode(OUTPUTS), type(OUTPUTS_MODE);
STEXTS_END: '}' -> popMode, type(TEXTS_END);
STEXTWS: [ \t\r\n]+ -> type(TEXTWS);
STEXT_KEYS: [\\$}] -> type(TEXT);
STEXT: (~[\\$}])+ -> type(TEXT);
mode DTEXTS;
DCOMMENT: '$*' .*? '*$' -> channel(HIDDEN);
DTEXTESC_OUTS: '\\$$' { setText("$$"); setType(TEXT); };
DTEXTESC_OPEN: '\\{{' { setText("{{"); setType(TEXT); };
DTEXTESC_CLOS: '\\}}' { setText("}}"); setType(TEXT); };
DOUTPUTS_MODE: '$$' -> pushMode(OUTPUTS), type(OUTPUTS_MODE);
DTEXTS_END: '}}' -> popMode, type(TEXTS_END);
DTEXTWS: [ \t\r\n]+ -> type(TEXTWS);
DTEXT_KEYS: [\\$}] -> type(TEXT);
DTEXT: (~[\\$}])+ -> type(TEXT);
mode OUTPUTS;
COMMENT1: '$*' .*? '*$' -> channel(HIDDEN);
COMMENT2: '//'..'\n' -> channel(HIDDEN);
DTEXTS_MODE: '{{' -> pushMode(DTEXTS), type(TEXTS_MODE);
STEXTS_MODE: {statementBlocks<0}? '{' -> pushMode(STEXTS), type(TEXTS_MODE);
OUTPUTS_END: {statementBlocks<=0}? ';' {resetStatementBlocks(); popMode();};
EXPORT: 'export';
MACRO: 'macro';
FUNC: 'func' {incStatementBlocks();};
IF: 'if';
ELSE: 'else';
FOREACH: 'foreach';
IN: 'in';
WHILE: 'while';
BREAK: 'break';
CONTINUE: 'continue';
SWITCH: 'switch';
CASE: 'case';
DEFAULT: 'default';
ISA: 'isa';
INSTANCEOF: 'instanceof';
VAR: 'var';
RETURN: 'return';
WITH: 'with';
ASSIGN: 'assign';
BEFORE: 'before';
AFTER: 'after';
REPLACE: 'replace';
INCLUDE: 'include';
IMPORT: 'import';
GLOBAL: 'global';
AS: 'as';
NULL: 'null';
TRUE: 'true';
FALSE: 'false';
QUESTDOT: '?.';
DOTDOT: '..';
DOT: '.';
SEMI: ';';
COLON: ':';
COMMA: ',';
QUEST: '?';
IDENTICAL: '===';
NIDENTICAL: '!==';
LSHIFT_ASSIGN: '<<=';
RSHIFT_ASSIGN: '>>=';
ADD_ASSIGN: '+=';
SUB_ASSIGN: '-=';
MUL_ASSIGN: '*=';
DIV_ASSIGN: '/=';
MOD_ASSIGN: '%=';
AND_ASSIGN: '&=';
XOR_ASSIGN: '^=';
OR_ASSIGN: '|=';
INC: '++';
DEC: '--';
LSHIFT: '<<';
RSHIFT: '>>';
EQUAL: '==';
NEQUAL: '!=';
GTEQUAL: '>=';
LTEQUAL: '<=';
LOG_OR: '||';
LOG_AND: '&&';
ADD: '+';
SUB: '-';
MUL: '*';
DIV: '/';
MOD: '%';
LOG_NEG: '!';
BIT_NEG: '~';
BIT_OR: '|';
BIT_XOR: '^';
BIT_AND: '&';
GT: '>';
LT: '<';
EQL_ASSIGN: '=';
PAREN_OPEN: '(';
PAREN_CLOSE: ')';
SQUARE_OPEN: '[';
SQUARE_CLOSE: ']';
BLOCK_OPEN: '{' {incStatementBlocks();};
BLOCK_CLOSE: '}' {decStatementBlocks();};
ID: [a-zA-Z_] [a-zA-Z0-9_]*;
SSTRING: '\'' (SSTRINGESC|.)*? '\'';
DSTRING: '\"' (DSTRINGESC|.)*? '\"';
fragment SSTRINGESC: '\\\'' | '\\\\';
fragment DSTRINGESC: '\\\"' | '\\\\';
INTEGER: INT [sil]?;
FLOAT: (INT '.' INT EXP? | INT EXP) [fd]?;
fragment INT: [0-9]+;
fragment EXP: [Ee] [+\-]? INT;
WS: [ \t\r\n]+ -> channel(HIDDEN);
|
Fix escaping
|
Fix escaping
|
ANTLR
|
bsd-3-clause
|
impossibl/stencil
|
16cb1697abd77400d3288361b65300f722f9a689
|
impl/src/main/antlr4/com/groupon/lex/metrics/grammar/ConfigTokenizer.g4
|
impl/src/main/antlr4/com/groupon/lex/metrics/grammar/ConfigTokenizer.g4
|
/*
* Copyright (c) 2016, Groupon, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of GROUPON 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.
*/
lexer grammar ConfigTokenizer;
options {
//backtrack = false;
//memoize = true;
//vocab = ConfigBnf;
//tokenVocab=ConfigBnf;
}
@header {
import java.util.regex.Matcher;
import java.util.regex.Pattern;
}
@members {
private static final Pattern SPECIAL = Pattern.compile("\\\\([\\\\abtnvfr'\"/]"
+ "|[0-7][0-7][0-7]"
+ "|[0-7][0-7]"
+ "|[0-7]"
+ "|x[0-9a-fA-F][0-9a-fA-F]"
+ "|u[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]"
+ "|U[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])");
private static String handleEscapes(String s) {
final StringBuilder result = new StringBuilder(s.length());
Matcher matcher = SPECIAL.matcher(s);
int b = 0;
while (matcher.find()) {
result.append(s, b, matcher.start());
b = matcher.end();
switch (s.charAt(matcher.start() + 1)) {
default:
throw new IllegalStateException("Programmer error: unhandled sequence " + s.substring(matcher.start(), matcher.end()));
case '\\':
result.append('\\');
break;
case 'a':
result.append('\007'); // Unknown to java.
break;
case 'b':
result.append('\010'); // Unknown to java.
break;
case 't':
result.append('\t');
break;
case 'n':
result.append('\n');
break;
case 'v':
result.append('\013'); // Unknown to java.
break;
case 'f':
result.append('\f');
break;
case 'r':
result.append('\r');
break;
case '/':
result.append('/');
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
final String octal_part = s.substring(matcher.start() + 1, matcher.end());
final int ch_int = Integer.parseInt(octal_part, 8);
if (ch_int > 127)
throw new NumberFormatException("Invalid octal escape: " + octal_part);
result.append((char) ch_int);
break;
case 'x':
case 'u':
case 'U':
final String hex_part = s.substring(matcher.start() + 2, matcher.end());
final int unicode_int = Integer.parseInt(hex_part, 16);
if (unicode_int > 0x10ffff)
throw new NumberFormatException("Invalid hex escape: " + hex_part);
result.append(Character.toChars(unicode_int));
break;
}
}
result.append(s, b, s.length());
return result.toString();
}
}
STAR_STAR : '**'
;
STAR : '*'
;
ENDSTATEMENT_KW : ';'
;
COMMENT : '#' ~('\n')*
{ skip(); }
;
CURLYBRACKET_OPEN: '{'
;
CURLYBRACKET_CLOSE
: '}'
;
IMPORT_KW : 'import'
;
COLLECTORS_KW : 'collectors'
;
ALL_KW : 'all'
;
FROM_KW : 'from'
;
COLLECT_KW : 'collect'
;
CONSTANT_KW : 'constant'
;
ALERT_KW : 'alert'
;
IF_KW : 'if'
;
MESSAGE_KW : 'message'
;
FOR_KW : 'for'
;
MATCH_KW : 'match'
;
AS_KW : 'as'
;
ATTRIBUTES_KW : 'attributes'
;
WHERE_KW : 'where'
;
ALIAS_KW : 'alias'
;
TAG_KW : 'tag'
;
TRUE_KW : 'true'
;
FALSE_KW : 'false'
;
DEFINE_KW : 'define'
;
KEEP_COMMON_KW : 'keep_common'
;
BY_KW : 'by'
;
WITHOUT_KW : 'without'
;
WS : (' '|'\n'|'\t')+
{ skip(); }
;
ID : ('_'|'a'..'z'|'A'..'Z') ('_'|'a'..'z'|'A'..'Z'|'0'..'9')*
;
FP_DECIMAL : ('0'..'9')+ (('e'|'E') '-'? ('0'..'9')+)
| ('0'..'9')* '.' ('0'..'9')+ (('e'|'E') ('0'..'9')+)?
;
FP_HEX : '0x' ('0'..'9'|'a'..'f'|'A'..'F')+ ('.' ('0'..'9'|'a'..'f'|'A'..'F')*)
| '0x' ('0'..'9'|'a'..'f'|'A'..'F')+ ('.' ('0'..'9'|'a'..'f'|'A'..'F')*)? (('p'|'P') '-'? ('0'..'9'|'a'..'f'|'A'..'F')+)
;
DIGITS : ('1'..'9') ('0'..'9')*
;
HEXDIGITS : '0x' ('0'..'9'|'a'..'f'|'A'..'F')+
;
OCTDIGITS : '0' ('0'..'7')*
;
/*
* String logic.
*
* Strings are enclosed in double quotes and may contain escape sequences.
* Strings are sensitive to white space.
*/
QSTRING : '"'
( ~('\\'|'"'|'\u0000'..'\u001f')
| '\\\\'
| '\\a'
| '\\b'
| '\\t'
| '\\n'
| '\\v'
| '\\f'
| '\\r'
| '\\\''
| '\\"'
| '\\/'
| '\\' ('0'..'7') ('0'..'7') ('0'..'7')
| '\\' ('0'..'7') ('0'..'7')
| '\\' ('0'..'7')
| '\\x' ('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
| '\\u' ('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
| '\\U' ('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
)*
'"'
{ setText(handleEscapes(getText().substring(1, getText().length() - 1))); }
;
SQSTRING : '\''
( ~('\\'|'\''|'\u0000'..'\u001f')
| '\\\\'
| '\\a'
| '\\b'
| '\\t'
| '\\n'
| '\\v'
| '\\f'
| '\\r'
| '\\\''
| '\\"'
| '\\/'
| '\\' ('0'..'7') ('0'..'7') ('0'..'7')
| '\\' ('0'..'7') ('0'..'7')
| '\\' ('0'..'7')
| '\\x' ('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
| '\\u' ('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
| '\\U' ('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
('0'..'9' | 'a'..'f' | 'A'..'F')
)*
'\''
{ setText(handleEscapes(getText().substring(1, getText().length() - 1))); }
;
REGEX : '//'
( '/' (~('/'|'\\') | '\\' .)
| '\\' .
| ~('/')
)*
'//'
{ setText(getText().substring(2, getText().length() - 2).replace("\\/", "/")); }
;
LEFTSHIFT_KW : '<<'
;
RIGHTSHIFT_KW : '>>'
;
LE_KW : '<='
;
GE_KW : '>='
;
LT_KW : '<'
;
GT_KW : '>'
;
EQ_KW : '='
;
NEQ_KW : '!='
;
REGEX_MATCH_KW : '=~'
;
REGEX_NEGATE_KW : '!~'
;
LOGICAL_AND_KW : '&&'
;
LOGICAL_OR_KW : '||'
;
/*
* Tokens for trivial character literals.
*/
COMMA_LIT : ','
;
DOT_LIT : '.'
;
PLUS_LIT : '+'
;
DASH_LIT : '-'
;
DOLLAR_LIT : '$'
;
BRACE_OPEN_LIT : '('
;
BRACE_CLOSE_LIT : ')'
;
SLASH_LIT : '/'
;
PERCENT_LIT : '%'
;
BANG_LIT : '!'
;
SQBRACE_OPEN_LIT : '['
;
SQBRACE_CLOSE_LIT: ']'
;
COLON_LIT : ':'
;
DOT_DOT_LIT : '..'
;
|
/*
* Copyright (c) 2016, Groupon, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of GROUPON 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.
*/
lexer grammar ConfigTokenizer;
options {
//backtrack = false;
//memoize = true;
//vocab = ConfigBnf;
//tokenVocab=ConfigBnf;
}
import MonsoonExprLexer;
@header {
import java.util.regex.Matcher;
import java.util.regex.Pattern;
}
ENDSTATEMENT_KW : ';'
;
COMMENT : '#' ~('\n')*
{ skip(); }
;
IMPORT_KW : 'import'
;
COLLECTORS_KW : 'collectors'
;
ALL_KW : 'all'
;
FROM_KW : 'from'
;
COLLECT_KW : 'collect'
;
CONSTANT_KW : 'constant'
;
ALERT_KW : 'alert'
;
IF_KW : 'if'
;
MESSAGE_KW : 'message'
;
FOR_KW : 'for'
;
MATCH_KW : 'match'
;
AS_KW : 'as'
;
ATTRIBUTES_KW : 'attributes'
;
WHERE_KW : 'where'
;
ALIAS_KW : 'alias'
;
DEFINE_KW : 'define'
;
|
Use expression lexer in config tokenizer.
|
Use expression lexer in config tokenizer.
|
ANTLR
|
bsd-3-clause
|
groupon/monsoon,groupon/monsoon,groupon/monsoon,groupon/monsoon
|
e5bfbf0feb33e7a73e3eaf5e2518fa29aab5acfa
|
lib/kicad/src/main/antlr4/org/marsik/elshelves/kicad/Schema.g4
|
lib/kicad/src/main/antlr4/org/marsik/elshelves/kicad/Schema.g4
|
grammar Schema;
// Lexer Constants
WS: (' ' | '\t')+ -> skip;
NL: '\r'? '\n' -> skip;
HEADER: 'EESchema Schematic ' ('File' | 'Spins') ' Version ' ('1' | '2');
ENDOFSCHEMA: '$EndSCHEMATC';
LIBS: 'LIBS:';
EELAYER: 'EELAYER';
END: 'END';
DESCR: '$Descr';
ENDDESCR: '$EndDescr';
COMPONENT_START: '$Comp';
COMPONENT_END: '$EndComp';
// Lexer elements
fragment NameCharacter: [a-zA-Z0-9$_.-];
fragment Digit: [0-9];
fragment SheetClass: [A-E];
fragment SheetSize: [0-4];
fragment EscapeSequence: '\\' [btnfr"'\\];
fragment StringCharacter: ~["\\] | EscapeSequence;
String: '"' StringCharacter* '"';
Number: Digit Digit*;
Name: NameCharacter NameCharacter*;
// Top level nonterminal
schema: HEADER libs layer description item* ENDOFSCHEMA;
// Other rules
layer: EELAYER Number Number EELAYER END;
libs: (LIBS Name)*;
description: DESCR sheetSize=Name sheetWidth=Number sheetHeight=Number description_content* ENDDESCR;
description_content: String | Number | Name;
item: component;
component: COMPONENT_START COMPONENT_END;
|
grammar Schema;
// Lexer Constants
WS: (' ' | '\t')+ -> skip;
NL: '\r'? '\n' -> skip;
HEADER: 'EESchema Schematic ' ('File' | 'Spins') ' Version ' ('1' | '2');
ENDOFSCHEMA: '$EndSCHEMATC';
LIBS: 'LIBS:';
EELAYER: 'EELAYER';
END: 'END';
DESCR: '$Descr';
ENDDESCR: '$EndDescr';
COMPONENT_START: '$Comp';
COMPONENT_END: '$EndComp';
// Hidden lexer elements (no token is generated)
fragment NameCharacter: [a-zA-Z0-9$_.-];
fragment Digit: [0-9];
fragment SheetClass: [A-E];
fragment SheetSize: [0-4];
fragment EscapeSequence: '\\' [btnfr"'\\];
fragment StringCharacter: ~["\\] | EscapeSequence;
// Lexer elements
String: '"' StringCharacter* '"';
Number: Digit Digit*;
Name: NameCharacter NameCharacter*;
// Top level nonterminal
schema: HEADER libs layer description item* ENDOFSCHEMA;
// Other rules
layer: EELAYER Number Number EELAYER END;
libs: lib*;
lib: LIBS name=Name;
description: DESCR sheetSize=Name sheetWidth=Number sheetHeight=Number description_content* ENDDESCR;
description_content: String | Number | Name;
item: component;
component: COMPONENT_START COMPONENT_END;
|
Fix grammar comments
|
Fix grammar comments
|
ANTLR
|
agpl-3.0
|
MarSik/shelves,MarSik/shelves,MarSik/shelves,MarSik/shelves
|
30f7a20da4571259881c3c7eb74e7867c985f439
|
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
|
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
|
grammar SQLServerDCLStatement;
import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol;
permissions
: ID *?
;
|
grammar SQLServerDCLStatement;
import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol;
permissionOnColumns
: permission columnList?
;
permission
: ID *?
;
|
add permissionOnColumns
|
add permissionOnColumns
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
aba1c22c7062279a3bd26f81413cf5bf72a21b91
|
javascript/JavaScriptParser.g4
|
javascript/JavaScriptParser.g4
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 by Bart Kiers (original author) and Alexandre Vitorelli (contributor -> ported to CSharp)
* Copyright (c) 2017 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)
*
* 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.
*/
parser grammar JavaScriptParser;
options {
tokenVocab=JavaScriptLexer;
superClass=JavaScriptBaseParser;
}
program
: sourceElements? EOF
;
sourceElement
: Export? statement
;
statement
: block
| variableStatement
| emptyStatement
| expressionStatement
| ifStatement
| iterationStatement
| continueStatement
| breakStatement
| returnStatement
| withStatement
| labelledStatement
| switchStatement
| throwStatement
| tryStatement
| debuggerStatement
| functionDeclaration
| classDeclaration
;
block
: '{' statementList? '}'
;
statementList
: statement+
;
variableStatement
: varModifier variableDeclarationList eos
;
variableDeclarationList
: variableDeclaration (',' variableDeclaration)*
;
variableDeclaration
: (Identifier | arrayLiteral | objectLiteral) ('=' singleExpression)? // ECMAScript 6: Array & Object Matching
;
emptyStatement
: SemiColon
;
expressionStatement
: {this.notOpenBraceAndNotFunction()}? expressionSequence eos
;
ifStatement
: If '(' expressionSequence ')' statement (Else statement)?
;
iterationStatement
: Do statement While '(' expressionSequence ')' eos # DoStatement
| While '(' expressionSequence ')' statement # WhileStatement
| For '(' expressionSequence? ';' expressionSequence? ';' expressionSequence? ')' statement # ForStatement
| For '(' varModifier variableDeclarationList ';' expressionSequence? ';' expressionSequence? ')'
statement # ForVarStatement
| For '(' singleExpression (In | Identifier{this.p("of")}?) expressionSequence ')' statement # ForInStatement
| For '(' varModifier variableDeclaration (In | Identifier{this.p("of")}?) expressionSequence ')' statement # ForVarInStatement
;
varModifier // let, const - ECMAScript 6
: Var
| Let
| Const
;
continueStatement
: Continue ({this.notLineTerminator()}? Identifier)? eos
;
breakStatement
: Break ({this.notLineTerminator()}? Identifier)? eos
;
returnStatement
: Return ({this.notLineTerminator()}? expressionSequence)? eos
;
withStatement
: With '(' expressionSequence ')' statement
;
switchStatement
: Switch '(' expressionSequence ')' caseBlock
;
caseBlock
: '{' caseClauses? (defaultClause caseClauses?)? '}'
;
caseClauses
: caseClause+
;
caseClause
: Case expressionSequence ':' statementList?
;
defaultClause
: Default ':' statementList?
;
labelledStatement
: Identifier ':' statement
;
throwStatement
: Throw {this.notLineTerminator()}? expressionSequence eos
;
tryStatement
: Try block (catchProduction finallyProduction? | finallyProduction)
;
catchProduction
: Catch '(' Identifier ')' block
;
finallyProduction
: Finally block
;
debuggerStatement
: Debugger eos
;
functionDeclaration
: Function Identifier '(' formalParameterList? ')' '{' functionBody '}'
;
classDeclaration
: Class Identifier classTail
;
classTail
: (Extends singleExpression)? '{' classElement* '}'
;
classElement
: (Static | {n("static")}? Identifier)? methodDefinition
| emptyStatement
;
methodDefinition
: propertyName '(' formalParameterList? ')' '{' functionBody '}'
| getter '(' ')' '{' functionBody '}'
| setter '(' formalParameterList? ')' '{' functionBody '}'
| generatorMethod
;
generatorMethod
: '*'? Identifier '(' formalParameterList? ')' '{' functionBody '}'
;
formalParameterList
: formalParameterArg (',' formalParameterArg)* (',' lastFormalParameterArg)?
| lastFormalParameterArg
| arrayLiteral // ECMAScript 6: Parameter Context Matching
| objectLiteral // ECMAScript 6: Parameter Context Matching
;
formalParameterArg
: Identifier ('=' singleExpression)? // ECMAScript 6: Initialization
;
lastFormalParameterArg // ECMAScript 6: Rest Parameter
: Ellipsis Identifier
;
functionBody
: sourceElements?
;
sourceElements
: sourceElement+
;
arrayLiteral
: '[' ','* elementList? ','* ']'
;
elementList
: singleExpression (','+ singleExpression)* (','+ lastElement)?
| lastElement
;
lastElement // ECMAScript 6: Spread Operator
: Ellipsis Identifier
;
objectLiteral
: '{' (propertyAssignment (',' propertyAssignment)*)? ','? '}'
;
propertyAssignment
: propertyName (':' |'=') singleExpression # PropertyExpressionAssignment
| '[' singleExpression ']' ':' singleExpression # ComputedPropertyExpressionAssignment
| getter '(' ')' '{' functionBody '}' # PropertyGetter
| setter '(' Identifier ')' '{' functionBody '}' # PropertySetter
| generatorMethod # MethodProperty
| Identifier # PropertyShorthand
;
propertyName
: identifierName
| StringLiteral
| numericLiteral
;
arguments
: '('(
singleExpression (',' singleExpression)* (',' lastArgument)? |
lastArgument
)?')'
;
lastArgument // ECMAScript 6: Spread Operator
: Ellipsis Identifier
;
expressionSequence
: singleExpression (',' singleExpression)*
;
singleExpression
: Function Identifier? '(' formalParameterList? ')' '{' functionBody '}' # FunctionExpression
| Class Identifier? classTail # ClassExpression
| singleExpression '[' expressionSequence ']' # MemberIndexExpression
| singleExpression '.' identifierName # MemberDotExpression
| singleExpression arguments # ArgumentsExpression
| New singleExpression arguments? # NewExpression
| singleExpression {this.notLineTerminator()}? '++' # PostIncrementExpression
| singleExpression {this.notLineTerminator()}? '--' # PostDecreaseExpression
| Delete singleExpression # DeleteExpression
| Void singleExpression # VoidExpression
| Typeof singleExpression # TypeofExpression
| '++' singleExpression # PreIncrementExpression
| '--' singleExpression # PreDecreaseExpression
| '+' singleExpression # UnaryPlusExpression
| '-' singleExpression # UnaryMinusExpression
| '~' singleExpression # BitNotExpression
| '!' singleExpression # NotExpression
| singleExpression ('*' | '/' | '%') singleExpression # MultiplicativeExpression
| singleExpression ('+' | '-') singleExpression # AdditiveExpression
| singleExpression ('<<' | '>>' | '>>>') singleExpression # BitShiftExpression
| singleExpression ('<' | '>' | '<=' | '>=') singleExpression # RelationalExpression
| singleExpression Instanceof singleExpression # InstanceofExpression
| singleExpression In singleExpression # InExpression
| singleExpression ('==' | '!=' | '===' | '!==') singleExpression # EqualityExpression
| singleExpression '&' singleExpression # BitAndExpression
| singleExpression '^' singleExpression # BitXOrExpression
| singleExpression '|' singleExpression # BitOrExpression
| singleExpression '&&' singleExpression # LogicalAndExpression
| singleExpression '||' singleExpression # LogicalOrExpression
| singleExpression '?' singleExpression ':' singleExpression # TernaryExpression
| singleExpression '=' singleExpression # AssignmentExpression
| singleExpression assignmentOperator singleExpression # AssignmentOperatorExpression
| singleExpression TemplateStringLiteral # TemplateStringExpression // ECMAScript 6
| This # ThisExpression
| Identifier # IdentifierExpression
| Super # SuperExpression
| literal # LiteralExpression
| arrayLiteral # ArrayLiteralExpression
| objectLiteral # ObjectLiteralExpression
| '(' expressionSequence ')' # ParenthesizedExpression
| arrowFunctionParameters '=>' arrowFunctionBody # ArrowFunctionExpression // ECMAScript 6
;
arrowFunctionParameters
: Identifier
| '(' formalParameterList? ')'
;
arrowFunctionBody
: singleExpression
| '{' functionBody '}'
;
assignmentOperator
: '*='
| '/='
| '%='
| '+='
| '-='
| '<<='
| '>>='
| '>>>='
| '&='
| '^='
| '|='
;
literal
: NullLiteral
| BooleanLiteral
| StringLiteral
| TemplateStringLiteral
| RegularExpressionLiteral
| numericLiteral
;
numericLiteral
: DecimalLiteral
| HexIntegerLiteral
| OctalIntegerLiteral
| OctalIntegerLiteral2
| BinaryIntegerLiteral
;
identifierName
: Identifier
| reservedWord
;
reservedWord
: keyword
| NullLiteral
| BooleanLiteral
;
keyword
: Break
| Do
| Instanceof
| Typeof
| Case
| Else
| New
| Var
| Catch
| Finally
| Return
| Void
| Continue
| For
| Switch
| While
| Debugger
| Function
| This
| With
| Default
| If
| Throw
| Delete
| In
| Try
| Class
| Enum
| Extends
| Super
| Const
| Export
| Import
| Implements
| Let
| Private
| Public
| Interface
| Package
| Protected
| Static
| Yield
;
getter
: Identifier{this.p("get")}? propertyName
;
setter
: Identifier{this.p("set")}? propertyName
;
eos
: SemiColon
| EOF
| {this.lineTerminatorAhead()}?
| {this.closeBrace()}?
;
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 by Bart Kiers (original author) and Alexandre Vitorelli (contributor -> ported to CSharp)
* Copyright (c) 2017 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)
*
* 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.
*/
parser grammar JavaScriptParser;
options {
tokenVocab=JavaScriptLexer;
superClass=JavaScriptBaseParser;
}
program
: sourceElements? EOF
;
sourceElement
: Export? statement
;
statement
: block
| variableStatement
| emptyStatement
| classDeclaration
| expressionStatement
| ifStatement
| iterationStatement
| continueStatement
| breakStatement
| returnStatement
| withStatement
| labelledStatement
| switchStatement
| throwStatement
| tryStatement
| debuggerStatement
| functionDeclaration
;
block
: '{' statementList? '}'
;
statementList
: statement+
;
variableStatement
: varModifier variableDeclarationList eos
;
variableDeclarationList
: variableDeclaration (',' variableDeclaration)*
;
variableDeclaration
: (Identifier | arrayLiteral | objectLiteral) ('=' singleExpression)? // ECMAScript 6: Array & Object Matching
;
emptyStatement
: SemiColon
;
expressionStatement
: {this.notOpenBraceAndNotFunction()}? expressionSequence eos
;
ifStatement
: If '(' expressionSequence ')' statement (Else statement)?
;
iterationStatement
: Do statement While '(' expressionSequence ')' eos # DoStatement
| While '(' expressionSequence ')' statement # WhileStatement
| For '(' expressionSequence? ';' expressionSequence? ';' expressionSequence? ')' statement # ForStatement
| For '(' varModifier variableDeclarationList ';' expressionSequence? ';' expressionSequence? ')'
statement # ForVarStatement
| For '(' singleExpression (In | Identifier{this.p("of")}?) expressionSequence ')' statement # ForInStatement
| For '(' varModifier variableDeclaration (In | Identifier{this.p("of")}?) expressionSequence ')' statement # ForVarInStatement
;
varModifier // let, const - ECMAScript 6
: Var
| Let
| Const
;
continueStatement
: Continue ({this.notLineTerminator()}? Identifier)? eos
;
breakStatement
: Break ({this.notLineTerminator()}? Identifier)? eos
;
returnStatement
: Return ({this.notLineTerminator()}? expressionSequence)? eos
;
withStatement
: With '(' expressionSequence ')' statement
;
switchStatement
: Switch '(' expressionSequence ')' caseBlock
;
caseBlock
: '{' caseClauses? (defaultClause caseClauses?)? '}'
;
caseClauses
: caseClause+
;
caseClause
: Case expressionSequence ':' statementList?
;
defaultClause
: Default ':' statementList?
;
labelledStatement
: Identifier ':' statement
;
throwStatement
: Throw {this.notLineTerminator()}? expressionSequence eos
;
tryStatement
: Try block (catchProduction finallyProduction? | finallyProduction)
;
catchProduction
: Catch '(' Identifier ')' block
;
finallyProduction
: Finally block
;
debuggerStatement
: Debugger eos
;
functionDeclaration
: Function Identifier '(' formalParameterList? ')' '{' functionBody '}'
;
classDeclaration
: Class Identifier classTail
;
classTail
: (Extends singleExpression)? '{' classElement* '}'
;
classElement
: (Static | {n("static")}? Identifier)? methodDefinition
| emptyStatement
;
methodDefinition
: propertyName '(' formalParameterList? ')' '{' functionBody '}'
| getter '(' ')' '{' functionBody '}'
| setter '(' formalParameterList? ')' '{' functionBody '}'
| generatorMethod
;
generatorMethod
: '*'? Identifier '(' formalParameterList? ')' '{' functionBody '}'
;
formalParameterList
: formalParameterArg (',' formalParameterArg)* (',' lastFormalParameterArg)?
| lastFormalParameterArg
| arrayLiteral // ECMAScript 6: Parameter Context Matching
| objectLiteral // ECMAScript 6: Parameter Context Matching
;
formalParameterArg
: Identifier ('=' singleExpression)? // ECMAScript 6: Initialization
;
lastFormalParameterArg // ECMAScript 6: Rest Parameter
: Ellipsis Identifier
;
functionBody
: sourceElements?
;
sourceElements
: sourceElement+
;
arrayLiteral
: '[' ','* elementList? ','* ']'
;
elementList
: singleExpression (','+ singleExpression)* (','+ lastElement)?
| lastElement
;
lastElement // ECMAScript 6: Spread Operator
: Ellipsis Identifier
;
objectLiteral
: '{' (propertyAssignment (',' propertyAssignment)*)? ','? '}'
;
propertyAssignment
: propertyName (':' |'=') singleExpression # PropertyExpressionAssignment
| '[' singleExpression ']' ':' singleExpression # ComputedPropertyExpressionAssignment
| getter '(' ')' '{' functionBody '}' # PropertyGetter
| setter '(' Identifier ')' '{' functionBody '}' # PropertySetter
| generatorMethod # MethodProperty
| Identifier # PropertyShorthand
;
propertyName
: identifierName
| StringLiteral
| numericLiteral
;
arguments
: '('(
singleExpression (',' singleExpression)* (',' lastArgument)? |
lastArgument
)?')'
;
lastArgument // ECMAScript 6: Spread Operator
: Ellipsis Identifier
;
expressionSequence
: singleExpression (',' singleExpression)*
;
singleExpression
: Function Identifier? '(' formalParameterList? ')' '{' functionBody '}' # FunctionExpression
| Class Identifier? classTail # ClassExpression
| singleExpression '[' expressionSequence ']' # MemberIndexExpression
| singleExpression '.' identifierName # MemberDotExpression
| singleExpression arguments # ArgumentsExpression
| New singleExpression arguments? # NewExpression
| singleExpression {this.notLineTerminator()}? '++' # PostIncrementExpression
| singleExpression {this.notLineTerminator()}? '--' # PostDecreaseExpression
| Delete singleExpression # DeleteExpression
| Void singleExpression # VoidExpression
| Typeof singleExpression # TypeofExpression
| '++' singleExpression # PreIncrementExpression
| '--' singleExpression # PreDecreaseExpression
| '+' singleExpression # UnaryPlusExpression
| '-' singleExpression # UnaryMinusExpression
| '~' singleExpression # BitNotExpression
| '!' singleExpression # NotExpression
| singleExpression ('*' | '/' | '%') singleExpression # MultiplicativeExpression
| singleExpression ('+' | '-') singleExpression # AdditiveExpression
| singleExpression ('<<' | '>>' | '>>>') singleExpression # BitShiftExpression
| singleExpression ('<' | '>' | '<=' | '>=') singleExpression # RelationalExpression
| singleExpression Instanceof singleExpression # InstanceofExpression
| singleExpression In singleExpression # InExpression
| singleExpression ('==' | '!=' | '===' | '!==') singleExpression # EqualityExpression
| singleExpression '&' singleExpression # BitAndExpression
| singleExpression '^' singleExpression # BitXOrExpression
| singleExpression '|' singleExpression # BitOrExpression
| singleExpression '&&' singleExpression # LogicalAndExpression
| singleExpression '||' singleExpression # LogicalOrExpression
| singleExpression '?' singleExpression ':' singleExpression # TernaryExpression
| singleExpression '=' singleExpression # AssignmentExpression
| singleExpression assignmentOperator singleExpression # AssignmentOperatorExpression
| singleExpression TemplateStringLiteral # TemplateStringExpression // ECMAScript 6
| This # ThisExpression
| Identifier # IdentifierExpression
| Super # SuperExpression
| literal # LiteralExpression
| arrayLiteral # ArrayLiteralExpression
| objectLiteral # ObjectLiteralExpression
| '(' expressionSequence ')' # ParenthesizedExpression
| arrowFunctionParameters '=>' arrowFunctionBody # ArrowFunctionExpression // ECMAScript 6
;
arrowFunctionParameters
: Identifier
| '(' formalParameterList? ')'
;
arrowFunctionBody
: singleExpression
| '{' functionBody '}'
;
assignmentOperator
: '*='
| '/='
| '%='
| '+='
| '-='
| '<<='
| '>>='
| '>>>='
| '&='
| '^='
| '|='
;
literal
: NullLiteral
| BooleanLiteral
| StringLiteral
| TemplateStringLiteral
| RegularExpressionLiteral
| numericLiteral
;
numericLiteral
: DecimalLiteral
| HexIntegerLiteral
| OctalIntegerLiteral
| OctalIntegerLiteral2
| BinaryIntegerLiteral
;
identifierName
: Identifier
| reservedWord
;
reservedWord
: keyword
| NullLiteral
| BooleanLiteral
;
keyword
: Break
| Do
| Instanceof
| Typeof
| Case
| Else
| New
| Var
| Catch
| Finally
| Return
| Void
| Continue
| For
| Switch
| While
| Debugger
| Function
| This
| With
| Default
| If
| Throw
| Delete
| In
| Try
| Class
| Enum
| Extends
| Super
| Const
| Export
| Import
| Implements
| Let
| Private
| Public
| Interface
| Package
| Protected
| Static
| Yield
;
getter
: Identifier{this.p("get")}? propertyName
;
setter
: Identifier{this.p("set")}? propertyName
;
eos
: SemiColon
| EOF
| {this.lineTerminatorAhead()}?
| {this.closeBrace()}?
;
|
Update JavaScriptParser.g4
|
Update JavaScriptParser.g4
Fixed invalid rules ordering in statement
|
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
|
16b072457354016d96ca98cbd44e21306cd8e1e0
|
antlr/antlr4/ANTLRv4Lexer.g4
|
antlr/antlr4/ANTLRv4Lexer.g4
|
/*
* [The "BSD license"]
* Copyright (c) 2012-2015 Terence Parr
* Copyright (c) 2012-2015 Sam Harwell
* Copyright (c) 2015 Gerald Rosenberg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* A grammar for ANTLR v4 implemented using v4 syntax
*
* Modified 2015.06.16 gbr
* -- update for compatibility with Antlr v4.5
*/
lexer grammar ANTLRv4Lexer;
options { superClass = LexerAdaptor; }
import LexBasic;
// Standard set of fragments
tokens { TOKEN_REF , RULE_REF , LEXER_CHAR_SET }
channels { OFF_CHANNEL , COMMENT }
// ======================================================
// Lexer specification
//
// -------------------------
// Comments
DOC_COMMENT
: DocComment
;
BLOCK_COMMENT
: BlockComment -> channel (COMMENT)
;
LINE_COMMENT
: LineComment -> channel (COMMENT)
;
// -------------------------
// Integer
//
INT
: DecimalNumeral
;
// -------------------------
// Literal string
//
// ANTLR makes no distinction between a single character literal and a
// multi-character string. All literals are single quote delimited and
// may contain unicode escape sequences of the form \uxxxx, where x
// is a valid hexadecimal number (per Unicode standard).
STRING_LITERAL
: SQuoteLiteral
;
UNTERMINATED_STRING_LITERAL
: USQuoteLiteral
;
// -------------------------
// Arguments
//
// Certain argument lists, such as those specifying call parameters
// to a rule invocation, or input parameters to a rule specification
// are contained within square brackets.
BEGIN_ARGUMENT
: LBrack
{ handleBeginArgument(); }
;
// -------------------------
// Target Language Actions
BEGIN_ACTION
: LBrace -> pushMode (TargetLanguageAction)
;
// -------------------------
// Keywords
//
// Keywords may not be used as labels for rules or in any other context where
// they would be ambiguous with the keyword vs some other identifier. OPTIONS,
// TOKENS, & CHANNELS blocks are handled idiomatically in dedicated lexical modes.
OPTIONS
: 'options' -> pushMode (Options)
;
TOKENS
: 'tokens' -> pushMode (Tokens)
;
CHANNELS
: 'channels' -> pushMode (Channels)
;
IMPORT
: 'import'
;
FRAGMENT
: 'fragment'
;
LEXER
: 'lexer'
;
PARSER
: 'parser'
;
GRAMMAR
: 'grammar'
;
PROTECTED
: 'protected'
;
PUBLIC
: 'public'
;
PRIVATE
: 'private'
;
RETURNS
: 'returns'
;
LOCALS
: 'locals'
;
THROWS
: 'throws'
;
CATCH
: 'catch'
;
FINALLY
: 'finally'
;
MODE
: 'mode'
;
// -------------------------
// Punctuation
COLON
: Colon
;
COLONCOLON
: DColon
;
COMMA
: Comma
;
SEMI
: Semi
;
LPAREN
: LParen
;
RPAREN
: RParen
;
LBRACE
: LBrace
;
RBRACE
: RBrace
;
RARROW
: RArrow
;
LT
: Lt
;
GT
: Gt
;
ASSIGN
: Equal
;
QUESTION
: Question
;
STAR
: Star
;
PLUS_ASSIGN
: PlusAssign
;
PLUS
: Plus
;
OR
: Pipe
;
DOLLAR
: Dollar
;
RANGE
: Range
;
DOT
: Dot
;
AT
: At
;
POUND
: Pound
;
NOT
: Tilde
;
// -------------------------
// Identifiers - allows unicode rule/token names
ID
: Id
;
// -------------------------
// Whitespace
WS
: Ws+ -> channel (OFF_CHANNEL)
;
// -------------------------
// Illegal Characters
//
// This is an illegal character trap which is always the last rule in the
// lexer specification. It matches a single character of any value and being
// the last rule in the file will match when no other rule knows what to do
// about the character. It is reported as an error but is not passed on to the
// parser. This means that the parser to deal with the gramamr file anyway
// but we will not try to analyse or code generate from a file with lexical
// errors.
//
// Comment this rule out to allow the error to be propagated to the parser
ERRCHAR
: . -> channel (HIDDEN)
;
// ======================================================
// Lexer modes
// -------------------------
// Arguments
mode Argument;
// E.g., [int x, List<String> a[]]
NESTED_ARGUMENT
: LBrack -> type (ARGUMENT_CONTENT) , pushMode (Argument)
;
ARGUMENT_ESCAPE
: EscAny -> type (ARGUMENT_CONTENT)
;
ARGUMENT_STRING_LITERAL
: DQuoteLiteral -> type (ARGUMENT_CONTENT)
;
ARGUMENT_CHAR_LITERAL
: SQuoteLiteral -> type (ARGUMENT_CONTENT)
;
END_ARGUMENT
: RBrack
{ handleEndArgument(); }
;
// added this to return non-EOF token type here. EOF does something weird
UNTERMINATED_ARGUMENT
: EOF -> popMode
;
ARGUMENT_CONTENT
: .
;
// -------------------------
// Target Language Actions
//
// Many language targets use {} as block delimiters and so we
// must recursively match {} delimited blocks to balance the
// braces. Additionally, we must make some assumptions about
// literal string representation in the target language. We assume
// that they are delimited by ' or " and so consume these
// in their own alts so as not to inadvertantly match {}.
mode TargetLanguageAction;
NESTED_ACTION
: LBrace -> type (ACTION_CONTENT) , pushMode (TargetLanguageAction)
;
ACTION_ESCAPE
: EscAny -> type (ACTION_CONTENT)
;
ACTION_STRING_LITERAL
: DQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_CHAR_LITERAL
: SQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_DOC_COMMENT
: DocComment -> type (ACTION_CONTENT)
;
ACTION_BLOCK_COMMENT
: BlockComment -> type (ACTION_CONTENT)
;
ACTION_LINE_COMMENT
: LineComment -> type (ACTION_CONTENT)
;
END_ACTION
: RBrace
{ handleEndAction(); }
;
UNTERMINATED_ACTION
: EOF -> popMode
;
ACTION_CONTENT
: .
;
// -------------------------
mode Options;
OPT_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (COMMENT)
;
OPT_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (COMMENT)
;
OPT_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (COMMENT)
;
OPT_LBRACE
: LBrace
{ handleOptionsLBrace(); }
;
OPT_RBRACE
: RBrace -> type (RBRACE) , popMode
;
OPT_ID
: Id -> type (ID)
;
OPT_DOT
: Dot -> type (DOT)
;
OPT_ASSIGN
: Equal -> type (ASSIGN)
;
OPT_STRING_LITERAL
: SQuoteLiteral -> type (STRING_LITERAL)
;
OPT_INT
: DecimalNumeral -> type (INT)
;
OPT_STAR
: Star -> type (STAR)
;
OPT_SEMI
: Semi -> type (SEMI)
;
OPT_WS
: Ws+ -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode Tokens;
TOK_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (COMMENT)
;
TOK_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (COMMENT)
;
TOK_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (COMMENT)
;
TOK_LBRACE
: LBrace -> type (LBRACE)
;
TOK_RBRACE
: RBrace -> type (RBRACE) , popMode
;
TOK_ID
: Id -> type (ID)
;
TOK_DOT
: Dot -> type (DOT)
;
TOK_COMMA
: Comma -> type (COMMA)
;
TOK_WS
: Ws+ -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode Channels;
// currently same as Tokens mode; distinguished by keyword
CHN_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (COMMENT)
;
CHN_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (COMMENT)
;
CHN_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (COMMENT)
;
CHN_LBRACE
: LBrace -> type (LBRACE)
;
CHN_RBRACE
: RBrace -> type (RBRACE) , popMode
;
CHN_ID
: Id -> type (ID)
;
CHN_DOT
: Dot -> type (DOT)
;
CHN_COMMA
: Comma -> type (COMMA)
;
CHN_WS
: Ws+ -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode LexerCharSet;
LEXER_CHAR_SET_BODY
: (~ [\]\\] | EscAny)+ -> more
;
LEXER_CHAR_SET
: RBrack -> popMode
;
UNTERMINATED_CHAR_SET
: EOF -> popMode
;
// ------------------------------------------------------------------------------
// Grammar specific Keywords, Punctuation, etc.
fragment Id
: NameStartChar NameChar*
;
|
/*
* [The "BSD license"]
* Copyright (c) 2012-2015 Terence Parr
* Copyright (c) 2012-2015 Sam Harwell
* Copyright (c) 2015 Gerald Rosenberg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* A grammar for ANTLR v4 implemented using v4 syntax
*
* Modified 2015.06.16 gbr
* -- update for compatibility with Antlr v4.5
*/
// ======================================================
// Lexer specification
// ======================================================
lexer grammar ANTLRv4Lexer;
options { superClass = Antlr2BGF.AntlrParser.LexerAdaptor; }
import LexBasic;
// Standard set of fragments
tokens { TOKEN_REF , RULE_REF , LEXER_CHAR_SET }
channels { OFF_CHANNEL , COMMENT }
// -------------------------
// Comments
DOC_COMMENT
: DocComment -> channel (COMMENT)
;
BLOCK_COMMENT
: BlockComment -> channel (COMMENT)
;
LINE_COMMENT
: LineComment -> channel (COMMENT)
;
// -------------------------
// Integer
INT
: DecimalNumeral
;
// -------------------------
// Literal string
//
// ANTLR makes no distinction between a single character literal and a
// multi-character string. All literals are single quote delimited and
// may contain unicode escape sequences of the form \uxxxx, where x
// is a valid hexadecimal number (per Unicode standard).
STRING_LITERAL
: SQuoteLiteral
;
UNTERMINATED_STRING_LITERAL
: USQuoteLiteral
;
// -------------------------
// Arguments
//
// Certain argument lists, such as those specifying call parameters
// to a rule invocation, or input parameters to a rule specification
// are contained within square brackets.
BEGIN_ARGUMENT
: LBrack
{ handleBeginArgument(); }
;
// -------------------------
// Target Language Actions
BEGIN_ACTION
: LBrace -> pushMode (TargetLanguageAction)
;
// -------------------------
// Keywords
//
// Keywords may not be used as labels for rules or in any other context where
// they would be ambiguous with the keyword vs some other identifier. OPTIONS,
// TOKENS, & CHANNELS blocks are handled idiomatically in dedicated lexical modes.
OPTIONS
: 'options' -> pushMode (Options)
;
TOKENS
: 'tokens' -> pushMode (Tokens)
;
CHANNELS
: 'channels' -> pushMode (Channels)
;
IMPORT
: 'import'
;
FRAGMENT
: 'fragment'
;
LEXER
: 'lexer'
;
PARSER
: 'parser'
;
GRAMMAR
: 'grammar'
;
PROTECTED
: 'protected'
;
PUBLIC
: 'public'
;
PRIVATE
: 'private'
;
RETURNS
: 'returns'
;
LOCALS
: 'locals'
;
THROWS
: 'throws'
;
CATCH
: 'catch'
;
FINALLY
: 'finally'
;
MODE
: 'mode'
;
// -------------------------
// Punctuation
COLON
: Colon
;
COLONCOLON
: DColon
;
COMMA
: Comma
;
SEMI
: Semi
;
LPAREN
: LParen
;
RPAREN
: RParen
;
LBRACE
: LBrace
;
RBRACE
: RBrace
;
RARROW
: RArrow
;
LT
: Lt
;
GT
: Gt
;
ASSIGN
: Equal
;
QUESTION
: Question
;
STAR
: Star
;
PLUS_ASSIGN
: PlusAssign
;
PLUS
: Plus
;
OR
: Pipe
;
DOLLAR
: Dollar
;
RANGE
: Range
;
DOT
: Dot
;
AT
: At
;
POUND
: Pound
;
NOT
: Tilde
;
// -------------------------
// Identifiers - allows unicode rule/token names
ID
: Id
;
// -------------------------
// Whitespace
WS
: Ws+ -> channel (OFF_CHANNEL)
;
// -------------------------
// Illegal Characters
//
// This is an illegal character trap which is always the last rule in the
// lexer specification. It matches a single character of any value and being
// the last rule in the file will match when no other rule knows what to do
// about the character. It is reported as an error but is not passed on to the
// parser. This means that the parser to deal with the gramamr file anyway
// but we will not try to analyse or code generate from a file with lexical
// errors.
//
// Comment this rule out to allow the error to be propagated to the parser
// ERRCHAR
// : . -> channel (HIDDEN)
// ;
// ======================================================
// Lexer modes
// -------------------------
// Arguments
mode Argument;
// E.g., [int x, List<String> a[]]
NESTED_ARGUMENT
: LBrack -> type (ARGUMENT_CONTENT) , pushMode (Argument)
;
ARGUMENT_ESCAPE
: EscAny -> type (ARGUMENT_CONTENT)
;
ARGUMENT_STRING_LITERAL
: DQuoteLiteral -> type (ARGUMENT_CONTENT)
;
ARGUMENT_CHAR_LITERAL
: SQuoteLiteral -> type (ARGUMENT_CONTENT)
;
END_ARGUMENT
: RBrack
{ handleEndArgument(); }
;
// added this to return non-EOF token type here. EOF does something weird
UNTERMINATED_ARGUMENT
: EOF -> popMode
;
ARGUMENT_CONTENT
: .
;
// -------------------------
// Target Language Actions
//
// Many language targets use {} as block delimiters and so we
// must recursively match {} delimited blocks to balance the
// braces. Additionally, we must make some assumptions about
// literal string representation in the target language. We assume
// that they are delimited by ' or " and so consume these
// in their own alts so as not to inadvertantly match {}.
mode TargetLanguageAction;
NESTED_ACTION
: LBrace -> type (ACTION_CONTENT) , pushMode (TargetLanguageAction)
;
ACTION_ESCAPE
: EscAny -> type (ACTION_CONTENT)
;
ACTION_STRING_LITERAL
: DQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_CHAR_LITERAL
: SQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_DOC_COMMENT
: DocComment -> type (ACTION_CONTENT)
;
ACTION_BLOCK_COMMENT
: BlockComment -> type (ACTION_CONTENT)
;
ACTION_LINE_COMMENT
: LineComment -> type (ACTION_CONTENT)
;
END_ACTION
: RBrace
{ handleEndAction(); }
;
UNTERMINATED_ACTION
: EOF -> popMode
;
ACTION_CONTENT
: .
;
// -------------------------
mode Options;
OPT_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (COMMENT)
;
OPT_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (COMMENT)
;
OPT_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (COMMENT)
;
OPT_LBRACE
: LBrace
{ handleOptionsLBrace(); }
;
OPT_RBRACE
: RBrace -> type (RBRACE) , popMode
;
OPT_ID
: Id -> type (ID)
;
OPT_DOT
: Dot -> type (DOT)
;
OPT_ASSIGN
: Equal -> type (ASSIGN)
;
OPT_STRING_LITERAL
: SQuoteLiteral -> type (STRING_LITERAL)
;
OPT_INT
: DecimalNumeral -> type (INT)
;
OPT_STAR
: Star -> type (STAR)
;
OPT_SEMI
: Semi -> type (SEMI)
;
OPT_WS
: Ws+ -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode Tokens;
TOK_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (COMMENT)
;
TOK_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (COMMENT)
;
TOK_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (COMMENT)
;
TOK_LBRACE
: LBrace -> type (LBRACE)
;
TOK_RBRACE
: RBrace -> type (RBRACE) , popMode
;
TOK_ID
: Id -> type (ID)
;
TOK_DOT
: Dot -> type (DOT)
;
TOK_COMMA
: Comma -> type (COMMA)
;
TOK_WS
: Ws+ -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode Channels;
// currently same as Tokens mode; distinguished by keyword
CHN_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (COMMENT)
;
CHN_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (COMMENT)
;
CHN_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (COMMENT)
;
CHN_LBRACE
: LBrace -> type (LBRACE)
;
CHN_RBRACE
: RBrace -> type (RBRACE) , popMode
;
CHN_ID
: Id -> type (ID)
;
CHN_DOT
: Dot -> type (DOT)
;
CHN_COMMA
: Comma -> type (COMMA)
;
CHN_WS
: Ws+ -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode LexerCharSet;
LEXER_CHAR_SET_BODY
: (~ [\]\\] | EscAny)+ -> more
;
LEXER_CHAR_SET
: RBrack -> popMode
;
UNTERMINATED_CHAR_SET
: EOF -> popMode
;
// ------------------------------------------------------------------------------
// Grammar specific Keywords, Punctuation, etc.
fragment Id
: NameStartChar NameChar*
;
|
Update ANTLRv4Lexer.g4
|
Update ANTLRv4Lexer.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
|
c64d5540ec6cf65cafaefbf98e52a316c88f107c
|
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, Literals;
parameterMarker
: QUESTION_
;
number
: NUMBER_
;
string
: STRING_
| characterSet_? STRING_ collateClause_?
| IDENTIFIER_ STRING_ COLLATE (STRING_ | IDENTIFIER_)?
;
dateTimeLiterals
: (DATE | TIME | TIMESTAMP) STRING_
| LBE_ identifier_ STRING_ RBE_
;
hexadecimalLiterals
: HEX_DIGIT_
| characterSet_? HEX_DIGIT_ collateClause_?
;
bitValueLiterals
: BIT_NUM_
| characterSet_? BIT_NUM_ collateClause_?
;
booleanLiterals
: TRUE
| FALSE
;
nullValueLiterals
: NULL
;
literals_
: number
| string
| booleanLiterals
| nullValueLiterals
| bitValueLiterals
| hexadecimalLiterals
| dateTimeLiterals
;
identifier_
: IDENTIFIER_ | unreservedWord_
;
variable_
: (AT_ AT_)? (GLOBAL | PERSIST | PERSIST_ONLY | SESSION)? DOT_? identifier_
;
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
;
tableName
: (identifier_ DOT_)? identifier_
;
columnName
: (identifier_ DOT_)? identifier_
;
columnNames
: LP_ columnName (COMMA_ columnName)* RP_
;
indexName
: identifier_
;
expr
: expr logicalOperator_ expr
| notOperator_ expr
| LP_ expr RP_
| booleanPrimary_
;
notOperator_
: NOT | NOT_
;
logicalOperator_
: OR | OR_ | XOR | AND | AND_
;
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
;
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 | number | 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_ | CHARSET 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, Literals;
parameterMarker
: QUESTION_
;
numberLiterals
: NUMBER_
;
stringLiterals
: STRING_
| characterSet_? STRING_ collateClause_?
| IDENTIFIER_ STRING_ COLLATE (STRING_ | IDENTIFIER_)?
;
dateTimeLiterals
: (DATE | TIME | TIMESTAMP) STRING_
| LBE_ identifier_ STRING_ RBE_
;
hexadecimalLiterals
: HEX_DIGIT_
| characterSet_? HEX_DIGIT_ collateClause_?
;
bitValueLiterals
: BIT_NUM_
| characterSet_? BIT_NUM_ collateClause_?
;
booleanLiterals
: TRUE
| FALSE
;
nullValueLiterals
: NULL
;
literals_
: numberLiterals
| stringLiterals
| booleanLiterals
| nullValueLiterals
| bitValueLiterals
| hexadecimalLiterals
| dateTimeLiterals
;
identifier_
: IDENTIFIER_ | unreservedWord_
;
variable_
: (AT_ AT_)? (GLOBAL | PERSIST | PERSIST_ONLY | SESSION)? DOT_? identifier_
;
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
;
tableName
: (identifier_ DOT_)? identifier_
;
columnName
: (identifier_ DOT_)? identifier_
;
columnNames
: LP_ columnName (COMMA_ columnName)* RP_
;
indexName
: identifier_
;
expr
: expr logicalOperator_ expr
| notOperator_ expr
| LP_ expr RP_
| booleanPrimary_
;
notOperator_
: NOT | NOT_
;
logicalOperator_
: OR | OR_ | XOR | AND | AND_
;
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
;
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_ | CHARSET EQ_? ignoredIdentifier_
;
collateClause_
: COLLATE EQ_? (STRING_ | ignoredIdentifier_)
;
ignoredIdentifier_
: identifier_ (DOT_ identifier_)?
;
ignoredIdentifiers_
: ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*
;
|
rename to stringLiterals
|
rename to stringLiterals
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
|
649adb3d4c79d0987fa4f14406fa78e21cc6b49f
|
src/main/antlr/Graphql.g4
|
src/main/antlr/Graphql.g4
|
grammar Graphql;
@header {
package graphql.parser.antlr;
}
// Document
document : definition+;
definition:
operationDefinition |
fragmentDefinition
;
operationDefinition:
selectionSet |
operationType NAME? variableDefinitions? directives? selectionSet;
operationType : 'query' | 'mutation';
variableDefinitions : '(' variableDefinition+ ')';
variableDefinition : variable ':' type defaultValue?;
variable : '$' NAME;
defaultValue : '=' value;
// Operations
selectionSet : '{' selection+ '}';
selection :
field |
fragmentSpread |
inlineFragment;
field : alias? NAME arguments? directives? selectionSet?;
alias : NAME ':';
arguments : '(' argument+ ')';
argument : NAME ':' valueWithVariable;
// Fragments
fragmentSpread : '...' fragmentName directives?;
inlineFragment : '...' 'on' typeCondition directives? selectionSet;
fragmentDefinition : 'fragment' fragmentName 'on' typeCondition directives? selectionSet;
fragmentName : NAME;
typeCondition : typeName;
// Value
value :
IntValue |
FloatValue |
StringValue |
BooleanValue |
enumValue |
arrayValue |
objectValue;
valueWithVariable :
variable |
IntValue |
FloatValue |
StringValue |
BooleanValue |
enumValue |
arrayValueWithVariable |
objectValueWithVariable;
enumValue : NAME ;
// Array Value
arrayValue: '[' value* ']';
arrayValueWithVariable: '[' valueWithVariable* ']';
// Object Value
objectValue: '{' objectField* '}';
objectValueWithVariable: '{' objectFieldWithVariable* '}';
objectField : NAME ':' value;
objectFieldWithVariable : NAME ':' valueWithVariable;
// Directives
directives : directive+;
directive :'@' NAME arguments?;
// Types
type : typeName | listType | nonNullType;
typeName : NAME;
listType : '[' type ']';
nonNullType: typeName '!' | listType '!';
// Token
BooleanValue: 'true' | 'false';
NAME: [_A-Za-z][_0-9A-Za-z]* ;
IntValue : Sign? IntegerPart;
FloatValue : Sign? IntegerPart ('.' Digit+)? ExponentPart?;
Sign : '-';
IntegerPart : '0' | NonZeroDigit | NonZeroDigit Digit+;
NonZeroDigit: '1'.. '9';
ExponentPart : ('e'|'E') Sign? Digit+;
Digit : '0'..'9';
StringValue: '"' (~(["\\\n\r\u2028\u2029])|EscapedChar)* '"';
fragment EscapedChar : '\\' (["\\/bfnrt] | Unicode) ;
fragment Unicode : 'u' Hex Hex Hex Hex ;
fragment Hex : [0-9a-fA-F] ;
Ignored: (Whitespace|Comma|LineTerminator|Comment) -> skip;
fragment Comment: '#' ~[\n\r\u2028\u2029]*;
fragment LineTerminator: [\n\r\u2028\u2029];
fragment Whitespace : [\t\u000b\f\u0020\u00a0];
fragment Comma : ',';
|
grammar Graphql;
@header {
package graphql.parser.antlr;
}
// Document
document : definition+;
definition:
operationDefinition |
fragmentDefinition
;
operationDefinition:
selectionSet |
operationType NAME? variableDefinitions? directives? selectionSet;
operationType : NAME;
variableDefinitions : '(' variableDefinition+ ')';
variableDefinition : variable ':' type defaultValue?;
variable : '$' NAME;
defaultValue : '=' value;
// Operations
selectionSet : '{' selection+ '}';
selection :
field |
fragmentSpread |
inlineFragment;
field : alias? NAME arguments? directives? selectionSet?;
alias : NAME ':';
arguments : '(' argument+ ')';
argument : NAME ':' valueWithVariable;
// Fragments
fragmentSpread : '...' fragmentName directives?;
inlineFragment : '...' 'on' typeCondition directives? selectionSet;
fragmentDefinition : 'fragment' fragmentName 'on' typeCondition directives? selectionSet;
fragmentName : NAME;
typeCondition : typeName;
// Value
value :
IntValue |
FloatValue |
StringValue |
BooleanValue |
enumValue |
arrayValue |
objectValue;
valueWithVariable :
variable |
IntValue |
FloatValue |
StringValue |
BooleanValue |
enumValue |
arrayValueWithVariable |
objectValueWithVariable;
enumValue : NAME ;
// Array Value
arrayValue: '[' value* ']';
arrayValueWithVariable: '[' valueWithVariable* ']';
// Object Value
objectValue: '{' objectField* '}';
objectValueWithVariable: '{' objectFieldWithVariable* '}';
objectField : NAME ':' value;
objectFieldWithVariable : NAME ':' valueWithVariable;
// Directives
directives : directive+;
directive :'@' NAME arguments?;
// Types
type : typeName | listType | nonNullType;
typeName : NAME;
listType : '[' type ']';
nonNullType: typeName '!' | listType '!';
// Token
BooleanValue: 'true' | 'false';
NAME: [_A-Za-z][_0-9A-Za-z]* ;
IntValue : Sign? IntegerPart;
FloatValue : Sign? IntegerPart ('.' Digit+)? ExponentPart?;
Sign : '-';
IntegerPart : '0' | NonZeroDigit | NonZeroDigit Digit+;
NonZeroDigit: '1'.. '9';
ExponentPart : ('e'|'E') Sign? Digit+;
Digit : '0'..'9';
StringValue: '"' (~(["\\\n\r\u2028\u2029])|EscapedChar)* '"';
fragment EscapedChar : '\\' (["\\/bfnrt] | Unicode) ;
fragment Unicode : 'u' Hex Hex Hex Hex ;
fragment Hex : [0-9a-fA-F] ;
Ignored: (Whitespace|Comma|LineTerminator|Comment) -> skip;
fragment Comment: '#' ~[\n\r\u2028\u2029]*;
fragment LineTerminator: [\n\r\u2028\u2029];
fragment Whitespace : [\t\u000b\f\u0020\u00a0];
fragment Comma : ',';
|
Update ANTLR grammar to fix #213
|
Update ANTLR grammar to fix #213
|
ANTLR
|
mit
|
blevandowski-lv/graphql-java,dminkovsky/graphql-java,fderose/graphql-java,graphql-java/graphql-java,blevandowski-lv/graphql-java,graphql-java/graphql-java,fderose/graphql-java,dminkovsky/graphql-java
|
bcd7751bb78f37a6d938a873f491a7b1c5f1e69c
|
src/main/antlr/BrygParser.g4
|
src/main/antlr/BrygParser.g4
|
parser grammar BrygParser;
// TODO: Find a way to do: if (...) a else b
// TODO: Rename ifExpression and eachExpression to *Statement, because they aren't expressions.
options {
tokenVocab = BrygLexer;
}
@header {
package io.collap.bryg.parser;
}
start
: (inDeclaration | NEWLINE)*
(statement | NEWLINE)*
EOF // EOF is needed for SLL(*) parsing! Otherwise no exception is thrown, which is needed to induce LL(*) parsing.
;
inDeclaration
: qualifier=(IN | OPT) type id
NEWLINE
;
statement
: ifStatement
| eachStatement
| whileStatement
| variableDeclaration
NEWLINE
| blockFunctionCall
| expression
NEWLINE
| statementFunctionCall /* This rule has to be placed after expression, because otherwise an expression
like a - 7 would be interpreted as a statementFunctionCall with an arithmetic
negation (that leads to the number -7) instead of a binary subtraction. */
| templateFragmentCall
NEWLINE
;
/**
* This rule is executed separately when the compiler finds an unescaped interpolation sequence (\{...}) in a string.
*/
interpolation
: expression NEWLINE
;
expression
: literal # literalExpression
| '(' expression ')' # expressionPrecedenceOrder
| expression '.' id # accessExpression
| expression '.' functionCall # methodCallExpression
| functionCall # functionCallExpression
| variable # variableExpression
| '(' type ')' expression # castExpression
| expression op=('++' | '--') # unaryPostfixExpression
| op=('+' | '-' | '++' | '--') expression # unaryPrefixExpression
| op=('~' | NOT) expression # unaryOperationExpression
| expression op=('*' | '/' | '%') expression # binaryMulDivRemExpression
| expression op=('+' | '-') expression # binaryAddSubExpression
| expression op=('<<' | '>>>' | '>>') expression # binaryShiftExpression
| expression op=('<=' | '>=' | '>' | '<') expression # binaryRelationalExpression
| expression 'is' type # binaryIsExpression // TODO: Implement
| expression op=('==' | '!=') expression # binaryEqualityExpression
| expression op=('===' | '!==') expression # binaryReferenceEqualityExpression
| expression '&' expression # binaryBitwiseAndExpression
| expression '^' expression # binaryBitwiseXorExpression
| expression '|' expression # binaryBitwiseOrExpression
| expression AND expression # binaryLogicalAndExpression
| expression OR expression # binaryLogicalOrExpression
| <assoc=right> expression
op=
( '='
| '+='
| '-='
| '*='
| '/='
| '%='
| '&='
| '|='
| '^='
| '>>='
| '>>>='
| '<<='
)
expression # binaryAssignmentExpression
;
ifStatement
: IF
( '(' expression ')' statement // This has to be statement, otherwise an ambiguity is created
// in conjunction with normal parentheses in expressions!
| expression NEWLINE block
)
(ELSE statementOrBlock)?
;
eachStatement
: EACH
( '(' eachHead ')' statementOrBlock
| eachHead NEWLINE block
)
;
eachHead
: type? element=id (',' index=id)? IN expression
;
whileStatement
: WHILE
( '(' condition=expression ')' statement
| condition=expression NEWLINE block
)
;
block
: INDENT
statement*
DEDENT
;
statementOrBlock
: NEWLINE block
| statement
;
variable
: id // Note that it is possible for a recognized variable to be a trivial function.
;
variableDeclaration
: (MUT | VAL)
type? id
('=' expression)?
;
functionCall
: id argumentList
;
blockFunctionCall
: id argumentList?
NEWLINE block
;
statementFunctionCall
: id argumentList?
statement
;
/* Calls functions of other templates. By default, 'render' is called. */
templateFragmentCall
: templateId argumentList?
;
templateId
: '@' (id '.') id
;
argumentList
: '(' (argument (',' argument)*)? ')'
;
argument
: argumentId? expression
;
argumentId
: id ('-' id)*
;
literal
: String # stringLiteral
| Integer # integerLiteral
| Double # doubleLiteral
| Float # floatLiteral
| NULL # nullLiteral
| value=(TRUE | FALSE) # booleanLiteral
;
type
: id
('<' type (',' type)* '>')?
;
id
: Identifier
| '`'
( Identifier
| NOT
| AND
| OR
| IN
| OPT
| IS
| EACH
| WHILE
| ELSE
| IF
| MUT
| VAL
| NULL
| TRUE
| FALSE
)
'`'
;
|
parser grammar BrygParser;
// TODO: Find a way to do: if (...) a else b
// TODO: Rename ifExpression and eachExpression to *Statement, because they aren't expressions.
options {
tokenVocab = BrygLexer;
}
@header {
package io.collap.bryg.parser;
}
start
: (inDeclaration | NEWLINE)*
(statement | NEWLINE)*
EOF // EOF is needed for SLL(*) parsing! Otherwise no exception is thrown, which is needed to induce LL(*) parsing.
;
inDeclaration
: qualifier=(IN | OPT) type id
NEWLINE
;
statement
: ifStatement
| eachStatement
| whileStatement
| variableDeclaration
NEWLINE
| blockFunctionCall
| expression
NEWLINE
| statementFunctionCall /* This rule has to be placed after expression, because otherwise an expression
like a - 7 would be interpreted as a statementFunctionCall with an arithmetic
negation (that leads to the number -7) instead of a binary subtraction. */
| templateFragmentCall
NEWLINE
;
/**
* This rule is executed separately when the compiler finds an unescaped interpolation sequence (\{...}) in a string.
*/
interpolation
: expression NEWLINE
;
expression
: literal # literalExpression
| '(' expression ')' # expressionPrecedenceOrder
| expression '.' id # accessExpression
| expression '.' functionCall # methodCallExpression
| functionCall # functionCallExpression
| variable # variableExpression
| '(' type ')' expression # castExpression
| expression op=('++' | '--') # unaryPostfixExpression
| op=('+' | '-' | '++' | '--') expression # unaryPrefixExpression
| op=('~' | NOT) expression # unaryOperationExpression
| expression op=('*' | '/' | '%') expression # binaryMulDivRemExpression
| expression op=('+' | '-') expression # binaryAddSubExpression
| expression op=('<<' | '>>>' | '>>') expression # binaryShiftExpression
| expression op=('<=' | '>=' | '>' | '<') expression # binaryRelationalExpression
| expression 'is' type # binaryIsExpression // TODO: Implement
| expression op=('==' | '!=') expression # binaryEqualityExpression
| expression op=('===' | '!==') expression # binaryReferenceEqualityExpression
| expression '&' expression # binaryBitwiseAndExpression
| expression '^' expression # binaryBitwiseXorExpression
| expression '|' expression # binaryBitwiseOrExpression
| expression AND expression # binaryLogicalAndExpression
| expression OR expression # binaryLogicalOrExpression
| <assoc=right> expression
op=
( '='
| '+='
| '-='
| '*='
| '/='
| '%='
| '&='
| '|='
| '^='
| '>>='
| '>>>='
| '<<='
)
expression # binaryAssignmentExpression
;
ifStatement
: IF
( '(' expression ')' statement // This has to be statement, otherwise an ambiguity is created
// in conjunction with normal parentheses in expressions!
| expression NEWLINE block
)
(ELSE statementOrBlock)?
;
eachStatement
: EACH
( '(' eachHead ')' statementOrBlock
| eachHead NEWLINE block
)
;
eachHead
: type? element=id (',' index=id)? IN expression
;
whileStatement
: WHILE
( '(' condition=expression ')' statement
| condition=expression NEWLINE block
)
;
block
: INDENT
statement*
DEDENT
;
statementOrBlock
: NEWLINE block
| statement
;
variable
: id // Note that it is possible for a recognized variable to be a trivial function.
;
variableDeclaration
: (MUT | VAL)
type? id
('=' expression)?
;
functionCall
: id argumentList
;
blockFunctionCall
: id argumentList?
NEWLINE block
;
statementFunctionCall
: id argumentList?
statement
;
/* Calls functions of other templates. By default, 'render' is called. */
templateFragmentCall
: templateId argumentList?
;
templateId
: '@' (id '.')* id
;
argumentList
: '(' (argument (',' argument)*)? ')'
;
argument
: argumentId? expression
;
argumentId
: id ('-' id)*
;
literal
: String # stringLiteral
| Integer # integerLiteral
| Double # doubleLiteral
| Float # floatLiteral
| NULL # nullLiteral
| value=(TRUE | FALSE) # booleanLiteral
;
type
: id
('<' type (',' type)* '>')?
;
id
: Identifier
| '`'
( Identifier
| NOT
| AND
| OR
| IN
| OPT
| IS
| EACH
| WHILE
| ELSE
| IF
| MUT
| VAL
| NULL
| TRUE
| FALSE
)
'`'
;
|
Fix multiple package levels not being allowed in template ids.
|
Fix multiple package levels not being allowed in template ids.
|
ANTLR
|
mit
|
Collap/bryg
|
20e5049b3ee7accd5b586c591b277fb714ec0081
|
rexx/RexxLexer.g4
|
rexx/RexxLexer.g4
|
lexer grammar RexxLexer;
// Main rules
// %INCLUDE statement
STMT_INCLUDE : Include_Statement ;
// Skippable stuff
LINE_COMMENT : Line_Comment_
-> channel(HIDDEN);
BLOCK_COMMENT : Block_Comment_
-> channel(HIDDEN);
WHISPACES : Whitespaces_ -> channel(HIDDEN);
CONTINUATION : Continue_ -> channel(HIDDEN);
// Keywords
KWD_ADDRESS : A D D R E S S ;
KWD_ARG : A R G ;
KWD_BY : B Y ;
KWD_CALL : C A L L ;
KWD_DIGITS : D I G I T S ;
KWD_DO : D O ;
KWD_DROP : D R O P ;
KWD_ELSE : E L S E ;
KWD_END : E N D ;
KWD_ENGINEERING : E N G I N E E R I N G ;
KWD_ERROR : E R R O R ;
KWD_EXIT : E X I T ;
KWD_EXPOSE : E X P O S E ;
KWD_EXTERNAL : E X T E R N A L ;
KWD_FAILURE : F A I L U R E ;
KWD_FOR : F O R ;
KWD_FOREVER : F O R E V E R ;
KWD_FORM : F O R M ;
KWD_FUZZ : F U Z Z ;
KWD_HALT : H A L T ;
KWD_IF : I F ;
KWD_INTERPRET : I N T E R P R E T ;
KWD_ITERATE : I T E R A T E ;
KWD_LEAVE : L E A V E ;
KWD_NAME : N A M E ;
KWD_NOP : N O P ;
KWD_NOVALUE : N O V A L U E ;
KWD_NUMERIC : N U M E R I C ;
KWD_OFF : O F F ;
KWD_ON : O N ;
KWD_OPTIONS : O P T I O N S ;
KWD_OTHERWISE : O T H E R W I S E ;
KWD_PARSE : P A R S E ;
KWD_PROCEDURE : P R O C E D U R E ;
KWD_PULL : P U L L ;
KWD_PUSH : P U S H ;
KWD_QUEUE : Q U E U E ;
KWD_RETURN : R E T U R N ;
KWD_SAY : S A Y ;
KWD_SCIENTIFIC : S C I E N T I F I C ;
KWD_SELECT : S E L E C T ;
KWD_SIGNAL : S I G N A L ;
KWD_SOURCE : S O U R C E ;
KWD_SYNTAX : S Y N T A X ;
KWD_THEN : T H E N ;
KWD_TO : T O ;
KWD_TRACE : T R A C E ;
KWD_UNTIL : U N T I L ;
KWD_UPPER : U P P E R ;
KWD_VALUE : V A L U E ;
KWD_VAR : V A R ;
KWD_VERSION : V E R S I O N ;
KWD_WHEN : W H E N ;
KWD_WHILE : W H I L E ;
KWD_WITH : W I T H ;
// Brackets
BR_O : Br_O_ ;
BR_C : Br_C_ ;
// Special variables: RC, RESULT, SIGL
SPECIAL_VAR : R C
| R E S U L T
| S I G L
;
// Label, const, var, number
NUMBER : Number_ ;
CONST_SYMBOL : Const_symbol_ ;
VAR_SYMBOL : Var_Symbol_ ;
// String and concatenation
STRING : String_
// Additionally, need to consume X or B at the end not followed by
// _!?A-Za-z.#@$0-9
{int currPos = this.getCharIndex();
int textLen = super.getInputStream().size();
if (textLen > currPos) {
if (textLen == currPos + 1) {
if (super.getInputStream()
.getText(
new Interval(currPos, currPos))
.matches("[XxBb]"))
super.getInputStream().consume();
} else {
if (super.getInputStream().getText(
new Interval(currPos, currPos + 1))
.matches("[XxBb][^_!?A-Za-z.#@$0-9]"))
super.getInputStream().consume();
}
}}
;
// In concatenation don't need the blanks - will be precoeesed by WHITESPACES
CONCAT : VBar_ VBar_ ;
// Operations
// Assignment (also comparison and template operator)
EQ : Eq_ ;
// Math: +, -, *, /, //, %, **
// Note: '+' and '-' are also used in prefix expressions and templates
PLUS : Plus_ ;
MINUS : Minus_ ;
MUL : Asterisk_ ;
DIV : Slash_ ;
QUOTINENT : Percent_sign_ ;
REMAINDER : Slash_ Slash_ ;
POW : Asterisk_ Asterisk_ ;
// Logical: NOT, OR, AND, XOR
// Note: '\\' also used for prefix expressions
NOT : Not_ ;
OR : VBar_ ;
XOR : Amp_ Amp_ ;
AND : Amp_ ;
// Comparison
// Strict comparison: ==, \==, >>, <<, >>=, <<=, \>>, \<<
CMPS_Eq : Eq_ Eq_ ;
CMPS_Neq : Not_ Eq_ Eq_ ;
CMPS_M : More_ More_ ;
CMPS_L : Less_ Less_ ;
CMPS_MEq : More_ More_ Eq_ ;
CMPS_LEq : Less_ Less_ Eq_ ;
CMPS_NM : Not_ More_ More_ ;
CMPS_NL : Not_ Less_ Less_ ;
// Non-strict: =, \=, <>, ><, >, <, >=, <=, \>, \<
// Note: '=' is taken from Assignment (EQ)
CMP_NEq : Not_ Eq_ ;
CMP_LM : Less_ More_ ;
CMP_ML : More_ Less_ ;
CMP_M : More_ ;
CMP_L : Less_ ;
CMP_MEq : More_ Eq_ ;
CMP_LEq : Less_ Eq_ ;
CMP_NM : Not_ More_ ;
CMP_NL : Not_ Less_ ;
// Additional elements
// .
STOP : Stop_ ;
// ,
COMMA : Comma_ ;
// :
COLON : Colon_ ;
// End of line
EOL : Eol_ ;
// Semicolumn
SEMICOL : Scol_ ;
// --------------------------------------------------------
// Fragments
// Comments
// Include statement - need to account for this
fragment Include_Statement : Comment_S Bo?
Percent_sign_ I N C L U D E
Bo Var_Symbol_+ Bo?
Comment_E
;
// Line comment - no EOL allowed inside.
fragment Line_Comment_ : Comment_S
Line_Commentpart*?
Asterisk_*?
( Comment_E | EOF )
;
fragment Line_Commentpart : Line_Comment_
| Slash_ Line_Comment_
| Slash_ ~[*\n\r]+?
| Asterisk_ ~[/\n\r]+?
| ~[/*\n\r]+
;
fragment Block_Comment_ : Comment_S
Block_Commentpart*?
Asterisk_*?
( Comment_E | EOF )
;
fragment Block_Commentpart : Block_Comment_
| Slash_ Block_Comment_
| Slash_ ~[*]+?
| Asterisk_ ~[/]+?
| ~[/*]+
;
fragment Comment_E : Asterisk_ Slash_ ;
fragment Comment_S : Slash_ Asterisk_ ;
// Whitespaces
fragment Whitespaces_ : Blank+ ;
// Continuation - full comments, but no EOL between
fragment Continue_ : Comma_
( Block_Comment_ | Line_Comment_ | Blank )*?
Eol_;
fragment Eol_ : New_Line_ Caret_Return_
| Caret_Return_ New_Line_
| New_Line_
| Caret_Return_
;
// Whitespaces
fragment Bo : Blank+ ;
fragment Blank : Space_
| Other_blank_character
;
fragment Other_blank_character : Form_Feed_
| HTab_
| VTab_
;
// Label, const, var, number
// Label, var
fragment Var_Symbol_ : General_letter Var_symbol_char*;
fragment Var_symbol_char : General_letter
| Digit_
| Stop_
;
fragment General_letter : Underscore_
| Exclamation_mark_
| Question_mark_
| A
| B
| C
| D
| E
| F
| G
| H
| I
| J
| K
| L
| M
| N
| O
| P
| Q
| R
| S
| T
| U
| V
| W
| X
| Y
| Z
| Extra_letter
;
fragment Extra_letter : Hash_
| At_
| Dollar_
;
// Const
fragment Const_symbol_ : Digit_ Var_symbol_char* ;
fragment Digit_ : [0-9] ;
// Number
fragment Number_ : Plain_number Exponent_? ;
fragment Plain_number : Digit_+ Stop_? Digit_*
| Stop_ Digit_+
;
fragment Exponent_ : E ( Plus_ | Minus_ )? Digit_+ ;
// String and concatenation
fragment String_ : Quoted_string ;
fragment Quoted_string : Quotation_mark_string
| Apostrophe_string
;
fragment Quotation_mark_string : Quote_ (String_char | Embedded_quotation_mark | Apostrophe_)* Quote_ ;
fragment Embedded_quotation_mark: Quote_ Quote_ ;
fragment Apostrophe_string : Apostrophe_ (String_char | Embedded_apostrophe | Quote_)* Apostrophe_ ;
fragment Embedded_apostrophe : Apostrophe_ Apostrophe_ ;
fragment String_char : String_or_comment_char | Asterisk_ | Slash_ ;
fragment String_or_comment_char : Digit_
| Stop_
| Special
| Operator_only
| General_letter
| Blank
| Other_character
;
fragment Special : Comma_
| Colon_
| Scol_
| Br_C_
| Br_O_
;
fragment Operator_only : Plus_
| Minus_
| Percent_sign_
| VBar_
| Amp_
| Eq_
| Not_
| More_
| Less_
;
fragment Other_character : ~["'\n\r*/] ;
fragment Not_ : Backslash_
| Other_negator
;
fragment Other_negator : Caret_
| Logical_Not_
| Slash_
;
// Single characters
fragment Stop_ : '.' ;
fragment Comma_ : ',' ;
fragment Colon_ : ':' ;
fragment Scol_ : ';' ;
fragment Eq_ : '=' ;
fragment Plus_ : '+' ;
fragment Minus_ : '-' ;
fragment Caret_ : '^' ;
fragment Logical_Not_ : '¬' ;
fragment Underscore_ : '_' ;
fragment Exclamation_mark_ : '!' ;
fragment Question_mark_ : '?' ;
fragment Br_O_ : '(' ;
fragment Br_C_ : ')' ;
fragment Space_ : ' ' ;
fragment Form_Feed_ : '\f' ;
fragment HTab_ : '\t' ;
fragment VTab_ : '\u000b' ;
fragment Caret_Return_ : '\r' ;
fragment New_Line_ : '\n' ;
fragment Quote_ : '"' ;
fragment Apostrophe_ : '\'' ;
fragment Slash_ : '/' ;
fragment Backslash_ : '\\' ;
fragment Asterisk_ : '*' ;
fragment More_ : '>' ;
fragment Less_ : '<' ;
fragment Percent_sign_ : '%' ;
fragment VBar_ : '|' ;
fragment Amp_ : '&' ;
fragment Hash_ : '#' ;
fragment At_ : '@' ;
fragment Dollar_ : '$' ;
// Letters
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');
// Unsupported characters
UNSUPPORTED_CHARACTER : . ;
|
lexer grammar RexxLexer;
// Main rules
// %INCLUDE statement
STMT_INCLUDE : Include_Statement ;
// Skippable stuff
LINE_COMMENT : Line_Comment_
-> channel(HIDDEN);
BLOCK_COMMENT : Block_Comment_
-> channel(HIDDEN);
WHISPACES : Whitespaces_ -> channel(HIDDEN);
CONTINUATION : Continue_ -> channel(HIDDEN);
// Keywords
KWD_ADDRESS : A D D R E S S ;
KWD_ARG : A R G ;
KWD_BY : B Y ;
KWD_CALL : C A L L ;
KWD_DIGITS : D I G I T S ;
KWD_DO : D O ;
KWD_DROP : D R O P ;
KWD_ELSE : E L S E ;
KWD_END : E N D ;
KWD_ENGINEERING : E N G I N E E R I N G ;
KWD_ERROR : E R R O R ;
KWD_EXIT : E X I T ;
KWD_EXPOSE : E X P O S E ;
KWD_EXTERNAL : E X T E R N A L ;
KWD_FAILURE : F A I L U R E ;
KWD_FOR : F O R ;
KWD_FOREVER : F O R E V E R ;
KWD_FORM : F O R M ;
KWD_FUZZ : F U Z Z ;
KWD_HALT : H A L T ;
KWD_IF : I F ;
KWD_INTERPRET : I N T E R P R E T ;
KWD_ITERATE : I T E R A T E ;
KWD_LEAVE : L E A V E ;
KWD_NAME : N A M E ;
KWD_NOP : N O P ;
KWD_NOVALUE : N O V A L U E ;
KWD_NUMERIC : N U M E R I C ;
KWD_OFF : O F F ;
KWD_ON : O N ;
KWD_OPTIONS : O P T I O N S ;
KWD_OTHERWISE : O T H E R W I S E ;
KWD_PARSE : P A R S E ;
KWD_PROCEDURE : P R O C E D U R E ;
KWD_PULL : P U L L ;
KWD_PUSH : P U S H ;
KWD_QUEUE : Q U E U E ;
KWD_RETURN : R E T U R N ;
KWD_SAY : S A Y ;
KWD_SCIENTIFIC : S C I E N T I F I C ;
KWD_SELECT : S E L E C T ;
KWD_SIGNAL : S I G N A L ;
KWD_SOURCE : S O U R C E ;
KWD_SYNTAX : S Y N T A X ;
KWD_THEN : T H E N ;
KWD_TO : T O ;
KWD_TRACE : T R A C E ;
KWD_UNTIL : U N T I L ;
KWD_UPPER : U P P E R ;
KWD_VALUE : V A L U E ;
KWD_VAR : V A R ;
KWD_VERSION : V E R S I O N ;
KWD_WHEN : W H E N ;
KWD_WHILE : W H I L E ;
KWD_WITH : W I T H ;
// Brackets
BR_O : Br_O_ ;
BR_C : Br_C_ ;
// Special variables: RC, RESULT, SIGL
SPECIAL_VAR : R C
| R E S U L T
| S I G L
;
// Label, const, var, number
NUMBER : Number_ ;
CONST_SYMBOL : Const_symbol_ ;
VAR_SYMBOL : Var_Symbol_ ;
// String and concatenation
STRING : String_
// Additionally, need to consume X or B at the end not followed by
// _!?A-Za-z.#@$0-9
{int currPos = this.getCharIndex();
int textLen = super.getInputStream().size();
if (textLen > currPos) {
if (textLen == currPos + 1) {
if (super.getInputStream()
.getText(
new Interval(currPos, currPos))
.matches("[XxBb]"))
super.getInputStream().consume();
} else {
if (super.getInputStream().getText(
new Interval(currPos, currPos + 1))
.matches("[XxBb][^_!?A-Za-z.#@$0-9]"))
super.getInputStream().consume();
}
}}
;
// In concatenation don't need the blanks - will be precoeesed by WHITESPACES
CONCAT : VBar_ VBar_ ;
// Operations
// Assignment (also comparison and template operator)
EQ : Eq_ ;
// Math: +, -, *, /, //, %, **
// Note: '+' and '-' are also used in prefix expressions and templates
PLUS : Plus_ ;
MINUS : Minus_ ;
MUL : Asterisk_ ;
DIV : Slash_ ;
QUOTINENT : Percent_sign_ ;
REMAINDER : Slash_ Slash_ ;
POW : Asterisk_ Asterisk_ ;
// Logical: NOT, OR, AND, XOR
// Note: '\\' also used for prefix expressions
NOT : Not_ ;
OR : VBar_ ;
XOR : Amp_ Amp_ ;
AND : Amp_ ;
// Comparison
// Strict comparison: ==, \==, >>, <<, >>=, <<=, \>>, \<<
CMPS_Eq : Eq_ Eq_ ;
CMPS_Neq : Not_ Eq_ Eq_ ;
CMPS_M : More_ More_ ;
CMPS_L : Less_ Less_ ;
CMPS_MEq : More_ More_ Eq_ ;
CMPS_LEq : Less_ Less_ Eq_ ;
CMPS_NM : Not_ More_ More_ ;
CMPS_NL : Not_ Less_ Less_ ;
// Non-strict: =, \=, <>, ><, >, <, >=, <=, \>, \<
// Note: '=' is taken from Assignment (EQ)
CMP_NEq : Not_ Eq_ ;
CMP_LM : Less_ More_ ;
CMP_ML : More_ Less_ ;
CMP_M : More_ ;
CMP_L : Less_ ;
CMP_MEq : More_ Eq_ ;
CMP_LEq : Less_ Eq_ ;
CMP_NM : Not_ More_ ;
CMP_NL : Not_ Less_ ;
// Additional elements
// .
STOP : Stop_ ;
// ,
COMMA : Comma_ ;
// :
COLON : Colon_ ;
// End of line
EOL : Eol_ ;
// Semicolumn
SEMICOL : Scol_ ;
// --------------------------------------------------------
// Fragments
// Comments
// Include statement - need to account for this
fragment Include_Statement : Comment_S Bo?
Percent_sign_ I N C L U D E
Bo Var_Symbol_+ Bo?
Comment_E
;
// Line comment - no EOL allowed inside.
fragment Line_Comment_ : Comment_S
Line_Commentpart*?
Asterisk_*?
( Comment_E | EOF )
;
fragment Line_Commentpart : Line_Comment_
| Slash_ Line_Comment_
| Slash_ ~[*\n\r]+?
| Asterisk_ ~[/\n\r]+?
| ~[/*\n\r]+
;
fragment Block_Comment_ : Comment_S
Block_Commentpart*?
Asterisk_*?
( Comment_E | EOF )
;
fragment Block_Commentpart : Block_Comment_
| Slash_ Block_Comment_
| Slash_ ~[*]+?
| Asterisk_ ~[/]+?
| ~[/*]+
;
fragment Comment_E : Asterisk_ Slash_ ;
fragment Comment_S : Slash_ Asterisk_ ;
// Whitespaces
fragment Whitespaces_ : Blank+ ;
// Continuation - full comments, but no EOL between
fragment Continue_ : Comma_
( Block_Comment_ | Line_Comment_ | Blank )*?
Eol_;
fragment Eol_ : New_Line_ Caret_Return_
| Caret_Return_ New_Line_
| New_Line_
| Caret_Return_
;
// Whitespaces
fragment Bo : Blank+ ;
fragment Blank : Space_
| Other_blank_character
;
fragment Other_blank_character : Form_Feed_
| HTab_
| VTab_
;
// Label, const, var, number
// Label, var
fragment Var_Symbol_ : General_letter Var_symbol_char*;
fragment Var_symbol_char : General_letter
| Digit_
| Stop_
;
fragment General_letter : Underscore_
| Exclamation_mark_
| Question_mark_
| A
| B
| C
| D
| E
| F
| G
| H
| I
| J
| K
| L
| M
| N
| O
| P
| Q
| R
| S
| T
| U
| V
| W
| X
| Y
| Z
| Extra_letter
;
fragment Extra_letter : Hash_
| At_
| Dollar_
;
// Const
fragment Const_symbol_ : ( Digit_ | Stop_ ) Var_symbol_char* ;
fragment Digit_ : [0-9] ;
// Number
fragment Number_ : Plain_number Exponent_? ;
fragment Plain_number : Digit_+ Stop_? Digit_*
| Stop_ Digit_+
;
fragment Exponent_ : E ( Plus_ | Minus_ )? Digit_+ ;
// String and concatenation
fragment String_ : Quoted_string ;
fragment Quoted_string : Quotation_mark_string
| Apostrophe_string
;
fragment Quotation_mark_string : Quote_ (String_char | Embedded_quotation_mark | Apostrophe_)* Quote_ ;
fragment Embedded_quotation_mark: Quote_ Quote_ ;
fragment Apostrophe_string : Apostrophe_ (String_char | Embedded_apostrophe | Quote_)* Apostrophe_ ;
fragment Embedded_apostrophe : Apostrophe_ Apostrophe_ ;
fragment String_char : String_or_comment_char | Asterisk_ | Slash_ ;
fragment String_or_comment_char : Digit_
| Stop_
| Special
| Operator_only
| General_letter
| Blank
| Other_character
;
fragment Special : Comma_
| Colon_
| Scol_
| Br_C_
| Br_O_
;
fragment Operator_only : Plus_
| Minus_
| Percent_sign_
| VBar_
| Amp_
| Eq_
| Not_
| More_
| Less_
;
fragment Other_character : ~["'\n\r*/] ;
fragment Not_ : Backslash_
| Other_negator
;
fragment Other_negator : Caret_
| Logical_Not_
| Slash_
;
// Single characters
fragment Stop_ : '.' ;
fragment Comma_ : ',' ;
fragment Colon_ : ':' ;
fragment Scol_ : ';' ;
fragment Eq_ : '=' ;
fragment Plus_ : '+' ;
fragment Minus_ : '-' ;
fragment Caret_ : '^' ;
fragment Logical_Not_ : '¬' ;
fragment Underscore_ : '_' ;
fragment Exclamation_mark_ : '!' ;
fragment Question_mark_ : '?' ;
fragment Br_O_ : '(' ;
fragment Br_C_ : ')' ;
fragment Space_ : ' ' ;
fragment Form_Feed_ : '\f' ;
fragment HTab_ : '\t' ;
fragment VTab_ : '\u000b' ;
fragment Caret_Return_ : '\r' ;
fragment New_Line_ : '\n' ;
fragment Quote_ : '"' ;
fragment Apostrophe_ : '\'' ;
fragment Slash_ : '/' ;
fragment Backslash_ : '\\' ;
fragment Asterisk_ : '*' ;
fragment More_ : '>' ;
fragment Less_ : '<' ;
fragment Percent_sign_ : '%' ;
fragment VBar_ : '|' ;
fragment Amp_ : '&' ;
fragment Hash_ : '#' ;
fragment At_ : '@' ;
fragment Dollar_ : '$' ;
// Letters
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');
// Unsupported characters
UNSUPPORTED_CHARACTER : . ;
|
Support constant symbol starting with period
|
Support constant symbol starting with period
|
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
|
0c6c88c1eab251a0d529b152d8a931a95b0baaa5
|
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_ (indexNotExistClause_ indexName)? ON tableName
;
alterTable
: alterTableNameWithAsterisk (alterTableActions | renameColumnSpecification | renameConstraint) | alterTableNameExists renameTableSpecification_
;
alterIndex
: alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace
;
dropTable
: DROP TABLE (IF EXISTS)? tableNames
;
dropIndex
: DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)*
;
truncateTable
: TRUNCATE TABLE? ONLY? tableNameParts
;
createTableSpecification_
: ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)?
;
tableNotExistClause_
: (IF NOT EXISTS)?
;
createDefinitionClause_
: LP_ (createDefinition (COMMA_ createDefinition)*)? RP_
;
createDefinition
: columnDefinition | tableConstraint | LIKE tableName likeOption*
;
columnDefinition
: columnName dataType collateClause? columnConstraint*
;
columnConstraint
: constraintClause? columnConstraintOption constraintOptionalParam
;
constraintClause
: CONSTRAINT ignoredIdentifier_
;
columnConstraintOption
: NOT? NULL
| checkOption
| DEFAULT defaultExpr
| GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)?
| UNIQUE indexParameters
| primaryKey indexParameters
| REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)*
;
checkOption
: CHECK expr (NO INHERIT)?
;
defaultExpr
: CURRENT_TIMESTAMP | expr
;
sequenceOptions
: sequenceOption+
;
sequenceOption
: START WITH? NUMBER_
| INCREMENT BY? NUMBER_
| MAXVALUE NUMBER_
| NO MAXVALUE
| MINVALUE NUMBER_
| NO MINVALUE
| CYCLE
| NO CYCLE
| CACHE NUMBER_
| OWNED BY
;
indexParameters
: (USING INDEX TABLESPACE ignoredIdentifier_)?
| INCLUDE columnNames
| WITH
;
action
: NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT)
;
constraintOptionalParam
: (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))?
;
likeOption
: (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL)
;
tableConstraint
: constraintClause? tableConstraintOption constraintOptionalParam
;
tableConstraintOption
: checkOption
| UNIQUE columnNames indexParameters
| primaryKey columnNames indexParameters
| EXCLUDE (USING ignoredIdentifier_)?
| FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)*
;
inheritClause_
: (INHERITS tableNames)?
;
createIndexSpecification_
: UNIQUE? INDEX CONCURRENTLY?
;
indexNotExistClause_
: (IF NOT EXISTS)?
;
alterIndexName
: ALTER INDEX (IF EXISTS)? indexName
;
renameIndexSpecification
: RENAME TO indexName
;
alterIndexDependsOnExtension
: ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_
;
alterIndexSetTableSpace
: ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)?
;
tableNameParts
: tableNamePart (COMMA_ tableNamePart)*
;
tableNamePart
: tableName ASTERISK_?
;
alterTableNameWithAsterisk
: ALTER TABLE (IF EXISTS)? ONLY? tableName ASTERISK_?
;
alterTableActions
: alterTableAction (COMMA_ alterTableAction)*
;
alterTableAction
: addColumnSpecification
| dropColumnSpecification
| modifyColumnSpecification
| addConstraintSpecification
| ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam
| VALIDATE CONSTRAINT ignoredIdentifier_
| DROP CONSTRAINT (IF EXISTS)? ignoredIdentifier_ (RESTRICT | CASCADE)?
| (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)?
| ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_
| (DISABLE | ENABLE) RULE ignoredIdentifier_
| ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_
| (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY
| CLUSTER ON indexName
| SET WITHOUT CLUSTER
| SET (WITH | WITHOUT) OIDS
| SET TABLESPACE ignoredIdentifier_
| SET (LOGGED | UNLOGGED)
| SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_
| RESET LP_ storageParameter (COMMA_ storageParameter)* RP_
| INHERIT tableName
| NO INHERIT tableName
| OF dataTypeName_
| NOT OF
| OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER)
| REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING)
;
tableConstraintUsingIndex
: (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam
;
addColumnSpecification
: ADD COLUMN? (IF NOT EXISTS)? columnDefinition
;
dropColumnSpecification
: DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)?
;
modifyColumnSpecification
: alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)?
| alterColumn SET DEFAULT expr
| alterColumn DROP DEFAULT
| alterColumn (SET | DROP) NOT NULL
| alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)?
| alterColumn alterColumnSetOption alterColumnSetOption*
| alterColumn DROP IDENTITY (IF EXISTS)?
| alterColumn SET STATISTICS NUMBER_
| alterColumn SET LP_ attributeOptions RP_
| alterColumn RESET LP_ attributeOptions RP_
| alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN)
;
alterColumn
: ALTER COLUMN? columnName
;
alterColumnSetOption
: SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)?
;
attributeOptions
: attributeOption (COMMA_ attributeOption)*
;
attributeOption
: IDENTIFIER_ EQ_ simpleExpr
;
addConstraintSpecification
: ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex)
;
renameColumnSpecification
: RENAME COLUMN? columnName TO columnName
;
renameConstraint
: RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_
;
storageParameterWithValue
: storageParameter EQ_ simpleExpr
;
storageParameter
: IDENTIFIER_
;
alterTableNameExists
: ALTER TABLE (IF EXISTS)? tableName
;
renameTableSpecification_
: RENAME TO newTableName
;
newTableName
: IDENTIFIER_
;
usingIndexType
: USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN)
;
excludeElement
: (columnName | expr) ignoredIdentifier_? (ASC | DESC)? (NULLS (FIRST | LAST))?
;
|
/*
* 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))?
;
|
add concurrentlyClause_
|
add concurrentlyClause_
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
|
8ad34bfed8d75f90cc07f7e74b7c51196de8710a
|
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 (tableIndexClause_ | bitmapJoinIndexClause_)
;
alterTable
: ALTER TABLE tableName alterClause_
;
// TODO hongjun throw exeption when alter index on oracle
alterIndex
: ALTER INDEX indexName (RENAME TO indexName)?
;
dropTable
: DROP TABLE tableName
;
dropIndex
: DROP INDEX indexName
;
truncateTable
: TRUNCATE TABLE tableName
;
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? (VISIBLE | INVISIBLE)? (DEFAULT (ON NULL)? expr | identityClause)? (ENCRYPT encryptionSpecification_)? (inlineConstraint+ | inlineRefConstraint)?
;
identityClause
: GENERATED (ALWAYS | BY DEFAULT (ON NULL)?) AS IDENTITY LP_? (identityOptions+)? RP_?
;
identityOptions
: START WITH (NUMBER_ | LIMIT VALUE)
| INCREMENT BY NUMBER_
| MAXVALUE NUMBER_
| NOMAXVALUE
| MINVALUE NUMBER_
| NOMINVALUE
| CYCLE
| NOCYCLE
| CACHE NUMBER_
| NOCACHE
| ORDER
| NOORDER
;
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)?
;
tableAlias
: tableName alias? (COMMA_ tableName alias?)*
;
alterClause_
: (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
;
|
/*
* 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? (VISIBLE | INVISIBLE)? (DEFAULT (ON NULL)? expr | identityClause)? (ENCRYPT encryptionSpecification_)? (inlineConstraint+ | inlineRefConstraint)?
;
identityClause
: GENERATED (ALWAYS | BY DEFAULT (ON NULL)?) AS IDENTITY LP_? (identityOptions+)? RP_?
;
identityOptions
: START WITH (NUMBER_ | LIMIT VALUE)
| INCREMENT BY NUMBER_
| MAXVALUE NUMBER_
| NOMAXVALUE
| MINVALUE NUMBER_
| NOMINVALUE
| CYCLE
| NOCYCLE
| CACHE NUMBER_
| NOCACHE
| ORDER
| NOORDER
;
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)?
;
|
add createIndexDefinitionClause_
|
add createIndexDefinitionClause_
|
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
|
b3db9eff07236d15e4409e74932d6b725b95677e
|
Compiler/src/grammar/Receipt.g4
|
Compiler/src/grammar/Receipt.g4
|
/**
* @author ariehfabbro, lucasdavid
*/
grammar Receipt;
@header {
import infrastructure.json.*;
}
receipt
returns [JsonStructure e]
@init { $e = new JsonStructure("receipt"); }
:
( basic { $e.add($basic.e); } )+
;
basic
returns [JsonElement e]
: id { $e = $id.e; }
| seller { $e = $seller.e; }
| buyer { $e = $buyer.e; }
| date { $e = $date.e; }
| products { $e = $products.e; }
| tax { $e = $tax.e; }
| total { $e = $total.e; }
;
id
returns [JsonElement e]
: INT { $e = new JsonElement("id", $INT.getText()); }
;
seller
returns [JsonStructure e]
@init { $e = new JsonStructure("company"); }
: entitySeller { $e.add($entitySeller.e); }
( address { $e.add($address.e); } )?
;
buyer
returns [JsonStructure e]
@init { $e = new JsonStructure("buyer"); }
: entityBuyer { $e.add($entityBuyer.e); }
( address { $e.add($address.e); } )?
;
date
returns [JsonElement e]
@init { String t; }
: (KEYWORD_DATE COLON?)?
INT { t = $INT.getText(); }
( SLASH { t += '/'; } | HIFEN { t += '-'; } )?
INT { t += $INT.getText(); }
( SLASH { t += '/'; } | HIFEN { t += '-'; } )?
INT
{
t += $INT.getText();
$e = new JsonElement("date", t);
}
;
products
returns [JsonStructure e]
@init { $e = new JsonStructure("products"); }
: KEYWORD_PRODUCTS COLON?
( NAME INT? DECIMAL
{
JsonStructure current = new JsonStructure($NAME.getText());
if ($INT != null && $INT.getText() != null && !$INT.getText().isEmpty()) {
current.add(new JsonElement("quantity", $INT.getText()));
}
current.add(new JsonElement("cost", $DECIMAL.getText()));
$e.add(current);
} )+
;
tax
returns [JsonElement e]
: KEYWORD_TAX COLON? DECIMAL { $e = new JsonElement("tax", $DECIMAL.getText()); }
;
total
returns [JsonElement e]
: KEYWORD_TOTAL COLON? DECIMAL { $e = new JsonElement("total", $DECIMAL.getText()); }
;
entityBuyer
returns [JsonStructure e]
@init { $e = new JsonStructure("entity"); }
: KEYWORD_BUYER (NAME IDNUMBER | IDNUMBER NAME)
{
$e
.add(new JsonElement("id", $IDNUMBER.getText()))
.add(new JsonElement("name", $NAME.getText()));
}
;
entitySeller
returns [JsonStructure e]
@init { $e = new JsonStructure("entity"); }
: KEYWORD_SELLER (NAME IDNUMBER? | IDNUMBER? NAME)
{
$e
.add(new JsonElement("id", $IDNUMBER.getText()))
.add(new JsonElement("name", $NAME.getText()));
}
;
address
returns [JsonStructure e]
@init { $e = new JsonStructure("address"); }
: KEYWORD_ADDRESS COLON?
NAME { $e.add(new JsonElement("main", $NAME.getText())); }
(zipcode { $e.add($zipcode.e); } )?
(city { $e.add($city.e); } )?
(state { $e.add($state.e); } )?
;
zipcode
returns [JsonElement e]
@init { String t = ""; }
:(DIGIT { t += $DIGIT.getText(); } )+
HIFEN?
(DIGIT { t += $DIGIT.getText(); } )+
{ $e = new JsonElement("zipcode", t); }
;
city
returns [JsonElement e]
: NAME { $e = new JsonElement("city", $NAME.getText()); }
;
state
returns [JsonElement e]
@init { String t; }
: CAPITAL_LETTER { t = $CAPITAL_LETTER.getText(); }
CAPITAL_LETTER {
t += $CAPITAL_LETTER.getText();
$e = new JsonElement("state", t);
}
;
IDNUMBER
: SSN | CPF | CNPJ
;
SSN
: DIGIT+ HIFEN DIGIT+ HIFEN DIGIT+
;
CPF
: DIGIT+ DOT DIGIT+ DOT DIGIT+ HIFEN DIGIT+
;
CNPJ
: DIGIT+ DOT DIGIT+ DOT DIGIT+ SLASH DIGIT+ HIFEN DIGIT+
;
DECIMAL
: CAPITAL_LETTER? DOLLAR DIGIT+ DOT DIGIT DIGIT
;
DOLLAR
: '$'
;
INT
: DIGIT+
;
HIFEN
: '-'
;
DOT
: '.'
;
SLASH
: '/'
;
KEYWORD_BUYER
: 'buyer' | 'comprador'
;
KEYWORD_SELLER
: 'seller' | 'vendedor'
;
KEYWORD_ADDRESS
: 'address' | 'endereco'
;
KEYWORD_TAX
: 'tax' | 'juros'
;
KEYWORD_TOTAL
: 'total'
;
KEYWORD_DATE
: 'date' | 'data'
;
KEYWORD_PRODUCTS
: 'products' | 'produtos'
;
COLON
: ':'
;
NAME
: (LETTER | CAPITAL_LETTER)+
;
LETTER
: 'a'..'z'
;
CAPITAL_LETTER
: 'A'..'Z'
;
DIGIT
: '0'..'9'
;
WHITESPACE
: (' ' | '\t' | '\r' | '\n') {skip();}
;
OTHERWISE
: .
;
|
/**
* @author ariehfabbro, lucasdavid
*/
grammar Receipt;
@header {
import infrastructure.json.*;
}
receipt
returns [JsonStructure e]
@init { $e = new JsonStructure("receipt"); }
:
( basic { $e.add($basic.e); } )+
;
basic
returns [JsonElement e]
: id { $e = $id.e; }
| seller { $e = $seller.e; }
| buyer { $e = $buyer.e; }
| date { $e = $date.e; }
| products { $e = $products.e; }
| tax { $e = $tax.e; }
| total { $e = $total.e; }
;
id
returns [JsonElement e]
: INT { $e = new JsonElement("id", $INT.getText()); }
;
seller
returns [JsonStructure e]
@init { $e = new JsonStructure("seller"); }
: entitySeller { $e.add($entitySeller.e); }
( address { $e.add($address.e); } )?
;
buyer
returns [JsonStructure e]
@init { $e = new JsonStructure("buyer"); }
: entityBuyer { $e.add($entityBuyer.e); }
( address { $e.add($address.e); } )?
;
date
returns [JsonElement e]
@init { String t; }
: (KEYWORD_DATE COLON?)?
INT { t = $INT.getText(); }
( SLASH { t += '/'; } | HIFEN { t += '-'; } )?
INT { t += $INT.getText(); }
( SLASH { t += '/'; } | HIFEN { t += '-'; } )?
INT
{
t += $INT.getText();
$e = new JsonElement("date", t);
}
;
products
returns [JsonStructure e]
@init { $e = new JsonStructure("products"); }
: KEYWORD_PRODUCTS COLON?
( NAME INT? DECIMAL
{
JsonStructure current = new JsonStructure($NAME.getText());
if ($INT != null && $INT.getText() != null && !$INT.getText().isEmpty()) {
current.add(new JsonElement("quantity", $INT.getText()));
}
current.add(new JsonElement("cost", $DECIMAL.getText()));
$e.add(current);
} )+
;
tax
returns [JsonElement e]
: KEYWORD_TAX COLON? DECIMAL { $e = new JsonElement("tax", $DECIMAL.getText()); }
;
total
returns [JsonElement e]
: KEYWORD_TOTAL COLON? DECIMAL { $e = new JsonElement("total", $DECIMAL.getText()); }
;
entityBuyer
returns [JsonStructure e]
@init { $e = new JsonStructure("entity"); }
: KEYWORD_BUYER (NAME IDNUMBER | IDNUMBER NAME)
{
$e
.add(new JsonElement("id", $IDNUMBER.getText()))
.add(new JsonElement("name", $NAME.getText()));
}
;
entitySeller
returns [JsonStructure e]
@init { $e = new JsonStructure("entity"); }
: KEYWORD_SELLER (NAME IDNUMBER? | IDNUMBER? NAME)
{
$e
.add(new JsonElement("id", $IDNUMBER.getText()))
.add(new JsonElement("name", $NAME.getText()));
}
;
address
returns [JsonStructure e]
@init { $e = new JsonStructure("address"); }
: KEYWORD_ADDRESS COLON?
NAME { $e.add(new JsonElement("main", $NAME.getText())); }
(zipcode { $e.add($zipcode.e); } )?
(
city { $e.add($city.e); }
( state { $e.add($state.e); } )?
)?
;
zipcode
returns [JsonElement e]
@init { String t = ""; }
: INT { t += $INT.getText(); }
HIFEN?
INT { t += $INT.getText(); }
{ $e = new JsonElement("zipcode", t); }
;
city
returns [JsonElement e]
: NAME { $e = new JsonElement("city", $NAME.getText()); }
;
state
returns [JsonElement e]
: NAME { $e = new JsonElement("state", $NAME.getText()); }
;
IDNUMBER
: SSN | CPF | CNPJ
;
SSN
: DIGIT+ HIFEN DIGIT+ HIFEN DIGIT+
;
CPF
: DIGIT+ DOT DIGIT+ DOT DIGIT+ HIFEN DIGIT+
;
CNPJ
: DIGIT+ DOT DIGIT+ DOT DIGIT+ SLASH DIGIT+ HIFEN DIGIT+
;
DECIMAL
: CAPITAL_LETTER? DOLLAR DIGIT+ DOT DIGIT DIGIT
;
DOLLAR
: '$'
;
INT
: DIGIT+
;
HIFEN
: '-'
;
DOT
: '.'
;
SLASH
: '/'
;
KEYWORD_BUYER
: 'buyer' | 'comprador'
;
KEYWORD_SELLER
: 'seller' | 'vendedor'
;
KEYWORD_ADDRESS
: 'address' | 'endereco'
;
KEYWORD_TAX
: 'tax' | 'juros'
;
KEYWORD_TOTAL
: 'total'
;
KEYWORD_DATE
: 'date' | 'data'
;
KEYWORD_PRODUCTS
: 'products' | 'produtos'
;
COLON
: ':'
;
NAME
: (LETTER | CAPITAL_LETTER)+
;
LETTER
: 'a'..'z'
;
CAPITAL_LETTER
: 'A'..'Z'
;
DIGIT
: '0'..'9'
;
WHITESPACE
: (' ' | '\t' | '\r' | '\n') {skip();}
;
OTHERWISE
: .
;
|
Update Receipt.g4: fix address parse
|
Update Receipt.g4: fix address parse
|
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
|
c7f66cf9f80ecf50fda3bfb706fb0fc599d4cb48
|
sharding-jdbc-ddl-parser/src/main/antlr4/io/shardingsphere/parser/antlr/oracle/OracleAlterTable.g4
|
sharding-jdbc-ddl-parser/src/main/antlr4/io/shardingsphere/parser/antlr/oracle/OracleAlterTable.g4
|
grammar OracleAlterTable;
import OracleKeyword, DataType, Keyword,OracleIndexBase, OracleTableBase,OracleBase,BaseRule,Symbol;
alterTable:
ALTER TABLE tableName
( alterTableProperties
| columnClauses
| constraintClauses
| alterTablePartitioning
| alterExternalTable
| moveTableClause
)?
( enableDisableClause
|((ENABLE | DISABLE) ( (TABLE LOCK) | (ALL TRIGGERS)))
)*
;
alterTableProperties:
alterIotOrXml
| shrinkClause
| (READ (ONLY|WRITE))
| (REKEY encryptionSpec )
;
alterIotOrXml:
(
alterIotOrXmlRepeatHeader+
|renameTable
)*
alterIotClauses? alterXmlschemaClause?
;
renameTable:
RENAME TO tableName
;
alterIotOrXmlRepeatHeader:
physicalAttributesClause
| loggingClause
| tableCompression
| supplementalTableLogging
| allocateExtentClause
| deallocateUnusedClause
| ( CACHE | NOCACHE )
| (RESULT_CACHE LEFT_PAREN MODE (DEFAULT | FORCE) RIGHT_PAREN )
| upgradeTableClause
| recordsPerBlockClause
| parallelClause
| rowMovementClause
| flashbackArchiveClause
;
supplementalTableLogging:
addSupplementalLogClause
| dropSupplementalLogClause
;
addSupplementalLogClause:
ADD addSupplementalLogItem (COMMA addSupplementalLogItem)*
;
addSupplementalLogItem:
SUPPLEMENTAL LOG
(supplementalLogGrpClause | supplementalIdKeyClause)
;
dropSupplementalLogClause:
DROP addSupplementalLogItem (COMMA addSupplementalLogItem)*
;
dropSupplementalLogItem:
SUPPLEMENTAL LOG
(supplementalIdKeyClause | (GROUP groupName))
;
allocateExtentClause:
ALLOCATE EXTENT
( LEFT_PAREN ( SIZE sizeClause
| DATAFILE 'filename'
| INSTANCE NUMBER
) *
RIGHT_PAREN
)?
;
deallocateUnusedClause:
DEALLOCATE UNUSED ( KEEP sizeClause )?
;
upgradeTableClause:
UPGRADE ( NOT? INCLUDING DATA )?
columnProperties?
;
recordsPerBlockClause:
MINIMIZE
| NOMINIMIZE
;
alterIotClauses:
indexOrgTableClause
| alterOverflowClause
| alterMappingTableClauses
| COALESCE
;
alterOverflowClause:
addOverflowClause
| overflowClause
;
addOverflowClause:
ADD OVERFLOW segmentAttributesClause?
partitionSegmentAttributesWithParen?
;
partitionSegmentAttributesWithParen:
LEFT_PAREN
partitionSegmentAttributes (COMMA partitionSegmentAttributes)*
RIGHT_PAREN
;
partitionSegmentAttributes:
PARTITION segmentAttributesClause?
;
overflowClause:
OVERFLOW
(
segmentAttributesClause
| allocateExtentClause
| shrinkClause
| deallocateUnusedClause
)+
;
shrinkClause:
SHRINK SPACE COMPACT? CASCADE?
;
alterMappingTableClauses:
MAPPING TABLE
( allocateExtentClause
| deallocateUnusedClause
)
;
alterXmlschemaClause:
(ALLOW ANYSCHEMA)
| (ALLOW NONSCHEMA)
| (DISALLOW NONSCHEMA)
;
columnClauses:
opColumnClause+
| renameColumnClause
| modifyCollectionRetrieval+
| modifyLobStorageClause+
| alterVarrayColProperties+
;
opColumnClause:
addColumnClause
| modifyColumnClauses
| dropColumnClause
;
addColumnClause:
ADD
columnOrVirtualDefinitions
columnProperties?
outOfLinePartStorages?
;
columnOrVirtualDefinitions:
columnOrVirtualDefinition
(COMMA columnOrVirtualDefinition)*
;
columnOrVirtualDefinition:
columnDefinition
| virtualColumnDefinition
;
outOfLinePartStorages:
outOfLinePartStorage ( COMMA outOfLinePartStorage)*
;
outOfLinePartStorage:
PARTITION partitionName
outOfLinePartBody+
(LEFT_PAREN
SUBPARTITION partitionName outOfLinePartBody+
RIGHT_PAREN
)?
;
outOfLinePartBody:
nestedTableColProperties
| lobStorageClause
| varrayColProperties
;
modifyColumnClauses:
MODIFY
(
LEFT_PAREN modifyColProperties (COMMA modifyColProperties)* RIGHT_PAREN
| modifyColSubstitutable
)
;
modifyColProperties:
columnName
( dataType )?
( DEFAULT expr )?
( ( ENCRYPT encryptionSpec ) | DECRYPT )?
inlineConstraint *
( lobStorageClause )?
( alterXmlschemaClause )?
;
modifyColSubstitutable:
COLUMN columnName
( NOT )? SUBSTITUTABLE AT ALL LEVELS
( FORCE )?
;
dropColumnClause:
( SET UNUSED columnOrColumnList cascadeOrInvalidate*)
| dropColumn
| (DROP ( (UNUSED COLUMNS)| (COLUMNS CONTINUE) )checkpointNumber?)
;
dropColumn:
DROP columnOrColumnList cascadeOrInvalidate* checkpointNumber?
;
columnOrColumnList:
(COLUMN columnName)
| (LEFT_PAREN columnName ( COMMA columnName )* RIGHT_PAREN)
;
cascadeOrInvalidate:
(CASCADE CONSTRAINTS )
| INVALIDATE
;
checkpointNumber:
CHECKPOINT NUMBER
;
renameColumnClause:
RENAME COLUMN columnName TO
;
modifyCollectionRetrieval:
MODIFY NESTED TABLE varrayItemName
RETURN AS ( LOCATOR | VALUE )
;
modifyLobStorageClause:
MODIFY LOB LEFT_PAREN lobItems RIGHT_PAREN
LEFT_PAREN modifyLobParameters RIGHT_PAREN
;
modifyLobParameters:
( storageClause
|lobCommonParameter
)+
;
alterVarrayColProperties:
MODIFY VARRAY varrayItemName
LEFT_PAREN modifyLobParameters RIGHT_PAREN
;
constraintClauses:
addConstraintClause
| modifyConstraintClause
| renameConstraintClause
| dropConstraintClause+
;
addConstraintClause:
ADD
( outOfLineConstraint+
|outOfLineRefConstraint
)
;
modifyConstraintClause:
MODIFY constraintOption constraintState CASCADE?
;
constraintWithName:
CONSTRAINT constraintName
;
constraintOption:
constraintWithName
| constraintPrimaryOrUnique
;
constraintPrimaryOrUnique:
(PRIMARY KEY)
| (UNIQUE columnList)
;
renameConstraintClause:
RENAME constraintWithName TO constraintName
;
dropConstraintClause:
DROP
(
(constraintPrimaryOrUnique CASCADE? (( KEEP | DROP) INDEX)?)
| (CONSTRAINT constraintName ( CASCADE )?)
)
;
alterTablePartitioning:
modifyTableDefaultAttrs
| alterIntervalPartitioning
| setSubpartitionTemplate
| modifyTablePartition
| modifyTableSubpartition
| moveTablePartition
| moveTableSubpartition
| addTablePartition
| coalesceTablePartition
| coalesceTableSubpartition
| dropTablePartition
| dropTableSubpartition
| renamePartitionSubpart
| truncatePartitionSubpart
| splitTablePartition
| splitTableSubpartition
| mergeTablePartitions
| mergeTableSubpartitions
| exchangePartitionSubpart
;
modifyTableDefaultAttrs:
MODIFY DEFAULT ATTRIBUTES
(FOR partitionExtendedName)?
deferredSegmentCreation?
segmentAttributesClause?
tableCompression?
( PCTTHRESHOLD NUMBER )?
( keyCompression )?
( alterOverflowClause )?
modifyTableLobOrArray*
;
modifyTableLobOrArray:
((LOB lobItemList )| (VARRAY varrayItemName)) LEFT_PAREN lobParameters RIGHT_PAREN
;
partitionExtendedName:
PARTITION
(
partitionName
|(FOR LEFT_PAREN partitionKeyValue ( COMMA partitionKeyValue)* RIGHT_PAREN)
)
;
alterIntervalPartitioning:
SET
(
INTERVAL LEFT_PAREN (expr)? RIGHT_PAREN
|(STORE IN LEFT_PAREN tablespaceName (COMMA tablespaceName)* RIGHT_PAREN )
)
;
setSubpartitionTemplate:
SET SUBPARTITION TEMPLATE
(LEFT_PAREN subpartitionDescs? RIGHT_PAREN )
| hashSubpartitionQuantity
;
subpartitionDescs:
rangeSubpartitionDescs
|listSubpartitionDescs
|individualHashSubpartses
;
rangeSubpartitionDescs:
rangeSubpartitionDesc ( COMMA rangeSubpartitionDesc)*
;
listSubpartitionDescs:
listSubpartitionDesc ( COMMA listSubpartitionDesc)*
;
individualHashSubpartses:
individualHashSubparts ( COMMA individualHashSubparts)*
;
hashSubpartitionQuantity:
matchNone
;
modifyTablePartition:
modifyRangePartition
| modifyHashPartition
| modifyListPartition
;
modifyRangePartition:
MODIFY partitionExtendedName
(modifyPartitionCommonOp
| alterMappingTableClause
)
;
modifyPartitionCommonOp:
partitionAttributes
| addRangeSubpartition
| addHashSubpartition
| addListSubpartition
| (COALESCE SUBPARTITION updateIndexClauses? parallelClause?)
| (REBUILD? UNUSABLE LOCAL INDEXES)
;
alterMappingTableClause:
matchNone
;
partitionAttributes:
(commonPartitionAttributes| shrinkClause)*
( OVERFLOW commonPartitionAttributes*)?
tableCompression?
modifyTableLobOrArray*
;
addRangeSubpartition:
ADD rangeSubpartitionDesc dependentTablesClause? ( updateIndexClauses )?
;
commonPartitionAttributes:
physicalAttributesClause
| loggingClause
| allocateExtentClause
| deallocateUnusedClause
;
dependentTablesClause:
DEPENDENT TABLES
LEFT_PAREN
tableNameAndPartitionSpecs (COMMA tableNameAndPartitionSpecs)*
RIGHT_PAREN
;
tableNameAndPartitionSpecs:
tableName LEFT_PAREN partitionSpecs RIGHT_PAREN
;
partitionSpecs:
partitionSpec (COMMA partitionSpec)*
;
partitionSpec:
PARTITION partitionName? tablePartitionDescription
;
tablePartitionDescription:
deferredSegmentCreation?
segmentAttributesClause?
(tableCompression | keyCompression)?
( OVERFLOW segmentAttributesClause? )?
( lobStorageClause
| varrayColProperties
| nestedTableColProperties
)*
;
updateIndexClauses:
updateGlobalIndexClause
| updateAllIndexesClause
;
updateGlobalIndexClause:
( UPDATE | INVALIDATE ) GLOBAL
;
updateAllIndexesClause:
UPDATE INDEXES
( LEFT_PAREN
indexNameWithUpdateIndexPartition ( COMMA indexNameWithUpdateIndexPartition)*
RIGHT_PAREN
)?
;
indexNameWithUpdateIndexPartition:
indexName
LEFT_PAREN
(
updateIndexPartition
| updateIndexSubpartition
)
RIGHT_PAREN
;
updateIndexPartition:
indexOrSubpartition(COMMA indexOrSubpartition)*
;
indexOrSubpartition:
indexPartitionDescription indexSubpartitionClause?
;
indexPartitionDescription:
PARTITION
( partitionName
(segmentAttributesClause| keyCompression)+
(PARAMETERS LEFT_PAREN STRING RIGHT_PAREN)
?
UNUSABLE?
)?
;
updateIndexSubpartition:
subpartionWithTablespace (COMMA subpartionWithTablespace)*
;
subpartionWithTablespace:
SUBPARTITION partitionName? (TABLESPACE tablespaceName )?
;
addHashSubpartition:
ADD
individualHashSubparts
dependentTablesClause?
( updateIndexClauses )?
( parallelClause )?
;
addListSubpartition:
ADD listSubpartitionDesc dependentTablesClause? ( updateIndexClauses )?
;
modifyHashPartition:
MODIFY partitionExtendedName
( partitionAttributes
| alterMappingTableClause
| (( REBUILD )? UNUSABLE LOCAL INDEXES)
)
;
modifyListPartition:
MODIFY partitionExtendedName
( modifyPartitionCommonOp
| addOrDropPartition
)
;
addOrDropPartition:
( ADD | DROP ) VALUES LEFT_PAREN simpleExpr( COMMA simpleExpr)* RIGHT_PAREN
;
modifyTableSubpartition:
MODIFY subpartitionExtendedName
( allocateExtentClause
| deallocateUnusedCluse
| shrinkClause
| ( ( LOB lobItems | VARRAY varrayItemName ) LEFT_PAREN modifyLobParameters RIGHT_PAREN )*
| (( REBUILD )? UNUSABLE LOCAL INDEXES)
| addOrDropPartition
)
;
subpartitionExtendedName:
(SUBPARTITION partitionName )
| (SUBPARTITION FOR LEFT_PAREN partitionKeyValue ( COMMA partitionKeyValue)* RIGHT_PAREN )
;
deallocateUnusedCluse:
matchNone;
moveTablePartition:
MOVE partitionExtendedName
( MAPPING TABLE )?
tablePartitionDescription
( updateIndexClauses )?
( parallelClause )?
;
moveTableSubpartition:
MOVE subpartitionExtendedName ( partitioningStorageClause )?
( updateIndexClauses )? ( parallelClause )?
;
addTablePartition:
ADD PARTITION partitionName?
( addRangePartitionClause
| addHashPartitionClause
| addListPartitionClause
)
dependentTablesClause?
;
addRangePartitionClause:
rangeValuesClause
tablePartitionDescription
subpartsDescsOrByQuantity?
( updateIndexClauses )?
;
subpartsDescsOrByQuantity:
(LEFT_PAREN subpartitionDescs RIGHT_PAREN)
| hashSubpartsByQuantity
;
hashSubpartsByQuantity:
SUBPARTITIONS NUMBER (STORE IN LEFT_PAREN tablespaceName ( COMMA tablespaceName)* RIGHT_PAREN )?
;
addHashPartitionClause:
partitioningStorageClause
( updateIndexClauses )?
( parallelClause )?
;
addListPartitionClause:
listValuesClause
tablePartitionDescription
subpartsDescsOrByQuantity?
( updateIndexClauses )?
;
coalesceTablePartition:
COALESCE PARTITION ( updateIndexClauses )? ( parallelClause )?
;
coalesceTableSubpartition:
COALESCE SUBPARTITION partitionName (updateIndexClauses)? (parallelClause)?
;
dropTablePartition:
DROP partitionExtendedName
( updateIndexClauses ( parallelClause )? )?
;
dropTableSubpartition:
DROP subpartitionExtendedName
( updateIndexClauses ( parallelClause )? )?
;
renamePartitionSubpart:
RENAME ( partitionExtendedName| subpartitionExtendedName) TO
;
truncatePartitionSubpart:
TRUNCATE
( partitionExtendedName
| subpartitionExtendedName
)
(((DROP ( ALL )?) | REUSE ) STORAGE )?
(updateIndexClauses ( parallelClause )?)?
;
splitTablePartition:
SPLIT partitionExtendedName
(
( AT simpleExprsWithParen ( INTO LEFT_PAREN rangePartitionDescs RIGHT_PAREN )?)
|
(VALUES simpleExprsWithParen ( INTO LEFT_PAREN listPartitionDescs RIGHT_PAREN )?)
)
( splitNestedTablePart )?
dependentTablesClause?
( updateIndexClauses )?
( parallelClause )?
;
partitionWithNames:
partitionWithName (COMMA partitionWithName)*
;
partitionWithName:
PARTITION partitionName
;
rangePartitionDescs:
rangePartitionDesc COMMA rangePartitionDesc
;
listPartitionDescs:
listPartitionDesc COMMA listPartitionDesc
;
rangePartitionDesc:
PARTITION partitionName?
rangeValuesClause?
tablePartitionDescription
subpartsDescsOrByQuantity?
;
listPartitionDesc:
PARTITION partitionName?
listValuesClause?
tablePartitionDescription
subpartsDescsOrByQuantity?
;
splitNestedTablePart:
NESTED TABLE columnName INTO
LEFT_PAREN partitionSegmentAttribute COMMA
partitionSegmentAttribute (splitNestedTablePart)?
RIGHT_PAREN
( splitNestedTablePart )?
;
partitionSegmentAttribute:
PARTITION partitionName (segmentAttributesClause)?
;
splitTableSubpartition:
SPLIT subpartitionExtendedName
(
(AT simpleExprsWithParen ( INTO LEFT_PAREN (rangeSubpartitionDescs) RIGHT_PAREN )?)
|(VALUES simpleExprsWithParen ( INTO LEFT_PAREN listSubpartitionDescs RIGHT_PAREN )?)
)
dependentTablesClause?
( updateIndexClauses )?
( parallelClause )?
;
mergeTablePartitions:
MERGE PARTITIONS
partitionNameOrForKeyValue
COMMA
partitionNameOrForKeyValue
( INTO partitionSpec )?
dependentTablesClause?
( updateIndexClauses )?
( parallelClause )?
;
partitionNameOrForKeyValue:
partitionName
| ( FOR LEFT_PAREN partitionKeyValue ( COMMA partitionKeyValue )* RIGHT_PAREN )
;
partitionKeyValue:
simpleExpr
;
mergeTableSubpartitions:
MERGE SUBPARTITIONS
partitionNameOrForKeyValue
COMMA
partitionNameOrForKeyValue
( INTO
(rangeSubpartitionDesc
| listSubpartitionDesc
)
)?
dependentTablesClause?
( updateIndexClauses )?
( parallelClause )?
;
exchangePartitionSubpart:
EXCHANGE
(
partitionExtendedName
| subpartitionExtendedName
)
WITH TABLE tableName
( ( INCLUDING | EXCLUDING ) INDEXES )?
( ( WITH | WITHOUT ) VALIDATION )?
( exceptionsClause )?
( updateIndexClauses ( parallelClause )? )?
;
alterExternalTable:
( addColumnClause
| modifyColumnClauses
| dropColumnClause
| parallelClause
| externalDataProperties
| (REJECT LIMIT ( NUMBER | UNLIMITED ))
| (PROJECT COLUMN ( ALL | REFERENCED ))
)+
;
externalDataProperties:
matchNone
;
moveTableClause:
MOVE ( ONLINE )?
segmentAttributesClause?
tableCompression?
( indexOrgTableClause )?
( lobStorageClause | varrayColProperties )*
( parallelClause )?
;
|
grammar OracleAlterTable;
import OracleKeyword, DataType, Keyword,OracleIndexBase, OracleTableBase,OracleBase,BaseRule,Symbol;
alterTable:
ALTER TABLE tableName
( alterTableProperties
| columnClauses
| constraintClauses
| alterTablePartitioning
| alterExternalTable
| moveTableClause
)?
( enableDisableClause
|((ENABLE | DISABLE) ( (TABLE LOCK) | (ALL TRIGGERS)))
)*
;
alterTableProperties:
alterIotOrXml
| shrinkClause
| (READ (ONLY|WRITE))
| (REKEY encryptionSpec )
;
alterIotOrXml:
(
alterIotOrXmlRepeatHeader+
|renameTable
)*
alterIotClauses? alterXmlschemaClause?
;
renameTable:
RENAME TO tableName
;
alterIotOrXmlRepeatHeader:
physicalAttributesClause
| loggingClause
| tableCompression
| supplementalTableLogging
| allocateExtentClause
| deallocateUnusedClause
| ( CACHE | NOCACHE )
| (RESULT_CACHE LEFT_PAREN MODE (DEFAULT | FORCE) RIGHT_PAREN )
| upgradeTableClause
| recordsPerBlockClause
| parallelClause
| rowMovementClause
| flashbackArchiveClause
;
supplementalTableLogging:
addSupplementalLogClause
| dropSupplementalLogClause
;
addSupplementalLogClause:
ADD addSupplementalLogItem (COMMA addSupplementalLogItem)*
;
addSupplementalLogItem:
SUPPLEMENTAL LOG
(supplementalLogGrpClause | supplementalIdKeyClause)
;
dropSupplementalLogClause:
DROP addSupplementalLogItem (COMMA addSupplementalLogItem)*
;
dropSupplementalLogItem:
SUPPLEMENTAL LOG
(supplementalIdKeyClause | (GROUP groupName))
;
allocateExtentClause:
ALLOCATE EXTENT
( LEFT_PAREN ( SIZE sizeClause
| DATAFILE 'filename'
| INSTANCE NUMBER
) *
RIGHT_PAREN
)?
;
deallocateUnusedClause:
DEALLOCATE UNUSED ( KEEP sizeClause )?
;
upgradeTableClause:
UPGRADE ( NOT? INCLUDING DATA )?
columnProperties?
;
recordsPerBlockClause:
MINIMIZE
| NOMINIMIZE
;
alterIotClauses:
indexOrgTableClause
| alterOverflowClause
| alterMappingTableClauses
| COALESCE
;
alterOverflowClause:
addOverflowClause
| overflowClause
;
addOverflowClause:
ADD OVERFLOW segmentAttributesClause?
partitionSegmentAttributesWithParen?
;
partitionSegmentAttributesWithParen:
LEFT_PAREN
partitionSegmentAttributes (COMMA partitionSegmentAttributes)*
RIGHT_PAREN
;
partitionSegmentAttributes:
PARTITION segmentAttributesClause?
;
overflowClause:
OVERFLOW
(
segmentAttributesClause
| allocateExtentClause
| shrinkClause
| deallocateUnusedClause
)+
;
shrinkClause:
SHRINK SPACE COMPACT? CASCADE?
;
alterMappingTableClauses:
MAPPING TABLE
( allocateExtentClause
| deallocateUnusedClause
)
;
alterXmlschemaClause:
(ALLOW ANYSCHEMA)
| (ALLOW NONSCHEMA)
| (DISALLOW NONSCHEMA)
;
columnClauses:
opColumnClause+
| renameColumn
| modifyCollectionRetrieval+
| modifyLobStorageClause+
| alterVarrayColProperties+
;
opColumnClause:
addColumn
| modifyColumn
| dropColumnClause
;
addColumn:
ADD
columnOrVirtualDefinitions
columnProperties?
outOfLinePartStorages?
;
columnOrVirtualDefinitions:
LEFT_PAREN
columnOrVirtualDefinition
(COMMA columnOrVirtualDefinition)*
RIGHT_PAREN
|columnOrVirtualDefinition
;
columnOrVirtualDefinition:
columnDefinition
| virtualColumnDefinition
;
outOfLinePartStorages:
outOfLinePartStorage ( COMMA outOfLinePartStorage)*
;
outOfLinePartStorage:
PARTITION partitionName
outOfLinePartBody+
(LEFT_PAREN
SUBPARTITION partitionName outOfLinePartBody+
RIGHT_PAREN
)?
;
outOfLinePartBody:
nestedTableColProperties
| lobStorageClause
| varrayColProperties
;
modifyColumn:
MODIFY
(
LEFT_PAREN modifyColProperties (COMMA modifyColProperties)* RIGHT_PAREN
| modifyColSubstitutable
)
;
modifyColProperties:
columnName
( dataType )?
( DEFAULT expr )?
( ( ENCRYPT encryptionSpec ) | DECRYPT )?
inlineConstraint *
( lobStorageClause )?
( alterXmlschemaClause )?
;
modifyColSubstitutable:
COLUMN columnName
( NOT )? SUBSTITUTABLE AT ALL LEVELS
( FORCE )?
;
dropColumnClause:
( SET UNUSED columnOrColumnList cascadeOrInvalidate*)
| dropColumn
| (DROP ( (UNUSED COLUMNS)| (COLUMNS CONTINUE) )checkpointNumber?)
;
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
;
modifyCollectionRetrieval:
MODIFY NESTED TABLE varrayItemName
RETURN AS ( LOCATOR | VALUE )
;
modifyLobStorageClause:
MODIFY LOB LEFT_PAREN lobItems RIGHT_PAREN
LEFT_PAREN modifyLobParameters RIGHT_PAREN
;
modifyLobParameters:
( storageClause
|lobCommonParameter
)+
;
alterVarrayColProperties:
MODIFY VARRAY varrayItemName
LEFT_PAREN modifyLobParameters RIGHT_PAREN
;
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 )?)
)
;
alterTablePartitioning:
modifyTableDefaultAttrs
| alterIntervalPartitioning
| setSubpartitionTemplate
| modifyTablePartition
| modifyTableSubpartition
| moveTablePartition
| moveTableSubpartition
| addTablePartition
| coalesceTablePartition
| coalesceTableSubpartition
| dropTablePartition
| dropTableSubpartition
| renamePartitionSubpart
| truncatePartitionSubpart
| splitTablePartition
| splitTableSubpartition
| mergeTablePartitions
| mergeTableSubpartitions
| exchangePartitionSubpart
;
modifyTableDefaultAttrs:
MODIFY DEFAULT ATTRIBUTES
(FOR partitionExtendedName)?
deferredSegmentCreation?
segmentAttributesClause?
tableCompression?
( PCTTHRESHOLD NUMBER )?
( keyCompression )?
( alterOverflowClause )?
modifyTableLobOrArray*
;
modifyTableLobOrArray:
((LOB lobItemList )| (VARRAY varrayItemName)) LEFT_PAREN lobParameters RIGHT_PAREN
;
partitionExtendedName:
PARTITION
(
partitionName
|(FOR LEFT_PAREN partitionKeyValue ( COMMA partitionKeyValue)* RIGHT_PAREN)
)
;
alterIntervalPartitioning:
SET
(
INTERVAL LEFT_PAREN (expr)? RIGHT_PAREN
|(STORE IN LEFT_PAREN tablespaceName (COMMA tablespaceName)* RIGHT_PAREN )
)
;
setSubpartitionTemplate:
SET SUBPARTITION TEMPLATE
(LEFT_PAREN subpartitionDescs? RIGHT_PAREN )
| hashSubpartitionQuantity
;
subpartitionDescs:
rangeSubpartitionDescs
|listSubpartitionDescs
|individualHashSubpartses
;
rangeSubpartitionDescs:
rangeSubpartitionDesc ( COMMA rangeSubpartitionDesc)*
;
listSubpartitionDescs:
listSubpartitionDesc ( COMMA listSubpartitionDesc)*
;
individualHashSubpartses:
individualHashSubparts ( COMMA individualHashSubparts)*
;
hashSubpartitionQuantity:
matchNone
;
modifyTablePartition:
modifyRangePartition
| modifyHashPartition
| modifyListPartition
;
modifyRangePartition:
MODIFY partitionExtendedName
(modifyPartitionCommonOp
| alterMappingTableClause
)
;
modifyPartitionCommonOp:
partitionAttributes
| addRangeSubpartition
| addHashSubpartition
| addListSubpartition
| (COALESCE SUBPARTITION updateIndexClauses? parallelClause?)
| (REBUILD? UNUSABLE LOCAL INDEXES)
;
alterMappingTableClause:
matchNone
;
partitionAttributes:
(commonPartitionAttributes| shrinkClause)*
( OVERFLOW commonPartitionAttributes*)?
tableCompression?
modifyTableLobOrArray*
;
addRangeSubpartition:
ADD rangeSubpartitionDesc dependentTablesClause? ( updateIndexClauses )?
;
commonPartitionAttributes:
physicalAttributesClause
| loggingClause
| allocateExtentClause
| deallocateUnusedClause
;
dependentTablesClause:
DEPENDENT TABLES
LEFT_PAREN
tableNameAndPartitionSpecs (COMMA tableNameAndPartitionSpecs)*
RIGHT_PAREN
;
tableNameAndPartitionSpecs:
tableName LEFT_PAREN partitionSpecs RIGHT_PAREN
;
partitionSpecs:
partitionSpec (COMMA partitionSpec)*
;
partitionSpec:
PARTITION partitionName? tablePartitionDescription
;
tablePartitionDescription:
deferredSegmentCreation?
segmentAttributesClause?
(tableCompression | keyCompression)?
( OVERFLOW segmentAttributesClause? )?
( lobStorageClause
| varrayColProperties
| nestedTableColProperties
)*
;
updateIndexClauses:
updateGlobalIndexClause
| updateAllIndexesClause
;
updateGlobalIndexClause:
( UPDATE | INVALIDATE ) GLOBAL
;
updateAllIndexesClause:
UPDATE INDEXES
( LEFT_PAREN
indexNameWithUpdateIndexPartition ( COMMA indexNameWithUpdateIndexPartition)*
RIGHT_PAREN
)?
;
indexNameWithUpdateIndexPartition:
indexName
LEFT_PAREN
(
updateIndexPartition
| updateIndexSubpartition
)
RIGHT_PAREN
;
updateIndexPartition:
indexOrSubpartition(COMMA indexOrSubpartition)*
;
indexOrSubpartition:
indexPartitionDescription indexSubpartitionClause?
;
indexPartitionDescription:
PARTITION
( partitionName
(segmentAttributesClause| keyCompression)+
(PARAMETERS LEFT_PAREN STRING RIGHT_PAREN)
?
UNUSABLE?
)?
;
updateIndexSubpartition:
subpartionWithTablespace (COMMA subpartionWithTablespace)*
;
subpartionWithTablespace:
SUBPARTITION partitionName? (TABLESPACE tablespaceName )?
;
addHashSubpartition:
ADD
individualHashSubparts
dependentTablesClause?
( updateIndexClauses )?
( parallelClause )?
;
addListSubpartition:
ADD listSubpartitionDesc dependentTablesClause? ( updateIndexClauses )?
;
modifyHashPartition:
MODIFY partitionExtendedName
( partitionAttributes
| alterMappingTableClause
| (( REBUILD )? UNUSABLE LOCAL INDEXES)
)
;
modifyListPartition:
MODIFY partitionExtendedName
( modifyPartitionCommonOp
| addOrDropPartition
)
;
addOrDropPartition:
( ADD | DROP ) VALUES LEFT_PAREN simpleExpr( COMMA simpleExpr)* RIGHT_PAREN
;
modifyTableSubpartition:
MODIFY subpartitionExtendedName
( allocateExtentClause
| deallocateUnusedCluse
| shrinkClause
| ( ( LOB lobItems | VARRAY varrayItemName ) LEFT_PAREN modifyLobParameters RIGHT_PAREN )*
| (( REBUILD )? UNUSABLE LOCAL INDEXES)
| addOrDropPartition
)
;
subpartitionExtendedName:
(SUBPARTITION partitionName )
| (SUBPARTITION FOR LEFT_PAREN partitionKeyValue ( COMMA partitionKeyValue)* RIGHT_PAREN )
;
deallocateUnusedCluse:
matchNone;
moveTablePartition:
MOVE partitionExtendedName
( MAPPING TABLE )?
tablePartitionDescription
( updateIndexClauses )?
( parallelClause )?
;
moveTableSubpartition:
MOVE subpartitionExtendedName ( partitioningStorageClause )?
( updateIndexClauses )? ( parallelClause )?
;
addTablePartition:
ADD PARTITION partitionName?
( addRangePartitionClause
| addHashPartitionClause
| addListPartitionClause
)
dependentTablesClause?
;
addRangePartitionClause:
rangeValuesClause
tablePartitionDescription
subpartsDescsOrByQuantity?
( updateIndexClauses )?
;
subpartsDescsOrByQuantity:
(LEFT_PAREN subpartitionDescs RIGHT_PAREN)
| hashSubpartsByQuantity
;
hashSubpartsByQuantity:
SUBPARTITIONS NUMBER (STORE IN LEFT_PAREN tablespaceName ( COMMA tablespaceName)* RIGHT_PAREN )?
;
addHashPartitionClause:
partitioningStorageClause
( updateIndexClauses )?
( parallelClause )?
;
addListPartitionClause:
listValuesClause
tablePartitionDescription
subpartsDescsOrByQuantity?
( updateIndexClauses )?
;
coalesceTablePartition:
COALESCE PARTITION ( updateIndexClauses )? ( parallelClause )?
;
coalesceTableSubpartition:
COALESCE SUBPARTITION partitionName (updateIndexClauses)? (parallelClause)?
;
dropTablePartition:
DROP partitionExtendedName
( updateIndexClauses ( parallelClause )? )?
;
dropTableSubpartition:
DROP subpartitionExtendedName
( updateIndexClauses ( parallelClause )? )?
;
renamePartitionSubpart:
RENAME ( partitionExtendedName| subpartitionExtendedName) TO
;
truncatePartitionSubpart:
TRUNCATE
( partitionExtendedName
| subpartitionExtendedName
)
(((DROP ( ALL )?) | REUSE ) STORAGE )?
(updateIndexClauses ( parallelClause )?)?
;
splitTablePartition:
SPLIT partitionExtendedName
(
( AT simpleExprsWithParen ( INTO LEFT_PAREN rangePartitionDescs RIGHT_PAREN )?)
|
(VALUES simpleExprsWithParen ( INTO LEFT_PAREN listPartitionDescs RIGHT_PAREN )?)
)
( splitNestedTablePart )?
dependentTablesClause?
( updateIndexClauses )?
( parallelClause )?
;
partitionWithNames:
partitionWithName (COMMA partitionWithName)*
;
partitionWithName:
PARTITION partitionName
;
rangePartitionDescs:
rangePartitionDesc COMMA rangePartitionDesc
;
listPartitionDescs:
listPartitionDesc COMMA listPartitionDesc
;
rangePartitionDesc:
PARTITION partitionName?
rangeValuesClause?
tablePartitionDescription
subpartsDescsOrByQuantity?
;
listPartitionDesc:
PARTITION partitionName?
listValuesClause?
tablePartitionDescription
subpartsDescsOrByQuantity?
;
splitNestedTablePart:
NESTED TABLE columnName INTO
LEFT_PAREN partitionSegmentAttribute COMMA
partitionSegmentAttribute (splitNestedTablePart)?
RIGHT_PAREN
( splitNestedTablePart )?
;
partitionSegmentAttribute:
PARTITION partitionName (segmentAttributesClause)?
;
splitTableSubpartition:
SPLIT subpartitionExtendedName
(
(AT simpleExprsWithParen ( INTO LEFT_PAREN (rangeSubpartitionDescs) RIGHT_PAREN )?)
|(VALUES simpleExprsWithParen ( INTO LEFT_PAREN listSubpartitionDescs RIGHT_PAREN )?)
)
dependentTablesClause?
( updateIndexClauses )?
( parallelClause )?
;
mergeTablePartitions:
MERGE PARTITIONS
partitionNameOrForKeyValue
COMMA
partitionNameOrForKeyValue
( INTO partitionSpec )?
dependentTablesClause?
( updateIndexClauses )?
( parallelClause )?
;
partitionNameOrForKeyValue:
partitionName
| ( FOR LEFT_PAREN partitionKeyValue ( COMMA partitionKeyValue )* RIGHT_PAREN )
;
partitionKeyValue:
simpleExpr
;
mergeTableSubpartitions:
MERGE SUBPARTITIONS
partitionNameOrForKeyValue
COMMA
partitionNameOrForKeyValue
( INTO
(rangeSubpartitionDesc
| listSubpartitionDesc
)
)?
dependentTablesClause?
( updateIndexClauses )?
( parallelClause )?
;
exchangePartitionSubpart:
EXCHANGE
(
partitionExtendedName
| subpartitionExtendedName
)
WITH TABLE tableName
( ( INCLUDING | EXCLUDING ) INDEXES )?
( ( WITH | WITHOUT ) VALIDATION )?
( exceptionsClause )?
( updateIndexClauses ( parallelClause )? )?
;
alterExternalTable:
( addColumn
| modifyColumn
| dropColumn
| parallelClause
| externalDataProperties
| (REJECT LIMIT ( NUMBER | UNLIMITED ))
| (PROJECT COLUMN ( ALL | REFERENCED ))
)+
;
externalDataProperties:
matchNone
;
moveTableClause:
MOVE ( ONLINE )?
segmentAttributesClause?
tableCompression?
( indexOrgTableClause )?
( lobStorageClause | varrayColProperties )*
( parallelClause )?
;
|
Update addColumn to support add one column Update addColumn to add multi column
|
Update addColumn to support add one column
Update addColumn to add multi column
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
|
a25e94e790e547a4c01f916bb139ab0bb94e5a23
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, MySQLKeyword, Literals, BaseRule;
createTable
: CREATE createTableSpecification_? TABLE tableNotExistClause_ tableName (createDefinitionClause_ | createLikeClause_)
;
createIndex
: CREATE createIndexSpecification_ INDEX indexName indexType_? ON tableName
;
alterTable
: ALTER TABLE tableName alterDefinitionClause_?
;
dropTable
: DROP dropTableSpecification_ TABLE tableExistClause_ tableNames
;
dropIndex
: DROP INDEX dropIndexSpecification_? indexName (ON tableName)?
;
truncateTable
: TRUNCATE TABLE? tableName
;
createDatabase
: CREATE (DATABASE | SCHEMA) (IF NOT EXISTS)? schemaName createDatabaseSpecificationClause_
;
alterDatabase
: ALTER (DATABASE | SCHEMA) schemaName createDatabaseSpecificationClause_
;
dropDatabse
: DROP (DATABASE | SCHEMA) (IF EXISTS)? schemaName
;
createTableSpecification_
: TEMPORARY
;
tableNotExistClause_
: (IF NOT EXISTS)?
;
createDefinitionClause_
: LP_ createDefinitions_ RP_
;
createDatabaseSpecificationClause_
: createDatabaseSpecification_*
;
createDatabaseSpecification_
: DEFAULT? (CHARACTER SET | CHARSET) EQ_? characterSetName_
| DEFAULT? COLLATE EQ_? collationName_
| DEFAULT ENCRYPTION EQ_ ('Y' | 'N')
;
createDefinitions_
: createDefinition_ (COMMA_ createDefinition_)*
;
createDefinition_
: columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_
;
columnDefinition
: columnName dataType (inlineDataType_* | generatedDataType_*)
;
inlineDataType_
: commonDataTypeOption_
| AUTO_INCREMENT
| DEFAULT (literals | expr)
| COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT)
| STORAGE (DISK | MEMORY | DEFAULT)
;
commonDataTypeOption_
: primaryKey | UNIQUE KEY? | NOT? NULL | collateClause_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_
;
checkConstraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)?
;
referenceDefinition_
: REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)*
;
referenceOption_
: RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT
;
generatedDataType_
: commonDataTypeOption_
| (GENERATED ALWAYS)? AS expr
| (VIRTUAL | STORED)
;
indexDefinition_
: (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
indexType_
: USING (BTREE | HASH)
;
keyParts_
: LP_ keyPart_ (COMMA_ keyPart_)* RP_
;
keyPart_
: (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)?
;
indexOption_
: KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE
;
constraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_)
;
primaryKeyOption_
: primaryKey indexType_? columnNames indexOption_*
;
primaryKey
: PRIMARY? KEY
;
uniqueOption_
: UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
foreignKeyOption_
: FOREIGN KEY indexName? columnNames referenceDefinition_
;
createLikeClause_
: LP_? LIKE tableName RP_?
;
createIndexSpecification_
: (UNIQUE | FULLTEXT | SPATIAL)?
;
alterDefinitionClause_
: alterSpecification_ (COMMA_ alterSpecification_)*
;
alterSpecification_
: tableOptions_
| addColumnSpecification
| addIndexSpecification
| addConstraintSpecification
| ADD checkConstraintDefinition_
| DROP CHECK ignoredIdentifier_
| ALTER CHECK ignoredIdentifier_ NOT? ENFORCED
| ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY)
| ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT)
| ALTER INDEX indexName (VISIBLE | INVISIBLE)
| changeColumnSpecification
| DEFAULT? characterSet_ collateClause_?
| CONVERT TO characterSet_ collateClause_?
| (DISABLE | ENABLE) KEYS
| (DISCARD | IMPORT_) TABLESPACE
| dropColumnSpecification
| dropIndexSpecification
| dropPrimaryKeySpecification
| DROP FOREIGN KEY ignoredIdentifier_
| FORCE
| LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE)
| modifyColumnSpecification
// TODO hongjun investigate ORDER BY col_name [, col_name] ...
| ORDER BY columnNames
| renameColumnSpecification
| renameIndexSpecification
| renameTableSpecification_
| (WITHOUT | WITH) VALIDATION
| ADD PARTITION LP_ partitionDefinition_ RP_
| DROP PARTITION ignoredIdentifiers_
| DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| TRUNCATE PARTITION (ignoredIdentifiers_ | ALL)
| COALESCE PARTITION NUMBER_
| REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_
| EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)?
| ANALYZE PARTITION (ignoredIdentifiers_ | ALL)
| CHECK PARTITION (ignoredIdentifiers_ | ALL)
| OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL)
| REBUILD PARTITION (ignoredIdentifiers_ | ALL)
| REPAIR PARTITION (ignoredIdentifiers_ | ALL)
| REMOVE PARTITIONING
| UPGRADE PARTITIONING
;
tableOptions_
: tableOption_ (COMMA_? tableOption_)*
;
tableOption_
: AUTO_INCREMENT EQ_? NUMBER_
| AVG_ROW_LENGTH EQ_? NUMBER_
| DEFAULT? (characterSet_ | collateClause_)
| CHECKSUM EQ_? NUMBER_
| COMMENT EQ_? STRING_
| COMPRESSION EQ_? STRING_
| CONNECTION EQ_? STRING_
| (DATA | INDEX) DIRECTORY EQ_? STRING_
| DELAY_KEY_WRITE EQ_? NUMBER_
| ENCRYPTION EQ_? STRING_
| ENGINE EQ_? ignoredIdentifier_
| INSERT_METHOD EQ_? (NO | FIRST | LAST)
| KEY_BLOCK_SIZE EQ_? NUMBER_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| PACK_KEYS EQ_? (NUMBER_ | DEFAULT)
| PASSWORD EQ_? STRING_
| ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT)
| STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_)
| STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_)
| STATS_SAMPLE_PAGES EQ_? NUMBER_
| TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))?
| UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_
;
addColumnSpecification
: ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_)
;
firstOrAfterColumn
: FIRST | AFTER columnName
;
addIndexSpecification
: ADD indexDefinition_
;
addConstraintSpecification
: ADD constraintDefinition_
;
changeColumnSpecification
: CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn?
;
dropColumnSpecification
: DROP COLUMN? columnName
;
dropIndexSpecification
: DROP (INDEX | KEY) indexName
;
dropPrimaryKeySpecification
: DROP primaryKey
;
modifyColumnSpecification
: MODIFY COLUMN? columnDefinition firstOrAfterColumn?
;
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
// TODO hongjun: should support renameIndexSpecification on mysql
renameIndexSpecification
: RENAME (INDEX | KEY) indexName TO indexName
;
renameTableSpecification_
: RENAME (TO | AS)? identifier_
;
partitionDefinitions_
: LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_
;
partitionDefinition_
: PARTITION identifier_
(VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))?
partitionDefinitionOption_*
(LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)?
;
partitionLessThanValue_
: LP_ (expr | partitionValueList_) RP_ | MAXVALUE
;
partitionValueList_
: literals (COMMA_ literals)*
;
partitionDefinitionOption_
: STORAGE? ENGINE EQ_? identifier_
| COMMENT EQ_? STRING_
| DATA DIRECTORY EQ_? STRING_
| INDEX DIRECTORY EQ_? STRING_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| TABLESPACE EQ_? identifier_
;
subpartitionDefinition_
: SUBPARTITION identifier_ partitionDefinitionOption_*
;
dropTableSpecification_
: TEMPORARY?
;
tableExistClause_
: (IF EXISTS)?
;
dropIndexSpecification_
: ONLINE | OFFLINE
;
|
/*
* 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, MySQLKeyword, Literals, BaseRule;
createTable
: CREATE createTableSpecification_? TABLE tableNotExistClause_ tableName (createDefinitionClause_ | createLikeClause_)
;
createIndex
: CREATE createIndexSpecification_ INDEX indexName indexType_? ON tableName
;
alterTable
: ALTER TABLE tableName alterDefinitionClause_?
;
dropTable
: DROP dropTableSpecification_ TABLE tableExistClause_ tableNames
;
dropIndex
: DROP INDEX dropIndexSpecification_? indexName (ON tableName)?
;
truncateTable
: TRUNCATE TABLE? tableName
;
createDatabase
: CREATE (DATABASE | SCHEMA) (IF NOT EXISTS)? schemaName createDatabaseSpecification_*
;
alterDatabase
: ALTER (DATABASE | SCHEMA) schemaName createDatabaseSpecification_*
;
dropDatabse
: DROP (DATABASE | SCHEMA) (IF EXISTS)? schemaName
;
createTableSpecification_
: TEMPORARY
;
tableNotExistClause_
: (IF NOT EXISTS)?
;
createDefinitionClause_
: LP_ createDefinitions_ RP_
;
createDatabaseSpecification_
: DEFAULT? (CHARACTER SET | CHARSET) EQ_? characterSetName_
| DEFAULT? COLLATE EQ_? collationName_
| DEFAULT ENCRYPTION EQ_ ('Y' | 'N')
;
createDefinitions_
: createDefinition_ (COMMA_ createDefinition_)*
;
createDefinition_
: columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_
;
columnDefinition
: columnName dataType (inlineDataType_* | generatedDataType_*)
;
inlineDataType_
: commonDataTypeOption_
| AUTO_INCREMENT
| DEFAULT (literals | expr)
| COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT)
| STORAGE (DISK | MEMORY | DEFAULT)
;
commonDataTypeOption_
: primaryKey | UNIQUE KEY? | NOT? NULL | collateClause_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_
;
checkConstraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)?
;
referenceDefinition_
: REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)*
;
referenceOption_
: RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT
;
generatedDataType_
: commonDataTypeOption_
| (GENERATED ALWAYS)? AS expr
| (VIRTUAL | STORED)
;
indexDefinition_
: (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
indexType_
: USING (BTREE | HASH)
;
keyParts_
: LP_ keyPart_ (COMMA_ keyPart_)* RP_
;
keyPart_
: (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)?
;
indexOption_
: KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE
;
constraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_)
;
primaryKeyOption_
: primaryKey indexType_? columnNames indexOption_*
;
primaryKey
: PRIMARY? KEY
;
uniqueOption_
: UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
foreignKeyOption_
: FOREIGN KEY indexName? columnNames referenceDefinition_
;
createLikeClause_
: LP_? LIKE tableName RP_?
;
createIndexSpecification_
: (UNIQUE | FULLTEXT | SPATIAL)?
;
alterDefinitionClause_
: alterSpecification_ (COMMA_ alterSpecification_)*
;
alterSpecification_
: tableOptions_
| addColumnSpecification
| addIndexSpecification
| addConstraintSpecification
| ADD checkConstraintDefinition_
| DROP CHECK ignoredIdentifier_
| ALTER CHECK ignoredIdentifier_ NOT? ENFORCED
| ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY)
| ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT)
| ALTER INDEX indexName (VISIBLE | INVISIBLE)
| changeColumnSpecification
| DEFAULT? characterSet_ collateClause_?
| CONVERT TO characterSet_ collateClause_?
| (DISABLE | ENABLE) KEYS
| (DISCARD | IMPORT_) TABLESPACE
| dropColumnSpecification
| dropIndexSpecification
| dropPrimaryKeySpecification
| DROP FOREIGN KEY ignoredIdentifier_
| FORCE
| LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE)
| modifyColumnSpecification
// TODO hongjun investigate ORDER BY col_name [, col_name] ...
| ORDER BY columnNames
| renameColumnSpecification
| renameIndexSpecification
| renameTableSpecification_
| (WITHOUT | WITH) VALIDATION
| ADD PARTITION LP_ partitionDefinition_ RP_
| DROP PARTITION ignoredIdentifiers_
| DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| TRUNCATE PARTITION (ignoredIdentifiers_ | ALL)
| COALESCE PARTITION NUMBER_
| REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_
| EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)?
| ANALYZE PARTITION (ignoredIdentifiers_ | ALL)
| CHECK PARTITION (ignoredIdentifiers_ | ALL)
| OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL)
| REBUILD PARTITION (ignoredIdentifiers_ | ALL)
| REPAIR PARTITION (ignoredIdentifiers_ | ALL)
| REMOVE PARTITIONING
| UPGRADE PARTITIONING
;
tableOptions_
: tableOption_ (COMMA_? tableOption_)*
;
tableOption_
: AUTO_INCREMENT EQ_? NUMBER_
| AVG_ROW_LENGTH EQ_? NUMBER_
| DEFAULT? (characterSet_ | collateClause_)
| CHECKSUM EQ_? NUMBER_
| COMMENT EQ_? STRING_
| COMPRESSION EQ_? STRING_
| CONNECTION EQ_? STRING_
| (DATA | INDEX) DIRECTORY EQ_? STRING_
| DELAY_KEY_WRITE EQ_? NUMBER_
| ENCRYPTION EQ_? STRING_
| ENGINE EQ_? ignoredIdentifier_
| INSERT_METHOD EQ_? (NO | FIRST | LAST)
| KEY_BLOCK_SIZE EQ_? NUMBER_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| PACK_KEYS EQ_? (NUMBER_ | DEFAULT)
| PASSWORD EQ_? STRING_
| ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT)
| STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_)
| STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_)
| STATS_SAMPLE_PAGES EQ_? NUMBER_
| TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))?
| UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_
;
addColumnSpecification
: ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_)
;
firstOrAfterColumn
: FIRST | AFTER columnName
;
addIndexSpecification
: ADD indexDefinition_
;
addConstraintSpecification
: ADD constraintDefinition_
;
changeColumnSpecification
: CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn?
;
dropColumnSpecification
: DROP COLUMN? columnName
;
dropIndexSpecification
: DROP (INDEX | KEY) indexName
;
dropPrimaryKeySpecification
: DROP primaryKey
;
modifyColumnSpecification
: MODIFY COLUMN? columnDefinition firstOrAfterColumn?
;
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
// TODO hongjun: should support renameIndexSpecification on mysql
renameIndexSpecification
: RENAME (INDEX | KEY) indexName TO indexName
;
renameTableSpecification_
: RENAME (TO | AS)? identifier_
;
partitionDefinitions_
: LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_
;
partitionDefinition_
: PARTITION identifier_
(VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))?
partitionDefinitionOption_*
(LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)?
;
partitionLessThanValue_
: LP_ (expr | partitionValueList_) RP_ | MAXVALUE
;
partitionValueList_
: literals (COMMA_ literals)*
;
partitionDefinitionOption_
: STORAGE? ENGINE EQ_? identifier_
| COMMENT EQ_? STRING_
| DATA DIRECTORY EQ_? STRING_
| INDEX DIRECTORY EQ_? STRING_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| TABLESPACE EQ_? identifier_
;
subpartitionDefinition_
: SUBPARTITION identifier_ partitionDefinitionOption_*
;
dropTableSpecification_
: TEMPORARY?
;
tableExistClause_
: (IF EXISTS)?
;
dropIndexSpecification_
: ONLINE | OFFLINE
;
|
fix mysql DDLStatement.g4
|
fix mysql DDLStatement.g4
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
90267ea949d87a8c45f1254be5468dabfeeb53db
|
presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4
|
presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.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.
*/
grammar SqlBase;
tokens {
DELIMITER
}
singleStatement
: statement EOF
;
singleExpression
: expression EOF
;
statement
: query #statementDefault
| USE schema=identifier #use
| USE catalog=identifier '.' schema=identifier #use
| CREATE TABLE qualifiedName AS query #createTableAsSelect
| CREATE TABLE qualifiedName
'(' tableElement (',' tableElement)* ')' #createTable
| DROP TABLE (IF EXISTS)? qualifiedName #dropTable
| INSERT INTO qualifiedName query #insertInto
| DELETE FROM qualifiedName (WHERE booleanExpression)? #delete
| ALTER TABLE from=qualifiedName RENAME TO to=qualifiedName #renameTable
| ALTER TABLE tableName=qualifiedName
RENAME COLUMN from=identifier TO to=identifier #renameColumn
| CREATE (OR REPLACE)? VIEW qualifiedName AS query #createView
| DROP VIEW (IF EXISTS)? qualifiedName #dropView
| EXPLAIN ('(' explainOption (',' explainOption)* ')')? statement #explain
| SHOW TABLES ((FROM | IN) qualifiedName)? (LIKE pattern=STRING)? #showTables
| SHOW SCHEMAS ((FROM | IN) identifier)? #showSchemas
| SHOW CATALOGS #showCatalogs
| SHOW COLUMNS (FROM | IN) qualifiedName #showColumns
| DESCRIBE qualifiedName #showColumns
| DESC qualifiedName #showColumns
| SHOW FUNCTIONS #showFunctions
| SHOW SESSION #showSession
| SET SESSION qualifiedName EQ STRING #setSession
| RESET SESSION qualifiedName #resetSession
| SHOW PARTITIONS (FROM | IN) qualifiedName
(WHERE booleanExpression)?
(ORDER BY sortItem (',' sortItem)*)?
(LIMIT limit=INTEGER_VALUE)? #showPartitions
;
query
: with? queryNoWith
;
with
: WITH RECURSIVE? namedQuery (',' namedQuery)*
;
tableElement
: identifier type
;
queryNoWith:
queryTerm
(ORDER BY sortItem (',' sortItem)*)?
(LIMIT limit=INTEGER_VALUE)?
(APPROXIMATE AT confidence=number CONFIDENCE)?
;
queryTerm
: queryPrimary #queryTermDefault
| left=queryTerm operator=INTERSECT setQuantifier? right=queryTerm #setOperation
| left=queryTerm operator=(UNION | EXCEPT) setQuantifier? right=queryTerm #setOperation
;
queryPrimary
: querySpecification #queryPrimaryDefault
| TABLE qualifiedName #table
| VALUES expression (',' expression)* #inlineTable
| '(' queryNoWith ')' #subquery
;
sortItem
: expression ordering=(ASC | DESC)? (NULLS nullOrdering=(FIRST | LAST))?
;
querySpecification
: SELECT setQuantifier? selectItem (',' selectItem)*
(FROM relation (',' relation)*)?
(WHERE where=booleanExpression)?
(GROUP BY groupBy+=expression (',' groupBy+=expression)*)?
(HAVING having=booleanExpression)?
;
namedQuery
: name=identifier (columnAliases)? AS '(' query ')'
;
setQuantifier
: DISTINCT
| ALL
;
selectItem
: expression (AS? identifier)? #selectSingle
| qualifiedName '.' ASTERISK #selectAll
| ASTERISK #selectAll
;
relation
: left=relation
( CROSS JOIN right=sampledRelation
| joinType JOIN rightRelation=relation joinCriteria
| NATURAL joinType JOIN right=sampledRelation
) #joinRelation
| sampledRelation #relationDefault
;
joinType
: INNER?
| LEFT OUTER?
| RIGHT OUTER?
| FULL OUTER?
;
joinCriteria
: ON booleanExpression
| USING '(' identifier (',' identifier)* ')'
;
sampledRelation
: aliasedRelation (
TABLESAMPLE sampleType '(' percentage=expression ')'
RESCALED?
(STRATIFY ON '(' stratify+=expression (',' stratify+=expression)* ')')?
)?
;
sampleType
: BERNOULLI
| SYSTEM
| POISSONIZED
;
aliasedRelation
: relationPrimary (AS? identifier columnAliases?)?
;
columnAliases
: '(' identifier (',' identifier)* ')'
;
relationPrimary
: qualifiedName #tableName
| '(' query ')' #subqueryRelation
| UNNEST '(' expression (',' expression)* ')' (WITH ORDINALITY)? #unnest
| '(' relation ')' #parenthesizedRelation
;
expression
: booleanExpression
;
booleanExpression
: predicated #booleanDefault
| NOT booleanExpression #logicalNot
| left=booleanExpression operator=AND right=booleanExpression #logicalBinary
| left=booleanExpression operator=OR right=booleanExpression #logicalBinary
| EXISTS '(' query ')' #exists
;
// workaround for:
// https://github.com/antlr/antlr4/issues/780
// https://github.com/antlr/antlr4/issues/781
predicated
: valueExpression predicate[$valueExpression.ctx]?
;
predicate[ParserRuleContext value]
: comparisonOperator right=valueExpression #comparison
| NOT? BETWEEN lower=valueExpression AND upper=valueExpression #between
| NOT? IN '(' expression (',' expression)* ')' #inList
| NOT? IN '(' query ')' #inSubquery
| NOT? LIKE pattern=valueExpression (ESCAPE escape=valueExpression)? #like
| IS NOT? NULL #nullPredicate
| IS NOT? DISTINCT FROM right=valueExpression #distinctFrom
;
valueExpression
: primaryExpression #valueExpressionDefault
| valueExpression AT timeZoneSpecifier #atTimeZone
| operator=(MINUS | PLUS) valueExpression #arithmeticUnary
| left=valueExpression operator=(ASTERISK | SLASH | PERCENT) right=valueExpression #arithmeticBinary
| left=valueExpression operator=(PLUS | MINUS) right=valueExpression #arithmeticBinary
| left=valueExpression CONCAT right=valueExpression #concatenation
;
primaryExpression
: NULL #nullLiteral
| interval #intervalLiteral
| identifier STRING #typeConstructor
| number #numericLiteral
| booleanValue #booleanLiteral
| STRING #stringLiteral
| '(' expression (',' expression)+ ')' #rowConstructor
| ROW '(' expression (',' expression)* ')' #rowConstructor
| qualifiedName #columnReference
| qualifiedName '(' ASTERISK ')' over? #functionCall
| qualifiedName '(' (setQuantifier? expression (',' expression)*)? ')' over? #functionCall
| '(' query ')' #subqueryExpression
| CASE valueExpression whenClause+ (ELSE elseExpression=expression)? END #simpleCase
| CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase
| CAST '(' expression AS type ')' #cast
| TRY_CAST '(' expression AS type ')' #cast
| ARRAY '[' (expression (',' expression)*)? ']' #arrayConstructor
| value=primaryExpression '[' index=valueExpression ']' #subscript
| value=primaryExpression '.' fieldName=identifier #fieldReference
| name=CURRENT_DATE #specialDateTimeFunction
| name=CURRENT_TIME ('(' precision=INTEGER_VALUE ')')? #specialDateTimeFunction
| name=CURRENT_TIMESTAMP ('(' precision=INTEGER_VALUE ')')? #specialDateTimeFunction
| name=LOCALTIME ('(' precision=INTEGER_VALUE ')')? #specialDateTimeFunction
| name=LOCALTIMESTAMP ('(' precision=INTEGER_VALUE ')')? #specialDateTimeFunction
| SUBSTRING '(' valueExpression FROM valueExpression (FOR valueExpression)? ')' #substring
| EXTRACT '(' identifier FROM valueExpression ')' #extract
| '(' expression ')' #parenthesizedExpression
;
timeZoneSpecifier
: TIME ZONE interval #timeZoneInterval
| TIME ZONE STRING #timeZoneString
;
comparisonOperator
: EQ | NEQ | LT | LTE | GT | GTE
;
booleanValue
: TRUE | FALSE
;
interval
: INTERVAL sign=(PLUS | MINUS)? STRING from=intervalField (TO to=intervalField)?
;
intervalField
: YEAR | MONTH | DAY | HOUR | MINUTE | SECOND
;
type
: type ARRAY
| ARRAY '<' type '>'
| MAP '<' type ',' type '>'
| simpleType
;
simpleType
: TIME_WITH_TIME_ZONE
| TIMESTAMP_WITH_TIME_ZONE
| identifier
;
whenClause
: WHEN condition=expression THEN result=expression
;
over
: OVER '('
(PARTITION BY partition+=expression (',' partition+=expression)*)?
(ORDER BY sortItem (',' sortItem)*)?
windowFrame?
')'
;
windowFrame
: frameType=RANGE start=frameBound
| frameType=ROWS start=frameBound
| frameType=RANGE BETWEEN start=frameBound AND end=frameBound
| frameType=ROWS BETWEEN start=frameBound AND end=frameBound
;
frameBound
: UNBOUNDED boundType=PRECEDING #unboundedFrame
| UNBOUNDED boundType=FOLLOWING #unboundedFrame
| CURRENT ROW #currentRowBound
| expression boundType=(PRECEDING | FOLLOWING) #boundedFrame // expression should be unsignedLiteral
;
explainOption
: FORMAT value=(TEXT | GRAPHVIZ | JSON) #explainFormat
| TYPE value=(LOGICAL | DISTRIBUTED) #explainType
;
qualifiedName
: identifier ('.' identifier)*
;
identifier
: IDENTIFIER #unquotedIdentifier
| quotedIdentifier #quotedIdentifierAlternative
| nonReserved #unquotedIdentifier
| BACKQUOTED_IDENTIFIER #backQuotedIdentifier
| DIGIT_IDENTIFIER #digitIdentifier
;
quotedIdentifier
: QUOTED_IDENTIFIER
;
number
: DECIMAL_VALUE #decimalLiteral
| INTEGER_VALUE #integerLiteral
;
nonReserved
: SHOW | TABLES | COLUMNS | COLUMN | PARTITIONS | FUNCTIONS | SCHEMAS | CATALOGS | SESSION
| OVER | PARTITION | RANGE | ROWS | PRECEDING | FOLLOWING | CURRENT | ROW | MAP
| DATE | TIME | TIMESTAMP | INTERVAL
| YEAR | MONTH | DAY | HOUR | MINUTE | SECOND
| EXPLAIN | FORMAT | TYPE | TEXT | GRAPHVIZ | LOGICAL | DISTRIBUTED
| TABLESAMPLE | SYSTEM | BERNOULLI | POISSONIZED | USE | JSON | TO
| RESCALED | APPROXIMATE | AT | CONFIDENCE
| SET | RESET
| VIEW | REPLACE
| IF | NULLIF | COALESCE
;
SELECT: 'SELECT';
FROM: 'FROM';
AS: 'AS';
ALL: 'ALL';
SOME: 'SOME';
ANY: 'ANY';
DISTINCT: 'DISTINCT';
WHERE: 'WHERE';
GROUP: 'GROUP';
BY: 'BY';
ORDER: 'ORDER';
HAVING: 'HAVING';
LIMIT: 'LIMIT';
APPROXIMATE: 'APPROXIMATE';
AT: 'AT';
CONFIDENCE: 'CONFIDENCE';
OR: 'OR';
AND: 'AND';
IN: 'IN';
NOT: 'NOT';
EXISTS: 'EXISTS';
BETWEEN: 'BETWEEN';
LIKE: 'LIKE';
IS: 'IS';
NULL: 'NULL';
TRUE: 'TRUE';
FALSE: 'FALSE';
NULLS: 'NULLS';
FIRST: 'FIRST';
LAST: 'LAST';
ESCAPE: 'ESCAPE';
ASC: 'ASC';
DESC: 'DESC';
SUBSTRING: 'SUBSTRING';
FOR: 'FOR';
DATE: 'DATE';
TIME: 'TIME';
TIMESTAMP: 'TIMESTAMP';
INTERVAL: 'INTERVAL';
YEAR: 'YEAR';
MONTH: 'MONTH';
DAY: 'DAY';
HOUR: 'HOUR';
MINUTE: 'MINUTE';
SECOND: 'SECOND';
ZONE: 'ZONE';
CURRENT_DATE: 'CURRENT_DATE';
CURRENT_TIME: 'CURRENT_TIME';
CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP';
LOCALTIME: 'LOCALTIME';
LOCALTIMESTAMP: 'LOCALTIMESTAMP';
EXTRACT: 'EXTRACT';
CASE: 'CASE';
WHEN: 'WHEN';
THEN: 'THEN';
ELSE: 'ELSE';
END: 'END';
JOIN: 'JOIN';
CROSS: 'CROSS';
OUTER: 'OUTER';
INNER: 'INNER';
LEFT: 'LEFT';
RIGHT: 'RIGHT';
FULL: 'FULL';
NATURAL: 'NATURAL';
USING: 'USING';
ON: 'ON';
OVER: 'OVER';
PARTITION: 'PARTITION';
RANGE: 'RANGE';
ROWS: 'ROWS';
UNBOUNDED: 'UNBOUNDED';
PRECEDING: 'PRECEDING';
FOLLOWING: 'FOLLOWING';
CURRENT: 'CURRENT';
ROW: 'ROW';
WITH: 'WITH';
RECURSIVE: 'RECURSIVE';
VALUES: 'VALUES';
CREATE: 'CREATE';
TABLE: 'TABLE';
VIEW: 'VIEW';
REPLACE: 'REPLACE';
INSERT: 'INSERT';
DELETE: 'DELETE';
INTO: 'INTO';
CONSTRAINT: 'CONSTRAINT';
DESCRIBE: 'DESCRIBE';
EXPLAIN: 'EXPLAIN';
FORMAT: 'FORMAT';
TYPE: 'TYPE';
TEXT: 'TEXT';
GRAPHVIZ: 'GRAPHVIZ';
JSON: 'JSON';
LOGICAL: 'LOGICAL';
DISTRIBUTED: 'DISTRIBUTED';
CAST: 'CAST';
TRY_CAST: 'TRY_CAST';
SHOW: 'SHOW';
TABLES: 'TABLES';
SCHEMAS: 'SCHEMAS';
CATALOGS: 'CATALOGS';
COLUMNS: 'COLUMNS';
COLUMN: 'COLUMN';
USE: 'USE';
PARTITIONS: 'PARTITIONS';
FUNCTIONS: 'FUNCTIONS';
DROP: 'DROP';
UNION: 'UNION';
EXCEPT: 'EXCEPT';
INTERSECT: 'INTERSECT';
TO: 'TO';
SYSTEM: 'SYSTEM';
BERNOULLI: 'BERNOULLI';
POISSONIZED: 'POISSONIZED';
TABLESAMPLE: 'TABLESAMPLE';
RESCALED: 'RESCALED';
STRATIFY: 'STRATIFY';
ALTER: 'ALTER';
RENAME: 'RENAME';
UNNEST: 'UNNEST';
ORDINALITY: 'ORDINALITY';
ARRAY: 'ARRAY';
MAP: 'MAP';
SET: 'SET';
RESET: 'RESET';
SESSION: 'SESSION';
IF: 'IF';
NULLIF: 'NULLIF';
COALESCE: 'COALESCE';
EQ : '=';
NEQ : '<>' | '!=';
LT : '<';
LTE : '<=';
GT : '>';
GTE : '>=';
PLUS: '+';
MINUS: '-';
ASTERISK: '*';
SLASH: '/';
PERCENT: '%';
CONCAT: '||';
STRING
: '\'' ( ~'\'' | '\'\'' )* '\''
;
INTEGER_VALUE
: DIGIT+
;
DECIMAL_VALUE
: DIGIT+ '.' DIGIT*
| '.' DIGIT+
| DIGIT+ ('.' DIGIT*)? EXPONENT
| '.' DIGIT+ EXPONENT
;
IDENTIFIER
: (LETTER | '_') (LETTER | DIGIT | '_' | '@' | ':')*
;
DIGIT_IDENTIFIER
: DIGIT (LETTER | DIGIT | '_' | '@' | ':')+
;
QUOTED_IDENTIFIER
: '"' ( ~'"' | '""' )* '"'
;
BACKQUOTED_IDENTIFIER
: '`' ( ~'`' | '``' )* '`'
;
TIME_WITH_TIME_ZONE
: 'TIME' WS 'WITH' WS 'TIME' WS 'ZONE'
;
TIMESTAMP_WITH_TIME_ZONE
: 'TIMESTAMP' WS 'WITH' WS 'TIME' WS 'ZONE'
;
fragment EXPONENT
: 'E' [+-]? DIGIT+
;
fragment DIGIT
: [0-9]
;
fragment LETTER
: [A-Z]
;
SIMPLE_COMMENT
: '--' ~[\r\n]* '\r'? '\n'? -> channel(HIDDEN)
;
BRACKETED_COMMENT
: '/*' .*? '*/' -> channel(HIDDEN)
;
WS
: [ \r\n\t]+ -> channel(HIDDEN)
;
// Catch-all for anything we can't recognize.
// We use this to be able to ignore and recover all the text
// when splitting statements with DelimiterLexer
UNRECOGNIZED
: .+?
;
|
/*
* 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 SqlBase;
tokens {
DELIMITER
}
singleStatement
: statement EOF
;
singleExpression
: expression EOF
;
statement
: query #statementDefault
| USE schema=identifier #use
| USE catalog=identifier '.' schema=identifier #use
| CREATE TABLE qualifiedName AS query #createTableAsSelect
| CREATE TABLE qualifiedName
'(' tableElement (',' tableElement)* ')' #createTable
| DROP TABLE (IF EXISTS)? qualifiedName #dropTable
| INSERT INTO qualifiedName query #insertInto
| DELETE FROM qualifiedName (WHERE booleanExpression)? #delete
| ALTER TABLE from=qualifiedName RENAME TO to=qualifiedName #renameTable
| ALTER TABLE tableName=qualifiedName
RENAME COLUMN from=identifier TO to=identifier #renameColumn
| CREATE (OR REPLACE)? VIEW qualifiedName AS query #createView
| DROP VIEW (IF EXISTS)? qualifiedName #dropView
| EXPLAIN ('(' explainOption (',' explainOption)* ')')? statement #explain
| SHOW TABLES ((FROM | IN) qualifiedName)? (LIKE pattern=STRING)? #showTables
| SHOW SCHEMAS ((FROM | IN) identifier)? #showSchemas
| SHOW CATALOGS #showCatalogs
| SHOW COLUMNS (FROM | IN) qualifiedName #showColumns
| DESCRIBE qualifiedName #showColumns
| DESC qualifiedName #showColumns
| SHOW FUNCTIONS #showFunctions
| SHOW SESSION #showSession
| SET SESSION qualifiedName EQ STRING #setSession
| RESET SESSION qualifiedName #resetSession
| SHOW PARTITIONS (FROM | IN) qualifiedName
(WHERE booleanExpression)?
(ORDER BY sortItem (',' sortItem)*)?
(LIMIT limit=INTEGER_VALUE)? #showPartitions
;
query
: with? queryNoWith
;
with
: WITH RECURSIVE? namedQuery (',' namedQuery)*
;
tableElement
: identifier type
;
queryNoWith:
queryTerm
(ORDER BY sortItem (',' sortItem)*)?
(LIMIT limit=INTEGER_VALUE)?
(APPROXIMATE AT confidence=number CONFIDENCE)?
;
queryTerm
: queryPrimary #queryTermDefault
| left=queryTerm operator=INTERSECT setQuantifier? right=queryTerm #setOperation
| left=queryTerm operator=(UNION | EXCEPT) setQuantifier? right=queryTerm #setOperation
;
queryPrimary
: querySpecification #queryPrimaryDefault
| TABLE qualifiedName #table
| VALUES expression (',' expression)* #inlineTable
| '(' queryNoWith ')' #subquery
;
sortItem
: expression ordering=(ASC | DESC)? (NULLS nullOrdering=(FIRST | LAST))?
;
querySpecification
: SELECT setQuantifier? selectItem (',' selectItem)*
(FROM relation (',' relation)*)?
(WHERE where=booleanExpression)?
(GROUP BY groupBy+=expression (',' groupBy+=expression)*)?
(HAVING having=booleanExpression)?
;
namedQuery
: name=identifier (columnAliases)? AS '(' query ')'
;
setQuantifier
: DISTINCT
| ALL
;
selectItem
: expression (AS? identifier)? #selectSingle
| qualifiedName '.' ASTERISK #selectAll
| ASTERISK #selectAll
;
relation
: left=relation
( CROSS JOIN right=sampledRelation
| joinType JOIN rightRelation=relation joinCriteria
| NATURAL joinType JOIN right=sampledRelation
) #joinRelation
| sampledRelation #relationDefault
;
joinType
: INNER?
| LEFT OUTER?
| RIGHT OUTER?
| FULL OUTER?
;
joinCriteria
: ON booleanExpression
| USING '(' identifier (',' identifier)* ')'
;
sampledRelation
: aliasedRelation (
TABLESAMPLE sampleType '(' percentage=expression ')'
RESCALED?
(STRATIFY ON '(' stratify+=expression (',' stratify+=expression)* ')')?
)?
;
sampleType
: BERNOULLI
| SYSTEM
| POISSONIZED
;
aliasedRelation
: relationPrimary (AS? identifier columnAliases?)?
;
columnAliases
: '(' identifier (',' identifier)* ')'
;
relationPrimary
: qualifiedName #tableName
| '(' query ')' #subqueryRelation
| UNNEST '(' expression (',' expression)* ')' (WITH ORDINALITY)? #unnest
| '(' relation ')' #parenthesizedRelation
;
expression
: booleanExpression
;
booleanExpression
: predicated #booleanDefault
| NOT booleanExpression #logicalNot
| left=booleanExpression operator=AND right=booleanExpression #logicalBinary
| left=booleanExpression operator=OR right=booleanExpression #logicalBinary
| EXISTS '(' query ')' #exists
;
// workaround for:
// https://github.com/antlr/antlr4/issues/780
// https://github.com/antlr/antlr4/issues/781
predicated
: valueExpression predicate[$valueExpression.ctx]?
;
predicate[ParserRuleContext value]
: comparisonOperator right=valueExpression #comparison
| NOT? BETWEEN lower=valueExpression AND upper=valueExpression #between
| NOT? IN '(' expression (',' expression)* ')' #inList
| NOT? IN '(' query ')' #inSubquery
| NOT? LIKE pattern=valueExpression (ESCAPE escape=valueExpression)? #like
| IS NOT? NULL #nullPredicate
| IS NOT? DISTINCT FROM right=valueExpression #distinctFrom
;
valueExpression
: primaryExpression #valueExpressionDefault
| valueExpression AT timeZoneSpecifier #atTimeZone
| operator=(MINUS | PLUS) valueExpression #arithmeticUnary
| left=valueExpression operator=(ASTERISK | SLASH | PERCENT) right=valueExpression #arithmeticBinary
| left=valueExpression operator=(PLUS | MINUS) right=valueExpression #arithmeticBinary
| left=valueExpression CONCAT right=valueExpression #concatenation
;
primaryExpression
: NULL #nullLiteral
| interval #intervalLiteral
| identifier STRING #typeConstructor
| number #numericLiteral
| booleanValue #booleanLiteral
| STRING #stringLiteral
| '(' expression (',' expression)+ ')' #rowConstructor
| ROW '(' expression (',' expression)* ')' #rowConstructor
| qualifiedName #columnReference
| qualifiedName '(' ASTERISK ')' over? #functionCall
| qualifiedName '(' (setQuantifier? expression (',' expression)*)? ')' over? #functionCall
| '(' query ')' #subqueryExpression
| CASE valueExpression whenClause+ (ELSE elseExpression=expression)? END #simpleCase
| CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase
| CAST '(' expression AS type ')' #cast
| TRY_CAST '(' expression AS type ')' #cast
| ARRAY '[' (expression (',' expression)*)? ']' #arrayConstructor
| value=primaryExpression '[' index=valueExpression ']' #subscript
| value=primaryExpression '.' fieldName=identifier #fieldReference
| name=CURRENT_DATE #specialDateTimeFunction
| name=CURRENT_TIME ('(' precision=INTEGER_VALUE ')')? #specialDateTimeFunction
| name=CURRENT_TIMESTAMP ('(' precision=INTEGER_VALUE ')')? #specialDateTimeFunction
| name=LOCALTIME ('(' precision=INTEGER_VALUE ')')? #specialDateTimeFunction
| name=LOCALTIMESTAMP ('(' precision=INTEGER_VALUE ')')? #specialDateTimeFunction
| SUBSTRING '(' valueExpression FROM valueExpression (FOR valueExpression)? ')' #substring
| EXTRACT '(' identifier FROM valueExpression ')' #extract
| '(' expression ')' #parenthesizedExpression
;
timeZoneSpecifier
: TIME ZONE interval #timeZoneInterval
| TIME ZONE STRING #timeZoneString
;
comparisonOperator
: EQ | NEQ | LT | LTE | GT | GTE
;
booleanValue
: TRUE | FALSE
;
interval
: INTERVAL sign=(PLUS | MINUS)? STRING from=intervalField (TO to=intervalField)?
;
intervalField
: YEAR | MONTH | DAY | HOUR | MINUTE | SECOND
;
type
: type ARRAY
| ARRAY '<' type '>'
| MAP '<' type ',' type '>'
| simpleType
;
simpleType
: TIME_WITH_TIME_ZONE
| TIMESTAMP_WITH_TIME_ZONE
| identifier
;
whenClause
: WHEN condition=expression THEN result=expression
;
over
: OVER '('
(PARTITION BY partition+=expression (',' partition+=expression)*)?
(ORDER BY sortItem (',' sortItem)*)?
windowFrame?
')'
;
windowFrame
: frameType=RANGE start=frameBound
| frameType=ROWS start=frameBound
| frameType=RANGE BETWEEN start=frameBound AND end=frameBound
| frameType=ROWS BETWEEN start=frameBound AND end=frameBound
;
frameBound
: UNBOUNDED boundType=PRECEDING #unboundedFrame
| UNBOUNDED boundType=FOLLOWING #unboundedFrame
| CURRENT ROW #currentRowBound
| expression boundType=(PRECEDING | FOLLOWING) #boundedFrame // expression should be unsignedLiteral
;
explainOption
: FORMAT value=(TEXT | GRAPHVIZ | JSON) #explainFormat
| TYPE value=(LOGICAL | DISTRIBUTED) #explainType
;
qualifiedName
: identifier ('.' identifier)*
;
identifier
: IDENTIFIER #unquotedIdentifier
| quotedIdentifier #quotedIdentifierAlternative
| nonReserved #unquotedIdentifier
| BACKQUOTED_IDENTIFIER #backQuotedIdentifier
| DIGIT_IDENTIFIER #digitIdentifier
;
quotedIdentifier
: QUOTED_IDENTIFIER
;
number
: DECIMAL_VALUE #decimalLiteral
| INTEGER_VALUE #integerLiteral
;
nonReserved
: SHOW | TABLES | COLUMNS | COLUMN | PARTITIONS | FUNCTIONS | SCHEMAS | CATALOGS | SESSION
| OVER | PARTITION | RANGE | ROWS | PRECEDING | FOLLOWING | CURRENT | ROW | MAP
| DATE | TIME | TIMESTAMP | INTERVAL
| YEAR | MONTH | DAY | HOUR | MINUTE | SECOND
| EXPLAIN | FORMAT | TYPE | TEXT | GRAPHVIZ | LOGICAL | DISTRIBUTED
| TABLESAMPLE | SYSTEM | BERNOULLI | POISSONIZED | USE | JSON | TO
| RESCALED | APPROXIMATE | AT | CONFIDENCE
| SET | RESET
| VIEW | REPLACE
| IF | NULLIF | COALESCE
;
SELECT: 'SELECT';
FROM: 'FROM';
AS: 'AS';
ALL: 'ALL';
SOME: 'SOME';
ANY: 'ANY';
DISTINCT: 'DISTINCT';
WHERE: 'WHERE';
GROUP: 'GROUP';
BY: 'BY';
ORDER: 'ORDER';
HAVING: 'HAVING';
LIMIT: 'LIMIT';
APPROXIMATE: 'APPROXIMATE';
AT: 'AT';
CONFIDENCE: 'CONFIDENCE';
OR: 'OR';
AND: 'AND';
IN: 'IN';
NOT: 'NOT';
EXISTS: 'EXISTS';
BETWEEN: 'BETWEEN';
LIKE: 'LIKE';
IS: 'IS';
NULL: 'NULL';
TRUE: 'TRUE';
FALSE: 'FALSE';
NULLS: 'NULLS';
FIRST: 'FIRST';
LAST: 'LAST';
ESCAPE: 'ESCAPE';
ASC: 'ASC';
DESC: 'DESC';
SUBSTRING: 'SUBSTRING';
FOR: 'FOR';
DATE: 'DATE';
TIME: 'TIME';
TIMESTAMP: 'TIMESTAMP';
INTERVAL: 'INTERVAL';
YEAR: 'YEAR';
MONTH: 'MONTH';
DAY: 'DAY';
HOUR: 'HOUR';
MINUTE: 'MINUTE';
SECOND: 'SECOND';
ZONE: 'ZONE';
CURRENT_DATE: 'CURRENT_DATE';
CURRENT_TIME: 'CURRENT_TIME';
CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP';
LOCALTIME: 'LOCALTIME';
LOCALTIMESTAMP: 'LOCALTIMESTAMP';
EXTRACT: 'EXTRACT';
CASE: 'CASE';
WHEN: 'WHEN';
THEN: 'THEN';
ELSE: 'ELSE';
END: 'END';
JOIN: 'JOIN';
CROSS: 'CROSS';
OUTER: 'OUTER';
INNER: 'INNER';
LEFT: 'LEFT';
RIGHT: 'RIGHT';
FULL: 'FULL';
NATURAL: 'NATURAL';
USING: 'USING';
ON: 'ON';
OVER: 'OVER';
PARTITION: 'PARTITION';
RANGE: 'RANGE';
ROWS: 'ROWS';
UNBOUNDED: 'UNBOUNDED';
PRECEDING: 'PRECEDING';
FOLLOWING: 'FOLLOWING';
CURRENT: 'CURRENT';
ROW: 'ROW';
WITH: 'WITH';
RECURSIVE: 'RECURSIVE';
VALUES: 'VALUES';
CREATE: 'CREATE';
TABLE: 'TABLE';
VIEW: 'VIEW';
REPLACE: 'REPLACE';
INSERT: 'INSERT';
DELETE: 'DELETE';
INTO: 'INTO';
CONSTRAINT: 'CONSTRAINT';
DESCRIBE: 'DESCRIBE';
EXPLAIN: 'EXPLAIN';
FORMAT: 'FORMAT';
TYPE: 'TYPE';
TEXT: 'TEXT';
GRAPHVIZ: 'GRAPHVIZ';
JSON: 'JSON';
LOGICAL: 'LOGICAL';
DISTRIBUTED: 'DISTRIBUTED';
CAST: 'CAST';
TRY_CAST: 'TRY_CAST';
SHOW: 'SHOW';
TABLES: 'TABLES';
SCHEMAS: 'SCHEMAS';
CATALOGS: 'CATALOGS';
COLUMNS: 'COLUMNS';
COLUMN: 'COLUMN';
USE: 'USE';
PARTITIONS: 'PARTITIONS';
FUNCTIONS: 'FUNCTIONS';
DROP: 'DROP';
UNION: 'UNION';
EXCEPT: 'EXCEPT';
INTERSECT: 'INTERSECT';
TO: 'TO';
SYSTEM: 'SYSTEM';
BERNOULLI: 'BERNOULLI';
POISSONIZED: 'POISSONIZED';
TABLESAMPLE: 'TABLESAMPLE';
RESCALED: 'RESCALED';
STRATIFY: 'STRATIFY';
ALTER: 'ALTER';
RENAME: 'RENAME';
UNNEST: 'UNNEST';
ORDINALITY: 'ORDINALITY';
ARRAY: 'ARRAY';
MAP: 'MAP';
SET: 'SET';
RESET: 'RESET';
SESSION: 'SESSION';
IF: 'IF';
NULLIF: 'NULLIF';
COALESCE: 'COALESCE';
EQ : '=';
NEQ : '<>' | '!=';
LT : '<';
LTE : '<=';
GT : '>';
GTE : '>=';
PLUS: '+';
MINUS: '-';
ASTERISK: '*';
SLASH: '/';
PERCENT: '%';
CONCAT: '||';
STRING
: '\'' ( ~'\'' | '\'\'' )* '\''
;
INTEGER_VALUE
: DIGIT+
;
DECIMAL_VALUE
: DIGIT+ '.' DIGIT*
| '.' DIGIT+
| DIGIT+ ('.' DIGIT*)? EXPONENT
| '.' DIGIT+ EXPONENT
;
IDENTIFIER
: (LETTER | '_') (LETTER | DIGIT | '_' | '@' | ':')*
;
DIGIT_IDENTIFIER
: DIGIT (LETTER | DIGIT | '_' | '@' | ':')+
;
QUOTED_IDENTIFIER
: '"' ( ~'"' | '""' )* '"'
;
BACKQUOTED_IDENTIFIER
: '`' ( ~'`' | '``' )* '`'
;
TIME_WITH_TIME_ZONE
: 'TIME' WS 'WITH' WS 'TIME' WS 'ZONE'
;
TIMESTAMP_WITH_TIME_ZONE
: 'TIMESTAMP' WS 'WITH' WS 'TIME' WS 'ZONE'
;
fragment EXPONENT
: 'E' [+-]? DIGIT+
;
fragment DIGIT
: [0-9]
;
fragment LETTER
: [A-Z]
;
SIMPLE_COMMENT
: '--' ~[\r\n]* '\r'? '\n'? -> channel(HIDDEN)
;
BRACKETED_COMMENT
: '/*' .*? '*/' -> channel(HIDDEN)
;
WS
: [ \r\n\t]+ -> channel(HIDDEN)
;
// Catch-all for anything we can't recognize.
// We use this to be able to ignore and recover all the text
// when splitting statements with DelimiterLexer
UNRECOGNIZED
: .
;
|
Improve lexer matching of invalid characters
|
Improve lexer matching of invalid characters
This variant is functionally equivalent but faster than the non-greedy match.
|
ANTLR
|
apache-2.0
|
zofuthan/presto,tellproject/presto,nezihyigitbasi/presto,toxeh/presto,ebyhr/presto,mandusm/presto,sunchao/presto,avasilevskiy/presto,smartpcr/presto,sunchao/presto,xiangel/presto,joy-yao/presto,jekey/presto,propene/presto,miniway/presto,ipros-team/presto,miquelruiz/presto,martint/presto,Svjard/presto,miquelruiz/presto,gcnonato/presto,kietly/presto,martint/presto,troels/nz-presto,jiangyifangh/presto,erichwang/presto,fengshao0907/presto,mcanthony/presto,harunurhan/presto,rockerbox/presto,kined/presto,prestodb/presto,twitter-forks/presto,TeradataCenterForHadoop/bootcamp,troels/nz-presto,dongjoon-hyun/presto,fipar/presto,aglne/presto,jekey/presto,xiangel/presto,Teradata/presto,geraint0923/presto,arhimondr/presto,cawallin/presto,losipiuk/presto,kietly/presto,Zoomdata/presto,saidalaoui/presto,prateek1306/presto,tomz/presto,wagnermarkd/presto,cawallin/presto,joy-yao/presto,losipiuk/presto,aglne/presto,stewartpark/presto,propene/presto,elonazoulay/presto,11xor6/presto,Zoomdata/presto,prateek1306/presto,11xor6/presto,cosinequanon/presto,miquelruiz/presto,miniway/presto,zzhao0/presto,fengshao0907/presto,Svjard/presto,Myrthan/presto,prateek1306/presto,mode/presto,dain/presto,ebd2/presto,twitter-forks/presto,kined/presto,mcanthony/presto,soz-fb/presto,youngwookim/presto,shixuan-fan/presto,nsabharwal/presto,mcanthony/presto,pwz3n0/presto,troels/nz-presto,takari/presto,wyukawa/presto,shixuan-fan/presto,hulu/presto,Yaliang/presto,bloomberg/presto,Teradata/presto,tomz/presto,ebyhr/presto,rockerbox/presto,mbeitchman/presto,kuzemchik/presto,deciament/presto,zzhao0/presto,tellproject/presto,fiedukow/presto,suyucs/presto,kietly/presto,dongjoon-hyun/presto,bloomberg/presto,lingochamp/presto,totticarter/presto,mattyb149/presto,nileema/presto,nsabharwal/presto,springning/presto,toyama0919/presto,ebd2/presto,youngwookim/presto,sunchao/presto,tellproject/presto,TeradataCenterForHadoop/bootcamp,kingland/presto,haozhun/presto,haitaoyao/presto,chrisunder/presto,svstanev/presto,haozhun/presto,yuananf/presto,siddhartharay007/presto,kaschaeffer/presto,mvp/presto,nakajijiji/presto,RobinUS2/presto,saidalaoui/presto,cosinequanon/presto,zzhao0/presto,hgschmie/presto,hulu/presto,DanielTing/presto,miniway/presto,jiekechoo/presto,nezihyigitbasi/presto,miquelruiz/presto,kined/presto,y-lan/presto,Svjard/presto,youngwookim/presto,Praveen2112/presto,mattyb149/presto,wagnermarkd/presto,zofuthan/presto,mpilman/presto,kined/presto,jf367/presto,kuzemchik/presto,gcnonato/presto,hgschmie/presto,toyama0919/presto,pwz3n0/presto,haitaoyao/presto,arhimondr/presto,idemura/presto,erichwang/presto,smartnews/presto,cberner/presto,suyucs/presto,losipiuk/presto,suyucs/presto,zjshen/presto,EvilMcJerkface/presto,mugglmenzel/presto,zofuthan/presto,nileema/presto,gh351135612/presto,prestodb/presto,Myrthan/presto,mcanthony/presto,Praveen2112/presto,electrum/presto,kietly/presto,EvilMcJerkface/presto,jxiang/presto,vermaravikant/presto,kaschaeffer/presto,ArturGajowy/presto,yuananf/presto,cberner/presto,sopel39/presto,damiencarol/presto,kined/presto,smartnews/presto,ajoabraham/presto,miniway/presto,y-lan/presto,dain/presto,ArturGajowy/presto,Teradata/presto,avasilevskiy/presto,sunchao/presto,toyama0919/presto,geraint0923/presto,ebd2/presto,nezihyigitbasi/presto,mode/presto,elonazoulay/presto,cawallin/presto,suyucs/presto,mpilman/presto,treasure-data/presto,sumanth232/presto,gh351135612/presto,suyucs/presto,elonazoulay/presto,Svjard/presto,kaschaeffer/presto,wrmsr/presto,sumanth232/presto,fiedukow/presto,siddhartharay007/presto,totticarter/presto,albertocsm/presto,ebd2/presto,hgschmie/presto,saidalaoui/presto,mbeitchman/presto,gh351135612/presto,dongjoon-hyun/presto,smartpcr/presto,propene/presto,hulu/presto,Yaliang/presto,facebook/presto,vermaravikant/presto,hulu/presto,bloomberg/presto,totticarter/presto,mvp/presto,nakajijiji/presto,fipar/presto,fiedukow/presto,zjshen/presto,mattyb149/presto,y-lan/presto,nakajijiji/presto,Zoomdata/presto,damiencarol/presto,aramesh117/presto,Jimexist/presto,ArturGajowy/presto,Myrthan/presto,RobinUS2/presto,Myrthan/presto,wagnermarkd/presto,ptkool/presto,avasilevskiy/presto,miquelruiz/presto,hgschmie/presto,Zoomdata/presto,aleph-zero/presto,yuananf/presto,jiangyifangh/presto,Yaliang/presto,gcnonato/presto,gh351135612/presto,yu-yamada/presto,jekey/presto,dongjoon-hyun/presto,yuananf/presto,deciament/presto,chrisunder/presto,joy-yao/presto,EvilMcJerkface/presto,tellproject/presto,facebook/presto,damiencarol/presto,ocono-tech/presto,ebd2/presto,springning/presto,yu-yamada/presto,rockerbox/presto,zofuthan/presto,Nasdaq/presto,deciament/presto,twitter-forks/presto,11xor6/presto,avasilevskiy/presto,fipar/presto,DanielTing/presto,kaschaeffer/presto,aramesh117/presto,smartnews/presto,martint/presto,svstanev/presto,zhenyuy-fb/presto,jiangyifangh/presto,fipar/presto,mandusm/presto,ebyhr/presto,Praveen2112/presto,XiaominZhang/presto,youngwookim/presto,troels/nz-presto,raghavsethi/presto,haitaoyao/presto,sumanth232/presto,yuananf/presto,smartpcr/presto,prestodb/presto,11xor6/presto,xiangel/presto,ajoabraham/presto,ptkool/presto,treasure-data/presto,arhimondr/presto,soz-fb/presto,nsabharwal/presto,erichwang/presto,mugglmenzel/presto,mpilman/presto,geraint0923/presto,mattyb149/presto,nezihyigitbasi/presto,mugglmenzel/presto,toyama0919/presto,cberner/presto,raghavsethi/presto,propene/presto,XiaominZhang/presto,ptkool/presto,rockerbox/presto,Jimexist/presto,soz-fb/presto,hgschmie/presto,fengshao0907/presto,treasure-data/presto,mpilman/presto,stewartpark/presto,harunurhan/presto,takari/presto,mvp/presto,EvilMcJerkface/presto,takari/presto,springning/presto,harunurhan/presto,ocono-tech/presto,XiaominZhang/presto,totticarter/presto,nsabharwal/presto,prateek1306/presto,11xor6/presto,sopel39/presto,idemura/presto,dain/presto,xiangel/presto,Nasdaq/presto,mode/presto,stewartpark/presto,prateek1306/presto,wrmsr/presto,wangcan2014/presto,harunurhan/presto,jiekechoo/presto,shixuan-fan/presto,pwz3n0/presto,albertocsm/presto,cawallin/presto,ArturGajowy/presto,losipiuk/presto,fiedukow/presto,sumitkgec/presto,nsabharwal/presto,kingland/presto,stewartpark/presto,shixuan-fan/presto,sumitkgec/presto,svstanev/presto,mbeitchman/presto,wrmsr/presto,TeradataCenterForHadoop/bootcamp,xiangel/presto,Jimexist/presto,mbeitchman/presto,damiencarol/presto,chrisunder/presto,totticarter/presto,chrisunder/presto,sopel39/presto,geraint0923/presto,pwz3n0/presto,dain/presto,treasure-data/presto,mbeitchman/presto,ipros-team/presto,cosinequanon/presto,fiedukow/presto,sopel39/presto,sumitkgec/presto,dabaitu/presto,facebook/presto,smartpcr/presto,DanielTing/presto,smartpcr/presto,lingochamp/presto,aleph-zero/presto,mvp/presto,ocono-tech/presto,kingland/presto,pwz3n0/presto,wangcan2014/presto,dongjoon-hyun/presto,hulu/presto,ptkool/presto,y-lan/presto,nileema/presto,TeradataCenterForHadoop/bootcamp,zjshen/presto,Nasdaq/presto,raghavsethi/presto,saidalaoui/presto,losipiuk/presto,ebyhr/presto,aramesh117/presto,smartnews/presto,Teradata/presto,wyukawa/presto,soz-fb/presto,youngwookim/presto,ipros-team/presto,vermaravikant/presto,Myrthan/presto,dabaitu/presto,deciament/presto,lingochamp/presto,ArturGajowy/presto,Praveen2112/presto,shixuan-fan/presto,toyama0919/presto,lingochamp/presto,raghavsethi/presto,toxeh/presto,wangcan2014/presto,arhimondr/presto,zhenyuy-fb/presto,fengshao0907/presto,nileema/presto,sunchao/presto,kingland/presto,toxeh/presto,twitter-forks/presto,wangcan2014/presto,jf367/presto,Teradata/presto,troels/nz-presto,joy-yao/presto,geraint0923/presto,Nasdaq/presto,tellproject/presto,TeradataCenterForHadoop/bootcamp,dabaitu/presto,lingochamp/presto,jf367/presto,facebook/presto,jiangyifangh/presto,tomz/presto,aleph-zero/presto,fipar/presto,XiaominZhang/presto,springning/presto,zofuthan/presto,jiangyifangh/presto,tomz/presto,siddhartharay007/presto,zhenyuy-fb/presto,mugglmenzel/presto,smartnews/presto,treasure-data/presto,erichwang/presto,ajoabraham/presto,siddhartharay007/presto,toxeh/presto,ocono-tech/presto,bloomberg/presto,aramesh117/presto,prestodb/presto,idemura/presto,mode/presto,mode/presto,harunurhan/presto,treasure-data/presto,albertocsm/presto,cberner/presto,zhenyuy-fb/presto,propene/presto,mandusm/presto,y-lan/presto,kietly/presto,ptkool/presto,ipros-team/presto,sumanth232/presto,haozhun/presto,twitter-forks/presto,albertocsm/presto,yu-yamada/presto,stewartpark/presto,electrum/presto,miniway/presto,martint/presto,cosinequanon/presto,albertocsm/presto,kaschaeffer/presto,yu-yamada/presto,mandusm/presto,RobinUS2/presto,vermaravikant/presto,wrmsr/presto,jekey/presto,EvilMcJerkface/presto,idemura/presto,gcnonato/presto,haozhun/presto,tomz/presto,ajoabraham/presto,mugglmenzel/presto,Zoomdata/presto,aleph-zero/presto,mpilman/presto,electrum/presto,cawallin/presto,kingland/presto,vermaravikant/presto,elonazoulay/presto,mandusm/presto,fengshao0907/presto,wyukawa/presto,ajoabraham/presto,siddhartharay007/presto,ebyhr/presto,tellproject/presto,jxiang/presto,wrmsr/presto,wagnermarkd/presto,mpilman/presto,nezihyigitbasi/presto,sumanth232/presto,erichwang/presto,raghavsethi/presto,sopel39/presto,mvp/presto,jiekechoo/presto,chrisunder/presto,zhenyuy-fb/presto,haitaoyao/presto,kuzemchik/presto,mcanthony/presto,dain/presto,joy-yao/presto,sumitkgec/presto,Nasdaq/presto,dabaitu/presto,haitaoyao/presto,aglne/presto,DanielTing/presto,electrum/presto,zjshen/presto,wyukawa/presto,aramesh117/presto,martint/presto,prestodb/presto,haozhun/presto,sumitkgec/presto,nakajijiji/presto,cosinequanon/presto,Jimexist/presto,toxeh/presto,yu-yamada/presto,ipros-team/presto,svstanev/presto,kuzemchik/presto,Svjard/presto,kuzemchik/presto,jiekechoo/presto,cberner/presto,mattyb149/presto,XiaominZhang/presto,facebook/presto,damiencarol/presto,idemura/presto,jxiang/presto,electrum/presto,nakajijiji/presto,jf367/presto,deciament/presto,nileema/presto,wrmsr/presto,DanielTing/presto,saidalaoui/presto,aleph-zero/presto,arhimondr/presto,jxiang/presto,jf367/presto,wyukawa/presto,prestodb/presto,Jimexist/presto,wagnermarkd/presto,zzhao0/presto,avasilevskiy/presto,gh351135612/presto,takari/presto,aglne/presto,bloomberg/presto,RobinUS2/presto,soz-fb/presto,springning/presto,aglne/presto,Yaliang/presto,takari/presto,Praveen2112/presto,wangcan2014/presto,rockerbox/presto,ocono-tech/presto,zzhao0/presto,Yaliang/presto,jekey/presto,svstanev/presto,dabaitu/presto,zjshen/presto,RobinUS2/presto,elonazoulay/presto,jxiang/presto,jiekechoo/presto
|
6d912a05a32f7c46f6e0a6623ac9e801f8cb7761
|
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
: ALTER TABLE tableExistClause_ onlyClause_ tableName asteriskClause_ (alterTableActions | renameColumnSpecification | renameConstraint | 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?
;
tableExistClause_
: (IF EXISTS)?
;
asteriskClause_
: ASTERISK_?
;
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_
;
renameTableSpecification_
: RENAME TO newTableName
;
newTableName
: IDENTIFIER_
;
usingIndexType
: USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN)
;
excludeElement
: (columnName | expr) ignoredIdentifier_? (ASC | DESC)? (NULLS (FIRST | LAST))?
;
|
modify alterTable
|
modify alterTable
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
|
8766c0a46fd823b0a868d69da2ba414428ff9e80
|
dcct/src/main/antlr4/Dcct.g4
|
dcct/src/main/antlr4/Dcct.g4
|
grammar Dcct;
// Parser
program
: schema EOF
;
schema
: cloudDataDecl*
;
// Types
// TODO just use generic identifier and rely on type checking to rule out wrong
// identifiers? Before we had entityIdent and arrayIdent now just ident. It
// seems to be more sensible for this to be a type error rather than a parse
// error.
indexType
: 'Int'
| 'String'
| Identifier // of array or
;
cloudDataDecl
: entityDecl
;
// Entities
entityDecl
: 'entity' Identifier '(' elements ')'
;
elements
: element (',' element)*
;
element
: Identifier ':' indexType
;
// LEXER
// Types
INT : 'Int';
STRING : 'String';
SET : 'Set';
CINT : 'CInt';
CSTRING : 'CString';
CSET : 'CSet';
// Keywords
NEW : 'new';
DELETE : 'delete';
ALL : 'all';
ENTRIES : 'entries';
YIELD : 'yield';
FLUSH : 'flush';
PROPERTY : 'property';
IF : 'if';
ELSE : 'else';
FOREACH : 'foreach';
WHERE : 'where';
VAR : 'var';
ORDERBY : 'orderby';
IN : 'in';
// Separators
LPAREN : '(';
RPAREN : ')';
LBRACK : '[';
RBRACK : ']';
LBRACE : '{';
RBRACE : '}';
SEMI : ';';
COMA : ',';
DOT : '.';
// Operators
LT : '<';
GT : '>';
COLON : ':';
ARROW : '->';
TARROW : '=>';
ASSIGN : '=';
BANG : '!';
Identifier
: Letter LetterOrDigit*
;
fragment
Letter
: [a-zA-Z$_] // these are the "valid letters" below 0xFF
| // covers all characters above 0xFF which are not a surrogate
~[\u0000-\u00FF\uD800-\uDBFF]
{Character.isJavaIdentifierStart(_input.LA(-1))}?
| // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF
[\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
fragment
LetterOrDigit
: [a-zA-Z0-9$_] // these are the "valid letters or digits" below 0xFF
| // covers all characters above 0xFF which are not a surrogate
~[\u0000-\u00FF\uD800-\uDBFF]
{Character.isJavaIdentifierPart(_input.LA(-1))}?
| // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF
[\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
fragment
Digit: [0-9];
Digits: Digit+;
IntegerLiteral: Digits;
StringLiteral
: '"' StringCharacters? '"'
;
fragment
StringCharacters
: StringCharacter+
;
fragment
StringCharacter
: ~["\\]
| EscapeSequence
;
// §3.10.6 Escape Sequences for Character and String Literals
fragment
EscapeSequence
: '\\' [btnfr"'\\]
;
//
// Whitespace and comments
//
WS
: [ \t\r\n\u000C]+ -> skip
;
COMMENT
: '/*' .*? '*/' -> skip
;
LINE_COMMENT
: '//' ~[\r\n]* -> skip
;
|
grammar Dcct;
// Parser
program
: schema expression* EOF
;
schema
: cloudDataDecl*
;
// Types
// TODO just use generic identifier and rely on type checking to rule out wrong
// identifiers? Before we had entityIdent and arrayIdent now just ident. It
// seems to be more sensible for this to be a type error rather than a parse
// error.
indexType
: 'Int'
| 'String'
| Identifier // of array or entity
;
cloudType
: 'CInt'
| 'CString'
| cloudSetType
;
expressionType
: indexType
| 'Set' '<' expressionType '>'
| expressionType '->' expressionType
;
cloudSetType
: 'CSet' '<' indexType '>'
;
cloudDataDecl
: entityDecl
| arrayDecl
;
// Entities
// TODO think if I need to make the body optional
entityDecl
: 'entity' Identifier '(' elements ')' '{' properties '}'
;
//TODO I think I am enforcing one or more elements, fix...
elements
: element (',' element)*
;
element
: Identifier ':' indexType
;
properties
: property ';' (property ';')*
;
property
: Identifier ':' cloudType
;
// Arrays
arrayDecl
: 'array' Identifier '[' elements ']' '{' properties '}'
;
// Expressions, expression, and related stuff
expressions
: expression (',' expression)*
;
expression
: 'new' Identifier '(' expressions ')'
| 'delete' expression
| Identifier '[' expressions ']'
| expression '(' expressions ')'
| expression '.' expression
| 'all' Identifier
| 'entries' Identifier
| 'yield'
| 'flush'
| expression expression
| expression ';' expression
| '(' expressions ')'
| expression bop expression
| foreach
| value
| varDeclaration
;
bop
: '=='
| '!='
;
varDeclaration
: 'var' Identifier '=' value
;
value
: Identifier
| literals
| Identifier '[' values ']'
| '(' values ')'
| '(' Identifier ':' expressionType ')' '=>' expression
;
ifelse
: 'if' '(' expression ')' block 'else' block
;
block
: '{' expression '}'
;
values
: value ',' value
| value
;
foreach
: 'foreach' Identifier 'in' ('all' | 'entries') expression '.' expression
('where' expression bop expression)?
('orderby' expression '.' expression)?
block
;
literals
: IntegerLiteral
| StringLiteral
;
// LEXER
// Types
INT : 'Int';
STRING : 'String';
SET : 'Set';
CINT : 'CInt';
CSTRING : 'CString';
CSET : 'CSet';
// Keywords
NEW : 'new';
DELETE : 'delete';
ALL : 'all';
ENTRIES : 'entries';
YIELD : 'yield';
FLUSH : 'flush';
IF : 'if';
ELSE : 'else';
FOREACH : 'foreach';
WHERE : 'where';
VAR : 'var';
ORDERBY : 'orderby';
IN : 'in';
// Separators
LPAREN : '(';
RPAREN : ')';
LBRACK : '[';
RBRACK : ']';
LBRACE : '{';
RBRACE : '}';
SEMI : ';';
COMA : ',';
DOT : '.';
// Operators
LT : '<';
GT : '>';
COLON : ':';
ARROW : '->';
TARROW : '=>';
ASSIGN : '=';
BANG : '!';
Identifier
: Letter LetterOrDigit*
;
fragment
Letter
: [a-zA-Z$_] // these are the "valid letters" below 0xFF
| // covers all characters above 0xFF which are not a surrogate
~[\u0000-\u00FF\uD800-\uDBFF]
{Character.isJavaIdentifierStart(_input.LA(-1))}?
| // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF
[\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
fragment
LetterOrDigit
: [a-zA-Z0-9$_] // these are the "valid letters or digits" below 0xFF
| // covers all characters above 0xFF which are not a surrogate
~[\u0000-\u00FF\uD800-\uDBFF]
{Character.isJavaIdentifierPart(_input.LA(-1))}?
| // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF
[\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
fragment
Digit: [0-9];
Digits: Digit+;
IntegerLiteral: Digits;
StringLiteral
: '"' StringCharacters? '"'
;
fragment
StringCharacters
: StringCharacter+
;
fragment
StringCharacter
: ~["\\]
| EscapeSequence
;
// §3.10.6 Escape Sequences for Character and String Literals
fragment
EscapeSequence
: '\\' [btnfr"'\\]
;
//
// Whitespace and comments
//
WS
: [ \t\r\n\u000C]+ -> skip
;
COMMENT
: '/*' .*? '*/' -> skip
;
LINE_COMMENT
: '//' ~[\r\n]* -> skip
;
|
Add further source constructs
|
Add further source constructs
|
ANTLR
|
bsd-3-clause
|
amanjpro/languages-a-la-carte,amanjpro/languages-a-la-carte
|
acef67b2ed6b2553dfff6828c0521c0805a05390
|
python2/Python2.g4
|
python2/Python2.g4
|
/*
* Taken from official Python 2.7.13 grammar:
* https://docs.python.org/2/reference/grammar.html
*
* Only minor syntactical changes (instances of [X] changed to (X)?, and
* semicolons added to ends of rules), and added lexer rules and whitespace
* handling.
*
* Compiles with ANTLR 4.7, generated lexer/parser for Python 2 target.
*/
grammar Python2;
tokens { INDENT, DEDENT, NEWLINE, ENDMARKER }
@lexer::header {
from Python2Parser import Python2Parser
from antlr4.Token import CommonToken
}
@lexer::members {
# Indented to append code to the constructor.
self._openBRCount = 0
self._suppressNewlines = False
self._tokens = self.TokenQueue()
self._indents = self.IndentStack()
class IndentStack:
def __init__(self) : self._s = []
def empty(self) : return len(self._s) == 0
def pop(self) : self._s.pop()
def wsval(self) : return self._s[-1] if len(self._s) > 0 else 0
def push(self, wsval) : self._s.append(wsval)
class TokenQueue:
def __init__(self) : self._q = []
def enq(self, t) : self._q.append(t)
def deq(self) : return self._q.pop(0)
def empty(self) : return len(self._q) == 0
def nextToken(self):
if not self._tokens.empty():
return self._tokens.deq()
else:
t = super(Python2Lexer, self).nextToken()
if t.type != Token.EOF:
return t
else:
self.emitFullDedent()
self.emitEndmarker()
self.emitEndToken(t)
return self._tokens.deq()
def emitEndToken(self, token):
self._tokens.enq(token)
def emitIndent(self, length=0, text='INDENT'):
t = self.createToken(Python2Parser.INDENT, text, length)
self._tokens.enq(t)
def emitDedent(self):
t = self.createToken(Python2Parser.DEDENT, 'DEDENT')
self._tokens.enq(t)
def emitFullDedent(self):
while not self._indents.empty():
self._indents.pop()
self.emitDedent()
def emitEndmarker(self):
t = self.createToken(Python2Parser.ENDMARKER, 'ENDMARKER')
self._tokens.enq(t)
def emitNewline(self):
t = self.createToken(Python2Parser.NEWLINE, 'NEWLINE')
self._tokens.enq(t)
def createToken(self, type_, text="", length=0):
start = self._tokenStartCharIndex
stop = start + length
t = CommonToken(self._tokenFactorySourcePair,
type_, self.DEFAULT_TOKEN_CHANNEL,
start, stop)
t.text = text
return t
}
// Included from official site.
/*
* Grammar for Python
*
* Note: Changing the grammar specified in this file will most likely
* require corresponding changes in the parser module
* (../Modules/parsermodule.c). If you can't make the changes to
* that module yourself, please co-ordinate the required changes
* with someone who can; ask around on python-dev for help. Fred
* Drake <[email protected]> will probably be listening there.
*
* NOTE WELL: You should also follow all the steps listed in PEP 306,
* "How to Change Python's Grammar"
*
* Start symbols for the grammar:
* single_input is a single interactive statement;
* file_input is a module or sequence of commands read from an input file;
* eval_input is the input for the eval() and input() functions.
* NB: compound_stmt in single_input is followed by extra NEWLINE!
*/
single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
;
file_input: (NEWLINE | stmt)* ENDMARKER
;
eval_input: testlist NEWLINE* ENDMARKER
;
decorator: '@' dotted_name ( '(' (arglist)? ')' )? NEWLINE
;
decorators: decorator+
;
decorated: decorators (classdef | funcdef)
;
funcdef: 'def' NAME parameters ':' suite
;
parameters: '(' (varargslist)? ')'
;
varargslist: ((fpdef ('=' test)? ',')*
('*' NAME (',' '**' NAME)? | '**' NAME) |
fpdef ('=' test)? (',' fpdef ('=' test)?)* (',')?)
;
fpdef: NAME | '(' fplist ')'
;
fplist: fpdef (',' fpdef)* (',')?
;
stmt: simple_stmt | compound_stmt
;
simple_stmt: small_stmt (';' small_stmt)* (';')? NEWLINE
;
small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
import_stmt | global_stmt | exec_stmt | assert_stmt)
;
expr_stmt: testlist (augassign (yield_expr|testlist) |
('=' (yield_expr|testlist))*)
;
augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
'<<=' | '>>=' | '**=' | '//=')
// For normal assignments, additional restrictions enforced by the interpreter
;
print_stmt: 'print' ( ( test (',' test)* (',')? )? |
'>>' test ( (',' test)+ (',')? )? )
;
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 (',' test (',' test)?)?)?
;
import_stmt: import_name | import_from
;
import_name: 'import' dotted_as_names
;
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)*
;
exec_stmt: 'exec' expr ('in' test (',' test)?)?
;
assert_stmt: 'assert' test (',' test)?
;
compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated
;
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' | ',') test)?)?
;
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
;
// Backward compatibility cruft to support:
// [ x for x in lambda: True, lambda: False if x() ]
// even while also allowing:
// lambda x: 5 if x else 2
// (But not a mix of the two)
testlist_safe: old_test ((',' old_test)+ (',')?)?
;
old_test: or_test | old_lambdef
;
old_lambdef: 'lambda' (varargslist)? ':' old_test
;
test: or_test ('if' or_test 'else' test)? | lambdef
;
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)*
;
comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
;
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 trailer* ('**' factor)?
;
atom: ('(' (yield_expr|testlist_comp)? ')' |
'[' (listmaker)? ']' |
'{' (dictorsetmaker)? '}' |
'`' testlist1 '`' |
NAME | NUMBER | STRING+)
;
listmaker: test ( list_for | (',' test)* (',')? )
;
testlist_comp: test ( comp_for | (',' test)* (',')? )
;
lambdef: 'lambda' (varargslist)? ':' test
;
trailer: '(' (arglist)? ')' | '[' subscriptlist ']' | '.' NAME
;
subscriptlist: subscript (',' subscript)* (',')?
;
subscript: '.' '.' '.' | test | (test)? ':' (test)? (sliceop)?
;
sliceop: ':' (test)?
;
exprlist: expr (',' expr)* (',')?
;
testlist: test (',' test)* (',')?
;
dictorsetmaker: ( (test ':' test (comp_for | (',' test ':' test)* (',')?)) |
(test (comp_for | (',' test)* (',')?)) )
;
classdef: 'class' NAME ('(' (testlist)? ')')? ':' suite
;
arglist: (argument ',')* (argument (',')?
|'*' test (',' argument)* (',' '**' test)?
|'**' test)
// The reason that keywords are test nodes instead of NAME is that using NAME
// results in an ambiguity. ast.c makes sure it's a NAME.
;
argument: test (comp_for)? | test '=' test
;
list_iter: list_for | list_if
;
list_for: 'for' exprlist 'in' testlist_safe (list_iter)?
;
list_if: 'if' old_test (list_iter)?
;
comp_iter: comp_for | comp_if
;
comp_for: 'for' exprlist 'in' or_test (comp_iter)?
;
comp_if: 'if' old_test (comp_iter)?
;
testlist1: test (',' test)*
;
// not used in grammar, but may appear in "node" passed from Parser to Compiler
encoding_decl: NAME
;
yield_expr: 'yield' (testlist)?
;
/*
* Lexer rules
*/
STRING
: [uUbB]? [rR]?
( '\'' ('\\' (([ \t]+ ('\r'? '\n')?)|.) | ~[\\\r\n'])* '\''
| '"' ('\\' (([ \t]+ ('\r'? '\n')?)|.) | ~[\\\r\n"])* '"'
| '"""' ('\\' . | ~'\\' )*? '"""'
| '\'\'\'' ('\\' . | ~'\\' )*? '\'\'\''
)
;
NAME: [a-zA-Z_] [a-zA-Z0-9_]*
;
NUMBER
: '0' ([xX] [0-9a-fA-F]+
| [oO] [0-7]+
| [bB] [01]+ )
| ([0-9]* '.')? [0-9]+ [jJ]?
;
NEWLINES: ('\r'? '\n')+
{
if self._openBRCount == 0:
if not self._suppressNewlines:
self.emitNewline()
self._suppressNewlines = True
la = self._input.LA(1)
if la not in [ord(' '), ord('\t'), ord('#')]:
self._suppressNewlines = False
self.emitFullDedent()
} -> channel(HIDDEN)
;
WHITESPACE: ('\t' | ' ')+
{
if self._tokenStartColumn == 0 and self._openBRCount == 0:
la = self._input.LA(1)
if la not in [ord('\r'), ord('\n'), ord('#')]:
self._suppressNewlines = False
wsCount = 0
for ch in self.text:
if ch == ' ': wsCount += 1
elif ch == '\t': wsCount += 8
if wsCount > self._indents.wsval():
self.emitIndent(len(self.text))
self._indents.push(wsCount)
else:
while wsCount < self._indents.wsval():
self.emitDedent()
self._indents.pop()
if wsCount != self._indents.wsval():
raise Exception()
} -> channel(HIDDEN)
;
COMMENT: '#' ~[\r\n]* -> skip;
OPEN_PAREN: '(' {self._openBRCount += 1};
CLOSE_PAREN: ')' {self._openBRCount -= 1};
OPEN_BRACE: '{' {self._openBRCount += 1};
CLOSE_BRACE: '}' {self._openBRCount -= 1};
OPEN_BRACKET: '[' {self._openBRCount += 1};
CLOSE_BRACKET: ']' {self._openBRCount -= 1};
|
/*
* Taken from official Python 2.7.13 grammar:
* https://docs.python.org/2/reference/grammar.html
*
* Only minor syntactical changes (instances of [X] changed to (X)?, and
* semicolons added to ends of rules), and added lexer rules and whitespace
* handling.
*
* Compiles with ANTLR 4.7, generated lexer/parser for Python 2 target.
*/
grammar Python2;
tokens { INDENT, DEDENT, NEWLINE, ENDMARKER }
@lexer::header {
from Python2Parser import Python2Parser
from antlr4.Token import CommonToken
}
@lexer::members {
# Indented to append code to the constructor.
self._openBRCount = 0
self._suppressNewlines = False
self._lineContinuation = False
self._tokens = self.TokenQueue()
self._indents = self.IndentStack()
class IndentStack:
def __init__(self) : self._s = []
def empty(self) : return len(self._s) == 0
def pop(self) : self._s.pop()
def wsval(self) : return self._s[-1] if len(self._s) > 0 else 0
def push(self, wsval) : self._s.append(wsval)
class TokenQueue:
def __init__(self) : self._q = []
def enq(self, t) : self._q.append(t)
def deq(self) : return self._q.pop(0)
def empty(self) : return len(self._q) == 0
def nextToken(self):
if not self._tokens.empty():
return self._tokens.deq()
else:
t = super(Python2Lexer, self).nextToken()
if t.type != Token.EOF:
return t
else:
self.emitFullDedent()
self.emitEndmarker()
self.emitEndToken(t)
return self._tokens.deq()
def emitEndToken(self, token):
self._tokens.enq(token)
def emitIndent(self, length=0, text='INDENT'):
t = self.createToken(Python2Parser.INDENT, text, length)
self._tokens.enq(t)
def emitDedent(self):
t = self.createToken(Python2Parser.DEDENT, 'DEDENT')
self._tokens.enq(t)
def emitFullDedent(self):
while not self._indents.empty():
self._indents.pop()
self.emitDedent()
def emitEndmarker(self):
t = self.createToken(Python2Parser.ENDMARKER, 'ENDMARKER')
self._tokens.enq(t)
def emitNewline(self):
t = self.createToken(Python2Parser.NEWLINE, 'NEWLINE')
self._tokens.enq(t)
def createToken(self, type_, text="", length=0):
start = self._tokenStartCharIndex
stop = start + length
t = CommonToken(self._tokenFactorySourcePair,
type_, self.DEFAULT_TOKEN_CHANNEL,
start, stop)
t.text = text
return t
}
// Included from official site.
/*
* Grammar for Python
*
* Note: Changing the grammar specified in this file will most likely
* require corresponding changes in the parser module
* (../Modules/parsermodule.c). If you can't make the changes to
* that module yourself, please co-ordinate the required changes
* with someone who can; ask around on python-dev for help. Fred
* Drake <[email protected]> will probably be listening there.
*
* NOTE WELL: You should also follow all the steps listed in PEP 306,
* "How to Change Python's Grammar"
*
* Start symbols for the grammar:
* single_input is a single interactive statement;
* file_input is a module or sequence of commands read from an input file;
* eval_input is the input for the eval() and input() functions.
* NB: compound_stmt in single_input is followed by extra NEWLINE!
*/
single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
;
file_input: (NEWLINE | stmt)* ENDMARKER
;
eval_input: testlist NEWLINE* ENDMARKER
;
decorator: '@' dotted_name ( '(' (arglist)? ')' )? NEWLINE
;
decorators: decorator+
;
decorated: decorators (classdef | funcdef)
;
funcdef: 'def' NAME parameters ':' suite
;
parameters: '(' (varargslist)? ')'
;
varargslist: ((fpdef ('=' test)? ',')*
('*' NAME (',' '**' NAME)? | '**' NAME) |
fpdef ('=' test)? (',' fpdef ('=' test)?)* (',')?)
;
fpdef: NAME | '(' fplist ')'
;
fplist: fpdef (',' fpdef)* (',')?
;
stmt: simple_stmt | compound_stmt
;
simple_stmt: small_stmt (';' small_stmt)* (';')? NEWLINE
;
small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
import_stmt | global_stmt | exec_stmt | assert_stmt)
;
expr_stmt: testlist (augassign (yield_expr|testlist) |
('=' (yield_expr|testlist))*)
;
augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
'<<=' | '>>=' | '**=' | '//=')
// For normal assignments, additional restrictions enforced by the interpreter
;
print_stmt: 'print' ( ( test (',' test)* (',')? )? |
'>>' test ( (',' test)+ (',')? )? )
;
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 (',' test (',' test)?)?)?
;
import_stmt: import_name | import_from
;
import_name: 'import' dotted_as_names
;
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)*
;
exec_stmt: 'exec' expr ('in' test (',' test)?)?
;
assert_stmt: 'assert' test (',' test)?
;
compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated
;
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' | ',') test)?)?
;
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
;
// Backward compatibility cruft to support:
// [ x for x in lambda: True, lambda: False if x() ]
// even while also allowing:
// lambda x: 5 if x else 2
// (But not a mix of the two)
testlist_safe: old_test ((',' old_test)+ (',')?)?
;
old_test: or_test | old_lambdef
;
old_lambdef: 'lambda' (varargslist)? ':' old_test
;
test: or_test ('if' or_test 'else' test)? | lambdef
;
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)*
;
comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
;
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 trailer* ('**' factor)?
;
atom: ('(' (yield_expr|testlist_comp)? ')' |
'[' (listmaker)? ']' |
'{' (dictorsetmaker)? '}' |
'`' testlist1 '`' |
NAME | NUMBER | STRING+)
;
listmaker: test ( list_for | (',' test)* (',')? )
;
testlist_comp: test ( comp_for | (',' test)* (',')? )
;
lambdef: 'lambda' (varargslist)? ':' test
;
trailer: '(' (arglist)? ')' | '[' subscriptlist ']' | '.' NAME
;
subscriptlist: subscript (',' subscript)* (',')?
;
subscript: '.' '.' '.' | test | (test)? ':' (test)? (sliceop)?
;
sliceop: ':' (test)?
;
exprlist: expr (',' expr)* (',')?
;
testlist: test (',' test)* (',')?
;
dictorsetmaker: ( (test ':' test (comp_for | (',' test ':' test)* (',')?)) |
(test (comp_for | (',' test)* (',')?)) )
;
classdef: 'class' NAME ('(' (testlist)? ')')? ':' suite
;
arglist: (argument ',')* (argument (',')?
|'*' test (',' argument)* (',' '**' test)?
|'**' test)
// The reason that keywords are test nodes instead of NAME is that using NAME
// results in an ambiguity. ast.c makes sure it's a NAME.
;
argument: test (comp_for)? | test '=' test
;
list_iter: list_for | list_if
;
list_for: 'for' exprlist 'in' testlist_safe (list_iter)?
;
list_if: 'if' old_test (list_iter)?
;
comp_iter: comp_for | comp_if
;
comp_for: 'for' exprlist 'in' or_test (comp_iter)?
;
comp_if: 'if' old_test (comp_iter)?
;
testlist1: test (',' test)*
;
// not used in grammar, but may appear in "node" passed from Parser to Compiler
encoding_decl: NAME
;
yield_expr: 'yield' (testlist)?
;
/*
* Lexer rules
*/
STRING
: [uUbB]? [rR]?
( '\'' ('\\' (([ \t]+ ('\r'? '\n')?)|.) | ~[\\\r\n'])* '\''
| '"' ('\\' (([ \t]+ ('\r'? '\n')?)|.) | ~[\\\r\n"])* '"'
| '"""' ('\\' . | ~'\\' )*? '"""'
| '\'\'\'' ('\\' . | ~'\\' )*? '\'\'\''
)
;
NAME: [a-zA-Z_] [a-zA-Z0-9_]*
;
NUMBER
: '0' ([xX] [0-9a-fA-F]+
| [oO] [0-7]+
| [bB] [01]+ )[lL]?
| ([0-9]* '.')? [0-9]+ [jJ]? [lL]?
;
LINENDING: (('\r'? '\n')+ {self._lineContinuation=False}
| '\\' [ \t]* ('\r'? '\n') {self._lineContinuation=True})
{
if self._openBRCount == 0 and not self._lineContinuation:
if not self._suppressNewlines:
self.emitNewline()
self._suppressNewlines = True
la = self._input.LA(1)
if la not in [ord(' '), ord('\t'), ord('#')]:
self._suppressNewlines = False
self.emitFullDedent()
} -> channel(HIDDEN)
;
WHITESPACE: ('\t' | ' ')+
{
if (self._tokenStartColumn == 0 and self._openBRCount == 0
and not self._lineContinuation):
la = self._input.LA(1)
if la not in [ord('\r'), ord('\n'), ord('#')]:
self._suppressNewlines = False
wsCount = 0
for ch in self.text:
if ch == ' ': wsCount += 1
elif ch == '\t': wsCount += 8
if wsCount > self._indents.wsval():
self.emitIndent(len(self.text))
self._indents.push(wsCount)
else:
while wsCount < self._indents.wsval():
self.emitDedent()
self._indents.pop()
if wsCount != self._indents.wsval():
raise Exception()
} -> channel(HIDDEN)
;
COMMENT: '#' ~[\r\n]* -> skip;
OPEN_PAREN: '(' {self._openBRCount += 1};
CLOSE_PAREN: ')' {self._openBRCount -= 1};
OPEN_BRACE: '{' {self._openBRCount += 1};
CLOSE_BRACE: '}' {self._openBRCount -= 1};
OPEN_BRACKET: '[' {self._openBRCount += 1};
CLOSE_BRACKET: ']' {self._openBRCount -= 1};
|
Update Python2.g4
|
Update Python2.g4
Added handling for line continuations.. and a temporary fix to the NUMBERS 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
|
07518e5c5d3a43c75e17f0c196be93eab21d6c83
|
antlr/antlr4/ANTLRv4Lexer.g4
|
antlr/antlr4/ANTLRv4Lexer.g4
|
/*
* [The "BSD license"]
* Copyright (c) 2012-2015 Terence Parr
* Copyright (c) 2012-2015 Sam Harwell
* Copyright (c) 2015 Gerald Rosenberg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* A grammar for ANTLR v4 implemented using v4 syntax
*
* Modified 2015.06.16 gbr
* -- update for compatibility with Antlr v4.5
*/
// ======================================================
// Lexer specification
// ======================================================
lexer grammar ANTLRv4Lexer;
options { superClass = LexerAdaptor; }
import LexBasic;
// Standard set of fragments
tokens { TOKEN_REF , RULE_REF , LEXER_CHAR_SET }
channels { OFF_CHANNEL , COMMENT }
// -------------------------
// Comments
DOC_COMMENT
: DocComment -> channel (COMMENT)
;
BLOCK_COMMENT
: BlockComment -> channel (COMMENT)
;
LINE_COMMENT
: LineComment -> channel (COMMENT)
;
// -------------------------
// Integer
INT
: DecimalNumeral
;
// -------------------------
// Literal string
//
// ANTLR makes no distinction between a single character literal and a
// multi-character string. All literals are single quote delimited and
// may contain unicode escape sequences of the form \uxxxx, where x
// is a valid hexadecimal number (per Unicode standard).
STRING_LITERAL
: SQuoteLiteral
;
UNTERMINATED_STRING_LITERAL
: USQuoteLiteral
;
// -------------------------
// Arguments
//
// Certain argument lists, such as those specifying call parameters
// to a rule invocation, or input parameters to a rule specification
// are contained within square brackets.
BEGIN_ARGUMENT
: LBrack
{ this.handleBeginArgument(); }
;
// -------------------------
// Target Language Actions
BEGIN_ACTION
: LBrace -> pushMode (TargetLanguageAction)
;
// -------------------------
// Keywords
//
// 'options', 'tokens', and 'channels' are considered keywords
// but only when followed by '{', and considered as a single token.
// Otherwise, the symbols are tokenized as RULE_REF and allowed as
// an identifier in a labeledElement.
OPTIONS : 'options' WSNLCHARS* '{' ;
TOKENS : 'tokens' WSNLCHARS* '{' ;
CHANNELS : 'channels' WSNLCHARS* '{' ;
fragment WSNLCHARS : ' ' | '\t' | '\f' | '\n' | '\r' ;
IMPORT
: 'import'
;
FRAGMENT
: 'fragment'
;
LEXER
: 'lexer'
;
PARSER
: 'parser'
;
GRAMMAR
: 'grammar'
;
PROTECTED
: 'protected'
;
PUBLIC
: 'public'
;
PRIVATE
: 'private'
;
RETURNS
: 'returns'
;
LOCALS
: 'locals'
;
THROWS
: 'throws'
;
CATCH
: 'catch'
;
FINALLY
: 'finally'
;
MODE
: 'mode'
;
// -------------------------
// Punctuation
COLON
: Colon
;
COLONCOLON
: DColon
;
COMMA
: Comma
;
SEMI
: Semi
;
LPAREN
: LParen
;
RPAREN
: RParen
;
LBRACE
: LBrace
;
RBRACE
: RBrace
;
RARROW
: RArrow
;
LT
: Lt
;
GT
: Gt
;
ASSIGN
: Equal
;
QUESTION
: Question
;
STAR
: Star
;
PLUS_ASSIGN
: PlusAssign
;
PLUS
: Plus
;
OR
: Pipe
;
DOLLAR
: Dollar
;
RANGE
: Range
;
DOT
: Dot
;
AT
: At
;
POUND
: Pound
;
NOT
: Tilde
;
// -------------------------
// Identifiers - allows unicode rule/token names
ID
: Id
;
// -------------------------
// Whitespace
WS
: Ws+ -> channel (OFF_CHANNEL)
;
// -------------------------
// Illegal Characters
//
// This is an illegal character trap which is always the last rule in the
// lexer specification. It matches a single character of any value and being
// the last rule in the file will match when no other rule knows what to do
// about the character. It is reported as an error but is not passed on to the
// parser. This means that the parser to deal with the gramamr file anyway
// but we will not try to analyse or code generate from a file with lexical
// errors.
// Comment this rule out to allow the error to be propagated to the parser
ERRCHAR
: . -> channel (HIDDEN)
;
// ======================================================
// Lexer modes
// -------------------------
// Arguments
mode Argument;
// E.g., [int x, List<String> a[]]
NESTED_ARGUMENT
: LBrack -> type (ARGUMENT_CONTENT) , pushMode (Argument)
;
ARGUMENT_ESCAPE
: EscAny -> type (ARGUMENT_CONTENT)
;
ARGUMENT_STRING_LITERAL
: DQuoteLiteral -> type (ARGUMENT_CONTENT)
;
ARGUMENT_CHAR_LITERAL
: SQuoteLiteral -> type (ARGUMENT_CONTENT)
;
END_ARGUMENT
: RBrack
{ this.handleEndArgument(); }
;
// added this to return non-EOF token type here. EOF does something weird
UNTERMINATED_ARGUMENT
: EOF -> popMode
;
ARGUMENT_CONTENT
: .
;
// -------------------------
// Target Language Actions
//
// Many language targets use {} as block delimiters and so we
// must recursively match {} delimited blocks to balance the
// braces. Additionally, we must make some assumptions about
// literal string representation in the target language. We assume
// that they are delimited by ' or " and so consume these
// in their own alts so as not to inadvertantly match {}.
mode TargetLanguageAction;
NESTED_ACTION
: LBrace -> type (ACTION_CONTENT) , pushMode (TargetLanguageAction)
;
ACTION_ESCAPE
: EscAny -> type (ACTION_CONTENT)
;
ACTION_STRING_LITERAL
: DQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_CHAR_LITERAL
: SQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_DOC_COMMENT
: DocComment -> type (ACTION_CONTENT)
;
ACTION_BLOCK_COMMENT
: BlockComment -> type (ACTION_CONTENT)
;
ACTION_LINE_COMMENT
: LineComment -> type (ACTION_CONTENT)
;
END_ACTION
: RBrace
{ this.handleEndAction(); }
;
UNTERMINATED_ACTION
: EOF -> popMode
;
ACTION_CONTENT
: .
;
// -------------------------
mode LexerCharSet;
LEXER_CHAR_SET_BODY
: (~ [\]\\] | EscAny)+ -> more
;
LEXER_CHAR_SET
: RBrack -> popMode
;
UNTERMINATED_CHAR_SET
: EOF -> popMode
;
// ------------------------------------------------------------------------------
// Grammar specific Keywords, Punctuation, etc.
fragment Id
: NameStartChar NameChar*
;
|
/*
* [The "BSD license"]
* Copyright (c) 2012-2015 Terence Parr
* Copyright (c) 2012-2015 Sam Harwell
* Copyright (c) 2015 Gerald Rosenberg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* A grammar for ANTLR v4 implemented using v4 syntax
*
* Modified 2015.06.16 gbr
* -- update for compatibility with Antlr v4.5
*/
// ======================================================
// Lexer specification
// ======================================================
lexer grammar ANTLRv4Lexer;
options { superClass = LexerAdaptor; }
import LexBasic;
// Standard set of fragments
tokens { TOKEN_REF , RULE_REF , LEXER_CHAR_SET }
channels { OFF_CHANNEL , COMMENT }
// -------------------------
// Comments
DOC_COMMENT
: DocComment -> channel (COMMENT)
;
BLOCK_COMMENT
: BlockComment -> channel (COMMENT)
;
LINE_COMMENT
: LineComment -> channel (COMMENT)
;
// -------------------------
// Integer
INT
: DecimalNumeral
;
// -------------------------
// Literal string
//
// ANTLR makes no distinction between a single character literal and a
// multi-character string. All literals are single quote delimited and
// may contain unicode escape sequences of the form \uxxxx, where x
// is a valid hexadecimal number (per Unicode standard).
STRING_LITERAL
: SQuoteLiteral
;
UNTERMINATED_STRING_LITERAL
: USQuoteLiteral
;
// -------------------------
// Arguments
//
// Certain argument lists, such as those specifying call parameters
// to a rule invocation, or input parameters to a rule specification
// are contained within square brackets.
BEGIN_ARGUMENT
: LBrack
{ this.handleBeginArgument(); }
;
// -------------------------
// Target Language Actions
BEGIN_ACTION
: LBrace -> pushMode (TargetLanguageAction)
;
// -------------------------
// Keywords
//
// 'options', 'tokens', and 'channels' are considered keywords
// but only when followed by '{', and considered as a single token.
// Otherwise, the symbols are tokenized as RULE_REF and allowed as
// an identifier in a labeledElement.
OPTIONS : 'options' WSNLCHARS* '{' ;
TOKENS : 'tokens' WSNLCHARS* '{' ;
CHANNELS : 'channels' WSNLCHARS* '{' ;
fragment WSNLCHARS : ' ' | '\t' | '\f' | '\n' | '\r' ;
IMPORT
: 'import'
;
FRAGMENT
: 'fragment'
;
LEXER
: 'lexer'
;
PARSER
: 'parser'
;
GRAMMAR
: 'grammar'
;
PROTECTED
: 'protected'
;
PUBLIC
: 'public'
;
PRIVATE
: 'private'
;
RETURNS
: 'returns'
;
LOCALS
: 'locals'
;
THROWS
: 'throws'
;
CATCH
: 'catch'
;
FINALLY
: 'finally'
;
MODE
: 'mode'
;
// -------------------------
// Punctuation
COLON
: Colon
;
COLONCOLON
: DColon
;
COMMA
: Comma
;
SEMI
: Semi
;
LPAREN
: LParen
;
RPAREN
: RParen
;
LBRACE
: LBrace
;
RBRACE
: RBrace
;
RARROW
: RArrow
;
LT
: Lt
;
GT
: Gt
;
ASSIGN
: Equal
;
QUESTION
: Question
;
STAR
: Star
;
PLUS_ASSIGN
: PlusAssign
;
PLUS
: Plus
;
OR
: Pipe
;
DOLLAR
: Dollar
;
RANGE
: Range
;
DOT
: Dot
;
AT
: At
;
POUND
: Pound
;
NOT
: Tilde
;
// -------------------------
// Identifiers - allows unicode rule/token names
ID
: Id
;
// -------------------------
// Whitespace
WS
: Ws+ -> channel (OFF_CHANNEL)
;
// -------------------------
// Illegal Characters
//
// This is an illegal character trap which is always the last rule in the
// lexer specification. It matches a single character of any value and being
// the last rule in the file will match when no other rule knows what to do
// about the character. It is reported as an error but is not passed on to the
// parser. This means that the parser to deal with the gramamr file anyway
// but we will not try to analyse or code generate from a file with lexical
// errors.
// Comment this rule out to allow the error to be propagated to the parser
ERRCHAR
: . -> channel (HIDDEN)
;
// ======================================================
// Lexer modes
// -------------------------
// Arguments
mode Argument;
// E.g., [int x, List<String> a[]]
NESTED_ARGUMENT
: LBrack -> type (ARGUMENT_CONTENT) , pushMode (Argument)
;
ARGUMENT_ESCAPE
: EscAny -> type (ARGUMENT_CONTENT)
;
ARGUMENT_STRING_LITERAL
: DQuoteLiteral -> type (ARGUMENT_CONTENT)
;
ARGUMENT_CHAR_LITERAL
: SQuoteLiteral -> type (ARGUMENT_CONTENT)
;
END_ARGUMENT
: RBrack
{ this.handleEndArgument(); }
;
// added this to return non-EOF token type here. EOF does something weird
UNTERMINATED_ARGUMENT
: EOF -> popMode
;
ARGUMENT_CONTENT
: .
;
// TODO: This grammar and the one used in the Intellij Antlr4 plugin differ
// for "actions". This needs to be resolved at some point.
// The Intellij Antlr4 grammar is here:
// https://github.com/antlr/intellij-plugin-v4/blob/1f36fde17f7fa63cb18d7eeb9cb213815ac658fb/src/main/antlr/org/antlr/intellij/plugin/parser/ANTLRv4Lexer.g4#L587
// -------------------------
// Target Language Actions
//
// Many language targets use {} as block delimiters and so we
// must recursively match {} delimited blocks to balance the
// braces. Additionally, we must make some assumptions about
// literal string representation in the target language. We assume
// that they are delimited by ' or " and so consume these
// in their own alts so as not to inadvertantly match {}.
mode TargetLanguageAction;
NESTED_ACTION
: LBrace -> type (ACTION_CONTENT) , pushMode (TargetLanguageAction)
;
ACTION_ESCAPE
: EscAny -> type (ACTION_CONTENT)
;
ACTION_STRING_LITERAL
: DQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_CHAR_LITERAL
: SQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_DOC_COMMENT
: DocComment -> type (ACTION_CONTENT)
;
ACTION_BLOCK_COMMENT
: BlockComment -> type (ACTION_CONTENT)
;
ACTION_LINE_COMMENT
: LineComment -> type (ACTION_CONTENT)
;
END_ACTION
: RBrace
{ this.handleEndAction(); }
;
UNTERMINATED_ACTION
: EOF -> popMode
;
ACTION_CONTENT
: .
;
// -------------------------
mode LexerCharSet;
LEXER_CHAR_SET_BODY
: (~ [\]\\] | EscAny)+ -> more
;
LEXER_CHAR_SET
: RBrack -> popMode
;
UNTERMINATED_CHAR_SET
: EOF -> popMode
;
// ------------------------------------------------------------------------------
// Grammar specific Keywords, Punctuation, etc.
fragment Id
: NameStartChar NameChar*
;
|
Add "TODO".
|
Add "TODO".
|
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
|
35c25ed7873349fecfa994f24947ac7b2b1f31f5
|
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, Literals;
parameterMarker
: QUESTION_
;
literals
: stringLiterals
| numberLiterals
| dateTimeLiterals
| hexadecimalLiterals
| bitValueLiterals
| booleanLiterals
| nullValueLiterals
;
stringLiterals
: characterSetName_? STRING_ collateName_?
;
numberLiterals
: NUMBER_
;
dateTimeLiterals
: (DATE | TIME | TIMESTAMP) STRING_
| LBE_ identifier_ STRING_ RBE_
;
hexadecimalLiterals
: characterSetName_? HEX_DIGIT_ collateName_?
;
bitValueLiterals
: characterSetName_? BIT_NUM_ collateName_?
;
booleanLiterals
: TRUE
| FALSE
;
nullValueLiterals
: NULL
;
characterSetName_
: IDENTIFIER_
;
collateName_
: IDENTIFIER_
;
identifier_
: IDENTIFIER_ | unreservedWord_
;
variable_
: (AT_ AT_)? (GLOBAL | PERSIST | PERSIST_ONLY | SESSION)? DOT_? identifier_
;
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
;
tableName
: (identifier_ DOT_)? identifier_
;
columnName
: (identifier_ DOT_)? identifier_
;
columnNames
: LP_ columnName (COMMA_ columnName)* RP_
;
indexName
: 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
;
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_ | CHARSET 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, Literals;
parameterMarker
: QUESTION_
;
literals
: stringLiterals
| numberLiterals
| dateTimeLiterals
| hexadecimalLiterals
| bitValueLiterals
| booleanLiterals
| nullValueLiterals
;
stringLiterals
: characterSetName_? STRING_ collateName_?
;
numberLiterals
: NUMBER_
;
dateTimeLiterals
: (DATE | TIME | TIMESTAMP) STRING_
| LBE_ identifier_ STRING_ RBE_
;
hexadecimalLiterals
: characterSetName_? HEX_DIGIT_ collateName_?
;
bitValueLiterals
: characterSetName_? BIT_NUM_ collateName_?
;
booleanLiterals
: TRUE | FALSE
;
nullValueLiterals
: NULL
;
characterSetName_
: IDENTIFIER_
;
collateName_
: IDENTIFIER_
;
identifier_
: IDENTIFIER_ | unreservedWord_
;
variable_
: (AT_ AT_)? (GLOBAL | PERSIST | PERSIST_ONLY | SESSION)? DOT_? identifier_
;
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
;
tableName
: (identifier_ DOT_)? identifier_
;
columnName
: (identifier_ DOT_)? identifier_
;
columnNames
: LP_ columnName (COMMA_ columnName)* RP_
;
indexName
: 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
;
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_ | CHARSET EQ_? ignoredIdentifier_
;
collateClause_
: COLLATE EQ_? (STRING_ | ignoredIdentifier_)
;
ignoredIdentifier_
: identifier_ (DOT_ identifier_)?
;
ignoredIdentifiers_
: ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*
;
|
delete newline
|
delete newline
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
ecd2f96d0d54722d4c206b27404704f254393643
|
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_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
: '_'
| [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
;
|
Update grammar.g4
|
Update grammar.g4
|
ANTLR
|
apache-2.0
|
codefacts/watertemplate-engine,tiagobento/watertemplate-engine,tiagobento/watertemplate-engine,codefacts/watertemplate-engine
|
a61c8c7f65b97f69cd7a6b9442dfad6a3ea8bffd
|
watertemplate-engine/grammar.g4
|
watertemplate-engine/grammar.g4
|
prop_name_head
: Upper- or lowercase letter A through Z
;
prop_name_body
: _
| prop_name_head
;
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
: Upper- or lowercase letter A through Z
;
prop_name_body
: '_'
| prop_name_head
;
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
|
codefacts/watertemplate-engine,tiagobento/watertemplate-engine,codefacts/watertemplate-engine,tiagobento/watertemplate-engine
|
d217882226ff6b900ef63fd96a1d2537fcf9c0e5
|
antlr4/ANTLRv4Lexer.PythonTarget.g4
|
antlr4/ANTLRv4Lexer.PythonTarget.g4
|
/*
* [The "BSD license"]
* Copyright (c) 2012-2015 Terence Parr
* Copyright (c) 2012-2015 Sam Harwell
* Copyright (c) 2015 Gerald Rosenberg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* A grammar for ANTLR v4 implemented using v4 syntax
*
* Modified 2015.06.16 gbr
* -- update for compatibility with Antlr v4.5
*/
lexer grammar ANTLRv4Lexer;
options {
superClass = LexerAdaptor ;
}
import LexBasic; // Standard set of fragments
@header {
from LexerAdaptor import LexerAdaptor
}
tokens {
TOKEN_REF,
RULE_REF,
LEXER_CHAR_SET
}
channels {
OFF_CHANNEL // non-default channel for whitespace and comments
}
// ======================================================
// Lexer specification
//
// -------------------------
// Comments
DOC_COMMENT
: DocComment
;
BLOCK_COMMENT
: BlockComment -> channel(OFF_CHANNEL)
;
LINE_COMMENT
: LineComment -> channel(OFF_CHANNEL)
;
// -------------------------
// Integer
//
INT : DecimalNumeral
;
// -------------------------
// Literal string
//
// ANTLR makes no distinction between a single character literal and a
// multi-character string. All literals are single quote delimited and
// may contain unicode escape sequences of the form \uxxxx, where x
// is a valid hexadecimal number (per Unicode standard).
STRING_LITERAL
: SQuoteLiteral
;
UNTERMINATED_STRING_LITERAL
: USQuoteLiteral
;
// -------------------------
// Arguments
//
// Certain argument lists, such as those specifying call parameters
// to a rule invocation, or input parameters to a rule specification
// are contained within square brackets.
BEGIN_ARGUMENT
: LBrack { self.handleBeginArgument() }
;
// -------------------------
// Actions
BEGIN_ACTION
: LBrace -> pushMode(Action)
;
// -------------------------
// Keywords
//
// Keywords may not be used as labels for rules or in any other context where
// they would be ambiguous with the keyword vs some other identifier. OPTIONS,
// TOKENS, & CHANNELS blocks are handled idiomatically in dedicated lexical modes.
OPTIONS : 'options' -> pushMode(Options) ;
TOKENS : 'tokens' -> pushMode(Tokens) ;
CHANNELS : 'channels' -> pushMode(Channels) ;
IMPORT : 'import' ;
FRAGMENT : 'fragment' ;
LEXER : 'lexer' ;
PARSER : 'parser' ;
GRAMMAR : 'grammar' ;
PROTECTED : 'protected' ;
PUBLIC : 'public' ;
PRIVATE : 'private' ;
RETURNS : 'returns' ;
LOCALS : 'locals' ;
THROWS : 'throws' ;
CATCH : 'catch' ;
FINALLY : 'finally' ;
MODE : 'mode' ;
// -------------------------
// Punctuation
COLON : Colon ;
COLONCOLON : DColon ;
COMMA : Comma ;
SEMI : Semi ;
LPAREN : LParen ;
RPAREN : RParen ;
LBRACE : LBrace ;
RBRACE : RBrace ;
RARROW : RArrow ;
LT : Lt ;
GT : Gt ;
ASSIGN : Equal ;
QUESTION : Question ;
STAR : Star ;
PLUS_ASSIGN : PlusAssign ;
PLUS : Plus ;
OR : Pipe ;
DOLLAR : Dollar ;
RANGE : Range ;
DOT : Dot ;
AT : At ;
POUND : Pound ;
NOT : Tilde ;
// -------------------------
// Identifiers - allows unicode rule/token names
ID : Id
;
// -------------------------
// Whitespace
WS : Ws+ -> channel(OFF_CHANNEL) ;
// -------------------------
// Illegal Characters
//
// This is an illegal character trap which is always the last rule in the
// lexer specification. It matches a single character of any value and being
// the last rule in the file will match when no other rule knows what to do
// about the character. It is reported as an error but is not passed on to the
// parser. This means that the parser to deal with the gramamr file anyway
// but we will not try to analyse or code generate from a file with lexical
// errors.
//
// Comment this rule out to allow the error to be propagated to the parser
ERRCHAR
: . -> channel(HIDDEN)
;
// ======================================================
// Lexer modes
// -------------------------
// Arguments
mode Argument; // E.g., [int x, List<String> a[]]
NESTED_ARGUMENT : LBrack -> type(ARGUMENT_CONTENT), pushMode(Argument) ;
ARGUMENT_ESCAPE : EscAny -> type(ARGUMENT_CONTENT) ;
ARGUMENT_STRING_LITERAL : DQuoteLiteral -> type(ARGUMENT_CONTENT) ;
ARGUMENT_CHAR_LITERAL : SQuoteLiteral -> type(ARGUMENT_CONTENT) ;
END_ARGUMENT : RBrack { self.handleEndArgument() } ;
// added this to return non-EOF token type here. EOF does something weird
UNTERMINATED_ARGUMENT : EOF -> popMode ;
ARGUMENT_CONTENT : . ;
// -------------------------
// Actions
//
// Many language targets use {} as block delimiters and so we
// must recursively match {} delimited blocks to balance the
// braces. Additionally, we must make some assumptions about
// literal string representation in the target language. We assume
// that they are delimited by ' or " and so consume these
// in their own alts so as not to inadvertantly match {}.
mode Action;
NESTED_ACTION : LBrace -> type(ACTION_CONTENT), pushMode(Action) ;
ACTION_ESCAPE : EscAny -> type(ACTION_CONTENT) ;
ACTION_STRING_LITERAL : DQuoteLiteral -> type(ACTION_CONTENT) ;
ACTION_CHAR_LITERAL : SQuoteLiteral -> type(ACTION_CONTENT) ;
ACTION_DOC_COMMENT : DocComment -> type(ACTION_CONTENT) ;
ACTION_BLOCK_COMMENT : BlockComment -> type(ACTION_CONTENT) ;
ACTION_LINE_COMMENT : LineComment -> type(ACTION_CONTENT) ;
END_ACTION : RBrace { self.handleEndAction() } ;
UNTERMINATED_ACTION : EOF -> popMode ;
ACTION_CONTENT : . ;
// -------------------------
mode Options;
OPT_DOC_COMMENT : DocComment -> type(DOC_COMMENT), channel(OFF_CHANNEL) ;
OPT_BLOCK_COMMENT : BlockComment -> type(BLOCK_COMMENT), channel(OFF_CHANNEL) ;
OPT_LINE_COMMENT : LineComment -> type(LINE_COMMENT), channel(OFF_CHANNEL) ;
OPT_LBRACE : LBrace -> type(LBRACE) ;
OPT_RBRACE : RBrace -> type(RBRACE), popMode ;
OPT_ID : Id -> type(ID) ;
OPT_DOT : Dot -> type(DOT) ;
OPT_ASSIGN : Equal -> type(ASSIGN) ;
OPT_STRING_LITERAL : SQuoteLiteral -> type(STRING_LITERAL) ;
OPT_INT : Int -> type(INT) ;
OPT_STAR : Star -> type(STAR) ;
OPT_SEMI : Semi -> type(SEMI) ;
OPT_WS : Ws+ -> type(WS), channel(OFF_CHANNEL) ;
// -------------------------
mode Tokens;
TOK_DOC_COMMENT : DocComment -> type(DOC_COMMENT), channel(OFF_CHANNEL) ;
TOK_BLOCK_COMMENT : BlockComment -> type(BLOCK_COMMENT), channel(OFF_CHANNEL) ;
TOK_LINE_COMMENT : LineComment -> type(LINE_COMMENT), channel(OFF_CHANNEL) ;
TOK_LBRACE : LBrace -> type(LBRACE) ;
TOK_RBRACE : RBrace -> type(RBRACE), popMode ;
TOK_ID : Id -> type(ID) ;
TOK_DOT : Dot -> type(DOT) ;
TOK_COMMA : Comma -> type(COMMA) ;
TOK_WS : Ws+ -> type(WS), channel(OFF_CHANNEL) ;
// -------------------------
mode Channels; // currently same as Tokens mode; distinguished by keyword
CHN_DOC_COMMENT : DocComment -> type(DOC_COMMENT), channel(OFF_CHANNEL) ;
CHN_BLOCK_COMMENT : BlockComment -> type(BLOCK_COMMENT), channel(OFF_CHANNEL) ;
CHN_LINE_COMMENT : LineComment -> type(LINE_COMMENT), channel(OFF_CHANNEL) ;
CHN_LBRACE : LBrace -> type(LBRACE) ;
CHN_RBRACE : RBrace -> type(RBRACE), popMode ;
CHN_ID : Id -> type(ID) ;
CHN_DOT : Dot -> type(DOT) ;
CHN_COMMA : Comma -> type(COMMA) ;
CHN_WS : Ws+ -> type(WS), channel(OFF_CHANNEL) ;
// -------------------------
mode LexerCharSet;
LEXER_CHAR_SET_BODY
: ( ~[\]\\]
| EscAny
)+ -> more
;
LEXER_CHAR_SET
: RBrack -> popMode
;
UNTERMINATED_CHAR_SET
: EOF -> popMode
;
// ------------------------------------------------------------------------------
// Grammar specific Keywords, Punctuation, etc.
fragment Id : NameStartChar NameChar* ;
|
/*
* [The "BSD license"]
* Copyright (c) 2012-2015 Terence Parr
* Copyright (c) 2012-2015 Sam Harwell
* Copyright (c) 2015 Gerald Rosenberg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* A grammar for ANTLR v4 implemented using v4 syntax
*
* Modified 2015.06.16 gbr
* -- update for compatibility with Antlr v4.5
*/
lexer grammar ANTLRv4Lexer;
options {
superClass = LexerAdaptor ;
}
import LexBasic; // Standard set of fragments
@header {
from LexerAdaptor import LexerAdaptor
}
tokens {
TOKEN_REF,
RULE_REF,
LEXER_CHAR_SET
}
channels {
OFF_CHANNEL // non-default channel for whitespace and comments
}
// ======================================================
// Lexer specification
//
// -------------------------
// Comments
DOC_COMMENT
: DocComment
;
BLOCK_COMMENT
: BlockComment -> channel(OFF_CHANNEL)
;
LINE_COMMENT
: LineComment -> channel(OFF_CHANNEL)
;
// -------------------------
// Integer
//
INT : DecimalNumeral
;
// -------------------------
// Literal string
//
// ANTLR makes no distinction between a single character literal and a
// multi-character string. All literals are single quote delimited and
// may contain unicode escape sequences of the form \uxxxx, where x
// is a valid hexadecimal number (per Unicode standard).
STRING_LITERAL
: SQuoteLiteral
;
UNTERMINATED_STRING_LITERAL
: USQuoteLiteral
;
// -------------------------
// Arguments
//
// Certain argument lists, such as those specifying call parameters
// to a rule invocation, or input parameters to a rule specification
// are contained within square brackets.
BEGIN_ARGUMENT
: LBrack { self.handleBeginArgument() }
;
// -------------------------
// Actions
BEGIN_ACTION
: LBrace -> pushMode(Action)
;
// -------------------------
// Keywords
//
// Keywords may not be used as labels for rules or in any other context where
// they would be ambiguous with the keyword vs some other identifier. OPTIONS,
// TOKENS, & CHANNELS blocks are handled idiomatically in dedicated lexical modes.
OPTIONS : 'options' -> pushMode(Options) ;
TOKENS : 'tokens' -> pushMode(Tokens) ;
CHANNELS : 'channels' -> pushMode(Channels) ;
IMPORT : 'import' ;
FRAGMENT : 'fragment' ;
LEXER : 'lexer' ;
PARSER : 'parser' ;
GRAMMAR : 'grammar' ;
PROTECTED : 'protected' ;
PUBLIC : 'public' ;
PRIVATE : 'private' ;
RETURNS : 'returns' ;
LOCALS : 'locals' ;
THROWS : 'throws' ;
CATCH : 'catch' ;
FINALLY : 'finally' ;
MODE : 'mode' ;
// -------------------------
// Punctuation
COLON : Colon ;
COLONCOLON : DColon ;
COMMA : Comma ;
SEMI : Semi ;
LPAREN : LParen ;
RPAREN : RParen ;
LBRACE : LBrace ;
RBRACE : RBrace ;
RARROW : RArrow ;
LT : Lt ;
GT : Gt ;
ASSIGN : Equal ;
QUESTION : Question ;
STAR : Star ;
PLUS_ASSIGN : PlusAssign ;
PLUS : Plus ;
OR : Pipe ;
DOLLAR : Dollar ;
RANGE : Range ;
DOT : Dot ;
AT : At ;
POUND : Pound ;
NOT : Tilde ;
// -------------------------
// Identifiers - allows unicode rule/token names
ID : Id
;
// -------------------------
// Whitespace
WS : Ws+ -> channel(OFF_CHANNEL) ;
// -------------------------
// Illegal Characters
//
// This is an illegal character trap which is always the last rule in the
// lexer specification. It matches a single character of any value and being
// the last rule in the file will match when no other rule knows what to do
// about the character. It is reported as an error but is not passed on to the
// parser. This means that the parser to deal with the gramamr file anyway
// but we will not try to analyse or code generate from a file with lexical
// errors.
//
// Comment this rule out to allow the error to be propagated to the parser
ERRCHAR
: . -> channel(HIDDEN)
;
// ======================================================
// Lexer modes
// -------------------------
// Arguments
mode Argument; // E.g., [int x, List<String> a[]]
NESTED_ARGUMENT : LBrack -> type(ARGUMENT_CONTENT), pushMode(Argument) ;
ARGUMENT_ESCAPE : EscAny -> type(ARGUMENT_CONTENT) ;
ARGUMENT_STRING_LITERAL : DQuoteLiteral -> type(ARGUMENT_CONTENT) ;
ARGUMENT_CHAR_LITERAL : SQuoteLiteral -> type(ARGUMENT_CONTENT) ;
END_ARGUMENT : RBrack { self.handleEndArgument() } ;
// added this to return non-EOF token type here. EOF does something weird
UNTERMINATED_ARGUMENT : EOF -> popMode ;
ARGUMENT_CONTENT : . ;
// -------------------------
// Actions
//
// Many language targets use {} as block delimiters and so we
// must recursively match {} delimited blocks to balance the
// braces. Additionally, we must make some assumptions about
// literal string representation in the target language. We assume
// that they are delimited by ' or " and so consume these
// in their own alts so as not to inadvertantly match {}.
mode Action;
NESTED_ACTION : LBrace -> type(ACTION_CONTENT), pushMode(Action) ;
ACTION_ESCAPE : EscAny -> type(ACTION_CONTENT) ;
ACTION_STRING_LITERAL : DQuoteLiteral -> type(ACTION_CONTENT) ;
ACTION_CHAR_LITERAL : SQuoteLiteral -> type(ACTION_CONTENT) ;
ACTION_DOC_COMMENT : DocComment -> type(ACTION_CONTENT) ;
ACTION_BLOCK_COMMENT : BlockComment -> type(ACTION_CONTENT) ;
ACTION_LINE_COMMENT : LineComment -> type(ACTION_CONTENT) ;
END_ACTION : RBrace { self.handleEndAction() } ;
UNTERMINATED_ACTION : EOF -> popMode ;
ACTION_CONTENT : . ;
// -------------------------
mode Options;
OPT_DOC_COMMENT : DocComment -> type(DOC_COMMENT), channel(OFF_CHANNEL) ;
OPT_BLOCK_COMMENT : BlockComment -> type(BLOCK_COMMENT), channel(OFF_CHANNEL) ;
OPT_LINE_COMMENT : LineComment -> type(LINE_COMMENT), channel(OFF_CHANNEL) ;
OPT_LBRACE : LBrace -> type(LBRACE) ;
OPT_RBRACE : RBrace -> type(RBRACE), popMode ;
OPT_ID : Id -> type(ID) ;
OPT_DOT : Dot -> type(DOT) ;
OPT_ASSIGN : Equal -> type(ASSIGN) ;
OPT_STRING_LITERAL : SQuoteLiteral -> type(STRING_LITERAL) ;
OPT_INT : DecimalNumeral -> type(INT) ;
OPT_STAR : Star -> type(STAR) ;
OPT_SEMI : Semi -> type(SEMI) ;
OPT_WS : Ws+ -> type(WS), channel(OFF_CHANNEL) ;
// -------------------------
mode Tokens;
TOK_DOC_COMMENT : DocComment -> type(DOC_COMMENT), channel(OFF_CHANNEL) ;
TOK_BLOCK_COMMENT : BlockComment -> type(BLOCK_COMMENT), channel(OFF_CHANNEL) ;
TOK_LINE_COMMENT : LineComment -> type(LINE_COMMENT), channel(OFF_CHANNEL) ;
TOK_LBRACE : LBrace -> type(LBRACE) ;
TOK_RBRACE : RBrace -> type(RBRACE), popMode ;
TOK_ID : Id -> type(ID) ;
TOK_DOT : Dot -> type(DOT) ;
TOK_COMMA : Comma -> type(COMMA) ;
TOK_WS : Ws+ -> type(WS), channel(OFF_CHANNEL) ;
// -------------------------
mode Channels; // currently same as Tokens mode; distinguished by keyword
CHN_DOC_COMMENT : DocComment -> type(DOC_COMMENT), channel(OFF_CHANNEL) ;
CHN_BLOCK_COMMENT : BlockComment -> type(BLOCK_COMMENT), channel(OFF_CHANNEL) ;
CHN_LINE_COMMENT : LineComment -> type(LINE_COMMENT), channel(OFF_CHANNEL) ;
CHN_LBRACE : LBrace -> type(LBRACE) ;
CHN_RBRACE : RBrace -> type(RBRACE), popMode ;
CHN_ID : Id -> type(ID) ;
CHN_DOT : Dot -> type(DOT) ;
CHN_COMMA : Comma -> type(COMMA) ;
CHN_WS : Ws+ -> type(WS), channel(OFF_CHANNEL) ;
// -------------------------
mode LexerCharSet;
LEXER_CHAR_SET_BODY
: ( ~[\]\\]
| EscAny
)+ -> more
;
LEXER_CHAR_SET
: RBrack -> popMode
;
UNTERMINATED_CHAR_SET
: EOF -> popMode
;
// ------------------------------------------------------------------------------
// Grammar specific Keywords, Punctuation, etc.
fragment Id : NameStartChar NameChar* ;
|
Fix int options parsing in ANTLRv4Lexer.g4
|
Fix int options parsing in ANTLRv4Lexer.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
|
0eb83d9481f9aacbeba910b05ca81b5764b0b581
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE temporaryClause_ TABLE existClause_ tableName (createDefinitionClause_ | createLikeClause_)
;
createIndex
: CREATE (UNIQUE | FULLTEXT | SPATIAL)? INDEX indexName indexType_? ON tableName
;
alterTable
: ALTER TABLE tableName alterSpecifications_?
;
dropTable
: DROP TEMPORARY? TABLE (IF EXISTS)? tableName (COMMA_ tableName)*
;
dropIndex
: DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName
;
truncateTable
: TRUNCATE TABLE? tableName
;
temporaryClause_
: TEMPORARY?
;
existClause_
: (IF NOT EXISTS)?
;
createDefinitionClause_
: LP_ createDefinitions_ RP_
;
createLikeClause_
: LP_? LIKE tableName RP_?
;
createDefinitions_
: createDefinition_ (COMMA_ createDefinition_)*
;
createDefinition_
: columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_
;
columnDefinition
: columnName dataType (inlineDataType_* | generatedDataType_*)
;
indexDefinition_
: (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
constraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_)
;
checkConstraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)?
;
inlineDataType_
: commonDataTypeOption_
| AUTO_INCREMENT
| DEFAULT (literals | 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
;
indexType_
: USING (BTREE | HASH)
;
keyParts_
: LP_ keyPart_ (COMMA_ keyPart_)* RP_
;
keyPart_
: (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)?
;
indexOption_
: KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE
;
primaryKeyOption_
: primaryKey indexType_? columnNames indexOption_*
;
primaryKey
: PRIMARY? KEY
;
uniqueOption_
: UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
foreignKeyOption_
: FOREIGN KEY indexName? columnNames referenceDefinition_
;
alterSpecifications_
: alterSpecification_ (COMMA_ alterSpecification_)*
;
alterSpecification_
: tableOptions_
| addColumnSpecification
| addIndexSpecification
| addConstraintSpecification
| ADD checkConstraintDefinition_
| DROP CHECK ignoredIdentifier_
| ALTER CHECK ignoredIdentifier_ NOT? ENFORCED
| ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY)
| ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT)
| ALTER INDEX indexName (VISIBLE | INVISIBLE)
| changeColumnSpecification
| DEFAULT? characterSet_ collateClause_?
| CONVERT TO characterSet_ collateClause_?
| (DISABLE | ENABLE) KEYS
| (DISCARD | IMPORT_) TABLESPACE
| dropColumnSpecification
| dropIndexSpecification
| dropPrimaryKeySpecification
| DROP FOREIGN KEY ignoredIdentifier_
| FORCE
| LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE)
| modifyColumnSpecification
// TODO hongjun investigate ORDER BY col_name [, col_name] ...
| ORDER BY columnName (COMMA_ columnName)*
| renameColumnSpecification
| renameIndexSpecification
| renameTableSpecification_
| (WITHOUT | WITH) VALIDATION
| ADD PARTITION LP_ partitionDefinition_ RP_
| DROP PARTITION ignoredIdentifiers_
| DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| TRUNCATE PARTITION (ignoredIdentifiers_ | ALL)
| COALESCE PARTITION NUMBER_
| REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_
| EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)?
| ANALYZE PARTITION (ignoredIdentifiers_ | ALL)
| CHECK PARTITION (ignoredIdentifiers_ | ALL)
| OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL)
| REBUILD PARTITION (ignoredIdentifiers_ | ALL)
| REPAIR PARTITION (ignoredIdentifiers_ | ALL)
| REMOVE PARTITIONING
| UPGRADE PARTITIONING
;
tableOptions_
: tableOption_ (COMMA_? tableOption_)*
;
tableOption_
: AUTO_INCREMENT EQ_? NUMBER_
| AVG_ROW_LENGTH EQ_? NUMBER_
| DEFAULT? (characterSet_ | collateClause_)
| CHECKSUM EQ_? NUMBER_
| COMMENT EQ_? STRING_
| COMPRESSION EQ_? STRING_
| CONNECTION EQ_? STRING_
| (DATA | INDEX) DIRECTORY EQ_? STRING_
| DELAY_KEY_WRITE EQ_? NUMBER_
| ENCRYPTION EQ_? STRING_
| ENGINE EQ_? ignoredIdentifier_
| INSERT_METHOD EQ_? (NO | FIRST | LAST)
| KEY_BLOCK_SIZE EQ_? NUMBER_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| PACK_KEYS EQ_? (NUMBER_ | DEFAULT)
| PASSWORD EQ_? STRING_
| ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT)
| STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_)
| STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_)
| STATS_SAMPLE_PAGES EQ_? NUMBER_
| TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))?
| UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_
;
addColumnSpecification
: ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_)
;
firstOrAfterColumn
: FIRST | AFTER columnName
;
addIndexSpecification
: ADD indexDefinition_
;
addConstraintSpecification
: ADD constraintDefinition_
;
changeColumnSpecification
: CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn?
;
dropColumnSpecification
: DROP COLUMN? columnName
;
dropIndexSpecification
: DROP (INDEX | KEY) indexName
;
dropPrimaryKeySpecification
: DROP primaryKey
;
modifyColumnSpecification
: MODIFY COLUMN? columnDefinition firstOrAfterColumn?
;
// TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
// TODO hongjun: should support renameIndexSpecification on mysql
renameIndexSpecification
: RENAME (INDEX | KEY) indexName TO indexName
;
// TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table
renameTableSpecification_
: RENAME (TO | AS)? newTableName
;
newTableName
: identifier_
;
partitionDefinitions_
: LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_
;
partitionDefinition_
: PARTITION identifier_
(VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))?
partitionDefinitionOption_*
(LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)?
;
partitionLessThanValue_
: LP_ (expr | partitionValueList_) RP_ | MAXVALUE
;
partitionValueList_
: literals (COMMA_ literals)*
;
partitionDefinitionOption_
: STORAGE? ENGINE EQ_? identifier_
| COMMENT EQ_? STRING_
| DATA DIRECTORY EQ_? STRING_
| INDEX DIRECTORY EQ_? STRING_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| TABLESPACE EQ_? identifier_
;
subpartitionDefinition_
: SUBPARTITION identifier_ partitionDefinitionOption_*
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE temporaryClause_ TABLE existClause_ tableName (createDefinitionClause_ | createLikeClause_)
;
createIndex
: CREATE (UNIQUE | FULLTEXT | SPATIAL)? INDEX indexName indexType_? ON tableName
;
alterTable
: ALTER TABLE tableName alterSpecifications_?
;
dropTable
: DROP TEMPORARY? TABLE (IF EXISTS)? tableName (COMMA_ tableName)*
;
dropIndex
: DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName
;
truncateTable
: TRUNCATE TABLE? tableName
;
temporaryClause_
: TEMPORARY?
;
existClause_
: (IF NOT EXISTS)?
;
createDefinitionClause_
: LP_ createDefinitions_ RP_
;
createLikeClause_
: LP_? LIKE tableName RP_?
;
createDefinitions_
: createDefinition_ (COMMA_ createDefinition_)*
;
createDefinition_
: columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_
;
columnDefinition
: columnName dataType (inlineDataType_* | generatedDataType_*)
;
indexDefinition_
: (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
constraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_)
;
checkConstraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)?
;
inlineDataType_
: commonDataTypeOption_
| NOT? NULL
| AUTO_INCREMENT
| DEFAULT (literals | expr)
| COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT)
| STORAGE (DISK | MEMORY | DEFAULT)
;
generatedDataType_
: commonDataTypeOption_
| (GENERATED ALWAYS)? AS expr
| (VIRTUAL | STORED)
;
commonDataTypeOption_
: primaryKey | UNIQUE KEY? | 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
;
indexType_
: USING (BTREE | HASH)
;
keyParts_
: LP_ keyPart_ (COMMA_ keyPart_)* RP_
;
keyPart_
: (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)?
;
indexOption_
: KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE
;
primaryKeyOption_
: primaryKey indexType_? columnNames indexOption_*
;
primaryKey
: PRIMARY? KEY
;
uniqueOption_
: UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
foreignKeyOption_
: FOREIGN KEY indexName? columnNames referenceDefinition_
;
alterSpecifications_
: alterSpecification_ (COMMA_ alterSpecification_)*
;
alterSpecification_
: tableOptions_
| addColumnSpecification
| addIndexSpecification
| addConstraintSpecification
| ADD checkConstraintDefinition_
| DROP CHECK ignoredIdentifier_
| ALTER CHECK ignoredIdentifier_ NOT? ENFORCED
| ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY)
| ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT)
| ALTER INDEX indexName (VISIBLE | INVISIBLE)
| changeColumnSpecification
| DEFAULT? characterSet_ collateClause_?
| CONVERT TO characterSet_ collateClause_?
| (DISABLE | ENABLE) KEYS
| (DISCARD | IMPORT_) TABLESPACE
| dropColumnSpecification
| dropIndexSpecification
| dropPrimaryKeySpecification
| DROP FOREIGN KEY ignoredIdentifier_
| FORCE
| LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE)
| modifyColumnSpecification
// TODO hongjun investigate ORDER BY col_name [, col_name] ...
| ORDER BY columnName (COMMA_ columnName)*
| renameColumnSpecification
| renameIndexSpecification
| renameTableSpecification_
| (WITHOUT | WITH) VALIDATION
| ADD PARTITION LP_ partitionDefinition_ RP_
| DROP PARTITION ignoredIdentifiers_
| DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| TRUNCATE PARTITION (ignoredIdentifiers_ | ALL)
| COALESCE PARTITION NUMBER_
| REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_
| EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)?
| ANALYZE PARTITION (ignoredIdentifiers_ | ALL)
| CHECK PARTITION (ignoredIdentifiers_ | ALL)
| OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL)
| REBUILD PARTITION (ignoredIdentifiers_ | ALL)
| REPAIR PARTITION (ignoredIdentifiers_ | ALL)
| REMOVE PARTITIONING
| UPGRADE PARTITIONING
;
tableOptions_
: tableOption_ (COMMA_? tableOption_)*
;
tableOption_
: AUTO_INCREMENT EQ_? NUMBER_
| AVG_ROW_LENGTH EQ_? NUMBER_
| DEFAULT? (characterSet_ | collateClause_)
| CHECKSUM EQ_? NUMBER_
| COMMENT EQ_? STRING_
| COMPRESSION EQ_? STRING_
| CONNECTION EQ_? STRING_
| (DATA | INDEX) DIRECTORY EQ_? STRING_
| DELAY_KEY_WRITE EQ_? NUMBER_
| ENCRYPTION EQ_? STRING_
| ENGINE EQ_? ignoredIdentifier_
| INSERT_METHOD EQ_? (NO | FIRST | LAST)
| KEY_BLOCK_SIZE EQ_? NUMBER_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| PACK_KEYS EQ_? (NUMBER_ | DEFAULT)
| PASSWORD EQ_? STRING_
| ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT)
| STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_)
| STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_)
| STATS_SAMPLE_PAGES EQ_? NUMBER_
| TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))?
| UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_
;
addColumnSpecification
: ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_)
;
firstOrAfterColumn
: FIRST | AFTER columnName
;
addIndexSpecification
: ADD indexDefinition_
;
addConstraintSpecification
: ADD constraintDefinition_
;
changeColumnSpecification
: CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn?
;
dropColumnSpecification
: DROP COLUMN? columnName
;
dropIndexSpecification
: DROP (INDEX | KEY) indexName
;
dropPrimaryKeySpecification
: DROP primaryKey
;
modifyColumnSpecification
: MODIFY COLUMN? columnDefinition firstOrAfterColumn?
;
// TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
// TODO hongjun: should support renameIndexSpecification on mysql
renameIndexSpecification
: RENAME (INDEX | KEY) indexName TO indexName
;
// TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table
renameTableSpecification_
: RENAME (TO | AS)? newTableName
;
newTableName
: identifier_
;
partitionDefinitions_
: LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_
;
partitionDefinition_
: PARTITION identifier_
(VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))?
partitionDefinitionOption_*
(LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)?
;
partitionLessThanValue_
: LP_ (expr | partitionValueList_) RP_ | MAXVALUE
;
partitionValueList_
: literals (COMMA_ literals)*
;
partitionDefinitionOption_
: STORAGE? ENGINE EQ_? identifier_
| COMMENT EQ_? STRING_
| DATA DIRECTORY EQ_? STRING_
| INDEX DIRECTORY EQ_? STRING_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| TABLESPACE EQ_? identifier_
;
subpartitionDefinition_
: SUBPARTITION identifier_ partitionDefinitionOption_*
;
|
modify commonDataTypeOption_
|
modify commonDataTypeOption_
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
|
646900c83c6f7ae600f8cd1342a6067082074c9e
|
sharding-core/sharding-core-parse/sharding-core-parse-sqlserver/src/main/antlr4/imports/sqlserver/DDLStatement.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-sqlserver/src/main/antlr4/imports/sqlserver/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 TABLE tableName fileTableClause_ createDefinitionClause_
;
createIndex
: CREATE createIndexSpecification_ INDEX indexName ON tableName columnNames
;
alterTable
: alterTableOp
(
alterColumn
| addColumnSpecification
| alterDrop
| alterCheckConstraint
| alterTrigger
| alterSwitch
| alterSet
| alterTableTableOption
| REBUILD
)
;
alterIndex
: ALTER INDEX (indexName | ALL) ON tableName
;
dropTable
: DROP TABLE (IF EXISTS)? tableName (COMMA_ tableName)*
;
dropIndex
: DROP INDEX (IF EXISTS)? indexName ON tableName
;
truncateTable
: TRUNCATE TABLE tableName
;
fileTableClause_
: (AS FILETABLE)?
;
createDefinitionClause_
: createTableDefinitions_ partitionScheme_ fileGroup_
;
createTableDefinitions_
: LP_ createTableDefinition_ (COMMA_ createTableDefinition_)* (COMMA_ periodClause)? RP_
;
createTableDefinition_
: columnDefinition | computedColumnDefinition | columnSetDefinition | tableConstraint | tableIndex
;
columnDefinition
: columnName dataType columnDefinitionOption* columnConstraints columnIndex?
;
columnDefinitionOption
: FILESTREAM
| COLLATE collationName
| SPARSE
| MASKED WITH LP_ FUNCTION EQ_ STRING_ RP_
| (CONSTRAINT ignoredIdentifier_)? DEFAULT expr
| IDENTITY (LP_ NUMBER_ COMMA_ NUMBER_ RP_)?
| NOT FOR REPLICATION
| GENERATED ALWAYS AS ROW (START | END) HIDDEN_?
| NOT? NULL
| ROWGUIDCOL
| ENCRYPTED WITH LP_ COLUMN_ENCRYPTION_KEY EQ_ ignoredIdentifier_ COMMA_ ENCRYPTION_TYPE EQ_ (DETERMINISTIC | RANDOMIZED) COMMA_ ALGORITHM EQ_ STRING_ RP_
| columnConstraint (COMMA_ columnConstraint)*
| columnIndex
;
columnConstraint
: (CONSTRAINT ignoredIdentifier_)? (primaryKeyConstraint | columnForeignKeyConstraint | checkConstraint)
;
primaryKeyConstraint
: (primaryKey | UNIQUE) (diskTablePrimaryKeyConstraintOption | memoryTablePrimaryKeyConstraintOption)
;
diskTablePrimaryKeyConstraintOption
: (CLUSTERED | NONCLUSTERED)? primaryKeyWithClause? primaryKeyOnClause?
;
primaryKeyWithClause
: WITH (FILLFACTOR EQ_ NUMBER_ | LP_ indexOption (COMMA_ indexOption)* RP_)
;
primaryKeyOnClause
: onSchemaColumn | onFileGroup | onString
;
onSchemaColumn
: ON schemaName LP_ columnName RP_
;
onFileGroup
: ON ignoredIdentifier_
;
onString
: ON STRING_
;
memoryTablePrimaryKeyConstraintOption
: CLUSTERED withBucket?
;
withBucket
: WITH LP_ BUCKET_COUNT EQ_ NUMBER_ RP_
;
columnForeignKeyConstraint
: (FOREIGN KEY)? REFERENCES tableName LP_ columnName RP_ foreignKeyOnAction*
;
foreignKeyOnAction
: ON (DELETE | UPDATE) foreignKeyOn | NOT FOR REPLICATION
;
foreignKeyOn
: NO ACTION | CASCADE | SET (NULL | DEFAULT)
;
checkConstraint
: CHECK(NOT FOR REPLICATION)? LP_ expr RP_
;
columnIndex
: INDEX indexName (CLUSTERED | NONCLUSTERED)? (WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause? (FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))?
;
indexOnClause
: onSchemaColumn | onFileGroup | onDefault
;
onDefault
: ON DEFAULT
;
columnConstraints
: (columnConstraint(COMMA_ columnConstraint)*)?
;
computedColumnDefinition
: columnName AS expr (PERSISTED(NOT NULL)?)? columnConstraint?
;
columnSetDefinition
: ignoredIdentifier_ IDENTIFIER_ COLUMN_SET FOR ALL_SPARSE_COLUMNS
;
tableConstraint
: (CONSTRAINT ignoredIdentifier_)? (tablePrimaryConstraint | tableForeignKeyConstraint | checkConstraint)
;
tablePrimaryConstraint
: primaryKeyUnique (diskTablePrimaryConstraintOption | memoryTablePrimaryConstraintOption)
;
primaryKeyUnique
: primaryKey | UNIQUE
;
diskTablePrimaryConstraintOption
: (CLUSTERED | NONCLUSTERED)? columnNames primaryKeyWithClause? primaryKeyOnClause?
;
memoryTablePrimaryConstraintOption
: NONCLUSTERED (columnNames | hashWithBucket)
;
hashWithBucket
: HASH columnNames withBucket
;
tableForeignKeyConstraint
: (FOREIGN KEY)? columnNames REFERENCES tableName columnNames foreignKeyOnAction*
;
tableIndex
: INDEX indexName
((CLUSTERED | NONCLUSTERED)? columnNames
| CLUSTERED COLUMNSTORE
| NONCLUSTERED? (COLUMNSTORE columnNames | hashWithBucket)
| CLUSTERED COLUMNSTORE (WITH LP_ COMPRESSION_DELAY EQ_ (NUMBER_ MINUTES?) RP_)?)
(WHERE expr)?
(WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause?
(FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))?
;
createIndexSpecification_
: UNIQUE? (CLUSTERED | NONCLUSTERED)?
;
tableOption
: DATA_COMPRESSION EQ_ (NONE | ROW | PAGE) (ON PARTITIONS LP_ partitionExpressions RP_)?
| FILETABLE_DIRECTORY EQ_ ignoredIdentifier_
| FILETABLE_COLLATE_FILENAME EQ_ (collationName | DATABASE_DEAULT)
| FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME EQ_ ignoredIdentifier_
| FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME EQ_ ignoredIdentifier_
| FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME EQ_ ignoredIdentifier_
| SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?
| REMOTE_DATA_ARCHIVE EQ_ (ON (LP_ tableStretchOptions (COMMA_ tableStretchOptions)* RP_)? | OFF LP_ MIGRATION_STATE EQ_ PAUSED RP_)
| tableOptOption
| distributionOption
| dataWareHouseTableOption
;
tableOptOption
: (MEMORY_OPTIMIZED EQ_ ON) | (DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA)) | (SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?)
;
distributionOption
: DISTRIBUTION EQ_ (HASH LP_ columnName RP_ | ROUND_ROBIN | REPLICATE)
;
dataWareHouseTableOption
: CLUSTERED COLUMNSTORE INDEX | HEAP | dataWareHousePartitionOption
;
dataWareHousePartitionOption
: (PARTITION LP_ columnName RANGE (LEFT | RIGHT)? FOR VALUES LP_ simpleExpr (COMMA_ simpleExpr)* RP_ RP_)
;
tableStretchOptions
: (FILTER_PREDICATE EQ_ (NULL | functionCall) COMMA_)? MIGRATION_STATE EQ_ (OUTBOUND | INBOUND | PAUSED)
;
partitionScheme_
: (ON (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_))?
;
fileGroup_
: (TEXTIMAGE_ON (ignoredIdentifier_ | STRING_))? ((FILESTREAM_ON (schemaName) | ignoredIdentifier_ STRING_))? (WITH LP_ tableOption (COMMA_ tableOption)* RP_)?
;
periodClause
: PERIOD FOR SYSTEM_TIME LP_ columnName COMMA_ columnName RP_
;
alterTableOp
: ALTER TABLE tableName
;
alterColumn
: modifyColumnSpecification
;
modifyColumnSpecification
: alterColumnOp dataType (COLLATE collationName)? (NULL | NOT NULL)? SPARSE?
;
alterColumnOp
: ALTER COLUMN columnName
;
addColumnSpecification
: (WITH (CHECK | NOCHECK))? ADD (alterColumnAddOption (COMMA_ alterColumnAddOption)* | (columnNameGeneratedClause COMMA_ periodClause| periodClause COMMA_ columnNameGeneratedClause))
;
alterColumnAddOption
: columnDefinition
| computedColumnDefinition
| columnSetDefinition
| tableConstraint
| alterTableTableIndex
| constraintForColumn
;
constraintForColumn
: (CONSTRAINT ignoredIdentifier_)? DEFAULT simpleExpr FOR columnName
;
columnNameWithSortsWithParen
: LP_ columnNameWithSort (COMMA_ columnNameWithSort)* RP_
;
columnNameWithSort
: columnName (ASC | DESC)?
;
columnNameGeneratedClause
: columnNameGenerated DEFAULT simpleExpr (WITH VALUES)? COMMA_ columnNameGenerated
;
columnNameGenerated
: columnName dataTypeName_ GENERATED ALWAYS AS ROW (START | END)? HIDDEN_? (NOT NULL)? (CONSTRAINT ignoredIdentifier_)?
;
alterDrop
: DROP
(
alterTableDropConstraint
| dropColumnSpecification
| dropIndexSpecification
| PERIOD FOR SYSTEM_TIME
)
;
alterTableDropConstraint
: CONSTRAINT? (IF EXISTS)? dropConstraintName (COMMA_ dropConstraintName)*
;
dropConstraintName
: ignoredIdentifier_ dropConstraintWithClause?
;
dropConstraintWithClause
: WITH LP_ dropConstraintOption (COMMA_ dropConstraintOption)* RP_
;
dropConstraintOption
: (MAXDOP EQ_ NUMBER_ | ONLINE EQ_ (ON | OFF) | MOVE TO (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_))
;
dropColumnSpecification
: COLUMN (IF EXISTS)? columnName (COMMA_ columnName)*
;
dropIndexSpecification
: INDEX (IF EXISTS)? indexName (COMMA_ indexName)*
;
alterCheckConstraint
: WITH? (CHECK | NOCHECK) CONSTRAINT (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*))
;
alterTrigger
: (ENABLE| DISABLE) TRIGGER (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*))
;
alterSwitch
: SWITCH (PARTITION expr)? TO tableName (PARTITION expr)? (WITH LP_ lowPriorityLockWait RP_)?
;
alterSet
: SET LP_ (setFileStreamClause | setSystemVersionClause) RP_
;
setFileStreamClause
: FILESTREAM_ON EQ_ (schemaName | ignoredIdentifier_ | STRING_)
;
setSystemVersionClause
: SYSTEM_VERSIONING EQ_ (OFF | alterSetOnClause)
;
alterSetOnClause
: ON
(
LP_ (HISTORY_TABLE EQ_ tableName)?
(COMMA_? DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))?
(COMMA_? HISTORY_RETENTION_PERIOD EQ_ (INFINITE | (NUMBER_ (DAY | DAYS | WEEK | WEEKS | MONTH | MONTHS | YEAR | YEARS))))?
RP_
)?
;
alterTableTableIndex
: indexWithName (indexNonClusterClause | indexClusterClause)
;
indexWithName
: INDEX indexName
;
indexNonClusterClause
: NONCLUSTERED (hashWithBucket | (columnNameWithSortsWithParen alterTableIndexOnClause?))
;
alterTableIndexOnClause
: ON ignoredIdentifier_ | DEFAULT
;
indexClusterClause
: CLUSTERED COLUMNSTORE (WITH COMPRESSION_DELAY EQ_ NUMBER_ MINUTES?)? indexOnClause?
;
alterTableTableOption
: SET LP_ LOCK_ESCALATION EQ_ (AUTO | TABLE | DISABLE) RP_
| MEMORY_OPTIMIZED EQ_ ON
| DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA)
| SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?
;
|
/*
* 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 TABLE tableName fileTableClause_ createDefinitionClause_
;
createIndex
: CREATE createIndexSpecification_ INDEX indexName ON tableName columnNames
;
alterTable
: ALTER TABLE tableName alterClause_
;
alterIndex
: ALTER INDEX (indexName | ALL) ON tableName
;
dropTable
: DROP TABLE (IF EXISTS)? tableName (COMMA_ tableName)*
;
dropIndex
: DROP INDEX (IF EXISTS)? indexName ON tableName
;
truncateTable
: TRUNCATE TABLE tableName
;
fileTableClause_
: (AS FILETABLE)?
;
createDefinitionClause_
: createTableDefinitions_ partitionScheme_ fileGroup_
;
createTableDefinitions_
: LP_ createTableDefinition_ (COMMA_ createTableDefinition_)* (COMMA_ periodClause)? RP_
;
createTableDefinition_
: columnDefinition | computedColumnDefinition | columnSetDefinition | tableConstraint | tableIndex
;
columnDefinition
: columnName dataType columnDefinitionOption* columnConstraints columnIndex?
;
columnDefinitionOption
: FILESTREAM
| COLLATE collationName
| SPARSE
| MASKED WITH LP_ FUNCTION EQ_ STRING_ RP_
| (CONSTRAINT ignoredIdentifier_)? DEFAULT expr
| IDENTITY (LP_ NUMBER_ COMMA_ NUMBER_ RP_)?
| NOT FOR REPLICATION
| GENERATED ALWAYS AS ROW (START | END) HIDDEN_?
| NOT? NULL
| ROWGUIDCOL
| ENCRYPTED WITH LP_ COLUMN_ENCRYPTION_KEY EQ_ ignoredIdentifier_ COMMA_ ENCRYPTION_TYPE EQ_ (DETERMINISTIC | RANDOMIZED) COMMA_ ALGORITHM EQ_ STRING_ RP_
| columnConstraint (COMMA_ columnConstraint)*
| columnIndex
;
columnConstraint
: (CONSTRAINT ignoredIdentifier_)? (primaryKeyConstraint | columnForeignKeyConstraint | checkConstraint)
;
primaryKeyConstraint
: (primaryKey | UNIQUE) (diskTablePrimaryKeyConstraintOption | memoryTablePrimaryKeyConstraintOption)
;
diskTablePrimaryKeyConstraintOption
: (CLUSTERED | NONCLUSTERED)? primaryKeyWithClause? primaryKeyOnClause?
;
primaryKeyWithClause
: WITH (FILLFACTOR EQ_ NUMBER_ | LP_ indexOption (COMMA_ indexOption)* RP_)
;
primaryKeyOnClause
: onSchemaColumn | onFileGroup | onString
;
onSchemaColumn
: ON schemaName LP_ columnName RP_
;
onFileGroup
: ON ignoredIdentifier_
;
onString
: ON STRING_
;
memoryTablePrimaryKeyConstraintOption
: CLUSTERED withBucket?
;
withBucket
: WITH LP_ BUCKET_COUNT EQ_ NUMBER_ RP_
;
columnForeignKeyConstraint
: (FOREIGN KEY)? REFERENCES tableName LP_ columnName RP_ foreignKeyOnAction*
;
foreignKeyOnAction
: ON (DELETE | UPDATE) foreignKeyOn | NOT FOR REPLICATION
;
foreignKeyOn
: NO ACTION | CASCADE | SET (NULL | DEFAULT)
;
checkConstraint
: CHECK(NOT FOR REPLICATION)? LP_ expr RP_
;
columnIndex
: INDEX indexName (CLUSTERED | NONCLUSTERED)? (WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause? (FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))?
;
indexOnClause
: onSchemaColumn | onFileGroup | onDefault
;
onDefault
: ON DEFAULT
;
columnConstraints
: (columnConstraint(COMMA_ columnConstraint)*)?
;
computedColumnDefinition
: columnName AS expr (PERSISTED(NOT NULL)?)? columnConstraint?
;
columnSetDefinition
: ignoredIdentifier_ IDENTIFIER_ COLUMN_SET FOR ALL_SPARSE_COLUMNS
;
tableConstraint
: (CONSTRAINT ignoredIdentifier_)? (tablePrimaryConstraint | tableForeignKeyConstraint | checkConstraint)
;
tablePrimaryConstraint
: primaryKeyUnique (diskTablePrimaryConstraintOption | memoryTablePrimaryConstraintOption)
;
primaryKeyUnique
: primaryKey | UNIQUE
;
diskTablePrimaryConstraintOption
: (CLUSTERED | NONCLUSTERED)? columnNames primaryKeyWithClause? primaryKeyOnClause?
;
memoryTablePrimaryConstraintOption
: NONCLUSTERED (columnNames | hashWithBucket)
;
hashWithBucket
: HASH columnNames withBucket
;
tableForeignKeyConstraint
: (FOREIGN KEY)? columnNames REFERENCES tableName columnNames foreignKeyOnAction*
;
tableIndex
: INDEX indexName
((CLUSTERED | NONCLUSTERED)? columnNames
| CLUSTERED COLUMNSTORE
| NONCLUSTERED? (COLUMNSTORE columnNames | hashWithBucket)
| CLUSTERED COLUMNSTORE (WITH LP_ COMPRESSION_DELAY EQ_ (NUMBER_ MINUTES?) RP_)?)
(WHERE expr)?
(WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause?
(FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))?
;
createIndexSpecification_
: UNIQUE? (CLUSTERED | NONCLUSTERED)?
;
alterClause_
: alterColumn | addColumnSpecification | alterDrop | alterCheckConstraint | alterTrigger | alterSwitch | alterSet | alterTableTableOption | REBUILD
;
tableOption
: DATA_COMPRESSION EQ_ (NONE | ROW | PAGE) (ON PARTITIONS LP_ partitionExpressions RP_)?
| FILETABLE_DIRECTORY EQ_ ignoredIdentifier_
| FILETABLE_COLLATE_FILENAME EQ_ (collationName | DATABASE_DEAULT)
| FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME EQ_ ignoredIdentifier_
| FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME EQ_ ignoredIdentifier_
| FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME EQ_ ignoredIdentifier_
| SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?
| REMOTE_DATA_ARCHIVE EQ_ (ON (LP_ tableStretchOptions (COMMA_ tableStretchOptions)* RP_)? | OFF LP_ MIGRATION_STATE EQ_ PAUSED RP_)
| tableOptOption
| distributionOption
| dataWareHouseTableOption
;
tableOptOption
: (MEMORY_OPTIMIZED EQ_ ON) | (DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA)) | (SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?)
;
distributionOption
: DISTRIBUTION EQ_ (HASH LP_ columnName RP_ | ROUND_ROBIN | REPLICATE)
;
dataWareHouseTableOption
: CLUSTERED COLUMNSTORE INDEX | HEAP | dataWareHousePartitionOption
;
dataWareHousePartitionOption
: (PARTITION LP_ columnName RANGE (LEFT | RIGHT)? FOR VALUES LP_ simpleExpr (COMMA_ simpleExpr)* RP_ RP_)
;
tableStretchOptions
: (FILTER_PREDICATE EQ_ (NULL | functionCall) COMMA_)? MIGRATION_STATE EQ_ (OUTBOUND | INBOUND | PAUSED)
;
partitionScheme_
: (ON (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_))?
;
fileGroup_
: (TEXTIMAGE_ON (ignoredIdentifier_ | STRING_))? ((FILESTREAM_ON (schemaName) | ignoredIdentifier_ STRING_))? (WITH LP_ tableOption (COMMA_ tableOption)* RP_)?
;
periodClause
: PERIOD FOR SYSTEM_TIME LP_ columnName COMMA_ columnName RP_
;
alterColumn
: modifyColumnSpecification
;
modifyColumnSpecification
: alterColumnOperation dataType (COLLATE collationName)? (NULL | NOT NULL)? SPARSE?
;
alterColumnOperation
: ALTER COLUMN columnName
;
addColumnSpecification
: (WITH (CHECK | NOCHECK))? ADD (alterColumnAddOption (COMMA_ alterColumnAddOption)* | (columnNameGeneratedClause COMMA_ periodClause| periodClause COMMA_ columnNameGeneratedClause))
;
alterColumnAddOption
: columnDefinition
| computedColumnDefinition
| columnSetDefinition
| tableConstraint
| alterTableTableIndex
| constraintForColumn
;
constraintForColumn
: (CONSTRAINT ignoredIdentifier_)? DEFAULT simpleExpr FOR columnName
;
columnNameWithSortsWithParen
: LP_ columnNameWithSort (COMMA_ columnNameWithSort)* RP_
;
columnNameWithSort
: columnName (ASC | DESC)?
;
columnNameGeneratedClause
: columnNameGenerated DEFAULT simpleExpr (WITH VALUES)? COMMA_ columnNameGenerated
;
columnNameGenerated
: columnName dataTypeName_ GENERATED ALWAYS AS ROW (START | END)? HIDDEN_? (NOT NULL)? (CONSTRAINT ignoredIdentifier_)?
;
alterDrop
: DROP
(
alterTableDropConstraint
| dropColumnSpecification
| dropIndexSpecification
| PERIOD FOR SYSTEM_TIME
)
;
alterTableDropConstraint
: CONSTRAINT? (IF EXISTS)? dropConstraintName (COMMA_ dropConstraintName)*
;
dropConstraintName
: ignoredIdentifier_ dropConstraintWithClause?
;
dropConstraintWithClause
: WITH LP_ dropConstraintOption (COMMA_ dropConstraintOption)* RP_
;
dropConstraintOption
: (MAXDOP EQ_ NUMBER_ | ONLINE EQ_ (ON | OFF) | MOVE TO (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_))
;
dropColumnSpecification
: COLUMN (IF EXISTS)? columnName (COMMA_ columnName)*
;
dropIndexSpecification
: INDEX (IF EXISTS)? indexName (COMMA_ indexName)*
;
alterCheckConstraint
: WITH? (CHECK | NOCHECK) CONSTRAINT (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*))
;
alterTrigger
: (ENABLE| DISABLE) TRIGGER (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*))
;
alterSwitch
: SWITCH (PARTITION expr)? TO tableName (PARTITION expr)? (WITH LP_ lowPriorityLockWait RP_)?
;
alterSet
: SET LP_ (setFileStreamClause | setSystemVersionClause) RP_
;
setFileStreamClause
: FILESTREAM_ON EQ_ (schemaName | ignoredIdentifier_ | STRING_)
;
setSystemVersionClause
: SYSTEM_VERSIONING EQ_ (OFF | alterSetOnClause)
;
alterSetOnClause
: ON
(
LP_ (HISTORY_TABLE EQ_ tableName)?
(COMMA_? DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))?
(COMMA_? HISTORY_RETENTION_PERIOD EQ_ (INFINITE | (NUMBER_ (DAY | DAYS | WEEK | WEEKS | MONTH | MONTHS | YEAR | YEARS))))?
RP_
)?
;
alterTableTableIndex
: indexWithName (indexNonClusterClause | indexClusterClause)
;
indexWithName
: INDEX indexName
;
indexNonClusterClause
: NONCLUSTERED (hashWithBucket | (columnNameWithSortsWithParen alterTableIndexOnClause?))
;
alterTableIndexOnClause
: ON ignoredIdentifier_ | DEFAULT
;
indexClusterClause
: CLUSTERED COLUMNSTORE (WITH COMPRESSION_DELAY EQ_ NUMBER_ MINUTES?)? indexOnClause?
;
alterTableTableOption
: SET LP_ LOCK_ESCALATION EQ_ (AUTO | TABLE | DISABLE) RP_
| MEMORY_OPTIMIZED EQ_ ON
| DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA)
| SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?
;
|
modify alterTable rule
|
modify alterTable rule
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
|
1b96bf6e5f77cde915d9f7625e5b3e0abdfc61a3
|
rexx/RexxParser.g4
|
rexx/RexxParser.g4
|
parser grammar RexxParser;
options { tokenVocab=RexxLexer; }
file : program_ EOF ;
program_ : ncl? instruction_list? ;
ncl : null_clause+ ;
null_clause : delim+ label_list?
| label_list
| include_statement
;
delim : SEMICOL
| EOL
;
label_list : ( label COLON delim* )+ ;
label : VAR_SYMBOL
| CONST_SYMBOL
| NUMBER
;
include_statement : STMT_INCLUDE ;
instruction_list : instruction+ ;
instruction : group_
| single_instruction ncl?
;
single_instruction : assignment
| keyword_instruction
| command_
;
assignment : ( VAR_SYMBOL | SPECIAL_VAR | CONST_SYMBOL ) EQ expression ;
keyword_instruction : address_
| arg_
| call_
| drop_
| exit_
| interpret_
| iterate_
| leave_
| nop_
| numeric_
| options_
| parse_
| procedure_
| pull_
| push_
| queue_
| return_
| say_
| signal_
| trace_
| upper_
;
command_ : expression ;
group_ : do_
| if_
| select_
;
do_ : KWD_DO do_rep? do_cond? ncl
instruction_list?
KWD_END var_symbol? ncl? ;
do_rep : assignment do_cnt?
| KWD_FOREVER
| expression
;
do_cnt : dot dob? dof?
| dot dof? dob?
| dob dot? dof?
| dob dof? dot?
| dof dot? dob?
| dof dob? dot?
;
dot : KWD_TO expression ;
dob : KWD_BY expression ;
dof : KWD_FOR expression ;
do_cond : KWD_WHILE expression
| KWD_UNTIL expression
;
if_ : KWD_IF expression delim* then_ (delim+ else_)? ;
then_ : KWD_THEN ncl? instruction ;
else_ : KWD_ELSE ncl? instruction ;
select_ : KWD_SELECT delim+ select_body KWD_END ncl? ;
select_body : when_+ otherwise_? ;
when_ : KWD_WHEN expression delim* then_ ;
otherwise_ : KWD_OTHERWISE delim* instruction_list? ;
/*
Note: The next part concentrates on the instructions.
It leaves unspecified the various forms of symbol, template and expression. */
address_ : KWD_ADDRESS
( taken_constant expression? | valueexp )?
;
taken_constant : symbol
| STRING
;
valueexp : KWD_VALUE expression ;
arg_ : KWD_ARG template_list? ;
call_ : KWD_CALL ( callon_spec | function_name call_parms? ) ;
callon_spec : KWD_ON callable_condition ( KWD_NAME function_name )?
| KWD_OFF callable_condition
;
callable_condition : KWD_ERROR
| KWD_FAILURE
| KWD_HALT
;
call_parms : BR_O expression_list? BR_C
| expression_list
;
expression_list : COMMA* expression
( COMMA+ expression )* ;
drop_ : KWD_DROP variable_list ;
variable_list : ( vref | var_symbol )+ ;
vref : BR_O var_symbol BR_C ;
var_symbol : VAR_SYMBOL
| SPECIAL_VAR
;
exit_ : KWD_EXIT expression? ;
interpret_ : KWD_INTERPRET expression ;
iterate_ : KWD_ITERATE var_symbol? ;
leave_ : KWD_LEAVE var_symbol? ;
nop_ : KWD_NOP ;
numeric_ : KWD_NUMERIC ( numeric_digits | numeric_form | numeric_fuzz ) ;
numeric_digits : KWD_DIGITS expression? ;
numeric_form : KWD_FORM
( KWD_ENGINEERING
| KWD_SCIENTIFIC
| valueexp
| expression
)?
;
numeric_fuzz : KWD_FUZZ expression? ;
options_ : KWD_OPTIONS expression ;
parse_ : KWD_PARSE KWD_UPPER? parse_type template_list? ;
parse_type : parse_key
| parse_value
| parse_var
;
parse_key : KWD_ARG
| KWD_EXTERNAL
| KWD_NUMERIC
| KWD_PULL
| KWD_SOURCE
| KWD_VERSION
;
parse_value : KWD_VALUE expression? KWD_WITH ;
parse_var : KWD_VAR var_symbol ;
procedure_ : KWD_PROCEDURE ( KWD_EXPOSE variable_list )? ;
pull_ : KWD_PULL template_list? ;
push_ : KWD_PUSH expression? ;
queue_ : KWD_QUEUE expression? ;
return_ : KWD_RETURN expression? ;
say_ : KWD_SAY expression? ;
signal_ : KWD_SIGNAL ( signal_spec | valueexp | taken_constant ) ;
signal_spec : KWD_ON condition ( KWD_NAME function_name )?
| KWD_OFF condition
;
condition : callable_condition
| KWD_NOVALUE
| KWD_SYNTAX
;
trace_ : KWD_TRACE
( taken_constant
| valueexp
| expression
| KWD_ERROR
| KWD_FAILURE
| KWD_OFF
)
;
upper_ : KWD_UPPER var_symbol+ ; // if stem -> error (cannot do 'upper j.')
/* Note: The next section describes templates. */
template_list : COMMA* template_ ( COMMA+ template_ )* ;
template_ : ( trigger_ | target_ )+ ;
target_ : VAR_SYMBOL
| SPECIAL_VAR
| STOP
;
trigger_ : pattern_
| positional_
;
pattern_ : STRING
| vref
;
positional_ : absolute_positional
| relative_positional
;
absolute_positional : NUMBER
| EQ position_
;
position_ : NUMBER
| vref
;
relative_positional : (PLUS | MINUS) position_ ;
// Note: The final part specifies the various forms of symbol, and expression.
symbol : var_symbol
| CONST_SYMBOL
| NUMBER
;
expression : and_expression
( or_operator and_expression )* ;
or_operator : OR
| XOR
;
and_expression : comparison ( AND comparison )* ;
comparison : concatenation ( comparison_operator concatenation )* ;
comparison_operator : normal_compare
| strict_compare
;
normal_compare : EQ
| CMP_NEq
| CMP_LM
| CMP_ML
| CMP_M
| CMP_L
| CMP_MEq
| CMP_LEq
| CMP_NM
| CMP_NL
;
strict_compare : CMPS_Eq
| CMPS_Neq
| CMPS_M
| CMPS_L
| CMPS_MEq
| CMPS_LEq
| CMPS_NM
| CMPS_NL
;
concatenation : addition ( CONCAT? addition )* ;
addition : multiplication ( additive_operator multiplication )* ;
additive_operator : PLUS
| MINUS
;
multiplication : power_expression ( multiplicative_operator power_expression )* ;
multiplicative_operator : MUL
| DIV
| QUOTINENT
| REMAINDER
;
power_expression : prefix_expression ( POW prefix_expression )* ;
prefix_expression : ( PLUS | MINUS | NOT )* term ;
term : function_
| BR_O expression BR_C
| symbol
| STRING
;
function_ : function_name function_parameters ;
function_name : KWD_ADDRESS
| KWD_ARG
| KWD_DIGITS
| KWD_FORM
| KWD_FUZZ
| KWD_TRACE
| KWD_VALUE
| taken_constant
;
function_parameters : BR_O expression_list? BR_C ;
|
parser grammar RexxParser;
options { tokenVocab=RexxLexer; }
file : program_ EOF ;
program_ : ncl? instruction_list? ;
ncl : null_clause+ ;
null_clause : delim+ label_list?
| label_list
| include_statement
;
delim : SEMICOL
| EOL
;
label_list : ( label COLON delim* )+ ;
label : VAR_SYMBOL
| CONST_SYMBOL
| NUMBER
;
include_statement : STMT_INCLUDE ;
instruction_list : instruction+ ;
instruction : group_
| single_instruction ncl?
;
single_instruction : assignment
| keyword_instruction
| command_
;
assignment : ( VAR_SYMBOL | SPECIAL_VAR | CONST_SYMBOL ) EQ expression? ;
keyword_instruction : address_
| arg_
| call_
| drop_
| exit_
| interpret_
| iterate_
| leave_
| nop_
| numeric_
| options_
| parse_
| procedure_
| pull_
| push_
| queue_
| return_
| say_
| signal_
| trace_
| upper_
;
command_ : expression ;
group_ : do_
| if_
| select_
;
do_ : KWD_DO do_rep? do_cond? ncl
instruction_list?
KWD_END var_symbol? ncl? ;
do_rep : assignment do_cnt?
| KWD_FOREVER
| expression
;
do_cnt : dot dob? dof?
| dot dof? dob?
| dob dot? dof?
| dob dof? dot?
| dof dot? dob?
| dof dob? dot?
;
dot : KWD_TO expression ;
dob : KWD_BY expression ;
dof : KWD_FOR expression ;
do_cond : KWD_WHILE expression
| KWD_UNTIL expression
;
if_ : KWD_IF expression delim* then_ (delim+ else_)? ;
then_ : KWD_THEN ncl? instruction ;
else_ : KWD_ELSE ncl? instruction ;
select_ : KWD_SELECT delim+ select_body KWD_END ncl? ;
select_body : when_+ otherwise_? ;
when_ : KWD_WHEN expression delim* then_ ;
otherwise_ : KWD_OTHERWISE delim* instruction_list? ;
/*
Note: The next part concentrates on the instructions.
It leaves unspecified the various forms of symbol, template and expression. */
address_ : KWD_ADDRESS
( taken_constant expression? | valueexp )?
;
taken_constant : symbol
| STRING
;
valueexp : KWD_VALUE expression ;
arg_ : KWD_ARG template_list? ;
call_ : KWD_CALL ( callon_spec | function_name call_parms? ) ;
callon_spec : KWD_ON callable_condition ( KWD_NAME function_name )?
| KWD_OFF callable_condition
;
callable_condition : KWD_ERROR
| KWD_FAILURE
| KWD_HALT
;
call_parms : BR_O expression_list? BR_C
| expression_list
;
expression_list : COMMA* expression
( COMMA+ expression )* ;
drop_ : KWD_DROP variable_list ;
variable_list : ( vref | var_symbol )+ ;
vref : BR_O var_symbol BR_C ;
var_symbol : VAR_SYMBOL
| SPECIAL_VAR
;
exit_ : KWD_EXIT expression? ;
interpret_ : KWD_INTERPRET expression ;
iterate_ : KWD_ITERATE var_symbol? ;
leave_ : KWD_LEAVE var_symbol? ;
nop_ : KWD_NOP ;
numeric_ : KWD_NUMERIC ( numeric_digits | numeric_form | numeric_fuzz ) ;
numeric_digits : KWD_DIGITS expression? ;
numeric_form : KWD_FORM
( KWD_ENGINEERING
| KWD_SCIENTIFIC
| valueexp
| expression
)?
;
numeric_fuzz : KWD_FUZZ expression? ;
options_ : KWD_OPTIONS expression ;
parse_ : KWD_PARSE KWD_UPPER? parse_type template_list? ;
parse_type : parse_key
| parse_value
| parse_var
;
parse_key : KWD_ARG
| KWD_EXTERNAL
| KWD_NUMERIC
| KWD_PULL
| KWD_SOURCE
| KWD_VERSION
;
parse_value : KWD_VALUE expression? KWD_WITH ;
parse_var : KWD_VAR var_symbol ;
procedure_ : KWD_PROCEDURE ( KWD_EXPOSE variable_list )? ;
pull_ : KWD_PULL template_list? ;
push_ : KWD_PUSH expression? ;
queue_ : KWD_QUEUE expression? ;
return_ : KWD_RETURN expression? ;
say_ : KWD_SAY expression? ;
signal_ : KWD_SIGNAL ( signal_spec | valueexp | taken_constant ) ;
signal_spec : KWD_ON condition ( KWD_NAME function_name )?
| KWD_OFF condition
;
condition : callable_condition
| KWD_NOVALUE
| KWD_SYNTAX
;
trace_ : KWD_TRACE
( taken_constant
| valueexp
| expression
| KWD_ERROR
| KWD_FAILURE
| KWD_OFF
)
;
upper_ : KWD_UPPER var_symbol+ ; // if stem -> error (cannot do 'upper j.')
/* Note: The next section describes templates. */
template_list : COMMA* template_ ( COMMA+ template_ )* ;
template_ : ( trigger_ | target_ )+ ;
target_ : VAR_SYMBOL
| SPECIAL_VAR
| STOP
;
trigger_ : pattern_
| positional_
;
pattern_ : STRING
| vref
;
positional_ : absolute_positional
| relative_positional
;
absolute_positional : NUMBER
| EQ position_
;
position_ : NUMBER
| vref
;
relative_positional : (PLUS | MINUS) position_ ;
// Note: The final part specifies the various forms of symbol, and expression.
symbol : var_symbol
| CONST_SYMBOL
| NUMBER
;
expression : and_expression
( or_operator and_expression )* ;
or_operator : OR
| XOR
;
and_expression : comparison ( AND comparison )* ;
comparison : concatenation ( comparison_operator concatenation )* ;
comparison_operator : normal_compare
| strict_compare
;
normal_compare : EQ
| CMP_NEq
| CMP_LM
| CMP_ML
| CMP_M
| CMP_L
| CMP_MEq
| CMP_LEq
| CMP_NM
| CMP_NL
;
strict_compare : CMPS_Eq
| CMPS_Neq
| CMPS_M
| CMPS_L
| CMPS_MEq
| CMPS_LEq
| CMPS_NM
| CMPS_NL
;
concatenation : addition ( CONCAT? addition )* ;
addition : multiplication ( additive_operator multiplication )* ;
additive_operator : PLUS
| MINUS
;
multiplication : power_expression ( multiplicative_operator power_expression )* ;
multiplicative_operator : MUL
| DIV
| QUOTINENT
| REMAINDER
;
power_expression : prefix_expression ( POW prefix_expression )* ;
prefix_expression : ( PLUS | MINUS | NOT )* term ;
term : function_
| BR_O expression BR_C
| symbol
| STRING
;
function_ : function_name function_parameters ;
function_name : KWD_ADDRESS
| KWD_ARG
| KWD_DIGITS
| KWD_FORM
| KWD_FUZZ
| KWD_TRACE
| KWD_VALUE
| taken_constant
;
function_parameters : BR_O expression_list? BR_C ;
|
Support optional assignment expression
|
Support optional assignment expression
|
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
|
b369f9f8edc525113eb66d8c9f867609790254ef
|
toml/toml.g4
|
toml/toml.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 toml;
/*
* Parser Rules
*/
document : expression (NL expression)* ;
expression : key_value comment | table comment | comment ;
comment: COMMENT? ;
key_value : key '=' value ;
key : simple_key | dotted_key ;
simple_key : quoted_key | unquoted_key ;
unquoted_key : UNQUOTED_KEY ;
quoted_key : BASIC_STRING | LITERAL_STRING ;
dotted_key : simple_key ('.' simple_key)+ ;
value : string | integer | floating_point | bool_ | date_time | array_ | inline_table ;
string : BASIC_STRING | ML_BASIC_STRING | LITERAL_STRING | ML_LITERAL_STRING ;
integer : DEC_INT | HEX_INT | OCT_INT | BIN_INT ;
floating_point : FLOAT | INF | NAN ;
bool_ : BOOLEAN ;
date_time : OFFSET_DATE_TIME | LOCAL_DATE_TIME | LOCAL_DATE | LOCAL_TIME ;
array_ : '[' array_values? comment_or_nl ']' ;
array_values : (comment_or_nl value ',' array_values comment_or_nl) | comment_or_nl value ','? ;
comment_or_nl : (COMMENT? NL)* ;
table : standard_table | array_table ;
standard_table : '[' key ']' ;
inline_table : '{' inline_table_keyvals '}' ;
inline_table_keyvals : inline_table_keyvals_non_empty? ;
inline_table_keyvals_non_empty : key '=' value (',' inline_table_keyvals_non_empty)? ;
array_table : '[[' key ']]' ;
/*
* Lexer Rules
*/
WS : [ \t]+ -> skip ;
NL : ('\r'? '\n')+ ;
COMMENT : '#' (~[\n])* ;
fragment DIGIT : [0-9] ;
fragment ALPHA : [A-Za-z] ;
// booleans
BOOLEAN : 'true' | 'false' ;
// strings
fragment ESC : '\\' (["\\/bfnrt] | UNICODE | EX_UNICODE) ;
fragment ML_ESC : '\\' '\r'? '\n' | ESC ;
fragment UNICODE : 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ;
fragment EX_UNICODE : 'U' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ;
BASIC_STRING : '"' (ESC | ~["\\\n])*? '"' ;
ML_BASIC_STRING : '"""' (ML_ESC | ~["\\])*? '"""' ;
LITERAL_STRING : '\'' (~['\n])*? '\'' ;
ML_LITERAL_STRING : '\'\'\'' (.)*? '\'\'\'';
// floating point numbers
fragment EXP : ('e' | 'E') DEC_INT ;
fragment ZERO_PREFIXABLE_INT : DIGIT (DIGIT | '_' DIGIT)* ;
fragment FRAC : '.' ZERO_PREFIXABLE_INT ;
FLOAT : DEC_INT ( EXP | FRAC EXP?) ;
INF : [+-]? 'inf' ;
NAN : [+-]? 'nan' ;
// integers
fragment HEX_DIGIT : [A-Fa-f] | DIGIT ;
fragment DIGIT_1_9 : [1-9] ;
fragment DIGIT_0_7 : [0-7] ;
fragment DIGIT_0_1 : [0-1] ;
DEC_INT : [+-]? (DIGIT | (DIGIT_1_9 (DIGIT | '_' DIGIT)+)) ;
HEX_INT : '0x' HEX_DIGIT (HEX_DIGIT | '_' HEX_DIGIT)* ;
OCT_INT : '0o' DIGIT_0_7 (DIGIT_0_7 | '_' DIGIT_0_7) ;
BIN_INT : '0b' DIGIT_0_1 (DIGIT_0_1 | '_' DIGIT_0_1)* ;
// dates
fragment YEAR : DIGIT DIGIT DIGIT DIGIT ;
fragment MONTH : DIGIT DIGIT ;
fragment DAY : DIGIT DIGIT ;
fragment DELIM : 'T' | 't' ;
fragment HOUR : DIGIT DIGIT ;
fragment MINUTE : DIGIT DIGIT ;
fragment SECOND : DIGIT DIGIT ;
fragment SECFRAC : '.' DIGIT+ ;
fragment NUMOFFSET : ('+' | '-') HOUR ':' MINUTE ;
fragment OFFSET : 'Z' | NUMOFFSET ;
fragment PARTIAL_TIME : HOUR ':' MINUTE ':' SECOND SECFRAC? ;
fragment FULL_DATE : YEAR '-' MONTH '-' DAY ;
fragment FULL_TIME : PARTIAL_TIME OFFSET ;
OFFSET_DATE_TIME : FULL_DATE DELIM FULL_TIME ;
LOCAL_DATE_TIME : FULL_DATE DELIM PARTIAL_TIME ;
LOCAL_DATE : FULL_DATE ;
LOCAL_TIME : PARTIAL_TIME ;
// keys
UNQUOTED_KEY : (ALPHA | DIGIT | '-' | '_')+ ;
|
/*
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 toml;
/*
* Parser Rules
*/
document : expression (NL expression)* ;
expression : key_value comment | table comment | comment ;
comment: COMMENT? ;
key_value : key '=' value ;
key : simple_key | dotted_key ;
simple_key : quoted_key | unquoted_key ;
unquoted_key : UNQUOTED_KEY ;
quoted_key : BASIC_STRING | LITERAL_STRING ;
dotted_key : simple_key ('.' simple_key)+ ;
value : string | integer | floating_point | bool_ | date_time | array_ | inline_table ;
string : BASIC_STRING | ML_BASIC_STRING | LITERAL_STRING | ML_LITERAL_STRING ;
integer : DEC_INT | HEX_INT | OCT_INT | BIN_INT ;
floating_point : FLOAT | INF | NAN ;
bool_ : BOOLEAN ;
date_time : OFFSET_DATE_TIME | LOCAL_DATE_TIME | LOCAL_DATE | LOCAL_TIME ;
array_ : '[' array_values? comment_or_nl ']' ;
array_values : (comment_or_nl value ',' array_values comment_or_nl) | comment_or_nl value ','? ;
comment_or_nl : (COMMENT? NL)* ;
table : standard_table | array_table ;
standard_table : '[' key ']' ;
inline_table : '{' inline_table_keyvals '}' ;
inline_table_keyvals : inline_table_keyvals_non_empty? ;
inline_table_keyvals_non_empty : key '=' value (',' inline_table_keyvals_non_empty)? ;
array_table : '[[' key ']]' ;
/*
* Lexer Rules
*/
WS : [ \t]+ -> skip ;
NL : ('\r'? '\n')+ ;
COMMENT : '#' (~[\n])* ;
fragment DIGIT : [0-9] ;
fragment ALPHA : [A-Za-z] ;
// booleans
BOOLEAN : 'true' | 'false' ;
// strings
fragment ESC : '\\' (["\\/bfnrt] | UNICODE | EX_UNICODE) ;
fragment ML_ESC : '\\' '\r'? '\n' | ESC ;
fragment UNICODE : 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ;
fragment EX_UNICODE : 'U' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ;
BASIC_STRING : '"' (ESC | ~["\\\n])*? '"' ;
ML_BASIC_STRING : '"""' (ML_ESC | ~["\\])*? '"""' ;
LITERAL_STRING : '\'' (~['\n])*? '\'' ;
ML_LITERAL_STRING : '\'\'\'' (.)*? '\'\'\'';
// floating point numbers
fragment EXP : ('e' | 'E') [+-]? ZERO_PREFIXABLE_INT ;
fragment ZERO_PREFIXABLE_INT : DIGIT (DIGIT | '_' DIGIT)* ;
fragment FRAC : '.' ZERO_PREFIXABLE_INT ;
FLOAT : DEC_INT ( EXP | FRAC EXP?) ;
INF : [+-]? 'inf' ;
NAN : [+-]? 'nan' ;
// integers
fragment HEX_DIGIT : [A-Fa-f] | DIGIT ;
fragment DIGIT_1_9 : [1-9] ;
fragment DIGIT_0_7 : [0-7] ;
fragment DIGIT_0_1 : [0-1] ;
DEC_INT : [+-]? (DIGIT | (DIGIT_1_9 (DIGIT | '_' DIGIT)+)) ;
HEX_INT : '0x' HEX_DIGIT (HEX_DIGIT | '_' HEX_DIGIT)* ;
OCT_INT : '0o' DIGIT_0_7 (DIGIT_0_7 | '_' DIGIT_0_7) ;
BIN_INT : '0b' DIGIT_0_1 (DIGIT_0_1 | '_' DIGIT_0_1)* ;
// dates
fragment YEAR : DIGIT DIGIT DIGIT DIGIT ;
fragment MONTH : DIGIT DIGIT ;
fragment DAY : DIGIT DIGIT ;
fragment DELIM : 'T' | 't' ;
fragment HOUR : DIGIT DIGIT ;
fragment MINUTE : DIGIT DIGIT ;
fragment SECOND : DIGIT DIGIT ;
fragment SECFRAC : '.' DIGIT+ ;
fragment NUMOFFSET : ('+' | '-') HOUR ':' MINUTE ;
fragment OFFSET : 'Z' | NUMOFFSET ;
fragment PARTIAL_TIME : HOUR ':' MINUTE ':' SECOND SECFRAC? ;
fragment FULL_DATE : YEAR '-' MONTH '-' DAY ;
fragment FULL_TIME : PARTIAL_TIME OFFSET ;
OFFSET_DATE_TIME : FULL_DATE DELIM FULL_TIME ;
LOCAL_DATE_TIME : FULL_DATE DELIM PARTIAL_TIME ;
LOCAL_DATE : FULL_DATE ;
LOCAL_TIME : PARTIAL_TIME ;
// keys
UNQUOTED_KEY : (ALPHA | DIGIT | '-' | '_')+ ;
|
allow leading zeroes in float exponent
|
[TOML] allow leading zeroes in float exponent
|
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
|
9931f78ad75b4d0fbbba65c77d5981edb01b7f44
|
java/JavaLexer.g4
|
java/JavaLexer.g4
|
/*
[The "BSD licence"]
Copyright (c) 2013 Terence Parr, Sam Harwell
Copyright (c) 2017 Ivan Kochurkin (upgrade to Java 8)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
lexer grammar JavaLexer;
// Keywords
ABSTRACT: 'abstract';
ASSERT: 'assert';
BOOLEAN: 'boolean';
BREAK: 'break';
BYTE: 'byte';
CASE: 'case';
CATCH: 'catch';
CHAR: 'char';
CLASS: 'class';
CONST: 'const';
CONTINUE: 'continue';
DEFAULT: 'default';
DO: 'do';
DOUBLE: 'double';
ELSE: 'else';
ENUM: 'enum';
EXTENDS: 'extends';
FINAL: 'final';
FINALLY: 'finally';
FLOAT: 'float';
FOR: 'for';
IF: 'if';
GOTO: 'goto';
IMPLEMENTS: 'implements';
IMPORT: 'import';
INSTANCEOF: 'instanceof';
INT: 'int';
INTERFACE: 'interface';
LONG: 'long';
NATIVE: 'native';
NEW: 'new';
PACKAGE: 'package';
PRIVATE: 'private';
PROTECTED: 'protected';
PUBLIC: 'public';
RETURN: 'return';
SHORT: 'short';
STATIC: 'static';
STRICTFP: 'strictfp';
SUPER: 'super';
SWITCH: 'switch';
SYNCHRONIZED: 'synchronized';
THIS: 'this';
THROW: 'throw';
THROWS: 'throws';
TRANSIENT: 'transient';
TRY: 'try';
VOID: 'void';
VOLATILE: 'volatile';
WHILE: 'while';
// Literals
DECIMAL_LITERAL: ('0' | [1-9] (Digits? | '_'+ Digits)) [lL]?;
HEX_LITERAL: '0' [xX] [0-9a-fA-F] ([0-9a-fA-F_]* [0-9a-fA-F])? [lL]?;
OCT_LITERAL: '0' '_'* [0-7] ([0-7_]* [0-7])? [lL]?;
BINARY_LITERAL: '0' [bB] [01] ([01_]* [01])? [lL]?;
FLOAT_LITERAL: (Digits '.' Digits? | '.' Digits) ExponentPart? [fFdD]?
| Digits (ExponentPart [fFdD]? | [fFdD])
;
HEX_FLOAT_LITERAL: '0' [xX] (HexDigits '.'? | HexDigits? '.' HexDigits) [pP] [+-]? Digits [fFdD]?;
BOOL_LITERAL: 'true'
| 'false'
;
CHAR_LITERAL: '\'' (~['\\\r\n] | EscapeSequence) '\'';
STRING_LITERAL: '"' (~["\\\r\n] | EscapeSequence)* '"';
NULL_LITERAL: 'null';
// Separators
LPAREN: '(';
RPAREN: ')';
LBRACE: '{';
RBRACE: '}';
LBRACK: '[';
RBRACK: ']';
SEMI: ';';
COMMA: ',';
DOT: '.';
// Operators
ASSIGN: '=';
GT: '>';
LT: '<';
BANG: '!';
TILDE: '~';
QUESTION: '?';
COLON: ':';
EQUAL: '==';
LE: '<=';
GE: '>=';
NOTEQUAL: '!=';
AND: '&&';
OR: '||';
INC: '++';
DEC: '--';
ADD: '+';
SUB: '-';
MUL: '*';
DIV: '/';
BITAND: '&';
BITOR: '|';
CARET: '^';
MOD: '%';
ADD_ASSIGN: '+=';
SUB_ASSIGN: '-=';
MUL_ASSIGN: '*=';
DIV_ASSIGN: '/=';
AND_ASSIGN: '&=';
OR_ASSIGN: '|=';
XOR_ASSIGN: '^=';
MOD_ASSIGN: '%=';
LSHIFT_ASSIGN: '<<=';
RSHIFT_ASSIGN: '>>=';
URSHIFT_ASSIGN: '>>>=';
// Java 8 tokens
ARROW: '->';
COLONCOLON: '::';
// Additional symbols not defined in the lexical specification
AT: '@';
ELLIPSIS: '...';
// Whitespace and comments
WS: [ \t\r\n\u000C]+ -> channel(HIDDEN);
COMMENT: '/*' .*? '*/' -> channel(HIDDEN);
LINE_COMMENT: '//' ~[\r\n]* -> channel(HIDDEN);
// Identifiers
IDENTIFIER: Letter LetterOrDigit*;
// Fragment rules
fragment ExponentPart
: [eE] [+-]? Digits
;
fragment EscapeSequence
: '\\' [btnfr"'\\]
| '\\' ([0-3]? [0-7])? [0-7]
| '\\' 'u' HexDigit HexDigit HexDigit HexDigit
;
fragment HexDigits
: HexDigit ((HexDigit | '_')* HexDigit)?
;
fragment HexDigit
: [0-9a-fA-F]
;
fragment Digits
: [0-9] ([0-9_]* [0-9])?
;
fragment LetterOrDigit
: Letter
| [0-9]
;
fragment Letter
: [a-zA-Z$_] // these are the "java letters" below 0x7F
| ~[\u0000-\u007F\uD800-\uDBFF] // covers all characters above 0x7F which are not a surrogate
| [\uD800-\uDBFF] [\uDC00-\uDFFF] // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF
;
|
/*
[The "BSD licence"]
Copyright (c) 2013 Terence Parr, Sam Harwell
Copyright (c) 2017 Ivan Kochurkin (upgrade to Java 8)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
lexer grammar JavaLexer;
// Keywords
ABSTRACT: 'abstract';
ASSERT: 'assert';
BOOLEAN: 'boolean';
BREAK: 'break';
BYTE: 'byte';
CASE: 'case';
CATCH: 'catch';
CHAR: 'char';
CLASS: 'class';
CONST: 'const';
CONTINUE: 'continue';
DEFAULT: 'default';
DO: 'do';
DOUBLE: 'double';
ELSE: 'else';
ENUM: 'enum';
EXTENDS: 'extends';
FINAL: 'final';
FINALLY: 'finally';
FLOAT: 'float';
FOR: 'for';
IF: 'if';
GOTO: 'goto';
IMPLEMENTS: 'implements';
IMPORT: 'import';
INSTANCEOF: 'instanceof';
INT: 'int';
INTERFACE: 'interface';
LONG: 'long';
NATIVE: 'native';
NEW: 'new';
PACKAGE: 'package';
PRIVATE: 'private';
PROTECTED: 'protected';
PUBLIC: 'public';
RETURN: 'return';
SHORT: 'short';
STATIC: 'static';
STRICTFP: 'strictfp';
SUPER: 'super';
SWITCH: 'switch';
SYNCHRONIZED: 'synchronized';
THIS: 'this';
THROW: 'throw';
THROWS: 'throws';
TRANSIENT: 'transient';
TRY: 'try';
VOID: 'void';
VOLATILE: 'volatile';
WHILE: 'while';
// Literals
DECIMAL_LITERAL: ('0' | [1-9] (Digits? | '_'+ Digits)) [lL]?;
HEX_LITERAL: '0' [xX] [0-9a-fA-F] ([0-9a-fA-F_]* [0-9a-fA-F])? [lL]?;
OCT_LITERAL: '0' '_'* [0-7] ([0-7_]* [0-7])? [lL]?;
BINARY_LITERAL: '0' [bB] [01] ([01_]* [01])? [lL]?;
FLOAT_LITERAL: (Digits '.' Digits? | '.' Digits) ExponentPart? [fFdD]?
| Digits (ExponentPart [fFdD]? | [fFdD])
;
HEX_FLOAT_LITERAL: '0' [xX] (HexDigits '.'? | HexDigits? '.' HexDigits) [pP] [+-]? Digits [fFdD]?;
BOOL_LITERAL: 'true'
| 'false'
;
CHAR_LITERAL: '\'' (~['\\\r\n] | EscapeSequence) '\'';
STRING_LITERAL: '"' (~["\\\r\n] | EscapeSequence)* '"';
NULL_LITERAL: 'null';
// Separators
LPAREN: '(';
RPAREN: ')';
LBRACE: '{';
RBRACE: '}';
LBRACK: '[';
RBRACK: ']';
SEMI: ';';
COMMA: ',';
DOT: '.';
// Operators
ASSIGN: '=';
GT: '>';
LT: '<';
BANG: '!';
TILDE: '~';
QUESTION: '?';
COLON: ':';
EQUAL: '==';
LE: '<=';
GE: '>=';
NOTEQUAL: '!=';
AND: '&&';
OR: '||';
INC: '++';
DEC: '--';
ADD: '+';
SUB: '-';
MUL: '*';
DIV: '/';
BITAND: '&';
BITOR: '|';
CARET: '^';
MOD: '%';
ADD_ASSIGN: '+=';
SUB_ASSIGN: '-=';
MUL_ASSIGN: '*=';
DIV_ASSIGN: '/=';
AND_ASSIGN: '&=';
OR_ASSIGN: '|=';
XOR_ASSIGN: '^=';
MOD_ASSIGN: '%=';
LSHIFT_ASSIGN: '<<=';
RSHIFT_ASSIGN: '>>=';
URSHIFT_ASSIGN: '>>>=';
// Java 8 tokens
ARROW: '->';
COLONCOLON: '::';
// Additional symbols not defined in the lexical specification
AT: '@';
ELLIPSIS: '...';
// Whitespace and comments
WS: [ \t\r\n\u000C]+ -> channel(HIDDEN);
COMMENT: '/*' .*? '*/' -> channel(HIDDEN);
LINE_COMMENT: '//' ~[\r\n]* -> channel(HIDDEN);
// Identifiers
IDENTIFIER: Letter LetterOrDigit*;
// Fragment rules
fragment ExponentPart
: [eE] [+-]? Digits
;
fragment EscapeSequence
: '\\' [btnfr"'\\]
| '\\' ([0-3]? [0-7])? [0-7]
| '\\' 'u'+ HexDigit HexDigit HexDigit HexDigit
;
fragment HexDigits
: HexDigit ((HexDigit | '_')* HexDigit)?
;
fragment HexDigit
: [0-9a-fA-F]
;
fragment Digits
: [0-9] ([0-9_]* [0-9])?
;
fragment LetterOrDigit
: Letter
| [0-9]
;
fragment Letter
: [a-zA-Z$_] // these are the "java letters" below 0x7F
| ~[\u0000-\u007F\uD800-\uDBFF] // covers all characters above 0x7F which are not a surrogate
| [\uD800-\uDBFF] [\uDC00-\uDFFF] // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF
;
|
Fix unicode escape in fast java grammar
|
Fix unicode escape in fast java 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
|
28849feebe6d9ab357c7421fdd0e67169ee0a436
|
webidl/WebIDL.g4
|
webidl/WebIDL.g4
|
/*
BSD License
Copyright (c) 2013,2015 Rainer Schuster
Copyright (c) 2021 ethanmdavidson
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Rainer Schuster nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Web IDL grammar derived from:
http://heycam.github.io/webidl/
Web IDL (Second Edition)
Editor’s Draft, 3 May 2021
*/
grammar WebIDL;
// Note: Replaced keywords: const, default, enum, interface, null.
// Note: Added "wrapper" rule webIDL with EOF token.
webIDL
: definitions EOF
;
definitions
: extendedAttributeList definition definitions
| /* empty */
;
definition
: callbackOrInterfaceOrMixin
| namespace
| partial
| dictionary
| enum_
| typedef_
| includesStatement
;
argumentNameKeyword
: 'async'
| 'attribute'
| 'callback'
| 'const'
| 'constructor'
| 'deleter'
| 'dictionary'
| 'enum'
| 'getter'
| 'includes'
| 'inherit'
| 'interface'
| 'iterable'
| 'maplike'
| 'mixin'
| 'namespace'
| 'partial'
| 'readonly'
| 'required'
| 'setlike'
| 'setter'
| 'static'
| 'stringifier'
| 'typedef'
| 'unrestricted'
;
callbackOrInterfaceOrMixin
: 'callback' callbackRestOrInterface
| 'interface' interfaceOrMixin
;
interfaceOrMixin
: interfaceRest
| mixinRest
;
interfaceRest
: IDENTIFIER_WEBIDL inheritance '{' interfaceMembers '}' ';'
;
partial
: 'partial' partialDefinition
;
partialDefinition
: 'interface' partialInterfaceOrPartialMixin
| partialDictionary
| namespace
;
partialInterfaceOrPartialMixin
: partialInterfaceRest
| mixinRest
;
partialInterfaceRest
: IDENTIFIER_WEBIDL '{' partialInterfaceMembers '}' ';'
;
interfaceMembers
: extendedAttributeList interfaceMember interfaceMembers
| /* empty */
;
interfaceMember
: partialInterfaceMember
| constructor
;
partialInterfaceMembers
: extendedAttributeList partialInterfaceMember partialInterfaceMembers
| /* empty */
;
partialInterfaceMember
: const_
| operation
| stringifier
| staticMember
| iterable
| asyncIterable
| readonlyMember
| readWriteAttribute
| readWriteMaplike
| readWriteSetlike
| inheritAttribute
;
inheritance
: ':' IDENTIFIER_WEBIDL
| /* empty */
;
mixinRest
: 'mixin' IDENTIFIER_WEBIDL '{' mixinMembers '}' ';'
;
mixinMembers
: extendedAttributeList mixinMember mixinMembers
| /* empty */
;
mixinMember
: const_
| regularOperation
| stringifier
| optionalReadOnly attributeRest
;
includesStatement
: IDENTIFIER_WEBIDL 'includes' IDENTIFIER_WEBIDL ';'
;
callbackRestOrInterface
: callbackRest
| 'interface' IDENTIFIER_WEBIDL '{' callbackInterfaceMembers '}' ';'
;
callbackInterfaceMembers
: extendedAttributeList callbackInterfaceMember callbackInterfaceMembers
| /* empty */
;
callbackInterfaceMember
: const_
| regularOperation
;
const_
: 'const' constType IDENTIFIER_WEBIDL '=' constValue ';'
;
constValue
: booleanLiteral
| floatLiteral
| INTEGER_WEBIDL
| 'null' //TODO: webidl grammar doesn't include null in constValue, but
// the docs seem to imply that its valid
;
booleanLiteral
: 'true'
| 'false'
;
floatLiteral
: DECIMAL_WEBIDL
| '-Infinity'
| 'Infinity'
| 'NaN'
;
constType
: primitiveType
| IDENTIFIER_WEBIDL
;
readonlyMember
: 'readonly' readonlyMemberRest
;
readonlyMemberRest
: attributeRest
| maplikeRest
| setlikeRest
;
readWriteAttribute
: attributeRest
;
inheritAttribute
: 'inherit' attributeRest
;
attributeRest
: 'attribute' typeWithExtendedAttributes attributeName ';'
;
attributeName
: attributeNameKeyword
| IDENTIFIER_WEBIDL
;
attributeNameKeyword
: 'async'
| 'required'
;
optionalReadOnly
: 'readonly'
| /* empty */
;
defaultValue
: constValue
| STRING_WEBIDL
| '[' ']'
| '{' '}'
| 'null'
;
operation
: regularOperation
| specialOperation
;
regularOperation
: type_ operationRest
;
specialOperation
: special regularOperation
;
special
: 'getter'
| 'setter'
| 'deleter'
;
operationRest
: optionalOperationName '(' argumentList ')' ';'
;
optionalOperationName
: operationName
| /* empty */
;
operationName
: operationNameKeyword
| IDENTIFIER_WEBIDL
;
operationNameKeyword
: 'includes'
;
argumentList
: argument arguments
| /* empty */
;
arguments
: ',' argument arguments
| /* empty */
;
argument
: extendedAttributeList argumentRest
;
argumentRest
: 'optional' typeWithExtendedAttributes argumentName default_
| type_ ellipsis argumentName
;
argumentName
: argumentNameKeyword
| IDENTIFIER_WEBIDL
;
ellipsis
: '...'
| /* empty */
;
constructor
: 'constructor' '(' argumentList ')' ';'
;
stringifier
: 'stringifier' stringifierRest
;
stringifierRest
: optionalReadOnly attributeRest
| regularOperation
| ';'
;
staticMember
: 'static' staticMemberRest
;
staticMemberRest
: optionalReadOnly attributeRest
| regularOperation
;
iterable
: 'iterable' '<' typeWithExtendedAttributes optionalType '>' ';'
;
optionalType
: ',' typeWithExtendedAttributes
| /* empty */
;
asyncIterable
: 'async' 'iterable' '<' typeWithExtendedAttributes optionalType '>' optionalArgumentList ';'
;
optionalArgumentList
: '(' argumentList ')'
| /* empty */
;
readWriteMaplike
: maplikeRest
;
maplikeRest
: 'maplike' '<' typeWithExtendedAttributes ',' typeWithExtendedAttributes '>' ';'
;
readWriteSetlike
: setlikeRest
;
setlikeRest
: 'setlike' '<' typeWithExtendedAttributes '>' ';'
;
namespace
: 'namespace' IDENTIFIER_WEBIDL '{' namespaceMembers '}' ';'
;
namespaceMembers
: extendedAttributeList namespaceMember namespaceMembers
| /* empty */
;
namespaceMember
: regularOperation
| 'readonly' attributeRest
| const_
;
dictionary
: 'dictionary' IDENTIFIER_WEBIDL inheritance '{' dictionaryMembers '}' ';'
;
dictionaryMembers
: dictionaryMember dictionaryMembers
| /* empty */
;
dictionaryMember
: extendedAttributeList dictionaryMemberRest
;
dictionaryMemberRest
: 'required' typeWithExtendedAttributes IDENTIFIER_WEBIDL ';'
| type_ IDENTIFIER_WEBIDL default_ ';'
;
partialDictionary
: 'dictionary' IDENTIFIER_WEBIDL '{' dictionaryMembers '}' ';'
;
default_
: '=' defaultValue
| /* empty */
;
enum_
: 'enum' IDENTIFIER_WEBIDL '{' enumValueList '}' ';'
;
enumValueList
: STRING_WEBIDL enumValueListComma
;
enumValueListComma
: ',' enumValueListString
| /* empty */
;
enumValueListString
: STRING_WEBIDL enumValueListComma
| /* empty */
;
callbackRest
: IDENTIFIER_WEBIDL '=' type_ '(' argumentList ')' ';'
;
typedef_
: 'typedef' typeWithExtendedAttributes IDENTIFIER_WEBIDL ';'
;
type_
: singleType
| unionType null_
;
typeWithExtendedAttributes
: extendedAttributeList type_
;
singleType
: distinguishableType
| 'any'
| promiseType
;
unionType
: '(' unionMemberType 'or' unionMemberType unionMemberTypes ')'
;
unionMemberType
: extendedAttributeList distinguishableType
| unionType null_
;
unionMemberTypes
: 'or' unionMemberType unionMemberTypes
| /* empty */
;
distinguishableType
: primitiveType null_
| stringType null_
| IDENTIFIER_WEBIDL null_
| 'sequence' '<' typeWithExtendedAttributes '>' null_
| 'object' null_
| 'symbol' null_
| bufferRelatedType null_
| 'FrozenArray' '<' typeWithExtendedAttributes '>' null_
| 'ObservableArray' '<' typeWithExtendedAttributes '>' null_
| recordType null_
;
primitiveType
: unsignedIntegerType
| unrestrictedFloatType
| 'undefined'
| 'boolean'
| 'byte'
| 'octet'
| 'bigint'
;
unrestrictedFloatType
: 'unrestricted' floatType
| floatType
;
floatType
: 'float'
| 'double'
;
unsignedIntegerType
: 'unsigned' integerType
| integerType
;
integerType
: 'short'
| 'long' optionalLong
;
optionalLong
: 'long'
| /* empty */
;
stringType
: 'ByteString'
| 'DOMString'
| 'USVString'
;
promiseType
: 'Promise' '<' type_ '>'
;
recordType
: 'record' '<' stringType ',' typeWithExtendedAttributes '>'
;
null_
: '?'
| /* empty */
;
bufferRelatedType
: 'ArrayBuffer'
| 'DataView'
| 'Int8Array'
| 'Int16Array'
| 'Int32Array'
| 'Uint8Array'
| 'Uint16Array'
| 'Uint32Array'
| 'Uint8ClampedArray'
| 'Float32Array'
| 'Float64Array'
;
extendedAttributeList
: '[' extendedAttribute extendedAttributes ']'
| /* empty */
;
extendedAttributes
: ',' extendedAttribute extendedAttributes
| /* empty */
;
extendedAttribute
: '(' extendedAttributeInner ')' extendedAttributeRest
| '[' extendedAttributeInner ']' extendedAttributeRest
| '{' extendedAttributeInner '}' extendedAttributeRest
| other extendedAttributeRest
;
extendedAttributeRest
: extendedAttribute
| /* empty */
;
extendedAttributeInner
: '(' extendedAttributeInner ')' extendedAttributeInner
| '[' extendedAttributeInner ']' extendedAttributeInner
| '{' extendedAttributeInner '}' extendedAttributeInner
| otherOrComma extendedAttributeInner
| /* empty */
;
other
: INTEGER_WEBIDL
| DECIMAL_WEBIDL
| IDENTIFIER_WEBIDL
| STRING_WEBIDL
| OTHER_WEBIDL
| '-'
| '-Infinity'
| '.'
| '...'
| ':'
| ';'
| '<'
| '='
| '>'
| '?'
| 'ByteString'
| 'DOMString'
| 'FrozenArray'
| 'Infinity'
| 'NaN'
| 'ObservableArray'
| 'Promise'
| 'USVString'
| 'any'
| 'bigint'
| 'boolean'
| 'byte'
| 'double'
| 'false'
| 'float'
| 'long'
| 'null'
| 'object'
| 'octet'
| 'or'
| 'optional'
| 'record'
| 'sequence'
| 'short'
| 'symbol'
| 'true'
| 'unsigned'
| 'undefined'
| argumentNameKeyword
| bufferRelatedType
;
otherOrComma
: other
| ','
;
identifierList
: IDENTIFIER_WEBIDL identifiers
;
identifiers
: ',' IDENTIFIER_WEBIDL identifiers
| /* empty */
;
extendedAttributeNoArgs
: IDENTIFIER_WEBIDL
;
extendedAttributeArgList
: IDENTIFIER_WEBIDL '(' argumentList ')'
;
extendedAttributeIdent
: IDENTIFIER_WEBIDL '=' IDENTIFIER_WEBIDL
;
extendedAttributeIdentList
: IDENTIFIER_WEBIDL '=' '(' identifierList ')'
;
extendedAttributeNamedArgList
: IDENTIFIER_WEBIDL '=' IDENTIFIER_WEBIDL '(' argumentList ')'
;
INTEGER_WEBIDL
: '-'?('0'([Xx][0-9A-Fa-f]+|[0-7]*)|[1-9][0-9]*)
;
DECIMAL_WEBIDL
: '-'?(([0-9]+'.'[0-9]*|[0-9]*'.'[0-9]+)([Ee][+\-]?[0-9]+)?|[0-9]+[Ee][+\-]?[0-9]+)
;
IDENTIFIER_WEBIDL
: [_-]?[A-Z_a-z][0-9A-Z_a-z]*
;
STRING_WEBIDL
: '"' ~["]* '"'
;
WHITESPACE_WEBIDL
: [\t\n\r ]+ -> channel(HIDDEN)
;
COMMENT_WEBIDL
: ('//'~[\n\r]*|'/*'(.|'\n')*?'*/')+ -> channel(HIDDEN)
; // Note: '/''/'~[\n\r]* instead of '/''/'.* (non-greedy because of wildcard).
OTHER_WEBIDL
: ~[\t\n\r 0-9A-Z_a-z]
;
|
/*
BSD License
Copyright (c) 2013,2015 Rainer Schuster
Copyright (c) 2021 ethanmdavidson
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Rainer Schuster nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Web IDL grammar derived from:
http://heycam.github.io/webidl/
Web IDL (Second Edition)
Editor’s Draft, 3 May 2021
*/
grammar WebIDL;
// Note: Replaced keywords: const, default, enum, interface, null.
// Note: Added "wrapper" rule webIDL with EOF token.
webIDL
: definitions EOF
;
definitions
: extendedAttributeList definition definitions
| /* empty */
;
definition
: callbackOrInterfaceOrMixin
| namespace
| partial
| dictionary
| enum_
| typedef_
| includesStatement
;
argumentNameKeyword
: 'async'
| 'attribute'
| 'callback'
| 'const'
| 'constructor'
| 'deleter'
| 'dictionary'
| 'enum'
| 'getter'
| 'includes'
| 'inherit'
| 'interface'
| 'iterable'
| 'maplike'
| 'mixin'
| 'namespace'
| 'partial'
| 'readonly'
| 'required'
| 'setlike'
| 'setter'
| 'static'
| 'stringifier'
| 'typedef'
| 'unrestricted'
;
callbackOrInterfaceOrMixin
: 'callback' callbackRestOrInterface
| 'interface' interfaceOrMixin
;
interfaceOrMixin
: interfaceRest
| mixinRest
;
interfaceRest
: IDENTIFIER_WEBIDL inheritance '{' interfaceMembers '}' ';'
;
partial
: 'partial' partialDefinition
;
partialDefinition
: 'interface' partialInterfaceOrPartialMixin
| partialDictionary
| namespace
;
partialInterfaceOrPartialMixin
: partialInterfaceRest
| mixinRest
;
partialInterfaceRest
: IDENTIFIER_WEBIDL '{' partialInterfaceMembers '}' ';'
;
interfaceMembers
: extendedAttributeList interfaceMember interfaceMembers
| /* empty */
;
interfaceMember
: partialInterfaceMember
| constructor
;
partialInterfaceMembers
: extendedAttributeList partialInterfaceMember partialInterfaceMembers
| /* empty */
;
partialInterfaceMember
: const_
| operation
| stringifier
| staticMember
| iterable
| asyncIterable
| readonlyMember
| readWriteAttribute
| readWriteMaplike
| readWriteSetlike
| inheritAttribute
;
inheritance
: ':' IDENTIFIER_WEBIDL
| /* empty */
;
mixinRest
: 'mixin' IDENTIFIER_WEBIDL '{' mixinMembers '}' ';'
;
mixinMembers
: extendedAttributeList mixinMember mixinMembers
| /* empty */
;
mixinMember
: const_
| regularOperation
| stringifier
| optionalReadOnly attributeRest
;
includesStatement
: IDENTIFIER_WEBIDL 'includes' IDENTIFIER_WEBIDL ';'
;
callbackRestOrInterface
: callbackRest
| 'interface' IDENTIFIER_WEBIDL '{' callbackInterfaceMembers '}' ';'
;
callbackInterfaceMembers
: extendedAttributeList callbackInterfaceMember callbackInterfaceMembers
| /* empty */
;
callbackInterfaceMember
: const_
| regularOperation
;
const_
: 'const' constType IDENTIFIER_WEBIDL '=' constValue ';'
;
constValue
: booleanLiteral
| floatLiteral
| INTEGER_WEBIDL
;
booleanLiteral
: 'true'
| 'false'
;
floatLiteral
: DECIMAL_WEBIDL
| '-Infinity'
| 'Infinity'
| 'NaN'
;
constType
: primitiveType
| IDENTIFIER_WEBIDL
;
readonlyMember
: 'readonly' readonlyMemberRest
;
readonlyMemberRest
: attributeRest
| maplikeRest
| setlikeRest
;
readWriteAttribute
: attributeRest
;
inheritAttribute
: 'inherit' attributeRest
;
attributeRest
: 'attribute' typeWithExtendedAttributes attributeName ';'
;
attributeName
: attributeNameKeyword
| IDENTIFIER_WEBIDL
;
attributeNameKeyword
: 'async'
| 'required'
;
optionalReadOnly
: 'readonly'
| /* empty */
;
defaultValue
: constValue
| STRING_WEBIDL
| '[' ']'
| '{' '}'
| 'null'
;
operation
: regularOperation
| specialOperation
;
regularOperation
: type_ operationRest
;
specialOperation
: special regularOperation
;
special
: 'getter'
| 'setter'
| 'deleter'
;
operationRest
: optionalOperationName '(' argumentList ')' ';'
;
optionalOperationName
: operationName
| /* empty */
;
operationName
: operationNameKeyword
| IDENTIFIER_WEBIDL
;
operationNameKeyword
: 'includes'
;
argumentList
: argument arguments
| /* empty */
;
arguments
: ',' argument arguments
| /* empty */
;
argument
: extendedAttributeList argumentRest
;
argumentRest
: 'optional' typeWithExtendedAttributes argumentName default_
| type_ ellipsis argumentName
;
argumentName
: argumentNameKeyword
| IDENTIFIER_WEBIDL
;
ellipsis
: '...'
| /* empty */
;
constructor
: 'constructor' '(' argumentList ')' ';'
;
stringifier
: 'stringifier' stringifierRest
;
stringifierRest
: optionalReadOnly attributeRest
| regularOperation
| ';'
;
staticMember
: 'static' staticMemberRest
;
staticMemberRest
: optionalReadOnly attributeRest
| regularOperation
;
iterable
: 'iterable' '<' typeWithExtendedAttributes optionalType '>' ';'
;
optionalType
: ',' typeWithExtendedAttributes
| /* empty */
;
asyncIterable
: 'async' 'iterable' '<' typeWithExtendedAttributes optionalType '>' optionalArgumentList ';'
;
optionalArgumentList
: '(' argumentList ')'
| /* empty */
;
readWriteMaplike
: maplikeRest
;
maplikeRest
: 'maplike' '<' typeWithExtendedAttributes ',' typeWithExtendedAttributes '>' ';'
;
readWriteSetlike
: setlikeRest
;
setlikeRest
: 'setlike' '<' typeWithExtendedAttributes '>' ';'
;
namespace
: 'namespace' IDENTIFIER_WEBIDL '{' namespaceMembers '}' ';'
;
namespaceMembers
: extendedAttributeList namespaceMember namespaceMembers
| /* empty */
;
namespaceMember
: regularOperation
| 'readonly' attributeRest
| const_
;
dictionary
: 'dictionary' IDENTIFIER_WEBIDL inheritance '{' dictionaryMembers '}' ';'
;
dictionaryMembers
: dictionaryMember dictionaryMembers
| /* empty */
;
dictionaryMember
: extendedAttributeList dictionaryMemberRest
;
dictionaryMemberRest
: 'required' typeWithExtendedAttributes IDENTIFIER_WEBIDL ';'
| type_ IDENTIFIER_WEBIDL default_ ';'
;
partialDictionary
: 'dictionary' IDENTIFIER_WEBIDL '{' dictionaryMembers '}' ';'
;
default_
: '=' defaultValue
| /* empty */
;
enum_
: 'enum' IDENTIFIER_WEBIDL '{' enumValueList '}' ';'
;
enumValueList
: STRING_WEBIDL enumValueListComma
;
enumValueListComma
: ',' enumValueListString
| /* empty */
;
enumValueListString
: STRING_WEBIDL enumValueListComma
| /* empty */
;
callbackRest
: IDENTIFIER_WEBIDL '=' type_ '(' argumentList ')' ';'
;
typedef_
: 'typedef' typeWithExtendedAttributes IDENTIFIER_WEBIDL ';'
;
type_
: singleType
| unionType null_
;
typeWithExtendedAttributes
: extendedAttributeList type_
;
singleType
: distinguishableType
| 'any'
| promiseType
;
unionType
: '(' unionMemberType 'or' unionMemberType unionMemberTypes ')'
;
unionMemberType
: extendedAttributeList distinguishableType
| unionType null_
;
unionMemberTypes
: 'or' unionMemberType unionMemberTypes
| /* empty */
;
distinguishableType
: primitiveType null_
| stringType null_
| IDENTIFIER_WEBIDL null_
| 'sequence' '<' typeWithExtendedAttributes '>' null_
| 'object' null_
| 'symbol' null_
| bufferRelatedType null_
| 'FrozenArray' '<' typeWithExtendedAttributes '>' null_
| 'ObservableArray' '<' typeWithExtendedAttributes '>' null_
| recordType null_
;
primitiveType
: unsignedIntegerType
| unrestrictedFloatType
| 'undefined'
| 'boolean'
| 'byte'
| 'octet'
| 'bigint'
;
unrestrictedFloatType
: 'unrestricted' floatType
| floatType
;
floatType
: 'float'
| 'double'
;
unsignedIntegerType
: 'unsigned' integerType
| integerType
;
integerType
: 'short'
| 'long' optionalLong
;
optionalLong
: 'long'
| /* empty */
;
stringType
: 'ByteString'
| 'DOMString'
| 'USVString'
;
promiseType
: 'Promise' '<' type_ '>'
;
recordType
: 'record' '<' stringType ',' typeWithExtendedAttributes '>'
;
null_
: '?'
| /* empty */
;
bufferRelatedType
: 'ArrayBuffer'
| 'DataView'
| 'Int8Array'
| 'Int16Array'
| 'Int32Array'
| 'Uint8Array'
| 'Uint16Array'
| 'Uint32Array'
| 'Uint8ClampedArray'
| 'Float32Array'
| 'Float64Array'
;
extendedAttributeList
: '[' extendedAttribute extendedAttributes ']'
| /* empty */
;
extendedAttributes
: ',' extendedAttribute extendedAttributes
| /* empty */
;
extendedAttribute
: '(' extendedAttributeInner ')' extendedAttributeRest
| '[' extendedAttributeInner ']' extendedAttributeRest
| '{' extendedAttributeInner '}' extendedAttributeRest
| other extendedAttributeRest
;
extendedAttributeRest
: extendedAttribute
| /* empty */
;
extendedAttributeInner
: '(' extendedAttributeInner ')' extendedAttributeInner
| '[' extendedAttributeInner ']' extendedAttributeInner
| '{' extendedAttributeInner '}' extendedAttributeInner
| otherOrComma extendedAttributeInner
| /* empty */
;
other
: INTEGER_WEBIDL
| DECIMAL_WEBIDL
| IDENTIFIER_WEBIDL
| STRING_WEBIDL
| OTHER_WEBIDL
| '-'
| '-Infinity'
| '.'
| '...'
| ':'
| ';'
| '<'
| '='
| '>'
| '?'
| 'ByteString'
| 'DOMString'
| 'FrozenArray'
| 'Infinity'
| 'NaN'
| 'ObservableArray'
| 'Promise'
| 'USVString'
| 'any'
| 'bigint'
| 'boolean'
| 'byte'
| 'double'
| 'false'
| 'float'
| 'long'
| 'null'
| 'object'
| 'octet'
| 'or'
| 'optional'
| 'record'
| 'sequence'
| 'short'
| 'symbol'
| 'true'
| 'unsigned'
| 'undefined'
| argumentNameKeyword
| bufferRelatedType
;
otherOrComma
: other
| ','
;
identifierList
: IDENTIFIER_WEBIDL identifiers
;
identifiers
: ',' IDENTIFIER_WEBIDL identifiers
| /* empty */
;
extendedAttributeNoArgs
: IDENTIFIER_WEBIDL
;
extendedAttributeArgList
: IDENTIFIER_WEBIDL '(' argumentList ')'
;
extendedAttributeIdent
: IDENTIFIER_WEBIDL '=' IDENTIFIER_WEBIDL
;
extendedAttributeIdentList
: IDENTIFIER_WEBIDL '=' '(' identifierList ')'
;
extendedAttributeNamedArgList
: IDENTIFIER_WEBIDL '=' IDENTIFIER_WEBIDL '(' argumentList ')'
;
INTEGER_WEBIDL
: '-'?('0'([Xx][0-9A-Fa-f]+|[0-7]*)|[1-9][0-9]*)
;
DECIMAL_WEBIDL
: '-'?(([0-9]+'.'[0-9]*|[0-9]*'.'[0-9]+)([Ee][+\-]?[0-9]+)?|[0-9]+[Ee][+\-]?[0-9]+)
;
IDENTIFIER_WEBIDL
: [_-]?[A-Z_a-z][0-9A-Z_a-z]*
;
STRING_WEBIDL
: '"' ~["]* '"'
;
WHITESPACE_WEBIDL
: [\t\n\r ]+ -> channel(HIDDEN)
;
COMMENT_WEBIDL
: ('//'~[\n\r]*|'/*'(.|'\n')*?'*/')+ -> channel(HIDDEN)
; // Note: '/''/'~[\n\r]* instead of '/''/'.* (non-greedy because of wildcard).
OTHER_WEBIDL
: ~[\t\n\r 0-9A-Z_a-z]
;
|
resolve todo
|
resolve todo
I think I was misreading the spec
|
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
|
aaed70a1bb3ebdde9ad1fab8c8a3d1e57db937d2
|
pattern_grammar/STIXPattern.g4
|
pattern_grammar/STIXPattern.g4
|
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 (EQ|NEQ) primitiveLiteral # propTestEqual
| objectPath (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 timeUnit
;
repeatedQualifier
: REPEATS IntLiteral TIMES
;
objectPath
: objectType COLON firstPathComponent objectPathComponent?
;
// The following two simple rules are for programmer convenience: you
// will get "notification" of object path components in order by the
// generated parser, which enables incremental processing during
// parsing.
objectType
: Identifier
;
firstPathComponent
: Identifier
;
objectPathComponent
: <assoc=left> objectPathComponent objectPathComponent # pathStep
| '.' Identifier # keyPathStep
| LBRACK (IntLiteral|ASTERISK) RBRACK # indexPathStep
;
setLiteral
: LPAREN RPAREN
| LPAREN primitiveLiteral (COMMA primitiveLiteral)* RPAREN
;
primitiveLiteral
: orderableLiteral
| BoolLiteral
| NULL
;
orderableLiteral
: IntLiteral
| FloatLiteral
| StringLiteral
| BinaryLiteral
| HexLiteral
| TimestampLiteral
;
timeUnit
: MILLISECONDS | SECONDS | MINUTES | HOURS | DAYS | MONTHS | YEARS
;
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 ;
MILLISECONDS: M I L L I S E C O N D S;
SECONDS: S E C O N D S;
MINUTES: M I N U T E S;
HOURS: H O U R S;
DAYS: D A Y S;
MONTHS: M O N T H S;
YEARS: Y E A R S;
TRUE: T R U E;
FALSE: F A L S E;
NULL: N U L L;
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.
Identifier :
'"' (~'"' | '""')* '"'
| [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 (EQ|NEQ) primitiveLiteral # propTestEqual
| objectPath (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 timeUnit
;
repeatedQualifier
: REPEATS IntLiteral TIMES
;
objectPath
: objectType COLON firstPathComponent objectPathComponent?
;
// The following two simple rules are for programmer convenience: you
// will get "notification" of object path components in order by the
// generated parser, which enables incremental processing during
// parsing.
objectType
: Identifier
;
firstPathComponent
: Identifier
;
objectPathComponent
: <assoc=left> objectPathComponent objectPathComponent # pathStep
| '.' Identifier # keyPathStep
| LBRACK (IntLiteral|ASTERISK) RBRACK # indexPathStep
;
setLiteral
: LPAREN RPAREN
| LPAREN primitiveLiteral (COMMA primitiveLiteral)* RPAREN
;
primitiveLiteral
: orderableLiteral
| BoolLiteral
| NULL
;
orderableLiteral
: IntLiteral
| FloatLiteral
| StringLiteral
| BinaryLiteral
| HexLiteral
| TimestampLiteral
;
timeUnit
: MILLISECONDS | SECONDS | MINUTES | HOURS | DAYS | MONTHS | YEARS
;
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 ;
MILLISECONDS: M I L L I S E C O N D S;
SECONDS: S E C O N D S;
MINUTES: M I N U T E S;
HOURS: H O U R S;
DAYS: D A Y S;
MONTHS: M O N T H S;
YEARS: Y E A R S;
TRUE: T R U E;
FALSE: F A L S E;
NULL: N U L L;
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.
Identifier :
'"' (~'"' | '""')* '"'
| [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
;
|
Add link to (eventual) spec location.
|
Add link to (eventual) spec location.
|
ANTLR
|
bsd-3-clause
|
oasis-open/cti-stix2-json-schemas
|
c986ffd6b7bea6308b849848ec854efda483195c
|
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
|
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
|
grammar OracleDCLStatement;
import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol;
/**
* each statement has a url,
* each base url : https://docs.oracle.com/database/121/SQLRF/.
* no begin statement in oracle
*/
//statements_9014.htm#SQLRF01603
grant
: GRANT
(
(grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))?
| grantRolesToPrograms
)
;
grantSystemPrivileges
: systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)?
;
systemObjects
: systemObject(COMMA systemObject)*
;
systemObject
: ALL PRIVILEGES
| roleName
| ID *?
;
grantees
: grantee (COMMA grantee)*
;
grantee
: userName
| roleName
| PUBLIC
;
granteeIdentifiedBy
: userNames IDENTIFIED BY STRING (COMMA STRING)*
;
grantObjectPrivilegeClause
: grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause
TO grantees (WITH HIERARCHY OPTION)?(WITH GRANT OPTION)?
;
grantObjectPrivilege
: objectPrivilege columnList?
;
objectPrivilege
: ID *?
| ALL PRIVILEGES?
;
onObjectClause
: ON
(
schemaName? ID
| USER userName ( COMMA userName)*
| (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID
)
;
grantRolesToPrograms
: roleNames TO programUnits
;
programUnits
: programUnit (COMMA programUnit)*
;
programUnit
: (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID
;
revoke
: REVOKE
(
(revokeSystemPrivileges | revokeObjectPrivileges) (CONTAINER EQ_ (CURRENT | ALL))?
| revokeRolesFromPrograms
)
;
revokeSystemPrivileges
: systemObjects FROM
;
revokeObjectPrivileges
: objectPrivilege (COMMA objectPrivilege)* onObjectClause
FROM grantees
(CASCADE CONSTRAINTS | FORCE)?
;
revokeRolesFromPrograms
: (roleNames | ALL) FROM programUnits
;
createUser
: CREATE USER userName IDENTIFIED
(BY STRING | (EXTERNALLY | GLOBALLY) ( AS STRING)?)
(
DEFAULT TABLESPACE ID
| TEMPORARY TABLESPACE ID
| (QUOTA (sizeClause | UNLIMITED) ON ID)
| PROFILE ID
| PASSWORD EXPIRE
| ACCOUNT (LOCK | UNLOCK)
| ENABLE EDITIONS
| CONTAINER EQ_ (CURRENT | ALL)
)*
;
sizeClause
: NUMBER ID?
;
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 ) )?
;
|
grammar OracleDCLStatement;
import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol;
/**
* each statement has a url,
* each base url : https://docs.oracle.com/database/121/SQLRF/.
* no begin statement in oracle
*/
//statements_9014.htm#SQLRF01603
grant
: GRANT
(
(grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))?
| grantRolesToPrograms
)
;
grantSystemPrivileges
: systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)?
;
systemObjects
: systemObject(COMMA systemObject)*
;
systemObject
: ALL PRIVILEGES
| roleName
| ID *?
;
grantees
: grantee (COMMA grantee)*
;
grantee
: userName
| roleName
| PUBLIC
;
granteeIdentifiedBy
: userNames IDENTIFIED BY STRING (COMMA STRING)*
;
grantObjectPrivilegeClause
: grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause
TO grantees (WITH HIERARCHY OPTION)?(WITH GRANT OPTION)?
;
grantObjectPrivilege
: objectPrivilege columnList?
;
objectPrivilege
: ID *?
| ALL PRIVILEGES?
;
onObjectClause
: ON
(
schemaName? ID
| USER userName ( COMMA userName)*
| (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID
)
;
grantRolesToPrograms
: roleNames TO programUnits
;
programUnits
: programUnit (COMMA programUnit)*
;
programUnit
: (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID
;
revoke
: REVOKE
(
(revokeSystemPrivileges | revokeObjectPrivileges) (CONTAINER EQ_ (CURRENT | ALL))?
| revokeRolesFromPrograms
)
;
revokeSystemPrivileges
: systemObjects FROM
;
revokeObjectPrivileges
: objectPrivilege (COMMA objectPrivilege)* onObjectClause
FROM grantees
(CASCADE CONSTRAINTS | FORCE)?
;
revokeRolesFromPrograms
: (roleNames | ALL) FROM programUnits
;
createUser
: CREATE USER userName IDENTIFIED
(BY STRING | (EXTERNALLY | GLOBALLY) ( AS STRING)?)
(
DEFAULT TABLESPACE ID
| TEMPORARY TABLESPACE ID
| (QUOTA (sizeClause | UNLIMITED) ON ID)
| PROFILE ID
| PASSWORD EXPIRE
| ACCOUNT (LOCK | UNLOCK)
| ENABLE EDITIONS
| CONTAINER EQ_ (CURRENT | ALL)
)*
;
sizeClause
: NUMBER ID?
;
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 ))?
;
|
add alterRole
|
add alterRole
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
|
d741352b566954d918f066e63aa20ad400f04bb1
|
src/main/antlr/WorkflowCatalogQueryLanguage.g4
|
src/main/antlr/WorkflowCatalogQueryLanguage.g4
|
grammar WorkflowCatalogQueryLanguage;
@header {
package org.ow2.proactive.workflow_catalog.rest.query.parser;
}
// PARSER
start // start rule, begin parsing here
: expression
;
expression // ANTLR resolves ambiguities in favor of the alternative given first
: expression AND expression #andExpression // match subexpressions joined with AND
| expression OR expression #orExpression // match subexpressions joined with OR
| clause #clauseExpression
// | LPAREN expression RPAREN #parenthesedExpression
;
clause
: AttributeLiteral COMPARE_OPERATOR StringLiteral #atomicClause
| AttributeLiteral LPAREN StringLiteral PAIR_SEPARATOR StringLiteral RPAREN #keyValueClause
;
// LEXER
AND : 'AND' ;
OR : 'OR' ;
COMPARE_OPERATOR : '!=' | '=' ;
LPAREN : '(' ;
RPAREN : ')' ;
PAIR_SEPARATOR : ',' ;
AttributeLiteral
: ID_LETTER (ID_LETTER | DIGIT)*
;
StringLiteral
: '"' ( ESC | . )*? '"'
;
WS
: [ \t\r\n]+ -> skip
;
fragment DIGIT : [0-9];
fragment ESC : '\\"' | '\\\\' | '\\%';
fragment ID_LETTER : [a-z]|[A-Z]|'_' ;
fragment LETTER : LOWERCASE | UPPERCASE;
fragment LOWERCASE : [a-z];
fragment UPPERCASE : [A-Z];
|
grammar WorkflowCatalogQueryLanguage;
@header {
package org.ow2.proactive.workflow_catalog.rest.query.parser;
}
// PARSER
start // start rule, begin parsing here
: expression
;
expression // ANTLR resolves ambiguities in favor of the alternative given first
: expression AND expression #andExpression // match subexpressions joined with AND
| expression OR expression #orExpression // match subexpressions joined with OR
| clause #clauseExpression
// | LPAREN expression RPAREN #parenthesedExpression
;
clause
: AttributeLiteral COMPARE_OPERATOR StringLiteral #atomicClause
| AttributeLiteral LPAREN StringLiteral PAIR_SEPARATOR StringLiteral RPAREN #keyValueClause
;
// LEXER
AND : 'AND' ;
OR : 'OR' ;
COMPARE_OPERATOR : '!=' | '=' ;
LPAREN : '(' ;
RPAREN : ')' ;
PAIR_SEPARATOR : ',' ;
AttributeLiteral
: ID_LETTER (ID_LETTER | DIGIT)*
;
StringLiteral
: '"' ( ESC | . )*? '"'
;
WS
: [ \t\r\n]+ -> skip
;
fragment DIGIT : [0-9];
fragment ESC : '\\"' | '\\\\' ; // 2-char sequences \" and \\
fragment ID_LETTER : [a-z]|[A-Z]|'_' ;
fragment LETTER : LOWERCASE | UPPERCASE;
fragment LOWERCASE : [a-z];
fragment UPPERCASE : [A-Z];
|
Update WorkflowCatalogQueryLanguage.g4
|
Update WorkflowCatalogQueryLanguage.g4
|
ANTLR
|
agpl-3.0
|
laurianed/catalog,ShatalovYaroslav/catalog,ow2-proactive/catalog,ShatalovYaroslav/catalog,laurianed/catalog,ow2-proactive/catalog,ow2-proactive/catalog,yinan-liu/workflow-catalog,paraita/workflow-catalog,ShatalovYaroslav/catalog,laurianed/workflow-catalog,ow2-proactive/workflow-catalog,gparanthoen/workflow-catalog,laurianed/catalog
|
d6359122f471d1a70981d32bb3a4a1df41d341ce
|
SQLParser/Grammar/SQL.g4
|
SQLParser/Grammar/SQL.g4
|
grammar SQL;
options
{
language=CSharp;
}
//Everything inside the @header section will be placed at the start of your Parser class
@header {
using System;
}
@parser::members
{
protected const int EOF = Eof;
}
@lexer::members
{
protected const int EOF = Eof;
protected const int HIDDEN = Hidden;
}
/*
* Parser Rules
*/
//parse : ( sql_stmt_list | error )* EOF;
parse : (sql_stmt_list | error);
error : UNEXPECTED_CHAR
{
throw new Exception("UNEXPECTED_CHAR=" + $UNEXPECTED_CHAR.text);
}
;
sql_stmt_list : ';'* sql_stmt ( ';'+ sql_stmt )* ';'* ;
sql_stmt : ( select_stmt) ;
select_stmt : select_or_values ( compound_operator select_or_values )* ( order_by )?
;
order_by
: K_ORDER K_BY op=(K_SUMRANK|K_BESTRANK) '(' + ')' #orderBySpecial
| K_ORDER K_BY ordering_term ( ',' ordering_term )* #orderByDefault
;
select_or_values
: K_SELECT (top_keyword)? ( K_DISTINCT | K_ALL )? result_column ( ',' result_column )*
( K_FROM ( table_or_subquery ( ',' table_or_subquery )* | join_clause ) )?
( K_WHERE expr )?
( K_SKYLINE K_OF exprSkyline )?
( K_GROUP K_BY expr ( ',' expr )* ( K_HAVING expr )? )?
| K_VALUES '(' expr ( ',' expr )* ')' ( ',' '(' expr ( ',' expr )* ')' )*
;
type_name : name+ ( '(' signed_number ')' | '(' signed_number ',' signed_number ')' )?
;
/*
SQL understands the following binary operators, in order from highest to
lowest precedence:
||
* / %
+ -
<< >> & |
< <= > >=
= == != <> IS IS NOT IN LIKE MATCH REGEXP
AND
OR
*/
expr
: literal_value #expropLiteral
| column_term #expropDatabaseName
| unary_operator expr #expropUnary
| expr '||' expr #expropOr
| expr ( '*' | '/' | '%' ) expr #expropPoint
| expr ( '+' | '-' ) expr #expropLine
| expr ( '<<' | '>>' | '&' | '|' ) expr #expropDoubleOrder
| expr ( '<' | '<=' | '>' | '>=' ) expr #expropOrder
| expr ( '=' | '==' | '!=' | '<>' | K_IS | K_IS K_NOT | K_IN | K_LIKE | K_MATCH ) expr #expropequal
| '{' exprOwnPreference '}' #exprexprOwnPreferenceOp
| expr K_AND expr #exprexprand
| expr K_OR expr #exprexpror
| function_name '(' ( K_DISTINCT? expr ( ',' expr )* | '*' )? ')' #exprfunction
| '(' expr ')' #exprexprInBracket
| K_CAST '(' expr K_AS type_name ')' #exprcast
| expr K_NOT? ( K_LIKE | K_MATCH ) expr ( K_ESCAPE expr )? #not
| expr ( K_ISNULL | K_NOTNULL | K_NOT K_NULL ) #exprisNull
| expr K_IS K_NOT? expr #exprisNot
| expr K_NOT? K_BETWEEN expr K_AND expr #exprnotBetween
| expr K_NOT? K_IN ( '(' ( select_stmt
| expr ( ',' expr )*
)?
')'
| ( database_name '.' )? table_name ) #exprnotIn
| ( ( K_NOT )? K_EXISTS )? '(' select_stmt ')' #exprnotExists
| K_CASE expr? ( K_WHEN expr K_THEN expr )+ ( K_ELSE expr )? K_END #exprcase
| column_term ('(' exprCategory ')') #orderbyCategory
;
exprSkyline
: exprSkyline ',' exprSkyline #exprAnd
| column_term op=(K_LOW | K_HIGH | K_LOWDATE | K_HIGHDATE) (signed_number (K_EQUAL | K_INCOMPARABLE))? #preferenceLOWHIGH
| column_term ('(' exprCategory ')') #preferenceCategory
| column_term op=(K_AROUND | K_FAVOUR | K_DISFAVOUR) (signed_number|geocoordinate|column_term) #preferenceAROUND
;
exprCategory
: literal_value #opLiteral
| '{' exprOwnPreference '}' #exprOwnPreferenceOp
| exprCategory ( '>>' | '==') exprCategory #opDoubleOrder
//OTHERS keywords are only possible with greater than
//With the EQUAL keyword it would be too much coding (i.e. blue >> red == OTHERS EQUAL --> blue == OTHERS EQUAL)
//With the INCOMPARABLE keyword it would be a contradiction (i.e. red == OTHERS INCOMPARABLE)
| exprCategory ( '>>') exprOthers #opExprOthersAfter
| exprOthers ( '>>') exprCategory #opExprOthersBefore
;
exprOthers
: K_OTHERS (K_EQUAL)
| K_OTHERS (K_INCOMPARABLE);
geocoordinate :'(' expr ',' expr ')';
//For own preferences
exprOwnPreference
: column_term
| exprOwnPreference ',' exprOwnPreference
;
column_term : ( ( database_name '.' )? table_name '.' )? column_name;
ordering_term : expr ( K_ASC | K_DESC )? ;
result_column : '*' | table_name '.' '*' | expr ( K_AS? column_alias )?;
table_or_subquery
: ( database_name '.' )? table_name ( K_AS? table_alias )?
| '(' ( table_or_subquery ( ',' table_or_subquery )*
| join_clause )
')' ( K_AS? table_alias )?
| '(' select_stmt ')' ( K_AS? table_alias )?
;
join_clause : table_or_subquery ( join_operator table_or_subquery join_constraint )* ;
join_operator: ',' | ( K_LEFT K_OUTER? | K_INNER | K_CROSS )? K_JOIN;
join_constraint: ( K_ON expr | K_USING '(' column_name ( ',' column_name )* ')' )?;
compound_operator: K_UNION | K_UNION K_ALL | K_INTERSECT | K_EXCEPT;
signed_number : ( '+' | '-' )? NUMERIC_LITERAL;
literal_value
: NUMERIC_LITERAL
| STRING_LITERAL
| K_NULL
| K_CURRENT_TIME
| K_CURRENT_DATE
| K_CURRENT_TIMESTAMP
;
unary_operator
: '-'
| '+'
| '~'
| K_NOT
;
error_message: STRING_LITERAL;
column_alias: IDENTIFIER | STRING_LITERAL;
keyword
: K_ALL
| K_AND
| K_AS
| K_ASC
| K_BETWEEN
| K_BY
| K_CASE
| K_CAST
| K_CROSS
| K_CURRENT_DATE
| K_CURRENT_TIME
| K_CURRENT_TIMESTAMP
| K_DESC
| K_DISTINCT
| K_ELSE
| K_END
| K_ESCAPE
| K_EXCEPT
| K_EXISTS
| K_FROM
| K_FULL
| K_GROUP
| K_HAVING
| K_IN
| K_INNER
| K_INTERSECT
| K_IS
| K_ISNULL
| K_JOIN
| K_LEFT
| K_LIKE
| K_MATCH
| K_NO
| K_NOT
| K_NOTNULL
| K_NULL
| K_OF
| K_ON
| K_OR
| K_ORDER
| K_OUTER
| K_RIGHT
| K_SELECT
| K_TOP
| K_TABLE
| K_THEN
| K_UNION
| K_USING
| K_VALUES
| K_WHEN
| K_WHERE
//Preference
| K_AROUND
| K_DISFAVOUR
| K_FAVOUR
| K_HIGH
| K_LOW
| K_LOWLEVEL
| K_HIGHDATE
| K_LOWDATE
| K_OTHERS
| K_EQUAL
| K_INCOMPARABLE
| K_SKYLINE
| K_SUMRANK
| K_BESTRANK
;
name : any_name;
function_name : any_name;
database_name : any_name;
table_name : any_name;
new_table_name : any_name;
column_name : any_name;
table_alias : any_name;
top_keyword : K_TOP expr;
any_name : IDENTIFIER
| keyword
| STRING_LITERAL
| '(' any_name ')'
;
SCOL : ';';
DOT : '.';
OPEN_PAR : '(';
CLOSE_PAR : ')';
COMMA : ',';
ASSIGN : '=';
STAR : '*';
PLUS : '+';
MINUS : '-';
TILDE : '~';
PIPE2 : '||';
DIV : '/';
MOD : '%';
LT2 : '<<';
GT2 : '>>';
AMP : '&';
PIPE : '|';
LT : '<';
LT_EQ : '<=';
GT : '>';
GT_EQ : '>=';
EQ : '==';
NOT_EQ1 : '!=';
NOT_EQ2 : '<>';
// SQL Keywords
K_ALL : A L L;
K_AND : A N D;
K_AS : A S;
K_ASC : A S C;
K_BETWEEN : B E T W E E N;
K_BY : B Y;
K_CASE : C A S E;
K_CAST : C A S T;
K_CROSS : C R O S S;
K_CURRENT_DATE : C U R R E N T '_' D A T E;
K_CURRENT_TIME : C U R R E N T '_' T I M E;
K_CURRENT_TIMESTAMP : C U R R E N T '_' T I M E S T A M P;
K_DESC : D E S C;
K_DISTINCT : D I S T I N C T;
K_ELSE : E L S E;
K_END : E N D;
K_ESCAPE : E S C A P E;
K_EXCEPT : E X C E P T;
K_EXISTS : E X I S T S;
K_FROM : F R O M;
K_FULL : F U L L;
K_GROUP : G R O U P;
K_HAVING : H A V I N G;
K_IN : I N;
K_INNER : I N N E R;
K_INTERSECT : I N T E R S E C T;
K_IS : I S;
K_ISNULL : I S N U L L;
K_JOIN : J O I N;
K_LEFT : L E F T;
K_LIKE : L I K E;
K_MATCH : M A T C H;
K_NO : N O;
K_NOT : N O T;
K_NOTNULL : N O T N U L L;
K_NULL : N U L L;
K_OF : O F;
K_ON : O N;
K_OR : O R;
K_ORDER : O R D E R;
K_OUTER : O U T E R;
K_RIGHT : R I G H T;
K_SELECT : S E L E C T;
K_TABLE : T A B L E;
K_THEN : T H E N;
K_TOP : T O P;
K_UNION : U N I O N;
K_USING : U S I N G;
K_VALUES : V A L U E S;
K_WHEN : W H E N;
K_WHERE : W H E R E;
//Preference Keywords
K_AROUND : A R O U N D;
K_DISFAVOUR : D I S F A V O U R;
K_FAVOUR : F A V O U R;
K_HIGH : H I G H;
K_LOW : L O W;
K_LOWLEVEL : L O W L E V E L;
K_HIGHDATE: H I G H D A T E;
K_LOWDATE : L O W D A T E;
K_OTHERS : O T H E R S ;
K_EQUAL : E Q U A L;
K_INCOMPARABLE : I N C O M P A R A B L E;
K_SKYLINE : S K Y L I N E;
K_SUMRANK : S U M '_' R A N K;
K_BESTRANK : B E S T '_' R A N K;
/*
* Lexer Rules
*/
IDENTIFIER
: '"' (~'"' | '""')* '"'
| '`' (~'`' | '``')* '`'
| '[' ~']'* ']'
| [a-zA-Z_] [a-zA-Z_0-9]*
;
NUMERIC_LITERAL
: DIGIT+ ( '.' DIGIT* )? ( E [-+]? DIGIT+ )?
| '.' DIGIT+ ( E [-+]? DIGIT+ )?
;
STRING_LITERAL
: '\'' ( ~'\'' | '\'\'' )* '\''
;
SINGLE_LINE_COMMENT
: '--' ~[\r\n]* -> channel(HIDDEN)
;
MULTILINE_COMMENT
: '/*' .*? ( '*/' | EOF ) -> channel(HIDDEN)
;
SPACES
: [ \u000B\t\r\n] -> channel(HIDDEN)
;
UNEXPECTED_CHAR : . ;
fragment DIGIT : [0-9];
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];
|
grammar SQL;
options
{
language=CSharp;
}
//Everything inside the @header section will be placed at the start of your Parser class
@header {
using System;
}
@parser::members
{
protected const int EOF = Eof;
}
@lexer::members
{
protected const int EOF = Eof;
protected const int HIDDEN = Hidden;
}
/*
* Parser Rules
*/
//parse : ( sql_stmt_list | error )* EOF;
parse : (sql_stmt_list | error);
error : UNEXPECTED_CHAR
{
throw new Exception("UNEXPECTED_CHAR=" + $UNEXPECTED_CHAR.text);
}
;
sql_stmt_list : ';'* sql_stmt ( ';'+ sql_stmt )* ';'* ;
sql_stmt : ( select_stmt) ;
select_stmt : select_or_values ( compound_operator select_or_values )* ( order_by )?
;
order_by
: K_ORDER K_BY op=(K_SUMRANK|K_BESTRANK) '(' + ')' #orderBySpecial
| K_ORDER K_BY ordering_term ( ',' ordering_term )* #orderByDefault
;
select_or_values
: K_SELECT ( K_DISTINCT | K_ALL )? (top_keyword)? select_List_Item ( ',' select_List_Item )*
( K_FROM ( table_List_Item ( ',' table_List_Item )* | join_clause ) )?
( K_WHERE expr )?
( K_SKYLINE K_OF exprSkyline )?
;
type_name : name+ ( '(' signed_number ')' | '(' signed_number ',' signed_number ')' )?
;
/*
SQL understands the following binary operators, in order from highest to
lowest precedence:
||
* / %
+ -
<< >> & |
< <= > >=
= == != <> IS IS NOT IN LIKE MATCH REGEXP
AND
OR
*/
expr
: literal_value #expropLiteral
| column_term #expropDatabaseName
| unary_operator expr #expropUnary
| expr '||' expr #expropOr
| expr ( '*' | '/' | '%' ) expr #expropPoint
| expr ( '+' | '-' ) expr #expropLine
| expr ( '<<' | '>>' | '&' | '|' ) expr #expropDoubleOrder
| expr ( '<' | '<=' | '>' | '>=' ) expr #expropOrder
| expr ( '=' | '==' | '!=' | '<>' | K_IS | K_IS K_NOT | K_IN | K_LIKE | K_MATCH ) expr #expropequal
| '{' exprOwnPreference '}' #exprexprOwnPreferenceOp
| expr K_AND expr #exprexprand
| expr K_OR expr #exprexpror
| function_name '(' ( K_DISTINCT? expr ( ',' expr )* | '*' )? ')' #exprfunction
| '(' expr ')' #exprexprInBracket
| K_CAST '(' expr K_AS type_name ')' #exprcast
| expr K_NOT? ( K_LIKE | K_MATCH ) expr ( K_ESCAPE expr )? #not
| expr ( K_ISNULL | K_NOTNULL | K_NOT K_NULL ) #exprisNull
| expr K_IS K_NOT? expr #exprisNot
| expr K_NOT? K_BETWEEN expr K_AND expr #exprnotBetween
| expr K_NOT? K_IN ( '(' ( select_stmt
| expr ( ',' expr )*
)?
')'
| ( database_name '.' )? table_name ) #exprnotIn
| ( ( K_NOT )? K_EXISTS )? '(' select_stmt ')' #exprnotExists
| K_CASE expr? ( K_WHEN expr K_THEN expr )+ ( K_ELSE expr )? K_END #exprcase
| column_term ('(' exprCategory ')') #orderbyCategory
;
exprSkyline
: exprSkyline ',' exprSkyline #exprAnd
| column_term op=(K_LOW | K_HIGH | K_LOWDATE | K_HIGHDATE) (signed_number (K_EQUAL | K_INCOMPARABLE))? #preferenceLOWHIGH
| column_term ('(' exprCategory ')') #preferenceCategory
| column_term op=(K_AROUND | K_FAVOUR | K_DISFAVOUR) (signed_number|geocoordinate|column_term) #preferenceAROUND
| exprSkyline K_IS K_MORE K_IMPORTANT K_THAN exprSkyline #preferenceMoreImportant
;
exprCategory
: literal_value #opLiteral
| '{' exprOwnPreference '}' #exprOwnPreferenceOp
| exprCategory ( '>>' | '==') exprCategory #opDoubleOrder
//OTHERS keywords are only possible with greater than
//With the EQUAL keyword it would be too much coding (i.e. blue >> red == OTHERS EQUAL --> blue == OTHERS EQUAL)
//With the INCOMPARABLE keyword it would be a contradiction (i.e. red == OTHERS INCOMPARABLE)
| exprCategory ( '>>') exprOthers #opExprOthersAfter
| exprOthers ( '>>') exprCategory #opExprOthersBefore
;
exprOthers
: K_OTHERS (K_EQUAL)
| K_OTHERS (K_INCOMPARABLE);
geocoordinate :'(' expr ',' expr ')';
//For own preferences
exprOwnPreference
: column_term
| exprOwnPreference ',' exprOwnPreference
;
column_term : ( ( database_name '.' )? table_name '.' )? column_name;
ordering_term : expr ( K_ASC | K_DESC )? ;
select_List_Item : '*' | table_name '.' '*' | expr ( K_AS? column_alias )?;
table_List_Item
: ( database_name '.' )? table_name ( K_AS? table_alias )?
| '(' ( table_List_Item ( ',' table_List_Item )*
| join_clause )
')' ( K_AS? table_alias )?
| '(' select_stmt ')' ( K_AS? table_alias )?
;
join_clause : table_List_Item ( join_operator table_List_Item join_constraint )* ;
join_operator: ',' | ( K_LEFT K_OUTER? | K_INNER | K_CROSS )? K_JOIN;
join_constraint: ( K_ON expr | K_USING '(' column_name ( ',' column_name )* ')' )?;
compound_operator: K_UNION | K_UNION K_ALL | K_INTERSECT | K_EXCEPT;
signed_number : ( '+' | '-' )? NUMERIC_LITERAL;
literal_value
: NUMERIC_LITERAL
| STRING_LITERAL
| K_NULL
| K_CURRENT_TIME
| K_CURRENT_DATE
| K_CURRENT_TIMESTAMP
;
unary_operator
: '-'
| '+'
| '~'
| K_NOT
;
error_message: STRING_LITERAL;
column_alias: IDENTIFIER | STRING_LITERAL;
keyword
: K_ALL
| K_AND
| K_AS
| K_ASC
| K_BETWEEN
| K_BY
| K_CASE
| K_CAST
| K_CROSS
| K_CURRENT_DATE
| K_CURRENT_TIME
| K_CURRENT_TIMESTAMP
| K_DESC
| K_DISTINCT
| K_ELSE
| K_END
| K_ESCAPE
| K_EXCEPT
| K_EXISTS
| K_FROM
| K_FULL
| K_GROUP
| K_HAVING
| K_IN
| K_INNER
| K_INTERSECT
| K_IS
| K_ISNULL
| K_JOIN
| K_LEFT
| K_LIKE
| K_MATCH
| K_NO
| K_NOT
| K_NOTNULL
| K_NULL
| K_OF
| K_ON
| K_OR
| K_ORDER
| K_OUTER
| K_RIGHT
| K_SELECT
| K_TOP
| K_TABLE
| K_THEN
| K_UNION
| K_USING
| K_VALUES
| K_WHEN
| K_WHERE
//Preference
| K_AROUND
| K_DISFAVOUR
| K_FAVOUR
| K_HIGH
| K_LOW
| K_LOWLEVEL
| K_HIGHDATE
| K_LOWDATE
| K_OTHERS
| K_EQUAL
| K_INCOMPARABLE
| K_SKYLINE
| K_SUMRANK
| K_BESTRANK
| K_MORE
| K_IMPORTANT
| K_THAN
;
name : any_name;
function_name : any_name;
database_name : any_name;
table_name : any_name;
new_table_name : any_name;
column_name : any_name;
table_alias : any_name;
top_keyword : K_TOP NUMERIC_LITERAL;
any_name : IDENTIFIER
| keyword
| STRING_LITERAL
| '(' any_name ')'
;
SCOL : ';';
DOT : '.';
OPEN_PAR : '(';
CLOSE_PAR : ')';
COMMA : ',';
ASSIGN : '=';
STAR : '*';
PLUS : '+';
MINUS : '-';
TILDE : '~';
PIPE2 : '||';
DIV : '/';
MOD : '%';
LT2 : '<<';
GT2 : '>>';
AMP : '&';
PIPE : '|';
LT : '<';
LT_EQ : '<=';
GT : '>';
GT_EQ : '>=';
EQ : '==';
NOT_EQ1 : '!=';
NOT_EQ2 : '<>';
// SQL Keywords
K_ALL : A L L;
K_AND : A N D;
K_AS : A S;
K_ASC : A S C;
K_BETWEEN : B E T W E E N;
K_BY : B Y;
K_CASE : C A S E;
K_CAST : C A S T;
K_CROSS : C R O S S;
K_CURRENT_DATE : C U R R E N T '_' D A T E;
K_CURRENT_TIME : C U R R E N T '_' T I M E;
K_CURRENT_TIMESTAMP : C U R R E N T '_' T I M E S T A M P;
K_DESC : D E S C;
K_DISTINCT : D I S T I N C T;
K_ELSE : E L S E;
K_END : E N D;
K_ESCAPE : E S C A P E;
K_EXCEPT : E X C E P T;
K_EXISTS : E X I S T S;
K_FROM : F R O M;
K_FULL : F U L L;
K_GROUP : G R O U P;
K_HAVING : H A V I N G;
K_IN : I N;
K_INNER : I N N E R;
K_INTERSECT : I N T E R S E C T;
K_IS : I S;
K_ISNULL : I S N U L L;
K_JOIN : J O I N;
K_LEFT : L E F T;
K_LIKE : L I K E;
K_MATCH : M A T C H;
K_NO : N O;
K_NOT : N O T;
K_NOTNULL : N O T N U L L;
K_NULL : N U L L;
K_OF : O F;
K_ON : O N;
K_OR : O R;
K_ORDER : O R D E R;
K_OUTER : O U T E R;
K_RIGHT : R I G H T;
K_SELECT : S E L E C T;
K_TABLE : T A B L E;
K_THEN : T H E N;
K_TOP : T O P;
K_UNION : U N I O N;
K_USING : U S I N G;
K_VALUES : V A L U E S;
K_WHEN : W H E N;
K_WHERE : W H E R E;
//Preference Keywords
K_AROUND : A R O U N D;
K_DISFAVOUR : D I S F A V O U R;
K_FAVOUR : F A V O U R;
K_HIGH : H I G H;
K_LOW : L O W;
K_LOWLEVEL : L O W L E V E L;
K_HIGHDATE: H I G H D A T E;
K_LOWDATE : L O W D A T E;
K_OTHERS : O T H E R S ;
K_EQUAL : E Q U A L;
K_INCOMPARABLE : I N C O M P A R A B L E;
K_SKYLINE : S K Y L I N E;
K_SUMRANK : S U M '_' R A N K;
K_BESTRANK : B E S T '_' R A N K;
K_MORE: M O R E;
K_IMPORTANT: I M P O R T A N T;
K_THAN: T H A N;
/*
* Lexer Rules
*/
IDENTIFIER
: '"' (~'"' | '""')* '"'
| '`' (~'`' | '``')* '`'
| '[' ~']'* ']'
| [a-zA-Z_] [a-zA-Z_0-9]*
;
NUMERIC_LITERAL
: DIGIT+ ( '.' DIGIT* )? ( E [-+]? DIGIT+ )?
| '.' DIGIT+ ( E [-+]? DIGIT+ )?
;
STRING_LITERAL
: '\'' ( ~'\'' | '\'\'' )* '\''
;
SINGLE_LINE_COMMENT
: '--' ~[\r\n]* -> channel(HIDDEN)
;
MULTILINE_COMMENT
: '/*' .*? ( '*/' | EOF ) -> channel(HIDDEN)
;
SPACES
: [ \u000B\t\r\n] -> channel(HIDDEN)
;
UNEXPECTED_CHAR : . ;
fragment DIGIT : [0-9];
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];
|
Remove GROUP BY Clause
|
Remove GROUP BY Clause
|
ANTLR
|
bsd-3-clause
|
migaman/prefSQL,taschnue/prefSQL,tcchrist/prefSQL
|
c8847c6328d62833e24eb92162d7dbe68066875f
|
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
|
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
|
/* Todo:
* - Comments justifying and explaining every rule.
*/
lexer grammar CreoleTokens;
options { superClass=ContextSensitiveLexer; }
@members {
Formatting bold;
Formatting italic;
Formatting strike;
public void setupFormatting() {
bold = new Formatting("**");
italic = new Formatting("//");
strike = new Formatting("--");
inlineFormatting.add(bold);
inlineFormatting.add(italic);
inlineFormatting.add(strike);
}
public boolean inHeader = false;
public boolean start = false;
public int listLevel = 0;
boolean nowiki = false;
boolean cpp = false;
boolean html = false;
boolean java = false;
boolean xhtml = false;
boolean xml = false;
boolean intr = false;
public void doHdr() {
String prefix = getText().trim();
boolean seekback = false;
if(!prefix.substring(prefix.length() - 1).equals("=")) {
prefix = prefix.substring(0, prefix.length() - 1);
seekback = true;
}
if(prefix.length() <= 6) {
if(seekback) {
seek(-1);
}
setText(prefix);
inHeader = true;
} else {
setType(Any);
}
}
public void setStart() {
String next1 = next();
String next2 = get(1);
start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#"));
}
public void doList(int level) {
listLevel = level;
seek(-1);
setStart();
resetFormatting();
}
public void doUrl() {
String url = getText();
String last = url.substring(url.length()-1);
String next = next();
if((last + next).equals("//") || last.equals(".") || last.equals(",")) {
seek(-1);
setText(url.substring(0, url.length() - 1));
}
}
public void breakOut() {
resetFormatting();
listLevel = 0;
inHeader = false;
intr = false;
nowiki = false;
cpp = false;
html = false;
java = false;
xhtml = false;
xml = false;
}
public String[] thisKillsTheFormatting() {
String[] ends = new String[4];
if(inHeader || intr || listLevel > 0) {
ends[0] = "\n";
} else {
ends[0] = null;
}
if(intr) {
ends[1] = "|";
} else {
ends[1] = null;
}
ends[2] = "\n\n";
ends[3] = "\r\n\r\n";
return ends;
}
public boolean checkWW() {
String ww = getText();
String prior = get(-ww.length() - 1);
String next = next();
return !(prior.matches("\\w") || next.matches("\\w"));
}
}
/* ***** Headings ***** */
HSt : LINE '='+ ~'=' WS? {doHdr();} ;
HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ;
/* ***** Lists ***** */
U1 : START '*' ~'*' {doList(1);} ;
U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ;
U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ;
U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ;
U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ;
O1 : START '#' ~'#' {doList(1);} ;
O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ;
O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ;
O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ;
O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ;
/* ***** Horizontal Rules ***** */
Rule : LINE '---' '-'+? {breakOut();} ;
/* ***** Tables ***** */
TdStartLn : LINE '|' {intr=true; setType(TdStart);} ;
ThStartLn : LINE '|=' {intr=true; setType(ThStart);} ;
RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ;
TdStart : '|' {intr}? {breakOut(); intr=true;} ;
ThStart : '|=' {intr}? {breakOut(); intr=true;} ;
/* ***** Inline Formatting ***** */
BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ;
ISt : '//' {!italic.active}? {setFormatting(italic, Any);} ;
SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ;
BEnd : '**' {bold.active}? {unsetFormatting(bold);} ;
IEnd : '//' {italic.active}? {unsetFormatting(italic);} ;
SEnd : '--' {strike.active}? {unsetFormatting(strike);} ;
NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ;
StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ;
StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ;
StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ;
StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ;
StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ;
/* ***** Links ***** */
LiSt : '[[' -> mode(LINK) ;
ImSt : '{{' -> mode(LINK) ;
/* ***** Breaks ***** */
InlineBrk : '\\\\' ;
ParBreak : LineBreak LineBreak+ {breakOut();} ;
LineBreak : '\r'? '\n' ;
/* ***** Links ***** */
RawUrl : (('http' 's'? | 'ftp') '://' | 'mailto:') (~(' '|'\t'|'\r'|'\n'|'/'|'|'|'['|']')+ '/'?)+ {doUrl();};
WikiWords : ((INTERWIKI UPNUM | UPPER) (ABBR | CAMEL) | INTERWIKI UPNUM+) {checkWW()}? ;
fragment INTERWIKI : ALPHA+ ':' ;
fragment ABBR : UPPER UPPER+ ;
fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ;
/* ***** Macros ***** */
MacroSt : '<<' -> mode(MACRO) ;
/* ***** Miscellaneous ***** */
Any : . ;
WS : (' '|'\t')+ ;
fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ;
fragment START : {start}? | LINE ;
fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*;
fragment LOWNUM : (LOWER | DIGIT) ;
fragment UPNUM : (UPPER | DIGIT) ;
fragment ALNUM : (ALPHA | DIGIT) ;
fragment ALPHA : (UPPER | LOWER) ;
fragment UPPER : ('A'..'Z') ;
fragment LOWER : ('a'..'z') ;
fragment DIGIT : ('0'..'9') ;
/* ***** Contextual stuff ***** */
mode LINK;
LiEnd : ']]' -> mode(DEFAULT_MODE) ;
ImEnd : '}}' -> mode(DEFAULT_MODE) ;
Sep : ' '* '|' ' '*;
InLink : ~(']'|'}'|'|')+ {setText(getText().trim());};
mode MACRO;
MacroName : ~(':'|'>')+ ;
MacroSep : ':' -> mode(MACRO_ARGS) ;
mode MACRO_ARGS;
MacroArgs : . -> more ;
MacroEnd : '>>' -> mode(DEFAULT_MODE) ;
mode CODE_INLINE;
AnyInline : ~('\r'|'\n') -> more;
OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ;
EndNoWikiInline : '}}}' (~'}' {seek(-1);} | EOF) {nowiki}? -> mode(DEFAULT_MODE) ;
EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ;
EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ;
EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ;
EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ;
EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
mode CODE_BLOCK;
AnyText : . -> more ;
EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ;
EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ;
EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ;
EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ;
EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ;
EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
|
/* Todo:
* - Comments justifying and explaining every rule.
*/
lexer grammar CreoleTokens;
options { superClass=ContextSensitiveLexer; }
@members {
Formatting bold;
Formatting italic;
Formatting strike;
public void setupFormatting() {
bold = new Formatting("**");
italic = new Formatting("//");
strike = new Formatting("--");
inlineFormatting.add(bold);
inlineFormatting.add(italic);
inlineFormatting.add(strike);
}
public boolean inHeader = false;
public boolean start = false;
public int listLevel = 0;
boolean nowiki = false;
boolean cpp = false;
boolean html = false;
boolean java = false;
boolean xhtml = false;
boolean xml = false;
boolean intr = false;
public void doHdr() {
String prefix = getText().trim();
boolean seekback = false;
if(!prefix.substring(prefix.length() - 1).equals("=")) {
prefix = prefix.substring(0, prefix.length() - 1);
seekback = true;
}
if(prefix.length() <= 6) {
if(seekback) {
seek(-1);
}
setText(prefix);
inHeader = true;
} else {
setType(Any);
}
}
public void setStart() {
String next1 = next();
String next2 = get(1);
start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#"));
}
public void doList(int level) {
listLevel = level;
seek(-1);
setStart();
resetFormatting();
}
public void doUrl() {
String url = getText();
String last = url.substring(url.length()-1);
String next = next();
if((last + next).equals("//") || last.equals(".") || last.equals(",") || last.equals(")")) {
seek(-1);
setText(url.substring(0, url.length() - 1));
}
}
public void breakOut() {
resetFormatting();
listLevel = 0;
inHeader = false;
intr = false;
nowiki = false;
cpp = false;
html = false;
java = false;
xhtml = false;
xml = false;
}
public String[] thisKillsTheFormatting() {
String[] ends = new String[4];
if(inHeader || intr || listLevel > 0) {
ends[0] = "\n";
} else {
ends[0] = null;
}
if(intr) {
ends[1] = "|";
} else {
ends[1] = null;
}
ends[2] = "\n\n";
ends[3] = "\r\n\r\n";
return ends;
}
public boolean checkWW() {
String ww = getText();
String prior = get(-ww.length() - 1);
String next = next();
return !(prior.matches("\\w") || next.matches("\\w"));
}
}
/* ***** Headings ***** */
HSt : LINE '='+ ~'=' WS? {doHdr();} ;
HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ;
/* ***** Lists ***** */
U1 : START '*' ~'*' {doList(1);} ;
U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ;
U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ;
U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ;
U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ;
O1 : START '#' ~'#' {doList(1);} ;
O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ;
O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ;
O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ;
O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ;
/* ***** Horizontal Rules ***** */
Rule : LINE '---' '-'+? {breakOut();} ;
/* ***** Tables ***** */
TdStartLn : LINE '|' {intr=true; setType(TdStart);} ;
ThStartLn : LINE '|=' {intr=true; setType(ThStart);} ;
RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ;
TdStart : '|' {intr}? {breakOut(); intr=true;} ;
ThStart : '|=' {intr}? {breakOut(); intr=true;} ;
/* ***** Inline Formatting ***** */
BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ;
ISt : '//' {!italic.active}? {setFormatting(italic, Any);} ;
SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ;
BEnd : '**' {bold.active}? {unsetFormatting(bold);} ;
IEnd : '//' {italic.active}? {unsetFormatting(italic);} ;
SEnd : '--' {strike.active}? {unsetFormatting(strike);} ;
NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ;
StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ;
StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ;
StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ;
StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ;
StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ;
/* ***** Links ***** */
LiSt : '[[' -> mode(LINK) ;
ImSt : '{{' -> mode(LINK) ;
/* ***** Breaks ***** */
InlineBrk : '\\\\' ;
ParBreak : LineBreak LineBreak+ {breakOut();} ;
LineBreak : '\r'? '\n' ;
/* ***** Links ***** */
RawUrl : (('http' 's'? | 'ftp') '://' | 'mailto:') (~(' '|'\t'|'\r'|'\n'|'/'|'|'|'['|']')+ '/'?)+ {doUrl();};
WikiWords : ((INTERWIKI UPNUM | UPPER) (ABBR | CAMEL) | INTERWIKI UPNUM+) {checkWW()}? ;
fragment INTERWIKI : ALPHA+ ':' ;
fragment ABBR : UPPER UPPER+ ;
fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ;
/* ***** Macros ***** */
MacroSt : '<<' -> mode(MACRO) ;
/* ***** Miscellaneous ***** */
Any : . ;
WS : (' '|'\t')+ ;
fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ;
fragment START : {start}? | LINE ;
fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*;
fragment LOWNUM : (LOWER | DIGIT) ;
fragment UPNUM : (UPPER | DIGIT) ;
fragment ALNUM : (ALPHA | DIGIT) ;
fragment ALPHA : (UPPER | LOWER) ;
fragment UPPER : ('A'..'Z') ;
fragment LOWER : ('a'..'z') ;
fragment DIGIT : ('0'..'9') ;
/* ***** Contextual stuff ***** */
mode LINK;
LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
Sep : ' '* '|' ' '*;
InLink : ~(']'|'}'|'|'|'\r'|'\n')+ {setText(getText().trim());};
mode MACRO;
MacroName : ~(':'|'>')+ ;
MacroSep : ':' -> mode(MACRO_ARGS) ;
mode MACRO_ARGS;
MacroArgs : . -> more ;
MacroEnd : '>>' -> mode(DEFAULT_MODE) ;
mode CODE_INLINE;
AnyInline : ~('\r'|'\n') -> more;
OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ;
EndNoWikiInline : '}}}' (~'}' {seek(-1);} | EOF) {nowiki}? -> mode(DEFAULT_MODE) ;
EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ;
EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ;
EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ;
EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ;
EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
mode CODE_BLOCK;
AnyText : . -> more ;
EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ;
EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ;
EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ;
EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ;
EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ;
EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
|
Terminate links by linebreaks as well as ending tokens
|
Terminate links by linebreaks as well as ending tokens
|
ANTLR
|
apache-2.0
|
strr/reviki,strr/reviki,CoreFiling/reviki,CoreFiling/reviki,ashirley/reviki,strr/reviki,CoreFiling/reviki,ashirley/reviki,strr/reviki,CoreFiling/reviki,ashirley/reviki,ashirley/reviki,strr/reviki,ashirley/reviki,CoreFiling/reviki
|
8a4ba6caf8aae49486f99073092a02e37610832c
|
Solidity.g4
|
Solidity.g4
|
// Copyright 2016-2017 Federico Bond <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
grammar Solidity;
sourceUnit
: (pragmaDirective | importDirective | contractDefinition)* EOF ;
pragmaDirective
: 'pragma' pragmaName pragmaValue ';' ;
pragmaName
: identifier ;
pragmaValue
: version | expression ;
version
: versionConstraint versionConstraint? ;
versionOperator
: '^' | '>=' | '>' | '<' | '<=' ;
versionConstraint
: versionOperator? VersionLiteral ;
importDeclaration
: identifier ('as' identifier)? ;
importDirective
: 'import' StringLiteral ('as' identifier)? ';'
| 'import' ('*' | identifier) ('as' identifier)? 'from' StringLiteral ';'
| 'import' '{' importDeclaration ( ',' importDeclaration )* '}' 'from' StringLiteral ';' ;
contractDefinition
: ( 'contract' | 'interface' | 'library' ) identifier
( 'is' inheritanceSpecifier (',' inheritanceSpecifier )* )?
'{' contractPart* '}' ;
inheritanceSpecifier
: userDefinedTypeName ( '(' expression ( ',' expression )* ')' )? ;
contractPart
: stateVariableDeclaration
| usingForDeclaration
| structDefinition
| modifierDefinition
| functionDefinition
| eventDefinition
| enumDefinition ;
stateVariableDeclaration
: typeName
( PublicKeyword | InternalKeyword | PrivateKeyword | ConstantKeyword )*
identifier ('=' expression)? ';' ;
usingForDeclaration
: 'using' identifier 'for' ('*' | typeName) ';' ;
structDefinition
: 'struct' identifier
'{' ( variableDeclaration ';' (variableDeclaration ';')* )? '}' ;
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 indexedParameterList AnonymousKeyword? ';' ;
enumValue
: identifier ;
enumDefinition
: 'enum' identifier '{' enumValue? (',' enumValue)* '}' ;
indexedParameterList
: '(' ( indexedParameter (',' indexedParameter)* )? ')' ;
indexedParameter
: typeName ( storageLocation | IndexedKeyword )* identifier? ;
parameterList
: '(' ( parameter (',' parameter)* )? ')' ;
parameter
: typeName storageLocation? identifier? ;
typeNameList
: '(' ( unnamedParameter (',' unnamedParameter)* )? ')' ;
unnamedParameter
: typeName storageLocation? ;
variableDeclaration
: typeName storageLocation? identifier ;
typeName
: elementaryTypeName
| userDefinedTypeName
| mapping
| typeName '[' expression? ']'
| functionTypeName ;
userDefinedTypeName
: identifier ( '.' identifier )* ;
mapping
: 'mapping' '(' elementaryTypeName '=>' typeName ')' ;
functionTypeName
: 'function' typeNameList
( InternalKeyword | ExternalKeyword | stateMutability )*
( 'returns' typeNameList )? ;
storageLocation
: 'memory' | 'storage' ;
stateMutability
: PureKeyword | ConstantKeyword | ViewKeyword | PayableKeyword ;
block
: '{' statement* '}' ;
statement
: ifStatement
| whileStatement
| forStatement
| block
| inlineAssemblyStatement
| doWhileStatement
| continueStatement
| breakStatement
| returnStatement
| throwStatement
| 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' ';' ;
variableDeclarationStatement
: ( 'var' identifierList | variableDeclaration ) ( '=' expression )? ';';
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? ;
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]* )? ( [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* | 'from') ;
fragment
IdentifierStart
: [a-zA-Z$_] ;
fragment
IdentifierPart
: [a-zA-Z0-9$_] ;
StringLiteral
: '"' DoubleQuotedStringCharacter* '"'
| '\'' SingleQuotedStringCharacter* '\'' ;
fragment
DoubleQuotedStringCharacter
: ~["\r\n\\] | ('\\' .) ;
fragment
SingleQuotedStringCharacter
: ~['\r\n\\] | ('\\' .) ;
WS
: [ \t\r\n\u000C]+ -> skip ;
COMMENT
: '/*' .*? '*/' -> channel(HIDDEN) ;
LINE_COMMENT
: '//' ~[\r\n]* -> channel(HIDDEN) ;
|
// Copyright 2016-2017 Federico Bond <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
grammar Solidity;
sourceUnit
: (pragmaDirective | importDirective | contractDefinition)* EOF ;
pragmaDirective
: 'pragma' pragmaName pragmaValue ';' ;
pragmaName
: identifier ;
pragmaValue
: version | expression ;
version
: versionConstraint versionConstraint? ;
versionOperator
: '^' | '>=' | '>' | '<' | '<=' ;
versionConstraint
: versionOperator? VersionLiteral ;
importDeclaration
: identifier ('as' identifier)? ;
importDirective
: 'import' StringLiteral ('as' identifier)? ';'
| 'import' ('*' | identifier) ('as' identifier)? 'from' StringLiteral ';'
| 'import' '{' importDeclaration ( ',' importDeclaration )* '}' 'from' StringLiteral ';' ;
contractDefinition
: ( 'contract' | 'interface' | 'library' ) identifier
( 'is' inheritanceSpecifier (',' inheritanceSpecifier )* )?
'{' contractPart* '}' ;
inheritanceSpecifier
: userDefinedTypeName ( '(' expression ( ',' expression )* ')' )? ;
contractPart
: stateVariableDeclaration
| usingForDeclaration
| structDefinition
| modifierDefinition
| functionDefinition
| eventDefinition
| enumDefinition ;
stateVariableDeclaration
: typeName
( PublicKeyword | InternalKeyword | PrivateKeyword | ConstantKeyword )*
identifier ('=' expression)? ';' ;
usingForDeclaration
: 'using' identifier 'for' ('*' | typeName) ';' ;
structDefinition
: 'struct' identifier
'{' ( variableDeclaration ';' (variableDeclaration ';')* )? '}' ;
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 indexedParameterList AnonymousKeyword? ';' ;
enumValue
: identifier ;
enumDefinition
: 'enum' identifier '{' enumValue? (',' enumValue)* '}' ;
indexedParameterList
: '(' ( indexedParameter (',' indexedParameter)* )? ')' ;
indexedParameter
: typeName ( storageLocation | IndexedKeyword )* identifier? ;
parameterList
: '(' ( parameter (',' parameter)* )? ')' ;
parameter
: typeName storageLocation? identifier? ;
typeNameList
: '(' ( unnamedParameter (',' unnamedParameter)* )? ')' ;
unnamedParameter
: typeName storageLocation? ;
variableDeclaration
: typeName storageLocation? identifier ;
typeName
: elementaryTypeName
| userDefinedTypeName
| mapping
| typeName '[' expression? ']'
| functionTypeName ;
userDefinedTypeName
: identifier ( '.' identifier )* ;
mapping
: 'mapping' '(' elementaryTypeName '=>' typeName ')' ;
functionTypeName
: 'function' typeNameList
( InternalKeyword | ExternalKeyword | stateMutability )*
( 'returns' typeNameList )? ;
storageLocation
: 'memory' | 'storage' ;
stateMutability
: PureKeyword | ConstantKeyword | ViewKeyword | PayableKeyword ;
block
: '{' statement* '}' ;
statement
: ifStatement
| whileStatement
| forStatement
| block
| inlineAssemblyStatement
| doWhileStatement
| continueStatement
| breakStatement
| returnStatement
| throwStatement
| 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' ';' ;
variableDeclarationStatement
: ( 'var' identifierList | variableDeclaration ) ( '=' expression )? ';';
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? ;
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]* )? ( [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) ;
|
Remove useless 'from' from Identifier lexer rule
|
Remove useless 'from' from Identifier lexer rule
|
ANTLR
|
mit
|
solidityj/solidity-antlr4,federicobond/solidity-antlr4
|
5a3fba7a67400ba82cc942f43a0c9996c27612e9
|
kotlin/KotlinParser.g4
|
kotlin/KotlinParser.g4
|
/**
* Kotlin Grammar for ANTLR v4
*
* Based on:
* http://jetbrains.github.io/kotlin-spec/#_grammars_and_parsing
* and
* http://kotlinlang.org/docs/reference/grammar.html
*
* Tested on
* https://github.com/JetBrains/kotlin/tree/master/compiler/testData/psi
*/
parser grammar KotlinParser;
options { tokenVocab = KotlinLexer; }
kotlinFile
: NL* fileAnnotation? packageHeader importList topLevelObject* EOF
;
script
: NL* fileAnnotation? packageHeader importList(expression semi?)* EOF
;
fileAnnotation
: (FILE COLON (LSQUARE unescapedAnnotation+ RSQUARE | unescapedAnnotation) semi?)+
;
packageHeader
: (PACKAGE identifier semi?)?
;
importList
: importHeader*
;
importHeader
: IMPORT identifier (DOT MULT | importAlias)? semi?
;
importAlias
: AS simpleIdentifier
;
topLevelObject
: (classDeclaration
| functionDeclaration
| objectDeclaration
| propertyDeclaration
| typeAlias) semi?
;
classDeclaration
: modifierList? (CLASS | INTERFACE) NL* simpleIdentifier
(NL* typeParameters)? (NL* primaryConstructor)?
(NL* COLON NL* delegationSpecifiers)?
(NL* typeConstraints)?
(NL* classBody | NL* enumClassBody)?
;
primaryConstructor
: modifierList? (CONSTRUCTOR NL*)? classParameters
;
classParameters
: LPAREN (classParameter (COMMA classParameter)*)? RPAREN
;
classParameter
: modifierList? (VAL | VAR)? simpleIdentifier COLON type (ASSIGNMENT expression)?
;
delegationSpecifiers
: annotations* delegationSpecifier (NL* COMMA NL* delegationSpecifier)*
;
delegationSpecifier
: constructorInvocation
| userType
| explicitDelegation
;
constructorInvocation
: userType callSuffix
;
explicitDelegation
: userType NL* BY NL* expression
;
classBody
: LCURL NL* classMemberDeclaration* NL* RCURL
;
classMemberDeclaration
: (classDeclaration
| functionDeclaration
| objectDeclaration
| companionObject
| propertyDeclaration
| anonymousInitializer
| secondaryConstructor
| typeAlias) semi?
;
anonymousInitializer
: INIT NL* block
;
secondaryConstructor
: modifierList? CONSTRUCTOR NL* functionValueParameters (NL* COLON NL* constructorDelegationCall)? NL* block
;
constructorDelegationCall
: THIS NL* valueArguments
| SUPER NL* valueArguments
;
enumClassBody
: LCURL NL* enumEntries? (NL* SEMICOLON NL* classMemberDeclaration*)? NL* RCURL
;
enumEntries
: (enumEntry NL*)+ SEMICOLON?
;
enumEntry
: simpleIdentifier (NL* valueArguments)? (NL* classBody)? (NL* COMMA)?
;
functionDeclaration
: modifierList? FUN
//(NL* typeParameters)?
(NL* type NL* DOT)?
(NL* typeParameters)?
(NL* identifier)?
NL* functionValueParameters
(NL* COLON NL* type)?
(NL* typeConstraints)?
(NL* functionBody)?
;
functionValueParameters
: LPAREN (functionValueParameter (COMMA functionValueParameter)*)? RPAREN
;
functionValueParameter
: modifierList? parameter (ASSIGNMENT expression)?
;
parameter
: simpleIdentifier COLON type
;
functionBody
: block
| ASSIGNMENT NL* expression
;
objectDeclaration
: modifierList? OBJECT
NL* simpleIdentifier
(NL* primaryConstructor)?
(NL* COLON NL* delegationSpecifiers)?
(NL* classBody)?
;
companionObject
: modifierList? COMPANION NL* modifierList? OBJECT
(NL* simpleIdentifier)?
(NL* COLON NL* delegationSpecifiers)?
(NL* classBody)?
;
propertyDeclaration
: modifierList? (VAL | VAR)
(NL* typeParameters)?
(NL* type NL* DOT)?
(NL* (multiVariableDeclaration | variableDeclaration))
(NL* typeConstraints)?
(NL* (BY | ASSIGNMENT) NL* expression)?
semi? (getter? (NL* setter)? | setter? (NL* getter)?)
;
multiVariableDeclaration
: LPAREN variableDeclaration (COMMA variableDeclaration)* RPAREN
;
variableDeclaration
: simpleIdentifier (COLON type)?
;
getter
: modifierList? GETTER
| modifierList? GETTER NL* LPAREN RPAREN (NL* COLON NL* type)? NL* (block | ASSIGNMENT NL* expression)
;
setter
: modifierList? SETTER
| modifierList? SETTER NL* LPAREN (annotations | parameterModifier)* (simpleIdentifier | parameter) RPAREN NL* functionBody
;
typeAlias
: modifierList? TYPE_ALIAS NL* simpleIdentifier (NL* typeParameters)? NL* ASSIGNMENT NL* type
;
typeParameters
: LANGLE NL* typeParameter (NL* COMMA NL* typeParameter)* NL* RANGLE
;
typeParameter
: modifierList? NL* simpleIdentifier (NL* COLON NL* type)?
;
type
: typeModifierList?
( parenthesizedType
| nullableType
| typeReference
| functionType)
;
typeModifierList
: (annotations | SUSPEND NL*)+
;
parenthesizedType
: LPAREN type RPAREN
;
nullableType
: (typeReference | parenthesizedType) NL* QUEST+
;
typeReference
: LPAREN typeReference RPAREN
| userType
| DYNAMIC
;
functionType
: (functionTypeReceiver NL* DOT NL*)? functionTypeParameters NL* ARROW (NL* type)?
;
functionTypeReceiver
: parenthesizedType
| nullableType
| typeReference
;
userType
: simpleUserType (NL* DOT NL* simpleUserType)*
;
simpleUserType
: simpleIdentifier (NL* typeArguments)?
;
//parameters for functionType
functionTypeParameters
: LPAREN (parameter | type)? (COMMA (parameter | type))* RPAREN
;
typeConstraints
: WHERE NL* typeConstraint (NL* COMMA NL* typeConstraint)*
;
typeConstraint
: annotations* simpleIdentifier NL* COLON NL* type
;
block
: LCURL NL* (statement semi)* (statement semi?)? NL* RCURL
;
statements
: ((statement semi)* statement semi?)?
;
statement
: declaration
| assignment
| expression
;
declaration
: labelDefinition*
( classDeclaration
| functionDeclaration
| propertyDeclaration
| typeAlias)
;
assignment
: assignableExpression assignmentOperator NL* disjunction
;
expression
: disjunction
;
disjunction
: conjunction (NL* DISJ NL* conjunction)*
;
conjunction
: equality (NL* CONJ NL* equality)*
;
equality
: comparison (equalityOperator NL* comparison)*
;
comparison
: infixOperation (comparisonOperator NL* infixOperation)?
;
infixOperation
: elvisExpression (inOperator NL* elvisExpression)*
| elvisExpression (isOperator NL* type)?
;
elvisExpression
: infixFunctionCall (NL* ELVIS NL* infixFunctionCall)*
;
infixFunctionCall
: rangeExpression (simpleIdentifier NL* rangeExpression)*
;
rangeExpression
: additiveExpression (RANGE NL* additiveExpression)*
;
additiveExpression
: multiplicativeExpression (additiveOperator NL* multiplicativeExpression)*
;
multiplicativeExpression
: asExpression (multiplicativeOperator NL* asExpression)*
;
asExpression
: prefixUnaryExpression asExpressionTail?
;
asExpressionTail
: NL* asOperator NL* type asExpressionTail?
;
prefixUnaryExpression
: prefixUnaryOperator* postfixUnaryExpression
| annotations* postfixUnaryExpression
;
postfixUnaryExpression
: assignableExpression
| callExpression
| labeledExpression
| dotQualifiedExpression
| assignableExpression postfixUnaryOperator*
| LPAREN callableReference RPAREN postfixUnaryOperator+
| callableReference
;
callExpression
: assignableExpression typeArguments? valueArguments? annotatedLambda*
;
labeledExpression
: labelDefinition postfixUnaryExpression
;
dotQualifiedExpression
: assignableExpression (NL* memberAccessOperator postfixUnaryExpression)+
;
assignableExpression
: primaryExpression
| indexingExpression
;
indexingExpression
: identifier arrayAccess+
;
callSuffix
: typeArguments valueArguments? annotatedLambda*
| valueArguments annotatedLambda*
| annotatedLambda+
;
annotatedLambda
: unescapedAnnotation* LabelDefinition? NL* functionLiteral
;
arrayAccess
: LSQUARE (expression (COMMA expression)*)? RSQUARE
;
valueArguments
: LPAREN valueArgument? RPAREN
| LPAREN valueArgument (COMMA valueArgument)* RPAREN
;
typeArguments
: LANGLE NL* typeProjection (NL* COMMA typeProjection)* NL* RANGLE
;
typeProjection
: typeProjectionModifierList? type | MULT
;
typeProjectionModifierList
: varianceAnnotation+
;
valueArgument
: (simpleIdentifier NL* ASSIGNMENT NL*)? MULT? NL* expression
;
primaryExpression
: parenthesizedExpression
| literalConstant
| stringLiteral
| simpleIdentifier
| functionLiteral
| objectLiteral
| collectionLiteral
| thisExpression
| superExpression
| conditionalExpression
| tryExpression
| loopExpression
| jumpExpression
;
parenthesizedExpression
: LPAREN expression RPAREN
;
literalConstant
: BooleanLiteral
| IntegerLiteral
| HexLiteral
| BinLiteral
| CharacterLiteral
| RealLiteral
| NullLiteral
| LongLiteral
;
stringLiteral
: lineStringLiteral
| multiLineStringLiteral
;
lineStringLiteral
: QUOTE_OPEN (lineStringContent | lineStringExpression)* QUOTE_CLOSE
;
multiLineStringLiteral
: TRIPLE_QUOTE_OPEN (multiLineStringContent | multiLineStringExpression | lineStringLiteral | MultiLineStringQuote)* TRIPLE_QUOTE_CLOSE
;
lineStringContent
: LineStrText
| LineStrEscapedChar
| LineStrRef
;
lineStringExpression
: LineStrExprStart expression RCURL
;
multiLineStringContent
: MultiLineStrText
| MultiLineStrEscapedChar
| MultiLineStrRef
;
multiLineStringExpression
: MultiLineStrExprStart expression RCURL
;
functionLiteral
: annotations*
( LCURL NL* statements NL* RCURL
| LCURL NL* lambdaParameters NL* ARROW NL* statements NL* RCURL )
;
lambdaParameters
: lambdaParameter? (NL* COMMA NL* lambdaParameter)*
;
lambdaParameter
: variableDeclaration
| multiVariableDeclaration (NL* COLON NL* type)?
;
objectLiteral
: OBJECT (NL* COLON NL* delegationSpecifiers)? NL* classBody
;
collectionLiteral
: LSQUARE expression? (COMMA expression)* RSQUARE
;
thisExpression
: THIS LabelReference?
;
superExpression
: SUPER (LANGLE NL* type NL* RANGLE)? LabelReference?
;
conditionalExpression
: ifExpression
| whenExpression
;
ifExpression
: IF NL* LPAREN expression RPAREN NL* controlStructureBody? SEMICOLON?
(NL* ELSE NL* controlStructureBody?)?
;
controlStructureBody
: block
| expression
;
whenExpression
: WHEN NL* (LPAREN expression RPAREN)? NL* LCURL NL* (whenEntry NL*)* NL* RCURL
;
whenEntry
: whenCondition (NL* COMMA NL* whenCondition)* NL* ARROW NL* controlStructureBody semi?
| ELSE NL* ARROW NL* controlStructureBody
;
whenCondition
: expression
| rangeTest
| typeTest
;
rangeTest
: inOperator NL* expression
;
typeTest
: isOperator NL* type
;
tryExpression
: TRY NL* block (NL* catchBlock)* (NL* finallyBlock)?
;
catchBlock
: CATCH NL* LPAREN annotations* simpleIdentifier COLON userType RPAREN NL* block
;
finallyBlock
: FINALLY NL* block
;
loopExpression
: forExpression
| whileExpression
| doWhileExpression
;
forExpression
: FOR NL* LPAREN annotations* (variableDeclaration | multiVariableDeclaration) IN expression RPAREN NL* controlStructureBody?
;
whileExpression
: WHILE NL* LPAREN expression RPAREN NL* controlStructureBody?
;
doWhileExpression
: DO NL* controlStructureBody? NL* WHILE NL* LPAREN expression RPAREN
;
jumpExpression
: THROW NL* expression
| (RETURN | RETURN_AT) expression?
| CONTINUE | CONTINUE_AT
| BREAK | BREAK_AT
;
callableReference
: (userType (QUEST NL*)*)? NL* (COLONCOLON | Q_COLONCOLON) NL* (identifier | CLASS)
;
assignmentOperator
: ASSIGNMENT
| ADD_ASSIGNMENT
| SUB_ASSIGNMENT
| MULT_ASSIGNMENT
| DIV_ASSIGNMENT
| MOD_ASSIGNMENT
;
equalityOperator
: EXCL_EQ
| EXCL_EQEQ
| EQEQ
| EQEQEQ
;
comparisonOperator
: LANGLE
| RANGLE
| LE
| GE
;
inOperator
: IN | NOT_IN
;
isOperator
: IS | NOT_IS
;
additiveOperator
: ADD | SUB
;
multiplicativeOperator
: MULT
| DIV
| MOD
;
asOperator
: AS
| AS_SAFE
| COLON
;
prefixUnaryOperator
: INCR
| DECR
| ADD
| SUB
| EXCL
;
postfixUnaryOperator
: INCR | DECR | EXCL EXCL
;
memberAccessOperator
: DOT | QUEST DOT
;
modifierList
: (annotations | modifier)+
;
modifier
: (classModifier
| memberModifier
| visibilityModifier
| varianceAnnotation
| functionModifier
| propertyModifier
| inheritanceModifier
| parameterModifier
| typeParameterModifier) NL*
;
classModifier
: ENUM
| SEALED
| ANNOTATION
| DATA
| INNER
;
memberModifier
: OVERRIDE
| LATEINIT
;
visibilityModifier
: PUBLIC
| PRIVATE
| INTERNAL
| PROTECTED
;
varianceAnnotation
: IN | OUT
;
functionModifier
: TAILREC
| OPERATOR
| INFIX
| INLINE
| EXTERNAL
| SUSPEND
;
propertyModifier
: CONST
;
inheritanceModifier
: ABSTRACT
| FINAL
| OPEN
;
parameterModifier
: VARARG
| NOINLINE
| CROSSINLINE
;
typeParameterModifier
: REIFIED
;
labelDefinition
: LabelDefinition NL*
;
annotations
: (annotation | annotationList) NL*
;
annotation
: annotationUseSiteTarget NL* COLON NL* unescapedAnnotation
| LabelReference (NL* typeArguments)? (NL* valueArguments)?
;
annotationList
: annotationUseSiteTarget COLON LSQUARE unescapedAnnotation+ RSQUARE
| AT LSQUARE unescapedAnnotation+ RSQUARE
;
annotationUseSiteTarget
: FIELD
| FILE
| PROPERTY
| GET
| SET
| RECEIVER
| PARAM
| SETPARAM
| DELEGATE
;
unescapedAnnotation
: identifier typeArguments? valueArguments?
;
identifier
: simpleIdentifier (NL* DOT simpleIdentifier)*
;
simpleIdentifier
: Identifier
//soft keywords:
| ABSTRACT
| ANNOTATION
| BY
| CATCH
| COMPANION
| CONSTRUCTOR
| CROSSINLINE
| DATA
| DYNAMIC
| ENUM
| EXTERNAL
| FINAL
| FINALLY
| GETTER
| IMPORT
| INFIX
| INIT
| INLINE
| INNER
| INTERNAL
| LATEINIT
| NOINLINE
| OPEN
| OPERATOR
| OUT
| OVERRIDE
| PRIVATE
| PROTECTED
| PUBLIC
| REIFIED
| SEALED
| TAILREC
| SETTER
| VARARG
| WHERE
//strong keywords
| CONST
| SUSPEND
;
semi: NL+ | SEMICOLON | SEMICOLON NL+;
|
/**
* Kotlin Grammar for ANTLR v4
*
* Based on:
* http://jetbrains.github.io/kotlin-spec/#_grammars_and_parsing
* and
* http://kotlinlang.org/docs/reference/grammar.html
*
* Tested on
* https://github.com/JetBrains/kotlin/tree/master/compiler/testData/psi
*/
parser grammar KotlinParser;
options { tokenVocab = KotlinLexer; }
kotlinFile
: NL* preamble topLevelObject* EOF
;
script
: NL* preamble expression* EOF
;
preamble
: fileAnnotations? packageHeader importList
;
fileAnnotations
: fileAnnotation+
;
fileAnnotation
: (FILE COLON (LSQUARE unescapedAnnotation+ RSQUARE | unescapedAnnotation) semi?)+
;
packageHeader
: (modifierList? PACKAGE identifier semi?)?
;
importList
: importHeader*
;
importHeader
: IMPORT identifier (DOT MULT | importAlias)? semi?
;
importAlias
: AS simpleIdentifier
;
topLevelObject
: (classDeclaration
| objectDeclaration
| functionDeclaration
| propertyDeclaration
| typeAlias) anysemi*
;
classDeclaration
: modifierList? (CLASS | INTERFACE) NL* simpleIdentifier
(NL* typeParameters)? (NL* primaryConstructor)?
(NL* COLON NL* delegationSpecifiers)?
(NL* typeConstraints)?
(NL* classBody | NL* enumClassBody)?
;
primaryConstructor
: modifierList? (CONSTRUCTOR NL*)? classParameters
;
classParameters
: LPAREN (classParameter (COMMA classParameter)*)? RPAREN
;
classParameter
: modifierList? (VAL | VAR)? simpleIdentifier COLON type (ASSIGNMENT expression)?
;
delegationSpecifiers
: annotations* delegationSpecifier (NL* COMMA NL* delegationSpecifier)*
;
delegationSpecifier
: constructorInvocation
| userType
| explicitDelegation
;
constructorInvocation
: userType callSuffix
;
explicitDelegation
: userType NL* BY NL* expression
;
classBody
: LCURL NL* classMemberDeclaration* NL* RCURL
;
classMemberDeclaration
: (classDeclaration
| functionDeclaration
| objectDeclaration
| companionObject
| propertyDeclaration
| anonymousInitializer
| secondaryConstructor
| typeAlias) anysemi*
;
anonymousInitializer
: INIT NL* block
;
secondaryConstructor
: modifierList? CONSTRUCTOR NL* functionValueParameters (NL* COLON NL* constructorDelegationCall)? NL* block
;
constructorDelegationCall
: THIS NL* valueArguments
| SUPER NL* valueArguments
;
enumClassBody
: LCURL NL* enumEntries? (NL* SEMICOLON NL* classMemberDeclaration*)? NL* RCURL
;
enumEntries
: (enumEntry NL*)+ SEMICOLON?
;
enumEntry
: simpleIdentifier (NL* valueArguments)? (NL* classBody)? (NL* COMMA)?
;
functionDeclaration
: modifierList? FUN
(NL* type NL* DOT)?
(NL* typeParameters)?
(NL* identifier)?
NL* functionValueParameters
(NL* COLON NL* type)?
(NL* typeConstraints)?
(NL* functionBody)?
;
functionValueParameters
: LPAREN (functionValueParameter (COMMA functionValueParameter)*)? RPAREN
;
functionValueParameter
: modifierList? parameter (ASSIGNMENT expression)?
;
parameter
: simpleIdentifier COLON type
;
functionBody
: block
| ASSIGNMENT NL* expression
;
objectDeclaration
: modifierList? OBJECT
NL* simpleIdentifier
(NL* primaryConstructor)?
(NL* COLON NL* delegationSpecifiers)?
(NL* classBody)?
;
companionObject
: modifierList? COMPANION NL* modifierList? OBJECT
(NL* simpleIdentifier)?
(NL* COLON NL* delegationSpecifiers)?
(NL* classBody)?
;
propertyDeclaration
: modifierList? (VAL | VAR)
(NL* typeParameters)?
(NL* type NL* DOT)?
(NL* (multiVariableDeclaration | variableDeclaration))
(NL* typeConstraints)?
(NL* (BY | ASSIGNMENT) NL* expression)?
(getter (semi setter)? | setter (semi getter)?)?
;
multiVariableDeclaration
: LPAREN variableDeclaration (COMMA variableDeclaration)* RPAREN
;
variableDeclaration
: simpleIdentifier (COLON type)?
;
getter
: modifierList? GETTER
| modifierList? GETTER NL* LPAREN RPAREN (NL* COLON NL* type)? NL* (block | ASSIGNMENT NL* expression)
;
setter
: modifierList? SETTER
| modifierList? SETTER NL* LPAREN (annotations | parameterModifier)* (simpleIdentifier | parameter) RPAREN NL* functionBody
;
typeAlias
: modifierList? TYPE_ALIAS NL* simpleIdentifier (NL* typeParameters)? NL* ASSIGNMENT NL* type
;
typeParameters
: LANGLE NL* typeParameter (NL* COMMA NL* typeParameter)* NL* RANGLE
;
typeParameter
: modifierList? NL* simpleIdentifier (NL* COLON NL* type)?
;
type
: typeModifierList?
( functionType
| parenthesizedType
| nullableType
| typeReference)
;
typeModifierList
: (annotations | SUSPEND NL*)+
;
parenthesizedType
: LPAREN type RPAREN
;
nullableType
: (typeReference | parenthesizedType) NL* QUEST+
;
typeReference
: LPAREN typeReference RPAREN
| userType
| DYNAMIC
;
functionType
: (functionTypeReceiver NL* DOT NL*)? functionTypeParameters NL* ARROW (NL* type)
;
functionTypeReceiver
: parenthesizedType
| nullableType
| typeReference
;
userType
: simpleUserType (NL* DOT NL* simpleUserType)*
;
simpleUserType
: simpleIdentifier (NL* typeArguments)?
;
//parameters for functionType
functionTypeParameters
: LPAREN (parameter | type)? (COMMA (parameter | type))* RPAREN
;
typeConstraints
: WHERE NL* typeConstraint (NL* COMMA NL* typeConstraint)*
;
typeConstraint
: annotations* simpleIdentifier NL* COLON NL* type
;
block
: LCURL statements RCURL
;
statements
: anysemi* (statement (anysemi+ statement)*)? anysemi*
;
statement
: declaration
| blockLevelExpression
;
blockLevelExpression
: annotations* NL* expression
;
declaration
: labelDefinition*
( classDeclaration
| functionDeclaration
| propertyDeclaration
| typeAlias)
;
expression
: disjunction (assignmentOperator disjunction)*
;
disjunction
: conjunction (NL* DISJ NL* conjunction)*
;
conjunction
: equalityComparison (NL* CONJ NL* equalityComparison)*
;
equalityComparison
: comparison (equalityOperation NL* comparison)*
;
comparison
: namedInfix (comparisonOperator NL* namedInfix)?
;
namedInfix
: elvisExpression ((inOperator NL* elvisExpression)+ | (isOperator NL* type))?
;
elvisExpression
: infixFunctionCall (NL* ELVIS NL* infixFunctionCall)*
;
infixFunctionCall
: rangeExpression (simpleIdentifier NL* rangeExpression)*
;
rangeExpression
: additiveExpression (RANGE NL* additiveExpression)*
;
additiveExpression
: multiplicativeExpression (additiveOperator NL* multiplicativeExpression)*
;
multiplicativeExpression
: typeRHS (multiplicativeOperation NL* typeRHS)*
;
typeRHS
: prefixUnaryExpression (NL* typeOperation prefixUnaryExpression)*
;
prefixUnaryExpression
: prefixUnaryOperation* postfixUnaryExpression
;
postfixUnaryExpression
: (atomicExpression | callableReference) postfixUnaryOperation*
;
atomicExpression
: parenthesizedExpression
| literalConstant
| functionLiteral
| thisExpression // THIS labelReference?
| superExpression // SUPER (LANGLE type RANGLE)? labelReference?
| conditionalExpression // ifExpression, whenExpression
| tryExpression
| objectLiteral
| jumpExpression
| loopExpression
| collectionLiteral
| simpleIdentifier
;
parenthesizedExpression
: LPAREN expression RPAREN
;
callSuffix
: typeArguments valueArguments? annotatedLambda*
| valueArguments annotatedLambda*
| annotatedLambda+
;
annotatedLambda
: unescapedAnnotation* LabelDefinition? NL* functionLiteral
;
arrayAccess
: LSQUARE (expression (COMMA expression)*)? RSQUARE
;
valueArguments
: LPAREN (valueArgument (COMMA valueArgument)*)? RPAREN
;
typeArguments
: LANGLE NL* typeProjection (NL* COMMA typeProjection)* NL* RANGLE
;
typeProjection
: typeProjectionModifierList? type | MULT
;
typeProjectionModifierList
: varianceAnnotation+
;
valueArgument
: (simpleIdentifier NL* ASSIGNMENT NL*)? MULT? NL* expression
;
literalConstant
: BooleanLiteral
| IntegerLiteral
| stringLiteral
| HexLiteral
| BinLiteral
| CharacterLiteral
| RealLiteral
| NullLiteral
| LongLiteral
;
stringLiteral
: lineStringLiteral
| multiLineStringLiteral
;
lineStringLiteral
: QUOTE_OPEN (lineStringContent | lineStringExpression)* QUOTE_CLOSE
;
multiLineStringLiteral
: TRIPLE_QUOTE_OPEN (multiLineStringContent | multiLineStringExpression | lineStringLiteral | MultiLineStringQuote)* TRIPLE_QUOTE_CLOSE
;
lineStringContent
: LineStrText
| LineStrEscapedChar
| LineStrRef
;
lineStringExpression
: LineStrExprStart expression RCURL
;
multiLineStringContent
: MultiLineStrText
| MultiLineStrEscapedChar
| MultiLineStrRef
;
multiLineStringExpression
: MultiLineStrExprStart expression RCURL
;
functionLiteral
: annotations*
( LCURL NL* statements NL* RCURL
| LCURL NL* lambdaParameters NL* ARROW NL* statements NL* RCURL )
;
lambdaParameters
: lambdaParameter? (NL* COMMA NL* lambdaParameter)*
;
lambdaParameter
: variableDeclaration
| multiVariableDeclaration (NL* COLON NL* type)?
;
objectLiteral
: OBJECT (NL* COLON NL* delegationSpecifiers)? NL* classBody
;
collectionLiteral
: LSQUARE expression? (COMMA expression)* RSQUARE
;
thisExpression
: THIS LabelReference?
;
superExpression
: SUPER (LANGLE NL* type NL* RANGLE)? LabelReference?
;
conditionalExpression
: ifExpression
| whenExpression
;
ifExpression
: IF NL* LPAREN expression RPAREN NL* controlStructureBody? SEMICOLON?
(NL* ELSE NL* controlStructureBody?)?
;
controlStructureBody
: block
| expression
;
whenExpression
: WHEN NL* (LPAREN expression RPAREN)? NL* LCURL NL* (whenEntry NL*)* NL* RCURL
;
whenEntry
: whenCondition (NL* COMMA NL* whenCondition)* NL* ARROW NL* controlStructureBody semi?
| ELSE NL* ARROW NL* controlStructureBody
;
whenCondition
: expression
| rangeTest
| typeTest
;
rangeTest
: inOperator NL* expression
;
typeTest
: isOperator NL* type
;
tryExpression
: TRY NL* block (NL* catchBlock)* (NL* finallyBlock)?
;
catchBlock
: CATCH NL* LPAREN annotations* simpleIdentifier COLON userType RPAREN NL* block
;
finallyBlock
: FINALLY NL* block
;
loopExpression
: forExpression
| whileExpression
| doWhileExpression
;
forExpression
: FOR NL* LPAREN annotations* (variableDeclaration | multiVariableDeclaration) IN expression RPAREN NL* controlStructureBody?
;
whileExpression
: WHILE NL* LPAREN expression RPAREN NL* controlStructureBody?
;
doWhileExpression
: DO NL* controlStructureBody? NL* WHILE NL* LPAREN expression RPAREN
;
jumpExpression
: THROW NL* expression
| (RETURN | RETURN_AT) expression?
| CONTINUE | CONTINUE_AT
| BREAK | BREAK_AT
;
callableReference
: (userType (QUEST NL*)*)? NL* (COLONCOLON | Q_COLONCOLON) NL* (identifier | CLASS)
;
assignmentOperator
: ASSIGNMENT
| ADD_ASSIGNMENT
| SUB_ASSIGNMENT
| MULT_ASSIGNMENT
| DIV_ASSIGNMENT
| MOD_ASSIGNMENT
;
equalityOperation
: EXCL_EQ
| EXCL_EQEQ
| EQEQ
| EQEQEQ
;
comparisonOperator
: LANGLE
| RANGLE
| LE
| GE
;
inOperator
: IN | NOT_IN
;
isOperator
: IS | NOT_IS
;
additiveOperator
: ADD | SUB
;
multiplicativeOperation
: MULT
| DIV
| MOD
;
typeOperation
: AS
| AS_SAFE
| COLON
;
prefixUnaryOperation
: INCR
| DECR
| ADD
| SUB
| EXCL
| annotations
| labelDefinition
;
postfixUnaryOperation
: INCR | DECR | EXCL EXCL
| callSuffix
| arrayAccess
| NL* memberAccessOperator postfixUnaryExpression
;
memberAccessOperator
: DOT | QUEST DOT
;
modifierList
: (annotations | modifier)+
;
modifier
: (classModifier
| memberModifier
| visibilityModifier
| varianceAnnotation
| functionModifier
| propertyModifier
| inheritanceModifier
| parameterModifier
| typeParameterModifier) NL*
;
classModifier
: ENUM
| SEALED
| ANNOTATION
| DATA
| INNER
;
memberModifier
: OVERRIDE
| LATEINIT
;
visibilityModifier
: PUBLIC
| PRIVATE
| INTERNAL
| PROTECTED
;
varianceAnnotation
: IN | OUT
;
functionModifier
: TAILREC
| OPERATOR
| INFIX
| INLINE
| EXTERNAL
| SUSPEND
;
propertyModifier
: CONST
;
inheritanceModifier
: ABSTRACT
| FINAL
| OPEN
;
parameterModifier
: VARARG
| NOINLINE
| CROSSINLINE
;
typeParameterModifier
: REIFIED
;
labelDefinition
: LabelDefinition NL*
;
annotations
: (annotation | annotationList) NL*
;
annotation
: annotationUseSiteTarget NL* COLON NL* unescapedAnnotation
| LabelReference (NL* typeArguments)? (NL* valueArguments)?
;
annotationList
: annotationUseSiteTarget COLON LSQUARE unescapedAnnotation+ RSQUARE
| AT LSQUARE unescapedAnnotation+ RSQUARE
;
annotationUseSiteTarget
: FIELD
| FILE
| PROPERTY
| GET
| SET
| RECEIVER
| PARAM
| SETPARAM
| DELEGATE
;
unescapedAnnotation
: identifier typeArguments? valueArguments?
;
identifier
: simpleIdentifier (NL* DOT simpleIdentifier)*
;
simpleIdentifier
: Identifier
//soft keywords:
| ABSTRACT
| ANNOTATION
| BY
| CATCH
| COMPANION
| CONSTRUCTOR
| CROSSINLINE
| DATA
| DYNAMIC
| ENUM
| EXTERNAL
| FINAL
| FINALLY
| GETTER
| IMPORT
| INFIX
| INIT
| INLINE
| INNER
| INTERNAL
| LATEINIT
| NOINLINE
| OPEN
| OPERATOR
| OUT
| OVERRIDE
| PRIVATE
| PROTECTED
| PUBLIC
| REIFIED
| SEALED
| TAILREC
| SETTER
| VARARG
| WHERE
//strong keywords
| CONST
| SUSPEND
;
semi: NL+ | NL* SEMICOLON NL*;
anysemi: NL | SEMICOLON;
|
Align rule names with the ones in Kotlin documentation
|
Align rule names with the ones in Kotlin documentation
|
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
|
d737aadba7160857fde076aad731a2e03ba883a7
|
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
|
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
|
/* Todo:
* - Comments justifying and explaining every rule.
*/
lexer grammar CreoleTokens;
options { superClass=ContextSensitiveLexer; }
@members {
Formatting bold;
Formatting italic;
Formatting strike;
public void setupFormatting() {
bold = new Formatting("**");
italic = new Formatting("//");
strike = new Formatting("--");
inlineFormatting.add(bold);
inlineFormatting.add(italic);
inlineFormatting.add(strike);
}
public boolean inHeader = false;
public boolean start = false;
public int listLevel = 0;
boolean nowiki = false;
boolean cpp = false;
boolean html = false;
boolean java = false;
boolean xhtml = false;
boolean xml = false;
boolean intr = false;
public void doHdr() {
String prefix = getText().trim();
boolean seekback = false;
if(!prefix.substring(prefix.length() - 1).equals("=")) {
prefix = prefix.substring(0, prefix.length() - 1);
seekback = true;
}
if(prefix.length() <= 6) {
if(seekback) {
seek(-1);
}
setText(prefix);
inHeader = true;
} else {
setType(Any);
}
}
public void setStart() {
String next1 = next();
String next2 = get(1);
start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#"));
}
public void doList(int level) {
listLevel = level;
seek(-1);
setStart();
resetFormatting();
}
public void doUrl() {
String url = getText();
String last = url.substring(url.length()-1);
String next = next();
if((last + next).equals("//") || last.equals(".") || last.equals(",") || last.equals(")")) {
seek(-1);
setText(url.substring(0, url.length() - 1));
}
}
public void breakOut() {
resetFormatting();
listLevel = 0;
inHeader = false;
intr = false;
nowiki = false;
cpp = false;
html = false;
java = false;
xhtml = false;
xml = false;
}
public String[] thisKillsTheFormatting() {
String[] ends = new String[4];
if(inHeader || intr || listLevel > 0) {
ends[0] = "\n";
} else {
ends[0] = null;
}
if(intr) {
ends[1] = "|";
} else {
ends[1] = null;
}
ends[2] = "\n\n";
ends[3] = "\r\n\r\n";
return ends;
}
}
/* ***** Headings ***** */
HSt : LINE '='+ ~'=' WS? {doHdr();} ;
HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ;
/* ***** Lists ***** */
U1 : START '*' ~'*' {doList(1);} ;
U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ;
U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ;
U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ;
U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ;
O1 : START '#' ~'#' {doList(1);} ;
O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ;
O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ;
O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ;
O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ;
/* ***** Horizontal Rules ***** */
Rule : LINE '---' '-'+? {breakOut();} ;
/* ***** Tables ***** */
TdStartLn : LINE '|' {intr=true; setType(TdStart);} ;
ThStartLn : LINE '|=' {intr=true; setType(ThStart);} ;
RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ;
TdStart : '|' {intr}? {breakOut(); intr=true;} ;
ThStart : '|=' {intr}? {breakOut(); intr=true;} ;
/* ***** Inline Formatting ***** */
BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ;
ISt : '//' {!italic.active}? {setFormatting(italic, Any);} ;
SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ;
BEnd : '**' {bold.active}? {unsetFormatting(bold);} ;
IEnd : '//' {italic.active}? {unsetFormatting(italic);} ;
SEnd : '--' {strike.active}? {unsetFormatting(strike);} ;
NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ;
StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ;
StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ;
StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ;
StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ;
StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ;
/* ***** Links ***** */
LiSt : '[[' -> mode(LINK) ;
ImSt : '{{' -> mode(LINK) ;
/* ***** Breaks ***** */
InlineBrk : '\\\\' ;
ParBreak : LineBreak LineBreak+ {breakOut();} ;
LineBreak : '\r'? '\n' ;
/* ***** Links ***** */
RawUrl : (URL {doUrl();} | ATTACHMENT {checkBounds("[a-zA-Z0-9@\\./]", "[a-zA-Z0-9@/]")}?) ;
fragment URL : (('http' 's'? | 'ftp') '://' | 'mailto:') (~(' '|'\t'|'\r'|'\n'|'/'|'|'|'['|']')+ '/'?)+ ;
fragment ATTACHMENT : UPPER ALNUM* ALPHA ALNUM+ '.' LOWER LOWNUM+ ;
WikiWords : ((INTERWIKI UPNUM | UPPER) (ABBR | CAMEL) | INTERWIKI UPNUM+) {checkBounds("[\\.\\w]", "\\w")}? ;
fragment INTERWIKI : ALPHA ALNUM+ ':' ;
fragment ABBR : UPPER UPPER+ ;
fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ;
/* ***** Macros ***** */
MacroSt : '<<' -> mode(MACRO) ;
/* ***** Miscellaneous ***** */
Any : . ;
WS : (' '|'\t')+ ;
fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ;
fragment START : {start}? | LINE ;
fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*;
fragment LOWNUM : (LOWER | DIGIT) ;
fragment UPNUM : (UPPER | DIGIT) ;
fragment ALNUM : (ALPHA | DIGIT) ;
fragment ALPHA : (UPPER | LOWER) ;
fragment UPPER : ('A'..'Z') ;
fragment LOWER : ('a'..'z') ;
fragment DIGIT : ('0'..'9') ;
/* ***** Contextual stuff ***** */
mode LINK;
LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
Sep : ' '* '|' ' '*;
InLink : ~(']'|'}'|'|'|'\r'|'\n')+ {setText(getText().trim());};
mode MACRO;
MacroName : ~(':'|'>')+ ;
MacroSep : ':' -> mode(MACRO_ARGS) ;
mode MACRO_ARGS;
MacroArgs : . -> more ;
MacroEnd : '>>' -> mode(DEFAULT_MODE) ;
mode CODE_INLINE;
AnyInline : ~('\r'|'\n') -> more;
OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ;
EndNoWikiInline : '}}}' (~'}' {seek(-1);} | EOF) {nowiki}? -> mode(DEFAULT_MODE) ;
EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ;
EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ;
EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ;
EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ;
EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
mode CODE_BLOCK;
AnyText : . -> more ;
EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ;
EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ;
EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ;
EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ;
EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ;
EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
|
/* Todo:
* - Comments justifying and explaining every rule.
*/
lexer grammar CreoleTokens;
options { superClass=ContextSensitiveLexer; }
@members {
Formatting bold;
Formatting italic;
Formatting strike;
public void setupFormatting() {
bold = new Formatting("**");
italic = new Formatting("//");
strike = new Formatting("--");
inlineFormatting.add(bold);
inlineFormatting.add(italic);
inlineFormatting.add(strike);
}
public boolean inHeader = false;
public boolean start = false;
public int listLevel = 0;
boolean nowiki = false;
boolean cpp = false;
boolean html = false;
boolean java = false;
boolean xhtml = false;
boolean xml = false;
boolean intr = false;
public void doHdr() {
String prefix = getText().trim();
boolean seekback = false;
if(!prefix.substring(prefix.length() - 1).equals("=")) {
prefix = prefix.substring(0, prefix.length() - 1);
seekback = true;
}
if(prefix.length() <= 6) {
if(seekback) {
seek(-1);
}
setText(prefix);
inHeader = true;
} else {
setType(Any);
}
}
public void setStart() {
String next1 = next();
String next2 = get(1);
start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#"));
}
public void doList(int level) {
listLevel = level;
seek(-1);
setStart();
resetFormatting();
}
public void doUrl() {
String url = getText();
String last = url.substring(url.length()-1);
String next = next();
if((last + next).equals("//") || last.equals(".") || last.equals(",") || last.equals(")")) {
seek(-1);
setText(url.substring(0, url.length() - 1));
}
}
public void breakOut() {
resetFormatting();
listLevel = 0;
inHeader = false;
intr = false;
nowiki = false;
cpp = false;
html = false;
java = false;
xhtml = false;
xml = false;
}
public String[] thisKillsTheFormatting() {
String[] ends = new String[4];
if(inHeader || intr || listLevel > 0) {
ends[0] = "\n";
} else {
ends[0] = null;
}
if(intr) {
ends[1] = "|";
} else {
ends[1] = null;
}
ends[2] = "\n\n";
ends[3] = "\r\n\r\n";
return ends;
}
}
/* ***** Headings ***** */
HSt : LINE '='+ ~'=' WS? {doHdr();} ;
HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ;
/* ***** Lists ***** */
U1 : START '*' ~'*' {doList(1);} ;
U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ;
U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ;
U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ;
U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ;
O1 : START '#' ~'#' {doList(1);} ;
O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ;
O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ;
O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ;
O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ;
/* ***** Horizontal Rules ***** */
Rule : LINE '---' '-'+? {breakOut();} ;
/* ***** Tables ***** */
TdStartLn : LINE '|' {intr=true; setType(TdStart);} ;
ThStartLn : LINE '|=' {intr=true; setType(ThStart);} ;
RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ;
TdStart : '|' {intr}? {breakOut(); intr=true;} ;
ThStart : '|=' {intr}? {breakOut(); intr=true;} ;
/* ***** Inline Formatting ***** */
BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ;
ISt : '//' {!italic.active}? {setFormatting(italic, Any);} ;
SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ;
BEnd : '**' {bold.active}? {unsetFormatting(bold);} ;
IEnd : '//' {italic.active}? {unsetFormatting(italic);} ;
SEnd : '--' {strike.active}? {unsetFormatting(strike);} ;
NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ;
StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ;
StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ;
StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ;
StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ;
StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ;
/* ***** Links ***** */
LiSt : '[[' -> mode(LINK) ;
ImSt : '{{' -> mode(LINK) ;
/* ***** Breaks ***** */
InlineBrk : '\\\\' ;
ParBreak : LineBreak LineBreak+ {breakOut();} ;
LineBreak : '\r'? '\n' ;
/* ***** Links ***** */
RawUrl : (URL {doUrl();} | ATTACHMENT {checkBounds("[a-zA-Z0-9@\\./]", "[a-zA-Z0-9@/]")}?) ;
fragment URL : (('http' 's'? | 'ftp') '://' | 'mailto:') (~(' '|'\t'|'\r'|'\n'|'|'|'['|']')+ '/'?)+ ;
fragment ATTACHMENT : UPPER ALNUM* ALPHA ALNUM+ '.' LOWER LOWNUM+ ;
WikiWords : ((INTERWIKI UPNUM | UPPER) (ABBR | CAMEL) | INTERWIKI UPNUM+) {checkBounds("[\\.\\w]", "\\w")}? ;
fragment INTERWIKI : ALPHA ALNUM+ ':' ;
fragment ABBR : UPPER UPPER+ ;
fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ;
/* ***** Macros ***** */
MacroSt : '<<' -> mode(MACRO) ;
/* ***** Miscellaneous ***** */
Any : . ;
WS : (' '|'\t')+ ;
fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ;
fragment START : {start}? | LINE ;
fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*;
fragment LOWNUM : (LOWER | DIGIT) ;
fragment UPNUM : (UPPER | DIGIT) ;
fragment ALNUM : (ALPHA | DIGIT) ;
fragment ALPHA : (UPPER | LOWER) ;
fragment UPPER : ('A'..'Z') ;
fragment LOWER : ('a'..'z') ;
fragment DIGIT : ('0'..'9') ;
/* ***** Contextual stuff ***** */
mode LINK;
LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
Sep : ' '* '|' ' '*;
InLink : ~(']'|'}'|'|'|'\r'|'\n')+ {setText(getText().trim());};
mode MACRO;
MacroName : ~(':'|'>')+ ;
MacroSep : ':' -> mode(MACRO_ARGS) ;
mode MACRO_ARGS;
MacroArgs : . -> more ;
MacroEnd : '>>' -> mode(DEFAULT_MODE) ;
mode CODE_INLINE;
AnyInline : ~('\r'|'\n') -> more;
OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ;
EndNoWikiInline : '}}}' (~'}' {seek(-1);} | EOF) {nowiki}? -> mode(DEFAULT_MODE) ;
EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ;
EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ;
EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ;
EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ;
EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
mode CODE_BLOCK;
AnyText : . -> more ;
EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ;
EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ;
EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ;
EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ;
EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ;
EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
|
Allow raw URLs to contain //s
|
Allow raw URLs to contain //s
|
ANTLR
|
apache-2.0
|
strr/reviki,ashirley/reviki,CoreFiling/reviki,strr/reviki,CoreFiling/reviki,strr/reviki,strr/reviki,CoreFiling/reviki,strr/reviki,CoreFiling/reviki,ashirley/reviki,CoreFiling/reviki,ashirley/reviki,ashirley/reviki,ashirley/reviki
|
fe5c760047d3ea0826885e9594379da0ffffa057
|
src/main/antlr4/YokohamaUnitLexer.g4
|
src/main/antlr4/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' ;
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) ;
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) ;
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' ;
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) ;
REGEX_TICK: 'regex' Spaces? '`' -> mode(REGEXP) ;
REGEXP_TICK: 'regexp' Spaces? '`' -> mode(REGEXP) ;
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) ;
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 regexp literal and verbs
|
Add regexp literal and verbs
|
ANTLR
|
mit
|
tkob/yokohamaunit,tkob/yokohamaunit
|
73c60f9d631104bb313819ebd84bfb041a2b135d
|
protobuf3/Protobuf3.g4
|
protobuf3/Protobuf3.g4
|
// SDPX-License-Ientifier: Apache-2.0
/**
* A Protocol Buffers 3 grammar
*
* Original source: https://developers.google.com/protocol-buffers/docs/reference/proto3-spec
* Original source is published under Apache License 2.0.
*
* Changes from the source above:
* - rewrite to antlr
* - extract some group to rule.
*
* @author anatawa12
*/
grammar Protobuf3;
proto
: syntax
(
importStatement
| packageStatement
| optionStatement
| topLevelDef
| emptyStatement
)*
;
// Syntax
syntax
: 'syntax' '=' ('\'proto3\'' | '"proto3"') ';'
;
// Import Statement
importStatement
: 'import' ( 'weak' | 'public' )? strLit ';'
;
// Package
packageStatement
: 'package' fullIdent ';'
;
// Option
optionStatement
: 'option' optionName '=' constant ';'
;
optionName
: fullIdent
| '(' fullIdent ')' ( '.' fullIdent )?
;
// Normal Field
field
: ( 'repeated' )? type fieldName '=' fieldNumber ( '[' fieldOptions ']' )? ';'
;
fieldOptions
: fieldOption ( ',' fieldOption )*
;
fieldOption
: optionName '=' constant
;
fieldNumber
: intLit
;
// Oneof and oneof field
oneof
: 'oneof' oneofName '{' ( optionStatement | oneofField | emptyStatement )* '}'
;
oneofField
: type fieldName '=' fieldNumber ( '[' fieldOptions ']' )? ';'
;
// Map field
mapField
: 'map' '<' keyType ',' type '>' mapName
'=' fieldNumber ( '[' fieldOptions ']' )? ';'
;
keyType
: 'int32'
| 'int64'
| 'uint32'
| 'uint64'
| 'sint32'
| 'sint64'
| 'fixed32'
| 'fixed64'
| 'sfixed32'
| 'sfixed64'
| 'bool'
| 'string'
;
// field types
type
: 'double'
| 'float'
| 'int32'
| 'int64'
| 'uint32'
| 'uint64'
| 'sint32'
| 'sint64'
| 'fixed32'
| 'fixed64'
| 'sfixed32'
| 'sfixed64'
| 'bool'
| 'string'
| 'bytes'
| messageType
| enumType
;
// Reserved
reserved
: 'reserved' ( ranges | reservedFieldNames ) ';'
;
ranges
: range ( ',' range )*
;
range
: intLit ( 'to' ( intLit | 'max' ) )?
;
reservedFieldNames
: strLit ( ',' strLit )*
;
// Top Level definitions
topLevelDef
: messageDef
| enumDef
| serviceDef
;
// enum
enumDef
: 'enum' enumName enumBody
;
enumBody
: '{' enumElement* '}'
;
enumElement
: optionStatement
| enumField
| emptyStatement
;
enumField
: ident '=' ( '-' )? intLit enumValueOptions?';'
;
enumValueOptions
: '[' enumValueOption ( ',' enumValueOption )* ']'
;
enumValueOption
: optionName '=' constant
;
// message
messageDef
: 'message' messageName messageBody
;
messageBody
: '{' messageElement* '}'
;
messageElement
: field
| enumDef
| messageDef
| optionStatement
| oneof
| mapField
| reserved
| emptyStatement
;
// service
serviceDef
: 'service' serviceName '{' serviceElement* '}'
;
serviceElement
: optionStatement
| rpc
| emptyStatement
;
rpc
: 'rpc' rpcName '(' ( 'stream' )? messageType ')'
'returns' '(' ( 'stream' )? messageType ')'
('{' ( optionStatement | emptyStatement )* '}' | ';')
;
// lexical
constant
: fullIdent
| ('-' | '+' )? intLit
| ( '-' | '+' )? floatLit
| strLit
| boolLit
| blockLit
;
// not specified in specification but used in tests
blockLit
: '{' ( ident ':' constant )* '}'
;
emptyStatement: ';';
// Lexical elements
ident: IDENTIFIER | keywords;
fullIdent: ident ( '.' ident )*;
messageName: ident;
enumName: ident;
fieldName: ident;
oneofName: ident;
mapName: ident;
serviceName: ident;
rpcName: ident;
messageType: ( '.' )? ( ident '.' )* messageName;
enumType: ( '.' )? ( ident '.' )* enumName;
intLit: INT_LIT;
strLit: STR_LIT;
boolLit: BOOL_LIT;
floatLit: FLOAT_LIT;
STR_LIT: ( '\'' ( CHAR_VALUE )*? '\'' ) | ( '"' ( CHAR_VALUE )*? '"' );
fragment CHAR_VALUE: HEX_ESCAPE | OCT_ESCAPE | CHAR_ESCAPE | ~[\u0000\n\\];
fragment HEX_ESCAPE: '\\' ( 'x' | 'X' ) HEX_DIGIT HEX_DIGIT;
fragment OCT_ESCAPE: '\\' OCTAL_DIGIT OCTAL_DIGIT OCTAL_DIGIT;
fragment CHAR_ESCAPE: '\\' ( 'a' | 'b' | 'f' | 'n' | 'r' | 't' | 'v' | '\\' | '\'' | '"' );
BOOL_LIT: 'true' | 'false';
FLOAT_LIT : ( DECIMALS '.' DECIMALS? EXPONENT? | DECIMALS EXPONENT | '.' DECIMALS EXPONENT? ) | 'inf' | 'nan';
fragment EXPONENT : ( 'e' | 'E' ) ('+' | '-')? DECIMALS;
fragment DECIMALS : DECIMAL_DIGIT+;
INT_LIT : DECIMAL_LIT | OCTAL_LIT | HEX_LIT;
fragment DECIMAL_LIT : ( [1-9] ) DECIMAL_DIGIT*;
fragment OCTAL_LIT : '0' OCTAL_DIGIT*;
fragment HEX_LIT : '0' ( 'x' | 'X' ) HEX_DIGIT+ ;
IDENTIFIER: LETTER ( LETTER | DECIMAL_DIGIT )*;
fragment LETTER: [A-Za-z_];
fragment DECIMAL_DIGIT: [0-9];
fragment OCTAL_DIGIT: [0-7];
fragment HEX_DIGIT: [0-9A-Fa-f];
// comments
WS : [ \t\r\n\u000C]+ -> skip;
LINE_COMMENT: '//' ~[\r\n]* -> skip;
COMMENT: '/*' .*? '*/' -> skip;
keywords
: 'syntax'
| 'import'
| 'weak'
| 'public'
| 'package'
| 'option'
| 'repeated'
| 'oneof'
| 'map'
| 'int32'
| 'int64'
| 'uint32'
| 'uint64'
| 'sint32'
| 'sint64'
| 'fixed32'
| 'fixed64'
| 'sfixed32'
| 'sfixed64'
| 'bool'
| 'string'
| 'double'
| 'float'
| 'bytes'
| 'reserved'
| 'to'
| 'max'
| 'enum'
| 'message'
| 'service'
| 'rpc'
| 'stream'
| 'returns'
;
|
// SPDX-License-Identifier: Apache-2.0
/**
* A Protocol Buffers 3 grammar
*
* Original source: https://developers.google.com/protocol-buffers/docs/reference/proto3-spec
* Original source is published under Apache License 2.0.
*
* Changes from the source above:
* - rewrite to antlr
* - extract some group to rule.
*
* @author anatawa12
*/
grammar Protobuf3;
proto
: syntax
(
importStatement
| packageStatement
| optionStatement
| topLevelDef
| emptyStatement
)*
;
// Syntax
syntax
: 'syntax' '=' ('\'proto3\'' | '"proto3"') ';'
;
// Import Statement
importStatement
: 'import' ( 'weak' | 'public' )? strLit ';'
;
// Package
packageStatement
: 'package' fullIdent ';'
;
// Option
optionStatement
: 'option' optionName '=' constant ';'
;
optionName
: fullIdent
| '(' fullIdent ')' ( '.' fullIdent )?
;
// Normal Field
field
: ( 'repeated' )? type fieldName '=' fieldNumber ( '[' fieldOptions ']' )? ';'
;
fieldOptions
: fieldOption ( ',' fieldOption )*
;
fieldOption
: optionName '=' constant
;
fieldNumber
: intLit
;
// Oneof and oneof field
oneof
: 'oneof' oneofName '{' ( optionStatement | oneofField | emptyStatement )* '}'
;
oneofField
: type fieldName '=' fieldNumber ( '[' fieldOptions ']' )? ';'
;
// Map field
mapField
: 'map' '<' keyType ',' type '>' mapName
'=' fieldNumber ( '[' fieldOptions ']' )? ';'
;
keyType
: 'int32'
| 'int64'
| 'uint32'
| 'uint64'
| 'sint32'
| 'sint64'
| 'fixed32'
| 'fixed64'
| 'sfixed32'
| 'sfixed64'
| 'bool'
| 'string'
;
// field types
type
: 'double'
| 'float'
| 'int32'
| 'int64'
| 'uint32'
| 'uint64'
| 'sint32'
| 'sint64'
| 'fixed32'
| 'fixed64'
| 'sfixed32'
| 'sfixed64'
| 'bool'
| 'string'
| 'bytes'
| messageType
| enumType
;
// Reserved
reserved
: 'reserved' ( ranges | reservedFieldNames ) ';'
;
ranges
: range ( ',' range )*
;
range
: intLit ( 'to' ( intLit | 'max' ) )?
;
reservedFieldNames
: strLit ( ',' strLit )*
;
// Top Level definitions
topLevelDef
: messageDef
| enumDef
| serviceDef
;
// enum
enumDef
: 'enum' enumName enumBody
;
enumBody
: '{' enumElement* '}'
;
enumElement
: optionStatement
| enumField
| emptyStatement
;
enumField
: ident '=' ( '-' )? intLit enumValueOptions?';'
;
enumValueOptions
: '[' enumValueOption ( ',' enumValueOption )* ']'
;
enumValueOption
: optionName '=' constant
;
// message
messageDef
: 'message' messageName messageBody
;
messageBody
: '{' messageElement* '}'
;
messageElement
: field
| enumDef
| messageDef
| optionStatement
| oneof
| mapField
| reserved
| emptyStatement
;
// service
serviceDef
: 'service' serviceName '{' serviceElement* '}'
;
serviceElement
: optionStatement
| rpc
| emptyStatement
;
rpc
: 'rpc' rpcName '(' ( 'stream' )? messageType ')'
'returns' '(' ( 'stream' )? messageType ')'
('{' ( optionStatement | emptyStatement )* '}' | ';')
;
// lexical
constant
: fullIdent
| ('-' | '+' )? intLit
| ( '-' | '+' )? floatLit
| strLit
| boolLit
| blockLit
;
// not specified in specification but used in tests
blockLit
: '{' ( ident ':' constant )* '}'
;
emptyStatement: ';';
// Lexical elements
ident: IDENTIFIER | keywords;
fullIdent: ident ( '.' ident )*;
messageName: ident;
enumName: ident;
fieldName: ident;
oneofName: ident;
mapName: ident;
serviceName: ident;
rpcName: ident;
messageType: ( '.' )? ( ident '.' )* messageName;
enumType: ( '.' )? ( ident '.' )* enumName;
intLit: INT_LIT;
strLit: STR_LIT;
boolLit: BOOL_LIT;
floatLit: FLOAT_LIT;
STR_LIT: ( '\'' ( CHAR_VALUE )*? '\'' ) | ( '"' ( CHAR_VALUE )*? '"' );
fragment CHAR_VALUE: HEX_ESCAPE | OCT_ESCAPE | CHAR_ESCAPE | ~[\u0000\n\\];
fragment HEX_ESCAPE: '\\' ( 'x' | 'X' ) HEX_DIGIT HEX_DIGIT;
fragment OCT_ESCAPE: '\\' OCTAL_DIGIT OCTAL_DIGIT OCTAL_DIGIT;
fragment CHAR_ESCAPE: '\\' ( 'a' | 'b' | 'f' | 'n' | 'r' | 't' | 'v' | '\\' | '\'' | '"' );
BOOL_LIT: 'true' | 'false';
FLOAT_LIT : ( DECIMALS '.' DECIMALS? EXPONENT? | DECIMALS EXPONENT | '.' DECIMALS EXPONENT? ) | 'inf' | 'nan';
fragment EXPONENT : ( 'e' | 'E' ) ('+' | '-')? DECIMALS;
fragment DECIMALS : DECIMAL_DIGIT+;
INT_LIT : DECIMAL_LIT | OCTAL_LIT | HEX_LIT;
fragment DECIMAL_LIT : ( [1-9] ) DECIMAL_DIGIT*;
fragment OCTAL_LIT : '0' OCTAL_DIGIT*;
fragment HEX_LIT : '0' ( 'x' | 'X' ) HEX_DIGIT+ ;
IDENTIFIER: LETTER ( LETTER | DECIMAL_DIGIT )*;
fragment LETTER: [A-Za-z_];
fragment DECIMAL_DIGIT: [0-9];
fragment OCTAL_DIGIT: [0-7];
fragment HEX_DIGIT: [0-9A-Fa-f];
// comments
WS : [ \t\r\n\u000C]+ -> skip;
LINE_COMMENT: '//' ~[\r\n]* -> skip;
COMMENT: '/*' .*? '*/' -> skip;
keywords
: 'syntax'
| 'import'
| 'weak'
| 'public'
| 'package'
| 'option'
| 'repeated'
| 'oneof'
| 'map'
| 'int32'
| 'int64'
| 'uint32'
| 'uint64'
| 'sint32'
| 'sint64'
| 'fixed32'
| 'fixed64'
| 'sfixed32'
| 'sfixed64'
| 'bool'
| 'string'
| 'double'
| 'float'
| 'bytes'
| 'reserved'
| 'to'
| 'max'
| 'enum'
| 'message'
| 'service'
| 'rpc'
| 'stream'
| 'returns'
;
|
fix typo of SPDX-License-Identifier
|
fix typo of SPDX-License-Identifier
|
ANTLR
|
mit
|
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
|
da2ea698702130df2f6f9e43ef25bb8333b02abf
|
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
|
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
|
grammar SQLServerDCLStatement;
import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol;
grant
: grantGeneral | grantDW
;
grantGeneral
: GRANT (ALL PRIVILEGES? | permissionOnColumns ( COMMA permissionOnColumns)*)
(ON (ID COLON COLON)? ID)? TO ids
(WITH GRANT OPTION)? (AS ID)?
;
permissionOnColumns
: permission columnList?
;
permission
: ID *?
;
grantDW
: GRANT permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
TO ids (WITH GRANT OPTION)?
;
classType
: LOGIN | DATABASE | OBJECT | ROLE | SCHEMA | USER
;
revoke
: revokeGeneral | revokeDW
;
revokeGeneral
: REVOKE (GRANT OPTION FOR)?
((ALL PRIVILEGES?)? | permissionOnColumns)
(ON (ID COLON COLON)? ID)?
(TO | FROM) ids (CASCADE)? (AS ID)?
;
revokeDW
: REVOKE permissionWithClass (FROM | TO)? ids CASCADE?
;
permissionWithClass
: permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
;
denyGeneral
: DENY permissionWithClass TO ids CASCADE? (AS ID)?
;
|
grammar SQLServerDCLStatement;
import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol;
grant
: grantGeneral | grantDW
;
grantGeneral
: GRANT (ALL PRIVILEGES? | permissionOnColumns ( COMMA permissionOnColumns)*)
(ON (ID COLON COLON)? ID)? TO ids (WITH GRANT OPTION)? (AS ID)?
;
permissionOnColumns
: permission columnList?
;
permission
: ID *?
;
grantDW
: GRANT permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
TO ids (WITH GRANT OPTION)?
;
classType
: LOGIN | DATABASE | OBJECT | ROLE | SCHEMA | USER
;
revoke
: revokeGeneral | revokeDW
;
revokeGeneral
: REVOKE (GRANT OPTION FOR)? ((ALL PRIVILEGES?)? | permissionOnColumns)
(ON (ID COLON COLON)? ID)? (TO | FROM) ids (CASCADE)? (AS ID)?
;
revokeDW
: REVOKE permissionWithClass (FROM | TO)? ids CASCADE?
;
permissionWithClass
: permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
;
deny
: DENY permissionWithClass TO ids CASCADE? (AS ID)?
;
limitedOptionsList
: DEFAU_SCHEMA EQ_ schemaName | ALLOW_ENCRYPTED_VALUE_MODIFICATIONS EQ_ (ON | OFF)?
;
|
add limitedOptionsList
|
add limitedOptionsList
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
|
0e816dd594d7e1175ab290486883808e04493e18
|
antlr/antlr4/ANTLRv4Lexer.g4
|
antlr/antlr4/ANTLRv4Lexer.g4
|
/*
* [The "BSD license"]
* Copyright (c) 2012-2015 Terence Parr
* Copyright (c) 2012-2015 Sam Harwell
* Copyright (c) 2015 Gerald Rosenberg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* A grammar for ANTLR v4 implemented using v4 syntax
*
* Modified 2015.06.16 gbr
* -- update for compatibility with Antlr v4.5
*/
lexer grammar ANTLRv4Lexer;
options { superClass = LexerAdaptor; }
import LexBasic;
// Standard set of fragments
tokens { TOKEN_REF , RULE_REF , LEXER_CHAR_SET }
channels { OFF_CHANNEL , COMMENT }
// ======================================================
// Lexer specification
//
// -------------------------
// Comments
DOC_COMMENT
: DocComment
;
BLOCK_COMMENT
: BlockComment -> channel (COMMENT)
;
LINE_COMMENT
: LineComment -> channel (COMMENT)
;
// -------------------------
// Integer
//
INT
: DecimalNumeral
;
// -------------------------
// Literal string
//
// ANTLR makes no distinction between a single character literal and a
// multi-character string. All literals are single quote delimited and
// may contain unicode escape sequences of the form \uxxxx, where x
// is a valid hexadecimal number (per Unicode standard).
STRING_LITERAL
: SQuoteLiteral
;
UNTERMINATED_STRING_LITERAL
: USQuoteLiteral
;
// -------------------------
// Arguments
//
// Certain argument lists, such as those specifying call parameters
// to a rule invocation, or input parameters to a rule specification
// are contained within square brackets.
BEGIN_ARGUMENT
: LBrack
{ handleBeginArgument(); }
;
// -------------------------
// Actions
BEGIN_ACTION
: LBrace -> pushMode (Action)
;
// -------------------------
// Keywords
//
// Keywords may not be used as labels for rules or in any other context where
// they would be ambiguous with the keyword vs some other identifier. OPTIONS,
// TOKENS, & CHANNELS blocks are handled idiomatically in dedicated lexical modes.
OPTIONS
: 'options' -> pushMode (Options)
;
TOKENS
: 'tokens' -> pushMode (Tokens)
;
CHANNELS
: 'channels' -> pushMode (Channels)
;
IMPORT
: 'import'
;
FRAGMENT
: 'fragment'
;
LEXER
: 'lexer'
;
PARSER
: 'parser'
;
GRAMMAR
: 'grammar'
;
PROTECTED
: 'protected'
;
PUBLIC
: 'public'
;
PRIVATE
: 'private'
;
RETURNS
: 'returns'
;
LOCALS
: 'locals'
;
THROWS
: 'throws'
;
CATCH
: 'catch'
;
FINALLY
: 'finally'
;
MODE
: 'mode'
;
// -------------------------
// Punctuation
COLON
: Colon
;
COLONCOLON
: DColon
;
COMMA
: Comma
;
SEMI
: Semi
;
LPAREN
: LParen
;
RPAREN
: RParen
;
LBRACE
: LBrace
;
RBRACE
: RBrace
;
RARROW
: RArrow
;
LT
: Lt
;
GT
: Gt
;
ASSIGN
: Equal
;
QUESTION
: Question
;
STAR
: Star
;
PLUS_ASSIGN
: PlusAssign
;
PLUS
: Plus
;
OR
: Pipe
;
DOLLAR
: Dollar
;
RANGE
: Range
;
DOT
: Dot
;
AT
: At
;
POUND
: Pound
;
NOT
: Tilde
;
// -------------------------
// Identifiers - allows unicode rule/token names
ID
: Id
;
// -------------------------
// Whitespace
WS
: Ws+ -> channel (OFF_CHANNEL)
;
// -------------------------
// Illegal Characters
//
// This is an illegal character trap which is always the last rule in the
// lexer specification. It matches a single character of any value and being
// the last rule in the file will match when no other rule knows what to do
// about the character. It is reported as an error but is not passed on to the
// parser. This means that the parser to deal with the gramamr file anyway
// but we will not try to analyse or code generate from a file with lexical
// errors.
//
// Comment this rule out to allow the error to be propagated to the parser
ERRCHAR
: . -> channel (HIDDEN)
;
// ======================================================
// Lexer modes
// -------------------------
// Arguments
mode Argument;
// E.g., [int x, List<String> a[]]
NESTED_ARGUMENT
: LBrack -> type (ARGUMENT_CONTENT) , pushMode (Argument)
;
ARGUMENT_ESCAPE
: EscAny -> type (ARGUMENT_CONTENT)
;
ARGUMENT_STRING_LITERAL
: DQuoteLiteral -> type (ARGUMENT_CONTENT)
;
ARGUMENT_CHAR_LITERAL
: SQuoteLiteral -> type (ARGUMENT_CONTENT)
;
END_ARGUMENT
: RBrack
{ handleEndArgument(); }
;
// added this to return non-EOF token type here. EOF does something weird
UNTERMINATED_ARGUMENT
: EOF -> popMode
;
ARGUMENT_CONTENT
: .
;
// -------------------------
// Actions
//
// Many language targets use {} as block delimiters and so we
// must recursively match {} delimited blocks to balance the
// braces. Additionally, we must make some assumptions about
// literal string representation in the target language. We assume
// that they are delimited by ' or " and so consume these
// in their own alts so as not to inadvertantly match {}.
mode Action;
NESTED_ACTION
: LBrace -> type (ACTION_CONTENT) , pushMode (Action)
;
ACTION_ESCAPE
: EscAny -> type (ACTION_CONTENT)
;
ACTION_STRING_LITERAL
: DQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_CHAR_LITERAL
: SQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_DOC_COMMENT
: DocComment -> type (ACTION_CONTENT)
;
ACTION_BLOCK_COMMENT
: BlockComment -> type (ACTION_CONTENT)
;
ACTION_LINE_COMMENT
: LineComment -> type (ACTION_CONTENT)
;
END_ACTION
: RBrace
{ handleEndAction(); }
;
UNTERMINATED_ACTION
: EOF -> popMode
;
ACTION_CONTENT
: .
;
// -------------------------
mode Options;
OPT_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (COMMENT)
;
OPT_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (COMMENT)
;
OPT_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (COMMENT)
;
OPT_LBRACE
: LBrace
{ handleOptionsLBrace(); }
;
OPT_RBRACE
: RBrace -> type (RBRACE) , popMode
;
OPT_ID
: Id -> type (ID)
;
OPT_DOT
: Dot -> type (DOT)
;
OPT_ASSIGN
: Equal -> type (ASSIGN)
;
OPT_STRING_LITERAL
: SQuoteLiteral -> type (STRING_LITERAL)
;
OPT_INT
: DecimalNumeral -> type (INT)
;
OPT_STAR
: Star -> type (STAR)
;
OPT_SEMI
: Semi -> type (SEMI)
;
OPT_WS
: Ws+ -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode Tokens;
TOK_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (COMMENT)
;
TOK_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (COMMENT)
;
TOK_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (COMMENT)
;
TOK_LBRACE
: LBrace -> type (LBRACE)
;
TOK_RBRACE
: RBrace -> type (RBRACE) , popMode
;
TOK_ID
: Id -> type (ID)
;
TOK_DOT
: Dot -> type (DOT)
;
TOK_COMMA
: Comma -> type (COMMA)
;
TOK_WS
: Ws+ -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode Channels;
// currently same as Tokens mode; distinguished by keyword
CHN_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (COMMENT)
;
CHN_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (COMMENT)
;
CHN_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (COMMENT)
;
CHN_LBRACE
: LBrace -> type (LBRACE)
;
CHN_RBRACE
: RBrace -> type (RBRACE) , popMode
;
CHN_ID
: Id -> type (ID)
;
CHN_DOT
: Dot -> type (DOT)
;
CHN_COMMA
: Comma -> type (COMMA)
;
CHN_WS
: Ws+ -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode LexerCharSet;
LEXER_CHAR_SET_BODY
: (~ [\]\\] | EscAny)+ -> more
;
LEXER_CHAR_SET
: RBrack -> popMode
;
UNTERMINATED_CHAR_SET
: EOF -> popMode
;
// ------------------------------------------------------------------------------
// Grammar specific Keywords, Punctuation, etc.
fragment Id
: NameStartChar NameChar*
;
|
/*
* [The "BSD license"]
* Copyright (c) 2012-2015 Terence Parr
* Copyright (c) 2012-2015 Sam Harwell
* Copyright (c) 2015 Gerald Rosenberg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* A grammar for ANTLR v4 implemented using v4 syntax
*
* Modified 2015.06.16 gbr
* -- update for compatibility with Antlr v4.5
*/
lexer grammar ANTLRv4Lexer;
options { superClass = Antlr2BGF.AntlrParser.LexerAdaptor; }
import LexBasic;
// Standard set of fragments
tokens { TOKEN_REF , RULE_REF , LEXER_CHAR_SET }
channels { OFF_CHANNEL , COMMENT }
// ======================================================
// Lexer specification
//
// -------------------------
// Comments
DOC_COMMENT
: DocComment
;
BLOCK_COMMENT
: BlockComment -> channel (COMMENT)
;
LINE_COMMENT
: LineComment -> channel (COMMENT)
;
// -------------------------
// Integer
//
INT
: DecimalNumeral
;
// -------------------------
// Literal string
//
// ANTLR makes no distinction between a single character literal and a
// multi-character string. All literals are single quote delimited and
// may contain unicode escape sequences of the form \uxxxx, where x
// is a valid hexadecimal number (per Unicode standard).
STRING_LITERAL
: SQuoteLiteral
;
UNTERMINATED_STRING_LITERAL
: USQuoteLiteral
;
// -------------------------
// Arguments
//
// Certain argument lists, such as those specifying call parameters
// to a rule invocation, or input parameters to a rule specification
// are contained within square brackets.
BEGIN_ARGUMENT
: LBrack
{ handleBeginArgument(); }
;
// -------------------------
// Target Language Actions
BEGIN_ACTION
: LBrace -> pushMode (TargetLanguageAction)
;
// -------------------------
// Keywords
//
// Keywords may not be used as labels for rules or in any other context where
// they would be ambiguous with the keyword vs some other identifier. OPTIONS,
// TOKENS, & CHANNELS blocks are handled idiomatically in dedicated lexical modes.
OPTIONS
: 'options' -> pushMode (Options)
;
TOKENS
: 'tokens' -> pushMode (Tokens)
;
CHANNELS
: 'channels' -> pushMode (Channels)
;
IMPORT
: 'import'
;
FRAGMENT
: 'fragment'
;
LEXER
: 'lexer'
;
PARSER
: 'parser'
;
GRAMMAR
: 'grammar'
;
PROTECTED
: 'protected'
;
PUBLIC
: 'public'
;
PRIVATE
: 'private'
;
RETURNS
: 'returns'
;
LOCALS
: 'locals'
;
THROWS
: 'throws'
;
CATCH
: 'catch'
;
FINALLY
: 'finally'
;
MODE
: 'mode'
;
// -------------------------
// Punctuation
COLON
: Colon
;
COLONCOLON
: DColon
;
COMMA
: Comma
;
SEMI
: Semi
;
LPAREN
: LParen
;
RPAREN
: RParen
;
LBRACE
: LBrace
;
RBRACE
: RBrace
;
RARROW
: RArrow
;
LT
: Lt
;
GT
: Gt
;
ASSIGN
: Equal
;
QUESTION
: Question
;
STAR
: Star
;
PLUS_ASSIGN
: PlusAssign
;
PLUS
: Plus
;
OR
: Pipe
;
DOLLAR
: Dollar
;
RANGE
: Range
;
DOT
: Dot
;
AT
: At
;
POUND
: Pound
;
NOT
: Tilde
;
// -------------------------
// Identifiers - allows unicode rule/token names
ID
: Id
;
// -------------------------
// Whitespace
WS
: Ws+ -> channel (OFF_CHANNEL)
;
// -------------------------
// Illegal Characters
//
// This is an illegal character trap which is always the last rule in the
// lexer specification. It matches a single character of any value and being
// the last rule in the file will match when no other rule knows what to do
// about the character. It is reported as an error but is not passed on to the
// parser. This means that the parser to deal with the gramamr file anyway
// but we will not try to analyse or code generate from a file with lexical
// errors.
//
// Comment this rule out to allow the error to be propagated to the parser
ERRCHAR
: . -> channel (HIDDEN)
;
// ======================================================
// Lexer modes
// -------------------------
// Arguments
mode Argument;
// E.g., [int x, List<String> a[]]
NESTED_ARGUMENT
: LBrack -> type (ARGUMENT_CONTENT) , pushMode (Argument)
;
ARGUMENT_ESCAPE
: EscAny -> type (ARGUMENT_CONTENT)
;
ARGUMENT_STRING_LITERAL
: DQuoteLiteral -> type (ARGUMENT_CONTENT)
;
ARGUMENT_CHAR_LITERAL
: SQuoteLiteral -> type (ARGUMENT_CONTENT)
;
END_ARGUMENT
: RBrack
{ handleEndArgument(); }
;
// added this to return non-EOF token type here. EOF does something weird
UNTERMINATED_ARGUMENT
: EOF -> popMode
;
ARGUMENT_CONTENT
: .
;
// -------------------------
// Target Language Actions
//
// Many language targets use {} as block delimiters and so we
// must recursively match {} delimited blocks to balance the
// braces. Additionally, we must make some assumptions about
// literal string representation in the target language. We assume
// that they are delimited by ' or " and so consume these
// in their own alts so as not to inadvertantly match {}.
mode TargetLanguageAction;
NESTED_ACTION
: LBrace -> type (ACTION_CONTENT) , pushMode (TargetLanguageAction)
;
ACTION_ESCAPE
: EscAny -> type (ACTION_CONTENT)
;
ACTION_STRING_LITERAL
: DQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_CHAR_LITERAL
: SQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_DOC_COMMENT
: DocComment -> type (ACTION_CONTENT)
;
ACTION_BLOCK_COMMENT
: BlockComment -> type (ACTION_CONTENT)
;
ACTION_LINE_COMMENT
: LineComment -> type (ACTION_CONTENT)
;
END_ACTION
: RBrace
{ handleEndAction(); }
;
UNTERMINATED_ACTION
: EOF -> popMode
;
ACTION_CONTENT
: .
;
// -------------------------
mode Options;
OPT_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (COMMENT)
;
OPT_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (COMMENT)
;
OPT_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (COMMENT)
;
OPT_LBRACE
: LBrace
{ handleOptionsLBrace(); }
;
OPT_RBRACE
: RBrace -> type (RBRACE) , popMode
;
OPT_ID
: Id -> type (ID)
;
OPT_DOT
: Dot -> type (DOT)
;
OPT_ASSIGN
: Equal -> type (ASSIGN)
;
OPT_STRING_LITERAL
: SQuoteLiteral -> type (STRING_LITERAL)
;
OPT_INT
: DecimalNumeral -> type (INT)
;
OPT_STAR
: Star -> type (STAR)
;
OPT_SEMI
: Semi -> type (SEMI)
;
OPT_WS
: Ws+ -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode Tokens;
TOK_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (COMMENT)
;
TOK_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (COMMENT)
;
TOK_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (COMMENT)
;
TOK_LBRACE
: LBrace -> type (LBRACE)
;
TOK_RBRACE
: RBrace -> type (RBRACE) , popMode
;
TOK_ID
: Id -> type (ID)
;
TOK_DOT
: Dot -> type (DOT)
;
TOK_COMMA
: Comma -> type (COMMA)
;
TOK_WS
: Ws+ -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode Channels;
// currently same as Tokens mode; distinguished by keyword
CHN_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (COMMENT)
;
CHN_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (COMMENT)
;
CHN_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (COMMENT)
;
CHN_LBRACE
: LBrace -> type (LBRACE)
;
CHN_RBRACE
: RBrace -> type (RBRACE) , popMode
;
CHN_ID
: Id -> type (ID)
;
CHN_DOT
: Dot -> type (DOT)
;
CHN_COMMA
: Comma -> type (COMMA)
;
CHN_WS
: Ws+ -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode LexerCharSet;
LEXER_CHAR_SET_BODY
: (~ [\]\\] | EscAny)+ -> more
;
LEXER_CHAR_SET
: RBrack -> popMode
;
UNTERMINATED_CHAR_SET
: EOF -> popMode
;
// ------------------------------------------------------------------------------
// Grammar specific Keywords, Punctuation, etc.
fragment Id
: NameStartChar NameChar*
;
|
Update ANTLRv4Lexer.g4
|
Update ANTLRv4Lexer.g4
Changed the Action mode to TargetLanguageAction to prevent a conflict with the Lexer built-in Action function
|
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
|
d47e1f7beaa85dfec8da2a478e2e0bf095d61b7a
|
src/main/antlr4/YokohamaUnitLexer.g4
|
src/main/antlr4/YokohamaUnitLexer.g4
|
lexer grammar YokohamaUnitLexer;
HASH1: '#' ;
HASH2: '##' ;
HASH3: '###' ;
HASH4: '####' ;
HASH5: '#####' ;
HASH6: '######' ;
TEST: 'Test:' -> mode(TEST_LEADING);
TABLE: 'Table:' -> mode(TABLE_LEADING);
SETUP: 'Setup' -> mode(PHASE_LEADING);
EXERCISE: 'Exercise' -> mode(PHASE_LEADING);
VERIFY: 'Verify' -> mode(PHASE_LEADING);
TEARDOWN: 'Teardown' -> mode(PHASE_LEADING);
BAR: '|' -> mode(IN_TABLE_HEADER) ;
ASSERT: 'Assert' -> mode(IN_THE_MIDDLE_OF_LINE) ;
THAT: 'that' -> mode(IN_THE_MIDDLE_OF_LINE) ;
STOP: '.' -> mode(IN_THE_MIDDLE_OF_LINE) ;
AND: 'and' -> mode(IN_THE_MIDDLE_OF_LINE) ;
IS: 'is' -> mode(IN_THE_MIDDLE_OF_LINE) ;
NOT: 'not' -> mode(IN_THE_MIDDLE_OF_LINE) ;
THROWS: 'throws' -> mode(IN_THE_MIDDLE_OF_LINE) ;
ACCORDING: 'according' -> mode(IN_THE_MIDDLE_OF_LINE) ;
TO: 'to' -> mode(IN_THE_MIDDLE_OF_LINE) ;
FOR: 'for' -> mode(IN_THE_MIDDLE_OF_LINE) ;
ALL: 'all' -> mode(IN_THE_MIDDLE_OF_LINE) ;
RULES: 'rules' -> mode(IN_THE_MIDDLE_OF_LINE) ;
IN: 'in' -> mode(IN_THE_MIDDLE_OF_LINE) ;
UTABLE: 'Table' -> mode(IN_THE_MIDDLE_OF_LINE) ;
CSV: 'CSV' -> mode(IN_THE_MIDDLE_OF_LINE) ;
TSV: 'TSV' -> mode(IN_THE_MIDDLE_OF_LINE) ;
EXCEL: 'Excel' -> mode(IN_THE_MIDDLE_OF_LINE) ;
WHERE: 'where' -> mode(IN_THE_MIDDLE_OF_LINE) ;
EQ: '=' -> mode(IN_THE_MIDDLE_OF_LINE) ;
LET: 'Let' -> mode(IN_THE_MIDDLE_OF_LINE) ;
BE: 'be' -> mode(IN_THE_MIDDLE_OF_LINE) ;
DO: 'Do' -> mode(IN_THE_MIDDLE_OF_LINE) ;
A: 'a' -> mode(IN_THE_MIDDLE_OF_LINE) ;
STUB: 'stub' -> mode(IN_THE_MIDDLE_OF_LINE) ;
OF: 'of' -> mode(IN_THE_MIDDLE_OF_LINE) ;
SUCH: 'such' -> mode(IN_THE_MIDDLE_OF_LINE) ;
METHOD: 'method' -> mode(AFTER_METHOD) ;
RETURNS: 'returns' -> mode(IN_THE_MIDDLE_OF_LINE) ;
Identifier: IdentStart IdentPart* ;
OPENBACKTICK: '`' -> skip, mode(IN_BACKTICK) ;
OPENDOUBLEQUOTE: '"' -> skip, mode(IN_DOUBLEQUOTE) ;
NEW_LINE : ('\r'? '\n')+ -> skip ;
WS : [ \t]+ -> skip ;
mode IN_THE_MIDDLE_OF_LINE;
ASSERT2: 'Assert' -> type(ASSERT) ;
THAT2: 'that' -> type(THAT) ;
STOP2: '.' -> type(STOP) ;
AND2: 'and' -> type(AND) ;
IS2: 'is' -> type(IS) ;
NOT2: 'not' -> type(NOT) ;
THROWS2: 'throws' -> type(THROWS) ;
ACCORDING2: 'according' -> type(ACCORDING) ;
TO2: 'to' -> type(TO) ;
FOR2: 'for' -> type(FOR) ;
ALL2: 'all' -> type(ALL) ;
RULES2: 'rules' -> type(RULES) ;
IN2: 'in' -> type(IN) ;
UTABLE2: 'Table' -> type(UTABLE) ;
CSV2: 'CSV' -> type(CSV) ;
TSV2: 'TSV' -> type(TSV) ;
EXCEL2: 'Excel' -> type(EXCEL) ;
WHERE2: 'where' -> type(WHERE) ;
EQ2: '=' -> type(EQ) ;
LET2: 'Let' -> type(LET) ;
BE2: 'be' -> type(BE) ;
DO2: 'Do' -> type(DO) ;
A2: 'a' -> type(A) ;
STUB2: 'stub' -> type(STUB) ;
OF2: 'of' -> type(OF) ;
SUCH2: 'such' -> type(SUCH) ;
METHOD2: 'method' -> type(METHOD), mode(AFTER_METHOD) ;
RETURNS2: 'returns' -> type(RETURNS) ;
Identifier2 : IdentStart IdentPart* -> type(Identifier);
OPENBACKTICK2: '`' -> skip, mode(IN_BACKTICK) ;
OPENDOUBLEQUOTE2: '"' -> skip, mode(IN_DOUBLEQUOTE) ;
NEW_LINE2 : ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
WS2 : [ \t]+ -> skip ;
mode TEST_LEADING;
WS3: [ \t]+ -> skip, mode(TEST_NAME);
mode TEST_NAME;
TestName: ~[\r\n]+ ;
NEW_LINE_TESTNAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
mode TABLE_LEADING;
WS4: [ \t]+ -> skip, mode(TABLE_NAME);
mode TABLE_NAME;
TableName: ~[\r\n]+ ;
NEW_LINE_TABLENAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
mode PHASE_LEADING;
COLON: ':' [ \t]* -> skip, mode(PHASE_DESCRIPTION) ;
WS5: [ \t]* '\r'? '\n' -> skip, mode(DEFAULT_MODE) ;
mode PHASE_DESCRIPTION;
PhaseDescription: ~[\r\n]+ ;
NEW_LINE_PHASE: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
mode IN_DOUBLEQUOTE;
Quoted: ~["]+ ;
CLOSEDOUBLEQUOTE: '"' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode IN_BACKTICK;
Expr: ~[`]+ /*-> type(Expr)*/ ;
CLOSEBACKTICK: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode IN_TABLE_HEADER;
IDENTHEADER: IdentStart IdentPart* -> type(Identifier) ;
BARH: '|' -> type(BAR) ;
NEWLINE: '\r'? '\n' -> mode(IN_TABLE_ONSET) ;
SPACETAB: [ \t]+ -> skip ;
mode IN_TABLE_CELL;
ExprCell: ~[|\r\n]+ -> type(Expr) ;
BARCELL: '|' -> type(BAR) ;
NEWLINECELL: '\r'? '\n' -> type(NEWLINE), mode(IN_TABLE_ONSET) ;
SPACETABCELL: [ \t]+ -> skip ;
mode IN_TABLE_ONSET;
BARONSET: '|' -> type(BAR), mode(IN_TABLE_CELL) ;
HBAR: '-'+ '\r'? '\n' ;
SPACETAB2: [ \t]+ -> skip ;
NEWLINEONSET: '\r'?'\n' -> skip, mode(DEFAULT_MODE) ;
mode AFTER_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' ;
COMMA: ',' ;
THREEDOTS: '...' ;
DOT: '.' ;
LPAREN: '(' ;
RPAREN: ')' ;
LBRACKET: '[' ;
RBRACKET: ']' ;
Identifier3 : IdentStart IdentPart* -> type(Identifier);
SPACETABNEWLINE2: [ \t\r\n]+ -> skip ;
CLOSEBACKTICK2: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
fragment
IdentStart: ~[\uD800-\uDBFF]
{Character.isJavaIdentifierStart(_input.LA(-1))}?
| [\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
fragment
IdentPart: ~[\uD800-\uDBFF]
{Character.isJavaIdentifierPart(_input.LA(-1))}?
| [\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
|
lexer grammar YokohamaUnitLexer;
HASH1: '#' ;
HASH2: '##' ;
HASH3: '###' ;
HASH4: '####' ;
HASH5: '#####' ;
HASH6: '######' ;
TEST: 'Test:' -> mode(TEST_LEADING);
TABLE: 'Table:' -> mode(TABLE_LEADING);
SETUP: 'Setup' -> mode(PHASE_LEADING);
EXERCISE: 'Exercise' -> mode(PHASE_LEADING);
VERIFY: 'Verify' -> mode(PHASE_LEADING);
TEARDOWN: 'Teardown' -> mode(PHASE_LEADING);
BAR: '|' -> mode(IN_TABLE_HEADER) ;
ASSERT: 'Assert' -> mode(IN_THE_MIDDLE_OF_LINE) ;
THAT: 'that' -> mode(IN_THE_MIDDLE_OF_LINE) ;
STOP: '.' -> mode(IN_THE_MIDDLE_OF_LINE) ;
AND: 'and' -> mode(IN_THE_MIDDLE_OF_LINE) ;
IS: 'is' -> mode(IN_THE_MIDDLE_OF_LINE) ;
NOT: 'not' -> mode(IN_THE_MIDDLE_OF_LINE) ;
THROWS: 'throws' -> mode(IN_THE_MIDDLE_OF_LINE) ;
FOR: 'for' -> mode(IN_THE_MIDDLE_OF_LINE) ;
ALL: 'all' -> mode(IN_THE_MIDDLE_OF_LINE) ;
RULES: 'rules' -> mode(IN_THE_MIDDLE_OF_LINE) ;
IN: 'in' -> mode(IN_THE_MIDDLE_OF_LINE) ;
UTABLE: 'Table' -> mode(IN_THE_MIDDLE_OF_LINE) ;
CSV: 'CSV' -> mode(IN_THE_MIDDLE_OF_LINE) ;
TSV: 'TSV' -> mode(IN_THE_MIDDLE_OF_LINE) ;
EXCEL: 'Excel' -> mode(IN_THE_MIDDLE_OF_LINE) ;
WHERE: 'where' -> mode(IN_THE_MIDDLE_OF_LINE) ;
EQ: '=' -> mode(IN_THE_MIDDLE_OF_LINE) ;
LET: 'Let' -> mode(IN_THE_MIDDLE_OF_LINE) ;
BE: 'be' -> mode(IN_THE_MIDDLE_OF_LINE) ;
DO: 'Do' -> mode(IN_THE_MIDDLE_OF_LINE) ;
A: 'a' -> mode(IN_THE_MIDDLE_OF_LINE) ;
STUB: 'stub' -> mode(IN_THE_MIDDLE_OF_LINE) ;
OF: 'of' -> mode(IN_THE_MIDDLE_OF_LINE) ;
SUCH: 'such' -> mode(IN_THE_MIDDLE_OF_LINE) ;
METHOD: 'method' -> mode(AFTER_METHOD) ;
RETURNS: 'returns' -> mode(IN_THE_MIDDLE_OF_LINE) ;
Identifier: IdentStart IdentPart* ;
OPENBACKTICK: '`' -> skip, mode(IN_BACKTICK) ;
OPENDOUBLEQUOTE: '"' -> skip, mode(IN_DOUBLEQUOTE) ;
NEW_LINE : ('\r'? '\n')+ -> skip ;
WS : [ \t]+ -> skip ;
mode IN_THE_MIDDLE_OF_LINE;
ASSERT2: 'Assert' -> type(ASSERT) ;
THAT2: 'that' -> type(THAT) ;
STOP2: '.' -> type(STOP) ;
AND2: 'and' -> type(AND) ;
IS2: 'is' -> type(IS) ;
NOT2: 'not' -> type(NOT) ;
THROWS2: 'throws' -> type(THROWS) ;
FOR2: 'for' -> type(FOR) ;
ALL2: 'all' -> type(ALL) ;
RULES2: 'rules' -> type(RULES) ;
IN2: 'in' -> type(IN) ;
UTABLE2: 'Table' -> type(UTABLE) ;
CSV2: 'CSV' -> type(CSV) ;
TSV2: 'TSV' -> type(TSV) ;
EXCEL2: 'Excel' -> type(EXCEL) ;
WHERE2: 'where' -> type(WHERE) ;
EQ2: '=' -> type(EQ) ;
LET2: 'Let' -> type(LET) ;
BE2: 'be' -> type(BE) ;
DO2: 'Do' -> type(DO) ;
A2: 'a' -> type(A) ;
STUB2: 'stub' -> type(STUB) ;
OF2: 'of' -> type(OF) ;
SUCH2: 'such' -> type(SUCH) ;
METHOD2: 'method' -> type(METHOD), mode(AFTER_METHOD) ;
RETURNS2: 'returns' -> type(RETURNS) ;
Identifier2 : IdentStart IdentPart* -> type(Identifier);
OPENBACKTICK2: '`' -> skip, mode(IN_BACKTICK) ;
OPENDOUBLEQUOTE2: '"' -> skip, mode(IN_DOUBLEQUOTE) ;
NEW_LINE2 : ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
WS2 : [ \t]+ -> skip ;
mode TEST_LEADING;
WS3: [ \t]+ -> skip, mode(TEST_NAME);
mode TEST_NAME;
TestName: ~[\r\n]+ ;
NEW_LINE_TESTNAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
mode TABLE_LEADING;
WS4: [ \t]+ -> skip, mode(TABLE_NAME);
mode TABLE_NAME;
TableName: ~[\r\n]+ ;
NEW_LINE_TABLENAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
mode PHASE_LEADING;
COLON: ':' [ \t]* -> skip, mode(PHASE_DESCRIPTION) ;
WS5: [ \t]* '\r'? '\n' -> skip, mode(DEFAULT_MODE) ;
mode PHASE_DESCRIPTION;
PhaseDescription: ~[\r\n]+ ;
NEW_LINE_PHASE: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
mode IN_DOUBLEQUOTE;
Quoted: ~["]+ ;
CLOSEDOUBLEQUOTE: '"' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode IN_BACKTICK;
Expr: ~[`]+ /*-> type(Expr)*/ ;
CLOSEBACKTICK: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode IN_TABLE_HEADER;
IDENTHEADER: IdentStart IdentPart* -> type(Identifier) ;
BARH: '|' -> type(BAR) ;
NEWLINE: '\r'? '\n' -> mode(IN_TABLE_ONSET) ;
SPACETAB: [ \t]+ -> skip ;
mode IN_TABLE_CELL;
ExprCell: ~[|\r\n]+ -> type(Expr) ;
BARCELL: '|' -> type(BAR) ;
NEWLINECELL: '\r'? '\n' -> type(NEWLINE), mode(IN_TABLE_ONSET) ;
SPACETABCELL: [ \t]+ -> skip ;
mode IN_TABLE_ONSET;
BARONSET: '|' -> type(BAR), mode(IN_TABLE_CELL) ;
HBAR: '-'+ '\r'? '\n' ;
SPACETAB2: [ \t]+ -> skip ;
NEWLINEONSET: '\r'?'\n' -> skip, mode(DEFAULT_MODE) ;
mode AFTER_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' ;
COMMA: ',' ;
THREEDOTS: '...' ;
DOT: '.' ;
LPAREN: '(' ;
RPAREN: ')' ;
LBRACKET: '[' ;
RBRACKET: ']' ;
Identifier3 : IdentStart IdentPart* -> type(Identifier);
SPACETABNEWLINE2: [ \t\r\n]+ -> skip ;
CLOSEBACKTICK2: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
fragment
IdentStart: ~[\uD800-\uDBFF]
{Character.isJavaIdentifierStart(_input.LA(-1))}?
| [\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
fragment
IdentPart: ~[\uD800-\uDBFF]
{Character.isJavaIdentifierPart(_input.LA(-1))}?
| [\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
|
Remove "according" and "to" tokens
|
Remove "according" and "to" tokens
|
ANTLR
|
mit
|
tkob/yokohamaunit,tkob/yokohamaunit
|
a14bbb54a6f0a46cb74db918a45ca570d8d03c2e
|
agc/agc.g4
|
agc/agc.g4
|
/*
BSD License
Copyright (c) 2013, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
http://www.ibiblio.org/apollo/
*/
/*
thtp://www.ibiblio.org/apollo/hrst/archive/1689.pdf
*/
/*
http://www.ibiblio.org/apollo/assembly_language_manual.html
*/
grammar agc;
prog
: line+
;
line
: comment_line
| blank_line
| instruction_line
| erase_line
| assignment_line
;
blank_line
: label? eol
;
comment_line
: ws? comment eol
;
// an instruction "line" can span many lines in the file, and can have comment lines in the middle of it
instruction_line
: label? ws opcodes (eol comment_line)? argument (eol argument)* eol
;
// erase can be specified with no variable
erase_line
: variable? ws 'ERASE' (ws? expression)* (ws comment)? eol
;
// assignment with no RHS is legal
assignment_line
: variable ws? ('=' | 'EQUALS') (ws? expression)* (ws comment)? eol
;
opcodes
: opcode (ws opcode)?
;
argument
: (ws expression)* (ws comment)?
;
ws
: WS
;
eol
: WS? EOL
;
comment
: COMMENT
;
label
: LABEL
;
variable
: LABEL
| (LPAREN LABEL RPAREN)
;
expression
: multiplyingExpression ((PLUS|MINUS) multiplyingExpression)*
;
multiplyingExpression
: atom ((TIMES|DIV) atom)*
;
atom
: inte
| decimal
| variable
| label
| register
;
inte
: INTE
;
decimal
: ('+' | '-')? DECIMAL
;
register
:'A'
| 'L'
| 'Q'
| 'EB'
| 'FB'
| 'Z'
| 'BB'
| 'ARUPT'
| 'LRUPT'
| 'QRUPT'
| 'QRUPT'
| 'BBRUPT'
| 'BRUPT'
| 'CYR'
| 'SR'
| 'CYL'
| 'EDOP'
| 'TIME2'
| 'TIME1'
| 'TIME3'
| 'TIME4'
| 'TIME5'
| 'TIME6'
| 'CDUX'
| 'CDUY'
| 'CDUZ'
| 'OPTY'
| 'OPTX'
| 'PIPAX'
| 'PIPAY'
| 'PIPAZ'
| 'Q-RHCCTR'
| 'RHCP'
| 'P-RHCCTR'
| 'RHCY'
| 'R-RHCCTR'
| 'RHCR'
| 'INLINK'
| 'RNRAD'
| 'GYROCTR'
| 'GYROCMD'
| 'CDUXCMD'
| 'CDUYCMD'
| 'CDUZCMD'
| 'OPTYCMD'
| 'OPTXCMD'
| 'THRUST'
| 'LEMONM'
| 'OUTLINK'
| 'ALTM'
;
opcode
: standard_opcode
| pseudo_opcode
| axt_opcode
;
// Address to Index
axt_opcode
: 'AXT,1'
| 'AXT,2'
;
pseudo_opcode
: '1DNADR'
| '2DNADR'
| '3DNADR'
| '4DNADR'
| '5DNADR'
| '6DNADR'
| 'DNCHAN'
| 'DNPTR'
| '-1DNADR'
| '-2DNADR'
| '-3DNADR'
| '-4DNADR'
| '-5DNADR'
| '-6DNADR'
| '-DNCHAN'
| '-DNPTR'
| '2DEC'
| '2DEC*'
| '2DNADR'
| '-2DNADR'
| '2FCADR' // embed a double-word constant
| '3DNADR'
| '-3DNADR'
| '4DNADR'
| '-4DNADR'
| '5DNADR'
| '-5DNADR'
| '6DNADR'
| '-6DNADR'
| 'BANK'
| 'BLOCK'
| 'BNKSUM'
| 'COUNT'
| 'COUNT*'
| 'DEC' // embed a single-precision (SP) constant
| '2DEC' // embed a double precision constant
| '2FCADR' // embed a double-word constant, to be used later by the DTCF instruction
| 'OCT' // embed an octal constant
| 'SETLOC'
| 'SUBRO'
;
standard_opcode
: 'TC' // transfer control
| 'TCR' // transfer control
| 'CCS' // Count, Compare, and Skip
| 'TCF' // Transfer Control to Fixed
| 'DAS' // Double Add to Storage
| 'LXCH' // Exchange L and K
| 'INCR' // Increment
| 'AD' // add to accumulator
| 'ADS' // Add to Storage
| 'CA' // Clear and Add
| 'CS' // Clear and Subtract
| 'INDEX' // Index
| 'DXCH' // double exchange
| 'TS' // Transfer to Storage
| 'XCH' // Exchange A and K
| 'AD' // AD
| 'MASK' // Mask A by K
| 'MSK' // Mask A by K
| 'READ' // Read Channel KC
| 'WRITE' // Write Channel KC
| 'RAND' // Read and Mask
| 'WAND' // Write and Mask
| 'ROR' // Read and Superimpose
| 'WOR' // Write and Superimpose
| 'RXOR' // Read and Invert
| 'EDRUPT' // for machine checkout only
| 'BZF' // Branch Zero to Fixed
| 'MSU' // Modular Subtract
| 'QXCH' // Exchange Q and K
| 'AUG' // augment
| 'DIM' // diminish
| 'DCA' // Double Clear and Add
| 'DCS' // Double Clear and Subtract
| 'SU' // subtract
| 'BZMF' // Branch Zero or Minus to Fixed
| 'MP' // Multiply
| 'XXALQ' // Execute Extracode Using A, L, and Q
| 'XLQ' // Execute Using L and Q
| 'RETURN' // Return from Subroutine
| 'RELINT' // Enable Interrupts
| 'INHINT' // Disable Interrupts
| 'EXTEND' // extend
| 'NOOP' // No-operation
| 'DDOUBL' // Double Precision Double
| 'DTCF' // Double Transfer Control, Switching F Bank
| 'COM' // Complement the Contents of A
| 'ZL' // Zero L
| 'RESUME' // Resume Interrupted Program
| 'DTCB' // Double Transfer Control, Switching Both Banks
| 'OVSK' // Overflow Skip
| 'TCAA' // Transfer Control to Address in A
| 'DOUBLE' // Double the Contents of A
| 'ZQ' // Zero Q
| 'DCOM' // Double Complement
| 'SQUARE' // Square the Contents of A
| 'PINC' // Add +1 in 1's-complement fashion to a counter
| 'PCDU' // Add +1 in 2's-complement fashion to a counter.
| 'MINC' // Add -1 in 1's-complement fashion to a counter.
| 'MCDU' // Add -1 in 2's-complement fashion to a counter.
| 'DINC' // look at the docs
| 'SHINC' // look at the docs
| 'SHANC' // look at the docs
| 'INOTRD' // look at the docs
| 'INOTLD' // look at the docs
| 'FETCH' // look at the docs
| 'STORE' // look at the docs
| 'GOJ' // Jump to location 04000 octal.
| 'TCSAJ' // look at the docs
| 'CAF' // Clear and Add Fixed
| 'CAE' // Clear and Add Erasable
| 'CADR'
| 'DMOVE'
| 'VMOVE'
| 'SMOVE'
| 'DSU'
| 'RTB'
| 'ITC'
| 'NOLOD'
| 'EXIT'
| 'BPL'
| 'SIN'
| 'COS'
| 'CAD'
| 'TEST'
| 'VXSC'
| 'ITC'
| 'DAD'
| 'VXV'
| 'VAD'
| 'DAD'
| 'BPL'
| 'DMP'
| 'BOV'
| 'VXV'
| 'VAD'
| 'UNIT'
| 'OCTAL'
| 'ADRES'
| 'ABVAL'
| 'COMP'
| 'DV' // Divide
| 'NDX' // INDEX (alternative syntax)
| 'POUT' // look at the docs
| 'MOUT' // look at the docs
| 'ZOUT' // look at the docs
| 'LODON' // this is used in a couple places in a "2-opcodes on a line" format
| 'TSLT' // this is used in a couple places in a "2-opcodes on a line" format
;
//
// labels can begin with + or -, letters or digits
//
// labels can contain "&" as well as math symbols "+-*/" and "."
//
LABEL
: [a-zA-Z0-9_.+\\-/*=&]+
;
INTE
: [0-9]+ ('DEC' | 'D')
;
DECIMAL
: ([0-9]+ ('.' [0-9]+)?)
| ('.' [0-9]+)
;
COMMENT
: '#' ~[\r\n]*
;
PLUS
: '+'
;
MINUS
: '-'
;
TIMES
: '*'
;
DIV
: '/'
;
COMMA
: ','
;
LPAREN
: '('
;
RPAREN
: ')'
;
EOL
: [\r\n]+
;
WS
: [ \t]+
;
|
/*
BSD License
Copyright (c) 2013, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
http://www.ibiblio.org/apollo/
*/
/*
thtp://www.ibiblio.org/apollo/hrst/archive/1689.pdf
*/
/*
http://www.ibiblio.org/apollo/assembly_language_manual.html
*/
grammar agc;
prog
: line+
;
line
: comment_line
| blank_line
| instruction_line
| erase_line
| assignment_line
;
blank_line
: label? eol
;
comment_line
: ws? comment eol
;
// an instruction "line" can span many lines in the file, and can have comment lines in the middle of it
instruction_line
: label? ws opcodes (eol comment_line)? argument (eol argument)* eol
;
// erase can be specified with no variable
erase_line
: variable? ws 'ERASE' (ws? expression)* (ws comment)? eol
;
// assignment with no RHS is legal
assignment_line
: variable ws? ('=' | 'EQUALS') (ws? expression)* (ws comment)? eol
;
opcodes
: opcode (ws opcode)?
;
argument
: (ws expression)* (ws comment)?
;
ws
: WS
;
eol
: WS? EOL
;
comment
: COMMENT
;
label
: LABEL
;
variable
: LABEL
| (LPAREN LABEL RPAREN)
;
expression
: multiplyingExpression ((PLUS|MINUS) multiplyingExpression)*
;
multiplyingExpression
: atom ((TIMES|DIV) atom)*
;
atom
: inte
| decimal
| variable
| label
| register
;
inte
: INTE
;
decimal
: ('+' | '-')? DECIMAL
;
register
:'A'
| 'L'
| 'Q'
| 'EB'
| 'FB'
| 'Z'
| 'BB'
| 'ARUPT'
| 'LRUPT'
| 'QRUPT'
| 'QRUPT'
| 'BBRUPT'
| 'BRUPT'
| 'CYR'
| 'SR'
| 'CYL'
| 'EDOP'
| 'TIME2'
| 'TIME1'
| 'TIME3'
| 'TIME4'
| 'TIME5'
| 'TIME6'
| 'CDUX'
| 'CDUY'
| 'CDUZ'
| 'OPTY'
| 'OPTX'
| 'PIPAX'
| 'PIPAY'
| 'PIPAZ'
| 'Q-RHCCTR'
| 'RHCP'
| 'P-RHCCTR'
| 'RHCY'
| 'R-RHCCTR'
| 'RHCR'
| 'INLINK'
| 'RNRAD'
| 'GYROCTR'
| 'GYROCMD'
| 'CDUXCMD'
| 'CDUYCMD'
| 'CDUZCMD'
| 'OPTYCMD'
| 'OPTXCMD'
| 'THRUST'
| 'LEMONM'
| 'OUTLINK'
| 'ALTM'
;
opcode
: standard_opcode
| pseudo_opcode
| axt_opcode
;
// Address to Index
axt_opcode
: 'AXT,1'
| 'AXT,2'
;
pseudo_opcode
: '1DNADR'
| '2DNADR'
| '3DNADR'
| '4DNADR'
| '5DNADR'
| '6DNADR'
| 'DNCHAN'
| 'DNPTR'
| '-1DNADR'
| '-2DNADR'
| '-3DNADR'
| '-4DNADR'
| '-5DNADR'
| '-6DNADR'
| '-DNCHAN'
| '-DNPTR'
| '2DEC'
| '2DEC*'
| '2DNADR'
| '-2DNADR'
| '2FCADR' // embed a double-word constant
| '3DNADR'
| '-3DNADR'
| '4DNADR'
| '-4DNADR'
| '5DNADR'
| '-5DNADR'
| '6DNADR'
| '-6DNADR'
| 'BANK'
| 'BLOCK'
| 'BNKSUM'
| 'COUNT'
| 'COUNT*'
| 'DEC' // embed a single-precision (SP) constant
| '2DEC' // embed a double precision constant
| '2FCADR' // embed a double-word constant, to be used later by the DTCF instruction
| 'OCT' // embed an octal constant
| 'SETLOC'
| 'SUBRO'
;
standard_opcode
: 'TC' // transfer control
| 'TCR' // transfer control
| 'CCS' // Count, Compare, and Skip
| 'TCF' // Transfer Control to Fixed
| 'DAS' // Double Add to Storage
| 'LXCH' // Exchange L and K
| 'INCR' // Increment
| 'AD' // add to accumulator
| 'ADS' // Add to Storage
| 'CA' // Clear and Add
| 'CS' // Clear and Subtract
| 'INDEX' // Index
| 'DXCH' // double exchange
| 'TS' // Transfer to Storage
| 'XCH' // Exchange A and K
| 'AD' // AD
| 'MASK' // Mask A by K
| 'MSK' // Mask A by K
| 'READ' // Read Channel KC
| 'WRITE' // Write Channel KC
| 'RAND' // Read and Mask
| 'WAND' // Write and Mask
| 'ROR' // Read and Superimpose
| 'WOR' // Write and Superimpose
| 'RXOR' // Read and Invert
| 'EDRUPT' // for machine checkout only
| 'BZF' // Branch Zero to Fixed
| 'MSU' // Modular Subtract
| 'QXCH' // Exchange Q and K
| 'AUG' // augment
| 'DIM' // diminish
| 'DCA' // Double Clear and Add
| 'DCS' // Double Clear and Subtract
| 'SU' // subtract
| 'BZMF' // Branch Zero or Minus to Fixed
| 'MP' // Multiply
| 'XXALQ' // Execute Extracode Using A, L, and Q
| 'XLQ' // Execute Using L and Q
| 'RETURN' // Return from Subroutine
| 'RELINT' // Enable Interrupts
| 'INHINT' // Disable Interrupts
| 'EXTEND' // extend
| 'NOOP' // No-operation
| 'DDOUBL' // Double Precision Double
| 'DTCF' // Double Transfer Control, Switching F Bank
| 'COM' // Complement the Contents of A
| 'ZL' // Zero L
| 'RESUME' // Resume Interrupted Program
| 'DTCB' // Double Transfer Control, Switching Both Banks
| 'OVSK' // Overflow Skip
| 'TCAA' // Transfer Control to Address in A
| 'DOUBLE' // Double the Contents of A
| 'ZQ' // Zero Q
| 'DCOM' // Double Complement
| 'SQUARE' // Square the Contents of A
| 'PINC' // Add +1 in 1's-complement fashion to a counter
| 'PCDU' // Add +1 in 2's-complement fashion to a counter.
| 'MINC' // Add -1 in 1's-complement fashion to a counter.
| 'MCDU' // Add -1 in 2's-complement fashion to a counter.
| 'DINC' // look at the docs
| 'SHINC' // look at the docs
| 'SHANC' // look at the docs
| 'INOTRD' // look at the docs
| 'INOTLD' // look at the docs
| 'FETCH' // look at the docs
| 'STORE' // look at the docs
| 'GOJ' // Jump to location 04000 octal.
| 'TCSAJ' // look at the docs
| 'CAF' // Clear and Add Fixed
| 'CAE' // Clear and Add Erasable
| 'CADR'
| 'DMOVE'
| 'VMOVE'
| 'SMOVE'
| 'DSU'
| 'RTB'
| 'ITC'
| 'NOLOD'
| 'EXIT'
| 'BPL'
| 'SIN'
| 'COS'
| 'CAD'
| 'TEST'
| 'VXSC'
| 'ITC'
| 'DAD'
| 'VXV'
| 'VAD'
| 'DAD'
| 'BPL'
| 'DMP'
| 'BOV'
| 'VXV'
| 'VAD'
| 'UNIT'
| 'OCTAL'
| 'ADRES'
| 'ABVAL'
| 'COMP'
| 'DV' // Divide
| 'NDX' // INDEX (alternative syntax)
| 'POUT' // look at the docs
| 'MOUT' // look at the docs
| 'ZOUT' // look at the docs
| 'LODON' // this is used in a couple places in a "2-opcodes on a line" format
| 'TSLT' // this is used in a couple places in a "2-opcodes on a line" format
;
//
// labels can begin with + or -, letters or digits
//
// labels can contain "&" as well as math symbols "+-*/" and "."
//
LABEL
: [a-zA-Z0-9_.+\\\-/*=&]+
;
INTE
: [0-9]+ ('DEC' | 'D')
;
DECIMAL
: ([0-9]+ ('.' [0-9]+)?)
| ('.' [0-9]+)
;
COMMENT
: '#' ~[\r\n]*
;
PLUS
: '+'
;
MINUS
: '-'
;
TIMES
: '*'
;
DIV
: '/'
;
COMMA
: ','
;
LPAREN
: '('
;
RPAREN
: ')'
;
EOL
: [\r\n]+
;
WS
: [ \t]+
;
|
fix to agc
|
fix to agc
|
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
|
41116f80391e397b85c6bb4566c1d3163dfa29b7
|
grammars/SimpleXML.g4
|
grammars/SimpleXML.g4
|
grammar SimpleXML;
document : prolog? comment? element
;
prolog : '<?xml ' attribute* '?>';
comment : '<!--' TEXT '-->'
;
element : LT Name attribute* '>' content* '</' Name '>'
| '<' Name attribute* '/>'
;
attribute : Name '="' TEXT '"'
;
content : TEXT
| element
| comment
| CDATA
;
Name : NameStartChar NameChar*
;
fragment
DIGIT : [0-9]
;
fragment
NameChar : NameStartChar
| '-'
| '_'
| '.'
| DIGIT
;
fragment
NameStartChar
: [:a-zA-Z]
;
LT : '<'
;
TEXT : ~[<"]*
;
CDATA : '<![CDATA[' .*? ']]>'
;
|
grammar SimpleXML;
document : prolog? comment? element
;
prolog : '<?xml ' attribute* '?>';
comment : '<!--' TEXT '-->'
;
element : '<' Name attribute* '>' content* '</' Name '>'
| '<' Name attribute* '/>'
;
attribute : Name '="' TEXT '"'
;
content : TEXT
| element
| comment
| CDATA
;
Name : NameStartChar NameChar*
;
fragment
DIGIT : [0-9]
;
fragment
NameChar : NameStartChar
| '-'
| '_'
| '.'
| DIGIT
;
fragment
NameStartChar
: [:a-zA-Z]
;
TEXT : ~[<"]*
;
CDATA : '<![CDATA[' .*? ']]>'
;
|
Fix up SimpleXML grammar as it appears in the thesis
|
Fix up SimpleXML grammar as it appears in the thesis
|
ANTLR
|
apache-2.0
|
premun/ingrid
|
b45ce1cb43f9c45881caa583b054f2e72943e44c
|
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 (EQ|NEQ) primitiveLiteral # propTestEqual
| objectPath (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?
;
// The following two simple rules are for programmer convenience: you
// will get "notification" of object path components in order by the
// generated parser, which enables incremental processing during
// parsing.
objectType
: Identifier
;
firstPathComponent
: Identifier
;
objectPathComponent
: <assoc=left> objectPathComponent objectPathComponent # pathStep
| '.' Identifier # 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.
Identifier :
'"' (~'"' | '""')* '"'
| [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 (EQ|NEQ) primitiveLiteral # propTestEqual
| objectPath (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?
;
// The following two simple rules are for programmer convenience: you
// will get "notification" of object path components in order by the
// generated parser, which enables incremental processing during
// parsing.
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
;
|
Update to disallow unquoted hyphens in property names.
|
Update to disallow unquoted hyphens in property names.
|
ANTLR
|
bsd-3-clause
|
oasis-open/cti-stix2-json-schemas
|
3f401b10a3033427efb06360d2ad3738c8512df9
|
src/main/antlr/mrtim/sasscompiler/grammar/Sass.g4
|
src/main/antlr/mrtim/sasscompiler/grammar/Sass.g4
|
grammar Sass;
NL : '\r'? '\n' -> skip;
WS : (' ' | '\t' | NL) -> skip;
COMMENT_START: '/*';
COMMENT_END: '*/';
COMMENT: COMMENT_START .*? COMMENT_END;
LINE_COMMENT : '//' ~[\r\n]* NL? -> skip;
DSTRING : '"' ('\\"' | ~'"')* '"';
SSTRING : '\'' ('\\\'' | ~'\'')* '\'';
URL : 'url(' ~[)]* ')';
COMMA : ',';
SEMICOLON: ';';
LPAREN: '(';
RPAREN: ')';
LBRACE: '{';
RBRACE: '}';
LSQBRACKET: '[';
RSQBRACKET: ']';
DOLLAR: '$';
EQUALS: '=';
COLON: ':';
STAR: '*';
BAR: '|';
DOT: '.';
IMPORT_KW : '@import';
MIXIN_KW: '@mixin';
FUNCTION_KW: '@function';
INCLUDE_KW: '@include';
//CSS constants
EVEN_KW: 'even';
ODD_KW: 'odd';
PSEUDO_NOT_KW: ':not';
DIMENSION : 'px';
DIGITS: [0-9]+;
PLUS: '+';
MINUS: '-';
DIVIDE: '/';
IDENTIFIER: [&a-zA-Z][a-zA-Z0-9_-]*;
VARIABLE: '$' IDENTIFIER;
TILDE: '~';
RARROW: '>';
PIPE: '|';
CARET: '^';
HASH: '#';
PERCENT: '%';
ID_NAME: HASH IDENTIFIER;
CLASS_NAME: DOT IDENTIFIER;
string: DSTRING | SSTRING;
import_target: URL | string;
import_statement : IMPORT_KW
import_target ( ',' import_target )*
SEMICOLON;
definition : ( MIXIN_KW | FUNCTION_KW)
IDENTIFIER
parameter_def_list
block_body
;
include_statement : INCLUDE_KW IDENTIFIER parameter_list? SEMICOLON;
parameter_def_list: LPAREN ( COMMENT? variable_def COMMENT? (COMMA COMMENT? variable_def COMMENT?)* )? RPAREN;
parameter_list: LPAREN ( parameter (COMMA parameter)* )? RPAREN;
parameter: (IDENTIFIER | variable_def | value);
variable_def: VARIABLE (COMMENT? COLON COMMENT? expression_list)?;
//selectors: L309-532
//selector_schema: parser.cpp:309
//selector_group: parser.cpp:336
selector_list: selector_combination (COMMA selector_combination)*;
//selector_combination: parser.cpp:362
selector_combination: simple_selector (selector_combinator selector_combination)*
| non_blank_combinator simple_selector (selector_combinator selector_combination)*;
non_blank_combinator : (PLUS | TILDE | RARROW);
selector_combinator : (non_blank_combinator | );
//simple_selector_sequence: parser.cpp:399
//simple_selector_sequence: simple_selector+;
//simple_selector: parser.cpp:426
simple_selector: tag (simple_selector_element)*
| simple_selector_element+;
tag: IDENTIFIER;
simple_selector_element: (ID_NAME | CLASS_NAME)
| negated_selector
| pseudo_selector
| attribute_selector
| placeholder_selector;
placeholder_selector: PERCENT IDENTIFIER;
//negated_selector: parser.cpp:453
negated_selector: PSEUDO_NOT_KW LPAREN selector_list RPAREN;
//pseudo_selector: parser.cpp:464
pseudo_selector: ((pseudo_prefix)? functional
((EVEN_KW | ODD_KW)
| binomial
| IDENTIFIER
| string
)?
RPAREN
)
| pseudo_prefix IDENTIFIER;
pseudo_prefix: COLON COLON?;
functional: IDENTIFIER LPAREN;
binomial: integer IDENTIFIER (PLUS DIGITS)?;
//attribute_selector: parser.cpp:517
attribute_selector: LSQBRACKET type_selector ((TILDE | PIPE | STAR | CARET | DOLLAR)? EQUALS (string | IDENTIFIER))? RSQBRACKET;
type_selector: namespace_prefix? IDENTIFIER;
namespace_prefix: (IDENTIFIER | STAR) BAR;
variable: variable_def SEMICOLON;
//parser.cpp:534
block_body: LBRACE
(
COMMENT
| import_statement // not allowed inside mixins and functions
| assignment
| ruleset
| include_statement
| variable
)*
RBRACE;
variable_assignment: VARIABLE COLON expression_list SEMICOLON;
css_identifier: MINUS? IDENTIFIER;
assignment: css_identifier COLON expression_list SEMICOLON;
expression_list: expression ( expression )*
| expression_list COMMA expression_list;
expression: expression STAR expression
| expression DIVIDE expression
| expression PLUS expression
| expression MINUS expression
| value
| LPAREN expression_list RPAREN;
value : (VARIABLE | IDENTIFIER | string | integer ( DIMENSION | PERCENT)? | URL | builtin_call);
builtin_call: IDENTIFIER parameter_list;
integer: (PLUS | MINUS)? DIGITS;
ruleset: selector_list block_body;
top_level: (
COMMENT
| import_statement
| definition
| ruleset
| variable
| include_statement
);
sass_file : top_level*;
|
grammar Sass;
NL : '\r'? '\n' -> skip;
WS : (' ' | '\t' | NL) -> skip;
COMMENT_START: '/*';
COMMENT_END: '*/';
COMMENT: COMMENT_START .*? COMMENT_END;
LINE_COMMENT : '//' ~[\r\n]* NL? -> skip;
DSTRING : '"' ('\\"' | ~'"')* '"';
SSTRING : '\'' ('\\\'' | ~'\'')* '\'';
URL : 'url(' ~[)]* ')';
COMMA : ',';
SEMICOLON: ';';
LPAREN: '(';
RPAREN: ')';
LBRACE: '{';
RBRACE: '}';
LSQBRACKET: '[';
RSQBRACKET: ']';
DOLLAR: '$';
EQUALS: '=';
COLON: ':';
STAR: '*';
BAR: '|';
DOT: '.';
IMPORT_KW : '@import';
MIXIN_KW: '@mixin';
FUNCTION_KW: '@function';
INCLUDE_KW: '@include';
//CSS constants
EVEN_KW: 'even';
ODD_KW: 'odd';
PSEUDO_NOT_KW: ':not';
DIMENSION : 'px' | 'pt' | 'em' | 'en' | 'ex';
DIGITS: [0-9]+;
PLUS: '+';
MINUS: '-';
DIVIDE: '/';
IDENTIFIER: [&a-zA-Z][a-zA-Z0-9_-]*;
VARIABLE: '$' IDENTIFIER;
TILDE: '~';
RARROW: '>';
PIPE: '|';
CARET: '^';
HASH: '#';
PERCENT: '%';
ID_NAME: HASH IDENTIFIER;
CLASS_NAME: DOT IDENTIFIER;
string: DSTRING | SSTRING;
import_target: URL | string;
import_statement : IMPORT_KW
import_target ( ',' import_target )*
SEMICOLON;
definition : ( MIXIN_KW | FUNCTION_KW)
IDENTIFIER
parameter_def_list
block_body
;
include_statement : INCLUDE_KW IDENTIFIER parameter_list? SEMICOLON;
parameter_def_list: LPAREN ( COMMENT? variable_def COMMENT? (COMMA COMMENT? variable_def COMMENT?)* )? RPAREN;
parameter_list: LPAREN ( parameter (COMMA parameter)* )? RPAREN;
parameter: (IDENTIFIER | variable_def | value);
variable_def: VARIABLE (COMMENT? COLON COMMENT? expression_list)?;
//selectors: L309-532
//selector_schema: parser.cpp:309
//selector_group: parser.cpp:336
selector_list: selector_combination (COMMA selector_combination)*;
//selector_combination: parser.cpp:362
selector_combination: simple_selector (selector_combinator selector_combination)*
| non_blank_combinator simple_selector (selector_combinator selector_combination)*;
non_blank_combinator : (PLUS | TILDE | RARROW);
selector_combinator : (non_blank_combinator | );
//simple_selector_sequence: parser.cpp:399
//simple_selector_sequence: simple_selector+;
//simple_selector: parser.cpp:426
simple_selector: tag (simple_selector_element)*
| simple_selector_element+;
tag: IDENTIFIER;
simple_selector_element: (ID_NAME | CLASS_NAME)
| negated_selector
| pseudo_selector
| attribute_selector
| placeholder_selector;
placeholder_selector: PERCENT IDENTIFIER;
//negated_selector: parser.cpp:453
negated_selector: PSEUDO_NOT_KW LPAREN selector_list RPAREN;
//pseudo_selector: parser.cpp:464
pseudo_selector: ((pseudo_prefix)? functional
((EVEN_KW | ODD_KW)
| binomial
| IDENTIFIER
| string
)?
RPAREN
)
| pseudo_prefix IDENTIFIER;
pseudo_prefix: COLON COLON?;
functional: IDENTIFIER LPAREN;
binomial: integer IDENTIFIER (PLUS DIGITS)?;
//attribute_selector: parser.cpp:517
attribute_selector: LSQBRACKET type_selector ((TILDE | PIPE | STAR | CARET | DOLLAR)? EQUALS (string | IDENTIFIER))? RSQBRACKET;
type_selector: namespace_prefix? IDENTIFIER;
namespace_prefix: (IDENTIFIER | STAR) BAR;
variable: variable_def SEMICOLON;
//parser.cpp:534
block_body: LBRACE
(
COMMENT
| import_statement // not allowed inside mixins and functions
| assignment
| ruleset
| include_statement
| variable
)*
RBRACE;
variable_assignment: VARIABLE COLON expression_list SEMICOLON;
css_identifier: MINUS? IDENTIFIER;
assignment: css_identifier COLON expression_list SEMICOLON;
expression_list: expression ( expression )*
| expression_list COMMA expression_list;
expression: expression STAR expression
| expression DIVIDE expression
| expression PLUS expression
| expression MINUS expression
| value
| LPAREN expression_list RPAREN;
value : (VARIABLE | IDENTIFIER | string | number | dimension | percentage | URL | builtin_call);
number: integer;
dimension: number DIMENSION;
percentage: number PERCENT;
builtin_call: IDENTIFIER parameter_list;
integer: (PLUS | MINUS)? DIGITS;
ruleset: selector_list block_body;
top_level: (
COMMENT
| import_statement
| definition
| ruleset
| variable
| include_statement
);
sass_file : top_level*;
|
Tidy up definition of value a little
|
Tidy up definition of value a little
|
ANTLR
|
mit
|
mr-tim/sass-compiler,mr-tim/sass-compiler
|
afd2e3c374e716f9d32ed8df3d730c09e8c6c463
|
src/main/antlr4/YokohamaUnitParser.g4
|
src/main/antlr4/YokohamaUnitParser.g4
|
parser grammar YokohamaUnitParser;
options { tokenVocab=YokohamaUnitLexer; }
group: abbreviation* definition* ;
abbreviation: STAR_LBRACKET ShortName RBRACKET_COLON Line ;
definition: test
| fourPhaseTest
| tableDef
| codeBlock
| heading
;
test: TEST Line assertion+ ;
assertion: ASSERT THAT? propositions condition? STOP ;
propositions: proposition (AND THAT? proposition)* ;
proposition: subject predicate ;
subject: quotedExpr | invokeExpr ;
predicate: isPredicate | isNotPredicate | throwsPredicate ;
isPredicate: IS matcher ;
isNotPredicate: IS NOT matcher ;
throwsPredicate: THROWS matcher ;
matcher: equalTo | instanceOf | instanceSuchThat | nullValue ;
equalTo: argumentExpr ;
instanceOf: AN_INSTANCE_OF_BACK_TICK classType BACK_TICK;
instanceSuchThat: AN_INSTANCE Identifier OF BACK_TICK classType BACK_TICK SUCH THAT proposition (AND proposition)*;
nullValue: NULL | NOTHING ;
condition: forAll
| bindings
;
forAll: FOR ALL vars IN tableRef ;
vars: Identifier ((COMMA Identifier)* AND Identifier)? ;
tableRef: UTABLE LBRACKET Anchor RBRACKET
| CSV_SINGLE_QUOTE FileName SINGLE_QUOTE
| TSV_SINGLE_QUOTE FileName SINGLE_QUOTE
| EXCEL_SINGLE_QUOTE BookName SINGLE_QUOTE
;
bindings: WHERE binding (AND binding)* ;
binding: Identifier (EQ | IS) expr ;
fourPhaseTest: TEST Line setup? exercise? verify teardown? ;
setup: SETUP Line? (letStatement+ statement* | statement+) ;
exercise: EXERCISE Line? statement+ ;
verify: VERIFY Line? assertion+ ;
teardown: TEARDOWN Line? statement+ ;
letStatement: LET letBinding (AND letBinding)* STOP ;
letBinding: Identifier (EQ | BE) expr ;
statement: execution | invoke ;
execution: DO quotedExpr (AND quotedExpr)* STOP ;
invoke: INVOKE_TICK classType (DOT | HASH) methodPattern BACK_TICK
( ON quotedExpr)?
( WITH argumentExpr (COMMA argumentExpr)* )? ;
tableDef: LBRACKET Anchor RBRACKET header HBAR? rows
| header HBAR? rows LBRACKET Anchor RBRACKET ;
header: (BAR Identifier)+ BAR_EOL ;
rows: row+ ;
row: (BAR argumentExpr)+ BAR_EOL ;
expr: quotedExpr
| stubExpr
| invokeExpr
| integerExpr
| floatingPointExpr
| booleanExpr
| charExpr
| stringExpr
| anchorExpr
;
quotedExpr: BACK_TICK Expr BACK_TICK ;
stubExpr: A_STUB_OF_BACK_TICK classType BACK_TICK ( SUCH THAT stubBehavior (AND stubBehavior)* )? ;
stubBehavior: METHOD_BACK_TICK methodPattern BACK_TICK RETURNS expr ;
methodPattern: Identifier LPAREN (type COMMA)* (type THREEDOTS?)? RPAREN ;
type : nonArrayType (LBRACKET RBRACKET)* ;
nonArrayType: primitiveType | classType ;
primitiveType: BOOLEAN | BYTE | SHORT | INT | LONG | CHAR | FLOAT | DOUBLE ;
classType: Identifier (DOT Identifier)* ;
invokeExpr: AN_INVOCATION_OF_BACK_TICK classType (DOT | HASH) methodPattern BACK_TICK
( ON quotedExpr)?
( WITH argumentExpr (COMMA argumentExpr)* )? ;
argumentExpr: quotedExpr
| integerExpr
| floatingPointExpr
| booleanExpr
| charExpr
| stringExpr
| anchorExpr
;
integerExpr: MINUS? Integer ;
floatingPointExpr: MINUS? FloatingPoint ;
booleanExpr: TRUE | FALSE ;
charExpr: SINGLE_QUOTE Char SINGLE_QUOTE ;
stringExpr: DOUBLE_QUOTE Str DOUBLE_QUOTE | EMPTY_STRING ;
anchorExpr: LBRACKET Anchor RBRACKET ;
codeBlock: heading BACK_TICKS attributes CodeLine* BACK_TICKS ;
attributes: CodeLine ;
heading: HASHES Line ;
|
parser grammar YokohamaUnitParser;
options { tokenVocab=YokohamaUnitLexer; }
group: abbreviation* definition* ;
abbreviation: STAR_LBRACKET ShortName RBRACKET_COLON Line ;
definition: test
| fourPhaseTest
| tableDef
| codeBlock
| heading
;
test: TEST Line assertion+ ;
assertion: ASSERT THAT? propositions condition? STOP ;
propositions: proposition (AND THAT? proposition)* ;
proposition: subject predicate ;
subject: quotedExpr | invokeExpr ;
predicate: isPredicate | isNotPredicate | throwsPredicate ;
isPredicate: IS matcher ;
isNotPredicate: IS NOT matcher ;
throwsPredicate: THROWS matcher ;
matcher: equalTo | instanceOf | instanceSuchThat | nullValue ;
equalTo: argumentExpr ;
instanceOf: AN_INSTANCE_OF_BACK_TICK classType BACK_TICK;
instanceSuchThat: AN_INSTANCE Identifier OF BACK_TICK classType BACK_TICK SUCH THAT proposition (AND proposition)*;
nullValue: NULL | NOTHING ;
condition: forAll
| bindings
;
forAll: FOR ALL vars IN tableRef ;
vars: Identifier ((COMMA Identifier)* AND Identifier)? ;
tableRef: UTABLE LBRACKET Anchor RBRACKET
| CSV_SINGLE_QUOTE FileName SINGLE_QUOTE
| TSV_SINGLE_QUOTE FileName SINGLE_QUOTE
| EXCEL_SINGLE_QUOTE BookName SINGLE_QUOTE
;
bindings: WHERE binding (AND binding)* ;
binding: Identifier (EQ | IS) expr ;
fourPhaseTest: TEST Line setup? exercise? verify teardown? ;
setup: SETUP Line? (letStatement+ statement* | statement+) ;
exercise: EXERCISE Line? statement+ ;
verify: VERIFY Line? assertion+ ;
teardown: TEARDOWN Line? statement+ ;
letStatement: LET letBinding (AND letBinding)* STOP ;
letBinding: Identifier (EQ | BE) expr ;
statement: execution | invoke ;
execution: DO quotedExpr (AND quotedExpr)* STOP ;
invoke: INVOKE_TICK classType (DOT | HASH) methodPattern BACK_TICK
( ON quotedExpr)?
( WITH argumentExpr (COMMA argumentExpr)* )?
STOP;
tableDef: LBRACKET Anchor RBRACKET header HBAR? rows
| header HBAR? rows LBRACKET Anchor RBRACKET ;
header: (BAR Identifier)+ BAR_EOL ;
rows: row+ ;
row: (BAR argumentExpr)+ BAR_EOL ;
expr: quotedExpr
| stubExpr
| invokeExpr
| integerExpr
| floatingPointExpr
| booleanExpr
| charExpr
| stringExpr
| anchorExpr
;
quotedExpr: BACK_TICK Expr BACK_TICK ;
stubExpr: A_STUB_OF_BACK_TICK classType BACK_TICK ( SUCH THAT stubBehavior (AND stubBehavior)* )? ;
stubBehavior: METHOD_BACK_TICK methodPattern BACK_TICK RETURNS expr ;
methodPattern: Identifier LPAREN (type COMMA)* (type THREEDOTS?)? RPAREN ;
type : nonArrayType (LBRACKET RBRACKET)* ;
nonArrayType: primitiveType | classType ;
primitiveType: BOOLEAN | BYTE | SHORT | INT | LONG | CHAR | FLOAT | DOUBLE ;
classType: Identifier (DOT Identifier)* ;
invokeExpr: AN_INVOCATION_OF_BACK_TICK classType (DOT | HASH) methodPattern BACK_TICK
( ON quotedExpr)?
( WITH argumentExpr (COMMA argumentExpr)* )? ;
argumentExpr: quotedExpr
| integerExpr
| floatingPointExpr
| booleanExpr
| charExpr
| stringExpr
| anchorExpr
;
integerExpr: MINUS? Integer ;
floatingPointExpr: MINUS? FloatingPoint ;
booleanExpr: TRUE | FALSE ;
charExpr: SINGLE_QUOTE Char SINGLE_QUOTE ;
stringExpr: DOUBLE_QUOTE Str DOUBLE_QUOTE | EMPTY_STRING ;
anchorExpr: LBRACKET Anchor RBRACKET ;
codeBlock: heading BACK_TICKS attributes CodeLine* BACK_TICKS ;
attributes: CodeLine ;
heading: HASHES Line ;
|
STOP was missing
|
Fix: STOP was missing
|
ANTLR
|
mit
|
tkob/yokohamaunit,tkob/yokohamaunit
|
cf8befd558627f94d4b30db32a9c2b8531d60f95
|
source/src/HML.g4
|
source/src/HML.g4
|
grammar HML;
hybridModel
: signalDeclaration*
variableDeclaration*
template*
program
EOF
;
template
: 'Template' ID formalParameters parStatement;
formalParameters
: '(' formalParameterDecls? ')'
;
formalParameterDecls
: type formalParameterDeclsRest
;
formalParameterDeclsRest
: variableDeclaratorId (',' formalParameterDecls)?
;
variableDeclaratorId
: ID ('[' ']')*
;
type
: primitiveType ('[' ']')*
;
primitiveType
: 'boolean'
| 'int'
| 'float'
;
signalDeclaration
: 'Signal' ('[' size=INT ']')* ID (',' ID)* ';'
;
modifier
: 'final' // used for the vars that cannot be modified
;
variableDeclaration
: modifier? type variableDeclarators ';'
;
variableDeclarators
: variableDeclarator (',' variableDeclarator)*
;
variableDeclarator
: variableDeclaratorId ('=' variableInitializer)?
;
variableInitializer
: arrayInitializer
| expr
;
arrayInitializer
: '{' (variableInitializer (',' variableInitializer)* (',')? )? '}'
| 'new' 'Array' ('[' INT ']')+
;
program : 'Main ' '{' signalDeclaration* variableDeclaration* blockStatement* '}';
blockStatement
: atom #AtomPro // Atomic
| blockStatement '|' blockStatement #NonCh // non-deterministrate choice
| blockStatement '||' blockStatement #ParaCom // parallel composition
| blockStatement ';' blockStatement #SeqCom // sequential composition
| '(' blockStatement '<' expr '>' blockStatement ')' #ConCh // conditional choice
| equation 'until' guard #Ode // differential equation
| 'when' '(' guardedchoice ')' #WhenPro // when program
| 'while' parExpression parStatement #LoopPro // loop
| 'if' parExpression parStatement
'else' parStatement #IfPro // if statement
| ID '(' exprList? ')' #CallTem // call template
| parStatement #ParPro // program with paraentheses outside
;
parStatement
: '{' blockStatement '}'
| '(' blockStatement ')'
;
exprList
: expr (',' expr)* ; // arg list
atom
: 'skip'
| ID '=' expr
| '!' ID
| 'suspend' '(' time=expr ')'
;
expr
: ID
| INT
| FLOAT
|'true'
| 'false'
| ('-' | '~') expr // negtive and negation
| expr ('*'|'/'|'mod') expr // % is mod
| expr ('+'|'-') expr
| expr ('>=' | '>' | '==' | '<' | '<=') expr
| expr 'and' expr
| expr 'or' expr
| 'floor' '(' expr ')'
| 'ceil' '(' expr ')'
| parExpression
;
parExpression
: '(' expr ')'
;
equation
: relation
| relation 'init' expr
| equation '||' equation
;
relation
: 'dot' ID '==' expr;
guard
: 'EMPTY'
| signal
| expr
| 'timeout' '(' expr ')'
| guard '<and>' guard
| guard '<or>' guard
| '(' guard ')'
;
signal
: ID ('[' expr ']')*;
guardedchoice
: guard '&' program
| guardedchoice '[]' guardedchoice
;
COMOP
: '>='
| '>'
| '=='
| '<'
| '<='
;
ID : (LETTER | '_') (LETTER|DIGIT|'_')*
;
fragment LETTER : [a-zA-Z] ;
INT : DIGIT+ ;
FLOAT : DIGIT+ '.' DIGIT+
;
fragment
DIGIT: '0'..'9' ;
COMMENT
: '/*' .*? '*/' -> channel(HIDDEN) // match anything between /* and */
;
LINE_COMMENT
: '//' ~[\r\n]* '\r'? '\n' -> channel(HIDDEN)
;
WS : [ \r\t\u000C\n]+ -> channel(HIDDEN)
;
|
grammar HML;
hybridModel
: signalDeclaration*
variableDeclaration*
template*
program
EOF
;
template
: 'Template' ID formalParameters parStatement;
formalParameters
: '(' formalParameterDecls? ')'
;
formalParameterDecls
: type formalParameterDeclsRest
;
formalParameterDeclsRest
: variableDeclaratorId (',' formalParameterDecls)?
;
variableDeclaratorId
: ID ('[' ']')*
;
type
: primitiveType ('[' ']')*
;
primitiveType
: 'boolean'
| 'int'
| 'float'
;
signalDeclaration
: 'Signal' ('[' size=INT ']')* ID (',' ID)* ';'
;
modifier
: 'final' // used for the vars that cannot be modified
;
variableDeclaration
: modifier? type variableDeclarators ';'
;
variableDeclarators
: variableDeclarator (',' variableDeclarator)*
;
variableDeclarator
: variableDeclaratorId ('=' variableInitializer)?
;
variableInitializer
: arrayInitializer
| expr
;
arrayInitializer
: '{' (variableInitializer (',' variableInitializer)* (',')? )? '}'
| 'new' 'Array' ('[' INT ']')+
;
program : 'Main ' '{' signalDeclaration* variableDeclaration* blockStatement* '}';
blockStatement
: atom #AtomPro // Atomic
| blockStatement '|' blockStatement #NonCh // non-deterministrate choice
| blockStatement '||' blockStatement #ParaCom // parallel composition
| blockStatement ';' blockStatement #SeqCom // sequential composition
| '(' blockStatement '<' expr '>' blockStatement ')' #ConCh // conditional choice
| equation 'until' guard #Ode // differential equation
| 'when' '{' guardedchoice '}' #WhenPro // when program
| 'while' parExpression parStatement #LoopPro // loop
| 'if' parExpression parStatement
'else' parStatement #IfPro // if statement
| ID '(' exprList? ')' #CallTem // call template
| parStatement #ParPro // program with paraentheses outside
;
parStatement
: '{' blockStatement '}'
| '(' blockStatement ')'
;
exprList
: expr (',' expr)* ; // arg list
atom
: 'skip'
| ID '=' expr
| '!' ID
| 'suspend' '(' time=expr ')'
;
expr
: ID
| INT
| FLOAT
|'true'
| 'false'
| ('-' | '~') expr // negtive and negation
| expr ('*'|'/'|'mod') expr // % is mod
| expr ('+'|'-') expr
| expr ('>=' | '>' | '==' | '<' | '<=') expr
| expr 'and' expr
| expr 'or' expr
| 'floor' '(' expr ')'
| 'ceil' '(' expr ')'
| parExpression
;
parExpression
: '(' expr ')'
;
equation
: relation
| relation 'init' expr
| equation '||' equation
;
relation
: 'dot' ID '==' expr;
guard
: 'EMPTY'
| signal
| expr
| 'timeout' '(' expr ')'
| guard '<and>' guard
| guard '<or>' guard
| '(' guard ')'
;
signal
: ID ('[' expr ']')*;
guardedchoice
: guard '->' blockStatement
| guardedchoice '[]' guardedchoice
| '(' guardedchoice ')'
;
COMOP
: '>='
| '>'
| '=='
| '<'
| '<='
;
ID : (LETTER | '_') (LETTER|DIGIT|'_')*
;
fragment LETTER : [a-zA-Z] ;
INT : DIGIT+ ;
FLOAT : DIGIT+ '.' DIGIT+
;
fragment
DIGIT: '0'..'9' ;
COMMENT
: '/*' .*? '*/' -> channel(HIDDEN) // match anything between /* and */
;
LINE_COMMENT
: '//' ~[\r\n]* '\r'? '\n' -> channel(HIDDEN)
;
WS : [ \r\t\u000C\n]+ -> channel(HIDDEN)
;
|
set when statement as : when{ a -> skip [] b->skip }
|
set when statement as :
when{ a -> skip [] b->skip }
|
ANTLR
|
mit
|
fanghuixing/HML
|
f5812ef2b28c129db366c8a7488991154ce8a053
|
graphql/GraphQL.g4
|
graphql/GraphQL.g4
|
/*
The MIT License (MIT)
Copyright (c) 2015 Joseph T. McBride
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
GraphQL grammar derived from:
GraphQL Draft Specification - July 2015
http://facebook.github.io/graphql/ https://github.com/facebook/graphql
AB:10-sep19: replaced type with type_ to resolve conflict for golang generator
AB: 13-oct-19: added type system as per June 2018 specs
AB: 26-oct-19: added ID type
AB: 30-Oct-19: description, boolean, schema & Block string fix.
now parses: https://raw.githubusercontent.com/graphql-cats/graphql-cats/master/scenarios/validation/validation.schema.graphql
*/
grammar GraphQL;
//https://spec.graphql.org/June2018/#sec-Language.Document
document: definition+;
definition:
executableDefinition
| typeSystemDefinition
| typeSystemExtension;
//https://spec.graphql.org/June2018/#ExecutableDefinition
executableDefinition: operationDefinition | fragmentDefinition;
//https://spec.graphql.org/June2018/#sec-Language.Operations
operationDefinition:
operationType name? variableDefinitions? directives? selectionSet
| selectionSet
;
operationType: 'query' | 'mutation' | 'subscription';
//https://spec.graphql.org/June2018/#sec-Selection-Sets
selectionSet: '{' selection+ '}';
selection: field
| fragmentSpread
| inlineFragment
;
//https://spec.graphql.org/June2018/#sec-Language.Fields
field: alias? name arguments? directives? selectionSet?;
//https://spec.graphql.org/June2018/#sec-Language.Arguments
arguments: '(' argument+ ')';
argument: name ':' value;
//https://spec.graphql.org/June2018/#sec-Field-Alias
alias: name ':';
//https://spec.graphql.org/June2018/#sec-Language.Fragments
fragmentSpread: '...' fragmentName directives?;
fragmentDefinition:
'fragment' fragmentName 'on' typeCondition directives? selectionSet;
fragmentName: name; // except on
//https://spec.graphql.org/June2018/#sec-Type-Conditions
typeCondition: 'on' namedType;
//https://spec.graphql.org/June2018/#sec-Inline-Fragments
inlineFragment: '...' typeCondition? directives? selectionSet;
//https://spec.graphql.org/June2018/#sec-Input-Values
value:
variable
| intValue
| floatValue
| stringValue
| booleanValue
| nullValue
| enumValue
| listValue
| objectValue
;
//https://spec.graphql.org/June2018/#sec-Int-Value
intValue: INT;
//https://spec.graphql.org/June2018/#sec-Float-Value
floatValue: FLOAT;
//https://spec.graphql.org/June2018/#sec-Boolean-Value
booleanValue
: 'true'
| 'false'
;
//https://spec.graphql.org/June2018/#sec-String-Value
stringValue : STRING | BLOCK_STRING;
//https://spec.graphql.org/June2018/#sec-Null-Value
nullValue: 'null';
//https://spec.graphql.org/June2018/#sec-Enum-Value
enumValue: name; //{ not (nullValue | booleanValue) };
//https://spec.graphql.org/June2018/#sec-List-Value
listValue: '[' ']'
| '[' value+ ']'
;
//https://spec.graphql.org/June2018/#sec-Input-Object-Values
objectValue: '{' '}'
| '{' objectField '}'
;
objectField: name ':' value;
//https://spec.graphql.org/June2018/#sec-Language.Variables
variable: '$' name;
variableDefinitions: '(' variableDefinition+ ')';
variableDefinition: variable ':' type_ defaultValue?;
defaultValue: '=' value;
//https://spec.graphql.org/June2018/#sec-Type-References
type_: namedType '!'?
| listType '!'?
;
namedType: name;
listType: '[' type_ ']';
//https://spec.graphql.org/June2018/#sec-Language.Directives
directives: directive+;
directive: '@' name arguments?;
// https://graphql.github.io/graphql-spec/June2018/#TypeSystemDefinition
typeSystemDefinition: schemaDefinition
| typeDefinition
| directiveDefinition
;
//https://spec.graphql.org/June2018/#TypeSystemExtension
typeSystemExtension: schemaExtension
| typeExtension
;
// https://graphql.github.io/graphql-spec/June2018/#sec-Schema
schemaDefinition:
'schema' directives? '{' rootOperationTypeDefinition+ '}';
rootOperationTypeDefinition: operationType ':' namedType;
//https://spec.graphql.org/June2018/#sec-Schema-Extension
schemaExtension:
'extend' 'schema' directives? '{' operationTypeDefinition+ '}'
| 'extend' 'schema' directives
;
//https://spec.graphql.org/June2018/#OperationTypeDefinition
operationTypeDefinition: operationType ':' namedType;
//https://spec.graphql.org/June2018/#sec-Descriptions
description: stringValue;
//https://spec.graphql.org/June2018/#sec-Types
typeDefinition:
scalarTypeDefinition
| objectTypeDefinition
| interfaceTypeDefinition
| unionTypeDefinition
| enumTypeDefinition
| inputObjectTypeDefinition;
//https://spec.graphql.org/June2018/#sec-Type-Extensions
typeExtension : scalarTypeExtension
| objectTypeExtension
| interfaceTypeExtension
| unionTypeExtension
| enumTypeExtension
| inputObjectTypeExtension
;
//https://spec.graphql.org/June2018/#sec-Scalars
scalarTypeDefinition: description? 'scalar' name directives?;
//https://spec.graphql.org/June2018/#sec-Scalar-Extensions
scalarTypeExtension: 'extends' 'scalar' name directives;
// https://graphql.github.io/graphql-spec/June2018/#sec-Objects
objectTypeDefinition :
description? 'type' name implementsInterfaces? directives? fieldsDefinition?;
implementsInterfaces: 'implements' '&'? namedType
| implementsInterfaces '&' namedType
;
fieldsDefinition: '{' fieldDefinition+ '}';
fieldDefinition: description? name argumentsDefinition? ':' type_ directives? ;
//https://spec.graphql.org/June2018/#sec-Field-Arguments
argumentsDefinition: '(' inputValueDefinition+ ')';
inputValueDefinition: description? name ':' type_ defaultValue? directives?;
//https://spec.graphql.org/June2018/#sec-Object-Extensions
objectTypeExtension:
'extend' 'type' name implementsInterfaces? directives? fieldsDefinition
| 'extend' 'type' name implementsInterfaces? directives
| 'extend' 'type' name implementsInterfaces
;
//https://spec.graphql.org/June2018/#sec-Interfaces
interfaceTypeDefinition: description? 'interface' name directives? fieldsDefinition?;
//https://spec.graphql.org/June2018/#sec-Interface-Extensions
interfaceTypeExtension: 'extend' 'interface' name directives? fieldsDefinition
| 'extend' 'interface' name directives
;
// https://graphql.github.io/graphql-spec/June2018/#sec-Unions
unionTypeDefinition: description? 'union' name directives? unionMemberTypes?;
unionMemberTypes: '=' '|'? namedType ('|'namedType)* ;
//https://spec.graphql.org/June2018/#sec-Union-Extensions
unionTypeExtension : 'extend' 'union' name directives? unionMemberTypes
| 'extend' 'union' name directives
;
//https://spec.graphql.org/June2018/#sec-Enums
enumTypeDefinition: description? 'enum' name directives? enumValuesDefinition?;
enumValuesDefinition: '{' enumValueDefinition '}';
enumValueDefinition: description? enumValue directives?;
//https://spec.graphql.org/June2018/#sec-Enum-Extensions
enumTypeExtension: 'extend' 'enum' name directives? enumValuesDefinition
| 'extend' 'enum' name directives
;
//https://spec.graphql.org/June2018/#sec-Input-Objects
inputObjectTypeDefinition: description? 'input' name directives? inputFieldsDefinition?;
inputFieldsDefinition: '{' inputValueDefinition+ '}';
//https://spec.graphql.org/June2018/#sec-Input-Object-Extensions
inputObjectTypeExtension: 'extend' 'input' name directives? inputFieldsDefinition
| 'extend' 'input' name directives
;
//https://spec.graphql.org/June2018/#sec-Type-System.Directives
directiveDefinition: description? 'directive' '@' name argumentsDefinition? 'on' directiveLocations;
directiveLocations: directiveLocation ('|' directiveLocation)*;
directiveLocation: executableDirectiveLocation | typeSystemDirectiveLocation;
executableDirectiveLocation:
'QUERY'
| 'MUTATION'
| 'SUBSCRIPTION'
| 'FIELD'
| 'FRAGMENT_DEFINITION'
| 'FRAGMENT_SPREAD'
| 'INLINE_FRAGMENT'
;
typeSystemDirectiveLocation:
'SCHEMA'
| 'SCALAR'
| 'OBJECT'
| 'FIELD_DEFINITION'
| 'ARGUMENT_DEFINITION'
| 'INTERFACE'
| 'UNION'
| 'ENUM'
| 'ENUM_VALUE'
| 'INPUT_OBJECT'
| 'INPUT_FIELD_DEFINITION'
;
name: NAME;
//Start lexer
NAME: [_A-Za-z] [_0-9A-Za-z]*;
fragment CHARACTER: ( ESC | ~ ["\\]);
STRING: '"' CHARACTER* '"';
BLOCK_STRING
: '"""' .*? '"""'
;
ID: STRING;
fragment ESC: '\\' ( ["\\/bfnrt] | UNICODE);
fragment UNICODE: 'u' HEX HEX HEX HEX;
fragment HEX: [0-9a-fA-F];
fragment NONZERO_DIGIT: [1-9];
fragment DIGIT: [0-9];
fragment FRACTIONAL_PART: '.' DIGIT+;
fragment EXPONENTIAL_PART: EXPONENT_INDICATOR SIGN? DIGIT+;
fragment EXPONENT_INDICATOR: [eE];
fragment SIGN: [+-];
fragment NEGATIVE_SIGN: '-';
FLOAT: INT FRACTIONAL_PART
| INT EXPONENTIAL_PART
| INT FRACTIONAL_PART EXPONENTIAL_PART
;
INT: NEGATIVE_SIGN? '0'
| NEGATIVE_SIGN? NONZERO_DIGIT DIGIT*
;
PUNCTUATOR: '!'
| '$'
| '(' | ')'
| '...'
| ':'
| '='
| '@'
| '[' | ']'
| '{' | '}'
| '|'
;
// no leading zeros
fragment EXP: [Ee] [+\-]? INT;
// \- since - means "range" inside [...]
WS: [ \t\n\r]+ -> skip;
COMMA: ',' -> skip;
LineComment
: '#' ~[\r\n]*
-> skip
;
UNICODE_BOM: (UTF8_BOM
| UTF16_BOM
| UTF32_BOM
) -> skip
;
UTF8_BOM: '\uEFBBBF';
UTF16_BOM: '\uFEFF';
UTF32_BOM: '\u0000FEFF';
|
/*
The MIT License (MIT)
Copyright (c) 2015 Joseph T. McBride
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
GraphQL grammar derived from:
GraphQL Draft Specification - July 2015
http://facebook.github.io/graphql/ https://github.com/facebook/graphql
AB:10-sep19: replaced type with type_ to resolve conflict for golang generator
AB: 13-oct-19: added type system as per June 2018 specs
AB: 26-oct-19: added ID type
AB: 30-Oct-19: description, boolean, schema & Block string fix.
now parses: https://raw.githubusercontent.com/graphql-cats/graphql-cats/master/scenarios/validation/validation.schema.graphql
*/
grammar GraphQL;
//https://spec.graphql.org/June2018/#sec-Language.Document
document: definition+;
definition:
executableDefinition
| typeSystemDefinition
| typeSystemExtension;
//https://spec.graphql.org/June2018/#ExecutableDefinition
executableDefinition: operationDefinition | fragmentDefinition;
//https://spec.graphql.org/June2018/#sec-Language.Operations
operationDefinition:
operationType name? variableDefinitions? directives? selectionSet
| selectionSet
;
operationType: 'query' | 'mutation' | 'subscription';
//https://spec.graphql.org/June2018/#sec-Selection-Sets
selectionSet: '{' selection+ '}';
selection: field
| fragmentSpread
| inlineFragment
;
//https://spec.graphql.org/June2018/#sec-Language.Fields
field: alias? name arguments? directives? selectionSet?;
//https://spec.graphql.org/June2018/#sec-Language.Arguments
arguments: '(' argument+ ')';
argument: name ':' value;
//https://spec.graphql.org/June2018/#sec-Field-Alias
alias: name ':';
//https://spec.graphql.org/June2018/#sec-Language.Fragments
fragmentSpread: '...' fragmentName directives?;
fragmentDefinition:
'fragment' fragmentName 'on' typeCondition directives? selectionSet;
fragmentName: name; // except on
//https://spec.graphql.org/June2018/#sec-Type-Conditions
typeCondition: 'on' namedType;
//https://spec.graphql.org/June2018/#sec-Inline-Fragments
inlineFragment: '...' typeCondition? directives? selectionSet;
//https://spec.graphql.org/June2018/#sec-Input-Values
value:
variable
| intValue
| floatValue
| stringValue
| booleanValue
| nullValue
| enumValue
| listValue
| objectValue
;
//https://spec.graphql.org/June2018/#sec-Int-Value
intValue: INT;
//https://spec.graphql.org/June2018/#sec-Float-Value
floatValue: FLOAT;
//https://spec.graphql.org/June2018/#sec-Boolean-Value
booleanValue
: 'true'
| 'false'
;
//https://spec.graphql.org/June2018/#sec-String-Value
stringValue : STRING | BLOCK_STRING;
//https://spec.graphql.org/June2018/#sec-Null-Value
nullValue: 'null';
//https://spec.graphql.org/June2018/#sec-Enum-Value
enumValue: name; //{ not (nullValue | booleanValue) };
//https://spec.graphql.org/June2018/#sec-List-Value
listValue: '[' ']'
| '[' value+ ']'
;
//https://spec.graphql.org/June2018/#sec-Input-Object-Values
objectValue: '{' '}'
| '{' objectField '}'
;
objectField: name ':' value;
//https://spec.graphql.org/June2018/#sec-Language.Variables
variable: '$' name;
variableDefinitions: '(' variableDefinition+ ')';
variableDefinition: variable ':' type_ defaultValue?;
defaultValue: '=' value;
//https://spec.graphql.org/June2018/#sec-Type-References
type_: namedType '!'?
| listType '!'?
;
namedType: name;
listType: '[' type_ ']';
//https://spec.graphql.org/June2018/#sec-Language.Directives
directives: directive+;
directive: '@' name arguments?;
// https://graphql.github.io/graphql-spec/June2018/#TypeSystemDefinition
typeSystemDefinition: schemaDefinition
| typeDefinition
| directiveDefinition
;
//https://spec.graphql.org/June2018/#TypeSystemExtension
typeSystemExtension: schemaExtension
| typeExtension
;
// https://graphql.github.io/graphql-spec/June2018/#sec-Schema
schemaDefinition:
'schema' directives? '{' rootOperationTypeDefinition+ '}';
rootOperationTypeDefinition: operationType ':' namedType;
//https://spec.graphql.org/June2018/#sec-Schema-Extension
schemaExtension:
'extend' 'schema' directives? '{' operationTypeDefinition+ '}'
| 'extend' 'schema' directives
;
//https://spec.graphql.org/June2018/#OperationTypeDefinition
operationTypeDefinition: operationType ':' namedType;
//https://spec.graphql.org/June2018/#sec-Descriptions
description: stringValue;
//https://spec.graphql.org/June2018/#sec-Types
typeDefinition:
scalarTypeDefinition
| objectTypeDefinition
| interfaceTypeDefinition
| unionTypeDefinition
| enumTypeDefinition
| inputObjectTypeDefinition;
//https://spec.graphql.org/June2018/#sec-Type-Extensions
typeExtension : scalarTypeExtension
| objectTypeExtension
| interfaceTypeExtension
| unionTypeExtension
| enumTypeExtension
| inputObjectTypeExtension
;
//https://spec.graphql.org/June2018/#sec-Scalars
scalarTypeDefinition: description? 'scalar' name directives?;
//https://spec.graphql.org/June2018/#sec-Scalar-Extensions
scalarTypeExtension: 'extends' 'scalar' name directives;
// https://graphql.github.io/graphql-spec/June2018/#sec-Objects
objectTypeDefinition :
description? 'type' name implementsInterfaces? directives? fieldsDefinition?;
implementsInterfaces: 'implements' '&'? namedType
| implementsInterfaces '&' namedType
;
fieldsDefinition: '{' fieldDefinition+ '}';
fieldDefinition: description? name argumentsDefinition? ':' type_ directives? ;
//https://spec.graphql.org/June2018/#sec-Field-Arguments
argumentsDefinition: '(' inputValueDefinition+ ')';
inputValueDefinition: description? name ':' type_ defaultValue? directives?;
//https://spec.graphql.org/June2018/#sec-Object-Extensions
objectTypeExtension:
'extend' 'type' name implementsInterfaces? directives? fieldsDefinition
| 'extend' 'type' name implementsInterfaces? directives
| 'extend' 'type' name implementsInterfaces
;
//https://spec.graphql.org/June2018/#sec-Interfaces
interfaceTypeDefinition: description? 'interface' name directives? fieldsDefinition?;
//https://spec.graphql.org/June2018/#sec-Interface-Extensions
interfaceTypeExtension: 'extend' 'interface' name directives? fieldsDefinition
| 'extend' 'interface' name directives
;
// https://graphql.github.io/graphql-spec/June2018/#sec-Unions
unionTypeDefinition: description? 'union' name directives? unionMemberTypes?;
unionMemberTypes: '=' '|'? namedType ('|'namedType)* ;
//https://spec.graphql.org/June2018/#sec-Union-Extensions
unionTypeExtension : 'extend' 'union' name directives? unionMemberTypes
| 'extend' 'union' name directives
;
//https://spec.graphql.org/June2018/#sec-Enums
enumTypeDefinition: description? 'enum' name directives? enumValuesDefinition?;
enumValuesDefinition: '{' enumValueDefinition+ '}';
enumValueDefinition: description? enumValue directives?;
//https://spec.graphql.org/June2018/#sec-Enum-Extensions
enumTypeExtension: 'extend' 'enum' name directives? enumValuesDefinition
| 'extend' 'enum' name directives
;
//https://spec.graphql.org/June2018/#sec-Input-Objects
inputObjectTypeDefinition: description? 'input' name directives? inputFieldsDefinition?;
inputFieldsDefinition: '{' inputValueDefinition+ '}';
//https://spec.graphql.org/June2018/#sec-Input-Object-Extensions
inputObjectTypeExtension: 'extend' 'input' name directives? inputFieldsDefinition
| 'extend' 'input' name directives
;
//https://spec.graphql.org/June2018/#sec-Type-System.Directives
directiveDefinition: description? 'directive' '@' name argumentsDefinition? 'on' directiveLocations;
directiveLocations: directiveLocation ('|' directiveLocation)*;
directiveLocation: executableDirectiveLocation | typeSystemDirectiveLocation;
executableDirectiveLocation:
'QUERY'
| 'MUTATION'
| 'SUBSCRIPTION'
| 'FIELD'
| 'FRAGMENT_DEFINITION'
| 'FRAGMENT_SPREAD'
| 'INLINE_FRAGMENT'
;
typeSystemDirectiveLocation:
'SCHEMA'
| 'SCALAR'
| 'OBJECT'
| 'FIELD_DEFINITION'
| 'ARGUMENT_DEFINITION'
| 'INTERFACE'
| 'UNION'
| 'ENUM'
| 'ENUM_VALUE'
| 'INPUT_OBJECT'
| 'INPUT_FIELD_DEFINITION'
;
name: NAME;
//Start lexer
NAME: [_A-Za-z] [_0-9A-Za-z]*;
fragment CHARACTER: ( ESC | ~ ["\\]);
STRING: '"' CHARACTER* '"';
BLOCK_STRING
: '"""' .*? '"""'
;
ID: STRING;
fragment ESC: '\\' ( ["\\/bfnrt] | UNICODE);
fragment UNICODE: 'u' HEX HEX HEX HEX;
fragment HEX: [0-9a-fA-F];
fragment NONZERO_DIGIT: [1-9];
fragment DIGIT: [0-9];
fragment FRACTIONAL_PART: '.' DIGIT+;
fragment EXPONENTIAL_PART: EXPONENT_INDICATOR SIGN? DIGIT+;
fragment EXPONENT_INDICATOR: [eE];
fragment SIGN: [+-];
fragment NEGATIVE_SIGN: '-';
FLOAT: INT FRACTIONAL_PART
| INT EXPONENTIAL_PART
| INT FRACTIONAL_PART EXPONENTIAL_PART
;
INT: NEGATIVE_SIGN? '0'
| NEGATIVE_SIGN? NONZERO_DIGIT DIGIT*
;
PUNCTUATOR: '!'
| '$'
| '(' | ')'
| '...'
| ':'
| '='
| '@'
| '[' | ']'
| '{' | '}'
| '|'
;
// no leading zeros
fragment EXP: [Ee] [+\-]? INT;
// \- since - means "range" inside [...]
WS: [ \t\n\r]+ -> skip;
COMMA: ',' -> skip;
LineComment
: '#' ~[\r\n]*
-> skip
;
UNICODE_BOM: (UTF8_BOM
| UTF16_BOM
| UTF32_BOM
) -> skip
;
UTF8_BOM: '\uEFBBBF';
UTF16_BOM: '\uFEFF';
UTF32_BOM: '\u0000FEFF';
|
Fix issue in GraphQL grammar limiting the enum value definition only to 1 (the spec allows for multiple enum value definitions).
|
Fix issue in GraphQL grammar limiting the enum value definition only to 1 (the spec allows for multiple enum value definitions).
|
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
|
41b5f4ef97f86ad5ad33853389ac0276782f0635
|
python/PythonParser.g4
|
python/PythonParser.g4
|
// Header included from Python site:
/*
* Grammar for Python
*
* Note: Changing the grammar specified in this file will most likely
* require corresponding changes in the parser module
* (../Modules/parsermodule.c). If you can't make the changes to
* that module yourself, please co-ordinate the required changes
* with someone who can; ask around on python-dev for help. Fred
* Drake <[email protected]> will probably be listening there.
*
* NOTE WELL: You should also follow all the steps listed in PEP 306,
* "How to Change Python's Grammar"
*
* Start symbols for the grammar:
* single_input is a single interactive statement;
* file_input is a module or sequence of commands read from an input file;
* eval_input is the input for the eval() and input() functions.
* NB: compound_stmt in single_input is followed by extra LINE_BREAK!
*/
parser grammar PythonParser;
options { tokenVocab=PythonLexer; }
root
: (single_input
| file_input
| eval_input)? EOF
;
single_input
: LINE_BREAK
| simple_stmt
| compound_stmt LINE_BREAK
;
file_input
: (LINE_BREAK | stmt)+
;
eval_input
: testlist LINE_BREAK*
;
stmt
: simple_stmt
| compound_stmt
;
//---------------- compound statement ----------------------------------------------------------------------------------
compound_stmt
: IF cond=test COLON suite elif_clause* else_clause? #if_stmt
| WHILE test COLON suite else_clause? #while_stmt
| ASYNC? FOR exprlist IN testlist COLON suite else_clause? #for_stmt
| TRY COLON suite (except_clause+ else_clause? finally_clause? | finally_clause) #try_stmt
| ASYNC? WITH with_item (COMMA with_item)* COLON suite #with_stmt
| decorator* (classdef | funcdef) #class_or_func_def_stmt
;
suite
: simple_stmt
| LINE_BREAK INDENT stmt+ DEDENT
;
decorator
: AT dotted_name (OPEN_PAREN arglist? CLOSE_PAREN)? LINE_BREAK
;
elif_clause
: ELIF test COLON suite
;
else_clause
: ELSE COLON suite
;
finally_clause
: FINALLY COLON suite
;
with_item
// NB compile.c makes sure that the default except clause is last
: test (AS expr)?
;
// Python 2 : EXCEPT test COMMA name
// Python 3 : EXCEPT test AS name
except_clause
: EXCEPT (test (COMMA name | AS name)?)? COLON suite
;
//----------------------------------------------------------------------------------------------------------------------
// ------ class definition ---------------------------------------------------------------------------------------------
classdef
: CLASS name (OPEN_PAREN arglist? CLOSE_PAREN)? COLON suite
;
//----------------------------------------------------------------------------------------------------------------------
// ------- function and its parameters definition ----------------------------------------------------------------------
funcdef
: ASYNC? DEF name OPEN_PAREN typedargslist? CLOSE_PAREN (ARROW test)? COLON suite
;
// python 3 paramters
// parameters list may have a trailing comma
typedargslist
: (def_parameters COMMA)? (args (COMMA def_parameters)? (COMMA kwargs)? | kwargs) COMMA?
| def_parameters COMMA?
;
args
: STAR named_parameter
;
kwargs
: POWER named_parameter
;
def_parameters
: def_parameter (COMMA def_parameter)*
;
// TODO: bare STAR parameter must follow named ones
def_parameter
: named_parameter (ASSIGN test)?
| STAR
;
named_parameter
: name (COLON test)?
;
//----------------------------------------------------------------------------------------------------------------------
// -------- simple statement -------------------------------------------------------------------------------------------
simple_stmt
: small_stmt (SEMI_COLON small_stmt)* SEMI_COLON? (LINE_BREAK | EOF)
;
// TODO 1: left part augmented assignment should be `test` only, no stars or lists
// TODO 2: semantically annotated declaration is not an assignment
small_stmt
: testlist_star_expr assign_part? #expr_stmt
| PRINT ((test (COMMA test)* COMMA?) | RIGHT_SHIFT test ((COMMA test)+ COMMA?)) #print_stmt // Python 2
| DEL exprlist #del_stmt
| PASS #pass_stmt
| BREAK #break_stmt
| CONTINUE #continue_stmt
| RETURN testlist? #return_stmt
| RAISE (test (COMMA test (COMMA test)?)?)? (FROM test)? #raise_stmt
| yield_expr #yield_stmt
| IMPORT dotted_as_names #import_stmt
| FROM ((DOT | ELLIPSIS)* dotted_name | (DOT | ELLIPSIS)+)
IMPORT (STAR | OPEN_PAREN import_as_names CLOSE_PAREN | import_as_names) #from_stmt
| GLOBAL name (COMMA name)* #global_stmt
| EXEC expr (IN test (COMMA test)?)? #exec_stmt // Python 2
| ASSERT test (COMMA test)? #assert_stmt
| NONLOCAL name (COMMA name)* #nonlocal_stmt // Python 3
;
//----------------------------------------------------------------------------------------------------------------------
// -------- expression statement ---------------------------------------------------------------------------------------
testlist_star_expr
: ((test | star_expr) COMMA)+ (test | star_expr)?
| testlist
;
star_expr
: STAR expr
;
assign_part
: (ASSIGN testlist_star_expr)+ | (ASSIGN testlist_star_expr)* ASSIGN yield_expr // if left expression in assign is bool literal, it's mean that is Python 2 here
| COLON test (ASSIGN testlist)? // annassign Python3 rule
| op=( ADD_ASSIGN
| SUB_ASSIGN
| MULT_ASSIGN
| AT_ASSIGN
| DIV_ASSIGN
| MOD_ASSIGN
| AND_ASSIGN
| OR_ASSIGN
| XOR_ASSIGN
| LEFT_SHIFT_ASSIGN
| RIGHT_SHIFT_ASSIGN
| POWER_ASSIGN
| IDIV_ASSIGN
)
(yield_expr | testlist)
;
exprlist
: expr (COMMA expr)* COMMA?
;
//----------------------------------------------------------------------------------------------------------------------
// -------- import statement -------------------------------------------------------------------------------------------
import_as_names
: import_as_name (COMMA import_as_name)* COMMA?
;
// TODO: that means we can use keyword True as the name here: `from foo import bar as True` -- no
import_as_name
: name (AS name)?
;
dotted_as_names
: dotted_as_name (COMMA dotted_as_name)*
;
dotted_as_name
: dotted_name (AS name)?
;
//----------------------------------------------------------------------------------------------------------------------
// -------------------------- test, lambda and its parameters ----------------------------------------------------------
/*
* Warning!
* According to https://docs.python.org/3/reference/expressions.html#lambda LAMBDA should be followed by
* `parameter_list` (in our case it is `typedargslist`)
* But that's not true! `typedargslist` may have parameters with type hinting, but that's not permitted in lambda
* definition
*/
// https://docs.python.org/3/reference/expressions.html#operator-precedence
test
: logical_test (IF logical_test ELSE test)?
| LAMBDA varargslist? COLON test
;
// the same as `typedargslist`, but with no types
varargslist
: (vardef_parameters COMMA)? (varargs (COMMA vardef_parameters)? (COMMA varkwargs)? | varkwargs) COMMA?
| vardef_parameters COMMA?
;
vardef_parameters
: vardef_parameter (COMMA vardef_parameter)*
;
// TODO: bare STAR parameter must follow named ones
vardef_parameter
: name (ASSIGN test)?
| STAR
;
varargs
: STAR name
;
varkwargs
: POWER name
;
//----------------------------------------------------------------------------------------------------------------------
// -------------------------- tests and comparisons --------------------------------------------------------------------
logical_test
: comparison
| NOT logical_test
| logical_test op=AND logical_test
| logical_test op=OR logical_test
;
comparison
: comparison (LESS_THAN | GREATER_THAN | EQUALS | GT_EQ | LT_EQ | NOT_EQ_1 | NOT_EQ_2 | optional=NOT? IN | IS optional=NOT?) comparison
| expr
;
//----------------------------------------------------------------------------------------------------------------------
// -------------------------- expressions ------------------------------------------------------------------------------
expr
: AWAIT? atom trailer*
| <assoc=right> expr op=POWER expr
| op=(ADD | MINUS | NOT_OP) expr
| expr op=(STAR | DIV | MOD | IDIV | AT) expr
| expr op=(ADD | MINUS) expr
| expr op=(LEFT_SHIFT | RIGHT_SHIFT) expr
| expr op=AND_OP expr
| expr op=XOR expr
| expr op=OR_OP expr
;
//----------------------------------------------------------------------------------------------------------------------
// -------------------------- atom -------------------------------------------------------------------------------------
atom
: OPEN_PAREN (yield_expr | testlist_comp)? CLOSE_PAREN
| OPEN_BRACKET testlist_comp? CLOSE_BRACKET
| OPEN_BRACE dictorsetmaker? CLOSE_BRACE
| REVERSE_QUOTE testlist COMMA? REVERSE_QUOTE
| ELLIPSIS
| name
| PRINT
| EXEC
| MINUS? number
| NONE
| STRING+
;
dictorsetmaker
: (test COLON test | POWER expr) (COMMA (test COLON test | POWER expr))* COMMA? // key_datum_list
| test COLON test comp_for // dict_comprehension
| testlist_comp
;
testlist_comp
: (test | star_expr) (comp_for | (COMMA (test | star_expr))* COMMA?)
;
testlist
: test (COMMA test)* COMMA?
;
dotted_name
: dotted_name DOT name
| name
;
name
: NAME
| TRUE
| FALSE
;
number
: integer
| IMAG_NUMBER
| FLOAT_NUMBER
;
integer
: DECIMAL_INTEGER
| OCT_INTEGER
| HEX_INTEGER
| BIN_INTEGER
;
//----------------------------------------------------------------------------------------------------------------------
// -------------------------- yield_expr -------------------------------------------------------------------------------
yield_expr
: YIELD yield_arg?
;
yield_arg
: FROM test
| testlist
;
//----------------------------------------------------------------------------------------------------------------------
// -------------------------- trailer ----------------------------------------------------------------------------------
// TODO: this way we can pass: `f(x for x in i, a)`, but it's invalid.
// See: https://docs.python.org/3/reference/expressions.html#calls
trailer
: OPEN_PAREN arglist? CLOSE_PAREN
| OPEN_BRACKET subscriptlist CLOSE_BRACKET
| DOT name
;
arglist
// The reason that keywords are test nodes instead of name is that using name
// results in an ambiguity. ast.c makes sure it's a name.
: argument (COMMA argument)* COMMA?
;
argument
: test (comp_for | ASSIGN test)?
| (POWER | STAR) test
;
// TODO: maybe inline?
subscriptlist
: subscript (COMMA subscript)* COMMA?
;
subscript
: ELLIPSIS
| test
| test? COLON test? sliceop?
;
// TODO: maybe inline?
sliceop
: COLON test?
;
//----------------------------------------------------------------------------------------------------------------------
// --------------------- comprehension ---------------------------------------------------------------------------------
comp_for
: FOR exprlist IN logical_test comp_iter?
;
comp_iter
: comp_for
| IF test comp_iter?
;
//----------------------------------------------------------------------------------------------------------------------
|
// Header included from Python site:
/*
* Grammar for Python
*
* Note: Changing the grammar specified in this file will most likely
* require corresponding changes in the parser module
* (../Modules/parsermodule.c). If you can't make the changes to
* that module yourself, please co-ordinate the required changes
* with someone who can; ask around on python-dev for help. Fred
* Drake <[email protected]> will probably be listening there.
*
* NOTE WELL: You should also follow all the steps listed in PEP 306,
* "How to Change Python's Grammar"
*
* Start symbols for the grammar:
* single_input is a single interactive statement;
* file_input is a module or sequence of commands read from an input file;
* eval_input is the input for the eval() and input() functions.
* NB: compound_stmt in single_input is followed by extra LINE_BREAK!
*/
parser grammar PythonParser;
options { tokenVocab=PythonLexer; superClass=PythonBaseParser; }
root
: (single_input
| file_input
| eval_input)? EOF
;
single_input
: LINE_BREAK
| simple_stmt
| compound_stmt LINE_BREAK
;
file_input
: (LINE_BREAK | stmt)+
;
eval_input
: testlist LINE_BREAK*
;
stmt
: simple_stmt
| compound_stmt
;
//---------------- compound statement ----------------------------------------------------------------------------------
compound_stmt
: IF cond=test COLON suite elif_clause* else_clause? #if_stmt
| WHILE test COLON suite else_clause? #while_stmt
| ASYNC? FOR exprlist IN testlist COLON suite else_clause? #for_stmt
| TRY COLON suite (except_clause+ else_clause? finally_clause? | finally_clause) #try_stmt
| ASYNC? WITH with_item (COMMA with_item)* COLON suite #with_stmt
| decorator* (classdef | funcdef) #class_or_func_def_stmt
;
suite
: simple_stmt
| LINE_BREAK INDENT stmt+ DEDENT
;
decorator
: AT dotted_name (OPEN_PAREN arglist? CLOSE_PAREN)? LINE_BREAK
;
elif_clause
: ELIF test COLON suite
;
else_clause
: ELSE COLON suite
;
finally_clause
: FINALLY COLON suite
;
with_item
// NB compile.c makes sure that the default except clause is last
: test (AS expr)?
;
// Python 2 : EXCEPT test COMMA name
// Python 3 : EXCEPT test AS name
except_clause
: EXCEPT (test ({CheckVersion(2)}? COMMA name {SetVersion(2);} | {CheckVersion(3)}? AS name {SetVersion(3);})?)? COLON suite
;
//----------------------------------------------------------------------------------------------------------------------
// ------ class definition ---------------------------------------------------------------------------------------------
classdef
: CLASS name (OPEN_PAREN arglist? CLOSE_PAREN)? COLON suite
;
//----------------------------------------------------------------------------------------------------------------------
// ------- function and its parameters definition ----------------------------------------------------------------------
funcdef
: ASYNC? DEF name OPEN_PAREN typedargslist? CLOSE_PAREN (ARROW test)? COLON suite
;
// python 3 paramters
// parameters list may have a trailing comma
typedargslist
: (def_parameters COMMA)? (args (COMMA def_parameters)? (COMMA kwargs)? | kwargs) COMMA?
| def_parameters COMMA?
;
args
: STAR named_parameter
;
kwargs
: POWER named_parameter
;
def_parameters
: def_parameter (COMMA def_parameter)*
;
// TODO: bare STAR parameter must follow named ones
def_parameter
: named_parameter (ASSIGN test)?
| STAR
;
named_parameter
: name (COLON test)?
;
//----------------------------------------------------------------------------------------------------------------------
// -------- simple statement -------------------------------------------------------------------------------------------
simple_stmt
: small_stmt (SEMI_COLON small_stmt)* SEMI_COLON? (LINE_BREAK | EOF)
;
// TODO 1: left part augmented assignment should be `test` only, no stars or lists
// TODO 2: semantically annotated declaration is not an assignment
small_stmt
: testlist_star_expr assign_part? #expr_stmt
| {CheckVersion(2)}? PRINT ((test (COMMA test)* COMMA?)
| RIGHT_SHIFT test ((COMMA test)+ COMMA?)) {SetVersion(2);} #print_stmt // Python 2
| DEL exprlist #del_stmt
| PASS #pass_stmt
| BREAK #break_stmt
| CONTINUE #continue_stmt
| RETURN testlist? #return_stmt
| RAISE (test (COMMA test (COMMA test)?)?)? (FROM test)? #raise_stmt
| yield_expr #yield_stmt
| IMPORT dotted_as_names #import_stmt
| FROM ((DOT | ELLIPSIS)* dotted_name | (DOT | ELLIPSIS)+)
IMPORT (STAR | OPEN_PAREN import_as_names CLOSE_PAREN | import_as_names) #from_stmt
| GLOBAL name (COMMA name)* #global_stmt
| {CheckVersion(2)}? EXEC expr (IN test (COMMA test)?)? {SetVersion(2);} #exec_stmt // Python 2
| ASSERT test (COMMA test)? #assert_stmt
| {CheckVersion(3)}? NONLOCAL name (COMMA name)* {SetVersion(3);} #nonlocal_stmt // Python 3
;
//----------------------------------------------------------------------------------------------------------------------
// -------- expression statement ---------------------------------------------------------------------------------------
testlist_star_expr
: ((test | star_expr) COMMA)+ (test | star_expr)?
| testlist
;
star_expr
: STAR expr
;
assign_part
// if left expression in assign is bool literal, it's mean that is Python 2 here
: ASSIGN ( testlist_star_expr ((ASSIGN testlist_star_expr)* (ASSIGN yield_expr)?)?
| yield_expr)
| {CheckVersion(3)}? COLON test (ASSIGN testlist)? {SetVersion(3);} // annassign Python3 rule
| op=( ADD_ASSIGN
| SUB_ASSIGN
| MULT_ASSIGN
| AT_ASSIGN
| DIV_ASSIGN
| MOD_ASSIGN
| AND_ASSIGN
| OR_ASSIGN
| XOR_ASSIGN
| LEFT_SHIFT_ASSIGN
| RIGHT_SHIFT_ASSIGN
| POWER_ASSIGN
| IDIV_ASSIGN
)
(yield_expr | testlist)
;
exprlist
: expr (COMMA expr)* COMMA?
;
//----------------------------------------------------------------------------------------------------------------------
// -------- import statement -------------------------------------------------------------------------------------------
import_as_names
: import_as_name (COMMA import_as_name)* COMMA?
;
// TODO: that means we can use keyword True as the name here: `from foo import bar as True` -- no
import_as_name
: name (AS name)?
;
dotted_as_names
: dotted_as_name (COMMA dotted_as_name)*
;
dotted_as_name
: dotted_name (AS name)?
;
//----------------------------------------------------------------------------------------------------------------------
// -------------------------- test, lambda and its parameters ----------------------------------------------------------
/*
* Warning!
* According to https://docs.python.org/3/reference/expressions.html#lambda LAMBDA should be followed by
* `parameter_list` (in our case it is `typedargslist`)
* But that's not true! `typedargslist` may have parameters with type hinting, but that's not permitted in lambda
* definition
*/
// https://docs.python.org/3/reference/expressions.html#operator-precedence
test
: logical_test (IF logical_test ELSE test)?
| LAMBDA varargslist? COLON test
;
// the same as `typedargslist`, but with no types
varargslist
: (vardef_parameters COMMA)? (varargs (COMMA vardef_parameters)? (COMMA varkwargs)? | varkwargs) COMMA?
| vardef_parameters COMMA?
;
vardef_parameters
: vardef_parameter (COMMA vardef_parameter)*
;
// TODO: bare STAR parameter must follow named ones
vardef_parameter
: name (ASSIGN test)?
| STAR
;
varargs
: STAR name
;
varkwargs
: POWER name
;
//----------------------------------------------------------------------------------------------------------------------
// -------------------------- tests and comparisons --------------------------------------------------------------------
logical_test
: comparison
| NOT logical_test
| logical_test op=AND logical_test
| logical_test op=OR logical_test
;
comparison
: comparison (LESS_THAN | GREATER_THAN | EQUALS | GT_EQ | LT_EQ | NOT_EQ_1 | NOT_EQ_2 | optional=NOT? IN | IS optional=NOT?) comparison
| expr
;
//----------------------------------------------------------------------------------------------------------------------
// -------------------------- expressions ------------------------------------------------------------------------------
expr
: AWAIT? atom trailer*
| <assoc=right> expr op=POWER expr
| op=(ADD | MINUS | NOT_OP) expr
| expr op=(STAR | DIV | MOD | IDIV | AT) expr
| expr op=(ADD | MINUS) expr
| expr op=(LEFT_SHIFT | RIGHT_SHIFT) expr
| expr op=AND_OP expr
| expr op=XOR expr
| expr op=OR_OP expr
;
//----------------------------------------------------------------------------------------------------------------------
// -------------------------- atom -------------------------------------------------------------------------------------
atom
: OPEN_PAREN (yield_expr | testlist_comp)? CLOSE_PAREN
| OPEN_BRACKET testlist_comp? CLOSE_BRACKET
| OPEN_BRACE dictorsetmaker? CLOSE_BRACE
| REVERSE_QUOTE testlist COMMA? REVERSE_QUOTE
| ELLIPSIS
| name
| PRINT
| EXEC
| MINUS? number
| NONE
| STRING+
;
dictorsetmaker
: (test COLON test | POWER expr) (COMMA (test COLON test | POWER expr))* COMMA? // key_datum_list
| test COLON test comp_for // dict_comprehension
| testlist_comp
;
testlist_comp
: (test | star_expr) (comp_for | (COMMA (test | star_expr))* COMMA?)
;
testlist
: test (COMMA test)* COMMA?
;
dotted_name
: dotted_name DOT name
| name
;
name
: NAME
| TRUE
| FALSE
;
number
: integer
| IMAG_NUMBER
| FLOAT_NUMBER
;
integer
: DECIMAL_INTEGER
| OCT_INTEGER
| HEX_INTEGER
| BIN_INTEGER
;
//----------------------------------------------------------------------------------------------------------------------
// -------------------------- yield_expr -------------------------------------------------------------------------------
yield_expr
: YIELD yield_arg?
;
yield_arg
: FROM test
| testlist
;
//----------------------------------------------------------------------------------------------------------------------
// -------------------------- trailer ----------------------------------------------------------------------------------
// TODO: this way we can pass: `f(x for x in i, a)`, but it's invalid.
// See: https://docs.python.org/3/reference/expressions.html#calls
trailer
: OPEN_PAREN arglist? CLOSE_PAREN
| OPEN_BRACKET subscriptlist CLOSE_BRACKET
| DOT name
;
arglist
// The reason that keywords are test nodes instead of name is that using name
// results in an ambiguity. ast.c makes sure it's a name.
: argument (COMMA argument)* COMMA?
;
argument
: test (comp_for | ASSIGN test)?
| (POWER | STAR) test
;
// TODO: maybe inline?
subscriptlist
: subscript (COMMA subscript)* COMMA?
;
subscript
: ELLIPSIS
| test (COLON test? sliceop?)?
| COLON test? sliceop?
;
// TODO: maybe inline?
sliceop
: COLON test?
;
//----------------------------------------------------------------------------------------------------------------------
// --------------------- comprehension ---------------------------------------------------------------------------------
comp_for
: FOR exprlist IN logical_test comp_iter?
;
comp_iter
: comp_for
| IF test comp_iter?
;
//----------------------------------------------------------------------------------------------------------------------
|
Use CheckVersion() and SetVersion() in PythonParser.g4
|
Use CheckVersion() and SetVersion() in PythonParser.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
|
f042500462a36144f0b777ccaf3ea77bb0a0b17b
|
projects/batfish/src/main/antlr4/org/batfish/grammar/cisco_nxos/CiscoNxosParser.g4
|
projects/batfish/src/main/antlr4/org/batfish/grammar/cisco_nxos/CiscoNxosParser.g4
|
parser grammar CiscoNxosParser;
import
CiscoNxos_common,
CiscoNxos_aaa,
CiscoNxos_bgp,
CiscoNxos_class_map,
CiscoNxos_crypto,
CiscoNxos_eigrp,
CiscoNxos_evpn,
CiscoNxos_fex,
CiscoNxos_interface,
CiscoNxos_ip_access_list,
CiscoNxos_ip_as_path_access_list,
CiscoNxos_ip_community_list,
CiscoNxos_ip_prefix_list,
CiscoNxos_ipv6_access_list,
CiscoNxos_ipv6_prefix_list,
CiscoNxos_logging,
CiscoNxos_mac,
CiscoNxos_monitor,
CiscoNxos_ntp,
CiscoNxos_object_group,
CiscoNxos_ospf,
CiscoNxos_policy_map,
CiscoNxos_route_map,
CiscoNxos_snmp,
CiscoNxos_static,
CiscoNxos_tacacs_server,
CiscoNxos_vlan,
CiscoNxos_vrf;
options {
superClass = 'org.batfish.grammar.cisco_nxos.parsing.CiscoNxosBaseParser';
tokenVocab = CiscoNxosLexer;
}
cisco_nxos_configuration
:
statement+ EOF
;
statement
:
s_aaa
| s_banner
| s_boot
| s_class_map
| s_control_plane
| s_crypto
| s_evpn
| s_fex
| s_hostname
| s_interface
| s_ip
| s_ipv6
| s_key
| s_logging
| s_mac
| s_monitor
| s_no
| s_ntp
| s_null
| s_nv
| s_object_group
| s_policy_map
| s_role
| s_route_map
| s_router
| s_snmp_server
| s_system
| s_tacacs_server
| s_track
| s_version
| s_vlan
| s_vrf_context
;
s_banner
:
BANNER
(
banner_exec
| banner_motd
)
;
banner_exec
:
EXEC BANNER_DELIMITER body=BANNER_BODY? BANNER_DELIMITER NEWLINE
;
banner_motd
:
MOTD BANNER_DELIMITER body=BANNER_BODY? BANNER_DELIMITER NEWLINE
;
s_boot
:
BOOT
(
boot_kickstart
| boot_nxos
| boot_system
)
;
boot_kickstart
:
KICKSTART image = WORD (SUP_1 | SUP_2)? NEWLINE
;
boot_nxos
:
NXOS image = WORD (SUP_1 | SUP_2)? NEWLINE
;
boot_system
:
SYSTEM image = WORD (SUP_1 | SUP_2)? NEWLINE
;
s_control_plane
:
CONTROL_PLANE NEWLINE cp_service_policy*
;
cp_service_policy
:
SERVICE_POLICY INPUT name = policy_map_name NEWLINE
;
s_hostname
:
(HOSTNAME | SWITCHNAME) hostname = subdomain_name NEWLINE
;
s_ip
:
IP
(
ip_access_list
| ip_as_path_access_list
| ip_community_list
| ip_domain_name
| ip_name_server
| ip_null
| ip_prefix_list
| ip_route
| ip_tacacs
| ip_sla
)
;
ip_domain_name
:
DOMAIN_NAME domain = domain_name NEWLINE
;
domain_name
:
// 1-64 characters
WORD
;
ip_name_server
:
NAME_SERVER servers += name_server+ (USE_VRF vrf = vrf_name)? NEWLINE
;
name_server
:
ip_address
| ipv6_address
;
ip_null
:
(
ARP
| DOMAIN_LOOKUP
) null_rest_of_line
;
ip_sla
:
SLA
(
ip_sla_block
| ip_sla_null
)
;
ip_sla_block
:
entry = uint32 NEWLINE
ip_sla_entry+
;
ip_sla_entry
:
(
DNS
| HTTP
| ICMP_ECHO
| TCP_CONNECT
| UDP_ECHO
| UDP_JITTER
) null_rest_of_line
;
ip_sla_null
:
(
GROUP
| LOGGING
| REACTION_CONFIGURATION
| REACTION_TRIGGER
| RESET
| RESPONDER
| SCHEDULE
) null_rest_of_line
;
s_ipv6
:
IPV6
(
ipv6_access_list
| ipv6_prefix_list
)
;
s_key
:
KEY key_chain
;
key_chain
:
CHAIN name = key_chain_name NEWLINE kc_key*
;
kc_key
:
KEY num = uint16 NEWLINE kck_key_string*
;
kck_key_string
:
KEY_STRING key_text = key_string_text NEWLINE
;
key_string_text
:
// 1-63 characters
REMARK_TEXT
;
s_null
:
(
BOOT
| CLI
| CLOCK
| ERRDISABLE
| FEATURE
| LICENSE
| SERVICE
| SSH
| SPANNING_TREE
| USERNAME
| USERPASSPHRASE
) null_rest_of_line
;
s_no
:
NO
(
no_null
| no_system
)
;
no_null
:
(
FEATURE
| IP
| NTP
) null_rest_of_line
;
no_system
:
SYSTEM
(
no_sys_default
| no_sys_null
)
;
no_sys_default
:
DEFAULT no_sysd_switchport
;
no_sys_null
:
(
INTERFACE
| MODE
) null_rest_of_line
;
no_sysd_switchport
:
SWITCHPORT
(
no_sysds_shutdown
| no_sysds_switchport
)
;
no_sysds_shutdown
:
SHUTDOWN NEWLINE
;
no_sysds_switchport
:
NEWLINE
;
s_nv
:
NV OVERLAY EVPN NEWLINE
;
s_role
:
ROLE NAME name = role_name NEWLINE role_null*
;
role_name
:
// 1-16 characters
WORD
;
role_null
:
(
DESCRIPTION
| RULE
) null_rest_of_line
;
s_router
:
ROUTER
(
router_bgp
| router_eigrp
| router_ospf
)
;
s_system
:
SYSTEM
(
sys_default
| sys_qos
)
;
sys_default
:
DEFAULT sysd_switchport
;
sysd_switchport
:
SWITCHPORT
(
sysds_shutdown
| sysds_switchport
)
;
sysds_shutdown
:
SHUTDOWN NEWLINE
;
sysds_switchport
:
NEWLINE
;
sys_qos
:
QOS NEWLINE
(
sysqos_null
| sysqos_service_policy
)*
;
sysqos_null
:
(
FEX
) null_rest_of_line
;
sysqos_service_policy
:
SERVICE_POLICY TYPE
(
sysqosspt_network_qos
| sysqosspt_qos
| sysqosspt_queueing
)
;
sysqosspt_network_qos
:
NETWORK_QOS name = policy_map_name NEWLINE
;
sysqosspt_qos
:
QOS INPUT name = policy_map_name NEWLINE
;
sysqosspt_queueing
:
QUEUING (INPUT | OUTPUT) name = policy_map_name NEWLINE
;
s_track
:
TRACK num = track_object_number
(
track_interface
| track_ip
)
;
track_interface
:
INTERFACE interface_name null_rest_of_line
;
track_ip
:
IP
(
track_ip_route
| track_ip_sla
)
;
track_ip_route
:
ROUTE null_rest_of_line tir_vrf*
;
tir_vrf
:
VRF MEMBER name = vrf_name NEWLINE
;
track_ip_sla
:
SLA null_rest_of_line
;
s_version
:
// arbitray string, not actual command
VERSION version = REMARK_TEXT NEWLINE
;
|
parser grammar CiscoNxosParser;
import
CiscoNxos_common,
CiscoNxos_aaa,
CiscoNxos_bgp,
CiscoNxos_class_map,
CiscoNxos_crypto,
CiscoNxos_eigrp,
CiscoNxos_evpn,
CiscoNxos_fex,
CiscoNxos_interface,
CiscoNxos_ip_access_list,
CiscoNxos_ip_as_path_access_list,
CiscoNxos_ip_community_list,
CiscoNxos_ip_prefix_list,
CiscoNxos_ipv6_access_list,
CiscoNxos_ipv6_prefix_list,
CiscoNxos_logging,
CiscoNxos_mac,
CiscoNxos_monitor,
CiscoNxos_ntp,
CiscoNxos_object_group,
CiscoNxos_ospf,
CiscoNxos_policy_map,
CiscoNxos_route_map,
CiscoNxos_snmp,
CiscoNxos_static,
CiscoNxos_tacacs_server,
CiscoNxos_vlan,
CiscoNxos_vrf;
options {
superClass = 'org.batfish.grammar.cisco_nxos.parsing.CiscoNxosBaseParser';
tokenVocab = CiscoNxosLexer;
}
cisco_nxos_configuration
:
statement+ EOF
;
statement
:
s_aaa
| s_banner
| s_boot
| s_class_map
| s_control_plane
| s_crypto
| s_evpn
| s_fex
| s_hostname
| s_interface
| s_ip
| s_ipv6
| s_key
| s_logging
| s_mac
| s_monitor
| s_no
| s_ntp
| s_null
| s_nv
| s_object_group
| s_policy_map
| s_role
| s_route_map
| s_router
| s_snmp_server
| s_system
| s_tacacs_server
| s_track
| s_version
| s_vlan
| s_vrf_context
;
s_banner
:
BANNER
(
banner_exec
| banner_motd
)
;
banner_exec
:
EXEC BANNER_DELIMITER body=BANNER_BODY? BANNER_DELIMITER NEWLINE
;
banner_motd
:
MOTD BANNER_DELIMITER body=BANNER_BODY? BANNER_DELIMITER NEWLINE
;
s_boot
:
BOOT
(
boot_kickstart
| boot_null
| boot_nxos
| boot_system
)
;
boot_kickstart
:
KICKSTART image = WORD (SUP_1 | SUP_2)? NEWLINE
;
boot_null
:
(
POAP
) null_rest_of_line
;
boot_nxos
:
NXOS image = WORD (SUP_1 | SUP_2)? NEWLINE
;
boot_system
:
SYSTEM image = WORD (SUP_1 | SUP_2)? NEWLINE
;
s_control_plane
:
CONTROL_PLANE NEWLINE cp_service_policy*
;
cp_service_policy
:
SERVICE_POLICY INPUT name = policy_map_name NEWLINE
;
s_hostname
:
(HOSTNAME | SWITCHNAME) hostname = subdomain_name NEWLINE
;
s_ip
:
IP
(
ip_access_list
| ip_as_path_access_list
| ip_community_list
| ip_domain_name
| ip_name_server
| ip_null
| ip_prefix_list
| ip_route
| ip_tacacs
| ip_sla
)
;
ip_domain_name
:
DOMAIN_NAME domain = domain_name NEWLINE
;
domain_name
:
// 1-64 characters
WORD
;
ip_name_server
:
NAME_SERVER servers += name_server+ (USE_VRF vrf = vrf_name)? NEWLINE
;
name_server
:
ip_address
| ipv6_address
;
ip_null
:
(
ARP
| DOMAIN_LOOKUP
) null_rest_of_line
;
ip_sla
:
SLA
(
ip_sla_block
| ip_sla_null
)
;
ip_sla_block
:
entry = uint32 NEWLINE
ip_sla_entry+
;
ip_sla_entry
:
(
DNS
| HTTP
| ICMP_ECHO
| TCP_CONNECT
| UDP_ECHO
| UDP_JITTER
) null_rest_of_line
;
ip_sla_null
:
(
GROUP
| LOGGING
| REACTION_CONFIGURATION
| REACTION_TRIGGER
| RESET
| RESPONDER
| SCHEDULE
) null_rest_of_line
;
s_ipv6
:
IPV6
(
ipv6_access_list
| ipv6_prefix_list
)
;
s_key
:
KEY key_chain
;
key_chain
:
CHAIN name = key_chain_name NEWLINE kc_key*
;
kc_key
:
KEY num = uint16 NEWLINE kck_key_string*
;
kck_key_string
:
KEY_STRING key_text = key_string_text NEWLINE
;
key_string_text
:
// 1-63 characters
REMARK_TEXT
;
s_null
:
(
CLI
| CLOCK
| ERRDISABLE
| FEATURE
| LICENSE
| SERVICE
| SSH
| SPANNING_TREE
| USERNAME
| USERPASSPHRASE
) null_rest_of_line
;
s_no
:
NO
(
no_null
| no_system
)
;
no_null
:
(
FEATURE
| IP
| NTP
) null_rest_of_line
;
no_system
:
SYSTEM
(
no_sys_default
| no_sys_null
)
;
no_sys_default
:
DEFAULT no_sysd_switchport
;
no_sys_null
:
(
INTERFACE
| MODE
) null_rest_of_line
;
no_sysd_switchport
:
SWITCHPORT
(
no_sysds_shutdown
| no_sysds_switchport
)
;
no_sysds_shutdown
:
SHUTDOWN NEWLINE
;
no_sysds_switchport
:
NEWLINE
;
s_nv
:
NV OVERLAY EVPN NEWLINE
;
s_role
:
ROLE NAME name = role_name NEWLINE role_null*
;
role_name
:
// 1-16 characters
WORD
;
role_null
:
(
DESCRIPTION
| RULE
) null_rest_of_line
;
s_router
:
ROUTER
(
router_bgp
| router_eigrp
| router_ospf
)
;
s_system
:
SYSTEM
(
sys_default
| sys_qos
)
;
sys_default
:
DEFAULT sysd_switchport
;
sysd_switchport
:
SWITCHPORT
(
sysds_shutdown
| sysds_switchport
)
;
sysds_shutdown
:
SHUTDOWN NEWLINE
;
sysds_switchport
:
NEWLINE
;
sys_qos
:
QOS NEWLINE
(
sysqos_null
| sysqos_service_policy
)*
;
sysqos_null
:
(
FEX
) null_rest_of_line
;
sysqos_service_policy
:
SERVICE_POLICY TYPE
(
sysqosspt_network_qos
| sysqosspt_qos
| sysqosspt_queueing
)
;
sysqosspt_network_qos
:
NETWORK_QOS name = policy_map_name NEWLINE
;
sysqosspt_qos
:
QOS INPUT name = policy_map_name NEWLINE
;
sysqosspt_queueing
:
QUEUING (INPUT | OUTPUT) name = policy_map_name NEWLINE
;
s_track
:
TRACK num = track_object_number
(
track_interface
| track_ip
)
;
track_interface
:
INTERFACE interface_name null_rest_of_line
;
track_ip
:
IP
(
track_ip_route
| track_ip_sla
)
;
track_ip_route
:
ROUTE null_rest_of_line tir_vrf*
;
tir_vrf
:
VRF MEMBER name = vrf_name NEWLINE
;
track_ip_sla
:
SLA null_rest_of_line
;
s_version
:
// arbitray string, not actual command
VERSION version = REMARK_TEXT NEWLINE
;
|
remove parse ambiguity with s_boot vs s_null (#4678)
|
NX-OS: remove parse ambiguity with s_boot vs s_null (#4678)
|
ANTLR
|
apache-2.0
|
dhalperi/batfish,batfish/batfish,intentionet/batfish,arifogel/batfish,arifogel/batfish,intentionet/batfish,batfish/batfish,intentionet/batfish,batfish/batfish,dhalperi/batfish,intentionet/batfish,intentionet/batfish,dhalperi/batfish,arifogel/batfish
|
c25d27cf9fb2d02db7ce3598f938a86c279d3ba7
|
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 (tableIndexClause_ | bitmapJoinIndexClause_)
;
alterTable
: ALTER TABLE tableName alterClause_
;
// TODO hongjun throw exeption when alter index on oracle
alterIndex
: ALTER INDEX indexName (RENAME TO indexName)?
;
dropTable
: DROP TABLE tableName
;
dropIndex
: DROP INDEX indexName
;
truncateTable
: TRUNCATE TABLE tableName
;
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? (VISIBLE | INVISIBLE)? (DEFAULT (ON NULL)? expr | identityClause)? (ENCRYPT encryptionSpecification_)? (inlineConstraint+ | inlineRefConstraint)?
;
identityClause
: GENERATED (ALWAYS | BY DEFAULT (ON NULL)?) AS IDENTITY LP_? (identityOptions+)? RP_?
;
identityOptions
: START WITH (NUMBER_ | LIMIT VALUE)
| INCREMENT BY NUMBER_
| MAXVALUE NUMBER_
| NOMAXVALUE
| MINVALUE NUMBER_
| NOMINVALUE
| CYCLE
| NOCYCLE
| CACHE NUMBER_
| NOCACHE
| ORDER
| NOORDER
;
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)?
;
tableAlias
: tableName alias? (COMMA_ tableName alias?)*
;
alterClause_
: (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
;
|
/*
* 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 (tableIndexClause_ | bitmapJoinIndexClause_)
;
alterTable
: ALTER TABLE tableName alterClause_
;
// TODO hongjun throw exeption when alter index on oracle
alterIndex
: ALTER INDEX indexName (RENAME TO indexName)?
;
dropTable
: DROP TABLE tableName
;
dropIndex
: DROP INDEX indexName
;
truncateTable
: TRUNCATE TABLE tableName
;
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? (VISIBLE | INVISIBLE)? (DEFAULT (ON NULL)? expr | identityClause)? (ENCRYPT encryptionSpecification_)? (inlineConstraint+ | inlineRefConstraint)?
;
identityClause
: GENERATED (ALWAYS | BY DEFAULT (ON NULL)?) AS IDENTITY LP_? (identityOptions+)? RP_?
;
identityOptions
: START WITH (NUMBER_ | LIMIT VALUE)
| INCREMENT BY NUMBER_
| MAXVALUE NUMBER_
| NOMAXVALUE
| MINVALUE NUMBER_
| NOMINVALUE
| CYCLE
| NOCYCLE
| CACHE NUMBER_
| NOCACHE
| ORDER
| NOORDER
;
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)?
;
tableAlias
: tableName alias? (COMMA_ tableName alias?)*
;
alterClause_
: (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
;
|
check style
|
check style
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
5c0250f1922abe3a80f535a08033a63213ecf18b
|
projects/batfish/src/org/batfish/grammar/cisco/Cisco_routemap.g4
|
projects/batfish/src/org/batfish/grammar/cisco/Cisco_routemap.g4
|
parser grammar Cisco_routemap;
import Cisco_common;
options {
tokenVocab = CiscoLexer;
}
ip_policy_list_stanza
:
IP POLICY_LIST name = variable access_list_action NEWLINE match_rm_stanza*
;
match_as_path_access_list_rm_stanza
:
MATCH AS_PATH
(
name_list += variable
)+ NEWLINE
;
match_community_list_rm_stanza
:
MATCH COMMUNITY
(
name_list +=
(
VARIABLE
| DEC
)
)+ NEWLINE
;
match_extcommunity_rm_stanza
:
MATCH EXTCOMMUNITY
(
name_list +=
(
VARIABLE
| DEC
)
)+ NEWLINE
;
match_interface_rm_stanza
:
MATCH INTERFACE interface_name+ NEWLINE
;
match_ip_access_list_rm_stanza
:
MATCH IP ADDRESS
(
name_list +=
(
VARIABLE
| DEC
)
)+ NEWLINE
;
match_ip_prefix_list_rm_stanza
:
MATCH IP ADDRESS PREFIX_LIST
(
name_list +=
(
VARIABLE
| DEC
)
)+ NEWLINE
;
match_ipv6_rm_stanza
:
MATCH IPV6 ~NEWLINE* NEWLINE
;
match_length_rm_stanza
:
MATCH LENGTH ~NEWLINE* NEWLINE
;
match_policy_list_rm_stanza
:
MATCH POLICY_LIST
(
name_list += variable
)+ NEWLINE
;
match_rm_stanza
:
match_as_path_access_list_rm_stanza
| match_community_list_rm_stanza
| match_extcommunity_rm_stanza
| match_interface_rm_stanza
| match_ip_access_list_rm_stanza
| match_ip_prefix_list_rm_stanza
| match_ipv6_rm_stanza
| match_length_rm_stanza
| match_policy_list_rm_stanza
| match_tag_rm_stanza
;
match_tag_rm_stanza
:
MATCH TAG
(
tag_list += DEC
)+ NEWLINE
;
null_rm_stanza
:
NO?
(
DESCRIPTION
) ~NEWLINE* NEWLINE
;
rm_stanza
:
match_rm_stanza
| null_rm_stanza
| set_rm_stanza
;
route_map_named_stanza
locals [boolean again]
:
ROUTE_MAP name = ~NEWLINE route_map_tail
{
$again = _input.LT(1).getType() == ROUTE_MAP &&
_input.LT(2).getType() != NEWLINE &&
_input.LT(2).getText().equals($name.text);
}
(
{$again}?
route_map_named_stanza
|
{!$again}?
)
;
route_map_stanza
:
named = route_map_named_stanza
;
route_map_tail
:
rmt = access_list_action num = DEC NEWLINE route_map_tail_tail
;
route_map_tail_tail
:
(
rms_list += rm_stanza
)*
;
route_policy_stanza
:
ROUTE_POLICY name = variable NEWLINE ~END_POLICY* END_POLICY NEWLINE
;
set_as_path_prepend_rm_stanza
:
SET AS_PATH PREPEND LAST_AS?
(
as_list += DEC
)+ NEWLINE
;
set_comm_list_delete_rm_stanza
:
SET COMM_LIST
(
name = DEC
| name = VARIABLE
) DELETE NEWLINE
;
set_community_additive_rm_stanza
:
SET COMMUNITY
(
comm_list += community
)+ ADDITIVE NEWLINE
;
set_community_none_rm_stanza
:
SET COMMUNITY NONE NEWLINE
;
set_community_rm_stanza
:
SET COMMUNITY
(
comm_list += community
)+ NEWLINE
;
set_extcomm_list_rm_stanza
:
SET EXTCOMM_LIST
(
comm_list += community
)+ DELETE NEWLINE
;
set_extcommunity_rm_stanza
:
SET EXTCOMMUNITY
(
COST
| RT
) extended_community NEWLINE
;
set_interface_rm_stanza
:
SET INTERFACE ~NEWLINE* NEWLINE
;
set_ip_df_rm_stanza
:
SET IP DF ~NEWLINE* NEWLINE
;
set_ipv6_rm_stanza
:
SET IPV6 ~NEWLINE* NEWLINE
;
set_local_preference_rm_stanza
:
SET LOCAL_PREFERENCE pref = DEC NEWLINE
;
set_metric_rm_stanza
:
SET METRIC metric = DEC NEWLINE
;
set_metric_type_rm_stanza
:
SET METRIC_TYPE type = variable NEWLINE
;
set_mpls_label_rm_stanza
:
SET MPLS_LABEL NEWLINE
;
set_next_hop_peer_address_stanza
:
SET IP NEXT_HOP PEER_ADDRESS NEWLINE
;
set_next_hop_rm_stanza
:
SET IP NEXT_HOP
(
nexthop_list += IP_ADDRESS
)+ NEWLINE
;
set_origin_rm_stanza
:
SET ORIGIN
(
(
EGP as = DEC
)
| IGP
| INCOMPLETE
) NEWLINE
;
set_tag_rm_stanza
:
SET TAG tag = DEC NEWLINE
;
set_weight_rm_stanza
:
SET WEIGHT weight = DEC NEWLINE
;
set_rm_stanza
:
set_as_path_prepend_rm_stanza
| set_comm_list_delete_rm_stanza
| set_community_rm_stanza
| set_community_additive_rm_stanza
| set_community_none_rm_stanza
| set_extcomm_list_rm_stanza
| set_extcommunity_rm_stanza
| set_interface_rm_stanza
| set_ip_df_rm_stanza
| set_ipv6_rm_stanza
| set_local_preference_rm_stanza
| set_metric_rm_stanza
| set_metric_type_rm_stanza
| set_mpls_label_rm_stanza
| set_next_hop_peer_address_stanza
| set_next_hop_rm_stanza
| set_origin_rm_stanza
| set_tag_rm_stanza
| set_weight_rm_stanza
;
|
parser grammar Cisco_routemap;
import Cisco_common;
options {
tokenVocab = CiscoLexer;
}
ip_policy_list_stanza
:
IP POLICY_LIST name = variable access_list_action NEWLINE match_rm_stanza*
;
match_as_path_access_list_rm_stanza
:
MATCH AS_PATH
(
name_list += variable
)+ NEWLINE
;
match_community_list_rm_stanza
:
MATCH COMMUNITY
(
name_list +=
(
VARIABLE
| DEC
)
)+ NEWLINE
;
match_extcommunity_rm_stanza
:
MATCH EXTCOMMUNITY
(
name_list +=
(
VARIABLE
| DEC
)
)+ NEWLINE
;
match_interface_rm_stanza
:
MATCH INTERFACE interface_name+ NEWLINE
;
match_ip_access_list_rm_stanza
:
MATCH IP ADDRESS
(
name_list +=
(
VARIABLE
| DEC
)
)+ NEWLINE
;
match_ip_prefix_list_rm_stanza
:
MATCH IP ADDRESS PREFIX_LIST
(
name_list +=
(
VARIABLE
| DEC
)
)+ NEWLINE
;
match_ipv6_rm_stanza
:
MATCH IPV6 ~NEWLINE* NEWLINE
;
match_length_rm_stanza
:
MATCH LENGTH ~NEWLINE* NEWLINE
;
match_policy_list_rm_stanza
:
MATCH POLICY_LIST
(
name_list += variable
)+ NEWLINE
;
match_rm_stanza
:
match_as_path_access_list_rm_stanza
| match_community_list_rm_stanza
| match_extcommunity_rm_stanza
| match_interface_rm_stanza
| match_ip_access_list_rm_stanza
| match_ip_prefix_list_rm_stanza
| match_ipv6_rm_stanza
| match_length_rm_stanza
| match_policy_list_rm_stanza
| match_tag_rm_stanza
;
match_tag_rm_stanza
:
MATCH TAG
(
tag_list += DEC
)+ NEWLINE
;
null_rm_stanza
:
NO?
(
DESCRIPTION
) ~NEWLINE* NEWLINE
;
rm_stanza
:
match_rm_stanza
| null_rm_stanza
| set_rm_stanza
;
route_map_named_stanza
locals [boolean again]
:
ROUTE_MAP name = ~NEWLINE route_map_tail
{
$again = _input.LT(1).getType() == ROUTE_MAP &&
_input.LT(2).getType() != NEWLINE &&
_input.LT(2).getText().equals($name.text);
}
(
{$again}?
route_map_named_stanza
|
{!$again}?
)
;
route_map_stanza
:
named = route_map_named_stanza
;
route_map_tail
:
rmt = access_list_action num = DEC NEWLINE route_map_tail_tail
;
route_map_tail_tail
:
(
rms_list += rm_stanza
)*
;
route_policy_stanza
:
ROUTE_POLICY name = variable NEWLINE ~END_POLICY* END_POLICY NEWLINE
;
set_as_path_prepend_rm_stanza
:
SET AS_PATH PREPEND LAST_AS?
(
as_list += DEC
)+ NEWLINE
;
set_comm_list_delete_rm_stanza
:
SET COMM_LIST
(
name = DEC
| name = VARIABLE
) DELETE NEWLINE
;
set_community_additive_rm_stanza
:
SET COMMUNITY COMMUNITY_LIST?
(
comm_list += community
)+ ADDITIVE NEWLINE
;
set_community_none_rm_stanza
:
SET COMMUNITY NONE NEWLINE
;
set_community_rm_stanza
:
SET COMMUNITY COMMUNITY_LIST?
(
comm_list += community
)+ NEWLINE
;
set_extcomm_list_rm_stanza
:
SET EXTCOMM_LIST
(
comm_list += community
)+ DELETE NEWLINE
;
set_extcommunity_rm_stanza
:
SET EXTCOMMUNITY
(
COST
| RT
) extended_community NEWLINE
;
set_interface_rm_stanza
:
SET INTERFACE ~NEWLINE* NEWLINE
;
set_ip_df_rm_stanza
:
SET IP DF ~NEWLINE* NEWLINE
;
set_ipv6_rm_stanza
:
SET IPV6 ~NEWLINE* NEWLINE
;
set_local_preference_rm_stanza
:
SET LOCAL_PREFERENCE pref = DEC NEWLINE
;
set_metric_rm_stanza
:
SET METRIC metric = DEC NEWLINE
;
set_metric_type_rm_stanza
:
SET METRIC_TYPE type = variable NEWLINE
;
set_mpls_label_rm_stanza
:
SET MPLS_LABEL NEWLINE
;
set_next_hop_peer_address_stanza
:
SET IP NEXT_HOP PEER_ADDRESS NEWLINE
;
set_next_hop_rm_stanza
:
SET IP NEXT_HOP
(
nexthop_list += IP_ADDRESS
)+ NEWLINE
;
set_origin_rm_stanza
:
SET ORIGIN
(
(
EGP as = DEC
)
| IGP
| INCOMPLETE
) NEWLINE
;
set_tag_rm_stanza
:
SET TAG tag = DEC NEWLINE
;
set_weight_rm_stanza
:
SET WEIGHT weight = DEC NEWLINE
;
set_rm_stanza
:
set_as_path_prepend_rm_stanza
| set_comm_list_delete_rm_stanza
| set_community_rm_stanza
| set_community_additive_rm_stanza
| set_community_none_rm_stanza
| set_extcomm_list_rm_stanza
| set_extcommunity_rm_stanza
| set_interface_rm_stanza
| set_ip_df_rm_stanza
| set_ipv6_rm_stanza
| set_local_preference_rm_stanza
| set_metric_rm_stanza
| set_metric_type_rm_stanza
| set_mpls_label_rm_stanza
| set_next_hop_peer_address_stanza
| set_next_hop_rm_stanza
| set_origin_rm_stanza
| set_tag_rm_stanza
| set_weight_rm_stanza
;
|
allow 'community-list'? for set community-list in route-map
|
allow 'community-list'? for set community-list in route-map
|
ANTLR
|
apache-2.0
|
dhalperi/batfish,batfish/batfish,intentionet/batfish,intentionet/batfish,intentionet/batfish,batfish/batfish,arifogel/batfish,arifogel/batfish,arifogel/batfish,dhalperi/batfish,dhalperi/batfish,intentionet/batfish,intentionet/batfish,batfish/batfish
|
b6c3e88c50f94eefd7b25c33647657cd9633795b
|
java-vtl-parser/src/main/antlr4/no/ssb/vtl/parser/VTL.g4
|
java-vtl-parser/src/main/antlr4/no/ssb/vtl/parser/VTL.g4
|
/*-
* #%L
* Java VTL
* %%
* Copyright (C) 2016 Hadrien Kohl
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
grammar VTL;
start : statement+ EOF;
/* Assignment */
statement : variableID ':=' datasetExpression
| variableID ':=' block
;
block : '{' statement+ '}' ;
/* Expressions */
datasetExpression : <assoc=right>datasetExpression clauseExpression #withClause
| relationalExpression #withRelational
| getExpression #withGet
| putExpression #withPut
| exprAtom #withAtom
;
getExpression : 'get' '(' datasetId ')';
putExpression : 'put(todo)';
datasetId : STRING_CONSTANT ;
/* Atom */
exprAtom : variableRef;
datasetRef: variableRef ;
componentRef : ( datasetRef '.')? variableRef ;
variableRef : identifier;
identifier : '\'' STRING_CONSTANT '\'' | IDENTIFIER ;
variableID : IDENTIFIER ;
constant : INTEGER_CONSTANT | FLOAT_CONSTANT | BOOLEAN_CONSTANT | STRING_CONSTANT | NULL_CONSTANT;
clauseExpression : '[' clause ']' ;
clause : 'rename' renameParam (',' renameParam)* #renameClause
| filter #filterClause
| keep #keepClause
| calc #calcClause
| attrcalc #attrcalcClause
| aggregate #aggregateClause
;
// [ rename component as string,
// component as string role = IDENTIFIER,
// component as string role = MEASURE,
// component as string role = ATTRIBUTE
// ]
renameParam : from=componentRef 'as' to=componentRef ( 'role' '=' role )? ;
role : ( 'IDENTIFIER' | 'MEASURE' | 'ATTRIBUTE' ) ;
filter : 'filter' booleanExpression ;
keep : 'keep' booleanExpression ( ',' booleanExpression )* ;
calc : 'calc' ;
attrcalc : 'attrcalc' ;
aggregate : 'aggregate' ;
//booleanExpression : 'booleanExpression' ;
//varID : 'varId';
//WS : [ \t\n\t] -> skip ;
booleanExpression
: booleanExpression AND booleanExpression
| booleanExpression ( OR booleanExpression | XOR booleanExpression )
| booleanEquallity
| BOOLEAN_CONSTANT
;
booleanEquallity
: booleanEquallity ( ( EQ | NE | LE | GE ) booleanEquallity )
| datasetExpression
// typed constant?
;
//datasetExpression
// : 'dsTest'
// ;
EQ : '=' ;
NE : '<>' ;
LE : '<=' ;
GE : '>=' ;
AND : 'and' ;
OR : 'or' ;
XOR : 'xor' ;
//WS : [ \r\t\u000C] -> skip ;
relationalExpression : unionExpression | joinExpression ;
unionExpression : 'union' '(' datasetExpression (',' datasetExpression )* ')' ;
joinExpression : '[' joinDefinition ']' '{' joinBody '}';
joinDefinition : INNER? joinParam #joinDefinitionInner
| OUTER joinParam #joinDefinitionOuter
| CROSS joinParam #joinDefinitionCross ;
joinParam : datasetRef (',' datasetRef )* ( 'on' dimensionExpression (',' dimensionExpression )* )? ;
dimensionExpression : IDENTIFIER; //unimplemented
joinBody : joinClause (',' joinClause)* ;
joinClause : role? variableID '=' joinCalcExpression # joinCalcClause
| joinDropExpression # joinDropClause
| joinKeepExpression # joinKeepClause
| joinRenameExpression # joinRenameClause
| joinFilterExpression # joinFilterClause
| joinFoldExpression # joinFoldClause
| joinUnfoldExpression # joinUnfoldClause
;
joinFoldExpression : 'fold' elements=foldUnfoldElements 'to' dimension=identifier ',' measure=identifier ;
joinUnfoldExpression : 'unfold' dimension=componentRef ',' measure=componentRef 'to' elements=foldUnfoldElements ;
// TODO: The spec writes examples with parentheses, but it seems unecessary to me.
// TODO: The spec is unclear regarding types of the elements, we support strings only for now.
// TODO: Reuse component references
foldUnfoldElements : STRING_CONSTANT (',' STRING_CONSTANT)* ;
// Left recursive
joinCalcExpression : leftOperand=joinCalcExpression sign=( '*' | '/' ) rightOperand=joinCalcExpression #joinCalcProduct
| leftOperand=joinCalcExpression sign=( '+' | '-' ) rightOperand=joinCalcExpression #joinCalcSummation
| '(' joinCalcExpression ')' #joinCalcPrecedence
| componentRef #joinCalcReference
| constant #joinCalcAtom
;
// Drop clause
joinDropExpression : 'drop' componentRef (',' componentRef)* ;
// Keep clause
joinKeepExpression : 'keep' componentRef (',' componentRef)* ;
// TODO: Use in keep, drop and calc.
// TODO: Make this the membership operator.
// TODO: Revise this when the final version of the specification precisely define if the rename needs ' or not.
// Rename clause
joinRenameExpression : 'rename' joinRenameParameter (',' joinRenameParameter)* ;
joinRenameParameter : from=componentRef 'to' to=identifier ;
// Filter clause
joinFilterExpression : 'filter' booleanExpression ;
//role : ( 'IDENTIFIER' | 'MEASURE' | 'ATTRIBUTE' ) ;
INNER : 'inner' ;
OUTER : 'outer' ;
CROSS : 'cross' ;
INTEGER_CONSTANT : DIGIT+;
BOOLEAN_CONSTANT : 'true' | 'false' ;
STRING_CONSTANT :'"' (~'"')* '"';
FLOAT_CONSTANT : (DIGIT)+ '.' (DIGIT)* FLOATEXP?
| (DIGIT)+ FLOATEXP
;
NULL_CONSTANT : 'null';
IDENTIFIER : REG_IDENTIFIER | ESCAPED_IDENTIFIER ;
//regular identifiers start with a (lowercase or uppercase) English alphabet letter, followed by zero or more letters, decimal digits, or underscores
fragment REG_IDENTIFIER: LETTER(LETTER|'_'|DIGIT)* ; //TODO: Case insensitive??
//VTL 1.1 allows us to escape the limitations imposed on regular identifiers by enclosing them in single quotes (apostrophes).
fragment ESCAPED_IDENTIFIER: QUOTE (~'\'' | '\'\'')+ QUOTE;
fragment QUOTE : '\'';
PLUS : '+';
MINUS : '-';
fragment DIGIT : '0'..'9' ;
fragment FLOATEXP : ('e'|'E')(PLUS|MINUS)?('0'..'9')+;
fragment LETTER : 'A'..'Z' | 'a'..'z';
WS : [ \n\r\t\u000C] -> skip ;
COMMENT : '/*' .*? '*/' -> skip;
|
/*-
* #%L
* Java VTL
* %%
* Copyright (C) 2016 Hadrien Kohl
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
grammar VTL;
start : statement+ EOF;
/* Assignment */
statement : variableID ':=' datasetExpression
| variableID ':=' block
;
block : '{' statement+ '}' ;
/* Expressions */
datasetExpression : <assoc=right>datasetExpression clauseExpression #withClause
| relationalExpression #withRelational
| getExpression #withGet
| putExpression #withPut
| exprAtom #withAtom
;
getExpression : 'get' '(' datasetId ')';
putExpression : 'put(todo)';
datasetId : STRING_CONSTANT ;
/* Atom */
exprAtom : variableRef;
datasetRef: variableRef ;
componentRef : ( datasetRef '.')? variableRef ;
variableRef : identifier;
identifier : '\'' STRING_CONSTANT '\'' | IDENTIFIER ;
variableID : IDENTIFIER ;
constant : INTEGER_CONSTANT | FLOAT_CONSTANT | BOOLEAN_CONSTANT | STRING_CONSTANT | NULL_CONSTANT;
clauseExpression : '[' clause ']' ;
clause : 'rename' renameParam (',' renameParam)* #renameClause
| filter #filterClause
| keep #keepClause
| calc #calcClause
| attrcalc #attrcalcClause
| aggregate #aggregateClause
;
// [ rename component as string,
// component as string role = IDENTIFIER,
// component as string role = MEASURE,
// component as string role = ATTRIBUTE
// ]
renameParam : from=componentRef 'as' to=identifier ( 'role' '=' role )? ;
role : ( 'IDENTIFIER' | 'MEASURE' | 'ATTRIBUTE' ) ;
filter : 'filter' booleanExpression ;
keep : 'keep' booleanExpression ( ',' booleanExpression )* ;
calc : 'calc' ;
attrcalc : 'attrcalc' ;
aggregate : 'aggregate' ;
//booleanExpression : 'booleanExpression' ;
//varID : 'varId';
//WS : [ \t\n\t] -> skip ;
booleanExpression
: booleanExpression AND booleanExpression
| booleanExpression ( OR booleanExpression | XOR booleanExpression )
| booleanEquallity
| BOOLEAN_CONSTANT
;
booleanEquallity
: booleanEquallity ( ( EQ | NE | LE | GE ) booleanEquallity )
| datasetExpression
| constant
// typed constant?
;
//datasetExpression
// : 'dsTest'
// ;
EQ : '=' ;
NE : '<>' ;
LE : '<=' ;
GE : '>=' ;
AND : 'and' ;
OR : 'or' ;
XOR : 'xor' ;
//WS : [ \r\t\u000C] -> skip ;
relationalExpression : unionExpression | joinExpression ;
unionExpression : 'union' '(' datasetExpression (',' datasetExpression )* ')' ;
joinExpression : '[' joinDefinition ']' '{' joinBody '}';
joinDefinition : INNER? joinParam #joinDefinitionInner
| OUTER joinParam #joinDefinitionOuter
| CROSS joinParam #joinDefinitionCross ;
joinParam : datasetRef (',' datasetRef )* ( 'on' dimensionExpression (',' dimensionExpression )* )? ;
dimensionExpression : IDENTIFIER; //unimplemented
joinBody : joinClause (',' joinClause)* ;
joinClause : role? variableID '=' joinCalcExpression # joinCalcClause
| joinDropExpression # joinDropClause
| joinKeepExpression # joinKeepClause
| joinRenameExpression # joinRenameClause
| joinFilterExpression # joinFilterClause
| joinFoldExpression # joinFoldClause
| joinUnfoldExpression # joinUnfoldClause
;
joinFoldExpression : 'fold' elements=componentRefs 'to' dimension=identifier ',' measure=identifier ;
componentRefs : componentRef (',' componentRef)* ;
joinUnfoldExpression : 'unfold' dimension=componentRef ',' measure=componentRef 'to' elements=foldUnfoldElements ;
// TODO: The spec writes examples with parentheses, but it seems unecessary to me.
// TODO: The spec is unclear regarding types of the elements, we support strings only for now.
// TODO: Reuse component references
foldUnfoldElements : STRING_CONSTANT (',' STRING_CONSTANT)* ;
// Left recursive
joinCalcExpression : leftOperand=joinCalcExpression sign=( '*' | '/' ) rightOperand=joinCalcExpression #joinCalcProduct
| leftOperand=joinCalcExpression sign=( '+' | '-' ) rightOperand=joinCalcExpression #joinCalcSummation
| '(' joinCalcExpression ')' #joinCalcPrecedence
| componentRef #joinCalcReference
| constant #joinCalcAtom
;
// Drop clause
joinDropExpression : 'drop' componentRef (',' componentRef)* ;
// Keep clause
joinKeepExpression : 'keep' componentRef (',' componentRef)* ;
// TODO: Use in keep, drop and calc.
// TODO: Make this the membership operator.
// TODO: Revise this when the final version of the specification precisely define if the rename needs ' or not.
// Rename clause
joinRenameExpression : 'rename' joinRenameParameter (',' joinRenameParameter)* ;
joinRenameParameter : from=componentRef 'to' to=identifier ;
// Filter clause
joinFilterExpression : 'filter' booleanExpression ;
//role : ( 'IDENTIFIER' | 'MEASURE' | 'ATTRIBUTE' ) ;
INNER : 'inner' ;
OUTER : 'outer' ;
CROSS : 'cross' ;
INTEGER_CONSTANT : DIGIT+;
BOOLEAN_CONSTANT : 'true' | 'false' ;
STRING_CONSTANT :'"' (~'"')* '"';
FLOAT_CONSTANT : (DIGIT)+ '.' (DIGIT)* FLOATEXP?
| (DIGIT)+ FLOATEXP
;
NULL_CONSTANT : 'null';
IDENTIFIER : REG_IDENTIFIER | ESCAPED_IDENTIFIER ;
//regular identifiers start with a (lowercase or uppercase) English alphabet letter, followed by zero or more letters, decimal digits, or underscores
REG_IDENTIFIER: LETTER(LETTER|'_'|DIGIT)* ; //TODO: Case insensitive??
//VTL 1.1 allows us to escape the limitations imposed on regular identifiers by enclosing them in single quotes (apostrophes).
fragment ESCAPED_IDENTIFIER: QUOTE (~'\'' | '\'\'')+ QUOTE;
fragment QUOTE : '\'';
PLUS : '+';
MINUS : '-';
fragment DIGIT : '0'..'9' ;
fragment FLOATEXP : ('e'|'E')(PLUS|MINUS)?('0'..'9')+;
fragment LETTER : 'A'..'Z' | 'a'..'z';
WS : [ \n\r\t\u000C] -> skip ;
COMMENT : '/*' .*? '*/' -> skip;
|
Use reference in the grammar
|
Use reference in the grammar
|
ANTLR
|
apache-2.0
|
statisticsnorway/java-vtl,statisticsnorway/java-vtl,statisticsnorway/java-vtl,hadrienk/java-vtl,hadrienk/java-vtl,statisticsnorway/java-vtl,hadrienk/java-vtl
|
657917c5241ca51027246e65755c629329b50bf4
|
src/main/antlr/UimaTokenRegex.g4
|
src/main/antlr/UimaTokenRegex.g4
|
/*******************************************************************************
* Copyright 2015-2017 - CNRS (Centre National de Recherche Scientifique)
*
* 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 UimaTokenRegex;
@header {
package fr.univnantes.lina.uima.tkregex.antlr.generated;
}
ruleList
: headerBlock shortcutMatcherDeclaration* ruleDeclaration*
;
headerBlock
: importDeclaration useDeclaration (externalListDeclaration | optionDeclaration)* javaMatcherDeclaration*
;
importDeclaration
: IMPORT Identifier ';'
;
useDeclaration
: mainUseDeclaration
( ',' secondaryUseDeclaration )*
';'
;
mainUseDeclaration : USE typeFullName ('as' typeShortName )? ;
secondaryUseDeclaration : typeFullName 'as' typeShortName ;
typeFullName : Identifier ;
typeShortName : Identifier ;
javaMatcherDeclaration
: JAVA_MATCHER ':' Identifier ';'
;
optionDeclaration
: SET Identifier '=' literal ';'
;
shortcutMatcherDeclaration
: MATCHER Identifier ('as' labelIdentifier)? ':' (featureMatcherDeclaration | Regex ) ';'
;
labelIdentifier
: Identifier
;
ruleDeclaration
: RULE ruleName ':' automatonDeclaration ';'
;
automatonDeclaration
: orBranchingDeclaration +
;
ruleName
: StringLiteral
;
matcherDeclaration
: ( IgnoreMatcher? Regex
| IgnoreMatcher? Identifier
| IgnoreMatcher? featureMatcherDeclaration
)
;
orBranchingDeclaration
: ( '(' automatonDeclaration ('|' automatonDeclaration)* ')'
| matcherDeclaration
) quantifierDeclaration?
;
featureMatcherDeclaration
: '[' ']'
| '[' ( expression | andexpression | orexpression ) ']'
;
//first, we try to match all first level && (e.g. && not included in some sub-expression)
andexpression
: expression (AND expression)*
;
//second, we try to match all first level || (e.g. || not included in some sub-expression)
orexpression
: expression (OR expression )*
;
expression
: atomicExpression
| '(' orexpression ')'
| '(' andexpression ')'
;
atomicExpression
: matcherIdentifier
| featureName operator literal
| featureName arrayOperator literalArray
| featureName inListOperator resourceIdentifier
| 'text' '==' coveredTextIgnoreCase
| 'text' '===' coveredTextExactly
| 'text' inListOperator coveredTextArray
;
matcherIdentifier : Identifier ;
resourceIdentifier
: Identifier
;
externalListDeclaration
: RESOURCE resourceIdentifier ':'
(simpleListDefinition
| csvListDefinition
| tsvListDefinition
| jsonListDefinition
| yamlListDefinition)
';'
;
simpleListDefinition : 'list' '(' path ')' ;
path : StringLiteral ;
yamlListDefinition : 'yaml' '(' path ',' keypath ')' ;
jsonListDefinition : 'json' '(' path ',' keypath ')' ;
csvListDefinition : 'csv' '(' path ',' separator ',' quote ',' IntegerLiteral ')' ;
tsvListDefinition : 'tsv' '(' path (',' IntegerLiteral) ? ')' ;
quote : StringLiteral ;
separator
: StringLiteral
;
keypath
: StringLiteral
;
quantifierDeclaration
: '{' IntegerLiteral (',' IntegerLiteral)? '}'
| '*'
| '?'
| '+'
;
featureName
: (typeShortName '.' )? featureBaseName
;
featureBaseName : Identifier ;
arrayOperator
: 'in'
| 'nin'
;
inListOperator
: arrayOperator
| 'inIgnoreCase'
| 'ninIgnoreCase'
;
operator
: '=='
| '!='
| '<'
| '<='
| '>'
| '>='
;
IgnoreMatcher
: '~'
;
// covered text
coveredTextArray
: '[' StringLiteral (',' StringLiteral)* ']'
;
// covered text
coveredTextIgnoreCase
: StringLiteral;
// covered text
coveredTextExactly
: StringLiteral;
literalArray
: '[' literal (',' literal)* ']'
;
// Literals
literal
: StringLiteral
| IntegerLiteral
| BooleanLiteral
| FloatingPointLiteral
;
// IntegerLiteral
IntegerLiteral
: '0'
| NonZeroDigit Digit*
;
NonZeroDigit: [1-9];
Digit: [0-9];
// Boolean Literals
BooleanLiteral
: 'true'
| 'false'
;
// String Literals
StringLiteral
: '"' StringCharacters? '"'
;
fragment
StringCharacters
: StringCharacter+
;
fragment
StringCharacter
: ~["\\]
| EscapeSequence
;
fragment
EscapeSequence
: '\\' [btnfr"'\\]
;
// Floats literal
FloatingPointLiteral
: Digit+ '.' Digit+
;
// Syntactic tokens
LCURL : '{';
RCURL : '}';
LPAREN : '(';
RPAREN : ')';
LBRACK : '[';
RBRACK : ']';
SEMI : ';';
// Regex Quantifiers
QUESTION : '?';
COLON : ':';
MUL : '*';
PLUS : '+';
// Logical Operators
AND : '&';
OR : '|';
// Operators
GT : '>';
LT : '<';
EQUAL : '==';
LE : '<=';
GE : '>=';
NOTEQUAL : '!=';
IN : 'in';
//header block declaration
IMPORT : 'import';
USE : 'use';
SET : 'set';
JAVA_MATCHER : 'java-matcher';
RESOURCE : 'resource';
// Comments
LINE_COMMENT
: '#' ~[\r\n]* -> skip
;
// Matcher declaration
MATCHER : 'matcher';
// Rule declaration
RULE : 'rule';
Identifier
: IdentifierPart ('.' IdentifierPart)*
;
IdentifierPart
: FirstLetter JavaLetterOrDigit*
;
fragment
FirstLetter
: [a-zA-Z_] // these are the "java letters" below 0xFF
| // covers all characters above 0xFF which are not a surrogate
~[\u0000-\u00FF\uD800-\uDBFF]
{Character.isJavaIdentifierStart(_input.LA(-1))}?
| // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF
[\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
fragment
JavaLetterOrDigit
: [a-zA-Z0-9$_] // these are the "java letters or digits" below 0xFF
| // covers all characters above 0xFF which are not a surrogate
~[\u0000-\u00FF\uD800-\uDBFF]
{Character.isJavaIdentifierPart(_input.LA(-1))}?
| // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF
[\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines
Regex: '/' (~[/]| EscapeSequence)* '/';
|
/*******************************************************************************
* Copyright 2015-2017 - CNRS (Centre National de Recherche Scientifique)
*
* 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 UimaTokenRegex;
@header {
package fr.univnantes.lina.uima.tkregex.antlr.generated;
}
ruleList
: headerBlock shortcutMatcherDeclaration* ruleDeclaration*
;
headerBlock
: importDeclaration useDeclaration (externalListDeclaration | optionDeclaration)* javaMatcherDeclaration*
;
importDeclaration
: IMPORT Identifier ';'
;
useDeclaration
: mainUseDeclaration
( ',' secondaryUseDeclaration )*
';'
;
mainUseDeclaration : USE typeFullName ('as' typeShortName )? ;
secondaryUseDeclaration : typeFullName 'as' typeShortName ;
typeFullName : Identifier ;
typeShortName : Identifier ;
javaMatcherDeclaration
: JAVA_MATCHER ':' Identifier ';'
;
optionDeclaration
: SET Identifier '=' literal ';'
;
shortcutMatcherDeclaration
: MATCHER Identifier ('as' labelIdentifier)? ':' (featureMatcherDeclaration | Regex ) ';'
;
labelIdentifier
: Identifier
;
ruleDeclaration
: RULE ruleName ':' automatonDeclaration ';'
;
automatonDeclaration
: orBranchingDeclaration +
;
ruleName
: StringLiteral
;
matcherDeclaration
: ( IgnoreMatcher? Regex
| IgnoreMatcher? Identifier
| IgnoreMatcher? featureMatcherDeclaration
)
;
orBranchingDeclaration
: ( '(' automatonDeclaration ('|' automatonDeclaration)* ')'
| matcherDeclaration
) quantifierDeclaration?
;
featureMatcherDeclaration
: '[' ']'
| '[' ( expression | andexpression | orexpression ) ']'
;
//first, we try to match all first level && (e.g. && not included in some sub-expression)
andexpression
: expression (AND expression)*
;
//second, we try to match all first level || (e.g. || not included in some sub-expression)
orexpression
: expression (OR expression )*
;
expression
: atomicExpression
| '(' orexpression ')'
| '(' andexpression ')'
;
atomicExpression
: matcherIdentifier
| featureName operator literal
| featureName arrayOperator literalArray
| featureName inListOperator resourceIdentifier
| 'text' '==' coveredTextIgnoreCase
| 'text' '===' coveredTextExactly
| 'text' inListOperator coveredTextArray
;
matcherIdentifier : Identifier ;
resourceIdentifier
: Identifier
;
externalListDeclaration
: RESOURCE resourceIdentifier ':'
(simpleListDefinition
| csvListDefinition
| tsvListDefinition
| jsonListDefinition
| yamlListDefinition)
';'
;
simpleListDefinition : 'list' '(' path ')' ;
path : StringLiteral ;
yamlListDefinition : 'yaml' '(' path ',' keypath ')' ;
jsonListDefinition : 'json' '(' path ',' keypath ')' ;
csvListDefinition : 'csv' '(' path ',' separator ',' quote ',' IntegerLiteral ')' ;
tsvListDefinition : 'tsv' '(' path (',' IntegerLiteral) ? ')' ;
quote : StringLiteral ;
separator
: StringLiteral
;
keypath
: StringLiteral
;
quantifierDeclaration
: '{' IntegerLiteral (',' IntegerLiteral)? '}'
| '*'
| '?'
| '+'
;
featureName
: (typeShortName '.' )? featureBaseName
;
featureBaseName : Identifier ;
arrayOperator
: 'in'
| 'nin'
;
inListOperator
: arrayOperator
| 'inIgnoreCase'
| 'ninIgnoreCase'
;
operator
: '=='
| '!='
| '<'
| '<='
| '>'
| '>='
;
IgnoreMatcher
: '~'
;
// covered text
coveredTextArray
: '[' StringLiteral (',' StringLiteral)* ']'
;
// covered text
coveredTextIgnoreCase
: StringLiteral;
// covered text
coveredTextExactly
: StringLiteral;
literalArray
: '[' literal (',' literal)* ']'
;
// Literals
literal
: StringLiteral
| IntegerLiteral
| BooleanLiteral
| FloatingPointLiteral
;
// IntegerLiteral
IntegerLiteral
: '0'
| NonZeroDigit Digit*
;
NonZeroDigit: [1-9];
Digit: [0-9];
// Boolean Literals
BooleanLiteral
: 'true'
| 'false'
;
// String Literals
StringLiteral
: '"' StringCharacters? '"'
;
fragment
StringCharacters
: StringCharacter+
;
fragment
StringCharacter
: ~["\\]
| EscapeSequence
;
fragment
EscapeSequence
: '\\' [btnfr"'\\]
;
// Floats literal
FloatingPointLiteral
: Digit+ '.' Digit+
;
// Syntactic tokens
LCURL : '{';
RCURL : '}';
LPAREN : '(';
RPAREN : ')';
LBRACK : '[';
RBRACK : ']';
SEMI : ';';
// Regex Quantifiers
QUESTION : '?';
COLON : ':';
MUL : '*';
PLUS : '+';
// Logical Operators
AND : '&';
OR : '|';
// Operators
GT : '>';
LT : '<';
EQUAL : '==';
LE : '<=';
GE : '>=';
NOTEQUAL : '!=';
IN : 'in';
//header block declaration
IMPORT : 'import';
USE : 'use';
SET : 'set';
JAVA_MATCHER : 'java-matcher';
RESOURCE : 'resource';
// Comments
LINE_COMMENT
: '#' ~[\r\n]* -> channel(HIDDEN)
;
// Matcher declaration
MATCHER : 'matcher';
// Rule declaration
RULE : 'rule';
Identifier
: IdentifierPart ('.' IdentifierPart)*
;
IdentifierPart
: FirstLetter JavaLetterOrDigit*
;
fragment
FirstLetter
: [a-zA-Z_] // these are the "java letters" below 0xFF
| // covers all characters above 0xFF which are not a surrogate
~[\u0000-\u00FF\uD800-\uDBFF]
{Character.isJavaIdentifierStart(_input.LA(-1))}?
| // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF
[\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
fragment
JavaLetterOrDigit
: [a-zA-Z0-9$_] // these are the "java letters or digits" below 0xFF
| // covers all characters above 0xFF which are not a surrogate
~[\u0000-\u00FF\uD800-\uDBFF]
{Character.isJavaIdentifierPart(_input.LA(-1))}?
| // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF
[\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
WS : [ \t\r\n]+ -> channel(HIDDEN) ; // skip spaces, tabs, newlines
Regex: '/' (~[/]| EscapeSequence)* '/';
|
improve lexer error printing by hiding whitespaces instead of skipping
|
improve lexer error printing by hiding whitespaces instead of skipping
|
ANTLR
|
apache-2.0
|
JuleStar/uima-tokens-regex
|
adb5be432935f6179a47fcd6e835815f30d99af5
|
css3/css3.g4
|
css3/css3.g4
|
grammar css3;
stylesheet
: importRule* (nested | ruleset)+
;
importRule
: ('@import' | '@include') STRING
;
nested
: '@' nest '{' properties? nested* '}'
;
nest
: IDENT IDENT* pseudo*
;
ruleset
: selectors '{' properties? '}'
;
selectors
: selector (',' selector)*
;
selector
: elem selectorOperation* attrib* pseudo?
;
selectorOperation
: selectop? elem
;
selectop
: '>'
| '+'
;
properties
: declaration (';' declaration?)*
;
elem
: IDENT
| '#' IDENT
| '.' IDENT
;
pseudo
: (':'|'::') IDENT
| (':'|'::') function
;
attrib
: '[' IDENT (attribRelate (STRING | IDENT))? ']'
;
attribRelate
: '='
| '~='
| '|='
;
declaration
: IDENT ':' args
;
args
: expr (','? expr)*
;
expr
: (NUM unit?)
| IDENT
| COLOR
| STRING
| function
;
unit
: ('%'|'px'|'cm'|'mm'|'in'|'pt'|'pc'|'em'|'ex'|'deg'|'rad'|'grad'|'ms'|'s'|'hz'|'khz')
;
function
: IDENT '(' args? ')'
;
IDENT
: ('_' | 'a'..'z'| 'A'..'Z' | '\u0100'..'\ufffe' )
('_' | '-' | 'a'..'z'| 'A'..'Z' | '\u0100'..'\ufffe' | '0'..'9')*
| '-' ('_' | 'a'..'z'| 'A'..'Z' | '\u0100'..'\ufffe' )
('_' | '-' | 'a'..'z'| 'A'..'Z' | '\u0100'..'\ufffe' | '0'..'9')*
;
STRING
: '"' (~('"'|'\n'|'\r'))* '"'
| '\'' (~('\''|'\n'|'\r'))* '\''
;
NUM
: '-' (('0'..'9')* '.')? ('0'..'9')+
| (('0'..'9')* '.')? ('0'..'9')+
;
COLOR
: '#' ('0'..'9'|'a'..'f'|'A'..'F')+
;
SL_COMMENT
: '//' (~('\n'|'\r'))* ('\n'|'\r'('\n')?) ->skip
;
COMMENT
: '/*' .* '*/' ->skip
;
WS : ( ' ' | '\t' | '\r' | '\n' | '\f' )+ ->skip
;
|
grammar css3;
stylesheet
: importRule* (nested | ruleset)+
;
import_css
: ('@import' | '@include') (STRING|URI) ';'?
;
nested
: '@' nest '{' properties? nested* '}'
;
nest
: IDENT IDENT* pseudo*
;
ruleset
: selectors '{' properties? '}'
;
selectors
: selector (',' selector)*
;
selector
: elem selectorOperation* attrib* pseudo?
;
selectorOperation
: selectop? elem
;
selectop
: '>'
| '+'
;
properties
: declaration (';' declaration?)*
;
elem
: IDENT
| '#' IDENT
| '.' IDENT
;
pseudo
: (':'|'::') IDENT
| (':'|'::') function
;
attrib
: '[' IDENT (attribRelate (STRING | IDENT))? ']'
;
attribRelate
: '='
| '~='
| '|='
;
declaration
: IDENT ':' args
;
args
: expr (','? expr)*
;
expr
: (NUM unit?)
| IDENT
| COLOR
| STRING
| function
;
unit
: ('%'|'px'|'cm'|'mm'|'in'|'pt'|'pc'|'em'|'ex'|'deg'|'rad'|'grad'|'ms'|'s'|'hz'|'khz')
;
function
: IDENT '(' args? ')'
;
IDENT
: ('_' | 'a'..'z'| 'A'..'Z' | '\u0100'..'\ufffe' )
('_' | '-' | 'a'..'z'| 'A'..'Z' | '\u0100'..'\ufffe' | '0'..'9')*
| '-' ('_' | 'a'..'z'| 'A'..'Z' | '\u0100'..'\ufffe' )
('_' | '-' | 'a'..'z'| 'A'..'Z' | '\u0100'..'\ufffe' | '0'..'9')*
;
STRING
: '"' (~('"'|'\n'|'\r'))* '"'
| '\'' (~('\''|'\n'|'\r'))* '\''
;
NUM
: '-' (('0'..'9')* '.')? ('0'..'9')+
| (('0'..'9')* '.')? ('0'..'9')+
;
COLOR
: '#' ('0'..'9'|'a'..'f'|'A'..'F')+
;
SL_COMMENT
: '//' (~('\n'|'\r'))* ('\n'|'\r'('\n')?) ->skip
;
COMMENT
: '/*' .* '*/' ->skip
;
WS : ( ' ' | '\t' | '\r' | '\n' | '\f' )+ ->skip
;
URI : 'url(' (~('\n'|'\r'))* ')'?
;
|
Update css3.g4
|
Update css3.g4
Adding suport to @import url(STRING)
Ex.:
@import url("Style.css");
@import "Style.css";
.c {
color: black;
}
|
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
|
cdae579d5c4e017a762467573a088590d387e445
|
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 | 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_)*
;
|
/*
* 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 GROUP_CONCAT's syntax
|
fix GROUP_CONCAT's syntax
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
68ede897e2ccb52a8dd1e7a784e5402fc915c246
|
MATLAB.g4
|
MATLAB.g4
|
grammar MATLAB;
fileDecl : functionDecl // (functionDecl | classDecl)? functionDecl*
// | stat* // Script
;
functionDecl
: 'function' outArgs? ID inArgs? NL
;
outArgs
: ID '='
| '[' ID (',' ID)* ']' '='
;
inArgs
: '(' ID (',' ID)* ')'
;
fragment
DIGIT
: [0-9] ;
NL : '\r'?'\n' ;
WS : [ \t]+ -> skip ;
fragment
LETTER
: [a-zA-Z] ;
ID : LETTER (LETTER|DIGIT|'_')* ;
|
grammar MATLAB;
fileDecl
: (functionDecl | classDecl)? functionDecl*
| stat* // Script
;
functionDecl
: 'function' outArgs? ID inArgs? NL stat* 'end' NL+
;
classDecl
: 'classdef' ID NL (propDecl|methodDecl)* 'end' NL+
;
propDecl
: 'properties' NL prop* 'end' NL+
;
methodDecl
: 'methods' NL functionDecl* 'end' NL+
;
outArgs
: ID '='
| '[' ID (',' ID)* ']' '='
;
inArgs
: '(' ID (',' ID)* ')'
| '(' ')'
;
prop
: ID ('=' expr)? NL
;
stat
: ID
| NL
;
expr
: ID
;
fragment
DIGIT
: [0-9] ;
NL : '\r'?'\n' ;
WS : [ \t]+ -> skip ;
fragment
LETTER
: [a-zA-Z] ;
ID : LETTER (LETTER|DIGIT|'_')* ;
|
Add simple classdef rule.
|
Add simple classdef rule.
|
ANTLR
|
apache-2.0
|
mattmcd/ParseMATLAB,mattmcd/ParseMATLAB
|
103c3b87deac72960f106bb15130aa28b09d380b
|
cache/src/main/antlr4/net/runelite/cache/script/assembler/rs2asm.g4
|
cache/src/main/antlr4/net/runelite/cache/script/assembler/rs2asm.g4
|
/*
* Copyright (c) 2017, Adam <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 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.
*
* 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 OWNER 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 rs2asm;
prog: (header NEWLINE+)* (line NEWLINE+)+ ;
header: id | int_stack_count | string_stack_count | int_var_count | string_var_count ;
id: '.id ' id_value ;
int_stack_count: '.int_stack_count ' int_stack_value ;
string_stack_count: '.string_stack_count ' string_stack_value ;
int_var_count: '.int_var_count ' int_var_value ;
string_var_count: '.string_var_count ' string_var_value ;
id_value: INT ;
int_stack_value: INT ;
string_stack_value: INT ;
int_var_value: INT ;
string_var_value: INT ;
line: instruction | label | switch_lookup ;
instruction: instruction_name instruction_operand ;
label: 'LABEL' INT ':' ;
instruction_name: name_string | name_opcode ;
name_string: INSTRUCTION ;
name_opcode: INT ;
instruction_operand: operand_int | operand_qstring | operand_label | ;
operand_int: INT ;
operand_qstring: QSTRING ;
operand_label: 'LABEL' INT ;
switch_lookup: switch_key ':' switch_value ;
switch_key: INT ;
switch_value: 'LABEL' INT ;
NEWLINE: ( '\r' | '\n' )+ ;
INT: '-'? [0-9]+ ;
QSTRING: '"' (~('"' | '\\' | '\r' | '\n') | '\\' ('"' | '\\'))* '"' ;
INSTRUCTION: [a-z0-9_]+ ;
COMMENT: ';' ~( '\r' | '\n' )* -> channel(HIDDEN) ;
WS: (' ' | '\t')+ -> channel(HIDDEN) ;
|
/*
* Copyright (c) 2017, Adam <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 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.
*
* 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 OWNER 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 rs2asm;
prog: NEWLINE* (header NEWLINE+)* (line NEWLINE+)+ ;
header: id | int_stack_count | string_stack_count | int_var_count | string_var_count ;
id: '.id ' id_value ;
int_stack_count: '.int_stack_count ' int_stack_value ;
string_stack_count: '.string_stack_count ' string_stack_value ;
int_var_count: '.int_var_count ' int_var_value ;
string_var_count: '.string_var_count ' string_var_value ;
id_value: INT ;
int_stack_value: INT ;
string_stack_value: INT ;
int_var_value: INT ;
string_var_value: INT ;
line: instruction | label | switch_lookup ;
instruction: instruction_name instruction_operand ;
label: 'LABEL' INT ':' ;
instruction_name: name_string | name_opcode ;
name_string: INSTRUCTION ;
name_opcode: INT ;
instruction_operand: operand_int | operand_qstring | operand_label | ;
operand_int: INT ;
operand_qstring: QSTRING ;
operand_label: 'LABEL' INT ;
switch_lookup: switch_key ':' switch_value ;
switch_key: INT ;
switch_value: 'LABEL' INT ;
NEWLINE: ( '\r' | '\n' )+ ;
INT: '-'? [0-9]+ ;
QSTRING: '"' (~('"' | '\\' | '\r' | '\n') | '\\' ('"' | '\\'))* '"' ;
INSTRUCTION: [a-z0-9_]+ ;
COMMENT: ';' ~( '\r' | '\n' )* -> channel(HIDDEN) ;
WS: (' ' | '\t')+ -> channel(HIDDEN) ;
|
Allow scripts to start with comments
|
cache: Allow scripts to start with comments
|
ANTLR
|
bsd-2-clause
|
runelite/runelite,Sethtroll/runelite,l2-/runelite,abelbriggs1/runelite,l2-/runelite,abelbriggs1/runelite,devinfrench/runelite,runelite/runelite,devinfrench/runelite,abelbriggs1/runelite,KronosDesign/runelite,Sethtroll/runelite,runelite/runelite,Noremac201/runelite,KronosDesign/runelite,Noremac201/runelite
|
b58291b299b4bc469ffc0b54757177157a028fa1
|
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
WS : ' ' { 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 : ',';
// Skip whitspaces
WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
|
Update whitespace skipping rule
|
Update whitespace skipping rule
|
ANTLR
|
bsd-2-clause
|
clementval/claw-compiler,clementval/claw-compiler
|
b6c7fc00b715a99b6ccdb0e9d0204df1d0f5d6ad
|
sharding-core/sharding-core-parse/sharding-core-parse-sqlserver/src/main/antlr4/imports/sqlserver/DDLStatement.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-sqlserver/src/main/antlr4/imports/sqlserver/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 TABLE tableName fileTableClause_ createDefinitionClause_
;
createIndex
: CREATE createIndexSpecification_ INDEX indexName ON tableName columnNames
;
alterTable
: ALTER TABLE tableName alterClause_
;
alterIndex
: ALTER INDEX (indexName | ALL) ON tableName
;
dropTable
: DROP TABLE (IF EXISTS)? tableName (COMMA_ tableName)*
;
dropIndex
: DROP INDEX (IF EXISTS)? indexName ON tableName
;
truncateTable
: TRUNCATE TABLE tableName
;
fileTableClause_
: (AS FILETABLE)?
;
createDefinitionClause_
: createTableDefinitions_ partitionScheme_ fileGroup_
;
createTableDefinitions_
: LP_ createTableDefinition_ (COMMA_ createTableDefinition_)* (COMMA_ periodClause)? RP_
;
createTableDefinition_
: columnDefinition | computedColumnDefinition | columnSetDefinition | tableConstraint | tableIndex
;
columnDefinition
: columnName dataType columnDefinitionOption* columnConstraints columnIndex?
;
columnDefinitionOption
: FILESTREAM
| COLLATE collationName
| SPARSE
| MASKED WITH LP_ FUNCTION EQ_ STRING_ RP_
| (CONSTRAINT ignoredIdentifier_)? DEFAULT expr
| IDENTITY (LP_ NUMBER_ COMMA_ NUMBER_ RP_)?
| NOT FOR REPLICATION
| GENERATED ALWAYS AS ROW (START | END) HIDDEN_?
| NOT? NULL
| ROWGUIDCOL
| ENCRYPTED WITH LP_ COLUMN_ENCRYPTION_KEY EQ_ ignoredIdentifier_ COMMA_ ENCRYPTION_TYPE EQ_ (DETERMINISTIC | RANDOMIZED) COMMA_ ALGORITHM EQ_ STRING_ RP_
| columnConstraint (COMMA_ columnConstraint)*
| columnIndex
;
columnConstraint
: (CONSTRAINT ignoredIdentifier_)? (primaryKeyConstraint | columnForeignKeyConstraint | checkConstraint)
;
primaryKeyConstraint
: (primaryKey | UNIQUE) (diskTablePrimaryKeyConstraintOption | memoryTablePrimaryKeyConstraintOption)
;
diskTablePrimaryKeyConstraintOption
: (CLUSTERED | NONCLUSTERED)? primaryKeyWithClause? primaryKeyOnClause?
;
primaryKeyWithClause
: WITH (FILLFACTOR EQ_ NUMBER_ | LP_ indexOption (COMMA_ indexOption)* RP_)
;
primaryKeyOnClause
: onSchemaColumn | onFileGroup | onString
;
onSchemaColumn
: ON schemaName LP_ columnName RP_
;
onFileGroup
: ON ignoredIdentifier_
;
onString
: ON STRING_
;
memoryTablePrimaryKeyConstraintOption
: CLUSTERED withBucket?
;
withBucket
: WITH LP_ BUCKET_COUNT EQ_ NUMBER_ RP_
;
columnForeignKeyConstraint
: (FOREIGN KEY)? REFERENCES tableName LP_ columnName RP_ foreignKeyOnAction*
;
foreignKeyOnAction
: ON (DELETE | UPDATE) foreignKeyOn | NOT FOR REPLICATION
;
foreignKeyOn
: NO ACTION | CASCADE | SET (NULL | DEFAULT)
;
checkConstraint
: CHECK(NOT FOR REPLICATION)? LP_ expr RP_
;
columnIndex
: INDEX indexName (CLUSTERED | NONCLUSTERED)? (WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause? (FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))?
;
indexOnClause
: onSchemaColumn | onFileGroup | onDefault
;
onDefault
: ON DEFAULT
;
columnConstraints
: (columnConstraint(COMMA_ columnConstraint)*)?
;
computedColumnDefinition
: columnName AS expr (PERSISTED(NOT NULL)?)? columnConstraint?
;
columnSetDefinition
: ignoredIdentifier_ IDENTIFIER_ COLUMN_SET FOR ALL_SPARSE_COLUMNS
;
tableConstraint
: (CONSTRAINT ignoredIdentifier_)? (tablePrimaryConstraint | tableForeignKeyConstraint | checkConstraint)
;
tablePrimaryConstraint
: primaryKeyUnique (diskTablePrimaryConstraintOption | memoryTablePrimaryConstraintOption)
;
primaryKeyUnique
: primaryKey | UNIQUE
;
diskTablePrimaryConstraintOption
: (CLUSTERED | NONCLUSTERED)? columnNames primaryKeyWithClause? primaryKeyOnClause?
;
memoryTablePrimaryConstraintOption
: NONCLUSTERED (columnNames | hashWithBucket)
;
hashWithBucket
: HASH columnNames withBucket
;
tableForeignKeyConstraint
: (FOREIGN KEY)? columnNames REFERENCES tableName columnNames foreignKeyOnAction*
;
tableIndex
: INDEX indexName
((CLUSTERED | NONCLUSTERED)? columnNames
| CLUSTERED COLUMNSTORE
| NONCLUSTERED? (COLUMNSTORE columnNames | hashWithBucket)
| CLUSTERED COLUMNSTORE (WITH LP_ COMPRESSION_DELAY EQ_ (NUMBER_ MINUTES?) RP_)?)
(WHERE expr)?
(WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause?
(FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))?
;
createIndexSpecification_
: UNIQUE? (CLUSTERED | NONCLUSTERED)?
;
alterClause_
: alterColumn | addColumnSpecification | alterDrop | alterCheckConstraint | alterTrigger | alterSwitch | alterSet | alterTableTableOption | REBUILD
;
tableOption
: DATA_COMPRESSION EQ_ (NONE | ROW | PAGE) (ON PARTITIONS LP_ partitionExpressions RP_)?
| FILETABLE_DIRECTORY EQ_ ignoredIdentifier_
| FILETABLE_COLLATE_FILENAME EQ_ (collationName | DATABASE_DEAULT)
| FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME EQ_ ignoredIdentifier_
| FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME EQ_ ignoredIdentifier_
| FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME EQ_ ignoredIdentifier_
| SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?
| REMOTE_DATA_ARCHIVE EQ_ (ON (LP_ tableStretchOptions (COMMA_ tableStretchOptions)* RP_)? | OFF LP_ MIGRATION_STATE EQ_ PAUSED RP_)
| tableOptOption
| distributionOption
| dataWareHouseTableOption
;
tableOptOption
: (MEMORY_OPTIMIZED EQ_ ON) | (DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA)) | (SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?)
;
distributionOption
: DISTRIBUTION EQ_ (HASH LP_ columnName RP_ | ROUND_ROBIN | REPLICATE)
;
dataWareHouseTableOption
: CLUSTERED COLUMNSTORE INDEX | HEAP | dataWareHousePartitionOption
;
dataWareHousePartitionOption
: (PARTITION LP_ columnName RANGE (LEFT | RIGHT)? FOR VALUES LP_ simpleExpr (COMMA_ simpleExpr)* RP_ RP_)
;
tableStretchOptions
: (FILTER_PREDICATE EQ_ (NULL | functionCall) COMMA_)? MIGRATION_STATE EQ_ (OUTBOUND | INBOUND | PAUSED)
;
partitionScheme_
: (ON (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_))?
;
fileGroup_
: (TEXTIMAGE_ON (ignoredIdentifier_ | STRING_))? ((FILESTREAM_ON (schemaName) | ignoredIdentifier_ STRING_))? (WITH LP_ tableOption (COMMA_ tableOption)* RP_)?
;
periodClause
: PERIOD FOR SYSTEM_TIME LP_ columnName COMMA_ columnName RP_
;
alterColumn
: modifyColumnSpecification
;
modifyColumnSpecification
: alterColumnOperation dataType (COLLATE collationName)? (NULL | NOT NULL)? SPARSE?
;
alterColumnOperation
: ALTER COLUMN columnName
;
addColumnSpecification
: (WITH (CHECK | NOCHECK))? ADD (alterColumnAddOption (COMMA_ alterColumnAddOption)* | (columnNameGeneratedClause COMMA_ periodClause| periodClause COMMA_ columnNameGeneratedClause))
;
alterColumnAddOption
: columnDefinition
| computedColumnDefinition
| columnSetDefinition
| tableConstraint
| alterTableTableIndex
| constraintForColumn
;
constraintForColumn
: (CONSTRAINT ignoredIdentifier_)? DEFAULT simpleExpr FOR columnName
;
columnNameWithSortsWithParen
: LP_ columnNameWithSort (COMMA_ columnNameWithSort)* RP_
;
columnNameWithSort
: columnName (ASC | DESC)?
;
columnNameGeneratedClause
: columnNameGenerated DEFAULT simpleExpr (WITH VALUES)? COMMA_ columnNameGenerated
;
columnNameGenerated
: columnName dataTypeName_ GENERATED ALWAYS AS ROW (START | END)? HIDDEN_? (NOT NULL)? (CONSTRAINT ignoredIdentifier_)?
;
alterDrop
: DROP
(
alterTableDropConstraint
| dropColumnSpecification
| dropIndexSpecification
| PERIOD FOR SYSTEM_TIME
)
;
alterTableDropConstraint
: CONSTRAINT? (IF EXISTS)? dropConstraintName (COMMA_ dropConstraintName)*
;
dropConstraintName
: ignoredIdentifier_ dropConstraintWithClause?
;
dropConstraintWithClause
: WITH LP_ dropConstraintOption (COMMA_ dropConstraintOption)* RP_
;
dropConstraintOption
: (MAXDOP EQ_ NUMBER_ | ONLINE EQ_ (ON | OFF) | MOVE TO (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_))
;
dropColumnSpecification
: COLUMN (IF EXISTS)? columnName (COMMA_ columnName)*
;
dropIndexSpecification
: INDEX (IF EXISTS)? indexName (COMMA_ indexName)*
;
alterCheckConstraint
: WITH? (CHECK | NOCHECK) CONSTRAINT (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*))
;
alterTrigger
: (ENABLE| DISABLE) TRIGGER (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*))
;
alterSwitch
: SWITCH (PARTITION expr)? TO tableName (PARTITION expr)? (WITH LP_ lowPriorityLockWait RP_)?
;
alterSet
: SET LP_ (setFileStreamClause | setSystemVersionClause) RP_
;
setFileStreamClause
: FILESTREAM_ON EQ_ (schemaName | ignoredIdentifier_ | STRING_)
;
setSystemVersionClause
: SYSTEM_VERSIONING EQ_ (OFF | alterSetOnClause)
;
alterSetOnClause
: ON
(
LP_ (HISTORY_TABLE EQ_ tableName)?
(COMMA_? DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))?
(COMMA_? HISTORY_RETENTION_PERIOD EQ_ (INFINITE | (NUMBER_ (DAY | DAYS | WEEK | WEEKS | MONTH | MONTHS | YEAR | YEARS))))?
RP_
)?
;
alterTableTableIndex
: indexWithName (indexNonClusterClause | indexClusterClause)
;
indexWithName
: INDEX indexName
;
indexNonClusterClause
: NONCLUSTERED (hashWithBucket | (columnNameWithSortsWithParen alterTableIndexOnClause?))
;
alterTableIndexOnClause
: ON ignoredIdentifier_ | DEFAULT
;
indexClusterClause
: CLUSTERED COLUMNSTORE (WITH COMPRESSION_DELAY EQ_ NUMBER_ MINUTES?)? indexOnClause?
;
alterTableTableOption
: SET LP_ LOCK_ESCALATION EQ_ (AUTO | TABLE | DISABLE) RP_
| MEMORY_OPTIMIZED EQ_ ON
| DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA)
| SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?
;
|
/*
* 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 TABLE tableName fileTableClause_ createDefinitionClause_
;
createIndex
: CREATE createIndexSpecification_ INDEX indexName ON tableName columnNames
;
alterTable
: ALTER TABLE tableName alterClause_
;
alterIndex
: ALTER INDEX (indexName | ALL) ON tableName
;
dropTable
: DROP TABLE (IF EXISTS)? tableName (COMMA_ tableName)*
;
dropIndex
: DROP INDEX (IF EXISTS)? indexName ON tableName
;
truncateTable
: TRUNCATE TABLE tableName
;
fileTableClause_
: (AS FILETABLE)?
;
createDefinitionClause_
: createTableDefinitions_ partitionScheme_ fileGroup_
;
createTableDefinitions_
: LP_ createTableDefinition_ (COMMA_ createTableDefinition_)* (COMMA_ periodClause)? RP_
;
createTableDefinition_
: columnDefinition | computedColumnDefinition | columnSetDefinition | tableConstraint | tableIndex
;
columnDefinition
: columnName dataType columnDefinitionOption* columnConstraints columnIndex?
;
columnDefinitionOption
: FILESTREAM
| COLLATE collationName
| SPARSE
| MASKED WITH LP_ FUNCTION EQ_ STRING_ RP_
| (CONSTRAINT ignoredIdentifier_)? DEFAULT expr
| IDENTITY (LP_ NUMBER_ COMMA_ NUMBER_ RP_)?
| NOT FOR REPLICATION
| GENERATED ALWAYS AS ROW (START | END) HIDDEN_?
| NOT? NULL
| ROWGUIDCOL
| ENCRYPTED WITH LP_ COLUMN_ENCRYPTION_KEY EQ_ ignoredIdentifier_ COMMA_ ENCRYPTION_TYPE EQ_ (DETERMINISTIC | RANDOMIZED) COMMA_ ALGORITHM EQ_ STRING_ RP_
| columnConstraint (COMMA_ columnConstraint)*
| columnIndex
;
columnConstraint
: (CONSTRAINT ignoredIdentifier_)? (primaryKeyConstraint | columnForeignKeyConstraint | checkConstraint)
;
primaryKeyConstraint
: (primaryKey | UNIQUE) (diskTablePrimaryKeyConstraintOption | memoryTablePrimaryKeyConstraintOption)
;
diskTablePrimaryKeyConstraintOption
: (CLUSTERED | NONCLUSTERED)? primaryKeyWithClause? primaryKeyOnClause?
;
primaryKeyWithClause
: WITH (FILLFACTOR EQ_ NUMBER_ | LP_ indexOption (COMMA_ indexOption)* RP_)
;
primaryKeyOnClause
: onSchemaColumn | onFileGroup | onString
;
onSchemaColumn
: ON schemaName LP_ columnName RP_
;
onFileGroup
: ON ignoredIdentifier_
;
onString
: ON STRING_
;
memoryTablePrimaryKeyConstraintOption
: CLUSTERED withBucket?
;
withBucket
: WITH LP_ BUCKET_COUNT EQ_ NUMBER_ RP_
;
columnForeignKeyConstraint
: (FOREIGN KEY)? REFERENCES tableName LP_ columnName RP_ foreignKeyOnAction*
;
foreignKeyOnAction
: ON (DELETE | UPDATE) foreignKeyOn | NOT FOR REPLICATION
;
foreignKeyOn
: NO ACTION | CASCADE | SET (NULL | DEFAULT)
;
checkConstraint
: CHECK(NOT FOR REPLICATION)? LP_ expr RP_
;
columnIndex
: INDEX indexName (CLUSTERED | NONCLUSTERED)? (WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause? (FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))?
;
indexOnClause
: onSchemaColumn | onFileGroup | onDefault
;
onDefault
: ON DEFAULT
;
columnConstraints
: (columnConstraint(COMMA_ columnConstraint)*)?
;
computedColumnDefinition
: columnName AS expr (PERSISTED(NOT NULL)?)? columnConstraint?
;
columnSetDefinition
: ignoredIdentifier_ IDENTIFIER_ COLUMN_SET FOR ALL_SPARSE_COLUMNS
;
tableConstraint
: (CONSTRAINT ignoredIdentifier_)? (tablePrimaryConstraint | tableForeignKeyConstraint | checkConstraint)
;
tablePrimaryConstraint
: primaryKeyUnique (diskTablePrimaryConstraintOption | memoryTablePrimaryConstraintOption)
;
primaryKeyUnique
: primaryKey | UNIQUE
;
diskTablePrimaryConstraintOption
: (CLUSTERED | NONCLUSTERED)? columnNames primaryKeyWithClause? primaryKeyOnClause?
;
memoryTablePrimaryConstraintOption
: NONCLUSTERED (columnNames | hashWithBucket)
;
hashWithBucket
: HASH columnNames withBucket
;
tableForeignKeyConstraint
: (FOREIGN KEY)? columnNames REFERENCES tableName columnNames foreignKeyOnAction*
;
tableIndex
: INDEX indexName
((CLUSTERED | NONCLUSTERED)? columnNames
| CLUSTERED COLUMNSTORE
| NONCLUSTERED? (COLUMNSTORE columnNames | hashWithBucket)
| CLUSTERED COLUMNSTORE (WITH LP_ COMPRESSION_DELAY EQ_ (NUMBER_ MINUTES?) RP_)?)
(WHERE expr)?
(WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause?
(FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))?
;
createIndexSpecification_
: UNIQUE? (CLUSTERED | NONCLUSTERED)?
;
alterClause_
: modifyColumnSpecification | addColumnSpecification | alterDrop | alterCheckConstraint | alterTrigger | alterSwitch | alterSet | alterTableTableOption | REBUILD
;
tableOption
: DATA_COMPRESSION EQ_ (NONE | ROW | PAGE) (ON PARTITIONS LP_ partitionExpressions RP_)?
| FILETABLE_DIRECTORY EQ_ ignoredIdentifier_
| FILETABLE_COLLATE_FILENAME EQ_ (collationName | DATABASE_DEAULT)
| FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME EQ_ ignoredIdentifier_
| FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME EQ_ ignoredIdentifier_
| FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME EQ_ ignoredIdentifier_
| SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?
| REMOTE_DATA_ARCHIVE EQ_ (ON (LP_ tableStretchOptions (COMMA_ tableStretchOptions)* RP_)? | OFF LP_ MIGRATION_STATE EQ_ PAUSED RP_)
| tableOptOption
| distributionOption
| dataWareHouseTableOption
;
tableOptOption
: (MEMORY_OPTIMIZED EQ_ ON) | (DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA)) | (SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?)
;
distributionOption
: DISTRIBUTION EQ_ (HASH LP_ columnName RP_ | ROUND_ROBIN | REPLICATE)
;
dataWareHouseTableOption
: CLUSTERED COLUMNSTORE INDEX | HEAP | dataWareHousePartitionOption
;
dataWareHousePartitionOption
: (PARTITION LP_ columnName RANGE (LEFT | RIGHT)? FOR VALUES LP_ simpleExpr (COMMA_ simpleExpr)* RP_ RP_)
;
tableStretchOptions
: (FILTER_PREDICATE EQ_ (NULL | functionCall) COMMA_)? MIGRATION_STATE EQ_ (OUTBOUND | INBOUND | PAUSED)
;
partitionScheme_
: (ON (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_))?
;
fileGroup_
: (TEXTIMAGE_ON (ignoredIdentifier_ | STRING_))? ((FILESTREAM_ON (schemaName) | ignoredIdentifier_ STRING_))? (WITH LP_ tableOption (COMMA_ tableOption)* RP_)?
;
periodClause
: PERIOD FOR SYSTEM_TIME LP_ columnName COMMA_ columnName RP_
;
modifyColumnSpecification
: alterColumnOperation dataType (COLLATE collationName)? (NULL | NOT NULL)? SPARSE?
;
alterColumnOperation
: ALTER COLUMN columnName
;
addColumnSpecification
: (WITH (CHECK | NOCHECK))? ADD (alterColumnAddOptions | (generatedColumnNameClause COMMA_ periodClause | periodClause COMMA_ generatedColumnNameClause))
;
alterColumnAddOptions
: alterColumnAddOption (COMMA_ alterColumnAddOption)*
;
alterColumnAddOption
: columnDefinition
| computedColumnDefinition
| columnSetDefinition
| tableConstraint
| alterTableTableIndex
| constraintForColumn
;
constraintForColumn
: (CONSTRAINT ignoredIdentifier_)? DEFAULT simpleExpr FOR columnName
;
columnNameWithSortsWithParen
: LP_ columnNameWithSort (COMMA_ columnNameWithSort)* RP_
;
columnNameWithSort
: columnName (ASC | DESC)?
;
generatedColumnNameClause
: generatedColumnName DEFAULT simpleExpr (WITH VALUES)? COMMA_ generatedColumnName
;
generatedColumnName
: columnName dataTypeName_ GENERATED ALWAYS AS ROW (START | END)? HIDDEN_? (NOT NULL)? (CONSTRAINT ignoredIdentifier_)?
;
alterDrop
: DROP
(
alterTableDropConstraint
| dropColumnSpecification
| dropIndexSpecification
| PERIOD FOR SYSTEM_TIME
)
;
alterTableDropConstraint
: CONSTRAINT? (IF EXISTS)? dropConstraintName (COMMA_ dropConstraintName)*
;
dropConstraintName
: ignoredIdentifier_ dropConstraintWithClause?
;
dropConstraintWithClause
: WITH LP_ dropConstraintOption (COMMA_ dropConstraintOption)* RP_
;
dropConstraintOption
: (MAXDOP EQ_ NUMBER_ | ONLINE EQ_ (ON | OFF) | MOVE TO (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_))
;
dropColumnSpecification
: COLUMN (IF EXISTS)? columnName (COMMA_ columnName)*
;
dropIndexSpecification
: INDEX (IF EXISTS)? indexName (COMMA_ indexName)*
;
alterCheckConstraint
: WITH? (CHECK | NOCHECK) CONSTRAINT (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*))
;
alterTrigger
: (ENABLE| DISABLE) TRIGGER (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*))
;
alterSwitch
: SWITCH (PARTITION expr)? TO tableName (PARTITION expr)? (WITH LP_ lowPriorityLockWait RP_)?
;
alterSet
: SET LP_ (setFileStreamClause | setSystemVersionClause) RP_
;
setFileStreamClause
: FILESTREAM_ON EQ_ (schemaName | ignoredIdentifier_ | STRING_)
;
setSystemVersionClause
: SYSTEM_VERSIONING EQ_ (OFF | alterSetOnClause)
;
alterSetOnClause
: ON
(
LP_ (HISTORY_TABLE EQ_ tableName)?
(COMMA_? DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))?
(COMMA_? HISTORY_RETENTION_PERIOD EQ_ (INFINITE | (NUMBER_ (DAY | DAYS | WEEK | WEEKS | MONTH | MONTHS | YEAR | YEARS))))?
RP_
)?
;
alterTableTableIndex
: indexWithName (indexNonClusterClause | indexClusterClause)
;
indexWithName
: INDEX indexName
;
indexNonClusterClause
: NONCLUSTERED (hashWithBucket | (columnNameWithSortsWithParen alterTableIndexOnClause?))
;
alterTableIndexOnClause
: ON ignoredIdentifier_ | DEFAULT
;
indexClusterClause
: CLUSTERED COLUMNSTORE (WITH COMPRESSION_DELAY EQ_ NUMBER_ MINUTES?)? indexOnClause?
;
alterTableTableOption
: SET LP_ LOCK_ESCALATION EQ_ (AUTO | TABLE | DISABLE) RP_
| MEMORY_OPTIMIZED EQ_ ON
| DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA)
| SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?
;
|
rename to generatedColumnNameClause
|
rename to generatedColumnNameClause
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
|
4716ae1161b66a976dc22b94b98cbae1f272aafa
|
omni-cx2x/src/cx2x/translator/language/Claw.g4
|
omni-cx2x/src/cx2x/translator/language/Claw.g4
|
/*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
/**
* ANTLR 4 Grammar file for the CLAW directive language.
*
* @author clementval
*/
grammar Claw;
@header
{
import java.util.List;
import java.util.ArrayList;
import cx2x.translator.common.Constant;
import cx2x.translator.pragma.*;
}
/*----------------------------------------------------------------------------
* PARSER RULES
*----------------------------------------------------------------------------*/
/*
* Entry point for the analyzis of a CLAW directive.
* Return a CLawLanguage object with all needed information.
*/
analyze returns [ClawLanguage language]
@init{
$language = new ClawLanguage();
}
:
CLAW directive[$language]
;
ids_list[List<String> ids]
:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids]
;
directive[ClawLanguage language]:
LFUSION { $language.setDirective(ClawDirective.LOOP_FUSION); } group_option[$language] EOF
| LINTERCHANGE { $language.setDirective(ClawDirective.LOOP_INTERCHANGE); } indexes_option[$language] EOF
| LEXTRACT range_option EOF
{
$language.setDirective(ClawDirective.LOOP_EXTRACT);
$language.setRange($range_option.r);
}
| REMOVE { $language.setDirective(ClawDirective.REMOVE); } EOF
| END REMOVE { $language.setDirective(ClawDirective.END_REMOVE); } EOF
;
group_option[ClawLanguage language]:
GROUP '(' group_name=IDENTIFIER ')'
{ $language.setGroupOption($group_name.text); }
| /* empty */
;
indexes_option[ClawLanguage language]
@init{
List<String> indexes = new ArrayList();
}
:
'(' ids_list[indexes] ')' { $language.setIndexes(indexes); }
| /* empty */
;
range_option returns [ClawRange r]
@init{
$r = new ClawRange();
}
:
RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ')'
{
$r.setInductionVar($induction.text);
$r.setLowerBound($lower.text);
$r.setUpperBound($upper.text);
$r.setStep(Constant.DEFAULT_STEP_VALUE);
}
| RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ',' step=IDENTIFIER ')'
{
$r.setInductionVar($induction.text);
$r.setLowerBound($lower.text);
$r.setUpperBound($upper.text);
$r.setStep($step.text);
}
;
mapping_var returns [ClawMappingVar mappingVar]:
lhs=IDENTIFIER '/' rhs=IDENTIFIER
{
$mappingVar = new ClawMappingVar($lhs.text, $rhs.text);
}
| i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); }
;
mapping_var_list[List<ClawMappingVar> vars]:
mv=mapping_var { $vars.add($mv.mappingVar); }
| mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars]
;
/*
mapping_option returns [ClawMapping mapping]
@init{
$mapping = new ClawMapping();
}
:
MAP '(' ids_list ':' ids_list ')'
;
map_list:
mapping_option
| mapping_option map_list
;
*/
/*----------------------------------------------------------------------------
* LEXER RULES
*----------------------------------------------------------------------------*/
// Start point
CLAW : 'claw';
// Directives
LFUSION : 'loop-fusion';
LINTERCHANGE : 'loop-interchange';
LEXTRACT : 'loop-extract';
REMOVE : 'remove';
END : 'end';
// Options
GROUP : 'group';
RANGE : 'range';
MAP : 'map';
// Special elements
IDENTIFIER : [a-zA-Z_$0-9] [a-zA-Z_$0-9]* ;
NUMBER : (DIGIT)+ ;
fragment DIGIT : '0'..'9' ;
// Skip whitspaces
WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
|
/*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
/**
* ANTLR 4 Grammar file for the CLAW directive language.
*
* @author clementval
*/
grammar Claw;
@header
{
import java.util.List;
import java.util.ArrayList;
import cx2x.translator.common.Constant;
import cx2x.translator.pragma.*;
}
/*----------------------------------------------------------------------------
* PARSER RULES
*----------------------------------------------------------------------------*/
/*
* Entry point for the analyzis of a CLAW directive.
* Return a CLawLanguage object with all needed information.
*/
analyze returns [ClawLanguage language]
@init{
$language = new ClawLanguage();
}
:
CLAW directive[$language]
;
ids_list[List<String> ids]
:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids]
;
directive[ClawLanguage language]:
// loop-fusion directive
LFUSION { $language.setDirective(ClawDirective.LOOP_FUSION); } group_option[$language] EOF
// loop-interchange directive
| LINTERCHANGE { $language.setDirective(ClawDirective.LOOP_INTERCHANGE); } indexes_option[$language] EOF
// loop-extract directive
| LEXTRACT range_option mapping_option EOF
{
$language.setDirective(ClawDirective.LOOP_EXTRACT);
$language.setRange($range_option.r);
}
// remove directive
| REMOVE { $language.setDirective(ClawDirective.REMOVE); } EOF
| END REMOVE { $language.setDirective(ClawDirective.END_REMOVE); } EOF
;
group_option[ClawLanguage language]:
GROUP '(' group_name=IDENTIFIER ')'
{ $language.setGroupOption($group_name.text); }
| /* empty */
;
indexes_option[ClawLanguage language]
@init{
List<String> indexes = new ArrayList();
}
:
'(' ids_list[indexes] ')' { $language.setIndexes(indexes); }
| /* empty */
;
range_option returns [ClawRange r]
@init{
$r = new ClawRange();
}
:
RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ')'
{
$r.setInductionVar($induction.text);
$r.setLowerBound($lower.text);
$r.setUpperBound($upper.text);
$r.setStep(Constant.DEFAULT_STEP_VALUE);
}
| RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ',' step=IDENTIFIER ')'
{
$r.setInductionVar($induction.text);
$r.setLowerBound($lower.text);
$r.setUpperBound($upper.text);
$r.setStep($step.text);
}
;
mapping_var returns [ClawMappingVar mappingVar]:
lhs=IDENTIFIER '/' rhs=IDENTIFIER
{
$mappingVar = new ClawMappingVar($lhs.text, $rhs.text);
}
| i=IDENTIFIER
{
$mappingVar = new ClawMappingVar($i.text, $i.text);
}
;
mapping_var_list[List<ClawMappingVar> vars]:
mv=mapping_var { $vars.add($mv.mappingVar); }
| mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars]
;
mapping_option returns [ClawMapping mapping]
@init{
$mapping = new ClawMapping();
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] ')'
;
/*----------------------------------------------------------------------------
* LEXER RULES
*----------------------------------------------------------------------------*/
// Start point
CLAW : 'claw';
// Directives
LFUSION : 'loop-fusion';
LINTERCHANGE : 'loop-interchange';
LEXTRACT : 'loop-extract';
REMOVE : 'remove';
END : 'end';
// Options
GROUP : 'group';
RANGE : 'range';
MAP : 'map';
// Special elements
IDENTIFIER : [a-zA-Z_$0-9] [a-zA-Z_$0-9]* ;
NUMBER : (DIGIT)+ ;
fragment DIGIT : '0'..'9' ;
// Skip whitspaces
WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
|
Add comment + set mapping_option
|
Add comment + set mapping_option
|
ANTLR
|
bsd-2-clause
|
clementval/claw-compiler,clementval/claw-compiler
|
bd582b12847fed01cbf57fae061cc87b01755c93
|
src/main/antlr4/PluginDoc.g4
|
src/main/antlr4/PluginDoc.g4
|
grammar PluginDoc;
// TODO: pluginOption default value 不支持element是string(即包含quote)的array
// TODO: 允许包含空格的字符串,目前的解决方案是quoted_string, TEXT与IDENTIFIER容易混淆
// TODO: 丰富的plugin description, option description无法用简单的rule来表达, 需要直接引入markdown
// TODO: udfs
// 内容类型: string, url, quote_string, code, markdown
// 能够写原始的markdown,能够指向链接,能够quote部分文字
// 或者开发者可以在生成的markdown doc上,修改markdown
// pluginUDF 有可能会有多个
// @waterdropPlugin
// @pluginGroup input | filter | output
// @pluginName
// @pluginDesc
// @pluginAuthor
// @pluginHomepage
// @pluginVersion
// @pluginOption type name(required default_value) description
// @pluginOptionsExample
// @pluginUDF
// @pluginUDFName
// @pluginUDFDesc
// @pluginUDFOptions order name desc type required default_value return_value_type
// @pluginUDFExample
waterdropPlugin
: WaterdropPlugin pluginBlock EOF
;
pluginBlock
: (definition)+
;
definition
: pluginGroup
| pluginName
| pluginDesc
| pluginAuthor
| pluginHomepage
| pluginVersion
| pluginOption
;
pluginGroup
: PluginGroup (INPUT | FILTER | OUTPUT)
;
pluginName
: PluginName IDENTIFIER
;
pluginDesc
: PluginDesc (IDENTIFIER | TEXT)
;
pluginAuthor
: PluginAuthor (IDENTIFIER | TEXT)
;
pluginHomepage
: PluginHomepage URL
;
pluginVersion
: PluginVersion VERSION_NUMBER
;
pluginOption
: PluginOption optionType optionName (EQUAL optionDefaultValue)? optionRequired (optionDesc)?
;
optionType
: NUMBER | STRING | ARRAY | BOOLEAN | NULL
;
optionName
: IDENTIFIER
;
optionRequired
: YES | NO
;
optionDefaultValue
: TEXT
;
optionDesc
: TEXT
;
WaterdropPlugin : '@waterdropPlugin';
PluginGroup : '@pluginGroup';
PluginName : '@pluginName';
PluginDesc : '@pluginDesc';
PluginAuthor : '@pluginAuthor';
PluginHomepage : '@pluginHomepage';
PluginVersion : '@pluginVersion';
PluginOption : '@pluginOption';
PluginOptionsExample : '@pluginOptionsExample';
PluginUDF : '@pluginUDF';
PluginUDFName : '@pluginUDFName';
PluginUDFDesc : '@pluginUDFDesc';
PluginUDFOptions : '@pluginUDFOptions';
PluginUDFExample : '@pluginUDFExample';
// pluginGroup
INPUT : 'input';
FILTER : 'filter';
OUTPUT : 'output';
// optionType
NUMBER : 'number';
STRING : 'string';
ARRAY : 'array';
BOOLEAN : 'boolean';
NULL : 'null';
YES : 'yes';
NO : 'no';
EQUAL : '=';
// IDENTIFIER should be placed before TEXT to be matched first
// IDENTIFIER should be placed before VERSION_NUMBER to be matched first
IDENTIFIER : [a-zA-Z_] [a-zA-Z_0-9]* ('.' [a-zA-Z_0-9]+)*;
VERSION_NUMBER : [0-9]+ '.' [0-9]+ '.' + [0-9]+;
URL : ('http' 's'? '://')? URL_VALID_CHARS ('.' URL_VALID_CHARS)+ ('/' | URL_PATH_FRAGMENT)* ('?' URL_PARAMS)?;
fragment URL_PATH_FRAGMENT
: '/' URL_VALID_CHARS
;
fragment URL_PARAMS
: URL_VALID_CHARS '=' URL_VALID_CHARS ('&' URL_VALID_CHARS '=' URL_VALID_CHARS)*
;
fragment URL_VALID_CHARS
: [0-9a-z_-]+
;
TEXT
: '"' ~( '"' | '\n' | '\t' )* '"'
;
WS
: [ \t\n\r]+ -> skip
;
|
grammar PluginDoc;
// TODO: pluginOption default value 不支持element是string(即包含quote)的array
// TODO: 允许包含空格的字符串,目前的解决方案是quoted_string, TEXT与IDENTIFIER容易混淆,
// see: https://stackoverflow.com/questions/6847971/antlr-identifier-with-whitespace
// https://stackoverflow.com/questions/29060496/allow-whitespace-sections-antlr4
// TODO: 丰富的plugin description, option description无法用简单的rule来表达, 需要直接引入markdown
// TODO: udfs
// 内容类型: string, url, quote_string, code, markdown
// 能够写原始的markdown,能够指向链接,能够quote部分文字
// 或者开发者可以在生成的markdown doc上,修改markdown
// pluginUDF 有可能会有多个
// @waterdropPlugin
// @pluginGroup input | filter | output
// @pluginName
// @pluginDesc
// @pluginAuthor
// @pluginHomepage
// @pluginVersion
// @pluginOption type name(required default_value) description
// @pluginOptionsExample
// @pluginUDF
// @pluginUDFName
// @pluginUDFDesc
// @pluginUDFOptions order name desc type required default_value return_value_type
// @pluginUDFExample
waterdropPlugin
: WaterdropPlugin pluginBlock EOF
;
pluginBlock
: (definition)+
;
definition
: pluginGroup
| pluginName
| pluginDesc
| pluginAuthor
| pluginHomepage
| pluginVersion
| pluginOption
;
pluginGroup
: PluginGroup (INPUT | FILTER | OUTPUT)
;
pluginName
: PluginName IDENTIFIER
;
pluginDesc
: PluginDesc (IDENTIFIER | TEXT)
;
pluginAuthor
: PluginAuthor (IDENTIFIER | TEXT)
;
pluginHomepage
: PluginHomepage URL
;
pluginVersion
: PluginVersion VERSION_NUMBER
;
pluginOption
: PluginOption optionType optionName (EQUAL optionDefaultValue)? optionRequired (optionDesc)?
;
optionType
: NUMBER | STRING | ARRAY | BOOLEAN | NULL
;
optionName
: IDENTIFIER
;
optionRequired
: YES | NO
;
optionDefaultValue
: TEXT
;
optionDesc
: TEXT
;
WaterdropPlugin : '@waterdropPlugin';
PluginGroup : '@pluginGroup';
PluginName : '@pluginName';
PluginDesc : '@pluginDesc';
PluginAuthor : '@pluginAuthor';
PluginHomepage : '@pluginHomepage';
PluginVersion : '@pluginVersion';
PluginOption : '@pluginOption';
PluginOptionsExample : '@pluginOptionsExample';
PluginUDF : '@pluginUDF';
PluginUDFName : '@pluginUDFName';
PluginUDFDesc : '@pluginUDFDesc';
PluginUDFOptions : '@pluginUDFOptions';
PluginUDFExample : '@pluginUDFExample';
// pluginGroup
INPUT : 'input';
FILTER : 'filter';
OUTPUT : 'output';
// optionType
NUMBER : 'number';
STRING : 'string';
ARRAY : 'array';
BOOLEAN : 'boolean';
NULL : 'null';
YES : 'yes';
NO : 'no';
EQUAL : '=';
// IDENTIFIER should be placed before TEXT to be matched first
// IDENTIFIER should be placed before VERSION_NUMBER to be matched first
IDENTIFIER : [a-zA-Z_] [a-zA-Z_0-9]* ('.' [a-zA-Z_0-9]+)*;
VERSION_NUMBER : [0-9]+ '.' [0-9]+ '.' + [0-9]+;
URL : ('http' 's'? '://')? URL_VALID_CHARS ('.' URL_VALID_CHARS)+ ('/' | URL_PATH_FRAGMENT)* ('?' URL_PARAMS)?;
fragment URL_PATH_FRAGMENT
: '/' URL_VALID_CHARS
;
fragment URL_PARAMS
: URL_VALID_CHARS '=' URL_VALID_CHARS ('&' URL_VALID_CHARS '=' URL_VALID_CHARS)*
;
fragment URL_VALID_CHARS
: [0-9a-z_-]+
;
TEXT
: '"' ~( '"' | '\n' | '\t' )* '"'
;
WS
: [ \t\n\r]+ -> skip
;
|
update TODOs in PluginDoc.g4
|
update TODOs in PluginDoc.g4
|
ANTLR
|
apache-2.0
|
InterestingLab/waterdrop,InterestingLab/waterdrop
|
9578ca325f966a72432158eb663ce2561a7695a6
|
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 qualifier?
;
observationExpression
: LBRACK comparisonExpression RBRACK # observationExpressionSimple
| LPAREN observationExpressions RPAREN # observationExpressionCompound
;
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
;
qualifier
: startStopQualifier withinQualifier? repeatedQualifier?
| startStopQualifier repeatedQualifier? withinQualifier?
| withinQualifier startStopQualifier? repeatedQualifier?
| withinQualifier repeatedQualifier? startStopQualifier?
| repeatedQualifier startStopQualifier? withinQualifier?
| repeatedQualifier withinQualifier? startStopQualifier?
;
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
: .
;
|
// 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
: .
;
|
Revert "Each Qualifier can only appear once"
|
Revert "Each Qualifier can only appear once"
This reverts commit e25a0f5da3d2a85c338165c00a1a7434862ed8ff.
In that commit the Exists operator was ambiguous if there are two
qualifiers. Also, the approach taken in that commit would not
scale well as more qualifiers are added. There is another way to
implement this in the grammar (semantic predicates) but it would
require different syntax based on the programming language that
will use the grammar, and we'd like to keep the grammar language-
agnostic. Thus this patterning feature will need to be implemented
in the pattern-validator.
|
ANTLR
|
bsd-3-clause
|
oasis-open/cti-stix2-json-schemas
|
5ab6d544c004e5653f1c9f484a5b314fd0506623
|
grammars/cs652/j/parser/J.g4
|
grammars/cs652/j/parser/J.g4
|
grammar J;
@header {
import cs652.j.semantics.*; // You will need these for stuff in "returns" clauses
import org.antlr.symbols.*;
}
file returns [GlobalScope scope] // this allows us to annotate trees with symtab info
: ... EOF
;
expression returns [Type type] // annotate all expression nodes with type info
: ...
;
// ...
|
grammar J;
@header {
import cs652.j.semantics.*; // You will need these for stuff in "returns" clauses
import org.antlr.symtab.*;
}
file returns [GlobalScope scope] // this allows us to annotate trees with symtab info
: ... EOF
;
expression returns [Type type] // annotate all expression nodes with type info
: ...
;
// ...
|
change package
|
change package
|
ANTLR
|
bsd-2-clause
|
USF-CS652-starterkits/parrt-vtable-symtab
|
6f4a547ff7472ace9640e0b72cd290d2e4de3438
|
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE temporaryClause_ TABLE existClause_ tableName createDefinitionClause_ inheritClause
;
createIndex
: CREATE UNIQUE? INDEX CONCURRENTLY? ((IF NOT EXISTS)? indexName)? ON tableName
;
alterTable
: alterTableNameWithAsterisk (alterTableActions | renameColumnSpecification | renameConstraint) | alterTableNameExists renameTableSpecification_
;
alterIndex
: alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace
;
dropTable
: DROP TABLE (IF EXISTS)? tableNames
;
dropIndex
: DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)*
;
truncateTable
: TRUNCATE TABLE? ONLY? tableNameParts
;
temporaryClause_
: ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)?
;
existClause_
: (IF NOT EXISTS)?
;
createDefinitionClause_
: LP_ (createDefinition (COMMA_ createDefinition)*)? RP_
;
createDefinition
: columnDefinition | tableConstraint | LIKE tableName likeOption*
;
columnDefinition
: columnName dataType collateClause? columnConstraint*
;
columnConstraint
: constraintClause? columnConstraintOption constraintOptionalParam
;
constraintClause
: CONSTRAINT ignoredIdentifier_
;
columnConstraintOption
: NOT? NULL
| checkOption
| DEFAULT defaultExpr
| GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)?
| UNIQUE indexParameters
| primaryKey indexParameters
| REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)*
;
checkOption
: CHECK expr (NO INHERIT)?
;
defaultExpr
: CURRENT_TIMESTAMP | expr
;
sequenceOptions
: sequenceOption+
;
sequenceOption
: START WITH? NUMBER_
| INCREMENT BY? NUMBER_
| MAXVALUE NUMBER_
| NO MAXVALUE
| MINVALUE NUMBER_
| NO MINVALUE
| CYCLE
| NO CYCLE
| CACHE NUMBER_
| OWNED BY
;
indexParameters
: (USING INDEX TABLESPACE ignoredIdentifier_)?
| INCLUDE columnNames
| WITH
;
action
: NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT)
;
constraintOptionalParam
: (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))?
;
likeOption
: (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL)
;
tableConstraint
: constraintClause? tableConstraintOption constraintOptionalParam
;
tableConstraintOption
: checkOption
| UNIQUE columnNames indexParameters
| primaryKey columnNames indexParameters
| EXCLUDE (USING ignoredIdentifier_)?
| FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)*
;
inheritClause
: (INHERITS tableNames)?
;
alterIndexName
: ALTER INDEX (IF EXISTS)? indexName
;
renameIndexSpecification
: RENAME TO indexName
;
alterIndexDependsOnExtension
: ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_
;
alterIndexSetTableSpace
: ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)?
;
tableNameParts
: tableNamePart (COMMA_ tableNamePart)*
;
tableNamePart
: tableName ASTERISK_?
;
alterTableNameWithAsterisk
: ALTER TABLE (IF EXISTS)? ONLY? tableName ASTERISK_?
;
alterTableActions
: alterTableAction (COMMA_ alterTableAction)*
;
alterTableAction
: addColumnSpecification
| dropColumnSpecification
| modifyColumnSpecification
| addConstraintSpecification
| ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam
| VALIDATE CONSTRAINT ignoredIdentifier_
| DROP CONSTRAINT (IF EXISTS)? ignoredIdentifier_ (RESTRICT | CASCADE)?
| (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)?
| ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_
| (DISABLE | ENABLE) RULE ignoredIdentifier_
| ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_
| (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY
| CLUSTER ON indexName
| SET WITHOUT CLUSTER
| SET (WITH | WITHOUT) OIDS
| SET TABLESPACE ignoredIdentifier_
| SET (LOGGED | UNLOGGED)
| SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_
| RESET LP_ storageParameter (COMMA_ storageParameter)* RP_
| INHERIT tableName
| NO INHERIT tableName
| OF dataTypeName_
| NOT OF
| OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER)
| REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING)
;
tableConstraintUsingIndex
: (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam
;
addColumnSpecification
: ADD COLUMN? (IF NOT EXISTS)? columnDefinition
;
dropColumnSpecification
: DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)?
;
modifyColumnSpecification
: alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)?
| alterColumn SET DEFAULT expr
| alterColumn DROP DEFAULT
| alterColumn (SET | DROP) NOT NULL
| alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)?
| alterColumn alterColumnSetOption alterColumnSetOption*
| alterColumn DROP IDENTITY (IF EXISTS)?
| alterColumn SET STATISTICS NUMBER_
| alterColumn SET LP_ attributeOptions RP_
| alterColumn RESET LP_ attributeOptions RP_
| alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN)
;
alterColumn
: ALTER COLUMN? columnName
;
alterColumnSetOption
: SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)?
;
attributeOptions
: attributeOption (COMMA_ attributeOption)*
;
attributeOption
: IDENTIFIER_ EQ_ simpleExpr
;
addConstraintSpecification
: ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex)
;
renameColumnSpecification
: RENAME COLUMN? columnName TO columnName
;
renameConstraint
: RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_
;
storageParameterWithValue
: storageParameter EQ_ simpleExpr
;
storageParameter
: IDENTIFIER_
;
alterTableNameExists
: ALTER TABLE (IF EXISTS)? tableName
;
renameTableSpecification_
: RENAME TO newTableName
;
newTableName
: IDENTIFIER_
;
usingIndexType
: USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN)
;
excludeElement
: (columnName | expr) ignoredIdentifier_? (ASC | DESC)? (NULLS (FIRST | LAST))?
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE temporaryClause_ TABLE existClause_ tableName createDefinitionClause_ inheritClause_
;
createIndex
: CREATE UNIQUE? INDEX CONCURRENTLY? ((IF NOT EXISTS)? indexName)? ON tableName
;
alterTable
: alterTableNameWithAsterisk (alterTableActions | renameColumnSpecification | renameConstraint) | alterTableNameExists renameTableSpecification_
;
alterIndex
: alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace
;
dropTable
: DROP TABLE (IF EXISTS)? tableNames
;
dropIndex
: DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)*
;
truncateTable
: TRUNCATE TABLE? ONLY? tableNameParts
;
temporaryClause_
: ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)?
;
existClause_
: (IF NOT EXISTS)?
;
createDefinitionClause_
: LP_ (createDefinition (COMMA_ createDefinition)*)? RP_
;
createDefinition
: columnDefinition | tableConstraint | LIKE tableName likeOption*
;
columnDefinition
: columnName dataType collateClause? columnConstraint*
;
columnConstraint
: constraintClause? columnConstraintOption constraintOptionalParam
;
constraintClause
: CONSTRAINT ignoredIdentifier_
;
columnConstraintOption
: NOT? NULL
| checkOption
| DEFAULT defaultExpr
| GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)?
| UNIQUE indexParameters
| primaryKey indexParameters
| REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)*
;
checkOption
: CHECK expr (NO INHERIT)?
;
defaultExpr
: CURRENT_TIMESTAMP | expr
;
sequenceOptions
: sequenceOption+
;
sequenceOption
: START WITH? NUMBER_
| INCREMENT BY? NUMBER_
| MAXVALUE NUMBER_
| NO MAXVALUE
| MINVALUE NUMBER_
| NO MINVALUE
| CYCLE
| NO CYCLE
| CACHE NUMBER_
| OWNED BY
;
indexParameters
: (USING INDEX TABLESPACE ignoredIdentifier_)?
| INCLUDE columnNames
| WITH
;
action
: NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT)
;
constraintOptionalParam
: (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))?
;
likeOption
: (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL)
;
tableConstraint
: constraintClause? tableConstraintOption constraintOptionalParam
;
tableConstraintOption
: checkOption
| UNIQUE columnNames indexParameters
| primaryKey columnNames indexParameters
| EXCLUDE (USING ignoredIdentifier_)?
| FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)*
;
inheritClause_
: (INHERITS tableNames)?
;
alterIndexName
: ALTER INDEX (IF EXISTS)? indexName
;
renameIndexSpecification
: RENAME TO indexName
;
alterIndexDependsOnExtension
: ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_
;
alterIndexSetTableSpace
: ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)?
;
tableNameParts
: tableNamePart (COMMA_ tableNamePart)*
;
tableNamePart
: tableName ASTERISK_?
;
alterTableNameWithAsterisk
: ALTER TABLE (IF EXISTS)? ONLY? tableName ASTERISK_?
;
alterTableActions
: alterTableAction (COMMA_ alterTableAction)*
;
alterTableAction
: addColumnSpecification
| dropColumnSpecification
| modifyColumnSpecification
| addConstraintSpecification
| ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam
| VALIDATE CONSTRAINT ignoredIdentifier_
| DROP CONSTRAINT (IF EXISTS)? ignoredIdentifier_ (RESTRICT | CASCADE)?
| (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)?
| ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_
| (DISABLE | ENABLE) RULE ignoredIdentifier_
| ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_
| (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY
| CLUSTER ON indexName
| SET WITHOUT CLUSTER
| SET (WITH | WITHOUT) OIDS
| SET TABLESPACE ignoredIdentifier_
| SET (LOGGED | UNLOGGED)
| SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_
| RESET LP_ storageParameter (COMMA_ storageParameter)* RP_
| INHERIT tableName
| NO INHERIT tableName
| OF dataTypeName_
| NOT OF
| OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER)
| REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING)
;
tableConstraintUsingIndex
: (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam
;
addColumnSpecification
: ADD COLUMN? (IF NOT EXISTS)? columnDefinition
;
dropColumnSpecification
: DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)?
;
modifyColumnSpecification
: alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)?
| alterColumn SET DEFAULT expr
| alterColumn DROP DEFAULT
| alterColumn (SET | DROP) NOT NULL
| alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)?
| alterColumn alterColumnSetOption alterColumnSetOption*
| alterColumn DROP IDENTITY (IF EXISTS)?
| alterColumn SET STATISTICS NUMBER_
| alterColumn SET LP_ attributeOptions RP_
| alterColumn RESET LP_ attributeOptions RP_
| alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN)
;
alterColumn
: ALTER COLUMN? columnName
;
alterColumnSetOption
: SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)?
;
attributeOptions
: attributeOption (COMMA_ attributeOption)*
;
attributeOption
: IDENTIFIER_ EQ_ simpleExpr
;
addConstraintSpecification
: ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex)
;
renameColumnSpecification
: RENAME COLUMN? columnName TO columnName
;
renameConstraint
: RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_
;
storageParameterWithValue
: storageParameter EQ_ simpleExpr
;
storageParameter
: IDENTIFIER_
;
alterTableNameExists
: ALTER TABLE (IF EXISTS)? tableName
;
renameTableSpecification_
: RENAME TO newTableName
;
newTableName
: IDENTIFIER_
;
usingIndexType
: USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN)
;
excludeElement
: (columnName | expr) ignoredIdentifier_? (ASC | DESC)? (NULLS (FIRST | LAST))?
;
|
rename to inheritClause_
|
rename to inheritClause_
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
|
b0f13b2bee121bcdf175ef25cca5bfcffd7b1ab1
|
antlr-calculator/src/main/java/net/codenest/antlr/calculator/Calculator.g4
|
antlr-calculator/src/main/java/net/codenest/antlr/calculator/Calculator.g4
|
grammar Calculator ;
/***********************************************************
* Parser rules: define grammars
**********************************************************/
input
: setVar NL input # ToSetVar
| plusOrMinus NL? EOF # Calculate ;
setVar
: ID EQUAL plusOrMinus # SetVariable ;
plusOrMinus
: plusOrMinus PLUS multOrDiv # Plus
| plusOrMinus MINUS multOrDiv # Minus
| multOrDiv # ToMultOrDiv ;
multOrDiv
: multOrDiv MULT pow # Multiplication
| multOrDiv DIV pow # Division
| pow # ToPow ;
pow
: unaryMinus (POW pow)? # Power ;
unaryMinus
: MINUS unaryMinus # ChangeSign
| atom # ToAtom ;
atom
: PI # ConstantPI
| E # ConstantE
| DOUBLE # Double
| INT # Int
| ID # Variable
| LPAR plusOrMinus RPAR # Braces ;
/***********************************************************
* Lexer rules: define tokens
**********************************************************/
INT
: [0-9]+ ;
DOUBLE
: [0-9]+'.'[0-9]+ ;
PI
: 'pi' ;
E
: 'e' ;
POW
: '^' ;
NL
: '\n' ;
WS
: [ \t\r]+ -> skip ;
ID
: [a-zA-Z_][a-zA-Z_0-9]* ;
PLUS
: '+' ;
EQUAL
: '=' ;
MINUS
: '-' ;
MULT
: '*' ;
DIV
: '/' ;
LPAR
: '(' ;
RPAR
: ')' ;
|
grammar Calculator ;
/***********************************************************
* Parser rules: define grammars
**********************************************************/
input
: setVar NL input # ToSetVar
| plusOrMinus NL? EOF # Calculate ;
setVar
: ID EQUAL plusOrMinus # SetVariable ;
plusOrMinus
: plusOrMinus PLUS multOrDiv # Plus
| plusOrMinus MINUS multOrDiv # Minus
| multOrDiv # ToMultOrDiv ;
multOrDiv
: multOrDiv MULT pow # Multiplication
| multOrDiv DIV pow # Division
| pow # ToPow ;
pow
: unaryMinus (POW pow)? # Power ;
unaryMinus
: MINUS unaryMinus # ChangeSign
| atom # ToAtom ;
atom
: PI # ConstantPI
| E # ConstantE
| DOUBLE # Double
| INT # Int
| ID # Variable
| LPAR plusOrMinus RPAR # Braces ;
/***********************************************************
* Lexer rules: define tokens
**********************************************************/
ID : [a-zA-Z_][a-zA-Z_0-9]* ;
INT : [0-9]+ ;
DOUBLE : [0-9]+'.'[0-9]+ ;
PI : 'pi' ;
E : 'e' ;
POW : '^' ;
PLUS : '+' ;
EQUAL : '=' ;
MINUS : '-' ;
MULT : '*' ;
DIV : '/' ;
LPAR : '(' ;
RPAR : ')' ;
NL : '\n' ;
WS : [ \t\r]+ -> skip ;
|
update grammar layout
|
update grammar layout
|
ANTLR
|
apache-2.0
|
sunke/codenest,sunke/codenest
|
287a1fd22191c7b29c36ee3024ab2b97d2bc0cf9
|
json5/JSON5.g4
|
json5/JSON5.g4
|
/** Taken from "The Definitive ANTLR 4 Reference" by Terence Parr */
// Derived from http://json.org
grammar JSON5;
json5
: value
;
obj
: '{' pair (',' pair)* ','? '}'
| '{' '}'
;
pair
: key ':' value
;
key
: STRING
| IDENTIFIER
;
arr
: '[' value (',' value)* ','? ']'
| '[' ']'
;
value
: STRING
| number
| obj
| arr
| 'true'
| 'false'
| 'null'
;
STRING
: '"' DOUBLE_QUOTE_CHAR* '"'
| '\'' SINGLE_QUOTE_CHAR* '\''
;
IDENTIFIER
: IDENTIFIER_START IDENTIFIER_PART*
;
fragment IDENTIFIER_START
: [\p{L}]
| '$'
| '_'
| UNICODE_ESC
;
fragment IDENTIFIER_PART
: IDENTIFIER_START
| [\p{M}]
| [\p{N}]
| [\p{Pc}]
| '\u200C'
| '\u200D'
;
fragment DOUBLE_QUOTE_CHAR
: '\\' ["\\/bfnrt\n]
| ~ ["\\\u0000-\u001F]
| UNICODE_ESC
;
fragment SINGLE_QUOTE_CHAR
: '\\' ['\\/bfnrt\n]
| ~ ['\\\u0000-\u001F]
| UNICODE_ESC
;
fragment UNICODE_ESC
: '\\u' HEX HEX HEX HEX
;
fragment HEX
: [0-9a-fA-F]
;
fragment SAFECODEPOINT
: ~ ["\\\u0000-\u001F]
;
number
: DECNUM
| HEXNUM
| INFINITY
| NAN
;
DECNUM
: [+-]? INT ('.' [0-9]*)? EXP?
| [+-]? '.' [0-9]+ EXP?
;
HEXNUM
: [+-]? '0' [xX] HEX+
;
INFINITY
: [+-]? 'Infinity'
;
NAN
: 'NaN'
;
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 JSON5;
json5
: value
;
obj
: '{' pair (',' pair)* ','? '}'
| '{' '}'
;
pair
: key ':' value
;
key
: STRING
| IDENTIFIER
;
arr
: '[' value (',' value)* ','? ']'
| '[' ']'
;
value
: STRING
| number
| obj
| arr
| 'true'
| 'false'
| 'null'
;
SINGLE_LINE_COMMENT
: '//' ~[\r\n\u2028\u2029]* -> skip
;
MULTI_LINE_COMMENT
: '/*' .*? '*/' -> skip
;
STRING
: '"' DOUBLE_QUOTE_CHAR* '"'
| '\'' SINGLE_QUOTE_CHAR* '\''
;
IDENTIFIER
: IDENTIFIER_START IDENTIFIER_PART*
;
fragment IDENTIFIER_START
: [\p{L}]
| '$'
| '_'
| UNICODE_ESC
;
fragment IDENTIFIER_PART
: IDENTIFIER_START
| [\p{M}]
| [\p{N}]
| [\p{Pc}]
| '\u200C'
| '\u200D'
;
fragment DOUBLE_QUOTE_CHAR
: '\\' ["\\/bfnrt\n]
| ~ ["\\\u0000-\u001F]
| UNICODE_ESC
;
fragment SINGLE_QUOTE_CHAR
: '\\' ['\\/bfnrt\n]
| ~ ['\\\u0000-\u001F]
| UNICODE_ESC
;
fragment UNICODE_ESC
: '\\u' HEX HEX HEX HEX
;
fragment HEX
: [0-9a-fA-F]
;
fragment SAFECODEPOINT
: ~ ["\\\u0000-\u001F]
;
number
: DECNUM
| HEXNUM
| INFINITY
| NAN
;
DECNUM
: [+-]? INT ('.' [0-9]*)? EXP?
| [+-]? '.' [0-9]+ EXP?
;
HEXNUM
: [+-]? '0' [xX] HEX+
;
INFINITY
: [+-]? 'Infinity'
;
NAN
: 'NaN'
;
fragment INT
: '0' | [1-9] [0-9]*
;
// no leading zeros
fragment EXP
: [Ee] [+\-]? INT
;
// \- since - means "range" inside [...]
WS
: [ \t\n\r] + -> skip
;
|
comment support
|
json5: comment support
|
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
|
d48fb7165f8671eba77db390e44f8a1cee9cda5e
|
sharding-core/src/main/antlr4/imports/BaseRule.g4
|
sharding-core/src/main/antlr4/imports/BaseRule.g4
|
//rule in this file does not allow override
grammar BaseRule;
import DataType,Keyword,Symbol;
ID:
(BACK_QUOTA?[a-zA-Z_$][a-zA-Z0-9_$]* BACK_QUOTA? DOT)?
(BACK_QUOTA?[a-zA-Z_$][a-zA-Z0-9_$]* BACK_QUOTA?)
|[a-zA-Z_$0-9]+ DOT ASTERISK
;
schemaName: ID;
tableName: ID;
columnName: ID;
tablespaceName: ID;
collationName: STRING | ID;
indexName: ID;
alias: ID;
cteName:ID;
parserName: ID;
extensionName: ID;
rowName: ID;
opclass: ID;
fileGroup: ID;
groupName: ID;
constraintName: ID;
keyName: ID;
typeName: ID;
xmlSchemaCollection:ID;
columnSetName: ID;
directoryName: ID;
triggerName: ID;
roleName: ID;
partitionName: ID;
rewriteRuleName: ID;
ownerName: ID;
userName: ID;
ifExists
: IF EXISTS;
ifNotExists
: IF NOT EXISTS;
dataTypeLength
: LEFT_PAREN (NUMBER (COMMA NUMBER)?)? RIGHT_PAREN
;
nullNotnull
: NULL
| NOT NULL
;
primaryKey
: PRIMARY? KEY
;
matchNone
: 'Default does not match anything'
;
idList
: LEFT_PAREN ID (COMMA ID)* RIGHT_PAREN
;
rangeClause
: NUMBER (COMMA NUMBER)*
| NUMBER OFFSET NUMBER
;
tableNamesWithParen
: LEFT_PAREN tableNames RIGHT_PAREN
;
tableNames
: tableName (COMMA tableName)*
;
columnNamesWithParen
: LEFT_PAREN columnNames RIGHT_PAREN
;
columnNames
: columnName (COMMA columnName)*
;
columnList
: LEFT_PAREN columnNames RIGHT_PAREN
;
indexNames
: indexName (COMMA indexName)*
;
rowNames
: rowName (COMMA rowName)*
;
roleNames
: roleName (COMMA roleName)*
;
userNames
: userName (COMMA userName)*
;
bitExprs:
bitExpr (COMMA bitExpr)*
;
exprs
: expr (COMMA expr)*
;
exprsWithParen
: LEFT_PAREN exprs RIGHT_PAREN
;
//https://dev.mysql.com/doc/refman/8.0/en/expressions.html
expr
: expr OR expr
| expr OR_SYM expr
| expr XOR expr
| expr AND expr
| expr AND_SYM expr
| LEFT_PAREN expr RIGHT_PAREN
| NOT expr
| NOT_SYM expr
| booleanPrimary
| exprRecursive
;
exprRecursive
: matchNone
;
booleanPrimary
: booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL)
| booleanPrimary SAFE_EQ predicate
| booleanPrimary comparisonOperator predicate
| booleanPrimary comparisonOperator (ALL | ANY) subquery
| predicate
;
comparisonOperator
: EQ_OR_ASSIGN
| GTE
| GT
| LTE
| LT
| NEQ_SYM
| NEQ
;
predicate
: bitExpr NOT? IN subquery
| bitExpr NOT? IN LEFT_PAREN simpleExpr ( COMMA simpleExpr)* RIGHT_PAREN
| bitExpr NOT? BETWEEN simpleExpr AND predicate
| bitExpr SOUNDS LIKE simpleExpr
| bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)*
| bitExpr NOT? REGEXP simpleExpr
| bitExpr
;
bitExpr
: bitExpr BIT_INCLUSIVE_OR bitExpr
| bitExpr BIT_AND bitExpr
| bitExpr SIGNED_LEFT_SHIFT bitExpr
| bitExpr SIGNED_RIGHT_SHIFT bitExpr
| bitExpr PLUS bitExpr
| bitExpr MINUS bitExpr
| bitExpr ASTERISK bitExpr
| bitExpr SLASH bitExpr
| bitExpr MOD bitExpr
| bitExpr MOD_SYM bitExpr
| bitExpr BIT_EXCLUSIVE_OR bitExpr
//| bitExpr '+' interval_expr
//| bitExpr '-' interval_expr
| simpleExpr
;
simpleExpr
: functionCall
| liter
| ID
| simpleExpr collateClause
//| param_marker
//| variable
| simpleExpr AND_SYM simpleExpr
| PLUS simpleExpr
| MINUS simpleExpr
| UNARY_BIT_COMPLEMENT simpleExpr
| NOT_SYM simpleExpr
| BINARY simpleExpr
| LEFT_PAREN expr RIGHT_PAREN
| ROW LEFT_PAREN simpleExpr( COMMA simpleExpr)* RIGHT_PAREN
| subquery
| EXISTS subquery
// | (identifier expr)
//| match_expr
//| case_expr
// | interval_expr
|privateExprOfDb
;
functionCall
: ID LEFT_PAREN( bitExprs?) RIGHT_PAREN
;
privateExprOfDb
: matchNone
;
liter
: QUESTION
| NUMBER
| TRUE
| FALSE
| NULL
| LEFT_BRACE ID STRING RIGHT_BRACE
| HEX_DIGIT
| ID? STRING collateClause?
| (DATE | TIME |TIMESTAMP) STRING
| ID? BIT_NUM collateClause?
;
subquery
: matchNone
;
collateClause
: matchNone
;
orderByClause
: ORDER BY groupByItem (COMMA groupByItem)*
;
groupByItem
: (columnName | NUMBER |expr) (ASC|DESC)?
;
|
//rule in this file does not allow override
grammar BaseRule;
import DataType,Keyword,Symbol;
ID:
(BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_? DOT)?
(BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_?)
| [a-zA-Z_$0-9]+ DOT ASTERISK
;
schemaName: ID;
tableName: ID;
columnName: ID;
tablespaceName: ID;
collationName: STRING | ID;
indexName: ID;
alias: ID;
cteName:ID;
parserName: ID;
extensionName: ID;
rowName: ID;
opclass: ID;
fileGroup: ID;
groupName: ID;
constraintName: ID;
keyName: ID;
typeName: ID;
xmlSchemaCollection:ID;
columnSetName: ID;
directoryName: ID;
triggerName: ID;
roleName: ID;
partitionName: ID;
rewriteRuleName: ID;
ownerName: ID;
userName: ID;
ifExists
: IF EXISTS;
ifNotExists
: IF NOT EXISTS;
dataTypeLength
: LP_ (NUMBER (COMMA NUMBER)?)? RP_
;
nullNotnull
: NULL
| NOT NULL
;
primaryKey
: PRIMARY? KEY
;
matchNone
: 'Default does not match anything'
;
ids
: ID (COMMA ID)*
;
idList
: LP_ ids RP_
;
rangeClause
: NUMBER (COMMA NUMBER)*
| NUMBER OFFSET NUMBER
;
tableNamesWithParen
: LP_ tableNames RP_
;
tableNames
: tableName (COMMA tableName)*
;
columnNamesWithParen
: LP_ columnNames RP_
;
columnNames
: columnName (COMMA columnName)*
;
columnList
: LP_ columnNames RP_
;
indexNames
: indexName (COMMA indexName)*
;
rowNames
: rowName (COMMA rowName)*
;
roleNames
: roleName (COMMA roleName)*
;
userNames
: userName (COMMA userName)*
;
bitExprs:
bitExpr (COMMA bitExpr)*
;
exprs
: expr (COMMA expr)*
;
exprsWithParen
: LP_ exprs RP_
;
//https://dev.mysql.com/doc/refman/8.0/en/expressions.html
expr
: expr OR expr
| expr OR_ expr
| expr XOR expr
| expr AND expr
| expr AND_ expr
| LP_ expr RP_
| NOT expr
| NOT_ expr
| booleanPrimary
| exprRecursive
;
exprRecursive
: matchNone
;
booleanPrimary
: booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL)
| booleanPrimary SAFE_EQ predicate
| booleanPrimary comparisonOperator predicate
| booleanPrimary comparisonOperator (ALL | ANY) subquery
| predicate
;
comparisonOperator
: EQ_
| GTE
| GT
| LTE
| LT
| NEQ_
| NEQ
;
predicate
: bitExpr NOT? IN subquery
| bitExpr NOT? IN LP_ simpleExpr ( COMMA simpleExpr)* RP_
| bitExpr NOT? BETWEEN simpleExpr AND predicate
| bitExpr SOUNDS LIKE simpleExpr
| bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)*
| bitExpr NOT? REGEXP simpleExpr
| bitExpr
;
bitExpr
: bitExpr BIT_INCLUSIVE_OR bitExpr
| bitExpr BIT_AND bitExpr
| bitExpr SIGNED_LEFT_SHIFT bitExpr
| bitExpr SIGNED_RIGHT_SHIFT bitExpr
| bitExpr PLUS bitExpr
| bitExpr MINUS bitExpr
| bitExpr ASTERISK bitExpr
| bitExpr SLASH bitExpr
| bitExpr MOD bitExpr
| bitExpr MOD_ bitExpr
| bitExpr BIT_EXCLUSIVE_OR bitExpr
//| bitExpr '+' interval_expr
//| bitExpr '-' interval_expr
| simpleExpr
;
simpleExpr
: functionCall
| liter
| ID
| simpleExpr collateClause
//| param_marker
//| variable
| simpleExpr AND_ simpleExpr
| PLUS simpleExpr
| MINUS simpleExpr
| UNARY_BIT_COMPLEMENT simpleExpr
| NOT_ simpleExpr
| BINARY simpleExpr
| LP_ expr RP_
| ROW LP_ simpleExpr( COMMA simpleExpr)* RP_
| subquery
| EXISTS subquery
// | (identifier expr)
//| match_expr
//| case_expr
// | interval_expr
|privateExprOfDb
;
functionCall
: ID LP_( bitExprs?) RP_
;
privateExprOfDb
: matchNone
;
liter
: QUESTION
| NUMBER
| TRUE
| FALSE
| NULL
| LBE_ ID STRING RBE_
| HEX_DIGIT
| ID? STRING collateClause?
| (DATE | TIME |TIMESTAMP) STRING
| ID? BIT_NUM collateClause?
;
subquery
: matchNone
;
collateClause
: matchNone
;
orderByClause
: ORDER BY groupByItem (COMMA groupByItem)*
;
groupByItem
: (columnName | NUMBER |expr) (ASC|DESC)?
;
|
fix BaseRule
|
fix BaseRule
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
|
84a145590f265ccadcca912d8c47f3affa9594d8
|
mysql/MySQL.g4
|
mysql/MySQL.g4
|
grammar MySQL;
options {
tokenVocab=MySQLBase;
}
@header {
package jp.co.future.parser.antlr4.mysql;
}
stat:
select_clause+
;
schema_name:
ID
;
select_clause:
SELECT
column_list_clause
(FROM table_references)?
(where_clause)?
;
table_name:
ID
;
table_alias:
ID
;
column_name:
((schema_name DOT)? ID DOT)? ID (column_name_alias)?
|
(table_alias DOT)? ID
|
USER_VAR (column_name_alias)?
;
column_name_alias:
ID
;
index_name:
ID
;
column_list:
LPAREN column_name (COMMA column_name)* RPAREN
;
column_list_clause:
column_name (COMMA column_name)*
;
from_clause:
FROM table_name (COMMA table_name)*
;
select_key:
SELECT
;
where_clause:
WHERE expression
;
expression:
simple_expression (expr_op simple_expression)*
;
element:
USER_VAR | ID | ('|' ID '|') | INT
| column_name
;
right_element:
element
;
left_element:
element
;
target_element:
element
;
relational_op:
EQ | LTH | GTH | NOT_EQ | LET | GET ;
expr_op:
AND | XOR | OR | NOT;
between_op:
BETWEEN
;
is_or_is_not:
IS | IS NOT
;
simple_expression:
left_element relational_op right_element
|
target_element between_op left_element AND right_element
|
target_element is_or_is_not NULL
;
table_references:
table_reference ( (COMMA table_reference) | join_clause )*
;
table_reference:
table_factor1 | table_atom
;
table_factor1:
table_factor2 ( (INNER | CROSS)? JOIN table_atom (join_condition)? )?
;
table_factor2:
table_factor3 ( STRAIGHT_JOIN table_atom (ON expression)? )?
;
table_factor3:
table_factor4 ( (LEFT|RIGHT) (OUTER)? JOIN table_factor4 join_condition )?
;
table_factor4:
table_atom ( NATURAL ( (LEFT|RIGHT) (OUTER)? )? JOIN table_atom )?
;
table_atom:
( table_name (partition_clause)? (table_alias)? (index_hint_list)? )
| ( subquery subquery_alias )
| ( LPAREN table_references RPAREN )
| ( OJ table_reference LEFT OUTER JOIN table_reference ON expression )
;
join_clause:
( (INNER | CROSS)? JOIN table_atom (join_condition)? )
|
( STRAIGHT_JOIN table_atom (ON expression)? )
|
( (LEFT|RIGHT) (OUTER)? JOIN table_factor4 join_condition )
|
( NATURAL ( (LEFT|RIGHT) (OUTER)? )? JOIN table_atom )
;
join_condition:
(ON expression (expr_op expression)*) | (USING column_list)
;
index_hint_list:
index_hint (COMMA index_hint)*
;
index_options:
(INDEX | KEY) (FOR ((JOIN) | (ORDER BY) | (GROUP BY)))?
;
index_hint:
USE index_options LPAREN (index_list)? RPAREN
| IGNORE index_options LPAREN index_list RPAREN
;
index_list:
index_name (COMMA index_name)*
;
partition_clause:
PARTITION LPAREN partition_names RPAREN
;
partition_names:
partition_name (COMMA partition_name)* ;
partition_name:
ID
;
subquery_alias:
ID
;
subquery:
LPAREN select_clause RPAREN
;
|
grammar MySQL;
options {
tokenVocab=MySQLBase;
}
stat:
select_clause+
;
schema_name:
ID
;
select_clause:
SELECT
column_list_clause
(FROM table_references)?
(where_clause)?
;
table_name:
ID
;
table_alias:
ID
;
column_name:
((schema_name DOT)? ID DOT)? ID (column_name_alias)?
|
(table_alias DOT)? ID
|
USER_VAR (column_name_alias)?
;
column_name_alias:
ID
;
index_name:
ID
;
column_list:
LPAREN column_name (COMMA column_name)* RPAREN
;
column_list_clause:
column_name (COMMA column_name)*
;
from_clause:
FROM table_name (COMMA table_name)*
;
select_key:
SELECT
;
where_clause:
WHERE expression
;
expression:
simple_expression (expr_op simple_expression)*
;
element:
USER_VAR | ID | ('|' ID '|') | INT
| column_name
;
right_element:
element
;
left_element:
element
;
target_element:
element
;
relational_op:
EQ | LTH | GTH | NOT_EQ | LET | GET ;
expr_op:
AND | XOR | OR | NOT;
between_op:
BETWEEN
;
is_or_is_not:
IS | IS NOT
;
simple_expression:
left_element relational_op right_element
|
target_element between_op left_element AND right_element
|
target_element is_or_is_not NULL
;
table_references:
table_reference ( (COMMA table_reference) | join_clause )*
;
table_reference:
table_factor1 | table_atom
;
table_factor1:
table_factor2 ( (INNER | CROSS)? JOIN table_atom (join_condition)? )?
;
table_factor2:
table_factor3 ( STRAIGHT_JOIN table_atom (ON expression)? )?
;
table_factor3:
table_factor4 ( (LEFT|RIGHT) (OUTER)? JOIN table_factor4 join_condition )?
;
table_factor4:
table_atom ( NATURAL ( (LEFT|RIGHT) (OUTER)? )? JOIN table_atom )?
;
table_atom:
( table_name (partition_clause)? (table_alias)? (index_hint_list)? )
| ( subquery subquery_alias )
| ( LPAREN table_references RPAREN )
| ( OJ table_reference LEFT OUTER JOIN table_reference ON expression )
;
join_clause:
( (INNER | CROSS)? JOIN table_atom (join_condition)? )
|
( STRAIGHT_JOIN table_atom (ON expression)? )
|
( (LEFT|RIGHT) (OUTER)? JOIN table_factor4 join_condition )
|
( NATURAL ( (LEFT|RIGHT) (OUTER)? )? JOIN table_atom )
;
join_condition:
(ON expression (expr_op expression)*) | (USING column_list)
;
index_hint_list:
index_hint (COMMA index_hint)*
;
index_options:
(INDEX | KEY) (FOR ((JOIN) | (ORDER BY) | (GROUP BY)))?
;
index_hint:
USE index_options LPAREN (index_list)? RPAREN
| IGNORE index_options LPAREN index_list RPAREN
;
index_list:
index_name (COMMA index_name)*
;
partition_clause:
PARTITION LPAREN partition_names RPAREN
;
partition_names:
partition_name (COMMA partition_name)* ;
partition_name:
ID
;
subquery_alias:
ID
;
subquery:
LPAREN select_clause RPAREN
;
|
Update MySQL.g4
|
Update MySQL.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
|
f08fcdd41841b5b7b1f0cc8c81dbb8ed75896443
|
src/main/antlr/mrtim/sasscompiler/grammar/Sass.g4
|
src/main/antlr/mrtim/sasscompiler/grammar/Sass.g4
|
grammar Sass;
NL : '\r'? '\n' -> skip;
WS : (' ' | '\t' | NL) -> skip;
COMMENT: '/*' .*? '*/' -> skip;
LINE_COMMENT : '//' ~[\r\n]* NL? -> skip;
STRING : '"' ('\\"' | ~'"')* '"';
URL : 'url(' ~[)]* ')';
COMMA : ',';
SEMICOLON: ';';
LPAREN: '(';
RPAREN: ')';
LBRACE: '{';
RBRACE: '}';
LSQBRACKET: '[';
RSQBRACKET: ']';
DOLLAR: '$';
EQUALS: '=';
COLON: ':';
SPACE: ' ';
STAR: '*';
BAR: '|';
DOT: '.';
IMPORT_KW : '@import';
MIXIN_KW: '@mixin';
FUNCTION_KW: '@function';
INCLUDE_KW: '@include';
//CSS constants
EVEN_KW: 'even';
ODD_KW: 'odd';
PSEUDO_NOT_KW: ':not';
DIMENSION : 'px';
DIGITS: [0-9]+;
PLUS: '+';
MINUS: '-';
IDENTIFIER: [a-zA-Z][a-zA-Z0-9_-]*;
VARIABLE: '$' IDENTIFIER;
TILDE: '~';
RARROW: '>';
PIPE: '|';
CARET: '^';
HASH: '#';
PERCENT: '%';
ID_NAME: HASH IDENTIFIER;
CLASS_NAME: DOT IDENTIFIER;
import_target: URL | STRING;
import_statement : IMPORT_KW
import_target ( ',' import_target )*
SEMICOLON;
definition : ( MIXIN_KW | FUNCTION_KW)
IDENTIFIER
parameter_def_list
block_body
;
include_statement : INCLUDE_KW IDENTIFIER parameter_list? SEMICOLON;
parameter_def_list: LPAREN ( variable_def (COMMA variable_def)* )? RPAREN;
parameter_list: LPAREN ( parameter (COMMA parameter)* )? RPAREN;
parameter: (IDENTIFIER | variable_def | value);
variable_def: VARIABLE (COLON value_list)?;
//selectors: L309-532
//selector_schema: parser.cpp:309
//selector_group: parser.cpp:336
selector_list: selector_combination (COMMA selector_combination)*;
//selector_combination: parser.cpp:362
selector_combination: (simple_selector+)? ((PLUS | TILDE | RARROW) selector_combination)?;
//simple_selector_sequence: parser.cpp:399
//simple_selector_sequence: simple_selector+;
//simple_selector: parser.cpp:426
simple_selector: (ID_NAME | CLASS_NAME | STRING ) // or number
| type_selector // don't think this is right...
| negated_selector
| pseudo_selector
| attribute_selector
| placeholder_selector
;
placeholder_selector: PERCENT IDENTIFIER;
//negated_selector: parser.cpp:453
negated_selector: PSEUDO_NOT_KW LPAREN selector_list RPAREN;
//pseudo_selector: parser.cpp:464
pseudo_selector: ((pseudo_prefix)? functional
((EVEN_KW | ODD_KW)
| binomial
| IDENTIFIER
| STRING
)?
RPAREN
)
| pseudo_prefix IDENTIFIER;
pseudo_prefix: COLON COLON?;
functional: IDENTIFIER LPAREN;
binomial: integer IDENTIFIER (PLUS DIGITS)?;
//attribute_selector: parser.cpp:517
attribute_selector: LSQBRACKET type_selector ((TILDE | PIPE | STAR | CARET | DOLLAR)? EQUALS (STRING | IDENTIFIER))? RSQBRACKET;
type_selector: namespace_prefix? IDENTIFIER;
namespace_prefix: (IDENTIFIER | STAR) BAR;
variable: variable_def SEMICOLON;
//parser.cpp:534
block_body: LBRACE
(
import_statement // not allowed inside mixins and functions
| assignment
| ruleset
| include_statement
| variable
)*
RBRACE;
variable_assignment: VARIABLE COLON value_list SEMICOLON;
css_identifier: MINUS? IDENTIFIER;
assignment: css_identifier COLON value_list SEMICOLON;
value_list: value ( value )*;
value : (VARIABLE | IDENTIFIER | STRING | integer ( DIMENSION | PERCENT)? );
integer: (PLUS | MINUS)? DIGITS;
ruleset: selector_list block_body;
sass_file : (
import_statement
| definition
| ruleset
| variable
| include_statement
)*;
|
grammar Sass;
NL : '\r'? '\n' -> skip;
WS : (' ' | '\t' | NL) -> skip;
COMMENT: '/*' .*? '*/' -> skip;
LINE_COMMENT : '//' ~[\r\n]* NL? -> skip;
DSTRING : '"' ('\\"' | ~'"')* '"';
SSTRING : '\'' ('\\\'' | ~'\'')* '\'';
URL : 'url(' ~[)]* ')';
COMMA : ',';
SEMICOLON: ';';
LPAREN: '(';
RPAREN: ')';
LBRACE: '{';
RBRACE: '}';
LSQBRACKET: '[';
RSQBRACKET: ']';
DOLLAR: '$';
EQUALS: '=';
COLON: ':';
SPACE: ' ';
STAR: '*';
BAR: '|';
DOT: '.';
IMPORT_KW : '@import';
MIXIN_KW: '@mixin';
FUNCTION_KW: '@function';
INCLUDE_KW: '@include';
//CSS constants
EVEN_KW: 'even';
ODD_KW: 'odd';
PSEUDO_NOT_KW: ':not';
DIMENSION : 'px';
DIGITS: [0-9]+;
PLUS: '+';
MINUS: '-';
IDENTIFIER: [a-zA-Z][a-zA-Z0-9_-]*;
VARIABLE: '$' IDENTIFIER;
TILDE: '~';
RARROW: '>';
PIPE: '|';
CARET: '^';
HASH: '#';
PERCENT: '%';
ID_NAME: HASH IDENTIFIER;
CLASS_NAME: DOT IDENTIFIER;
string: DSTRING | SSTRING;
import_target: URL | string;
import_statement : IMPORT_KW
import_target ( ',' import_target )*
SEMICOLON;
definition : ( MIXIN_KW | FUNCTION_KW)
IDENTIFIER
parameter_def_list
block_body
;
include_statement : INCLUDE_KW IDENTIFIER parameter_list? SEMICOLON;
parameter_def_list: LPAREN ( variable_def (COMMA variable_def)* )? RPAREN;
parameter_list: LPAREN ( parameter (COMMA parameter)* )? RPAREN;
parameter: (IDENTIFIER | variable_def | value);
variable_def: VARIABLE (COLON value_list)?;
//selectors: L309-532
//selector_schema: parser.cpp:309
//selector_group: parser.cpp:336
selector_list: selector_combination (COMMA selector_combination)*;
//selector_combination: parser.cpp:362
selector_combination: (simple_selector+)? ((PLUS | TILDE | RARROW) selector_combination)?;
//simple_selector_sequence: parser.cpp:399
//simple_selector_sequence: simple_selector+;
//simple_selector: parser.cpp:426
simple_selector: (ID_NAME | CLASS_NAME | string ) // or number
| type_selector // don't think this is right...
| negated_selector
| pseudo_selector
| attribute_selector
| placeholder_selector
;
placeholder_selector: PERCENT IDENTIFIER;
//negated_selector: parser.cpp:453
negated_selector: PSEUDO_NOT_KW LPAREN selector_list RPAREN;
//pseudo_selector: parser.cpp:464
pseudo_selector: ((pseudo_prefix)? functional
((EVEN_KW | ODD_KW)
| binomial
| IDENTIFIER
| string
)?
RPAREN
)
| pseudo_prefix IDENTIFIER;
pseudo_prefix: COLON COLON?;
functional: IDENTIFIER LPAREN;
binomial: integer IDENTIFIER (PLUS DIGITS)?;
//attribute_selector: parser.cpp:517
attribute_selector: LSQBRACKET type_selector ((TILDE | PIPE | STAR | CARET | DOLLAR)? EQUALS (string | IDENTIFIER))? RSQBRACKET;
type_selector: namespace_prefix? IDENTIFIER;
namespace_prefix: (IDENTIFIER | STAR) BAR;
variable: variable_def SEMICOLON;
//parser.cpp:534
block_body: LBRACE
(
import_statement // not allowed inside mixins and functions
| assignment
| ruleset
| include_statement
| variable
)*
RBRACE;
variable_assignment: VARIABLE COLON value_list SEMICOLON;
css_identifier: MINUS? IDENTIFIER;
assignment: css_identifier COLON value_list SEMICOLON;
value_list: value ( value )*;
value : (VARIABLE | IDENTIFIER | string | integer ( DIMENSION | PERCENT)? );
integer: (PLUS | MINUS)? DIGITS;
ruleset: selector_list block_body;
sass_file : (
import_statement
| definition
| ruleset
| variable
| include_statement
)*;
|
Allow strings to be single or double quoted
|
Allow strings to be single or double quoted
|
ANTLR
|
mit
|
mr-tim/sass-compiler,mr-tim/sass-compiler
|
7815a5a8ef4360f64bc790e73dd4aa3360ddb261
|
robozonky-strategy-natural/src/main/antlr4/imports/InvestmentSize.g4
|
robozonky-strategy-natural/src/main/antlr4/imports/InvestmentSize.g4
|
grammar InvestmentSize;
import Tokens;
@header {
import com.github.robozonky.strategy.natural.*;
}
investmentSizeExpression returns [Collection<InvestmentSize> result]:
{ Collection<InvestmentSize> result = new LinkedHashSet<>(); }
(i=investmentSizeRatingExpression { result.add($i.result); })+
{ $result = result; }
;
investmentSizeRatingExpression returns [InvestmentSize result] :
'Do úvěrů v ratingu ' r=ratingExpression ' investovat' i=investmentSizeRatingSubExpression {
$result = new InvestmentSize($r.result, $i.result);
}
;
|
grammar InvestmentSize;
import Tokens;
@header {
import com.github.robozonky.strategy.natural.*;
}
investmentSizeExpression returns [Collection<InvestmentSize> result]:
{ Collection<InvestmentSize> result = new LinkedHashSet<>(); }
(i=investmentSizeRatingExpression { result.add($i.result); })*
{ $result = result; }
;
investmentSizeRatingExpression returns [InvestmentSize result] :
'Do úvěrů v ratingu ' r=ratingExpression ' investovat' i=investmentSizeRatingSubExpression {
$result = new InvestmentSize($r.result, $i.result);
}
;
|
Make investment size spec optional
|
Make investment size spec optional
|
ANTLR
|
apache-2.0
|
triceo/zonkybot,triceo/zonkybot,triceo/robozonky,RoboZonky/robozonky,triceo/robozonky,RoboZonky/robozonky
|
455776b1be8fc8163ea274b34f246a1d43ad5ce0
|
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: '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
;
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
: .
;
|
Add an EOF token at the end of the top-level pattern rule, so that parsers are forced to match all tokens in a sequence (instead of only an initial prefix of them).
|
Add an EOF token at the end of the top-level pattern rule,
so that parsers are forced to match all tokens in a sequence
(instead of only an initial prefix of them).
|
ANTLR
|
bsd-3-clause
|
oasis-open/cti-stix2-json-schemas
|
a13af4ad00de08c52eefab4bc1f9b931b9b5da56
|
toml/toml.g4
|
toml/toml.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 toml;
/*
* Parser Rules
*/
document : expression (NL expression)* ;
expression : key_value comment | table comment | comment ;
comment: COMMENT? ;
key_value : key '=' value ;
key : simple_key | dotted_key ;
simple_key : quoted_key | unquoted_key ;
unquoted_key : UNQUOTED_KEY ;
quoted_key : BASIC_STRING | LITERAL_STRING ;
dotted_key : simple_key ('.' simple_key)+ ;
value : string | integer | floating_point | bool_ | date_time | array_ | inline_table ;
string : BASIC_STRING | ML_BASIC_STRING | LITERAL_STRING | ML_LITERAL_STRING ;
integer : DEC_INT | HEX_INT | OCT_INT | BIN_INT ;
floating_point : FLOAT | INF | NAN ;
bool_ : BOOLEAN ;
date_time : OFFSET_DATE_TIME | LOCAL_DATE_TIME | LOCAL_DATE | LOCAL_TIME ;
array_ : '[' array_values? comment_or_nl ']' ;
array_values : (comment_or_nl value ',' array_values comment_or_nl) | comment_or_nl value ','? ;
comment_or_nl : (COMMENT? NL)* ;
table : standard_table | array_table ;
standard_table : '[' key ']' ;
inline_table : '{' inline_table_keyvals '}' ;
inline_table_keyvals : inline_table_keyvals_non_empty? ;
inline_table_keyvals_non_empty : key '=' value (',' inline_table_keyvals_non_empty)? ;
array_table : '[' '[' key ']' ']' ;
/*
* Lexer Rules
*/
WS : [ \t]+ -> skip ;
NL : ('\r'? '\n')+ ;
COMMENT : '#' (~[\n])* ;
fragment DIGIT : [0-9] ;
fragment ALPHA : [A-Za-z] ;
// booleans
BOOLEAN : 'true' | 'false' ;
// strings
fragment ESC : '\\' (["\\/bfnrt] | UNICODE | EX_UNICODE) ;
fragment ML_ESC : '\\' '\r'? '\n' | ESC ;
fragment UNICODE : 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ;
fragment EX_UNICODE : 'U' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ;
BASIC_STRING : '"' (ESC | ~["\\\n])*? '"' ;
ML_BASIC_STRING : '"""' (ML_ESC | ~["\\])*? '"""' ;
LITERAL_STRING : '\'' (~['\n])*? '\'' ;
ML_LITERAL_STRING : '\'\'\'' (.)*? '\'\'\'';
// floating point numbers
fragment EXP : ('e' | 'E') [+-]? ZERO_PREFIXABLE_INT ;
fragment ZERO_PREFIXABLE_INT : DIGIT (DIGIT | '_' DIGIT)* ;
fragment FRAC : '.' ZERO_PREFIXABLE_INT ;
FLOAT : DEC_INT ( EXP | FRAC EXP?) ;
INF : [+-]? 'inf' ;
NAN : [+-]? 'nan' ;
// integers
fragment HEX_DIGIT : [A-Fa-f] | DIGIT ;
fragment DIGIT_1_9 : [1-9] ;
fragment DIGIT_0_7 : [0-7] ;
fragment DIGIT_0_1 : [0-1] ;
DEC_INT : [+-]? (DIGIT | (DIGIT_1_9 (DIGIT | '_' DIGIT)+)) ;
HEX_INT : '0x' HEX_DIGIT (HEX_DIGIT | '_' HEX_DIGIT)* ;
OCT_INT : '0o' DIGIT_0_7 (DIGIT_0_7 | '_' DIGIT_0_7) ;
BIN_INT : '0b' DIGIT_0_1 (DIGIT_0_1 | '_' DIGIT_0_1)* ;
// dates
fragment YEAR : DIGIT DIGIT DIGIT DIGIT ;
fragment MONTH : DIGIT DIGIT ;
fragment DAY : DIGIT DIGIT ;
fragment DELIM : 'T' | 't' ;
fragment HOUR : DIGIT DIGIT ;
fragment MINUTE : DIGIT DIGIT ;
fragment SECOND : DIGIT DIGIT ;
fragment SECFRAC : '.' DIGIT+ ;
fragment NUMOFFSET : ('+' | '-') HOUR ':' MINUTE ;
fragment OFFSET : 'Z' | NUMOFFSET ;
fragment PARTIAL_TIME : HOUR ':' MINUTE ':' SECOND SECFRAC? ;
fragment FULL_DATE : YEAR '-' MONTH '-' DAY ;
fragment FULL_TIME : PARTIAL_TIME OFFSET ;
OFFSET_DATE_TIME : FULL_DATE DELIM FULL_TIME ;
LOCAL_DATE_TIME : FULL_DATE DELIM PARTIAL_TIME ;
LOCAL_DATE : FULL_DATE ;
LOCAL_TIME : PARTIAL_TIME ;
// keys
UNQUOTED_KEY : (ALPHA | DIGIT | '-' | '_')+ ;
|
/*
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 toml;
/*
* Parser Rules
*/
document : expression (NL expression)* ;
expression : key_value comment | table comment | comment ;
comment: COMMENT? ;
key_value : key '=' value ;
key : simple_key | dotted_key ;
simple_key : quoted_key | unquoted_key ;
unquoted_key : UNQUOTED_KEY ;
quoted_key : BASIC_STRING | LITERAL_STRING ;
dotted_key : simple_key ('.' simple_key)+ ;
value : string | integer | floating_point | bool_ | date_time | array_ | inline_table ;
string : BASIC_STRING | ML_BASIC_STRING | LITERAL_STRING | ML_LITERAL_STRING ;
integer : DEC_INT | HEX_INT | OCT_INT | BIN_INT ;
floating_point : FLOAT | INF | NAN ;
bool_ : BOOLEAN ;
date_time : OFFSET_DATE_TIME | LOCAL_DATE_TIME | LOCAL_DATE | LOCAL_TIME ;
array_ : '[' array_values? comment_or_nl ']' ;
array_values : (comment_or_nl value ',' array_values comment_or_nl) | comment_or_nl value ','? ;
comment_or_nl : (COMMENT? NL)* ;
table : standard_table | array_table ;
standard_table : '[' key ']' ;
inline_table : '{' inline_table_keyvals '}' ;
inline_table_keyvals : inline_table_keyvals_non_empty? ;
inline_table_keyvals_non_empty : key '=' value (',' inline_table_keyvals_non_empty)? ;
array_table : '[' '[' key ']' ']' ;
/*
* Lexer Rules
*/
WS : [ \t]+ -> skip ;
NL : ('\r'? '\n')+ ;
COMMENT : '#' (~[\n])* ;
fragment DIGIT : [0-9] ;
fragment ALPHA : [A-Za-z] ;
// booleans
BOOLEAN : 'true' | 'false' ;
// strings
fragment ESC : '\\' (["\\/bfnrt] | UNICODE | EX_UNICODE) ;
fragment ML_ESC : '\\' '\r'? '\n' | ESC ;
fragment UNICODE : 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ;
fragment EX_UNICODE : 'U' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ;
BASIC_STRING : '"' (ESC | ~["\\\n])*? '"' ;
ML_BASIC_STRING : '"""' (ML_ESC | ~["\\])*? '"""' ;
LITERAL_STRING : '\'' (~['\n])*? '\'' ;
ML_LITERAL_STRING : '\'\'\'' (.)*? '\'\'\'';
// floating point numbers
fragment EXP : ('e' | 'E') [+-]? ZERO_PREFIXABLE_INT ;
fragment ZERO_PREFIXABLE_INT : DIGIT (DIGIT | '_' DIGIT)* ;
fragment FRAC : '.' ZERO_PREFIXABLE_INT ;
FLOAT : DEC_INT ( EXP | FRAC EXP?) ;
INF : [+-]? 'inf' ;
NAN : [+-]? 'nan' ;
// integers
fragment HEX_DIGIT : [A-Fa-f] | DIGIT ;
fragment DIGIT_1_9 : [1-9] ;
fragment DIGIT_0_7 : [0-7] ;
fragment DIGIT_0_1 : [0-1] ;
DEC_INT : [+-]? (DIGIT | (DIGIT_1_9 (DIGIT | '_' DIGIT)+)) ;
HEX_INT : '0x' HEX_DIGIT (HEX_DIGIT | '_' HEX_DIGIT)* ;
OCT_INT : '0o' DIGIT_0_7 (DIGIT_0_7 | '_' DIGIT_0_7)* ;
BIN_INT : '0b' DIGIT_0_1 (DIGIT_0_1 | '_' DIGIT_0_1)* ;
// dates
fragment YEAR : DIGIT DIGIT DIGIT DIGIT ;
fragment MONTH : DIGIT DIGIT ;
fragment DAY : DIGIT DIGIT ;
fragment DELIM : 'T' | 't' ;
fragment HOUR : DIGIT DIGIT ;
fragment MINUTE : DIGIT DIGIT ;
fragment SECOND : DIGIT DIGIT ;
fragment SECFRAC : '.' DIGIT+ ;
fragment NUMOFFSET : ('+' | '-') HOUR ':' MINUTE ;
fragment OFFSET : 'Z' | NUMOFFSET ;
fragment PARTIAL_TIME : HOUR ':' MINUTE ':' SECOND SECFRAC? ;
fragment FULL_DATE : YEAR '-' MONTH '-' DAY ;
fragment FULL_TIME : PARTIAL_TIME OFFSET ;
OFFSET_DATE_TIME : FULL_DATE DELIM FULL_TIME ;
LOCAL_DATE_TIME : FULL_DATE DELIM PARTIAL_TIME ;
LOCAL_DATE : FULL_DATE ;
LOCAL_TIME : PARTIAL_TIME ;
// keys
UNQUOTED_KEY : (ALPHA | DIGIT | '-' | '_')+ ;
|
allow more than two digits in octal integers
|
[TOML] allow more than two digits in octal integers
|
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
|
e1b9c9441cd5b3050dcbcd6d1b3bbf90baf775f4
|
java-vtl-parser/src/main/antlr4/imports/Relational.g4
|
java-vtl-parser/src/main/antlr4/imports/Relational.g4
|
grammar Relational;
relationalExpression : unionExpression ;
unionExpression : 'union' '(' datasetExpression (',' datasetExpression )* ')' ;
datasetExpression : 'datasetExpr' NUM+;
NUM : '0'..'9' ;
WS : [ \t\n\t] -> skip ;
|
grammar Relational;
relationalExpression : unionExpression | joinExpression ;
unionExpression : 'union' '(' datasetExpression (',' datasetExpression )* ')' ;
datasetExpression : 'datasetExpr' NUM+;
joinExpression : '[' (INNER | OUTER | CROSS ) datasetExpression (',' datasetExpression )* ']' joinClause (',' joinClause)* ;
joinClause : joinCalc
| joinFilter
| joinKeep
| joinRename ;
// | joinDrop
// | joinUnfold
// | joinFold ;
joinCalc : 'TODO' ;
joinFilter : 'TODO' ;
joinKeep : 'TODO' ;
joinRename : 'TODO' ;
INNER : 'inner' ;
OUTER : 'outer' ;
CROSS : 'cross' ;
NUM : '0'..'9' ;
WS : [ \t\n\t] -> skip ;
|
Add joinExpression to the relationalExpression
|
Add joinExpression to the relationalExpression
|
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
|
de0303db24af747f9c80753dc72a3ac48776f673
|
chabuildly.g4
|
chabuildly.g4
|
grammar chabuildly;
options {
language=JavaScript;
}
program : function* mainFunction;
mainFunction: 'start' '{' vars* block '}' 'end';
function: 'function' ID ':' params '{' vars* block '}' 'end';
vars : ('var' type ID | list) ';';
block : '{' statement* '}';
statement : (conditional|assignment|write|loop| returnStmt |funcCall| drawingStmts | listStmt) ';';
conditional : 'if' expression block ('elif' expression block)? ('else' block)? 'end';
write : 'print' (expression| STRING);
expression : bExpression (boolOp bExpression)? ;
bExpression :exp ( 'less?' | 'greater?' | 'equals?'| 'different?') exp | 'true' | 'false';
params:'params' ':' '(' ( type ID ( ',' type ID)*)? ')';
type: 'number'|'string'|'bool';
loop : 'repeat' 'while' '(' expression ')' block 'end';
exp : (term (('+'|'-') term)*);
term : (factor (('*'|'/') factor)*);
factor : ('+' | '-'| 'not')? (cte|funcCall) | '(' exp ')';
assignment : 'set' ID '=' expression;
returnStmt : 'return' expression;
funcCall : 'call' ID '(' (exp ( ',' exp )*)? ')';
cte : ID | NUMBER;
list : 'list' type 'id' '=' '(' (cte)* ')';
listStmt : 'list' 'id' ('add' cte| 'remove' cte);
boolOp : 'and'| 'or';
drawingStmts : drwShape | back | random;
drwShape : 'draw' 'shape' shape 'color' color 'point-width' cte;
shape : line | polygon | circle | rectangle;
line : 'line' 'from' point 'to' point;
polygon :'polygon' 'with' 'points' 'list' ID;
circle : 'circle' 'at' point 'radius' cte;
rectangle : 'rectangle' 'at' point 'width' cte 'height' cte;
point : 'point' 'x' ':' cte 'y' ':' cte;
color: '(' cte ',' cte ',' cte ')';
back : 'set' 'background' 'color' color;
random : 'random' 'number' 'min:' cte 'max:' cte;
ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*
;
NUMBER : ('0'..'9')+(('.')('0'..'9')+)?
;
STRING
: '"' ( ESC_SEQ | ~('\\'|'"') )* '"'
;
fragment
HEX_DIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ;
fragment
ESC_SEQ
: '\\' ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\')
| UNICODE_ESC
| OCTAL_ESC
;
fragment
OCTAL_ESC
: '\\' ('0'..'3') ('0'..'7') ('0'..'7')
| '\\' ('0'..'7') ('0'..'7')
| '\\' ('0'..'7')
;
fragment
UNICODE_ESC
: '\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
;
|
grammar chabuildly;
options {
language=JavaScript;
}
program : function* mainFunction;
mainFunction: 'start' '{' vars* block '}' 'end';
function: 'function' type ID ':' params '{' vars* block '}' 'end';
vars : ('var' type ID | list) ';';
block : '{' statement* '}';
statement : (conditional|assignment|write|loop| returnStmt |funcCall| drawingStmts | listStmt) ';';
conditional : 'if' expression block ('elif' expression block)? ('else' block)? 'end';
write : 'print' (expression| STRING);
expression : bExpression (boolOp bExpression)? ;
bExpression :exp ( 'less?' | 'greater?' | 'equals?'| 'different?') exp | 'true' | 'false';
params:'params' ':' '(' ( type ID ( ',' type ID)*)? ')';
type: 'number'|'string'|'bool';
loop : 'repeat' 'while' '(' expression ')' block 'end';
exp : (term (('+'|'-') term)*);
term : (factor (('*'|'/') factor)*);
factor : ('+' | '-'| 'not')? (cte|funcCall) | '(' exp ')';
assignment : 'set' ID '=' expression;
returnStmt : 'return' expression;
funcCall : 'call' ID '(' (exp ( ',' exp )*)? ')';
cte : ID | NUMBER;
list : 'list' type 'id' '=' '(' (cte)* ')';
listStmt : 'list' 'id' ('add' cte| 'remove' cte);
boolOp : 'and'| 'or';
drawingStmts : drwShape | back | random;
drwShape : 'draw' 'shape' shape 'color' color 'point-width' cte;
shape : line | polygon | circle | rectangle;
line : 'line' 'from' point 'to' point;
polygon :'polygon' 'with' 'points' 'list' ID;
circle : 'circle' 'at' point 'radius' cte;
rectangle : 'rectangle' 'at' point 'width' cte 'height' cte;
point : 'point' 'x' ':' cte 'y' ':' cte;
color: '(' cte ',' cte ',' cte ')';
back : 'set' 'background' 'color' color;
random : 'random' 'number' 'min:' cte 'max:' cte;
ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*
;
NUMBER : ('0'..'9')+(('.')('0'..'9')+)?
;
STRING
: '"' ( ESC_SEQ | ~('\\'|'"') )* '"'
;
fragment
HEX_DIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ;
fragment
ESC_SEQ
: '\\' ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\')
| UNICODE_ESC
| OCTAL_ESC
;
fragment
OCTAL_ESC
: '\\' ('0'..'3') ('0'..'7') ('0'..'7')
| '\\' ('0'..'7') ('0'..'7')
| '\\' ('0'..'7')
;
fragment
UNICODE_ESC
: '\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
;
|
add type to function
|
add type to function
|
ANTLR
|
mit
|
montselozanod/ChabuScript,montselozanod/ChabuScript,montselozanod/ChabuScript
|
82557f60b22937a4ac4b8f5a8b12d63bcff1af08
|
src/main/antlr4/JmesPath.g4
|
src/main/antlr4/JmesPath.g4
|
grammar JmesPath;
import JSON;
query : expression EOF ;
expression
: expression '.' (identifier | multiSelectList | multiSelectHash | functionExpression | '*') # chainExpression
| expression bracketSpecifier # bracketedExpression
| bracketSpecifier # bracketExpression
| expression '||' expression # orExpression
| identifier # identifierExpression
| expression '&&' expression # andExpression
| expression COMPARATOR expression # comparisonExpression
| '!' 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 | '*' | SLICE_EXPRESSION) ']'
| '[]'
| '[' '?' expression ']'
;
SLICE_EXPRESSION : SIGNED_INT? ':' SIGNED_INT? (':' SIGNED_INT?)? ;
COMPARATOR
: '<'
| '<='
| '=='
| '>='
| '>'
| '!='
;
// TODO: should be NAME and not IDENTIFIER, but that doesn't work
functionExpression : IDENTIFIER (noArgs | oneOrMoreArgs) ;
noArgs : '(' ')' ;
oneOrMoreArgs : '(' functionArg (',' functionArg)* ')' ;
functionArg
: expression
| expressionType
;
currentNode : '@' ;
expressionType : '&' expression ;
RAW_STRING : '\'' (RAW_ESC | ~['\\])* '\'' ;
fragment RAW_ESC : '\\' ['\\] ;
literal : '`' value '`' ;
SIGNED_INT : '-'? DIGIT+ ;
DIGIT : [0-9] ;
LETTER : [a-zA-Z] ;
identifier
: NAME
| STRING
;
NAME : LETTER (LETTER | DIGIT | '_')* ;
|
grammar JmesPath;
import JSON;
query : expression EOF ;
expression
: expression '.' (identifier | multiSelectList | multiSelectHash | functionExpression | '*') # chainExpression
| expression bracketSpecifier # bracketedExpression
| bracketSpecifier # bracketExpression
| expression '||' expression # orExpression
| identifier # identifierExpression
| expression '&&' expression # andExpression
| expression COMPARATOR expression # comparisonExpression
| '!' 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 | '*' | SLICE_EXPRESSION) ']'
| '[]'
| '[' '?' expression ']'
;
SLICE_EXPRESSION : SIGNED_INT? ':' SIGNED_INT? (':' 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 '`' ;
SIGNED_INT : '-'? DIGIT+ ;
DIGIT : [0-9] ;
LETTER : [a-zA-Z] ;
identifier
: NAME
| STRING
;
NAME : LETTER (LETTER | DIGIT | '_')* ;
|
Use NAME directly in function expressions
|
Use NAME directly in function expressions
This was not possible before when identifier was a lexer rule, but now when it's a parser rule there's no ambiguity and NAME works.
|
ANTLR
|
bsd-3-clause
|
burtcorp/jmespath-java
|
1cc5edf0d021213e9d08816731553376c399c06a
|
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
|
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
|
grammar OracleDCLStatement;
import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol;
/**
* each statement has a url,
* each base url : https://docs.oracle.com/database/121/SQLRF/.
* no begin statement in oracle
*/
//statements_9014.htm#SQLRF01603
grant
: GRANT
(
(grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))?
| grantRolesToPrograms
)
;
grantSystemPrivileges
: systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)?
;
systemObjects
: systemObject(COMMA systemObject)*
;
systemObject
: ALL PRIVILEGES
| roleName
| ID *?
;
grantees
: grantee (COMMA grantee)*
;
grantee
: userName
| roleName
| PUBLIC
;
granteeIdentifiedBy
: userNames IDENTIFIED BY STRING (COMMA STRING)*
;
grantObjectPrivilegeClause
: grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause
TO grantees (WITH HIERARCHY OPTION)?(WITH GRANT OPTION)?
;
grantObjectPrivilege
: objectPrivilege columnList?
;
objectPrivilege
: ID *?
| ALL PRIVILEGES?
;
onObjectClause
: ON
(
schemaName? ID
| USER userName ( COMMA userName)*
| (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID
)
;
grantRolesToPrograms
: roleNames TO programUnits
;
programUnits
: programUnit (COMMA programUnit)*
;
programUnit
: (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID
;
revoke
: REVOKE
(
(revokeSystemPrivileges | revokeObjectPrivileges) (CONTAINER EQ_ (CURRENT | ALL))?
| revokeRolesFromPrograms
)
;
revokeSystemPrivileges
: systemObjects FROM
;
revokeObjectPrivileges
: objectPrivilege (COMMA objectPrivilege)* onObjectClause
FROM grantees
(CASCADE CONSTRAINTS | FORCE)?
;
revokeRolesFromPrograms
: (roleNames | ALL) FROM programUnits
;
createUser
: CREATE USER userName IDENTIFIED
(BY STRING | (EXTERNALLY | GLOBALLY) ( AS STRING)?)
(
DEFAULT TABLESPACE ID
| TEMPORARY TABLESPACE ID
| (QUOTA (sizeClause | UNLIMITED) ON ID)
| PROFILE ID
| PASSWORD EXPIRE
| ACCOUNT (LOCK | UNLOCK)
| ENABLE EDITIONS
| CONTAINER EQ_ (CURRENT | ALL)
)*
;
sizeClause
: NUMBER ID?
;
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 ))?
;
|
grammar OracleDCLStatement;
import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol;
/**
* each statement has a url,
* each base url : https://docs.oracle.com/database/121/SQLRF/.
* no begin statement in oracle
*/
//statements_9014.htm#SQLRF01603
grant
: GRANT
(
(grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))?
| grantRolesToPrograms
)
;
grantSystemPrivileges
: systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)?
;
systemObjects
: systemObject(COMMA systemObject)*
;
systemObject
: ALL PRIVILEGES
| roleName
| ID *?
;
grantees
: grantee (COMMA grantee)*
;
grantee
: userName
| roleName
| PUBLIC
;
granteeIdentifiedBy
: userNames IDENTIFIED BY STRING (COMMA STRING)*
;
grantObjectPrivilegeClause
: grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause
TO grantees (WITH HIERARCHY OPTION)?(WITH GRANT OPTION)?
;
grantObjectPrivilege
: objectPrivilege columnList?
;
objectPrivilege
: ID *?
| ALL PRIVILEGES?
;
onObjectClause
: ON
(
schemaName? ID
| USER userName ( COMMA userName)*
| (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID
)
;
grantRolesToPrograms
: roleNames TO programUnits
;
programUnits
: programUnit (COMMA programUnit)*
;
programUnit
: (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID
;
revoke
: REVOKE
(
(revokeSystemPrivileges | revokeObjectPrivileges) (CONTAINER EQ_ (CURRENT | ALL))?
| revokeRolesFromPrograms
)
;
revokeSystemPrivileges
: systemObjects FROM
;
revokeObjectPrivileges
: objectPrivilege (COMMA objectPrivilege)* onObjectClause
FROM grantees
(CASCADE CONSTRAINTS | FORCE)?
;
revokeRolesFromPrograms
: (roleNames | ALL) FROM programUnits
;
createUser
: CREATE USER userName IDENTIFIED
(BY STRING | (EXTERNALLY | GLOBALLY) ( AS STRING)?)
(
DEFAULT TABLESPACE ID
| TEMPORARY TABLESPACE ID
| (QUOTA (sizeClause | UNLIMITED) ON ID)
| PROFILE ID
| PASSWORD EXPIRE
| ACCOUNT (LOCK | UNLOCK)
| ENABLE EDITIONS
| CONTAINER EQ_ (CURRENT | ALL)
)*
;
sizeClause
: NUMBER ID?
;
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
;
|
add dropRole
|
add dropRole
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
|
297c0ffaf2a1ada851414c4f39cc856407a9fd80
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE createTableSpecification_ TABLE notExistClause_ tableName (createDefinitionClause_ | createLikeClause_)
;
createIndex
: CREATE createIndexSpecification_ INDEX indexName indexType_? ON tableName
;
alterTable
: ALTER TABLE tableName alterSpecifications_?
;
dropTable
: DROP TEMPORARY? TABLE (IF EXISTS)? tableName (COMMA_ tableName)*
;
dropIndex
: DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName
;
truncateTable
: TRUNCATE TABLE? tableName
;
createTableSpecification_
: TEMPORARY?
;
notExistClause_
: (IF NOT EXISTS)?
;
createDefinitionClause_
: LP_ createDefinitions_ RP_
;
createDefinitions_
: createDefinition_ (COMMA_ createDefinition_)*
;
createDefinition_
: columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_
;
columnDefinition
: columnName dataType (inlineDataType_* | generatedDataType_*)
;
inlineDataType_
: commonDataTypeOption_
| AUTO_INCREMENT
| DEFAULT (literals | expr)
| COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT)
| STORAGE (DISK | MEMORY | DEFAULT)
;
commonDataTypeOption_
: primaryKey | UNIQUE KEY? | NOT? NULL | collateName_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_
;
checkConstraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)?
;
referenceDefinition_
: REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)*
;
referenceOption_
: RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT
;
generatedDataType_
: commonDataTypeOption_
| (GENERATED ALWAYS)? AS expr
| (VIRTUAL | STORED)
;
indexDefinition_
: (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
indexType_
: USING (BTREE | HASH)
;
keyParts_
: LP_ keyPart_ (COMMA_ keyPart_)* RP_
;
keyPart_
: (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)?
;
indexOption_
: KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE
;
constraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_)
;
primaryKeyOption_
: primaryKey indexType_? columnNames indexOption_*
;
primaryKey
: PRIMARY? KEY
;
uniqueOption_
: UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
foreignKeyOption_
: FOREIGN KEY indexName? columnNames referenceDefinition_
;
createLikeClause_
: LP_? LIKE tableName RP_?
;
createIndexSpecification_
: (UNIQUE | FULLTEXT | SPATIAL)?
;
alterSpecifications_
: alterSpecification_ (COMMA_ alterSpecification_)*
;
alterSpecification_
: tableOptions_
| addColumnSpecification
| addIndexSpecification
| addConstraintSpecification
| ADD checkConstraintDefinition_
| DROP CHECK ignoredIdentifier_
| ALTER CHECK ignoredIdentifier_ NOT? ENFORCED
| ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY)
| ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT)
| ALTER INDEX indexName (VISIBLE | INVISIBLE)
| changeColumnSpecification
| DEFAULT? characterSet_ collateClause_?
| CONVERT TO characterSet_ collateClause_?
| (DISABLE | ENABLE) KEYS
| (DISCARD | IMPORT_) TABLESPACE
| dropColumnSpecification
| dropIndexSpecification
| dropPrimaryKeySpecification
| DROP FOREIGN KEY ignoredIdentifier_
| FORCE
| LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE)
| modifyColumnSpecification
// TODO hongjun investigate ORDER BY col_name [, col_name] ...
| ORDER BY columnName (COMMA_ columnName)*
| renameColumnSpecification
| renameIndexSpecification
| renameTableSpecification_
| (WITHOUT | WITH) VALIDATION
| ADD PARTITION LP_ partitionDefinition_ RP_
| DROP PARTITION ignoredIdentifiers_
| DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| TRUNCATE PARTITION (ignoredIdentifiers_ | ALL)
| COALESCE PARTITION NUMBER_
| REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_
| EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)?
| ANALYZE PARTITION (ignoredIdentifiers_ | ALL)
| CHECK PARTITION (ignoredIdentifiers_ | ALL)
| OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL)
| REBUILD PARTITION (ignoredIdentifiers_ | ALL)
| REPAIR PARTITION (ignoredIdentifiers_ | ALL)
| REMOVE PARTITIONING
| UPGRADE PARTITIONING
;
tableOptions_
: tableOption_ (COMMA_? tableOption_)*
;
tableOption_
: AUTO_INCREMENT EQ_? NUMBER_
| AVG_ROW_LENGTH EQ_? NUMBER_
| DEFAULT? (characterSet_ | collateClause_)
| CHECKSUM EQ_? NUMBER_
| COMMENT EQ_? STRING_
| COMPRESSION EQ_? STRING_
| CONNECTION EQ_? STRING_
| (DATA | INDEX) DIRECTORY EQ_? STRING_
| DELAY_KEY_WRITE EQ_? NUMBER_
| ENCRYPTION EQ_? STRING_
| ENGINE EQ_? ignoredIdentifier_
| INSERT_METHOD EQ_? (NO | FIRST | LAST)
| KEY_BLOCK_SIZE EQ_? NUMBER_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| PACK_KEYS EQ_? (NUMBER_ | DEFAULT)
| PASSWORD EQ_? STRING_
| ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT)
| STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_)
| STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_)
| STATS_SAMPLE_PAGES EQ_? NUMBER_
| TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))?
| UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_
;
addColumnSpecification
: ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_)
;
firstOrAfterColumn
: FIRST | AFTER columnName
;
addIndexSpecification
: ADD indexDefinition_
;
addConstraintSpecification
: ADD constraintDefinition_
;
changeColumnSpecification
: CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn?
;
dropColumnSpecification
: DROP COLUMN? columnName
;
dropIndexSpecification
: DROP (INDEX | KEY) indexName
;
dropPrimaryKeySpecification
: DROP primaryKey
;
modifyColumnSpecification
: MODIFY COLUMN? columnDefinition firstOrAfterColumn?
;
// TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
// TODO hongjun: should support renameIndexSpecification on mysql
renameIndexSpecification
: RENAME (INDEX | KEY) indexName TO indexName
;
// TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table
renameTableSpecification_
: RENAME (TO | AS)? newTableName
;
newTableName
: identifier_
;
partitionDefinitions_
: LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_
;
partitionDefinition_
: PARTITION identifier_
(VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))?
partitionDefinitionOption_*
(LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)?
;
partitionLessThanValue_
: LP_ (expr | partitionValueList_) RP_ | MAXVALUE
;
partitionValueList_
: literals (COMMA_ literals)*
;
partitionDefinitionOption_
: STORAGE? ENGINE EQ_? identifier_
| COMMENT EQ_? STRING_
| DATA DIRECTORY EQ_? STRING_
| INDEX DIRECTORY EQ_? STRING_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| TABLESPACE EQ_? identifier_
;
subpartitionDefinition_
: SUBPARTITION identifier_ partitionDefinitionOption_*
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE createTableSpecification_ TABLE tableNotExistClause_ tableName (createDefinitionClause_ | createLikeClause_)
;
createIndex
: CREATE createIndexSpecification_ INDEX indexName indexType_? ON tableName
;
alterTable
: ALTER TABLE tableName alterSpecifications_?
;
dropTable
: DROP TEMPORARY? TABLE (IF EXISTS)? tableName (COMMA_ tableName)*
;
dropIndex
: DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName
;
truncateTable
: TRUNCATE TABLE? tableName
;
createTableSpecification_
: TEMPORARY?
;
tableNotExistClause_
: (IF NOT EXISTS)?
;
createDefinitionClause_
: LP_ createDefinitions_ RP_
;
createDefinitions_
: createDefinition_ (COMMA_ createDefinition_)*
;
createDefinition_
: columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_
;
columnDefinition
: columnName dataType (inlineDataType_* | generatedDataType_*)
;
inlineDataType_
: commonDataTypeOption_
| AUTO_INCREMENT
| DEFAULT (literals | expr)
| COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT)
| STORAGE (DISK | MEMORY | DEFAULT)
;
commonDataTypeOption_
: primaryKey | UNIQUE KEY? | NOT? NULL | collateName_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_
;
checkConstraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)?
;
referenceDefinition_
: REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)*
;
referenceOption_
: RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT
;
generatedDataType_
: commonDataTypeOption_
| (GENERATED ALWAYS)? AS expr
| (VIRTUAL | STORED)
;
indexDefinition_
: (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
indexType_
: USING (BTREE | HASH)
;
keyParts_
: LP_ keyPart_ (COMMA_ keyPart_)* RP_
;
keyPart_
: (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)?
;
indexOption_
: KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE
;
constraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_)
;
primaryKeyOption_
: primaryKey indexType_? columnNames indexOption_*
;
primaryKey
: PRIMARY? KEY
;
uniqueOption_
: UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
foreignKeyOption_
: FOREIGN KEY indexName? columnNames referenceDefinition_
;
createLikeClause_
: LP_? LIKE tableName RP_?
;
createIndexSpecification_
: (UNIQUE | FULLTEXT | SPATIAL)?
;
alterSpecifications_
: alterSpecification_ (COMMA_ alterSpecification_)*
;
alterSpecification_
: tableOptions_
| addColumnSpecification
| addIndexSpecification
| addConstraintSpecification
| ADD checkConstraintDefinition_
| DROP CHECK ignoredIdentifier_
| ALTER CHECK ignoredIdentifier_ NOT? ENFORCED
| ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY)
| ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT)
| ALTER INDEX indexName (VISIBLE | INVISIBLE)
| changeColumnSpecification
| DEFAULT? characterSet_ collateClause_?
| CONVERT TO characterSet_ collateClause_?
| (DISABLE | ENABLE) KEYS
| (DISCARD | IMPORT_) TABLESPACE
| dropColumnSpecification
| dropIndexSpecification
| dropPrimaryKeySpecification
| DROP FOREIGN KEY ignoredIdentifier_
| FORCE
| LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE)
| modifyColumnSpecification
// TODO hongjun investigate ORDER BY col_name [, col_name] ...
| ORDER BY columnName (COMMA_ columnName)*
| renameColumnSpecification
| renameIndexSpecification
| renameTableSpecification_
| (WITHOUT | WITH) VALIDATION
| ADD PARTITION LP_ partitionDefinition_ RP_
| DROP PARTITION ignoredIdentifiers_
| DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| TRUNCATE PARTITION (ignoredIdentifiers_ | ALL)
| COALESCE PARTITION NUMBER_
| REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_
| EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)?
| ANALYZE PARTITION (ignoredIdentifiers_ | ALL)
| CHECK PARTITION (ignoredIdentifiers_ | ALL)
| OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL)
| REBUILD PARTITION (ignoredIdentifiers_ | ALL)
| REPAIR PARTITION (ignoredIdentifiers_ | ALL)
| REMOVE PARTITIONING
| UPGRADE PARTITIONING
;
tableOptions_
: tableOption_ (COMMA_? tableOption_)*
;
tableOption_
: AUTO_INCREMENT EQ_? NUMBER_
| AVG_ROW_LENGTH EQ_? NUMBER_
| DEFAULT? (characterSet_ | collateClause_)
| CHECKSUM EQ_? NUMBER_
| COMMENT EQ_? STRING_
| COMPRESSION EQ_? STRING_
| CONNECTION EQ_? STRING_
| (DATA | INDEX) DIRECTORY EQ_? STRING_
| DELAY_KEY_WRITE EQ_? NUMBER_
| ENCRYPTION EQ_? STRING_
| ENGINE EQ_? ignoredIdentifier_
| INSERT_METHOD EQ_? (NO | FIRST | LAST)
| KEY_BLOCK_SIZE EQ_? NUMBER_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| PACK_KEYS EQ_? (NUMBER_ | DEFAULT)
| PASSWORD EQ_? STRING_
| ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT)
| STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_)
| STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_)
| STATS_SAMPLE_PAGES EQ_? NUMBER_
| TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))?
| UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_
;
addColumnSpecification
: ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_)
;
firstOrAfterColumn
: FIRST | AFTER columnName
;
addIndexSpecification
: ADD indexDefinition_
;
addConstraintSpecification
: ADD constraintDefinition_
;
changeColumnSpecification
: CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn?
;
dropColumnSpecification
: DROP COLUMN? columnName
;
dropIndexSpecification
: DROP (INDEX | KEY) indexName
;
dropPrimaryKeySpecification
: DROP primaryKey
;
modifyColumnSpecification
: MODIFY COLUMN? columnDefinition firstOrAfterColumn?
;
// TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
// TODO hongjun: should support renameIndexSpecification on mysql
renameIndexSpecification
: RENAME (INDEX | KEY) indexName TO indexName
;
// TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table
renameTableSpecification_
: RENAME (TO | AS)? newTableName
;
newTableName
: identifier_
;
partitionDefinitions_
: LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_
;
partitionDefinition_
: PARTITION identifier_
(VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))?
partitionDefinitionOption_*
(LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)?
;
partitionLessThanValue_
: LP_ (expr | partitionValueList_) RP_ | MAXVALUE
;
partitionValueList_
: literals (COMMA_ literals)*
;
partitionDefinitionOption_
: STORAGE? ENGINE EQ_? identifier_
| COMMENT EQ_? STRING_
| DATA DIRECTORY EQ_? STRING_
| INDEX DIRECTORY EQ_? STRING_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| TABLESPACE EQ_? identifier_
;
subpartitionDefinition_
: SUBPARTITION identifier_ partitionDefinitionOption_*
;
|
rename to tableNotExistClause_
|
rename to tableNotExistClause_
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
|
423e75c75ee9b981f9746c0949ee6b3e5c9c30c6
|
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,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
|
664bf582118659d4993643cc76d377aebd04cc9c
|
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';
|
Remove unnecessary parenthesis
|
Remove unnecessary parenthesis
|
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
|
3dc5bf34a677d6ef81034603257a13ed63758d06
|
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
|
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
|
grammar SQLServerDCLStatement;
import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol;
grant
: grantGeneral | grantDW
;
grantGeneral
: GRANT (ALL PRIVILEGES? | permissionOnColumns ( COMMA permissionOnColumns)*)
(ON (ID COLON COLON)? ID)? TO ids (WITH GRANT OPTION)? (AS ID)?
;
permissionOnColumns
: permission columnList?
;
permission
: ID *?
;
grantDW
: GRANT permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
TO ids (WITH GRANT OPTION)?
;
classType
: LOGIN | DATABASE | OBJECT | ROLE | SCHEMA | USER
;
revoke
: revokeGeneral | revokeDW
;
revokeGeneral
: REVOKE (GRANT OPTION FOR)? ((ALL PRIVILEGES?)? | permissionOnColumns)
(ON (ID COLON COLON)? ID)? (TO | FROM) ids (CASCADE)? (AS ID)?
;
revokeDW
: REVOKE permissionWithClass (FROM | TO)? ids CASCADE?
;
permissionWithClass
: permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
;
deny
: DENY permissionWithClass TO ids CASCADE? (AS ID)?
;
createUser2
: CREATE USER userName
(
windowsPrincipal (WITH optionsList (COMMA optionsList)*)?
| userName WITH PASSWORD EQ_ STRING (COMMA optionsList)*
| ID FROM EXTERNAL PROVIDER
)
;
createUser3
: CREATE USER userName
(
ID (( FOR | FROM ) LOGIN ID)?
| userName ( FOR | FROM ) LOGIN ID
)
;
createUser4
: CREATE USER userName
(
WITHOUT LOGIN (WITH limitedOptionsList (COMMA limitedOptionsList)*)?
| (FOR | FROM ) CERTIFICATE ID
| (FOR | FROM) ASYMMETRIC KEY ID
)
;
optionsList
: DEFAU_SCHEMA EQ_ schemaName
| DEFAU_LANGUAGE EQ_ ( NONE | ID)
| SID EQ_ ID
| ALLOW_ENCRYPTED_VALUE_MODIFICATIONS EQ_ (ON | OFF)
;
limitedOptionsList
: DEFAU_SCHEMA EQ_ schemaName | ALLOW_ENCRYPTED_VALUE_MODIFICATIONS EQ_ (ON | OFF)?
;
|
grammar SQLServerDCLStatement;
import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol;
grant
: grantGeneral | grantDW
;
grantGeneral
: GRANT (ALL PRIVILEGES? | permissionOnColumns ( COMMA permissionOnColumns)*)
(ON (ID COLON COLON)? ID)? TO ids (WITH GRANT OPTION)? (AS ID)?
;
permissionOnColumns
: permission columnList?
;
permission
: ID *?
;
grantDW
: GRANT permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
TO ids (WITH GRANT OPTION)?
;
classType
: LOGIN | DATABASE | OBJECT | ROLE | SCHEMA | USER
;
revoke
: revokeGeneral | revokeDW
;
revokeGeneral
: REVOKE (GRANT OPTION FOR)? ((ALL PRIVILEGES?)? | permissionOnColumns)
(ON (ID COLON COLON)? ID)? (TO | FROM) ids (CASCADE)? (AS ID)?
;
revokeDW
: REVOKE permissionWithClass (FROM | TO)? ids CASCADE?
;
permissionWithClass
: permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
;
deny
: DENY permissionWithClass TO ids CASCADE? (AS ID)?
;
createUser1
: CREATE USER userName
((FOR | FROM) LOGIN ID)? (WITH limitedOptionsList ( COMMA limitedOptionsList)*)?
;
createUser2
: CREATE USER userName
(
ID (WITH optionsList (COMMA optionsList)*)?
| userName WITH PASSWORD EQ_ STRING (COMMA optionsList)*
| ID FROM EXTERNAL PROVIDER
)
;
createUser3
: CREATE USER userName
(
ID (( FOR | FROM ) LOGIN ID)?
| userName ( FOR | FROM ) LOGIN ID
)
;
createUser4
: CREATE USER userName
(
WITHOUT LOGIN (WITH limitedOptionsList (COMMA limitedOptionsList)*)?
| (FOR | FROM ) CERTIFICATE ID
| (FOR | FROM) ASYMMETRIC KEY ID
)
;
optionsList
: DEFAU_SCHEMA EQ_ schemaName
| DEFAU_LANGUAGE EQ_ ( NONE | ID)
| SID EQ_ ID
| ALLOW_ENCRYPTED_VALUE_MODIFICATIONS EQ_ (ON | OFF)
;
limitedOptionsList
: DEFAU_SCHEMA EQ_ schemaName | ALLOW_ENCRYPTED_VALUE_MODIFICATIONS EQ_ (ON | OFF)?
;
|
add createUser1
|
add createUser1
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
|
0617223b2483293621a91785e231fcbb332eb8fd
|
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
: k=PropertyKeyword name=propertyName value=propertyValue
;
propertyName
: Name
;
propertyValue
: writeValue
;
streamNode
: acceptNode
| acceptableNode
| connectNode
;
acceptNode
: k=AcceptKeyword
(AwaitKeyword await=Name)?
acceptURI=location (AsKeyword as=Name)?
(NotifyKeyword notify=Name)?
acceptOption*
serverStreamableNode*
;
acceptOption
: OptionKeyword name=Name value=writeValue
;
acceptableNode
: k=AcceptedKeyword ( text=Name )? streamableNode+
;
connectNode
: k=ConnectKeyword
(AwaitKeyword await=Name ConnectKeyword?)?
connectURI=location
connectOption*
streamableNode+
;
connectOption
: OptionKeyword name=Name value=writeValue
;
serverStreamableNode
: barrierNode
| serverEventNode
| serverCommandNode
| optionNode
;
optionNode
: readOptionMaskNode
| readOptionOffsetNode
| writeOptionMaskNode
| writeOptionOffsetNode
| writeOptionHttpChunkExtensionNode
| readOptionHttpChunkExtensionNode
;
readOptionMaskNode
: k=ReadKeyword OptionKeyword name=MaskKeyword value=writeValue
;
readOptionOffsetNode
: k=ReadKeyword OptionKeyword name=OffsetKeyword value=writeValue
;
readOptionHttpChunkExtensionNode
: k=ReadKeyword OptionKeyword name=ChunkExtensionKeyWord value=writeValue
;
writeOptionMaskNode
: k=WriteKeyword OptionKeyword name=MaskKeyword value=writeValue
;
writeOptionOffsetNode
: k=WriteKeyword OptionKeyword name=OffsetKeyword value=writeValue
;
writeOptionHttpChunkExtensionNode
: k=WriteKeyword OptionKeyword name=ChunkExtensionKeyWord value=writeValue
;
serverCommandNode
: unbindNode
| closeNode
;
serverEventNode
: openedNode
| boundNode
| childOpenedNode
| childClosedNode
| unboundNode
| closedNode
;
streamableNode
: barrierNode
| eventNode
| commandNode
| optionNode
;
commandNode
: writeNode
| writeFlushNode
| writeCloseNode
| closeNode
| writeHttpContentLengthNode
| writeHttpHeaderNode
| writeHttpChunkTrailerNode
| writeHttpHostNode
| writeHttpMethodNode
| writeHttpParameterNode
| writeHttpRequestNode
| writeHttpStatusNode
| writeHttpVersionNode
| abortNode
;
eventNode
: openedNode
| boundNode
| readNode
| readClosedNode
| disconnectedNode
| unboundNode
| closedNode
| connectedNode
| readHttpHeaderNode
| readHttpChunkTrailerNode
| readHttpMethodNode
| readHttpParameterNode
| readHttpVersionNode
| readHttpStatusNode
| abortedNode
;
barrierNode
: readAwaitNode
| readNotifyNode
| writeAwaitNode
| writeNotifyNode
;
closeNode
: k=CloseKeyword
;
writeFlushNode:
k=WriteKeyword FlushKeyword;
writeCloseNode:
k=WriteKeyword CloseKeyword;
disconnectNode
: k=DisconnectKeyword
;
unbindNode
: k=UnbindKeyword
;
writeNode
: k=WriteKeyword writeValue+
;
childOpenedNode
: k=ChildKeyword OpenedKeyword
;
childClosedNode
: k=ChildKeyword ClosedKeyword
;
boundNode
: k=BoundKeyword
;
closedNode
: k=ClosedKeyword
;
connectedNode
: k=ConnectedKeyword
;
disconnectedNode
: k=DisconnectedKeyword
;
openedNode
: k=OpenedKeyword
;
abortNode
: k=AbortKeyword
;
abortedNode
: k=AbortedKeyword
;
readClosedNode:
k=ReadKeyword ClosedKeyword;
readNode
: k=ReadKeyword matcher+
;
unboundNode
: k=UnboundKeyword
;
readAwaitNode
: k=ReadKeyword AwaitKeyword barrier=Name
;
readNotifyNode
: k=ReadKeyword NotifyKeyword barrier=Name
;
writeAwaitNode
: k=WriteKeyword AwaitKeyword barrier=Name
;
writeNotifyNode
: k=WriteKeyword NotifyKeyword barrier=Name
;
readHttpHeaderNode
: k=ReadKeyword HttpHeaderKeyword name=literalText (HttpMissingKeyword | matcher+)
;
readHttpChunkTrailerNode
: k=ReadKeyword HttpChunkTrailerKeyword name=literalText (HttpMissingKeyword | matcher+)
;
writeHttpHeaderNode
: k=WriteKeyword HttpHeaderKeyword name=literalText writeValue+
;
writeHttpChunkTrailerNode
: k=WriteKeyword HttpChunkTrailerKeyword name=literalText writeValue+
;
writeHttpContentLengthNode
: k=WriteKeyword HttpHeaderKeyword HttpContentLengthKeyword
;
writeHttpHostNode
: k=WriteKeyword HttpHeaderKeyword HttpHostKeyword
;
readHttpMethodNode
: k=ReadKeyword HttpMethodKeyword method=matcher
;
writeHttpMethodNode
: k=WriteKeyword HttpMethodKeyword method=writeValue
;
readHttpParameterNode
: k=ReadKeyword HttpParameterKeyword name=literalText matcher+
;
writeHttpParameterNode
: k=WriteKeyword HttpParameterKeyword name=literalText writeValue+
;
readHttpVersionNode
: k=ReadKeyword HttpVersionKeyword version=matcher
;
writeHttpVersionNode
: k=WriteKeyword HttpVersionKeyword version=writeValue
;
readHttpStatusNode
: k=ReadKeyword HttpStatusKeyword code=matcher reason=matcher
;
writeHttpRequestNode
: k=WriteKeyword HttpRequestKeyword form=writeValue
;
writeHttpStatusNode
: k=WriteKeyword HttpStatusKeyword code=writeValue reason=writeValue
;
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
: literalURI
| literalText
| literalBytes
| literalByte
| literalShort
| literalInteger
| literalLong
| expressionValue
;
literalURI
: literal=URILiteral
;
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
: literalURI
| expressionValue
;
SignedDecimalLiteral
: Plus DecimalLiteral
| Minus DecimalLiteral
// | DecimalLiteral
;
MaskKeyword: 'mask';
OffsetKeyword : 'offset';
OptionKeyword: 'option';
ChunkExtensionKeyWord: 'chunkExtension';
ShortKeyword
: 'short'
;
IntKeyword
: 'int'
;
ByteKeyword
: 'byte'
;
LongKeyword
: 'long'
;
AcceptKeyword
: 'accept'
;
AcceptedKeyword
: 'accepted'
;
AsKeyword
: 'as'
;
AwaitKeyword
: 'await'
;
BindKeyword
: 'bind'
;
BoundKeyword
: 'bound'
;
ChildKeyword
: 'child'
;
CloseKeyword
: 'close'
;
ClosedKeyword
: 'closed'
;
ConnectKeyword
: 'connect'
;
ConnectedKeyword
: 'connected'
;
DisconnectKeyword
: 'disconnect'
;
DisconnectedKeyword
: 'disconnected'
;
AbortKeyword
: 'abort'
;
AbortedKeyword
: 'aborted'
;
FlushKeyword
: 'flush'
;
NotifyKeyword
: 'notify'
;
OpenedKeyword
: 'opened'
;
PropertyKeyword
: 'property'
;
ReadKeyword
: 'read'
;
UnbindKeyword
: 'unbind'
;
UnboundKeyword
: 'unbound'
;
WriteKeyword
: 'write'
;
HttpContentLengthKeyword
: 'content-length'
;
HttpHeaderKeyword
: 'header'
;
HttpChunkTrailerKeyword
: 'trailer'
;
HttpHostKeyword
: 'host'
;
HttpMethodKeyword
: 'method'
;
HttpMissingKeyword
: 'missing'
;
HttpParameterKeyword
: 'parameter'
;
HttpRequestKeyword
: 'request'
;
HttpResponseKeyword
: 'response'
;
HttpStatusKeyword
: 'status'
;
HttpVersionKeyword
: 'version'
;
// 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
;
fragment
Identifier
: Letter (Digit | 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
;
streamNode
: acceptNode
| acceptableNode
| connectNode
;
acceptNode
: AcceptKeyword
(AwaitKeyword await=Name)?
acceptURI=location (AsKeyword as=Name)?
(NotifyKeyword notify=Name)?
acceptOption*
serverStreamableNode*
;
acceptOption
: OptionKeyword name=Name value=writeValue
;
acceptableNode
: AcceptedKeyword ( text=Name )? streamableNode+
;
connectNode
: ConnectKeyword
(AwaitKeyword await=Name ConnectKeyword?)?
connectURI=location
connectOption*
streamableNode+
;
connectOption
: OptionKeyword name=Name value=writeValue
;
serverStreamableNode
: barrierNode
| serverEventNode
| serverCommandNode
| optionNode
;
optionNode
: readOptionMaskNode
| readOptionOffsetNode
| writeOptionMaskNode
| writeOptionOffsetNode
| writeOptionHttpChunkExtensionNode
| readOptionHttpChunkExtensionNode
;
readOptionMaskNode
: ReadKeyword OptionKeyword name=MaskKeyword value=writeValue
;
readOptionOffsetNode
: ReadKeyword OptionKeyword name=OffsetKeyword value=writeValue
;
readOptionHttpChunkExtensionNode
: ReadKeyword OptionKeyword name=ChunkExtensionKeyWord value=writeValue
;
writeOptionMaskNode
: WriteKeyword OptionKeyword name=MaskKeyword value=writeValue
;
writeOptionOffsetNode
: WriteKeyword OptionKeyword name=OffsetKeyword value=writeValue
;
writeOptionHttpChunkExtensionNode
: WriteKeyword OptionKeyword name=ChunkExtensionKeyWord value=writeValue
;
serverCommandNode
: unbindNode
| closeNode
;
serverEventNode
: openedNode
| boundNode
| childOpenedNode
| childClosedNode
| unboundNode
| closedNode
;
streamableNode
: barrierNode
| eventNode
| commandNode
| optionNode
;
commandNode
: writeNode
| writeFlushNode
| writeCloseNode
| closeNode
| writeHttpContentLengthNode
| writeHttpHeaderNode
| writeHttpChunkTrailerNode
| writeHttpHostNode
| writeHttpMethodNode
| writeHttpParameterNode
| writeHttpRequestNode
| writeHttpStatusNode
| writeHttpVersionNode
| abortNode
;
eventNode
: openedNode
| boundNode
| readNode
| readClosedNode
| disconnectedNode
| unboundNode
| closedNode
| connectedNode
| readHttpHeaderNode
| readHttpChunkTrailerNode
| readHttpMethodNode
| readHttpParameterNode
| readHttpVersionNode
| readHttpStatusNode
| abortedNode
;
barrierNode
: readAwaitNode
| readNotifyNode
| writeAwaitNode
| writeNotifyNode
;
closeNode
: CloseKeyword
;
writeFlushNode:
WriteKeyword FlushKeyword;
writeCloseNode:
WriteKeyword CloseKeyword;
disconnectNode
: DisconnectKeyword
;
unbindNode
: UnbindKeyword
;
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;
readNode
: ReadKeyword matcher+
;
unboundNode
: UnboundKeyword
;
readAwaitNode
: ReadKeyword AwaitKeyword barrier=Name
;
readNotifyNode
: ReadKeyword NotifyKeyword barrier=Name
;
writeAwaitNode
: WriteKeyword AwaitKeyword barrier=Name
;
writeNotifyNode
: WriteKeyword NotifyKeyword barrier=Name
;
readHttpHeaderNode
: ReadKeyword HttpHeaderKeyword name=literalText (HttpMissingKeyword | matcher+)
;
readHttpChunkTrailerNode
: ReadKeyword HttpChunkTrailerKeyword name=literalText (HttpMissingKeyword | matcher+)
;
writeHttpHeaderNode
: WriteKeyword HttpHeaderKeyword name=literalText writeValue+
;
writeHttpChunkTrailerNode
: WriteKeyword HttpChunkTrailerKeyword name=literalText writeValue+
;
writeHttpContentLengthNode
: WriteKeyword HttpHeaderKeyword HttpContentLengthKeyword
;
writeHttpHostNode
: WriteKeyword HttpHeaderKeyword HttpHostKeyword
;
readHttpMethodNode
: ReadKeyword HttpMethodKeyword method=matcher
;
writeHttpMethodNode
: WriteKeyword HttpMethodKeyword method=writeValue
;
readHttpParameterNode
: ReadKeyword HttpParameterKeyword name=literalText matcher+
;
writeHttpParameterNode
: WriteKeyword HttpParameterKeyword name=literalText writeValue+
;
readHttpVersionNode
: ReadKeyword HttpVersionKeyword version=matcher
;
writeHttpVersionNode
: WriteKeyword HttpVersionKeyword version=writeValue
;
readHttpStatusNode
: ReadKeyword HttpStatusKeyword code=matcher reason=matcher
;
writeHttpRequestNode
: WriteKeyword HttpRequestKeyword form=writeValue
;
writeHttpStatusNode
: WriteKeyword HttpStatusKeyword code=writeValue reason=writeValue
;
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
: literalURI
| literalText
| literalBytes
| literalByte
| literalShort
| literalInteger
| literalLong
| expressionValue
;
literalURI
: literal=URILiteral
;
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
: literalURI
| expressionValue
;
SignedDecimalLiteral
: Plus DecimalLiteral
| Minus DecimalLiteral
// | DecimalLiteral
;
MaskKeyword: 'mask';
OffsetKeyword : 'offset';
OptionKeyword: 'option';
ChunkExtensionKeyWord: 'chunkExtension';
ShortKeyword
: 'short'
;
IntKeyword
: 'int'
;
ByteKeyword
: 'byte'
;
LongKeyword
: 'long'
;
AcceptKeyword
: 'accept'
;
AcceptedKeyword
: 'accepted'
;
AsKeyword
: 'as'
;
AwaitKeyword
: 'await'
;
BindKeyword
: 'bind'
;
BoundKeyword
: 'bound'
;
ChildKeyword
: 'child'
;
CloseKeyword
: 'close'
;
ClosedKeyword
: 'closed'
;
ConnectKeyword
: 'connect'
;
ConnectedKeyword
: 'connected'
;
DisconnectKeyword
: 'disconnect'
;
DisconnectedKeyword
: 'disconnected'
;
AbortKeyword
: 'abort'
;
AbortedKeyword
: 'aborted'
;
FlushKeyword
: 'flush'
;
NotifyKeyword
: 'notify'
;
OpenedKeyword
: 'opened'
;
PropertyKeyword
: 'property'
;
ReadKeyword
: 'read'
;
UnbindKeyword
: 'unbind'
;
UnboundKeyword
: 'unbound'
;
WriteKeyword
: 'write'
;
HttpContentLengthKeyword
: 'content-length'
;
HttpHeaderKeyword
: 'header'
;
HttpChunkTrailerKeyword
: 'trailer'
;
HttpHostKeyword
: 'host'
;
HttpMethodKeyword
: 'method'
;
HttpMissingKeyword
: 'missing'
;
HttpParameterKeyword
: 'parameter'
;
HttpRequestKeyword
: 'request'
;
HttpResponseKeyword
: 'response'
;
HttpStatusKeyword
: 'status'
;
HttpVersionKeyword
: 'version'
;
// 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
;
fragment
Identifier
: Letter (Digit | 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;
|
Remove unused token labels from grammar
|
Remove unused token labels from grammar
|
ANTLR
|
apache-2.0
|
jfallows/k3po,StCostea/k3po,cmebarrow/k3po,jfallows/k3po,k3po/k3po,cmebarrow/k3po,StCostea/k3po,k3po/k3po
|
9fa590fcde6137df5ffc1125c7a1855850f4f593
|
sharding-core/src/main/antlr4/imports/BaseRule.g4
|
sharding-core/src/main/antlr4/imports/BaseRule.g4
|
//rule in this file does not allow override
grammar BaseRule;
import DataType,Keyword,Symbol;
ID:
(BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_? DOT)?
(BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_?)
|[a-zA-Z_$0-9]+ DOT ASTERISK
;
schemaName: ID;
tableName: ID;
columnName: ID;
tablespaceName: ID;
collationName: STRING | ID;
indexName: ID;
alias: ID;
cteName:ID;
parserName: ID;
extensionName: ID;
rowName: ID;
opclass: ID;
fileGroup: ID;
groupName: ID;
constraintName: ID;
keyName: ID;
typeName: ID;
xmlSchemaCollection:ID;
columnSetName: ID;
directoryName: ID;
triggerName: ID;
roleName: ID;
partitionName: ID;
rewriteRuleName: ID;
ownerName: ID;
userName: ID;
ifExists
: IF EXISTS;
ifNotExists
: IF NOT EXISTS;
dataTypeLength
: LP_ (NUMBER (COMMA NUMBER)?)? RP_
;
nullNotnull
: NULL
| NOT NULL
;
primaryKey
: PRIMARY? KEY
;
matchNone
: 'Default does not match anything'
;
idList
: LP_ ID (COMMA ID)* RP_
;
rangeClause
: NUMBER (COMMA NUMBER)*
| NUMBER OFFSET NUMBER
;
tableNamesWithParen
: LP_ tableNames RP_
;
tableNames
: tableName (COMMA tableName)*
;
columnNamesWithParen
: LP_ columnNames RP_
;
columnNames
: columnName (COMMA columnName)*
;
columnList
: LP_ columnNames RP_
;
indexNames
: indexName (COMMA indexName)*
;
rowNames
: rowName (COMMA rowName)*
;
bitExprs:
bitExpr (COMMA bitExpr)*
;
exprs
: expr (COMMA expr)*
;
exprsWithParen
: LP_ exprs RP_
;
//https://dev.mysql.com/doc/refman/8.0/en/expressions.html
expr
: expr OR expr
| expr OR_ expr
| expr XOR expr
| expr AND expr
| expr AND_ expr
| LP_ expr RP_
| NOT expr
| NOT_ expr
| booleanPrimary
| exprRecursive
;
exprRecursive
: matchNone
;
booleanPrimary
: booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL)
| booleanPrimary SAFE_EQ predicate
| booleanPrimary comparisonOperator predicate
| booleanPrimary comparisonOperator (ALL | ANY) subquery
| predicate
;
comparisonOperator
: EQ_
| GTE
| GT
| LTE
| LT
| NEQ_
| NEQ
;
predicate
: bitExpr NOT? IN subquery
| bitExpr NOT? IN LP_ simpleExpr ( COMMA simpleExpr)* RP_
| bitExpr NOT? BETWEEN simpleExpr AND predicate
| bitExpr SOUNDS LIKE simpleExpr
| bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)*
| bitExpr NOT? REGEXP simpleExpr
| bitExpr
;
bitExpr
: bitExpr BIT_INCLUSIVE_OR bitExpr
| bitExpr BIT_AND bitExpr
| bitExpr SIGNED_LEFT_SHIFT bitExpr
| bitExpr SIGNED_RIGHT_SHIFT bitExpr
| bitExpr PLUS bitExpr
| bitExpr MINUS bitExpr
| bitExpr ASTERISK bitExpr
| bitExpr SLASH bitExpr
| bitExpr MOD bitExpr
| bitExpr MOD_ bitExpr
| bitExpr BIT_EXCLUSIVE_OR bitExpr
//| bitExpr '+' interval_expr
//| bitExpr '-' interval_expr
| simpleExpr
;
simpleExpr
: functionCall
| liter
| ID
| simpleExpr collateClause
//| param_marker
//| variable
| simpleExpr AND_ simpleExpr
| PLUS simpleExpr
| MINUS simpleExpr
| UNARY_BIT_COMPLEMENT simpleExpr
| NOT_ simpleExpr
| BINARY simpleExpr
| LP_ expr RP_
| ROW LP_ simpleExpr( COMMA simpleExpr)* RP_
| subquery
| EXISTS subquery
// | (identifier expr)
//| match_expr
//| case_expr
// | interval_expr
|privateExprOfDb
;
functionCall
: ID LP_( bitExprs?) RP_
;
privateExprOfDb
: matchNone
;
liter
: QUESTION
| NUMBER
| TRUE
| FALSE
| NULL
| LBE_ ID STRING RBE_
| HEX_DIGIT
| ID? STRING collateClause?
| (DATE | TIME |TIMESTAMP) STRING
| ID? BIT_NUM collateClause?
;
subquery
: matchNone
;
collateClause
: matchNone
;
orderByClause
: ORDER BY groupByItem (COMMA groupByItem)*
;
groupByItem
: (columnName | NUMBER |expr) (ASC|DESC)?
;
|
//rule in this file does not allow override
grammar BaseRule;
import DataType,Keyword,Symbol;
ID:
(BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_? DOT)?
(BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_?)
|[a-zA-Z_$0-9]+ DOT ASTERISK
;
schemaName: ID;
tableName: ID;
columnName: ID;
tablespaceName: ID;
collationName: STRING | ID;
indexName: ID;
alias: ID;
cteName:ID;
parserName: ID;
extensionName: ID;
rowName: ID;
opclass: ID;
fileGroup: ID;
groupName: ID;
constraintName: ID;
keyName: ID;
typeName: ID;
xmlSchemaCollection:ID;
columnSetName: ID;
directoryName: ID;
triggerName: ID;
roleName: ID;
partitionName: ID;
rewriteRuleName: ID;
ownerName: ID;
userName: ID;
ifExists
: IF EXISTS;
ifNotExists
: IF NOT EXISTS;
dataTypeLength
: LP_ (NUMBER (COMMA NUMBER)?)? RP_
;
nullNotnull
: NULL
| NOT NULL
;
primaryKey
: PRIMARY? KEY
;
matchNone
: 'Default does not match anything'
;
idList
: LP_ ID (COMMA ID)* RP_
;
rangeClause
: NUMBER (COMMA NUMBER)*
| NUMBER OFFSET NUMBER
;
tableNamesWithParen
: LP_ tableNames RP_
;
tableNames
: tableName (COMMA tableName)*
;
columnNamesWithParen
: LP_ columnNames RP_
;
columnNames
: columnName (COMMA columnName)*
;
columnList
: LP_ columnNames RP_
;
indexNames
: indexName (COMMA indexName)*
;
rowNames
: rowName (COMMA rowName)*
;
roleNames
: roleName (COMMA roleName)*
;
userNames
: userName (COMMA userName)*
;
bitExprs:
bitExpr (COMMA bitExpr)*
;
exprs
: expr (COMMA expr)*
;
exprsWithParen
: LP_ exprs RP_
;
//https://dev.mysql.com/doc/refman/8.0/en/expressions.html
expr
: expr OR expr
| expr OR_ expr
| expr XOR expr
| expr AND expr
| expr AND_ expr
| LP_ expr RP_
| NOT expr
| NOT_ expr
| booleanPrimary
| exprRecursive
;
exprRecursive
: matchNone
;
booleanPrimary
: booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL)
| booleanPrimary SAFE_EQ predicate
| booleanPrimary comparisonOperator predicate
| booleanPrimary comparisonOperator (ALL | ANY) subquery
| predicate
;
comparisonOperator
: EQ_
| GTE
| GT
| LTE
| LT
| NEQ_
| NEQ
;
predicate
: bitExpr NOT? IN subquery
| bitExpr NOT? IN LP_ simpleExpr ( COMMA simpleExpr)* RP_
| bitExpr NOT? BETWEEN simpleExpr AND predicate
| bitExpr SOUNDS LIKE simpleExpr
| bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)*
| bitExpr NOT? REGEXP simpleExpr
| bitExpr
;
bitExpr
: bitExpr BIT_INCLUSIVE_OR bitExpr
| bitExpr BIT_AND bitExpr
| bitExpr SIGNED_LEFT_SHIFT bitExpr
| bitExpr SIGNED_RIGHT_SHIFT bitExpr
| bitExpr PLUS bitExpr
| bitExpr MINUS bitExpr
| bitExpr ASTERISK bitExpr
| bitExpr SLASH bitExpr
| bitExpr MOD bitExpr
| bitExpr MOD_ bitExpr
| bitExpr BIT_EXCLUSIVE_OR bitExpr
//| bitExpr '+' interval_expr
//| bitExpr '-' interval_expr
| simpleExpr
;
simpleExpr
: functionCall
| liter
| ID
| simpleExpr collateClause
//| param_marker
//| variable
| simpleExpr AND_ simpleExpr
| PLUS simpleExpr
| MINUS simpleExpr
| UNARY_BIT_COMPLEMENT simpleExpr
| NOT_ simpleExpr
| BINARY simpleExpr
| LP_ expr RP_
| ROW LP_ simpleExpr( COMMA simpleExpr)* RP_
| subquery
| EXISTS subquery
// | (identifier expr)
//| match_expr
//| case_expr
// | interval_expr
|privateExprOfDb
;
functionCall
: ID LP_( bitExprs?) RP_
;
privateExprOfDb
: matchNone
;
liter
: QUESTION
| NUMBER
| TRUE
| FALSE
| NULL
| LBE_ ID STRING RBE_
| HEX_DIGIT
| ID? STRING collateClause?
| (DATE | TIME |TIMESTAMP) STRING
| ID? BIT_NUM collateClause?
;
subquery
: matchNone
;
collateClause
: matchNone
;
orderByClause
: ORDER BY groupByItem (COMMA groupByItem)*
;
groupByItem
: (columnName | NUMBER |expr) (ASC|DESC)?
;
|
add userNames roleNames
|
add userNames roleNames
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
|
01594e3e783bfb5c96b53faef8ad856ab905d32b
|
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';
ON : 'on'; // TODO: not used?
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;}
) -> channel(HIDDEN)
;
COMMENT
: ( ('//') ~('\n'|'\r')* '\r'? '\n'?
// | '/*' ( options {greedy=false;} : . )* '*/'
| '/*' .*? '*/'
)
-> 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()));}
//{return ID<IDNode>[$keyword_as_ident.text];}
| ID
;
keyword_as_ident
: SELECT | LIMIT | OFFSET | WHERE | 'order' | 'by' | DESC | ON | 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 //{return ^(ARRAY_LITERAL literal_element+);}
;
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';
ON : 'on'; // TODO: not used?
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 | ON | 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
;
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.