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
|
---|---|---|---|---|---|---|---|---|---|
a8fd4db66a3b2b06e47709d3da63cab710d23b0b
|
trans/src/wich/parser/Wich.g4
|
trans/src/wich/parser/Wich.g4
|
/*
The MIT License (MIT)
Copyright (c) 2015 Terence Parr, Hanzhou Shi, Shuai Yuan, Yuanyuan Zhang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
grammar Wich;
@header {
import wich.semantics.type.*;
import org.antlr.symtab.*;
}
file : script ;
script returns [GlobalScope scope]
: (statement | function)* EOF ;
function returns [WFunctionSymbol scope]
: 'func' ID '(' formal_args? ')' (':' type)? block
;
formal_args : formal_arg (',' formal_arg)* ;
formal_arg : ID ':' type ;
type: 'int'
| 'float'
| 'string'
| '[' ']'
;
block returns [Scope scope]
: '{' statement* '}';
statement
: 'if' '(' expr ')' statement ('else' statement)? # If
| 'while' '(' expr ')' statement # While
| 'var' ID '=' expr # VarDef
| ID '=' expr # Assign
| ID '[' expr ']' '=' expr # ElementAssign
| call_expr # CallStatement
| 'return' expr # Return
| block # BlockStatement
;
expr returns [Type exprType]
: expr operator expr # Op
| '-' expr # Negate
| '!' expr # Not
| call_expr # Call
| ID '[' expr ']' # Index
| '(' expr ')' # Parens
| primary # Atom
;
operator : '*'|'/'|'+'|'-'|'<'|'<='|'=='|'!='|'>'|'>='|'||'|'&&'|' . ' ; // no precedence
call_expr : ID '(' expr_list ')' ; // todo: maybe add print as keyword?
expr_list : expr (',' expr)* ;
primary
: ID
| INT
| FLOAT
| STRING
| '[' expr_list ']'
;
LINE_COMMENT : '//' .*? ('\n'|EOF) -> channel(HIDDEN) ;
COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ;
ID : [a-zA-Z_] [a-zA-Z0-9_]* ;
INT : [0-9]+ ;
FLOAT
: '-'? INT '.' INT EXP? // 1.35, 1.35E-9, 0.3, -4.5
| '-'? INT EXP // 1e10 -3e4
;
fragment EXP : [Ee] [+\-]? INT ;
STRING : '"' (ESC | ~["\\])* '"' ;
fragment ESC : '\\' ["\bfnrt] ;
WS : [ \t\n\r]+ -> channel(HIDDEN) ;
|
/*
The MIT License (MIT)
Copyright (c) 2015 Terence Parr, Hanzhou Shi, Shuai Yuan, Yuanyuan Zhang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
grammar Wich;
@header {
import wich.semantics.type.*;
import org.antlr.symtab.*;
}
file : script ;
script returns [GlobalScope scope]
: (statement | function)* EOF ;
function returns [WFunctionSymbol scope]
: 'func' ID '(' formal_args? ')' (':' type)? block
;
formal_args : formal_arg (',' formal_arg)* ;
formal_arg : ID ':' type ;
type: 'int'
| 'float'
| 'string'
| '[' ']'
;
block returns [Scope scope]
: '{' statement* '}';
statement
: 'if' '(' expr ')' statement ('else' statement)? # If
| 'while' '(' expr ')' statement # While
| 'var' ID '=' expr # VarDef
| ID '=' expr # Assign
| ID '[' expr ']' '=' expr # ElementAssign
| call_expr # CallStatement
| 'return' expr # Return
| block # BlockStatement
;
expr returns [Type exprType]
: expr operator expr # Op
| '-' expr # Negate
| '!' expr # Not
| call_expr # Call
| ID '[' expr ']' # Index
| '(' expr ')' # Parens
| primary # Atom
;
operator : '*'|'/'|'+'|'-'|'<'|'<='|'=='|'!='|'>'|'>='|'||'|'&&'|' . ' ; // no precedence
call_expr : ID '(' expr_list ')' ; // todo: maybe add print as keyword?
expr_list : expr (',' expr)* ;
primary
: ID
| INT
| FLOAT
| STRING
| '[' expr_list ']'
;
LPAREN : '(' ;
RPAREN : ')' ;
COLON : ':' ;
COMMA : ',' ;
LBRACK : '[' ;
RBRACK : ']' ;
LBRACE : '{' ;
RBRACE : '}' ;
IF : 'if' ;
ELSE : 'else' ;
WHILE : 'while' ;
VAR : 'var' ;
EQUAL : '=' ;
RETURN : 'return' ;
SUB : '-' ;
BANG : '!' ;
MUL : '*' ;
DIV : '/' ;
ADD : '+' ;
LT : '<' ;
LE : '<=' ;
EQUAL_EQUAL : '==' ;
NOT_EQUAL : '!=' ;
GT : '>' ;
GE : '>=' ;
OR : '||' ;
AND : '&&' ;
DOT : ' . ' ;
LINE_COMMENT : '//' .*? ('\n'|EOF) -> channel(HIDDEN) ;
COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ;
ID : [a-zA-Z_] [a-zA-Z0-9_]* ;
INT : [0-9]+ ;
FLOAT
: '-'? INT '.' INT EXP? // 1.35, 1.35E-9, 0.3, -4.5
| '-'? INT EXP // 1e10 -3e4
;
fragment EXP : [Ee] [+\-]? INT ;
STRING : '"' (ESC | ~["\\])* '"' ;
fragment ESC : '\\' ["\bfnrt] ;
WS : [ \t\n\r]+ -> channel(HIDDEN) ;
|
add token type labels to parser
|
add token type labels to parser
|
ANTLR
|
mit
|
YuanyuanZh/wich-c,syuanivy/wich-c,hanjoes/wich-c,langwich/wich-c,hanjoes/wich-c,syuanivy/wich-c,langwich/wich-c,YuanyuanZh/wich-c
|
30ad4f2198906d5d7f6028e93cffc02327bac79a
|
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)?
;
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)?
;
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 createUser4
|
add createUser4
|
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
|
0f084b63aed473f63e39dd7b3fb8a88f9250f549
|
vrj.g4
|
vrj.g4
|
grammar vrj;
init:
( typeDefinition
| nativeDefinition
| globalDefinition
| functionDefinition
| libraryDefinition
| structDefinition
| NL
)*
EOF
;
visibility: 'private' | 'public';
member: variableExpression | functionExpression;
memberExpression: member ('.' member)+;
name: ID;
type: memberExpression | name | 'nothing';
param: type name;
paramList:
( param (',' param)* )
| 'nothing'
;
typeDefinition: 'type' typeName=name ('extends' typeExtends=name) NL;
functionSignature: name 'takes' paramList 'returns' type NL;
nativeDefinition: ('constant')? 'native' functionSignature;
arguments: '(' expressionList? ')';
functionExpression: name arguments;
variableExpression: name ('[' expression ']')?;
expression:
'(' expression ')' #Parenthesis
| '-' expression #Negative
| 'not' expression #Not
| expression '%' expression #Mod
| expression '/' expression #Div
| expression '*' expression #Mult
| expression '+' expression #Sum
| expression '-' expression #Sub
| memberExpression #IgnoreMemberExpression
| variableExpression #IgnoreVariableExpression
| functionExpression #IgnoreFunctionExpression
| expression operator=('=='|'!='|'<='|'<'|'>'|'>=') expression #Comparison
| expression operator=('or'|'and') expression #Logical
| 'function' name #Code
| ('true'|'false') #Boolean
| 'null' #Null
| STRING #String
| REAL #Real
| INT #Integer
;
expressionList: expression (',' expression)*;
variableStatement: type (array='array')? name ('=' expression)? NL;
globalVariable: visibility? (constant='constant')? variableStatement;
globalDefinition:
'globals' NL
(globalVariable | NL)*
'endglobals' NL;
loopStatement:
'loop' NL
statements
'endloop' NL;
elseIfStatement: 'elseif' expression 'then' NL statements;
elseStatement: 'else' NL statements;
ifStatement:
(sstatic='static')? 'if' expression 'then' NL
statements
elseIfStatement*
elseStatement?
'endif' NL;
localVariable: 'local' variableStatement;
setVariable: 'set' (variableExpression | memberExpression) '=' expression NL;
exitwhen: 'exitwhen' expression NL;
functionCall: 'call' (functionExpression | memberExpression) NL;
returnStatement: 'return' expression? NL;
statement:
localVariable
| setVariable
| exitwhen
| functionCall
| returnStatement
| ifStatement
| loopStatement
;
statements: (statement | NL)*;
functionDefinition:
visibility? 'function' functionSignature
statements
'endfunction' NL;
libraryRequirementExpression: name (',' name)*;
libraryBody:
( globalDefinition
| functionDefinition
| structDefinition
| NL
)*
;
libraryDefinition:
'library' name ('initializer' initializer=name)? ('requires' libraryRequirementExpression)? NL
libraryBody
'endlibrary' NL;
propertyStatement: visibility? (sstatic='static')? variableStatement;
methodDefinition:
visibility? (sstatic='static')? 'method' (operator='operator')? functionSignature
statements
'endmethod' NL;
extendable:
'array'
| name
| memberExpression
;
structBody:
( propertyStatement
| methodDefinition
| NL
)*
;
structDefinition:
visibility? 'struct' name ('extends' extendsFrom=extendable)? NL
structBody
'endstruct' NL;
STRING: '"' .*? '"';
REAL: [0-9]+ '.' [0-9]* | '.'[0-9]+;
INT: [0-9]+ | '0x' [0-9a-fA-F]+ | '\'' . . . . '\'' | '\'' . '\'';
NL: [\r\n]+;
ID: [a-zA-Z_][a-zA-Z0-9_]*;
WS : [ \t]+ -> channel(HIDDEN);
COMMENT : '/*' .*? '*/' -> channel(HIDDEN);
LINE_COMMENT: '//' ~[\r\n]* -> channel(HIDDEN);
|
/**
* MIT License
*
* Copyright (c) 2017 Franco Montenegro
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
grammar vrj;
init
: (topDeclaration | NL)* EOF
;
topDeclaration
: libraryDeclaration
| structDeclaration
| typeDeclaration
| nativeDeclaration
| functionDeclaration
| globalDeclaration
;
visibility
: 'private'
| 'public'
;
name
: ID
;
type
: expression
| 'nothing'
;
param
: type name
;
paramList
: (param (',' param)*)
| 'nothing'
;
typeDeclaration
: 'type' typeName=name ('extends' typeExtends=name)? NL
;
functionSignature
: name 'takes' paramList 'returns' type NL
;
nativeDeclaration
: ('constant')? 'native' functionSignature
;
arguments
: '(' expressionList? ')'
;
expression
: '(' expression ')' #ParenthesisExpression
| left=expression '.' right=expression #ChainExpression
| variable=name ('[' index=expression ']')? #VariableExpression
| function=name arguments #FunctionExpression
| '-' expression #NegativeExpression
| 'not' expression #NotExpression
| left=expression '%' right=expression #ModuloExpression
| left=expression operator=('/' | '*') right=expression #DivMultExpression
| left=expression operator=('+' | '-') right=expression #SumSubExpression
| left=expression operator=('==' | '!=' | '<=' | '<' | '>' | '>=') right=expression #ComparisonExpression
| left=expression operator=('or' | 'and') right=expression #LogicalExpression
| 'function' code=expression #CodeExpression
| ('true' | 'false') #BooleanExpression
| 'null' #NullExpression
| STRING #StringExpression
| REAL #RealExpression
| INT #IntegerExpression
;
expressionList
: expression (',' expression)*
;
variableDeclaration
: type 'array' name NL #ArrayVariableDeclaration
| type name ('=' value=expression)? NL #NonArrayVariableDeclaration
;
globalVariableDeclaration
: visibility? (constant='constant')? variableDeclaration
;
globalDeclaration
: 'globals' NL
(globalVariableDeclaration | NL)*
'endglobals' NL
;
loopStatement
: 'loop' NL
statements
'endloop' NL
;
elseIfStatement
: 'elseif' condition=expression 'then' NL statements
;
elseStatement
: 'else' NL statements
;
ifStatement
: (sstatic='static')? 'if' condition=expression 'then' NL
statements
elseIfStatement*
elseStatement?
'endif' NL
;
localVariableDeclaration
: 'local' variableDeclaration
;
setVariableStatement
: 'set' variable=expression '=' value=expression NL
;
exitWhenStatement
: 'exitwhen' condition=expression NL
;
functionCallStatement
: 'call' function=expression NL
;
returnStatement
: 'return' expression? NL
;
statement
: localVariableDeclaration
| setVariableStatement
| exitWhenStatement
| functionCallStatement
| returnStatement
| ifStatement
| loopStatement
;
statements
: (statement | NL)*
;
functionDeclaration
: visibility? 'function' functionSignature
statements
'endfunction' NL
;
libraryRequirementsExpression
: name (',' name)*
;
libraryBody
: ( globalDeclaration
| functionDeclaration
| structDeclaration
| NL
)*
;
libraryDeclaration
: 'library' name ('initializer' initializer=name)? ('requires' libraryRequirementsExpression)? NL
libraryBody
'endlibrary' NL
;
propertyDeclaration
: visibility? (sstatic='static')? variableDeclaration
;
methodDeclaration
: visibility? (sstatic='static')? 'method' (operator='operator')? functionSignature
statements
'endmethod' NL
;
extendsFromExpression
: 'array'
| expression
;
structBody
: ( propertyDeclaration
| methodDeclaration
| NL
)*
;
structDeclaration
: visibility? 'struct' name ('extends' extendsFromExpression)? NL
structBody
'endstruct' NL
;
STRING
: '"' .*? '"'
;
// Credits to WurstScript
REAL
: [0-9]+ '.' [0-9]*
| '.'[0-9]+
;
// Credits to WurstScript
INT
: [0-9]+
| '0x' [0-9a-fA-F]+
| '\'' . . . . '\''
| '\'' . '\''
;
NL
: [\r\n]+
;
ID
: [a-zA-Z_][a-zA-Z0-9_]*
;
WS
: [ \t]+ -> channel(HIDDEN)
;
COMMENT
: '/*' .*? '*/' -> channel(HIDDEN)
;
LINE_COMMENT: '//' ~[\r\n]* -> channel(HIDDEN);
|
Clean grammar and add MIT licence header
|
Clean grammar and add MIT licence header
|
ANTLR
|
mit
|
Ruk33/vrJASS2
|
ee85463c9aebba3ebc4a734d52cb0399c070dae0
|
mysql/MySQL.g4
|
mysql/MySQL.g4
|
grammar MySQL;
options {
tokenVocab=MySQLBase;
}
@header {
}
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 )*
;
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_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;
}
@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
;
|
add join clause
|
add join clause
|
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
|
813a73c31042a4db29c1e3fdf01e187b87ab9303
|
metamath/metamath.g4
|
metamath/metamath.g4
|
/*
BSD License
Copyright (c) 2020, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar metamath;
database
: outermostscopestmt*
;
outermostscopestmt
: includestmt
| constantstmt
| stmt
;
includestmt
: '$[' filename '$]'
;
constantstmt
: '$c' constant+ '$.'
;
stmt
: block
| variablestmt
| disjointstmt
| hypothesisstmt
| assertstmt
;
block
: '${' stmt* '$}'
;
variablestmt
: '$v' variable+ '$.'
;
disjointstmt
: '$d' variable variable variable* '$.'
;
hypothesisstmt
: floatingstmt
| essentialstmt
;
floatingstmt
: LABEL '$f' typecode variable '$.'
;
essentialstmt
: LABEL '$e' typecode mathsymbol* '$.'
;
assertstmt
: axiomstmt
| provablestmt
;
axiomstmt
: LABEL '$a' typecode mathsymbol* '$.'
;
provablestmt
: LABEL '$p' typecode mathsymbol* '$=' proof '$.'
;
proof
: uncompressedproof
| compressedproof
;
uncompressedproof
: (LABEL | '?')+
;
compressedproof
: '(' LABEL* ')' COMPRESSEDPROOFBLOCK+
;
typecode
: constant
;
mathsymbol
: (PRINTABLECHARACTER | LPAREN | RPAREN)+
;
filename
: mathsymbol
;
constant
: mathsymbol
;
variable
: mathsymbol
;
LPAREN
: '('
;
RPAREN
: ')'
;
PRINTABLECHARACTER
: [\u0021-\u007e]+
;
LABEL
: (LETTERORDIGIT | '.' | '-' | '_')+
;
fragment LETTERORDIGIT
: [A-Za-z0-9]
;
COMPRESSEDPROOFBLOCK
: ([A-Z] | '?')+
;
BLOCK_COMMENT
: '$(' .*? '$)' -> skip
;
WS
: [ \r\n\t\f]+ -> skip
;
|
/*
BSD License
Copyright (c) 2020, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar metamath;
database
: outermostscopestmt* EOF
;
outermostscopestmt
: includestmt
| constantstmt
| stmt
;
includestmt
: '$[' filename '$]'
;
constantstmt
: '$c' constant+ '$.'
;
stmt
: block
| variablestmt
| disjointstmt
| hypothesisstmt
| assertstmt
;
block
: '${' stmt* '$}'
;
variablestmt
: '$v' variable+ '$.'
;
disjointstmt
: '$d' variable variable variable* '$.'
;
hypothesisstmt
: floatingstmt
| essentialstmt
;
floatingstmt
: LABEL '$f' typecode variable '$.'
;
essentialstmt
: LABEL '$e' typecode mathsymbol* '$.'
;
assertstmt
: axiomstmt
| provablestmt
;
axiomstmt
: LABEL '$a' typecode mathsymbol* '$.'
;
provablestmt
: LABEL '$p' typecode mathsymbol* '$=' proof '$.'
;
proof
: uncompressedproof
| compressedproof
;
uncompressedproof
: (LABEL | '?')+
;
compressedproof
: '(' LABEL* ')' COMPRESSEDPROOFBLOCK+
;
typecode
: constant
;
mathsymbol
: (printablecharacter | LPAREN | RPAREN)+
;
printablecharacter
: PRINTABLECHARACTER | LABEL
;
filename
: mathsymbol
;
constant
: mathsymbol
;
variable
: mathsymbol
;
LPAREN
: '('
;
RPAREN
: ')'
;
LABEL
: (LETTERORDIGIT | '.' | '-' | '_')+
;
PRINTABLECHARACTER
: [\u0021-\u007e]+
;
fragment LETTERORDIGIT
: [A-Za-z0-9]
;
COMPRESSEDPROOFBLOCK
: ([A-Z] | '?')+
;
BLOCK_COMMENT
: '$(' .*? '$)' -> skip
;
WS
: [ \r\n\t\f]+ -> skip
;
|
Add EOF start rule for metamath. Fix overlapping PRINTABLECHARACTER and LABEL.
|
Add EOF start rule for metamath. Fix overlapping PRINTABLECHARACTER and LABEL.
|
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
|
40d4c68d68c420e754a19290d8a7164ce8003f53
|
parser/gen/CEL.g4
|
parser/gen/CEL.g4
|
// Copyright 2018 Google LLC
//
// 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 CEL;
// Grammar Rules
// =============
start
: e=expr EOF
;
expr
: e=conditionalOr (op='?' e1=conditionalOr ':' e2=expr)?
;
conditionalOr
: e=conditionalAnd (ops+='||' e1+=conditionalAnd)*
;
conditionalAnd
: e=relation (ops+='&&' e1+=relation)*
;
relation
: calc
| relation op=('<'|'<='|'>='|'>'|'=='|'!='|'in') relation
;
calc
: unary
| calc op=('*'|'/'|'%') calc
| calc op=('+'|'-') calc
;
unary
: member # MemberExpr
| (ops+='!')+ member # LogicalNot
| (ops+='-')+ member # Negate
;
member
: primary # PrimaryExpr
| member op='.' id=IDENTIFIER (open='(' args=exprList? ')')? # SelectOrCall
| member op='[' index=expr ']' # Index
| member op='{' entries=fieldInitializerList? '}' # CreateMessage
;
primary
: leadingDot='.'? id=IDENTIFIER (op='(' args=exprList? ')')? # IdentOrGlobalCall
| '(' e=expr ')' # Nested
| op='[' elems=exprList? ','? ']' # CreateList
| op='{' entries=mapInitializerList? '}' # CreateStruct
| literal # ConstantLiteral
;
exprList
: e+=expr (',' e+=expr)*
;
fieldInitializerList
: fields+=IDENTIFIER cols+=':' values+=expr (',' fields+=IDENTIFIER cols+=':' values+=expr)*
;
mapInitializerList
: keys+=expr cols+=':' values+=expr (',' keys+=expr cols+=':' values+=expr)*
;
literal
: sign=MINUS? tok=NUM_INT # Int
| tok=NUM_UINT # Uint
| sign=MINUS? tok=NUM_FLOAT # Double
| tok=STRING # String
| tok=BYTES # Bytes
| tok='true' # BoolTrue
| tok='false' # BoolFalse
| tok='null' # Null
;
// Lexer Rules
// ===========
EQUALS : '==';
NOT_EQUALS : '!=';
LESS : '<';
LESS_EQUALS : '<=';
GREATER_EQUALS : '>=';
GREATER : '>';
LOGICAL_AND : '&&';
LOGICAL_OR : '||';
LBRACKET : '[';
RPRACKET : ']';
LBRACE : '{';
RBRACE : '}';
LPAREN : '(';
RPAREN : ')';
DOT : '.';
COMMA : ',';
MINUS : '-';
EXCLAM : '!';
QUESTIONMARK : '?';
COLON : ':';
PLUS : '+';
STAR : '*';
SLASH : '/';
PERCENT : '%';
TRUE : 'true';
FALSE : 'false';
NULL : 'null';
fragment BACKSLASH : '\\';
fragment LETTER : 'A'..'Z' | 'a'..'z' ;
fragment DIGIT : '0'..'9' ;
fragment EXPONENT : ('e' | 'E') ( '+' | '-' )? DIGIT+ ;
fragment HEXDIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ;
fragment RAW : 'r' | 'R';
fragment ESC_SEQ
: ESC_CHAR_SEQ
| ESC_BYTE_SEQ
| ESC_UNI_SEQ
| ESC_OCT_SEQ
;
fragment ESC_CHAR_SEQ
: BACKSLASH ('a'|'b'|'f'|'n'|'r'|'t'|'v'|'"'|'\''|'\\'|'?'|'`')
;
fragment ESC_OCT_SEQ
: BACKSLASH ('0'..'3') ('0'..'7') ('0'..'7')
;
fragment ESC_BYTE_SEQ
: BACKSLASH ( 'x' | 'X' ) HEXDIGIT HEXDIGIT
;
fragment ESC_UNI_SEQ
: BACKSLASH 'u' HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT
| BACKSLASH 'U' HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT
;
WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ -> channel(HIDDEN) ;
COMMENT : '//' (~'\n')* -> channel(HIDDEN) ;
NUM_FLOAT
: ( DIGIT+ ('.' DIGIT+) EXPONENT?
| DIGIT+ EXPONENT
| '.' DIGIT+ EXPONENT?
)
;
NUM_INT
: ( DIGIT+ | '0x' HEXDIGIT+ );
NUM_UINT
: DIGIT+ ( 'u' | 'U' )
| '0x' HEXDIGIT+ ( 'u' | 'U' )
;
STRING
: '"' (ESC_SEQ | ~('\\'|'"'|'\n'|'\r'))* '"'
| '\'' (ESC_SEQ | ~('\\'|'\''|'\n'|'\r'))* '\''
| '"""' (ESC_SEQ | ~('\\'))*? '"""'
| '\'\'\'' (ESC_SEQ | ~('\\'))*? '\'\'\''
| RAW '"' ~('"'|'\n'|'\r')* '"'
| RAW '\'' ~('\''|'\n'|'\r')* '\''
| RAW '"""' .*? '"""'
| RAW '\'\'\'' .*? '\'\'\''
;
BYTES : ('b' | 'B') STRING;
IDENTIFIER : (LETTER | '_') ( LETTER | DIGIT | '_')*;
|
// Copyright 2018 Google LLC
//
// 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 CEL;
// Grammar Rules
// =============
start
: e=expr EOF
;
expr
: e=conditionalOr (op='?' e1=conditionalOr ':' e2=expr)?
;
conditionalOr
: e=conditionalAnd (ops+='||' e1+=conditionalAnd)*
;
conditionalAnd
: e=relation (ops+='&&' e1+=relation)*
;
relation
: calc
| relation op=('<'|'<='|'>='|'>'|'=='|'!='|'in') relation
;
calc
: unary
| calc op=('*'|'/'|'%') calc
| calc op=('+'|'-') calc
;
unary
: member # MemberExpr
| (ops+='!')+ member # LogicalNot
| (ops+='-')+ member # Negate
;
member
: primary # PrimaryExpr
| member op='.' id=IDENTIFIER (open='(' args=exprList? ')')? # SelectOrCall
| member op='[' index=expr ']' # Index
| member op='{' entries=fieldInitializerList? '}' # CreateMessage
;
primary
: leadingDot='.'? id=IDENTIFIER (op='(' args=exprList? ')')? # IdentOrGlobalCall
| '(' e=expr ')' # Nested
| op='[' elems=exprList? ','? ']' # CreateList
| op='{' entries=mapInitializerList? '}' # CreateStruct
| literal # ConstantLiteral
;
exprList
: e+=expr (',' e+=expr)*
;
fieldInitializerList
: fields+=IDENTIFIER cols+=':' values+=expr (',' fields+=IDENTIFIER cols+=':' values+=expr)*
;
mapInitializerList
: keys+=expr cols+=':' values+=expr (',' keys+=expr cols+=':' values+=expr)*
;
literal
: sign=MINUS? tok=NUM_INT # Int
| tok=NUM_UINT # Uint
| sign=MINUS? tok=NUM_FLOAT # Double
| tok=STRING # String
| tok=BYTES # Bytes
| tok='true' # BoolTrue
| tok='false' # BoolFalse
| tok='null' # Null
;
// Lexer Rules
// ===========
EQUALS : '==';
NOT_EQUALS : '!=';
IN: 'in';
LESS : '<';
LESS_EQUALS : '<=';
GREATER_EQUALS : '>=';
GREATER : '>';
LOGICAL_AND : '&&';
LOGICAL_OR : '||';
LBRACKET : '[';
RPRACKET : ']';
LBRACE : '{';
RBRACE : '}';
LPAREN : '(';
RPAREN : ')';
DOT : '.';
COMMA : ',';
MINUS : '-';
EXCLAM : '!';
QUESTIONMARK : '?';
COLON : ':';
PLUS : '+';
STAR : '*';
SLASH : '/';
PERCENT : '%';
TRUE : 'true';
FALSE : 'false';
NULL : 'null';
fragment BACKSLASH : '\\';
fragment LETTER : 'A'..'Z' | 'a'..'z' ;
fragment DIGIT : '0'..'9' ;
fragment EXPONENT : ('e' | 'E') ( '+' | '-' )? DIGIT+ ;
fragment HEXDIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ;
fragment RAW : 'r' | 'R';
fragment ESC_SEQ
: ESC_CHAR_SEQ
| ESC_BYTE_SEQ
| ESC_UNI_SEQ
| ESC_OCT_SEQ
;
fragment ESC_CHAR_SEQ
: BACKSLASH ('a'|'b'|'f'|'n'|'r'|'t'|'v'|'"'|'\''|'\\'|'?'|'`')
;
fragment ESC_OCT_SEQ
: BACKSLASH ('0'..'3') ('0'..'7') ('0'..'7')
;
fragment ESC_BYTE_SEQ
: BACKSLASH ( 'x' | 'X' ) HEXDIGIT HEXDIGIT
;
fragment ESC_UNI_SEQ
: BACKSLASH 'u' HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT
| BACKSLASH 'U' HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT
;
WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ -> channel(HIDDEN) ;
COMMENT : '//' (~'\n')* -> channel(HIDDEN) ;
NUM_FLOAT
: ( DIGIT+ ('.' DIGIT+) EXPONENT?
| DIGIT+ EXPONENT
| '.' DIGIT+ EXPONENT?
)
;
NUM_INT
: ( DIGIT+ | '0x' HEXDIGIT+ );
NUM_UINT
: DIGIT+ ( 'u' | 'U' )
| '0x' HEXDIGIT+ ( 'u' | 'U' )
;
STRING
: '"' (ESC_SEQ | ~('\\'|'"'|'\n'|'\r'))* '"'
| '\'' (ESC_SEQ | ~('\\'|'\''|'\n'|'\r'))* '\''
| '"""' (ESC_SEQ | ~('\\'))*? '"""'
| '\'\'\'' (ESC_SEQ | ~('\\'))*? '\'\'\''
| RAW '"' ~('"'|'\n'|'\r')* '"'
| RAW '\'' ~('\''|'\n'|'\r')* '\''
| RAW '"""' .*? '"""'
| RAW '\'\'\'' .*? '\'\'\''
;
BYTES : ('b' | 'B') STRING;
IDENTIFIER : (LETTER | '_') ( LETTER | DIGIT | '_')*;
|
Add missing lexer rule for 'in' (#260)
|
Add missing lexer rule for 'in' (#260)
|
ANTLR
|
apache-2.0
|
google/cel-go,google/cel-go
|
80ba2b530576b2305179ec1fed3d7b3cf50c09c9
|
pattern_grammar/STIXPattern.g4
|
pattern_grammar/STIXPattern.g4
|
// This is an ANTLR4 grammar for the STIX Patterning Language.
//
// http://docs.oasis-open.org/cti/stix/v2.0/stix-v2.0-part5-stix-patterning.html
grammar STIXPattern;
pattern
: observationExpressions EOF
;
observationExpressions
: <assoc=left> observationExpressions FOLLOWEDBY observationExpressions
| observationExpressionOr
;
observationExpressionOr
: <assoc=left> observationExpressionOr OR observationExpressionOr
| observationExpressionAnd
;
observationExpressionAnd
: <assoc=left> observationExpressionAnd AND observationExpressionAnd
| observationExpression
;
observationExpression
: LBRACK comparisonExpression RBRACK # observationExpressionSimple
| LPAREN observationExpressions RPAREN # observationExpressionCompound
| observationExpression startStopQualifier # observationExpressionStartStop
| observationExpression withinQualifier # observationExpressionWithin
| observationExpression repeatedQualifier # observationExpressionRepeated
;
comparisonExpression
: <assoc=left> comparisonExpression OR comparisonExpression
| comparisonExpressionAnd
;
comparisonExpressionAnd
: <assoc=left> comparisonExpressionAnd AND comparisonExpressionAnd
| propTest
;
propTest
: objectPath NOT? (EQ|NEQ) primitiveLiteral # propTestEqual
| objectPath NOT? (GT|LT|GE|LE) orderableLiteral # propTestOrder
| objectPath NOT? IN setLiteral # propTestSet
| objectPath NOT? LIKE StringLiteral # propTestLike
| objectPath NOT? MATCHES StringLiteral # propTestRegex
| objectPath NOT? ISSUBSET StringLiteral # propTestIsSubset
| objectPath NOT? ISSUPERSET StringLiteral # propTestIsSuperset
| LPAREN comparisonExpression RPAREN # propTestParen
| 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
: .
;
|
// This is an ANTLR4 grammar for the STIX Patterning Language.
//
// https://docs.oasis-open.org/cti/stix/v2.1/os/stix-v2.1-os.html#_e8slinrhxcc9
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
: .
;
|
Update link to STIX Patterning documentation
|
Update link to STIX Patterning documentation
|
ANTLR
|
bsd-3-clause
|
oasis-open/cti-stix2-json-schemas
|
d1c59c3c120725680ee643c3b1ee144c92276018
|
css3/css3.g4
|
css3/css3.g4
|
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'))* ')'?
;
|
grammar css3;
stylesheet
: importRule* (nested | ruleset)+
;
importRule
: ('@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
|
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
|
7e243534f5398a9d6b59c8100bff21a80d2af94c
|
sharding-core/src/main/antlr4/imports/OracleKeyword.g4
|
sharding-core/src/main/antlr4/imports/OracleKeyword.g4
|
lexer grammar OracleKeyword;
import Symbol;
ADMIN
: A D M I N
;
AT
: A T
;
BATCH
: B A T C H
;
BITMAP
: B I T M A P
;
CACHE
: C A C H E
;
CASE
: C A S E
;
CHECKPOINT
: C H E C K P O I N T
;
COMMENT
: C O M M E N T
;
CONSTRAINTS
: C O N S T R A I N T S
;
CONTAINER
: C O N T A I N E R
;
CURRENT
: C U R R E N T
;
CYCLE
: C Y C L E
;
DAY
: D A Y
;
DBTIMEZONE
: D B T I M E Z O N E
;
DECRYPT
: D E C R Y P T
;
DEFERRABLE
: D E F E R R A B L E
;
DEFERRED
: D E F E R R E D
;
DELEGATE
: D E L E G A T E
;
DOUBLE
: D O U B L E
;
ELEMENT
: E L E M E N T
;
ELSE
: E L S E
;
ENCRYPT
: E N C R Y P T
;
END
: E N D
;
EXCEPTIONS
: E X C E P T I O N S
;
FOR
: F O R
;
FORCE
: F O R C E
;
FUNCTION
: F U N C T I O N
;
GLOBAL
: G L O B A L
;
GRANT
: G R A N T
;
IDENTIFIED
: I D E N T I F I E D
;
IDENTITY
: I D E N T I T Y
;
IMMEDIATE
: I M M E D I A T E
;
INCREMENT
: I N C R E M E N T
;
INITIALLY
: I N I T I A L L Y
;
INTERVAL
: I N T E R V A L
;
INTO
: I N T O
;
INVALIDATE
: I N V A L I D A T E
;
KEEP
: K E E P
;
LEVELS
: L E V E L S
;
LOCAL
: L O C A L
;
MAXVALUE
: M A X V A L U E
;
MINVALUE
: M I N V A L U E
;
MODIFY
: M O D I F Y
;
MONTH
: M O N T H
;
NAME
: N A M E
;
NATIONAL
: N A T I O N A L
;
NEW
: N E W
;
NOCACHE
: N O C A C H E
;
NOCYCLE
: N O C Y C L E
;
NOMAXVALUE
: N O M A X V A L U E
;
NOMINVALUE
: N O M I N V A L U E
;
NOORDER
: N O O R D E R
;
NORELY
: N O R E L Y
;
NOVALIDATE
: N O V A L I D A T E
;
NOWAIT
: N O W A I T
;
OF
: O F
;
ONLY
: O N L Y
;
OPTION
: O P T I O N
;
PACKAGE
: P A C K A G E
;
PRECISION
: P R E C I S I O N
;
PRESERVE
: P R E S E R V E
;
PRIOR
: P R I O R
;
PRIVILEGES
: P R I V I L E G E S
;
PROCEDURE
: P R O C E D U R E
;
PUBLIC
: P U B L I C
;
REF
: R E F
;
REKEY
: R E K E Y
;
RELY
: R E L Y
;
RENAME
: R E N A M E
;
ROWID
: R O W I D
;
ROWS
: R O W S
;
SALT
: S A L T
;
SAVEPOINT
: S A V E P O I N T
;
SCOPE
: S C O P E
;
SECOND
: S E C O N D
;
SEGMENT
: S E G M E N T
;
SORT
: S O R T
;
SQLRF
: S Q L R F
;
SUBSTITUTABLE
: S U B S T I T U T A B L E
;
TABLESPACE
: T A B L E S P A C E
;
TEMPORARY
: T E M P O R A R Y
;
THEN
: T H E N
;
TREAT
: T R E A T
;
TYPE
: T Y P E
;
UNUSED
: U N U S E D
;
USE
: U S E
;
USING
: U S I N G
;
VALIDATE
: V A L I D A T E
;
VALUE
: V A L U E
;
VARYING
: V A R Y I N G
;
VIRTUAL
: V I R T U A L
;
WAIT
: W A I T
;
WHEN
: W H E N
;
WRITE
: W R I T E
;
ZONE
: Z O N E
;
|
lexer grammar OracleKeyword;
import Symbol;
ADMIN
: A D M I N
;
AT
: A T
;
BATCH
: B A T C H
;
BITMAP
: B I T M A P
;
CACHE
: C A C H E
;
CASE
: C A S E
;
CHECKPOINT
: C H E C K P O I N T
;
COMMENT
: C O M M E N T
;
CONSTRAINTS
: C O N S T R A I N T S
;
CONTAINER
: C O N T A I N E R
;
CURRENT
: C U R R E N T
;
CYCLE
: C Y C L E
;
DAY
: D A Y
;
DBTIMEZONE
: D B T I M E Z O N E
;
DECRYPT
: D E C R Y P T
;
DEFERRABLE
: D E F E R R A B L E
;
DEFERRED
: D E F E R R E D
;
DELEGATE
: D E L E G A T E
;
DIRECTORY
: D I R E C T O R Y
;
DOUBLE
: D O U B L E
;
EDITION
: E D I T I O N
;
ELEMENT
: E L E M E N T
;
ELSE
: E L S E
;
ENCRYPT
: E N C R Y P T
;
END
: E N D
;
EXCEPTIONS
: E X C E P T I O N S
;
FOR
: F O R
;
FORCE
: F O R C E
;
FUNCTION
: F U N C T I O N
;
GLOBAL
: G L O B A L
;
GRANT
: G R A N T
;
HIERARCHY
: H I E R A R C H Y
;
IDENTIFIED
: I D E N T I F I E D
;
IDENTITY
: I D E N T I T Y
;
IMMEDIATE
: I M M E D I A T E
;
INCREMENT
: I N C R E M E N T
;
INITIALLY
: I N I T I A L L Y
;
INTERVAL
: I N T E R V A L
;
INTO
: I N T O
;
INVALIDATE
: I N V A L I D A T E
;
JAVA
: J A V A
;
KEEP
: K E E P
;
LEVELS
: L E V E L S
;
LOCAL
: L O C A L
;
MAXVALUE
: M A X V A L U E
;
MINING
: M I N I N G
;
MINVALUE
: M I N V A L U E
;
MODEL
: M O D E L
;
MODIFY
: M O D I F Y
;
MONTH
: M O N T H
;
NAME
: N A M E
;
NATIONAL
: N A T I O N A L
;
NEW
: N E W
;
NOCACHE
: N O C A C H E
;
NOCYCLE
: N O C Y C L E
;
NOMAXVALUE
: N O M A X V A L U E
;
NOMINVALUE
: N O M I N V A L U E
;
NOORDER
: N O O R D E R
;
NORELY
: N O R E L Y
;
NOVALIDATE
: N O V A L I D A T E
;
NOWAIT
: N O W A I T
;
OF
: O F
;
ONLY
: O N L Y
;
OPTION
: O P T I O N
;
PACKAGE
: P A C K A G E
;
PRECISION
: P R E C I S I O N
;
PRESERVE
: P R E S E R V E
;
PRIOR
: P R I O R
;
PRIVILEGES
: P R I V I L E G E S
;
PROCEDURE
: P R O C E D U R E
;
PROFILE
: P R O F I L E
;
PUBLIC
: P U B L I C
;
REF
: R E F
;
REKEY
: R E K E Y
;
RELY
: R E L Y
;
RENAME
: R E N A M E
;
RESOURCE
: R E S O U R C E
;
ROWID
: R O W I D
;
ROWS
: R O W S
;
SALT
: S A L T
;
SAVEPOINT
: S A V E P O I N T
;
SCOPE
: S C O P E
;
SECOND
: S E C O N D
;
SEGMENT
: S E G M E N T
;
SORT
: S O R T
;
SOURCE
: S O U R C E
;
SQL
: S Q L
;
SQLRF
: S Q L R F
;
SUBSTITUTABLE
: S U B S T I T U T A B L E
;
TABLESPACE
: T A B L E S P A C E
;
TEMPORARY
: T E M P O R A R Y
;
THEN
: T H E N
;
TRANSLATION
: T R A N S L A T I O N
;
TREAT
: T R E A T
;
TYPE
: T Y P E
;
UNUSED
: U N U S E D
;
USE
: U S E
;
USER
: U S E R
;
USING
: U S I N G
;
VALIDATE
: V A L I D A T E
;
VALUE
: V A L U E
;
VARYING
: V A R Y I N G
;
VIRTUAL
: V I R T U A L
;
WAIT
: W A I T
;
WHEN
: W H E N
;
WRITE
: W R I T E
;
ZONE
: Z O N E
;
|
add keyword
|
add keyword
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
|
6cb215d9bddf89619cb2980a492af610fdf4f47c
|
sharding-jdbc-ddl-parser/src/main/resources/io/shardingsphere/parser/antlr/MySQLKeyword.g4
|
sharding-jdbc-ddl-parser/src/main/resources/io/shardingsphere/parser/antlr/MySQLKeyword.g4
|
lexer grammar MySQLKeyword;
import Symbol;
FIRST: F I R S T;
AFTER: A F T E R;
SPATIAL: S P A T I A L;
ALGORITHM: A L G O R I T H M;
CHANGE: C H A N G E;
DISCARD: D I S C A R D;
CHARACTER: C H A R A C T E R;
COLLATE: C O L L A T E;
CONVERT: C O N V E R T;
SHARED: S H A R E D;
EXCLUSIVE: E X C L U S I V E;
REORGANIZE: R E O R G A N I Z E;
EXCHANGE: E X C H A N G E;
BTREE: B T R E E;
HASH: H A S H;
KEY_BLOCK_SIZE: K E Y UL_ B L O C K UL_ S I Z E;
PARSER: P A R S E R;
COMMENT: C O M M E N T;
AUTO_INCREMENT: A U T O UL_ I N C R E M E N T;
AVG_ROW_LENGTH: A V G UL_ R O W UL_ L E N G T H;
CHECKSUM: C H E C K S U M;
COMPRESSION: C O M P R E S S I O N;
ZLIB: Z L I B;
LZ: L Z;
CONNECTION: C O N N E C T I O N;
DATA: D A T A;
DIRECTORY: D I R E C T O R Y;
DELAY_KEY_WRITE: D E L A Y UL_ K E Y UL_ W R I T E;
ENCRYPTION: E N C R Y P T I O N;
ENGINE: E N G I N E;
INSERT_METHOD: I N S E R T UL_ M E T H O D;
NO: N O;
LAST: L A S T;
MAX_ROWS: M A X UL_ R O W S;
MIN_ROWS: M I N UL_ R O W S;
PACK_KEYS: P A C K UL_ K E Y S;
PASSWORD: P A S S W O R D;
ROW_FORMAT: R O W UL_ F O R M A T;
DYNAMIC: D Y N A M I C;
FIXED: F I X E D;
COMPRESSED: C O M P R E S S E D;
REDUNDANT: R E D U N D A N T;
COMPACT: C O M P A C T;
STATS_AUTO_RECALC: S T A T S UL_ A U T O UL_ R E C A L C;
STATS_PERSISTENT: S T A T S UL_ P E R S I S T E N T;
STATS_SAMPLE_PAGES: S T A T S UL_ S A M P L E UL_ P A G E S;
STORAGE: S T O R A G E;
DISK: D I S K;
MEMORY: M E M O R Y;
PARTITIONING: P A R T I T I O N I N G;
GENERATED: G E N E R A T E D;
ALWAYS: A L W A Y S;
COLUMN_FORMAT: C O L U M N UL_ F O R M A T;
VIRTUAL: V I R T U A L;
STORED: S T O R E D;
INPLACE: I N P L A C E;
SUBPARTITION: S U B P A R T I T I O N;
MAXVALUE: M A X V A L U E;
LESS: L E S S;
THAN: T H A N;
DISTINCTROW: D I S T I N C T R O W;
HIGH_PRIORITY: H I G H UL_ P R I O R I T Y;
STRAIGHT_JOIN: S T R A I G H T UL_ J O I N;
SQL_SMALL_RESULT: S Q L UL_ S M A L L UL_ R E S U L T;
SQL_BIG_RESULT: S Q L UL_ B I G UL_ R E S U L T;
SQL_BUFFER_RESULT: S Q L UL_ B U F F E R UL_ R E S U L T;
SQL_CACHE: S Q L UL_ C A C H E;
SQL_NO_CACHE: S Q L UL_ N O UL_ C A C H E;
SQL_CALC_FOUND_ROWS: S Q L UL_ C A L C UL_ F O U N D UL_ R O W S;
REFERENCES: R E F E R E N C E S;
MATCH: M A T C H;
FULL: F U L L;
PARTIAL: P A R T I A L;
SIMPLE: S I M P L E;
RESTRICT: R E S T R I C T;
CASCADE: C A S C A D E ;
ACTION: A C T I O N;
LINEAR: L I N E A R;
COLUMNS: C O L U M N S;
RANGE: R A N G E;
LIST: L I S T;
PARTITIONS: P A R T I T I O N S;
SUBPARTITIONS: S U B P A R T I T I O N S;
OUTFILE: O U T F I L E;
DUMPFILE: D U M P F I L E;
SKIP_: S K I P;
OJ: O J;
LOW_PRIORITY: L O W UL_ P R I O R I T Y;
DELAYED: D E L A Y E D;
|
lexer grammar MySQLKeyword;
import Symbol;
FIRST: F I R S T;
AFTER: A F T E R;
SPATIAL: S P A T I A L;
ALGORITHM: A L G O R I T H M;
CHANGE: C H A N G E;
DISCARD: D I S C A R D;
CHARACTER: C H A R A C T E R;
COLLATE: C O L L A T E;
CONVERT: C O N V E R T;
SHARED: S H A R E D;
EXCLUSIVE: E X C L U S I V E;
REORGANIZE: R E O R G A N I Z E;
EXCHANGE: E X C H A N G E;
BTREE: B T R E E;
HASH: H A S H;
KEY_BLOCK_SIZE: K E Y UL_ B L O C K UL_ S I Z E;
PARSER: P A R S E R;
COMMENT: C O M M E N T;
AUTO_INCREMENT: A U T O UL_ I N C R E M E N T;
AVG_ROW_LENGTH: A V G UL_ R O W UL_ L E N G T H;
CHECKSUM: C H E C K S U M;
COMPRESSION: C O M P R E S S I O N;
ZLIB: Z L I B;
LZ: L Z;
CONNECTION: C O N N E C T I O N;
DATA: D A T A;
DIRECTORY: D I R E C T O R Y;
DELAY_KEY_WRITE: D E L A Y UL_ K E Y UL_ W R I T E;
ENCRYPTION: E N C R Y P T I O N;
ENGINE: E N G I N E;
INSERT_METHOD: I N S E R T UL_ M E T H O D;
NO: N O;
LAST: L A S T;
MAX_ROWS: M A X UL_ R O W S;
MIN_ROWS: M I N UL_ R O W S;
PACK_KEYS: P A C K UL_ K E Y S;
PASSWORD: P A S S W O R D;
ROW_FORMAT: R O W UL_ F O R M A T;
DYNAMIC: D Y N A M I C;
FIXED: F I X E D;
COMPRESSED: C O M P R E S S E D;
REDUNDANT: R E D U N D A N T;
COMPACT: C O M P A C T;
STATS_AUTO_RECALC: S T A T S UL_ A U T O UL_ R E C A L C;
STATS_PERSISTENT: S T A T S UL_ P E R S I S T E N T;
STATS_SAMPLE_PAGES: S T A T S UL_ S A M P L E UL_ P A G E S;
STORAGE: S T O R A G E;
DISK: D I S K;
MEMORY: M E M O R Y;
PARTITIONING: P A R T I T I O N I N G;
GENERATED: G E N E R A T E D;
ALWAYS: A L W A Y S;
COLUMN_FORMAT: C O L U M N UL_ F O R M A T;
VIRTUAL: V I R T U A L;
STORED: S T O R E D;
INPLACE: I N P L A C E;
SUBPARTITION: S U B P A R T I T I O N;
MAXVALUE: M A X V A L U E;
LESS: L E S S;
THAN: T H A N;
DISTINCTROW: D I S T I N C T R O W;
HIGH_PRIORITY: H I G H UL_ P R I O R I T Y;
STRAIGHT_JOIN: S T R A I G H T UL_ J O I N;
SQL_SMALL_RESULT: S Q L UL_ S M A L L UL_ R E S U L T;
SQL_BIG_RESULT: S Q L UL_ B I G UL_ R E S U L T;
SQL_BUFFER_RESULT: S Q L UL_ B U F F E R UL_ R E S U L T;
SQL_CACHE: S Q L UL_ C A C H E;
SQL_NO_CACHE: S Q L UL_ N O UL_ C A C H E;
SQL_CALC_FOUND_ROWS: S Q L UL_ C A L C UL_ F O U N D UL_ R O W S;
REFERENCES: R E F E R E N C E S;
MATCH: M A T C H;
FULL: F U L L;
PARTIAL: P A R T I A L;
SIMPLE: S I M P L E;
RESTRICT: R E S T R I C T;
CASCADE: C A S C A D E ;
ACTION: A C T I O N;
LINEAR: L I N E A R;
COLUMNS: C O L U M N S;
RANGE: R A N G E;
LIST: L I S T;
PARTITIONS: P A R T I T I O N S;
SUBPARTITIONS: S U B P A R T I T I O N S;
UNSIGNED: U N S I G N E D;
ZEROFILL: Z E R O F I L L;
OUTFILE: O U T F I L E;
DUMPFILE: D U M P F I L E;
SKIP_: S K I P;
OJ: O J;
LOW_PRIORITY: L O W UL_ P R I O R I T Y;
DELAYED: D E L A Y E D;
|
add mysql keyword
|
add mysql keyword
|
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
|
a49f29822fa170efb6ec0c5069123e3fe0cb192e
|
src/main/antlr/GraphqlCommon.g4
|
src/main/antlr/GraphqlCommon.g4
|
grammar GraphqlCommon;
operationType : SUBSCRIPTION | MUTATION | QUERY;
description : stringValue;
enumValue : enumValueName ;
arrayValue: '[' value* ']';
arrayValueWithVariable: '[' valueWithVariable* ']';
objectValue: '{' objectField* '}';
objectValueWithVariable: '{' objectFieldWithVariable* '}';
objectField : name ':' value;
objectFieldWithVariable : name ':' valueWithVariable;
directives : directive+;
directive :'@' name arguments?;
arguments : '(' argument+ ')';
argument : name ':' valueWithVariable;
baseName: NAME | FRAGMENT | QUERY | MUTATION | SUBSCRIPTION | SCHEMA | SCALAR | TYPE | INTERFACE | IMPLEMENTS | ENUM | UNION | INPUT | EXTEND | DIRECTIVE;
fragmentName: baseName | BooleanValue | NullValue;
enumValueName: baseName | ON_KEYWORD;
name: baseName | BooleanValue | NullValue | ON_KEYWORD;
value :
stringValue |
IntValue |
FloatValue |
BooleanValue |
NullValue |
enumValue |
arrayValue |
objectValue;
valueWithVariable :
variable |
stringValue |
IntValue |
FloatValue |
BooleanValue |
NullValue |
enumValue |
arrayValueWithVariable |
objectValueWithVariable;
variable : '$' name;
defaultValue : '=' value;
stringValue
: TripleQuotedStringValue
| StringValue
;
type : typeName | listType | nonNullType;
typeName : name;
listType : '[' type ']';
nonNullType: typeName '!' | listType '!';
BooleanValue: 'true' | 'false';
NullValue: 'null';
FRAGMENT: 'fragment';
QUERY: 'query';
MUTATION: 'mutation';
SUBSCRIPTION: 'subscription';
SCHEMA: 'schema';
SCALAR: 'scalar';
TYPE: 'type';
INTERFACE: 'interface';
IMPLEMENTS: 'implements';
ENUM: 'enum';
UNION: 'union';
INPUT: 'input';
EXTEND: 'extend';
DIRECTIVE: 'directive';
ON_KEYWORD: 'on';
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') ('+'|'-')? Digit+;
Digit : '0'..'9';
StringValue
: '"' ( ~["\\\n\r\u2028\u2029] | EscapedChar )* '"'
;
TripleQuotedStringValue
: '"""' TripleQuotedStringPart? '"""'
;
// Fragments never become a token of their own: they are only used inside other lexer rules
fragment TripleQuotedStringPart : ( EscapedTripleQuote | ExtendedSourceCharacter )+?;
fragment EscapedTripleQuote : '\\"""';
// this is currently not covered by the spec because we allow all unicode chars
// u0009 = \t Horizontal tab
// u000a = \n line feed
// u000d = \r carriage return
// u0020 = space
fragment ExtendedSourceCharacter :[\u0009\u000A\u000D\u0020-\u{10FFFF}];
fragment ExtendedSourceCharacterWitoutLineFeed :[\u0009\u0020-\u{10FFFF}];
// this is the spec definition
// fragment SourceCharacter :[\u0009\u000A\u000D\u0020-\uFFFF];
Comment: '#' ExtendedSourceCharacterWitoutLineFeed* -> channel(2);
fragment EscapedChar : '\\' (["\\/bfnrt] | Unicode) ;
fragment Unicode : 'u' Hex Hex Hex Hex ;
fragment Hex : [0-9a-fA-F] ;
LF: [\n] -> channel(3);
CR: [\r] -> channel(3);
LineTerminator: [\u2028\u2029] -> channel(3);
Space : [\u0020] -> channel(3);
Tab : [\u0009] -> channel(3);
Comma : ',' -> channel(3);
UnicodeBOM : [\ufeff] -> channel(3);
|
grammar GraphqlCommon;
operationType : SUBSCRIPTION | MUTATION | QUERY;
description : stringValue;
enumValue : enumValueName ;
arrayValue: '[' value* ']';
arrayValueWithVariable: '[' valueWithVariable* ']';
objectValue: '{' objectField* '}';
objectValueWithVariable: '{' objectFieldWithVariable* '}';
objectField : name ':' value;
objectFieldWithVariable : name ':' valueWithVariable;
directives : directive+;
directive :'@' name arguments?;
arguments : '(' argument+ ')';
argument : name ':' valueWithVariable;
baseName: NAME | FRAGMENT | QUERY | MUTATION | SUBSCRIPTION | SCHEMA | SCALAR | TYPE | INTERFACE | IMPLEMENTS | ENUM | UNION | INPUT | EXTEND | DIRECTIVE;
fragmentName: baseName | BooleanValue | NullValue;
enumValueName: baseName | ON_KEYWORD;
name: baseName | BooleanValue | NullValue | ON_KEYWORD;
value :
stringValue |
IntValue |
FloatValue |
BooleanValue |
NullValue |
enumValue |
arrayValue |
objectValue;
valueWithVariable :
variable |
stringValue |
IntValue |
FloatValue |
BooleanValue |
NullValue |
enumValue |
arrayValueWithVariable |
objectValueWithVariable;
variable : '$' name;
defaultValue : '=' value;
stringValue
: TripleQuotedStringValue
| StringValue
;
type : typeName | listType | nonNullType;
typeName : name;
listType : '[' type ']';
nonNullType: typeName '!' | listType '!';
BooleanValue: 'true' | 'false';
NullValue: 'null';
FRAGMENT: 'fragment';
QUERY: 'query';
MUTATION: 'mutation';
SUBSCRIPTION: 'subscription';
SCHEMA: 'schema';
SCALAR: 'scalar';
TYPE: 'type';
INTERFACE: 'interface';
IMPLEMENTS: 'implements';
ENUM: 'enum';
UNION: 'union';
INPUT: 'input';
EXTEND: 'extend';
DIRECTIVE: 'directive';
ON_KEYWORD: 'on';
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') ('+'|'-')? Digit+;
Digit : '0'..'9';
StringValue
: '"' ( ~["\\\n\r\u2028\u2029] | EscapedChar )* '"'
;
TripleQuotedStringValue
: '"""' TripleQuotedStringPart? '"""'
;
// Fragments never become a token of their own: they are only used inside other lexer rules
fragment TripleQuotedStringPart : ( EscapedTripleQuote | ExtendedSourceCharacter )+?;
fragment EscapedTripleQuote : '\\"""';
// this is currently not covered by the spec because we allow all unicode chars
// u0009 = \t Horizontal tab
// u000a = \n line feed
// u000d = \r carriage return
// u0020 = space
fragment ExtendedSourceCharacter :[\u0009\u000A\u000D\u0020-\u{10FFFF}];
fragment ExtendedSourceCharacterWithoutLineFeed :[\u0009\u0020-\u{10FFFF}];
// this is the spec definition
// fragment SourceCharacter :[\u0009\u000A\u000D\u0020-\uFFFF];
Comment: '#' ExtendedSourceCharacterWithoutLineFeed* -> channel(2);
fragment EscapedChar : '\\' (["\\/bfnrt] | Unicode) ;
fragment Unicode : 'u' Hex Hex Hex Hex ;
fragment Hex : [0-9a-fA-F] ;
LF: [\n] -> channel(3);
CR: [\r] -> channel(3);
LineTerminator: [\u2028\u2029] -> channel(3);
Space : [\u0020] -> channel(3);
Tab : [\u0009] -> channel(3);
Comma : ',' -> channel(3);
UnicodeBOM : [\ufeff] -> channel(3);
|
fix typo
|
fix typo
|
ANTLR
|
mit
|
graphql-java/graphql-java,graphql-java/graphql-java
|
b20fb4c4872d4f8981164fe70b2ea54ebec676c3
|
sharding-core/sharding-core-parse/sharding-core-parse-oracle/src/main/antlr4/imports/oracle/DCLStatement.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-oracle/src/main/antlr4/imports/oracle/DCLStatement.g4
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DCLStatement;
import Symbol, Keyword, Literals, BaseRule;
grant
: GRANT (objectPrivileges_ (ON onObjectClause_)? | otherPrivileges_)
;
revoke
: REVOKE (objectPrivileges_ (ON onObjectClause_)? | otherPrivileges_)
;
objectPrivileges_
: objectPrivilegeType_ columnNames? (COMMA_ objectPrivilegeType_ columnNames?)*
;
objectPrivilegeType_
: ALL PRIVILEGES?
| SELECT
| INSERT
| DELETE
| UPDATE
| ALTER
| READ
| WRITE
| EXECUTE
| USE
| INDEX
| REFERENCES
| DEBUG
| UNDER
| FLASHBACK ARCHIVE
| ON COMMIT REFRESH
| QUERY REWRITE
| KEEP SEQUENCE
| INHERIT PRIVILEGES
| TRANSLATE SQL
| MERGE VIEW
;
onObjectClause_
: USER | DIRECTORY | EDITION | MINING MODEL | SQL TRANSLATION PROFILE
| JAVA (SOURCE | RESOURCE) tableName
| tableName
;
otherPrivileges_
: STRING_+ | IDENTIFIER_+
;
createUser
: CREATE USER
;
dropUser
: DROP USER
;
alterUser
: ALTER USER
;
createRole
: CREATE ROLE
;
dropRole
: DROP ROLE
;
alterRole
: ALTER ROLE
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DCLStatement;
import Symbol, Keyword, Literals, BaseRule;
grant
: GRANT (objectPrivilegeClause_ | systemPrivilegeClause_ | roleClause_)
;
revoke
: REVOKE (objectPrivilegeClause_ | systemPrivilegeClause_ | roleClause_)
;
objectPrivilegeClause_
: objectPrivileges_ ON onObjectClause_
;
systemPrivilegeClause_
: systemPrivilege_
;
roleClause_
: ignoredIdentifiers_
;
objectPrivileges_
: objectPrivilegeType_ columnNames? (COMMA_ objectPrivilegeType_ columnNames?)*
;
objectPrivilegeType_
: ALL PRIVILEGES?
| SELECT
| INSERT
| DELETE
| UPDATE
| ALTER
| READ
| WRITE
| EXECUTE
| USE
| INDEX
| REFERENCES
| DEBUG
| UNDER
| FLASHBACK ARCHIVE
| ON COMMIT REFRESH
| QUERY REWRITE
| KEEP SEQUENCE
| INHERIT PRIVILEGES
| TRANSLATE SQL
| MERGE VIEW
;
onObjectClause_
: USER | DIRECTORY | EDITION | MINING MODEL | SQL TRANSLATION PROFILE
| JAVA (SOURCE | RESOURCE) tableName
| tableName
;
systemPrivilege_
: ALL PRIVILEGES
| ignoredIdentifiers_
;
createUser
: CREATE USER
;
dropUser
: DROP USER
;
alterUser
: ALTER USER
;
createRole
: CREATE ROLE
;
dropRole
: DROP ROLE
;
alterRole
: ALTER ROLE
;
|
modify dcl for oracle
|
modify dcl for oracle
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
bc859c6c9101c348704a60780020d6927106e4e4
|
sparkle-V4/sparkle-pretty-printer/src/main/antlr4/com/googlecode/sparkleg/SparqlParser.g4
|
sparkle-V4/sparkle-pretty-printer/src/main/antlr4/com/googlecode/sparkleg/SparqlParser.g4
|
/*
* Copyright 2007-2012 The sparkle-g Team
*
* 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.
*/
/**
* @author Simone Tripodi (simone.tripodi)
* @author Michele Mostarda (michele.mostarda)
* @author Juergen Pfundt (Juergen.Pfundt)
* @version $Id: Sparql.g 523 2012-02-17 23:10:57Z [email protected] $
*/
parser grammar SparqlParser;
options{
tokenVocab=SparqlLexer;
}
// $<Parser
query
: prologue (selectQuery | constructQuery | describeQuery | askQuery) valuesClause EOF
| updateCommand EOF
;
prologue
: (baseDecl | prefixDecl)*
;
baseDecl
: BASE IRIREF
;
prefixDecl
: PREFIX PNAME_NS IRIREF
;
selectQuery
: selectClause datasetClause* whereClause solutionModifier
;
subSelect
: selectClause whereClause solutionModifier valuesClause
;
selectClause
: SELECT (DISTINCT | REDUCED)? (selectVariables+ | '*')
;
selectVariables
: var
| '(' expression AS var ')'
;
constructQuery
: CONSTRUCT (constructTemplate datasetClause* whereClause solutionModifier | datasetClause* WHERE '{' triplesTemplate? '}' solutionModifier)
;
describeQuery
: DESCRIBE (varOrIRI+ | '*') datasetClause* whereClause? solutionModifier
;
askQuery
: ASK datasetClause* whereClause solutionModifier
;
datasetClause
: FROM NAMED? iri
;
whereClause
: WHERE? groupGraphPattern
;
solutionModifier
: groupClause? havingClause? orderClause? limitOffsetClauses?
;
groupClause
: GROUP BY groupCondition+
;
groupCondition
: builtInCall | functionCall | '(' expression (AS var)? ')' | var
;
havingClause
: HAVING havingCondition+
;
havingCondition
: constraint
;
orderClause
: ORDER BY orderCondition+
;
orderCondition
: (ASC|DESC) '(' expression ')'
| constraint
| var
;
limitOffsetClauses
: limitClause offsetClause? | offsetClause limitClause?
;
limitClause
: LIMIT INTEGER
;
offsetClause
: OFFSET INTEGER
;
valuesClause
: (VALUES dataBlock)?
;
updateCommand
: prologue (update (';' updateCommand)?)?
;
update
: load | clear | drop | add | move | copy | create | insertData | deleteData | deleteWhere | modify
;
load
: LOAD SILENT? iri (INTO graphRef)?
;
clear
: CLEAR SILENT? graphRefAll
;
drop
: DROP SILENT? graphRefAll
;
create
: CREATE SILENT? graphRef
;
add
: ADD SILENT? graphOrDefault TO graphOrDefault
;
move
: MOVE SILENT? graphOrDefault TO graphOrDefault
;
copy
: COPY SILENT? graphOrDefault TO graphOrDefault
;
insertData
: INSERT DATA quadData
;
deleteData
: DELETE DATA quadData
;
deleteWhere
: DELETE WHERE quadPattern
;
modify
: (WITH iri)? (deleteClause insertClause? | insertClause) usingClause* WHERE groupGraphPattern
;
deleteClause
: DELETE quadPattern
;
insertClause
: INSERT quadPattern
;
usingClause
: USING NAMED? iri
;
graphOrDefault
: DEFAULT | GRAPH? iri
;
graphRef
: GRAPH iri
;
graphRefAll
: graphRef | DEFAULT | NAMED | ALL
;
quadPattern
: '{' quads '}'
;
quadData
: '{' quads '}'
;
quads
: triplesTemplate? quadsDetails*
;
quadsDetails
: quadsNotTriples '.'? triplesTemplate?
;
quadsNotTriples
: GRAPH varOrIRI '{' triplesTemplate? '}'
;
triplesTemplate
: triplesSameSubject ('.' triplesSameSubject?)*
;
groupGraphPattern
: '{' (subSelect | groupGraphPatternSub) '}'
;
groupGraphPatternSub
: triplesBlock? groupGraphPatternSubList*
;
groupGraphPatternSubList
: graphPatternNotTriples '.'? triplesBlock?
;
triplesBlock
: triplesSameSubjectPath ('.' triplesSameSubjectPath?)*
;
graphPatternNotTriples
: groupOrUnionGraphPattern | optionalGraphPattern | minusGraphPattern | graphGraphPattern | serviceGraphPattern | filter | bind | inlineData
;
optionalGraphPattern
: OPTIONAL groupGraphPattern
;
graphGraphPattern
: GRAPH varOrIRI groupGraphPattern
;
serviceGraphPattern
: SERVICE SILENT? varOrIRI groupGraphPattern
;
bind
: BIND '(' expression AS var ')'
;
inlineData
: VALUES dataBlock
;
dataBlock
: inlineDataOneVar | inlineDataFull
;
inlineDataOneVar
: var '{' dataBlockValue* '}'
;
inlineDataFull
: '(' var* ')' '{' dataBlockValues* '}'
;
dataBlockValues
: '(' dataBlockValue* ')'
;
dataBlockValue
: iri | rdfLiteral | numericLiteral | booleanLiteral | UNDEF
;
minusGraphPattern
: MINUS groupGraphPattern
;
groupOrUnionGraphPattern
: groupGraphPattern (UNION groupGraphPattern)*
;
filter
: FILTER constraint
;
constraint
: '(' expression ')' | builtInCall | functionCall
;
functionCall
: iri argList
;
argList
: '(' (DISTINCT? expressionList|) ')'
;
expressionList
: expression (',' expression)*
;
constructTemplate
: '{' constructTriples? '}'
;
constructTriples
: triplesSameSubject ('.' constructTriples?)*
;
triplesSameSubject
: varOrTerm propertyListNotEmpty | triplesNode propertyList
;
propertyList
: propertyListNotEmpty?
;
propertyListNotEmpty
: verb objectList (';' (verb objectList)?)*
;
verb
: varOrIRI | A
;
objectList
: object (',' object)*
;
object
: graphNode
;
triplesSameSubjectPath
: varOrTerm propertyListPathNotEmpty | triplesNodePath propertyListPath
;
propertyListPath
: propertyListPathNotEmpty?
;
propertyListPathNotEmpty
: (verbPath|verbSimple) objectListPath (';' propertyListPathNotEmptyList?)*
;
propertyListPathNotEmptyList
: (verbPath|verbSimple) objectList
;
verbPath
: path
;
verbSimple
: var
;
objectListPath
: objectPath (',' objectPath)*
;
objectPath
: graphNodePath
;
path
: pathAlternative
;
pathAlternative
: pathSequence ('|' pathSequence)*
;
pathSequence
: pathEltOrInverse ('/' pathEltOrInverse)*
;
pathElt
: pathPrimary pathMod?
;
pathEltOrInverse
: INVERSE? pathElt
;
pathMod
: QUESTION_MARK | ASTERISK | PLUS_SIGN
;
pathPrimary
: iri | A | '!' pathNegatedPropertySet | '(' path ')'
;
pathNegatedPropertySet
: pathOneInPropertySet | '(' (pathOneInPropertySet ('|' pathOneInPropertySet)*)? ')'
;
pathOneInPropertySet
: INVERSE? (iri | A)
;
integer
: INTEGER
;
triplesNode
: collection | blankNodePropertyList
;
blankNodePropertyList
: '[' propertyListNotEmpty ']'
;
triplesNodePath
: collectionPath | blankNodePropertyListPath
;
blankNodePropertyListPath
: '[' propertyListPathNotEmpty ']'
;
collection
: '(' graphNode+ ')'
;
collectionPath
: '(' graphNodePath+ ')'
;
graphNode
: varOrTerm | triplesNode
;
graphNodePath
: varOrTerm | triplesNodePath
;
varOrTerm
: var | graphTerm
;
varOrIRI
: var | iri
;
var
: VAR1 | VAR2
;
graphTerm
: iri | rdfLiteral | numericLiteral | booleanLiteral | blankNode | nil
;
nil
: '(' ')'
;
/* ANTLR V4 branded expressions */
expression
: primaryExpression # baseExpression
| op=('*'|'/') expression # unaryMultiplicativeExpression
| op=('+'|'-') expression # unaryAdditiveExpression
| '!' expression # unaryNegationExpression
| expression op=('*'|'/') expression # multiplicativeExpression
| expression op=('+'|'-') expression # additiveExpression
| expression unaryLiteralExpression # unarySignedLiteralExpression
| expression NOT? IN '(' expressionList? ')' # relationalSetExpression
| expression op=('='|'!='|'<'|'>'|'<='|'>=') expression # relationalExpression
| expression ('&&' expression) # conditionalAndExpression
| expression ('||' expression) # conditionalOrExpression
;
unaryLiteralExpression
: (numericLiteralPositive|numericLiteralNegative) (op=('*'|'/') unaryExpression)?
;
unaryExpression
: op=('!'|'+'|'-')? primaryExpression
;
primaryExpression
: '(' expression ')' | builtInCall | iriRefOrFunction | rdfLiteral | numericLiteral | booleanLiteral | var
;
builtInCall
: aggregate
| STR '(' expression ')'
| LANG '(' expression ')'
| LANGMATCHES '(' expression ',' expression ')'
| DATATYPE '(' expression ')'
| BOUND '(' var ')'
| IRI '(' expression ')'
| URI '(' expression ')'
| BNODE '(' expression? ')'
| RAND '(' ')'
| ABS '(' expression ')'
| CEIL '(' expression ')'
| FLOOR '(' expression ')'
| ROUND '(' expression ')'
| CONCAT '(' expressionList? ')'
| subStringExpression
| STRLEN '(' expression ')'
| strReplaceExpression
| UCASE '(' expression ')'
| LCASE '(' expression ')'
| ENCODE_FOR_URI '(' expression ')'
| CONTAINS '(' expression ',' expression ')'
| STRSTARTS '(' expression ',' expression ')'
| STRENDS '(' expression ',' expression ')'
| STRBEFORE '(' expression ',' expression ')'
| STRAFTER '(' expression ',' expression ')'
| YEAR '(' expression ')'
| MONTH '(' expression ')'
| DAY '(' expression ')'
| HOURS '(' expression ')'
| MINUTES '(' expression ')'
| SECONDS '(' expression ')'
| TIMEZONE '(' expression ')'
| TZ '(' expression ')'
| NOW '(' ')'
| UUID '(' ')'
| STRUUID '(' ')'
| MD5 '(' expression ')'
| SHA1 '(' expression ')'
| SHA256 '(' expression ')'
| SHA384 '(' expression ')'
| SHA512 '(' expression ')'
| COALESCE '(' expressionList? ')'
| IF '(' expression ',' expression ',' expression ')'
| STRLANG '(' expression ',' expression ')'
| STRDT '(' expression ',' expression ')'
| SAMETERM '(' expression ',' expression ')'
| ISIRI '(' expression ')'
| ISURI '(' expression ')'
| ISBLANK '(' expression ')'
| ISLITERAL '(' expression ')'
| ISNUMERIC '(' expression ')'
| regexExpression
| existsFunction
| notExistsFunction
;
regexExpression
: REGEX '(' expression ',' expression (',' expression)? ')'
;
subStringExpression
: SUBSTR '(' expression ',' expression (',' expression)? ')'
;
strReplaceExpression
: REPLACE '(' expression ',' expression ',' expression (',' expression)? ')'
;
existsFunction
: EXISTS groupGraphPattern
;
notExistsFunction
: NOT EXISTS groupGraphPattern
;
aggregate
: COUNT '(' DISTINCT? (ASTERISK | expression) ')'
| SUM '(' DISTINCT? expression ')'
| MIN '(' DISTINCT? expression ')'
| MAX '(' DISTINCT? expression ')'
| AVG '(' DISTINCT? expression ')'
| SAMPLE '(' DISTINCT? expression ')'
| GROUP_CONCAT '(' DISTINCT? expression (';' SEPARATOR '=' string)? ')'
;
iriRefOrFunction
: iri argList?
;
rdfLiteral
: string (LANGTAG | ('^^' iri))?
;
numericLiteral
: numericLiteralUnsigned | numericLiteralPositive | numericLiteralNegative
;
numericLiteralUnsigned
: INTEGER | DECIMAL | DOUBLE
;
numericLiteralPositive
: INTEGER_POSITIVE | DECIMAL_POSITIVE | DOUBLE_POSITIVE
;
numericLiteralNegative
: INTEGER_NEGATIVE | DECIMAL_NEGATIVE | DOUBLE_NEGATIVE
;
booleanLiteral
: TRUE | FALSE
;
string
: STRING_LITERAL1 | STRING_LITERAL2 | STRING_LITERAL_LONG1 | STRING_LITERAL_LONG2
;
iri
: IRIREF | prefixedName
;
prefixedName
: PNAME_LN | PNAME_NS
;
blankNode
: BLANK_NODE_LABEL | anon
;
anon
: '[' ']'
;
// $>
|
/*
* Copyright 2007-2012 The sparkle-g Team
*
* 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.
*/
/**
* @author Simone Tripodi (simone.tripodi)
* @author Michele Mostarda (michele.mostarda)
* @author Juergen Pfundt (Juergen.Pfundt)
* @version $Id: Sparql.g 523 2012-02-17 23:10:57Z [email protected] $
*/
parser grammar SparqlParser;
options{
tokenVocab=SparqlLexer;
}
// $<Parser
query
: prologue (selectQuery | constructQuery | describeQuery | askQuery)? valuesClause EOF
| updateCommand EOF
;
prologue
: (baseDecl | prefixDecl)*
;
baseDecl
: BASE IRIREF
;
prefixDecl
: PREFIX PNAME_NS IRIREF
;
selectQuery
: selectClause datasetClause* whereClause solutionModifier
;
subSelect
: selectClause whereClause solutionModifier valuesClause
;
selectClause
: SELECT (DISTINCT | REDUCED)? (selectVariables+ | '*')
;
selectVariables
: var
| '(' expression AS var ')'
;
constructQuery
: CONSTRUCT (constructTemplate datasetClause* whereClause solutionModifier | datasetClause* WHERE '{' triplesTemplate? '}' solutionModifier)
;
describeQuery
: DESCRIBE (varOrIRI+ | '*') datasetClause* whereClause? solutionModifier
;
askQuery
: ASK datasetClause* whereClause solutionModifier
;
datasetClause
: FROM NAMED? iri
;
whereClause
: WHERE? groupGraphPattern
;
solutionModifier
: groupClause? havingClause? orderClause? limitOffsetClauses?
;
groupClause
: GROUP BY groupCondition+
;
groupCondition
: builtInCall | functionCall | '(' expression (AS var)? ')' | var
;
havingClause
: HAVING havingCondition+
;
havingCondition
: constraint
;
orderClause
: ORDER BY orderCondition+
;
orderCondition
: (ASC|DESC) '(' expression ')'
| constraint
| var
;
limitOffsetClauses
: limitClause offsetClause? | offsetClause limitClause?
;
limitClause
: LIMIT INTEGER
;
offsetClause
: OFFSET INTEGER
;
valuesClause
: (VALUES dataBlock)?
;
updateCommand
: prologue (update (';' updateCommand)?)?
;
update
: load | clear | drop | add | move | copy | create | insertData | deleteData | deleteWhere | modify
;
load
: LOAD SILENT? iri (INTO graphRef)?
;
clear
: CLEAR SILENT? graphRefAll
;
drop
: DROP SILENT? graphRefAll
;
create
: CREATE SILENT? graphRef
;
add
: ADD SILENT? graphOrDefault TO graphOrDefault
;
move
: MOVE SILENT? graphOrDefault TO graphOrDefault
;
copy
: COPY SILENT? graphOrDefault TO graphOrDefault
;
insertData
: INSERT DATA quadData
;
deleteData
: DELETE DATA quadData
;
deleteWhere
: DELETE WHERE quadPattern
;
modify
: (WITH iri)? (deleteClause insertClause? | insertClause) usingClause* WHERE groupGraphPattern
;
deleteClause
: DELETE quadPattern
;
insertClause
: INSERT quadPattern
;
usingClause
: USING NAMED? iri
;
graphOrDefault
: DEFAULT | GRAPH? iri
;
graphRef
: GRAPH iri
;
graphRefAll
: graphRef | DEFAULT | NAMED | ALL
;
quadPattern
: '{' quads '}'
;
quadData
: '{' quads '}'
;
quads
: triplesTemplate? quadsDetails*
;
quadsDetails
: quadsNotTriples '.'? triplesTemplate?
;
quadsNotTriples
: GRAPH varOrIRI '{' triplesTemplate? '}'
;
triplesTemplate
: triplesSameSubject ('.' triplesSameSubject?)*
;
groupGraphPattern
: '{' (subSelect | groupGraphPatternSub) '}'
;
groupGraphPatternSub
: triplesBlock? groupGraphPatternSubList*
;
groupGraphPatternSubList
: graphPatternNotTriples '.'? triplesBlock?
;
triplesBlock
: triplesSameSubjectPath ('.' triplesSameSubjectPath?)*
;
graphPatternNotTriples
: groupOrUnionGraphPattern | optionalGraphPattern | minusGraphPattern | graphGraphPattern | serviceGraphPattern | filter | bind | inlineData
;
optionalGraphPattern
: OPTIONAL groupGraphPattern
;
graphGraphPattern
: GRAPH varOrIRI groupGraphPattern
;
serviceGraphPattern
: SERVICE SILENT? varOrIRI groupGraphPattern
;
bind
: BIND '(' expression AS var ')'
;
inlineData
: VALUES dataBlock
;
dataBlock
: inlineDataOneVar | inlineDataFull
;
inlineDataOneVar
: var '{' dataBlockValue* '}'
;
inlineDataFull
: '(' var* ')' '{' dataBlockValues* '}'
;
dataBlockValues
: '(' dataBlockValue* ')'
;
dataBlockValue
: iri | rdfLiteral | numericLiteral | booleanLiteral | UNDEF
;
minusGraphPattern
: MINUS groupGraphPattern
;
groupOrUnionGraphPattern
: groupGraphPattern (UNION groupGraphPattern)*
;
filter
: FILTER constraint
;
constraint
: '(' expression ')' | builtInCall | functionCall
;
functionCall
: iri argList
;
argList
: '(' (DISTINCT? expressionList|) ')'
;
expressionList
: expression (',' expression)*
;
constructTemplate
: '{' constructTriples? '}'
;
constructTriples
: triplesSameSubject ('.' constructTriples?)*
;
triplesSameSubject
: varOrTerm propertyListNotEmpty | triplesNode propertyList
;
propertyList
: propertyListNotEmpty?
;
propertyListNotEmpty
: verb objectList (';' (verb objectList)?)*
;
verb
: varOrIRI | A
;
objectList
: object (',' object)*
;
object
: graphNode
;
triplesSameSubjectPath
: varOrTerm propertyListPathNotEmpty | triplesNodePath propertyListPath
;
propertyListPath
: propertyListPathNotEmpty?
;
propertyListPathNotEmpty
: (verbPath|verbSimple) objectListPath (';' propertyListPathNotEmptyList?)*
;
propertyListPathNotEmptyList
: (verbPath|verbSimple) objectList
;
verbPath
: path
;
verbSimple
: var
;
objectListPath
: objectPath (',' objectPath)*
;
objectPath
: graphNodePath
;
path
: pathAlternative
;
pathAlternative
: pathSequence ('|' pathSequence)*
;
pathSequence
: pathEltOrInverse ('/' pathEltOrInverse)*
;
pathElt
: pathPrimary pathMod?
;
pathEltOrInverse
: INVERSE? pathElt
;
pathMod
: QUESTION_MARK | ASTERISK | PLUS_SIGN
;
pathPrimary
: iri | A | '!' pathNegatedPropertySet | '(' path ')'
;
pathNegatedPropertySet
: pathOneInPropertySet | '(' (pathOneInPropertySet ('|' pathOneInPropertySet)*)? ')'
;
pathOneInPropertySet
: INVERSE? (iri | A)
;
integer
: INTEGER
;
triplesNode
: collection | blankNodePropertyList
;
blankNodePropertyList
: '[' propertyListNotEmpty ']'
;
triplesNodePath
: collectionPath | blankNodePropertyListPath
;
blankNodePropertyListPath
: '[' propertyListPathNotEmpty ']'
;
collection
: '(' graphNode+ ')'
;
collectionPath
: '(' graphNodePath+ ')'
;
graphNode
: varOrTerm | triplesNode
;
graphNodePath
: varOrTerm | triplesNodePath
;
varOrTerm
: var | graphTerm
;
varOrIRI
: var | iri
;
var
: VAR1 | VAR2
;
graphTerm
: iri | rdfLiteral | numericLiteral | booleanLiteral | blankNode | nil
;
nil
: '(' ')'
;
/* ANTLR V4 branded expressions */
expression
: primaryExpression # baseExpression
| op=('*'|'/') expression # unaryMultiplicativeExpression
| op=('+'|'-') expression # unaryAdditiveExpression
| '!' expression # unaryNegationExpression
| expression op=('*'|'/') expression # multiplicativeExpression
| expression op=('+'|'-') expression # additiveExpression
| expression unaryLiteralExpression # unarySignedLiteralExpression
| expression NOT? IN '(' expressionList? ')' # relationalSetExpression
| expression op=('='|'!='|'<'|'>'|'<='|'>=') expression # relationalExpression
| expression ('&&' expression) # conditionalAndExpression
| expression ('||' expression) # conditionalOrExpression
;
unaryLiteralExpression
: (numericLiteralPositive|numericLiteralNegative) (op=('*'|'/') unaryExpression)?
;
unaryExpression
: op=('!'|'+'|'-')? primaryExpression
;
primaryExpression
: '(' expression ')' | builtInCall | iriRefOrFunction | rdfLiteral | numericLiteral | booleanLiteral | var
;
builtInCall
: aggregate
| STR '(' expression ')'
| LANG '(' expression ')'
| LANGMATCHES '(' expression ',' expression ')'
| DATATYPE '(' expression ')'
| BOUND '(' var ')'
| IRI '(' expression ')'
| URI '(' expression ')'
| BNODE '(' expression? ')'
| RAND '(' ')'
| ABS '(' expression ')'
| CEIL '(' expression ')'
| FLOOR '(' expression ')'
| ROUND '(' expression ')'
| CONCAT '(' expressionList? ')'
| subStringExpression
| STRLEN '(' expression ')'
| strReplaceExpression
| UCASE '(' expression ')'
| LCASE '(' expression ')'
| ENCODE_FOR_URI '(' expression ')'
| CONTAINS '(' expression ',' expression ')'
| STRSTARTS '(' expression ',' expression ')'
| STRENDS '(' expression ',' expression ')'
| STRBEFORE '(' expression ',' expression ')'
| STRAFTER '(' expression ',' expression ')'
| YEAR '(' expression ')'
| MONTH '(' expression ')'
| DAY '(' expression ')'
| HOURS '(' expression ')'
| MINUTES '(' expression ')'
| SECONDS '(' expression ')'
| TIMEZONE '(' expression ')'
| TZ '(' expression ')'
| NOW '(' ')'
| UUID '(' ')'
| STRUUID '(' ')'
| MD5 '(' expression ')'
| SHA1 '(' expression ')'
| SHA256 '(' expression ')'
| SHA384 '(' expression ')'
| SHA512 '(' expression ')'
| COALESCE '(' expressionList? ')'
| IF '(' expression ',' expression ',' expression ')'
| STRLANG '(' expression ',' expression ')'
| STRDT '(' expression ',' expression ')'
| SAMETERM '(' expression ',' expression ')'
| ISIRI '(' expression ')'
| ISURI '(' expression ')'
| ISBLANK '(' expression ')'
| ISLITERAL '(' expression ')'
| ISNUMERIC '(' expression ')'
| regexExpression
| existsFunction
| notExistsFunction
;
regexExpression
: REGEX '(' expression ',' expression (',' expression)? ')'
;
subStringExpression
: SUBSTR '(' expression ',' expression (',' expression)? ')'
;
strReplaceExpression
: REPLACE '(' expression ',' expression ',' expression (',' expression)? ')'
;
existsFunction
: EXISTS groupGraphPattern
;
notExistsFunction
: NOT EXISTS groupGraphPattern
;
aggregate
: COUNT '(' DISTINCT? (ASTERISK | expression) ')'
| SUM '(' DISTINCT? expression ')'
| MIN '(' DISTINCT? expression ')'
| MAX '(' DISTINCT? expression ')'
| AVG '(' DISTINCT? expression ')'
| SAMPLE '(' DISTINCT? expression ')'
| GROUP_CONCAT '(' DISTINCT? expression (';' SEPARATOR '=' string)? ')'
;
iriRefOrFunction
: iri argList?
;
rdfLiteral
: string (LANGTAG | ('^^' iri))?
;
numericLiteral
: numericLiteralUnsigned | numericLiteralPositive | numericLiteralNegative
;
numericLiteralUnsigned
: INTEGER | DECIMAL | DOUBLE
;
numericLiteralPositive
: INTEGER_POSITIVE | DECIMAL_POSITIVE | DOUBLE_POSITIVE
;
numericLiteralNegative
: INTEGER_NEGATIVE | DECIMAL_NEGATIVE | DOUBLE_NEGATIVE
;
booleanLiteral
: TRUE | FALSE
;
string
: STRING_LITERAL1 | STRING_LITERAL2 | STRING_LITERAL_LONG1 | STRING_LITERAL_LONG2
;
iri
: IRIREF | prefixedName
;
prefixedName
: PNAME_LN | PNAME_NS
;
blankNode
: BLANK_NODE_LABEL | anon
;
anon
: '[' ']'
;
// $>
|
Allow empty queries. Allow queries with just a prologue part.
|
Allow empty queries.
Allow queries with just a prologue part.
|
ANTLR
|
apache-2.0
|
vnadgir-ft/sparkle-g
|
22b693f9de8a858a8d491c756a607bfa3f28988e
|
shardingsphere-sql-parser/shardingsphere-sql-parser-dialect/shardingsphere-sql-parser-oracle/src/main/antlr4/imports/oracle/BaseRule.g4
|
shardingsphere-sql-parser/shardingsphere-sql-parser-dialect/shardingsphere-sql-parser-oracle/src/main/antlr4/imports/oracle/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, OracleKeyword, Literals;
parameterMarker
: QUESTION_
;
literals
: stringLiterals
| numberLiterals
| dateTimeLiterals
| hexadecimalLiterals
| bitValueLiterals
| booleanLiterals
| nullValueLiterals
;
stringLiterals
: STRING_
;
numberLiterals
: MINUS_? NUMBER_
;
dateTimeLiterals
: (DATE | TIME | TIMESTAMP) STRING_
| LBE_ identifier STRING_ RBE_
;
hexadecimalLiterals
: HEX_DIGIT_
;
bitValueLiterals
: BIT_NUM_
;
booleanLiterals
: TRUE | FALSE
;
nullValueLiterals
: NULL
;
identifier
: IDENTIFIER_ | unreservedWord
;
unreservedWord
: TRUNCATE | FUNCTION | PROCEDURE | CASE | WHEN | CAST | TRIM | SUBSTRING
| NATURAL | JOIN | FULL | INNER | OUTER | LEFT | RIGHT
| CROSS | USING | IF | TRUE | FALSE | LIMIT | OFFSET
| BEGIN | COMMIT | ROLLBACK | SAVEPOINT | BOOLEAN | DOUBLE | CHARACTER
| ARRAY | INTERVAL | TIME | TIMESTAMP | LOCALTIME | LOCALTIMESTAMP | YEAR
| QUARTER | MONTH | WEEK | DAY | HOUR | MINUTE | SECOND
| MICROSECOND | MAX | MIN | SUM | COUNT | AVG | ENABLE
| DISABLE | BINARY | ESCAPE | MOD | UNKNOWN | XOR | ALWAYS
| CASCADE | GENERATED | PRIVILEGES | READ | WRITE | REFERENCES | TRANSACTION
| ROLE | VISIBLE | INVISIBLE | EXECUTE | USE | DEBUG | UNDER
| FLASHBACK | ARCHIVE | REFRESH | QUERY | REWRITE | KEEP | SEQUENCE
| INHERIT | TRANSLATE | SQL | MERGE | AT | BITMAP | CACHE | CHECKPOINT
| CONNECT | CONSTRAINTS | CYCLE | DBTIMEZONE | ENCRYPT | DECRYPT | DEFERRABLE
| DEFERRED | EDITION | ELEMENT | END | EXCEPTIONS | FORCE | GLOBAL
| IDENTITY | INITIALLY | INVALIDATE | JAVA | LEVELS | LOCAL | MAXVALUE
| MINVALUE | NOMAXVALUE | NOMINVALUE | MINING | MODEL | NATIONAL | NEW
| NOCACHE | NOCYCLE | NOORDER | NORELY | NOVALIDATE | ONLY | PRESERVE
| PROFILE | REF | REKEY | RELY | REPLACE | SOURCE | SALT
| SCOPE | SORT | SUBSTITUTABLE | TABLESPACE | TEMPORARY | TRANSLATION | TREAT
| NO | TYPE | UNUSED | VALUE | VARYING | VIRTUAL | ZONE
| ADVISOR | ADMINISTER | TUNING | MANAGE | MANAGEMENT | OBJECT | CLUSTER
| CONTEXT | EXEMPT | REDACTION | POLICY | DATABASE | SYSTEM | AUDIT
| LINK | ANALYZE | DICTIONARY | DIMENSION | INDEXTYPE | EXTERNAL | JOB
| CLASS | PROGRAM | SCHEDULER | LIBRARY | LOGMINING | MATERIALIZED | CUBE
| MEASURE | FOLDER | BUILD | PROCESS | OPERATOR | OUTLINE | PLUGGABLE
| CONTAINER | SEGMENT | RESTRICTED | COST | SYNONYM | BACKUP | UNLIMITED
| BECOME | CHANGE | NOTIFICATION | ACCESS | PRIVILEGE | PURGE | RESUMABLE
| SYSGUID | SYSBACKUP | SYSDBA | SYSDG | SYSKM | SYSOPER | DBA_RECYCLEBIN |SCHEMA
| DO | DEFINER | CURRENT_USER | CASCADED | CLOSE | OPEN | NEXT | NAME | NAMES
| INTEGER | COLLATION | REAL | DECIMAL | TYPE | FIRST
;
schemaName
: identifier
;
tableName
: (owner DOT_)? name
;
viewName
: (owner DOT_)? name
;
columnName
: (owner DOT_)? name
;
objectName
: (owner DOT_)? name
;
clusterName
: (owner DOT_)? name
;
indexName
: identifier
;
savepointName
: identifier
;
synonymName
: identifier
;
owner
: identifier
;
name
: identifier
;
tablespaceName
: identifier
;
tablespaceSetName
: identifier
;
serviceName
: identifier
;
ilmPolicyName
: identifier
;
functionName
: identifier
;
directoryName
: identifier
;
opaqueFormatSpec
: identifier
;
accessDriverType
: identifier
;
partition
: identifier
;
type
: identifier
;
varrayItem
: identifier
;
nestedItem
: identifier
;
storageTable
: identifier
;
lobSegname
: identifier
;
locationSpecifier
: identifier
;
xmlSchemaURLName
: identifier
;
elementName
: identifier
;
subpartitionName
: identifier
;
partitionName
: identifier
;
partitionSetName
: identifier
;
zonemapName
: identifier
;
flashbackArchiveName
: identifier
;
roleName
: identifier
;
password
: identifier
;
columnNames
: LP_? columnName (COMMA_ columnName)* RP_?
;
tableNames
: LP_? tableName (COMMA_ tableName)* RP_?
;
oracleId
: IDENTIFIER_ | (STRING_ DOT_)* STRING_
;
collationName
: STRING_ | IDENTIFIER_
;
alias
: IDENTIFIER_
;
dataTypeLength
: LP_ (NUMBER_ (COMMA_ NUMBER_)?)? RP_
;
primaryKey
: PRIMARY? KEY
;
exprs
: expr (COMMA_ expr)*
;
exprList
: LP_ exprs RP_
;
// TODO comb expr
expr
: expr logicalOperator expr
| notOperator expr
| LP_ expr RP_
| booleanPrimary
;
logicalOperator
: OR | OR_ | AND | AND_
;
notOperator
: NOT | NOT_
;
booleanPrimary
: booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN | NULL)
| booleanPrimary SAFE_EQ_ predicate
| booleanPrimary comparisonOperator predicate
| booleanPrimary comparisonOperator (ALL | ANY) subquery
| predicate
;
comparisonOperator
: EQ_ | GTE_ | GT_ | LTE_ | LT_ | NEQ_
;
predicate
: bitExpr NOT? IN subquery
| bitExpr NOT? IN LP_ expr (COMMA_ expr)* RP_
| bitExpr NOT? BETWEEN bitExpr AND predicate
| bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)?
| bitExpr
;
bitExpr
: bitExpr VERTICAL_BAR_ bitExpr
| bitExpr AMPERSAND_ bitExpr
| bitExpr SIGNED_LEFT_SHIFT_ bitExpr
| bitExpr SIGNED_RIGHT_SHIFT_ bitExpr
| bitExpr PLUS_ bitExpr
| bitExpr MINUS_ bitExpr
| bitExpr ASTERISK_ bitExpr
| bitExpr SLASH_ bitExpr
| bitExpr MOD_ bitExpr
| bitExpr CARET_ bitExpr
| simpleExpr
;
simpleExpr
: functionCall
| parameterMarker
| literals
| columnName
| simpleExpr OR_ simpleExpr
| (PLUS_ | MINUS_ | TILDE_ | NOT_ | BINARY) simpleExpr
| ROW? LP_ expr (COMMA_ expr)* RP_
| EXISTS? subquery
| LBE_ identifier expr RBE_
| caseExpression
| privateExprOfDb
;
functionCall
: aggregationFunction | specialFunction | regularFunction
;
aggregationFunction
: aggregationFunctionName LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? RP_
;
aggregationFunctionName
: MAX | MIN | SUM | COUNT | AVG
;
distinct
: DISTINCT
;
specialFunction
: castFunction | charFunction
;
castFunction
: CAST LP_ expr AS dataType RP_
;
charFunction
: CHAR LP_ expr (COMMA_ expr)* (USING ignoredIdentifier)? RP_
;
regularFunction
: regularFunctionName LP_ (expr (COMMA_ expr)* | ASTERISK_)? RP_
;
regularFunctionName
: identifier | IF | LOCALTIME | LOCALTIMESTAMP | INTERVAL
;
caseExpression
: CASE simpleExpr? caseWhen+ caseElse?
;
caseWhen
: WHEN expr THEN expr
;
caseElse
: ELSE expr
;
subquery
: matchNone
;
orderByClause
: ORDER BY orderByItem (COMMA_ orderByItem)*
;
orderByItem
: (columnName | numberLiterals | expr) (ASC | DESC)?
;
attributeName
: oracleId
;
indexTypeName
: IDENTIFIER_
;
simpleExprs
: simpleExpr (COMMA_ simpleExpr)*
;
lobItem
: attributeName | columnName
;
lobItems
: lobItem (COMMA_ lobItem)*
;
lobItemList
: LP_ lobItems RP_
;
dataType
: dataTypeName dataTypeLength? | specialDatatype | dataTypeName dataTypeLength? datetimeTypeSuffix
;
specialDatatype
: dataTypeName (LP_ NUMBER_ CHAR RP_) | NATIONAL dataTypeName VARYING? LP_ NUMBER_ RP_ | dataTypeName LP_? columnName RP_?
;
dataTypeName
: CHAR | NCHAR | RAW | VARCHAR | VARCHAR2 | NVARCHAR2 | LONG | LONG RAW | BLOB | CLOB | NCLOB | BINARY_FLOAT | BINARY_DOUBLE
| BOOLEAN | PLS_INTEGER | BINARY_INTEGER | INTEGER | NUMBER | NATURAL | NATURALN | POSITIVE | POSITIVEN | SIGNTYPE
| SIMPLE_INTEGER | BFILE | MLSLABEL | UROWID | DATE | TIMESTAMP | TIMESTAMP WITH TIME ZONE | TIMESTAMP WITH LOCAL TIME ZONE
| INTERVAL DAY TO SECOND | INTERVAL YEAR TO MONTH | JSON | FLOAT | REAL | DOUBLE PRECISION | INT | SMALLINT
| DECIMAL | NUMERIC | DEC | IDENTIFIER_ | XMLTYPE
;
datetimeTypeSuffix
: (WITH LOCAL? TIME ZONE)? | TO MONTH | TO SECOND (LP_ NUMBER_ RP_)?
;
treatFunction
: TREAT LP_ expr AS REF? dataTypeName RP_
;
privateExprOfDb
: treatFunction | caseExpr | intervalExpression | objectAccessExpression | constructorExpr
;
caseExpr
: CASE (simpleCaseExpr | searchedCaseExpr) elseClause? END
;
simpleCaseExpr
: expr searchedCaseExpr+
;
searchedCaseExpr
: WHEN expr THEN simpleExpr
;
elseClause
: ELSE expr
;
intervalExpression
: LP_ expr MINUS_ expr RP_ (DAY (LP_ NUMBER_ RP_)? TO SECOND (LP_ NUMBER_ RP_)? | YEAR (LP_ NUMBER_ RP_)? TO MONTH)
;
objectAccessExpression
: (LP_ simpleExpr RP_ | treatFunction) DOT_ (attributeName (DOT_ attributeName)* (DOT_ functionCall)? | functionCall)
;
constructorExpr
: NEW dataTypeName exprList
;
ignoredIdentifier
: IDENTIFIER_
;
ignoredIdentifiers
: ignoredIdentifier (COMMA_ ignoredIdentifier)*
;
matchNone
: 'Default does not match anything'
;
hashSubpartitionQuantity
: NUMBER
;
|
/*
* 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, OracleKeyword, Literals;
parameterMarker
: QUESTION_
;
literals
: stringLiterals
| numberLiterals
| dateTimeLiterals
| hexadecimalLiterals
| bitValueLiterals
| booleanLiterals
| nullValueLiterals
;
stringLiterals
: STRING_
;
numberLiterals
: MINUS_? NUMBER_
;
dateTimeLiterals
: (DATE | TIME | TIMESTAMP) STRING_
| LBE_ identifier STRING_ RBE_
;
hexadecimalLiterals
: HEX_DIGIT_
;
bitValueLiterals
: BIT_NUM_
;
booleanLiterals
: TRUE | FALSE
;
nullValueLiterals
: NULL
;
identifier
: IDENTIFIER_ | unreservedWord
;
unreservedWord
: TRUNCATE | FUNCTION | PROCEDURE | CASE | WHEN | CAST | TRIM | SUBSTRING
| NATURAL | JOIN | FULL | INNER | OUTER | LEFT | RIGHT
| CROSS | USING | IF | TRUE | FALSE | LIMIT | OFFSET
| BEGIN | COMMIT | ROLLBACK | SAVEPOINT | BOOLEAN | DOUBLE | CHARACTER
| ARRAY | INTERVAL | TIME | TIMESTAMP | LOCALTIME | LOCALTIMESTAMP | YEAR
| QUARTER | MONTH | WEEK | DAY | HOUR | MINUTE | SECOND
| MICROSECOND | MAX | MIN | SUM | COUNT | AVG | ENABLE
| DISABLE | BINARY | ESCAPE | MOD | UNKNOWN | XOR | ALWAYS
| CASCADE | GENERATED | PRIVILEGES | READ | WRITE | REFERENCES | TRANSACTION
| ROLE | VISIBLE | INVISIBLE | EXECUTE | USE | DEBUG | UNDER
| FLASHBACK | ARCHIVE | REFRESH | QUERY | REWRITE | KEEP | SEQUENCE
| INHERIT | TRANSLATE | SQL | MERGE | AT | BITMAP | CACHE | CHECKPOINT
| CONSTRAINTS | CYCLE | DBTIMEZONE | ENCRYPT | DECRYPT | DEFERRABLE
| DEFERRED | EDITION | ELEMENT | END | EXCEPTIONS | FORCE | GLOBAL
| IDENTITY | INITIALLY | INVALIDATE | JAVA | LEVELS | LOCAL | MAXVALUE
| MINVALUE | NOMAXVALUE | NOMINVALUE | MINING | MODEL | NATIONAL | NEW
| NOCACHE | NOCYCLE | NOORDER | NORELY | NOVALIDATE | ONLY | PRESERVE
| PROFILE | REF | REKEY | RELY | REPLACE | SOURCE | SALT
| SCOPE | SORT | SUBSTITUTABLE | TABLESPACE | TEMPORARY | TRANSLATION | TREAT
| NO | TYPE | UNUSED | VALUE | VARYING | VIRTUAL | ZONE
| ADVISOR | ADMINISTER | TUNING | MANAGE | MANAGEMENT | OBJECT
| CONTEXT | EXEMPT | REDACTION | POLICY | DATABASE | SYSTEM
| LINK | ANALYZE | DICTIONARY | DIMENSION | INDEXTYPE | EXTERNAL | JOB
| CLASS | PROGRAM | SCHEDULER | LIBRARY | LOGMINING | MATERIALIZED | CUBE
| MEASURE | FOLDER | BUILD | PROCESS | OPERATOR | OUTLINE | PLUGGABLE
| CONTAINER | SEGMENT | RESTRICTED | COST | BACKUP | UNLIMITED
| BECOME | CHANGE | NOTIFICATION | PRIVILEGE | PURGE | RESUMABLE
| SYSGUID | SYSBACKUP | SYSDBA | SYSDG | SYSKM | SYSOPER | DBA_RECYCLEBIN |SCHEMA
| DO | DEFINER | CURRENT_USER | CASCADED | CLOSE | OPEN | NEXT | NAME | NAMES
| COLLATION | REAL | TYPE | FIRST
;
schemaName
: identifier
;
tableName
: (owner DOT_)? name
;
viewName
: (owner DOT_)? name
;
columnName
: (owner DOT_)? name
;
objectName
: (owner DOT_)? name
;
clusterName
: (owner DOT_)? name
;
indexName
: identifier
;
savepointName
: identifier
;
synonymName
: identifier
;
owner
: identifier
;
name
: identifier
;
tablespaceName
: identifier
;
tablespaceSetName
: identifier
;
serviceName
: identifier
;
ilmPolicyName
: identifier
;
functionName
: identifier
;
directoryName
: identifier
;
opaqueFormatSpec
: identifier
;
accessDriverType
: identifier
;
partition
: identifier
;
type
: identifier
;
varrayItem
: identifier
;
nestedItem
: identifier
;
storageTable
: identifier
;
lobSegname
: identifier
;
locationSpecifier
: identifier
;
xmlSchemaURLName
: identifier
;
elementName
: identifier
;
subpartitionName
: identifier
;
partitionName
: identifier
;
partitionSetName
: identifier
;
zonemapName
: identifier
;
flashbackArchiveName
: identifier
;
roleName
: identifier
;
password
: identifier
;
columnNames
: LP_? columnName (COMMA_ columnName)* RP_?
;
tableNames
: LP_? tableName (COMMA_ tableName)* RP_?
;
oracleId
: IDENTIFIER_ | (STRING_ DOT_)* STRING_
;
collationName
: STRING_ | IDENTIFIER_
;
alias
: IDENTIFIER_
;
dataTypeLength
: LP_ (NUMBER_ (COMMA_ NUMBER_)?)? RP_
;
primaryKey
: PRIMARY? KEY
;
exprs
: expr (COMMA_ expr)*
;
exprList
: LP_ exprs RP_
;
// TODO comb expr
expr
: expr logicalOperator expr
| notOperator expr
| LP_ expr RP_
| booleanPrimary
;
logicalOperator
: OR | OR_ | AND | AND_
;
notOperator
: NOT | NOT_
;
booleanPrimary
: booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN | NULL)
| booleanPrimary SAFE_EQ_ predicate
| booleanPrimary comparisonOperator predicate
| booleanPrimary comparisonOperator (ALL | ANY) subquery
| predicate
;
comparisonOperator
: EQ_ | GTE_ | GT_ | LTE_ | LT_ | NEQ_
;
predicate
: bitExpr NOT? IN subquery
| bitExpr NOT? IN LP_ expr (COMMA_ expr)* RP_
| bitExpr NOT? BETWEEN bitExpr AND predicate
| bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)?
| bitExpr
;
bitExpr
: bitExpr VERTICAL_BAR_ bitExpr
| bitExpr AMPERSAND_ bitExpr
| bitExpr SIGNED_LEFT_SHIFT_ bitExpr
| bitExpr SIGNED_RIGHT_SHIFT_ bitExpr
| bitExpr PLUS_ bitExpr
| bitExpr MINUS_ bitExpr
| bitExpr ASTERISK_ bitExpr
| bitExpr SLASH_ bitExpr
| bitExpr MOD_ bitExpr
| bitExpr CARET_ bitExpr
| simpleExpr
;
simpleExpr
: functionCall
| parameterMarker
| literals
| columnName
| simpleExpr OR_ simpleExpr
| (PLUS_ | MINUS_ | TILDE_ | NOT_ | BINARY) simpleExpr
| ROW? LP_ expr (COMMA_ expr)* RP_
| EXISTS? subquery
| LBE_ identifier expr RBE_
| caseExpression
| privateExprOfDb
;
functionCall
: aggregationFunction | specialFunction | regularFunction
;
aggregationFunction
: aggregationFunctionName LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? RP_
;
aggregationFunctionName
: MAX | MIN | SUM | COUNT | AVG
;
distinct
: DISTINCT
;
specialFunction
: castFunction | charFunction
;
castFunction
: CAST LP_ expr AS dataType RP_
;
charFunction
: CHAR LP_ expr (COMMA_ expr)* (USING ignoredIdentifier)? RP_
;
regularFunction
: regularFunctionName LP_ (expr (COMMA_ expr)* | ASTERISK_)? RP_
;
regularFunctionName
: identifier | IF | LOCALTIME | LOCALTIMESTAMP | INTERVAL
;
caseExpression
: CASE simpleExpr? caseWhen+ caseElse?
;
caseWhen
: WHEN expr THEN expr
;
caseElse
: ELSE expr
;
subquery
: matchNone
;
orderByClause
: ORDER BY orderByItem (COMMA_ orderByItem)*
;
orderByItem
: (columnName | numberLiterals | expr) (ASC | DESC)?
;
attributeName
: oracleId
;
indexTypeName
: IDENTIFIER_
;
simpleExprs
: simpleExpr (COMMA_ simpleExpr)*
;
lobItem
: attributeName | columnName
;
lobItems
: lobItem (COMMA_ lobItem)*
;
lobItemList
: LP_ lobItems RP_
;
dataType
: dataTypeName dataTypeLength? | specialDatatype | dataTypeName dataTypeLength? datetimeTypeSuffix
;
specialDatatype
: dataTypeName (LP_ NUMBER_ CHAR RP_) | NATIONAL dataTypeName VARYING? LP_ NUMBER_ RP_ | dataTypeName LP_? columnName RP_?
;
dataTypeName
: CHAR | NCHAR | RAW | VARCHAR | VARCHAR2 | NVARCHAR2 | LONG | LONG RAW | BLOB | CLOB | NCLOB | BINARY_FLOAT | BINARY_DOUBLE
| BOOLEAN | PLS_INTEGER | BINARY_INTEGER | INTEGER | NUMBER | NATURAL | NATURALN | POSITIVE | POSITIVEN | SIGNTYPE
| SIMPLE_INTEGER | BFILE | MLSLABEL | UROWID | DATE | TIMESTAMP | TIMESTAMP WITH TIME ZONE | TIMESTAMP WITH LOCAL TIME ZONE
| INTERVAL DAY TO SECOND | INTERVAL YEAR TO MONTH | JSON | FLOAT | REAL | DOUBLE PRECISION | INT | SMALLINT
| DECIMAL | NUMERIC | DEC | IDENTIFIER_ | XMLTYPE
;
datetimeTypeSuffix
: (WITH LOCAL? TIME ZONE)? | TO MONTH | TO SECOND (LP_ NUMBER_ RP_)?
;
treatFunction
: TREAT LP_ expr AS REF? dataTypeName RP_
;
privateExprOfDb
: treatFunction | caseExpr | intervalExpression | objectAccessExpression | constructorExpr
;
caseExpr
: CASE (simpleCaseExpr | searchedCaseExpr) elseClause? END
;
simpleCaseExpr
: expr searchedCaseExpr+
;
searchedCaseExpr
: WHEN expr THEN simpleExpr
;
elseClause
: ELSE expr
;
intervalExpression
: LP_ expr MINUS_ expr RP_ (DAY (LP_ NUMBER_ RP_)? TO SECOND (LP_ NUMBER_ RP_)? | YEAR (LP_ NUMBER_ RP_)? TO MONTH)
;
objectAccessExpression
: (LP_ simpleExpr RP_ | treatFunction) DOT_ (attributeName (DOT_ attributeName)* (DOT_ functionCall)? | functionCall)
;
constructorExpr
: NEW dataTypeName exprList
;
ignoredIdentifier
: IDENTIFIER_
;
ignoredIdentifiers
: ignoredIdentifier (COMMA_ ignoredIdentifier)*
;
matchNone
: 'Default does not match anything'
;
hashSubpartitionQuantity
: NUMBER
;
|
Correct Oracle unreservedWord (#10018)
|
Correct Oracle unreservedWord (#10018)
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
|
b4cf05f91cf8b533943f4f9afd6e118a4c454531
|
java-vtl-parser/src/main/antlr4/imports/Relational.g4
|
java-vtl-parser/src/main/antlr4/imports/Relational.g4
|
grammar Relational;
relationalExpression : unionExpression | joinExpression ;
unionExpression : 'union' '(' datasetExpression (',' datasetExpression )* ')' ;
joinExpression : '[' joinDefinition ']' '{' joinBody '}';
joinDefinition : INNER? joinParam #joinDefinitionInner
| OUTER joinParam #joinDefinitionOuter
| CROSS joinParam #joinDefinitionCross ;
joinParam : varID (',' varID )* ( 'on' dimensionExpression (',' dimensionExpression )* )? ;
joinBody : joinClause (',' joinClause)* ;
joinClause : role? varID '=' joinCalcExpression # joinCalcClause;
//| joinFilter
//| joinKeep
//| joinRename ;
//| joinDrop
//| joinUnfold
//| joinFold ;
// Left recursive
joinCalcExpression : leftOperand=joinCalcExpression sign=( '*' | '/' ) rightOperand=joinCalcExpression #joinCalcProduct
| leftOperand=joinCalcExpression sign=( '+' | '-' ) rightOperand=joinCalcExpression #joinCalcSummation
| '(' joinCalcExpression ')' #joinCalcPrecedence
| joinCalcRef #joinCalcReference
| constant #joinCalcAtom
;
joinCalcRef : (aliasName=varID '.')? componentName=varID ;
role : ( 'IDENTIFIER' | 'MEASURE' | 'ATTRIBUTE' ) ;
INNER : 'inner' ;
OUTER : 'outer' ;
CROSS : 'cross' ;
// For tests only
varID : 'varID' NUM+;
variableRef : ( 'varName' | 'constant' ) NUM+;
datasetExpression : 'datasetExpr' NUM*;
dimensionExpression : 'dimensionExpr' NUM*;
constant : NUM ;
NUM : '0'..'9' ;
WS : [ \t\n\t] -> skip ;
|
grammar Relational;
relationalExpression : unionExpression | joinExpression ;
unionExpression : 'union' '(' datasetExpression (',' datasetExpression )* ')' ;
joinExpression : '[' joinDefinition ']' '{' joinBody '}';
joinDefinition : INNER? joinParam #joinDefinitionInner
| OUTER joinParam #joinDefinitionOuter
| CROSS joinParam #joinDefinitionCross ;
joinParam : varID (',' varID )* ( 'on' dimensionExpression (',' dimensionExpression )* )? ;
joinBody : joinClause (',' joinClause)* ;
joinClause : role? varID '=' joinCalcExpression # joinCalcClause
| joinDropExpression # joinDropClause
| joinKeepExpression # joinKeepClause
;
//| joinFilter
//| joinKeep
//| joinRename ;
//| joinDrop
//| joinUnfold
//| joinFold ;
// Left recursive
joinCalcExpression : leftOperand=joinCalcExpression sign=( '*' | '/' ) rightOperand=joinCalcExpression #joinCalcProduct
| leftOperand=joinCalcExpression sign=( '+' | '-' ) rightOperand=joinCalcExpression #joinCalcSummation
| '(' joinCalcExpression ')' #joinCalcPrecedence
| joinCalcRef #joinCalcReference
| constant #joinCalcAtom
;
// TODO: This is the membership operator!
joinCalcRef : (aliasName=varID '.')? componentName=varID ;
// Drop clause
joinDropExpression : 'drop' joinDropRef (',' joinDropRef)+ ;
joinDropRef : (aliasName=varID '.')? componentName=varID ;
// Keep clause
joinKeepExpression : 'keep' joidKeepRef (',' joidKeepRef)+ ;
joidKeepRef : (aliasName=varID '.')? componentName=varID ;
role : ( 'IDENTIFIER' | 'MEASURE' | 'ATTRIBUTE' ) ;
INNER : 'inner' ;
OUTER : 'outer' ;
CROSS : 'cross' ;
// For tests only
varID : 'varID' NUM+;
variableRef : ( 'varName' | 'constant' ) NUM+;
datasetExpression : 'datasetExpr' NUM*;
dimensionExpression : 'dimensionExpr' NUM*;
constant : NUM ;
NUM : '0'..'9' ;
WS : [ \t\n\t] -> skip ;
|
Add the keep and drop join clauses
|
Add the keep and drop join clauses
|
ANTLR
|
apache-2.0
|
hadrienk/java-vtl,hadrienk/java-vtl,statisticsnorway/java-vtl,statisticsnorway/java-vtl,statisticsnorway/java-vtl,hadrienk/java-vtl,statisticsnorway/java-vtl
|
b0036b0f4df26816dd4b764b5c90728e4fbff6a8
|
expr/src/main/antlr4/org/teavm/flavour/expr/antlr/Expr.g4
|
expr/src/main/antlr4/org/teavm/flavour/expr/antlr/Expr.g4
|
grammar Expr;
NUMBER : INT_NUMBER | FRAC_NUMBER ;
fragment INT_NUMBER : '0' | '1'..'9' ('0'..'9')* ;
fragment FRAC_NUMBER : INT_NUMBER '.' DIGITS EXPONENT? | INT_NUMBER EXPONENT ;
fragment DIGITS : ('0'..'9')+ ;
fragment EXPONENT : ('e' | 'E') ('+' | '-')? DIGITS ;
IDENTIFIER : IDENTIFIER_START IDENTIFIER_PART* ;
fragment IDENTIFIER_START : 'A'..'Z' | 'a'..'z' | '_' | '$' ;
fragment IDENTIFIER_PART : IDENTIFIER_START | '0'..'9' ;
STRING_LITERAL : '\'' STRING_CHAR* '\'' ;
fragment STRING_CHAR : STRING_NON_ESCAPE_CHAR | STRING_ESCAPE_CHAR ;
fragment STRING_NON_ESCAPE_CHAR : ' ' .. '&' | '(' .. '[' | ']' .. '\uFFFF' ;
fragment STRING_ESCAPE_CHAR : '\\' ('r' | 'n' | 't' | '\\' | '\'' | '\\u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT) ;
fragment HEX_DIGIT : [0-9a-fA-F] ;
WHITESPACE : (' ' | '\r' | '\n' | '\t') -> channel(HIDDEN) ;
object
: '{' (entires+=objectEntry (',' entries+=objectEntry)*)? '}'
;
objectEntry
: key=IDENTIFIER ':' value=lambda
;
lambda
: (boundVars=lambdaBoundVars '->')? body=assignment
;
lambdaBoundVars
: '(' (boundVars+=lambdaBoundVar (',' boundVars+=lambdaBoundVar)*)? ')'
| boundVars+=lambdaBoundVar
;
lambdaBoundVar
: varType=type? varName=lambdaIdentifier
;
lambdaIdentifier
: '_'
| IDENTIFIER
;
assignment
: (lhs=path '=')? rhs=ternaryCondition
;
expression
: value=ternaryCondition
;
ternaryCondition
: condition=or ('?' consequent=or ':' alternative=ternaryCondition)?
;
or
: arguments+=and ('or' arguments+=and)*
;
and
: arguments+=not ('and' arguments+=not)*
;
not
: (notKeyword='not')? operand=comparison
;
comparison
: first=additive (operations+=comparisonOperation remaining+=additive)*
;
comparisonOperation
: '=='
| '!='
| '<'
| 'lt'
| '>'
| 'gt'
| '<='
| 'loe'
| '>='
| 'goe'
;
additive
: arguments+=multiplicative (operations+=('+' | '-') arguments+=multiplicative)*
;
multiplicative
: arguments+=arithmetic (operations+=('*' | '/' | '%') arguments+=arithmetic)*
;
arithmetic
: '-' operand=arithmetic #trueArithmetic
| operand=path #arithmeticFallback
;
path
: '(' targetType=type ')' value=primitive #pathCast
| base=primitive navigations+=navigation* isInstance=instanceOf? #pathNavigated
;
navigation
: '.' id=IDENTIFIER (invoke='(' arguments=expressionList? ')')? #propertyNavigation
| '[' index=expression ']' #arrayNavigation
;
instanceOf
: 'instanceof' checkedType=genericType
;
primitive
: value=NUMBER #numberPrimitive
| value=STRING_LITERAL #stringPrimitive
| 'this' #thisPrimitive
| 'true' #truePrimitive
| 'false' #falsePrimitive
| 'null' #nullPrimitive
| functionName=IDENTIFIER '(' arguments=expressionList? ')' #functionCall
| id=IDENTIFIER #idPrimitive
| '(' value=expression ')' #parenthesized
;
expressionList
: expressions+=lambda (',' expressions+=lambda)*
;
type
: baseType=nonArrayType suffix=arraySuffix?
;
genericType
: baseType=qualifiedClassType suffix=arraySuffix?
;
arraySuffix
: (suffice+='[' ']')+
;
nonArrayType
: 'boolean' #booleanType
| 'char' #charType
| 'byte' #byteType
| 'short' #shortType
| 'int' #intType
| 'long' #longType
| 'float' #floatType
| 'double' #doubleType
| qualifiedClassType #classType
;
qualifiedClassType
: raw=rawClassType ('<' args=typeArguments '>')?
;
rawClassType
: fqnPart+=IDENTIFIER ('.' fqnPart+=IDENTIFIER)*
;
typeArguments
: types+=genericType (',' types+=genericType)*
;
|
grammar Expr;
NUMBER : INT_NUMBER | FRAC_NUMBER ;
fragment INT_NUMBER : '0' | '1'..'9' ('0'..'9')* ;
fragment FRAC_NUMBER : INT_NUMBER '.' DIGITS EXPONENT? | INT_NUMBER EXPONENT ;
fragment DIGITS : ('0'..'9')+ ;
fragment EXPONENT : ('e' | 'E') ('+' | '-')? DIGITS ;
IDENTIFIER : IDENTIFIER_START IDENTIFIER_PART* ;
fragment IDENTIFIER_START : 'A'..'Z' | 'a'..'z' | '_' | '$' ;
fragment IDENTIFIER_PART : IDENTIFIER_START | '0'..'9' ;
STRING_LITERAL : '\'' STRING_CHAR* '\'' ;
fragment STRING_CHAR : STRING_NON_ESCAPE_CHAR | STRING_ESCAPE_CHAR ;
fragment STRING_NON_ESCAPE_CHAR : ' ' .. '&' | '(' .. '[' | ']' .. '\uFFFF' ;
fragment STRING_ESCAPE_CHAR : '\\' ('r' | 'n' | 't' | '\\' | '\'' | '\\u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT) ;
fragment HEX_DIGIT : [0-9a-fA-F] ;
WHITESPACE : (' ' | '\r' | '\n' | '\t') -> channel(HIDDEN) ;
object
: '{' (entires+=objectEntry (',' entries+=objectEntry)*)? '}'
;
objectEntry
: key=IDENTIFIER ':' value=lambda
;
lambda
: (boundVars=lambdaBoundVars '->')? body=assignment
;
lambdaBoundVars
: '(' (boundVars+=lambdaBoundVar (',' boundVars+=lambdaBoundVar)*)? ')'
| boundVars+=lambdaBoundVar
;
lambdaBoundVar
: varType=type? varName=lambdaIdentifier
;
lambdaIdentifier
: '_'
| IDENTIFIER
;
assignment
: (lhs=path '=')? rhs=ternaryCondition
;
expression
: value=ternaryCondition
;
ternaryCondition
: condition=or ('?' consequent=or ':' alternative=ternaryCondition)?
;
or
: arguments+=and (('or' | '||') arguments+=and)*
;
and
: arguments+=not (('and' | '&&') arguments+=not)*
;
not
: (notKeyword=('not' | '!'))? operand=comparison
;
comparison
: first=additive (operations+=comparisonOperation remaining+=additive)*
;
comparisonOperation
: '=='
| '!='
| '<'
| 'lt'
| '>'
| 'gt'
| '<='
| 'loe'
| '>='
| 'goe'
;
additive
: arguments+=multiplicative (operations+=('+' | '-') arguments+=multiplicative)*
;
multiplicative
: arguments+=arithmetic (operations+=('*' | '/' | '%') arguments+=arithmetic)*
;
arithmetic
: '-' operand=arithmetic #trueArithmetic
| operand=path #arithmeticFallback
;
path
: '(' targetType=type ')' value=primitive #pathCast
| base=primitive navigations+=navigation* isInstance=instanceOf? #pathNavigated
;
navigation
: '.' id=IDENTIFIER (invoke='(' arguments=expressionList? ')')? #propertyNavigation
| '[' index=expression ']' #arrayNavigation
;
instanceOf
: 'instanceof' checkedType=genericType
;
primitive
: value=NUMBER #numberPrimitive
| value=STRING_LITERAL #stringPrimitive
| 'this' #thisPrimitive
| 'true' #truePrimitive
| 'false' #falsePrimitive
| 'null' #nullPrimitive
| functionName=IDENTIFIER '(' arguments=expressionList? ')' #functionCall
| id=IDENTIFIER #idPrimitive
| '(' value=expression ')' #parenthesized
;
expressionList
: expressions+=lambda (',' expressions+=lambda)*
;
type
: baseType=nonArrayType suffix=arraySuffix?
;
genericType
: baseType=qualifiedClassType suffix=arraySuffix?
;
arraySuffix
: (suffice+='[' ']')+
;
nonArrayType
: 'boolean' #booleanType
| 'char' #charType
| 'byte' #byteType
| 'short' #shortType
| 'int' #intType
| 'long' #longType
| 'float' #floatType
| 'double' #doubleType
| qualifiedClassType #classType
;
qualifiedClassType
: raw=rawClassType ('<' args=typeArguments '>')?
;
rawClassType
: fqnPart+=IDENTIFIER ('.' fqnPart+=IDENTIFIER)*
;
typeArguments
: types+=genericType (',' types+=genericType)*
;
|
Allow to use &&, || and ! operators in EL
|
Allow to use &&, || and ! operators in EL
|
ANTLR
|
apache-2.0
|
konsoletyper/teavm-flavour,konsoletyper/teavm-flavour
|
6e75fbe7dd3cc4ef3f7eddfe303c6a391ccf2434
|
mdx/mdx.g4
|
mdx/mdx.g4
|
grammar mdx;
mdx_statement
: (select_statement) EOF
;
select_statement
: (WITH formula_specification)? SELECT axis_specification_list? FROM cube_specification (WHERE slicer_specification)? cell_props?
;
formula_specification
: single_formula_specification +
;
single_formula_specification
: member_specification
| set_specification
;
set_specification
: SET set_name AS (QUOTE expression QUOTE | expression)
;
member_specification
: MEMBER member_name AS ((QUOTE value_expression QUOTE | value_expression) COMMA member_property_def_list?)
;
axis_specification_list
: axis_specification (COMMA axis_specification)*
;
member_property_def_list
: member_property_definition (COMMA member_property_definition)*
;
member_name
: compound_id
;
member_property_definition
: identifier EQ value_expression
;
set_name
: compound_id
;
compound_id
: identifier (DOT identifier)*
;
axis_specification
: (NON EMPTY)? expression dim_props? ON axis_name
;
axis_name
: identifier
;
dim_props
: DIMENSION? PROPERTIES property_list
;
property_list
: property (COMMA property)*
;
property
: compound_id
;
cube_specification
: cube_name
;
cube_name
: compound_id
;
slicer_specification
: expression
;
cell_props
: CELL? PROPERTIES cell_property_list
;
cell_property_list
: cell_property COMMA cell_property*
;
cell_property
: mandatory_cell_property
| provider_specific_cell_property
;
mandatory_cell_property
: CELL_ORDINAL
| VALUE
| FORMATTED_VALUE
;
provider_specific_cell_property
: identifier
;
expression
: value_expression (COLON value_expression)*
;
value_expression
: term5 (value_xor_expression | value_or_expression)*
;
value_xor_expression
: XOR term5
;
value_or_expression
: OR term5
;
term5
: term4 (AND term4)*
;
term4
: NOT term4
| term3
;
term3
: term2 (comp_op term2)*
;
term2
: term ((CONCAT | PLUS | MINUS) term)*
;
term
: factor ((SOLIDUS | ASTERISK) factor)*
;
factor
: MINUS value_expression_primary
| PLUS value_expression_primary
| value_expression_primary
;
function
: identifier LPAREN (exp_list)? RPAREN
;
value_expression_primary
: value_expression_primary0 (DOT (unquoted_identifier | quoted_identifier | amp_quoted_identifier | function))*
;
value_expression_primary0
: function
| (LPAREN exp_list RPAREN)
| (LBRACE (exp_list)? RBRACE)
| case_expression
| STRING
| NUMBER
| identifier
;
exp_list
: expression (COMMA expression)*
;
case_expression
: CASE (value_expression)? (when_list)? (ELSE value_expression)? END
;
when_list
: when_clause (when_clause)*
;
when_clause
: WHEN value_expression THEN value_expression
;
comp_op
: EQ
| NE
| LT
| GT
| LE
| GE
;
identifier
: (unquoted_identifier | quoted_identifier)
;
unquoted_identifier
: keyword
| ID
;
amp_quoted_identifier
: AMP_QUOTED_ID
;
quoted_identifier
: QUOTED_ID
;
keyword
: DIMENSION
| PROPERTIES
;
QUOTE
: '\''
;
ASTERISK
: '*'
;
COLON
: ':'
;
SEMICOLON
: ';'
;
COMMA
: ','
;
CONCAT
: '||'
;
DOT
: '.'
;
EQ
: '='
;
GE
: '>='
;
GT
: '>'
;
LBRACE
: '{'
;
LE
: '<='
;
LPAREN
: '('
;
LT
: '<'
;
MINUS
: '-'
;
NE
: '<>'
;
PLUS
: '+'
;
RBRACE
: '}'
;
RPAREN
: ')'
;
SOLIDUS
: '/'
;
AND
: 'AND'
;
AS
: 'AS'
;
CASE
: 'CASE'
;
CELL
: 'CELL'
;
CELL_ORDINAL
: 'CELL_ORDINAL'
;
CREATE
: 'CREATE'
;
DIMENSION
: 'DIMENSION'
;
ELSE
: 'ELSE'
;
EMPTY
: 'EMPTY'
;
END
: 'END'
;
FORMATTED_VALUE
: 'FORMATTED_VALUE'
;
FROM
: 'FROM'
;
GLOBAL
: 'GLOBAL'
;
MEMBER
: 'MEMBER'
;
NON
: 'NON'
;
NOT
: 'NOT'
;
ON
: 'ON'
;
OR
: 'OR'
;
PROPERTIES
: 'PROPERTIES'
;
SELECT
: 'SELECT'
;
SESSION
: 'SESSION'
;
SET
: 'SET'
;
THEN
: 'THEN'
;
VALUE
: 'VALUE'
;
WHEN
: 'WHEN'
;
WHERE
: 'WHERE'
;
XOR
: 'XOR'
;
WITH
: 'WITH'
;
NUMBER
: ('0' .. '9') +
;
F
: '0' .. '9' + '.' '0' .. '9'*
;
ID
: ('a' .. 'z' | 'A' .. 'Z' | '_' | '$') ('a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' | '$')*
;
AMP_QUOTED_ID
: '[&' (ID ((' ' | '\t') + ID)* | NUMBER) ']'
;
QUOTED_ID
: ('[' (ID ((' ' | '\t') + ID)* | NUMBER) ']')
;
STRING
: '"' (~ '"')* '"' | '\'' (~ '\'')* '\''
;
WS
: (' ' | '\t' | '\r' | '\f' | '\n') + -> skip
;
|
grammar mdx;
mdx_statement
: (select_statement) EOF
;
select_statement
: (WITH formula_specification)? SELECT axis_specification_list? FROM cube_specification (WHERE slicer_specification)? cell_props?
;
formula_specification
: single_formula_specification +
;
single_formula_specification
: member_specification
| set_specification
;
set_specification
: SET set_name AS (QUOTE expression QUOTE | expression)
;
member_specification
: MEMBER member_name AS ((QUOTE value_expression QUOTE | value_expression) COMMA member_property_def_list?)
;
axis_specification_list
: axis_specification (COMMA axis_specification)*
;
member_property_def_list
: member_property_definition (COMMA member_property_definition)*
;
member_name
: compound_id
;
member_property_definition
: identifier EQ value_expression
;
set_name
: compound_id
;
compound_id
: identifier (DOT identifier)*
;
axis_specification
: (NON EMPTY)? expression dim_props? ON axis_name
;
axis_name
: identifier
;
dim_props
: DIMENSION? PROPERTIES property_list
;
property_list
: property (COMMA property)*
;
property
: compound_id
;
cube_specification
: cube_name
;
cube_name
: compound_id
;
slicer_specification
: expression
;
cell_props
: CELL? PROPERTIES cell_property_list
;
cell_property_list
: cell_property (COMMA cell_property)*
;
cell_property
: mandatory_cell_property
| provider_specific_cell_property
;
mandatory_cell_property
: CELL_ORDINAL
| VALUE
| FORMATTED_VALUE
;
provider_specific_cell_property
: identifier
;
expression
: value_expression (COLON value_expression)*
;
value_expression
: term5 (value_xor_expression | value_or_expression)*
;
value_xor_expression
: XOR term5
;
value_or_expression
: OR term5
;
term5
: term4 (AND term4)*
;
term4
: NOT term4
| term3
;
term3
: term2 (comp_op term2)*
;
term2
: term ((CONCAT | PLUS | MINUS) term)*
;
term
: factor ((SOLIDUS | ASTERISK) factor)*
;
factor
: MINUS value_expression_primary
| PLUS value_expression_primary
| value_expression_primary
;
function
: identifier LPAREN (exp_list)? RPAREN
;
value_expression_primary
: value_expression_primary0 (DOT (unquoted_identifier | quoted_identifier | amp_quoted_identifier | function))*
;
value_expression_primary0
: function
| (LPAREN exp_list RPAREN)
| (LBRACE (exp_list)? RBRACE)
| case_expression
| STRING
| NUMBER
| identifier
;
exp_list
: expression (COMMA expression)*
;
case_expression
: CASE (value_expression)? (when_list)? (ELSE value_expression)? END
;
when_list
: when_clause (when_clause)*
;
when_clause
: WHEN value_expression THEN value_expression
;
comp_op
: EQ
| NE
| LT
| GT
| LE
| GE
;
identifier
: (unquoted_identifier | quoted_identifier)
;
unquoted_identifier
: keyword
| ID
;
amp_quoted_identifier
: AMP_QUOTED_ID
;
quoted_identifier
: QUOTED_ID
;
keyword
: DIMENSION
| PROPERTIES
;
QUOTE
: '\''
;
ASTERISK
: '*'
;
COLON
: ':'
;
SEMICOLON
: ';'
;
COMMA
: ','
;
CONCAT
: '||'
;
DOT
: '.'
;
EQ
: '='
;
GE
: '>='
;
GT
: '>'
;
LBRACE
: '{'
;
LE
: '<='
;
LPAREN
: '('
;
LT
: '<'
;
MINUS
: '-'
;
NE
: '<>'
;
PLUS
: '+'
;
RBRACE
: '}'
;
RPAREN
: ')'
;
SOLIDUS
: '/'
;
AND
: 'AND'
;
AS
: 'AS'
;
CASE
: 'CASE'
;
CELL
: 'CELL'
;
CELL_ORDINAL
: 'CELL_ORDINAL'
;
CREATE
: 'CREATE'
;
DIMENSION
: 'DIMENSION'
;
ELSE
: 'ELSE'
;
EMPTY
: 'EMPTY'
;
END
: 'END'
;
FORMATTED_VALUE
: 'FORMATTED_VALUE'
;
FROM
: 'FROM'
;
GLOBAL
: 'GLOBAL'
;
MEMBER
: 'MEMBER'
;
NON
: 'NON'
;
NOT
: 'NOT'
;
ON
: 'ON'
;
OR
: 'OR'
;
PROPERTIES
: 'PROPERTIES'
;
SELECT
: 'SELECT'
;
SESSION
: 'SESSION'
;
SET
: 'SET'
;
THEN
: 'THEN'
;
VALUE
: 'VALUE'
;
WHEN
: 'WHEN'
;
WHERE
: 'WHERE'
;
XOR
: 'XOR'
;
WITH
: 'WITH'
;
NUMBER
: ('0' .. '9') +
;
F
: '0' .. '9' + '.' '0' .. '9'*
;
ID
: ('a' .. 'z' | 'A' .. 'Z' | '_' | '$') ('a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' | '$')*
;
AMP_QUOTED_ID
: '[&' (ID ((' ' | '\t') + ID)* | NUMBER) ']'
;
QUOTED_ID
: ('[' (ID ((' ' | '\t') + ID)* | NUMBER) ']')
;
STRING
: '"' (~ '"')* '"' | '\'' (~ '\'')* '\''
;
WS
: (' ' | '\t' | '\r' | '\f' | '\n') + -> skip
;
|
Update mdx.g4
|
Update mdx.g4
The comma is not mandatory, and you cannot have multiple properties after the comma. Rather, the statement can have multiple pairs of a comma and cell_property after the first cell_property
|
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
|
ed83f7750227f6f12a9d7f7e9db73d0038320ec8
|
src/main/antlr4/Config.g4
|
src/main/antlr4/Config.g4
|
grammar Config;
// [done] STRING lexer rule定义过于简单,不满足需求, 包括其中包含Quote(',")的String
// [done] nested bool expression中的字段引用
// [done] nested bool expression
// [done] Filter, Output 允许if else, 包含nested if..else
// [done] 允许key不包含双引号
// [done] 允许多行配置没有","分割
// [done] 允许plugin中不包含任何配置
// notes: lexer rule vs parser rule
// notes: don't let two lexer rule match the same token
import BoolExpr;
config
: COMMENT* 'input' input_block COMMENT* 'filter' filter_block COMMENT* 'output' output_block COMMENT* EOF
;
input_block
: '{' plugin_list '}'
;
filter_block
: '{' statement '}'
;
output_block
: '{' statement '}'
;
statement
: (plugin | if_statement | COMMENT)*
;
if_statement
: IF expression '{' statement '}' (ELSE IF expression '{' statement '}')* (ELSE '{' statement '}')?
;
plugin_list
: (plugin | COMMENT)*
;
plugin
: IDENTIFIER entries
// : plugin_name entries
;
entries
: '{' (pair | COMMENT)* '}'
;
// entries
// : '{' pair (','? pair)* '}'
// | '{' '}'
// ;
pair
: IDENTIFIER '=' value
;
array
: '[' value (',' value)* ']'
| '[' ']'
;
value
: DECIMAL
| QUOTED_STRING
// | entries
| array
| TRUE
| FALSE
| NULL
;
COMMENT
: '#' ~( '\r' | '\n' )* -> skip
;
// double and single quoted string support
fragment BSLASH : '\\';
fragment DQUOTE : '"';
fragment SQUOTE : '\'';
fragment DQ_STRING_ESC : BSLASH ["\\/bfnrt] ;
fragment SQ_STRING_ESC : BSLASH ['\\/bfnrt] ;
fragment DQ_STRING : DQUOTE (DQ_STRING_ESC | ~["\\])* DQUOTE ;
fragment SQ_STRING : SQUOTE (SQ_STRING_ESC | ~['\\])* SQUOTE ;
QUOTED_STRING : DQ_STRING | SQ_STRING ;
NULL
: 'null'
;
WS
: [ \t\n\r]+ -> skip
;
|
grammar Config;
// [done] STRING lexer rule定义过于简单,不满足需求, 包括其中包含Quote(',")的String
// [done] nested bool expression中的字段引用
// [done] nested bool expression
// [done] Filter, Output 允许if else, 包含nested if..else
// [done] 允许key不包含双引号
// [done] 允许多行配置没有","分割
// [done] 允许plugin中不包含任何配置
// notes: lexer rule vs parser rule
// notes: don't let two lexer rule match the same token
import BoolExpr;
config
: COMMENT* 'input' input_block COMMENT* 'filter' filter_block COMMENT* 'output' output_block COMMENT* EOF
;
input_block
: '{' (plugin | COMMENT)* '}'
;
filter_block
: '{' statement '}'
;
output_block
: '{' statement '}'
;
statement
: (plugin | if_statement | COMMENT)*
;
if_statement
: IF expression '{' statement '}' (ELSE IF expression '{' statement '}')* (ELSE '{' statement '}')?
;
plugin
: IDENTIFIER entries
// : plugin_name entries
;
entries
: '{' (pair | COMMENT)* '}'
;
// entries
// : '{' pair (','? pair)* '}'
// | '{' '}'
// ;
pair
: IDENTIFIER '=' value
;
array
: '[' value (',' value)* ']'
| '[' ']'
;
value
: DECIMAL
| QUOTED_STRING
// | entries
| array
| TRUE
| FALSE
| NULL
;
COMMENT
: '#' ~( '\r' | '\n' )* -> skip
;
// double and single quoted string support
fragment BSLASH : '\\';
fragment DQUOTE : '"';
fragment SQUOTE : '\'';
fragment DQ_STRING_ESC : BSLASH ["\\/bfnrt] ;
fragment SQ_STRING_ESC : BSLASH ['\\/bfnrt] ;
fragment DQ_STRING : DQUOTE (DQ_STRING_ESC | ~["\\])* DQUOTE ;
fragment SQ_STRING : SQUOTE (SQ_STRING_ESC | ~['\\])* SQUOTE ;
QUOTED_STRING : DQ_STRING | SQ_STRING ;
NULL
: 'null'
;
WS
: [ \t\n\r]+ -> skip
;
|
remove plugin_list parser rule
|
remove plugin_list parser rule
|
ANTLR
|
apache-2.0
|
InterestingLab/waterdrop,InterestingLab/waterdrop
|
6091635ebb8557e5ba42dff2832469292680a876
|
sharding-core/sharding-core-parse/sharding-core-parse-sqlserver/src/main/antlr4/imports/sqlserver/BaseRule.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-sqlserver/src/main/antlr4/imports/sqlserver/BaseRule.g4
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar BaseRule;
import Keyword, Symbol, Literals;
schemaName
: IDENTIFIER_
;
tableName
: (IDENTIFIER_ DOT_)? IDENTIFIER_
;
columnName
: IDENTIFIER_
;
collationName
: STRING_ | IDENTIFIER_
;
indexName
: IDENTIFIER_
;
alias
: IDENTIFIER_
;
dataTypeLength
: LP_ (NUMBER_ (COMMA_ NUMBER_)?)? RP_
;
primaryKey
: PRIMARY? KEY
;
columnNames
: LP_ columnNameWithSort (COMMA_ columnNameWithSort)* RP_
;
exprs
: expr (COMMA_ expr)*
;
exprList
: LP_ exprs RP_
;
expr
: expr AND expr
| expr AND_ expr
| expr XOR expr
| LP_ expr RP_
| NOT expr
| NOT_ expr
| expr OR expr
| expr OR_ expr
| booleanPrimary
| exprRecursive
;
exprRecursive
: matchNone
;
booleanPrimary
: booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL)
| booleanPrimary SAFE_EQ_ predicate
| booleanPrimary comparisonOperator predicate
| booleanPrimary comparisonOperator (ALL | ANY) subquery
| predicate
;
comparisonOperator
: EQ_
| GTE_
| GT_
| LTE_
| LT_
| NEQ_
;
predicate
: bitExpr NOT? IN subquery
| bitExpr NOT? IN LP_ simpleExpr (COMMA_ simpleExpr)* RP_
| bitExpr NOT? BETWEEN simpleExpr AND predicate
| bitExpr SOUNDS LIKE simpleExpr
| bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)*
| bitExpr NOT? REGEXP simpleExpr
| bitExpr
;
bitExpr
: bitExpr VERTICAL_BAR_ bitExpr
| bitExpr AMPERSAND_ bitExpr
| bitExpr SIGNED_LEFT_SHIFT_ bitExpr
| bitExpr SIGNED_RIGHT_SHIFT_ bitExpr
| bitExpr PLUS_ bitExpr
| bitExpr MINUS_ bitExpr
| bitExpr ASTERISK_ bitExpr
| bitExpr SLASH_ bitExpr
| bitExpr MOD bitExpr
| bitExpr MOD_ bitExpr
| bitExpr CARET_ bitExpr
| bitExpr PLUS_ intervalExpr
| bitExpr MINUS_ intervalExpr
| simpleExpr
;
simpleExpr
: functionCall
| literal
| columnName
| simpleExpr collateClause
//| param_marker
| variable
| simpleExpr AND_ simpleExpr
| PLUS_ simpleExpr
| MINUS_ simpleExpr
| TILDE_ simpleExpr
| NOT_ simpleExpr
| BINARY simpleExpr
| exprList
| ROW exprList
| subquery
| EXISTS subquery
// | (identifier_ expr)
//| match_expr
| caseExpress
| intervalExpr
| privateExprOfDb
;
functionCall
: IDENTIFIER_ LP_ distinct? (exprs | ASTERISK_)? RP_
;
distinct
: DISTINCT
;
intervalExpr
: matchNone
;
caseExpress
: matchNone
;
privateExprOfDb
: windowedFunction | atTimeZoneExpr | castExpr | convertExpr
;
variable
: matchNone
;
literal
: question
| number
| TRUE
| FALSE
| NULL
| LBE_ IDENTIFIER_ STRING_ RBE_
| HEX_DIGIT_
| string
| IDENTIFIER_ STRING_ collateClause?
| (DATE | TIME | TIMESTAMP) STRING_
| IDENTIFIER_? BIT_NUM_ collateClause?
;
question
: QUESTION_
;
number
: NUMBER_
;
string
: STRING_
;
subquery
: matchNone
;
collateClause
: matchNone
;
orderByClause
: ORDER BY orderByExpr (COMMA_ orderByExpr)*
;
orderByItem
: (columnName | number | expr) (ASC | DESC)?
;
asterisk
: ASTERISK_
;
dataType
: dataTypeName_ (dataTypeLength | LP_ MAX RP_ | LP_ (CONTENT | DOCUMENT)? ignoredIdentifier_ RP_)?
;
dataTypeName_
: IDENTIFIER_
;
atTimeZoneExpr
: IDENTIFIER_ (WITH TIME ZONE)? STRING_
;
castExpr
: CAST LP_ expr AS dataType (LP_ NUMBER_ RP_)? RP_
;
convertExpr
: CONVERT (dataType (LP_ NUMBER_ RP_)? COMMA_ expr (COMMA_ NUMBER_)?)
;
windowedFunction
: functionCall overClause
;
overClause
: OVER LP_ partitionByClause? orderByClause? rowRangeClause? RP_
;
partitionByClause
: PARTITION BY expr (COMMA_ expr)*
;
orderByExpr
: expr (COLLATE collationName)? (ASC | DESC)?
;
rowRangeClause
: (ROWS | RANGE) windowFrameExtent
;
windowFrameExtent
: windowFramePreceding | windowFrameBetween
;
windowFrameBetween
: BETWEEN windowFrameBound AND windowFrameBound
;
windowFrameBound
: windowFramePreceding | windowFrameFollowing
;
windowFramePreceding
: UNBOUNDED PRECEDING | NUMBER_ PRECEDING | CURRENT ROW
;
windowFrameFollowing
: UNBOUNDED FOLLOWING | NUMBER_ FOLLOWING | CURRENT ROW
;
columnNameWithSort
: columnName (ASC | DESC)?
;
indexOption
: FILLFACTOR EQ_ NUMBER_
| eqOnOffOption
| (COMPRESSION_DELAY | MAX_DURATION) eqTime
| MAXDOP EQ_ NUMBER_
| compressionOption onPartitionClause?
;
compressionOption
: DATA_COMPRESSION EQ_ (NONE | ROW | PAGE | COLUMNSTORE | COLUMNSTORE_ARCHIVE)
;
eqTime
: EQ_ NUMBER_ (MINUTES)?
;
eqOnOffOption
: eqKey eqOnOff
;
eqKey
: PAD_INDEX
| SORT_IN_TEMPDB
| IGNORE_DUP_KEY
| STATISTICS_NORECOMPUTE
| STATISTICS_INCREMENTAL
| DROP_EXISTING
| ONLINE
| RESUMABLE
| ALLOW_ROW_LOCKS
| ALLOW_PAGE_LOCKS
| COMPRESSION_DELAY
| SORT_IN_TEMPDB
;
eqOnOff
: EQ_ (ON | OFF)
;
onPartitionClause
: ON PARTITIONS LP_ partitionExpressions RP_
;
partitionExpressions
: partitionExpression (COMMA_ partitionExpression)*
;
partitionExpression
: NUMBER_ | numberRange
;
numberRange
: NUMBER_ TO NUMBER_
;
lowPriorityLockWait
: WAIT_AT_LOW_PRIORITY LP_ MAX_DURATION EQ_ NUMBER_ (MINUTES)? COMMA_ ABORT_AFTER_WAIT EQ_ (NONE | SELF | BLOCKERS) RP_
;
onLowPriorLockWait
: ON (LP_ lowPriorityLockWait RP_)?
;
ignoredIdentifier_
: IDENTIFIER_
;
ignoredIdentifiers_
: ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*
;
matchNone
: 'Default does not match anything'
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar BaseRule;
import Keyword, Symbol, Literals;
schemaName
: IDENTIFIER_
;
tableName
: (IDENTIFIER_ DOT_)? IDENTIFIER_
;
columnName
: IDENTIFIER_
;
collationName
: STRING_ | IDENTIFIER_
;
indexName
: IDENTIFIER_
;
alias
: IDENTIFIER_
;
dataTypeLength
: LP_ (NUMBER_ (COMMA_ NUMBER_)?)? RP_
;
primaryKey
: PRIMARY? KEY
;
columnNames
: LP_ columnNameWithSort (COMMA_ columnNameWithSort)* RP_
;
tableNames
: tableName (COMMA_ tableName)*
;
exprs
: expr (COMMA_ expr)*
;
exprList
: LP_ exprs RP_
;
expr
: expr AND expr
| expr AND_ expr
| expr XOR expr
| LP_ expr RP_
| NOT expr
| NOT_ expr
| expr OR expr
| expr OR_ expr
| booleanPrimary
| exprRecursive
;
exprRecursive
: matchNone
;
booleanPrimary
: booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL)
| booleanPrimary SAFE_EQ_ predicate
| booleanPrimary comparisonOperator predicate
| booleanPrimary comparisonOperator (ALL | ANY) subquery
| predicate
;
comparisonOperator
: EQ_
| GTE_
| GT_
| LTE_
| LT_
| NEQ_
;
predicate
: bitExpr NOT? IN subquery
| bitExpr NOT? IN LP_ simpleExpr (COMMA_ simpleExpr)* RP_
| bitExpr NOT? BETWEEN simpleExpr AND predicate
| bitExpr SOUNDS LIKE simpleExpr
| bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)*
| bitExpr NOT? REGEXP simpleExpr
| bitExpr
;
bitExpr
: bitExpr VERTICAL_BAR_ bitExpr
| bitExpr AMPERSAND_ bitExpr
| bitExpr SIGNED_LEFT_SHIFT_ bitExpr
| bitExpr SIGNED_RIGHT_SHIFT_ bitExpr
| bitExpr PLUS_ bitExpr
| bitExpr MINUS_ bitExpr
| bitExpr ASTERISK_ bitExpr
| bitExpr SLASH_ bitExpr
| bitExpr MOD bitExpr
| bitExpr MOD_ bitExpr
| bitExpr CARET_ bitExpr
| bitExpr PLUS_ intervalExpr
| bitExpr MINUS_ intervalExpr
| simpleExpr
;
simpleExpr
: functionCall
| literal
| columnName
| simpleExpr collateClause
//| param_marker
| variable
| simpleExpr AND_ simpleExpr
| PLUS_ simpleExpr
| MINUS_ simpleExpr
| TILDE_ simpleExpr
| NOT_ simpleExpr
| BINARY simpleExpr
| exprList
| ROW exprList
| subquery
| EXISTS subquery
// | (identifier_ expr)
//| match_expr
| caseExpress
| intervalExpr
| privateExprOfDb
;
functionCall
: IDENTIFIER_ LP_ distinct? (exprs | ASTERISK_)? RP_
;
distinct
: DISTINCT
;
intervalExpr
: matchNone
;
caseExpress
: matchNone
;
privateExprOfDb
: windowedFunction | atTimeZoneExpr | castExpr | convertExpr
;
variable
: matchNone
;
literal
: question
| number
| TRUE
| FALSE
| NULL
| LBE_ IDENTIFIER_ STRING_ RBE_
| HEX_DIGIT_
| string
| IDENTIFIER_ STRING_ collateClause?
| (DATE | TIME | TIMESTAMP) STRING_
| IDENTIFIER_? BIT_NUM_ collateClause?
;
question
: QUESTION_
;
number
: NUMBER_
;
string
: STRING_
;
subquery
: matchNone
;
collateClause
: matchNone
;
orderByClause
: ORDER BY orderByExpr (COMMA_ orderByExpr)*
;
orderByItem
: (columnName | number | expr) (ASC | DESC)?
;
asterisk
: ASTERISK_
;
dataType
: dataTypeName_ (dataTypeLength | LP_ MAX RP_ | LP_ (CONTENT | DOCUMENT)? ignoredIdentifier_ RP_)?
;
dataTypeName_
: IDENTIFIER_
;
atTimeZoneExpr
: IDENTIFIER_ (WITH TIME ZONE)? STRING_
;
castExpr
: CAST LP_ expr AS dataType (LP_ NUMBER_ RP_)? RP_
;
convertExpr
: CONVERT (dataType (LP_ NUMBER_ RP_)? COMMA_ expr (COMMA_ NUMBER_)?)
;
windowedFunction
: functionCall overClause
;
overClause
: OVER LP_ partitionByClause? orderByClause? rowRangeClause? RP_
;
partitionByClause
: PARTITION BY expr (COMMA_ expr)*
;
orderByExpr
: expr (COLLATE collationName)? (ASC | DESC)?
;
rowRangeClause
: (ROWS | RANGE) windowFrameExtent
;
windowFrameExtent
: windowFramePreceding | windowFrameBetween
;
windowFrameBetween
: BETWEEN windowFrameBound AND windowFrameBound
;
windowFrameBound
: windowFramePreceding | windowFrameFollowing
;
windowFramePreceding
: UNBOUNDED PRECEDING | NUMBER_ PRECEDING | CURRENT ROW
;
windowFrameFollowing
: UNBOUNDED FOLLOWING | NUMBER_ FOLLOWING | CURRENT ROW
;
columnNameWithSort
: columnName (ASC | DESC)?
;
indexOption
: FILLFACTOR EQ_ NUMBER_
| eqOnOffOption
| (COMPRESSION_DELAY | MAX_DURATION) eqTime
| MAXDOP EQ_ NUMBER_
| compressionOption onPartitionClause?
;
compressionOption
: DATA_COMPRESSION EQ_ (NONE | ROW | PAGE | COLUMNSTORE | COLUMNSTORE_ARCHIVE)
;
eqTime
: EQ_ NUMBER_ (MINUTES)?
;
eqOnOffOption
: eqKey eqOnOff
;
eqKey
: PAD_INDEX
| SORT_IN_TEMPDB
| IGNORE_DUP_KEY
| STATISTICS_NORECOMPUTE
| STATISTICS_INCREMENTAL
| DROP_EXISTING
| ONLINE
| RESUMABLE
| ALLOW_ROW_LOCKS
| ALLOW_PAGE_LOCKS
| COMPRESSION_DELAY
| SORT_IN_TEMPDB
;
eqOnOff
: EQ_ (ON | OFF)
;
onPartitionClause
: ON PARTITIONS LP_ partitionExpressions RP_
;
partitionExpressions
: partitionExpression (COMMA_ partitionExpression)*
;
partitionExpression
: NUMBER_ | numberRange
;
numberRange
: NUMBER_ TO NUMBER_
;
lowPriorityLockWait
: WAIT_AT_LOW_PRIORITY LP_ MAX_DURATION EQ_ NUMBER_ (MINUTES)? COMMA_ ABORT_AFTER_WAIT EQ_ (NONE | SELF | BLOCKERS) RP_
;
onLowPriorLockWait
: ON (LP_ lowPriorityLockWait RP_)?
;
ignoredIdentifier_
: IDENTIFIER_
;
ignoredIdentifiers_
: ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*
;
matchNone
: 'Default does not match anything'
;
|
add tableNames
|
add tableNames
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
|
fd02effce9930b1a320c915f999755d61463a7b0
|
parsers/antlr/lect.g4
|
parsers/antlr/lect.g4
|
grammar lect;
// ----- Start symbols for the grammar.
// A single interactive statement, entered in REPL prompt.
// Note the extra line break to terminate.
single_input
: LINE_BREAK | simple_stmt | compound_stmt LINE_BREAK
;
// A single file of code.
file_input
: (LINE_BREAK | stmt)* ENDMARKER
;
// An expression passed to the eval() function.
eval_input
: testlist LINE_BREAK* ENDMARKER
;
stmt
: simple_stmt | compound_stmt
;
simple_stmt
: small_stmt (';' small_stmt)* ';' LINE_BREAK
;
small_stmt
: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | assert_stmt)
;
expr_stmt
: testlist (augassign (yield_expr|testlist) | (ASSIGN (yield_expr|testlist))*)
;
augassign
: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '**=' | '//=')
;
// For normal assignments, additional restrictions enforced by the interpreter
print_stmt
: 'print' ( ( test (',' test)* ',' )? | '>>' test ( (',' test)+ ','? )? )
;
assert_stmt
: ASSERT test (',' test)?
;
del_stmt
: DEL exprlist
;
pass_stmt
: PASS
;
flow_stmt
: break_stmt | continue_stmt | return_stmt | throw_stmt | yield_stmt
;
break_stmt
: BREAK
;
continue_stmt
: CONTINUE
;
return_stmt
: RETURN testlist?
;
yield_stmt
: yield_expr
;
throw_stmt
: THROW (test (',' test (',' test))?)?
;
// URLs refer to directory structure within sandbox or component, or to
// a URL on the web from which a component can be downloaded.
url
: protocol IDENTIFIER ('/' IDENTIFIER)*?
;
protocol
: ('@component' | '@sandbox' | 'http' 's'?) '://'
;
import_stmt
: IMPORT url (AS IDENTIFIER)?
;
compound_stmt
: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef
;
if_stmt
: IF test ':' suite (ELIF test ':' suite)* (ELSE ':' suite)?
;
while_stmt
: WHILE test ':' suite
;
for_stmt
: FOR exprlist IN testlist ':' suite
;
try_stmt
: TRY ':' suite (except_clause ':' 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
: CATCH (test ((AS | ',') test)?)?
;
suite
: simple_stmt | LINE_BREAK INDENT stmt+ DEDENT
;
// A "test" is an expression that might or might not be wrapped in boolean
// logic. The boolean operator precedence is reflected in how the nesting
// is done here.
test
: or_test (IF or_test ELSE test)? | lambdef
;
// OR is the lowest-priority boolean expr; AND is bound
// more tightly.
or_test
: and_test (OR and_test)*
;
// AND has a higher priority than OR, but lower than NOT.
and_test
: not_test (AND not_test)*
;
// NOT has a higher priority than AND.
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 '`' | IDENTIFIER | number | STR_LITERAL+)
;
listmaker
: test ( list_for | (',' test)* ','? )
;
testlist_comp
: test ( comp_for | (',' test)* ','? )
;
// A mark is something like:
// +pure
// +text(1, 50)
// Marks can appear between identifiers and their values.
mark
: ('-' | '+') IDENTIFIER ('(' arglist ')')?
;
marks
: mark+
;
funcdef
: FUNC IDENTIFIER ':' LINE_BREAK suite
;
// We recognize function invocations by the presence of args at the end
// of an identifier.
args
: '(' arglist? ')'
;
arglist
: arg (',' arg)*
;
// An arg is something passed to a called function. Do not confuse with a
// param, which is the definition of what might be passed.
arg
: (IDENTIFIER ASSIGN)? test
;
lambdef
: 'lambda' 'FIXME' ':' test
;
trailer
: '(' arglist? ')' | '[' subscriptlist ']' | '.' IDENTIFIER
;
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 IDENTIFIER ':' suite
;
// The reason that keywords are test nodes instead of IDENTIFIER is that using IDENTIFIER
// results in an ambiguity. ast.c makes sure it's a IDENTIFIER.
argument
: test comp_for? | test ASSIGN test
;
list_iter
: list_for | list_if
;
list_for
: FOR exprlist IN testlist list_iter?
;
list_if
: IF test list_iter?
;
comp_iter
: comp_for | comp_if
;
comp_for
: FOR exprlist IN or_test comp_iter?
;
comp_if
: IF test comp_iter?
;
testlist1
: test (',' test)*
;
yield_expr
: YIELD testlist?
;
number
: INTEGER_LITERAL | FLOAT_LITERAL
;
INTEGER_LITERAL
: DECIMAL_INTEGER_LITERAL | HEX_INTEGER_LITERAL | OCT_INTEGER_LITERAL | BINARY_INTEGER_LITERAL
;
fragment
DECIMAL_INTEGER_LITERAL
: DECIMAL_NUMERAL INTEGER_TYPE_SUFFIX?
;
fragment
HEX_INTEGER_LITERAL
: HEX_NUMERAL INTEGER_TYPE_SUFFIX?
;
fragment
OCT_INTEGER_LITERAL
: OCT_NUMERAL INTEGER_TYPE_SUFFIX?
;
fragment
BINARY_INTEGER_LITERAL
: BIN_NUMERAL INTEGER_TYPE_SUFFIX?
;
// Allow all integer literals to have "L" at the end
// to force 64-bit.
fragment
INTEGER_TYPE_SUFFIX
: [lL]
;
fragment
DECIMAL_NUMERAL
: '0' | NON_ZERO_DIGIT (DIGITS? | UNDERSCORES DIGITS)
;
fragment
DIGITS
: DIGIT (DIGITS_AND_UNDERSCORES? DIGIT)?
;
fragment
DIGIT
: '0' | NON_ZERO_DIGIT
;
fragment
NON_ZERO_DIGIT
: [1-9]
;
fragment
DIGITS_AND_UNDERSCORES
: DIGIT_OR_UNDERSCORE+
;
fragment
DIGIT_OR_UNDERSCORE
: DIGIT | '_'
;
// Like java, allow _ as a separator or grouping char between digits
// for those who'd like improved readability of numeric literals.
fragment
UNDERSCORES
: '_'+
;
fragment
HEX_NUMERAL
: '0' [xX] HEX_DIGITS
;
fragment
HEX_DIGITS
: HEX_DIGIT (HEX_DIGITS_AND_UNDERSCORES? HEX_DIGIT)?
;
fragment
HEX_DIGIT
: [0-9a-fA-F]
;
fragment
HEX_DIGITS_AND_UNDERSCORES
: HEX_DIGIT_OR_UNDERSCORE+
;
fragment
HEX_DIGIT_OR_UNDERSCORE
: HEX_DIGIT | '_'
;
fragment
OCT_NUMERAL
: '0' UNDERSCORES? OCT_DIGITS
;
fragment
OCT_DIGITS
: OCT_DIGIT (OCT_DIGITS_AND_UNDERSCORES? OCT_DIGIT)?
;
fragment
OCT_DIGIT
: [0-7]
;
fragment
OCT_DIGITS_AND_UNDERSCORES
: OCT_DIGIT_OR_UNDERSCORE+
;
fragment
OCT_DIGIT_OR_UNDERSCORE
: OCT_DIGIT | '_'
;
fragment
BIN_NUMERAL
: '0' [bB] BIN_DIGITS
;
fragment
BIN_DIGITS
: BIN_DIGIT (BIN_DIGIT_AND_UNDERSCORES? BIN_DIGIT)?
;
fragment
BIN_DIGIT
: [01]
;
fragment
BIN_DIGIT_AND_UNDERSCORES
: BIN_DIGIT_OR_UNDERSCORE+
;
fragment
BIN_DIGIT_OR_UNDERSCORE
: BIN_DIGIT | '_'
;
// 3.10.2 Floating-Point Literals
FLOAT_LITERAL
: DECIMAL_FLOAT_LITERAL | HEX_FLOAT_LITERAL
;
fragment
DECIMAL_FLOAT_LITERAL
: DIGITS '.' DIGITS? EXPONENT_PART? FLOAT_TYPE_SUFFIX?
| '.' DIGITS EXPONENT_PART? FLOAT_TYPE_SUFFIX?
| DIGITS EXPONENT_PART FLOAT_TYPE_SUFFIX?
| DIGITS FLOAT_TYPE_SUFFIX
;
fragment
EXPONENT_PART
: EXPONENT_INDICATOR SIGNED_INTEGER
;
fragment
EXPONENT_INDICATOR
: [eE]
;
fragment
SIGNED_INTEGER
: SIGN? DIGITS
;
fragment
SIGN
: [+-]
;
fragment
FLOAT_TYPE_SUFFIX
: [fFdD]
;
fragment
HEX_FLOAT_LITERAL
: HEX_SIGNIFICAND BINARY_EXPONENT FLOAT_TYPE_SUFFIX?
;
fragment
HEX_SIGNIFICAND
: HEX_NUMERAL '.'?
| '0' [xX] HEX_DIGITS? '.' HEX_DIGITS
;
fragment
BINARY_EXPONENT
: BINARY_EXPONENT_INDICATOR SIGNED_INTEGER
;
fragment
BINARY_EXPONENT_INDICATOR
: [pP]
;
IDENTIFIER
: [a-z_][a-z_0-9]*
;
FOR: 'for';
IF: 'if';
CLASS: 'class';
CHAR_LITERAL
: '\'' ONE_CHAR '\''
| '\'' ESCAPE_SEQ '\''
;
fragment
ONE_CHAR
: ~['\\]
;
// String Literals
STR_LITERAL
: '"' STR_CHARS? '"'
;
fragment
STR_CHARS
: STR_CHAR+
;
fragment
STR_CHAR
: ~["\\] | ESCAPE_SEQ
;
// 3.10.6 Escape Sequences for Character and String Literals
fragment
ESCAPE_SEQ
: '\\' [btnfr"'\\]
| UNI_ESCAPE
;
fragment
UNI_ESCAPE
: '\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
;
fragment
ZERO_TO_3
: [0-3]
;
// Separators
LPAREN : '(';
RPAREN : ')';
LBRACE : '{';
RBRACE : '}';
LBRACK : '[';
RBRACK : ']';
SEMI : ';';
COMMA : ',';
DOT : '.';
// Operators
ASSIGN : '=';
GT : '>';
LT : '<';
BANG : '!';
TILDE : '~';
QUESTION : '?';
COLON : ':';
EQUAL : '==';
LE : '<=';
GE : '>=';
NOTEQUAL : '!=';
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 : '>>>=';
WS // only within a statement
: [ \t]+ -> skip
;
LINE_BREAK // statement separator in most cases
: [\r\n\u000C]
;
COMMENT
: '##' .*? '##' -> skip
;
LINE_COMMENT
: '#' ~[\r\n]* -> skip
;
// Keywords
BREAK: 'break';
RETURN: 'return';
IMPORT: 'import';
WHILE: 'while';
ELSE: 'else';
IN: 'in';
TRY: 'try';
ELIF: 'elif';
FINALLY: 'finally';
WITH: 'with';
AS: 'as';
CATCH: 'catch';
YIELD: 'yield';
TRUE: 'true';
FALSE: 'false';
NULL: 'null';
AND: 'and';
OR: 'or';
NOT: 'not';
ASSERT: 'assert';
DEL: 'del';
PASS: 'pass';
CONTINUE: 'continue';
THROW: 'throw';
FUNC: 'func';
|
grammar lect;
// ----- Start symbols for the grammar.
// A single interactive statement, entered in REPL prompt.
// Note the extra line break to terminate.
single_input
: LINE_BREAK | simple_stmt | compound_stmt LINE_BREAK
;
// A single file of code.
file_input
: (LINE_BREAK | stmt)* ENDMARKER
;
// An expression passed to the eval() function.
eval_input
: testlist LINE_BREAK* ENDMARKER
;
stmt
: simple_stmt | compound_stmt
;
simple_stmt
: small_stmt (';' small_stmt)* ';' LINE_BREAK
;
small_stmt
: (expr_stmt | print_stmt | stub_stmt | pass_stmt | flow_stmt | import_stmt | assert_stmt)
;
expr_stmt
: testlist (augassign (yield_expr|testlist) | (ASSIGN (yield_expr|testlist))*)
;
augassign
: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '**=' | '//=')
;
// For normal assignments, additional restrictions enforced by the interpreter
print_stmt
: 'print' ( ( test (',' test)* ',' )? | '>>' test ( (',' test)+ ','? )? )
;
assert_stmt
: ASSERT test // FIXME: allow explanatory string in case of failure?
;
pseudocode_stmt // FIXME: figure out where to allow pseudocode; probably in func body...
: sentence '.'
;
sentence
: CAPITAL_LETTER .*? '.'
;
fragment
CAPITAL_LETTER
: [A-Z]
;
//FIXME: line continuations?
stub_stmt
: STUB
;
pass_stmt
: PASS
;
flow_stmt
: break_stmt | continue_stmt | return_stmt | throw_stmt | yield_stmt
;
break_stmt
: BREAK
;
continue_stmt
: CONTINUE
;
return_stmt
: RETURN testlist?
;
yield_stmt
: yield_expr
;
throw_stmt
: THROW test?
;
// URLs refer to directory structure within sandbox or component, or to
// a URL on the web from which a component can be downloaded.
url
: protocol IDENTIFIER ('/' IDENTIFIER)*?
;
protocol
: ('@component' | '@sandbox' | 'http' 's'?) '://'
;
import_stmt
: IMPORT url (AS IDENTIFIER)?
;
compound_stmt
: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef
;
if_stmt
: IF test ':' suite (ELIF test ':' suite)* (ELSE ':' suite)?
;
while_stmt
: WHILE test ':' suite
;
for_stmt
: FOR exprlist IN testlist ':' suite
;
try_stmt
: TRY ':' suite (except_clause ':' 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
: CATCH (test ((AS | ',') test)?)?
;
suite
: simple_stmt | LINE_BREAK INDENT stmt+ DEDENT
;
// A "test" is an expression that might or might not be wrapped in boolean
// logic. The boolean operator precedence is reflected in how the nesting
// is done here.
test
: or_test (IF or_test ELSE test)? | lambdef
;
// OR is the lowest-priority boolean expr; AND is bound
// more tightly.
or_test
: and_test (OR and_test)*
;
// AND has a higher priority than OR, but lower than NOT.
and_test
: not_test (AND not_test)*
;
// NOT has a higher priority than AND.
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 '`' | IDENTIFIER | number | STR_LITERAL+)
;
listmaker
: test ( list_for | (',' test)* ','? )
;
testlist_comp
: test ( comp_for | (',' test)* ','? )
;
// A mark is something like:
// +pure
// +text(1, 50)
// Marks can appear between identifiers and their values.
mark
: ('-' | '+') IDENTIFIER ('(' arglist ')')?
;
marks
: mark+
;
funcdef
: FUNC IDENTIFIER ':' LINE_BREAK suite
;
// We recognize function invocations by the presence of args at the end
// of an identifier.
args
: '(' arglist? ')'
;
arglist
: arg (',' arg)*
;
// An arg is something passed to a called function. Do not confuse with a
// param, which is the definition of what might be passed.
arg
: (IDENTIFIER ASSIGN)? test
;
lambdef
: 'lambda' 'FIXME' ':' test
;
trailer
: '(' arglist? ')' | '[' subscriptlist ']' | '.' IDENTIFIER
;
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 IDENTIFIER ':' suite
;
// The reason that keywords are test nodes instead of IDENTIFIER is that using IDENTIFIER
// results in an ambiguity. ast.c makes sure it's a IDENTIFIER.
argument
: test comp_for? | test ASSIGN test
;
list_iter
: list_for | list_if
;
list_for
: FOR exprlist IN testlist list_iter?
;
list_if
: IF test list_iter?
;
comp_iter
: comp_for | comp_if
;
comp_for
: FOR exprlist IN or_test comp_iter?
;
comp_if
: IF test comp_iter?
;
testlist1
: test (',' test)*
;
yield_expr
: YIELD testlist?
;
number
: INTEGER_LITERAL | FLOAT_LITERAL
;
INTEGER_LITERAL
: DECIMAL_INTEGER_LITERAL | HEX_INTEGER_LITERAL | OCT_INTEGER_LITERAL | BINARY_INTEGER_LITERAL
;
fragment
DECIMAL_INTEGER_LITERAL
: DECIMAL_NUMERAL INTEGER_TYPE_SUFFIX?
;
fragment
HEX_INTEGER_LITERAL
: HEX_NUMERAL INTEGER_TYPE_SUFFIX?
;
fragment
OCT_INTEGER_LITERAL
: OCT_NUMERAL INTEGER_TYPE_SUFFIX?
;
fragment
BINARY_INTEGER_LITERAL
: BIN_NUMERAL INTEGER_TYPE_SUFFIX?
;
// Allow all integer literals to have "L" at the end
// to force 64-bit.
fragment
INTEGER_TYPE_SUFFIX
: [lL]
;
fragment
DECIMAL_NUMERAL
: '0' | NON_ZERO_DIGIT (DIGITS? | UNDERSCORES DIGITS)
;
fragment
DIGITS
: DIGIT (DIGITS_AND_UNDERSCORES? DIGIT)?
;
fragment
DIGIT
: '0' | NON_ZERO_DIGIT
;
fragment
NON_ZERO_DIGIT
: [1-9]
;
fragment
DIGITS_AND_UNDERSCORES
: DIGIT_OR_UNDERSCORE+
;
fragment
DIGIT_OR_UNDERSCORE
: DIGIT | '_'
;
// Like java, allow _ as a separator or grouping char between digits
// for those who'd like improved readability of numeric literals.
fragment
UNDERSCORES
: '_'+
;
fragment
HEX_NUMERAL
: '0' [xX] HEX_DIGITS
;
fragment
HEX_DIGITS
: HEX_DIGIT (HEX_DIGITS_AND_UNDERSCORES? HEX_DIGIT)?
;
fragment
HEX_DIGIT
: [0-9a-fA-F]
;
fragment
HEX_DIGITS_AND_UNDERSCORES
: HEX_DIGIT_OR_UNDERSCORE+
;
fragment
HEX_DIGIT_OR_UNDERSCORE
: HEX_DIGIT | '_'
;
fragment
OCT_NUMERAL
: '0' UNDERSCORES? OCT_DIGITS
;
fragment
OCT_DIGITS
: OCT_DIGIT (OCT_DIGITS_AND_UNDERSCORES? OCT_DIGIT)?
;
fragment
OCT_DIGIT
: [0-7]
;
fragment
OCT_DIGITS_AND_UNDERSCORES
: OCT_DIGIT_OR_UNDERSCORE+
;
fragment
OCT_DIGIT_OR_UNDERSCORE
: OCT_DIGIT | '_'
;
fragment
BIN_NUMERAL
: '0' [bB] BIN_DIGITS
;
fragment
BIN_DIGITS
: BIN_DIGIT (BIN_DIGIT_AND_UNDERSCORES? BIN_DIGIT)?
;
fragment
BIN_DIGIT
: [01]
;
fragment
BIN_DIGIT_AND_UNDERSCORES
: BIN_DIGIT_OR_UNDERSCORE+
;
fragment
BIN_DIGIT_OR_UNDERSCORE
: BIN_DIGIT | '_'
;
// 3.10.2 Floating-Point Literals
FLOAT_LITERAL
: DECIMAL_FLOAT_LITERAL | HEX_FLOAT_LITERAL
;
fragment
DECIMAL_FLOAT_LITERAL
: DIGITS '.' DIGITS? EXPONENT_PART? FLOAT_TYPE_SUFFIX?
| '.' DIGITS EXPONENT_PART? FLOAT_TYPE_SUFFIX?
| DIGITS EXPONENT_PART FLOAT_TYPE_SUFFIX?
| DIGITS FLOAT_TYPE_SUFFIX
;
fragment
EXPONENT_PART
: EXPONENT_INDICATOR SIGNED_INTEGER
;
fragment
EXPONENT_INDICATOR
: [eE]
;
fragment
SIGNED_INTEGER
: SIGN? DIGITS
;
fragment
SIGN
: [+-]
;
fragment
FLOAT_TYPE_SUFFIX
: [fFdD]
;
fragment
HEX_FLOAT_LITERAL
: HEX_SIGNIFICAND BINARY_EXPONENT FLOAT_TYPE_SUFFIX?
;
fragment
HEX_SIGNIFICAND
: HEX_NUMERAL '.'?
| '0' [xX] HEX_DIGITS? '.' HEX_DIGITS
;
fragment
BINARY_EXPONENT
: BINARY_EXPONENT_INDICATOR SIGNED_INTEGER
;
fragment
BINARY_EXPONENT_INDICATOR
: [pP]
;
IDENTIFIER
: [a-z_][a-z_0-9]*
;
FOR: 'for';
IF: 'if';
CLASS: 'class';
CHAR_LITERAL
: '\'' ONE_CHAR '\''
| '\'' ESCAPE_SEQ '\''
;
fragment
ONE_CHAR
: ~['\\]
;
// String Literals
STR_LITERAL
: '"' STR_CHARS? '"'
;
fragment
STR_CHARS
: STR_CHAR+
;
fragment
STR_CHAR
: ~["\\] | ESCAPE_SEQ
;
// 3.10.6 Escape Sequences for Character and String Literals
fragment
ESCAPE_SEQ
: '\\' [btnfr"'\\]
| UNI_ESCAPE
;
fragment
UNI_ESCAPE
: '\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
;
fragment
ZERO_TO_3
: [0-3]
;
// Separators
LPAREN : '(';
RPAREN : ')';
LBRACE : '{';
RBRACE : '}';
LBRACK : '[';
RBRACK : ']';
SEMI : ';';
COMMA : ',';
DOT : '.';
// Operators
ASSIGN : '=';
GT : '>';
LT : '<';
BANG : '!';
TILDE : '~';
QUESTION : '?';
COLON : ':';
EQUAL : '==';
LE : '<=';
GE : '>=';
NOTEQUAL : '!=';
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 : '>>>=';
WS // only within a statement
: [ \t]+ -> skip
;
LINE_BREAK // statement separator in most cases
: [\r\n\u000C]
;
COMMENT
: '##' .*? '##' -> skip
;
LINE_COMMENT
: '#' ~[\r\n]* -> skip
;
// Keywords
BREAK: 'break';
RETURN: 'return';
IMPORT: 'import';
WHILE: 'while';
ELSE: 'else';
IN: 'in';
TRY: 'try';
ELIF: 'elif';
FINALLY: 'finally';
WITH: 'with';
AS: 'as';
CATCH: 'catch';
YIELD: 'yield';
TRUE: 'true';
FALSE: 'false';
NULL: 'null';
AND: 'and';
OR: 'or';
NOT: 'not';
ASSERT: 'assert';
STUB: 'stub';
CONTINUE: 'continue';
THROW: 'throw';
FUNC: 'func';
PASS: 'pass';
|
tweak grammar; add beginnings of support for pseudocode and stubbing
|
tweak grammar; add beginnings of support for pseudocode and stubbing
|
ANTLR
|
apache-2.0
|
dhh1128/lect,dhh1128/lect,dhh1128/lect
|
c5f473a3c492f8180e44e9136c82b6d72c01462d
|
cto/CtoParser.g4
|
cto/CtoParser.g4
|
/*
[The "BSD licence"]
Copyright (c) 2018 Mario Schroeder
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 Hyperledger Composer Modeling Language
https://hyperledger.github.io/composer/latest/reference/cto_language.html
*/
parser grammar CtoParser;
options { tokenVocab=CtoLexer; }
modelUnit
: namespaceDeclaration? importDeclaration* typeDeclaration* EOF
;
namespaceDeclaration
: NAMESPACE qualifiedName EOL?
;
importDeclaration
: IMPORT qualifiedName ('.' '*')?
;
typeDeclaration
: (assetDeclaration
| conceptDeclaration
| enumDeclaration
| participantDeclaration
| transactionDeclaration
| eventDeclaration)
;
classModifier
: decorator
| ABSTRACT
;
assetDeclaration
: classModifier*
ASSET IDENTIFIER
extendsOrIdentified
classBody
;
conceptDeclaration
: classModifier*
CONCEPT IDENTIFIER
(EXTENDS IDENTIFIER)?
classBody
;
enumDeclaration
: ENUM IDENTIFIER '{' enumConstant* '}';
enumConstant
: VAR IDENTIFIER;
eventDeclaration
: EVENT IDENTIFIER
classBody
;
participantDeclaration
: classModifier*
PARTICIPANT IDENTIFIER
extendsOrIdentified
classBody
;
transactionDeclaration
: classModifier*
TRANSACTION IDENTIFIER
classBody
;
extendsOrIdentified: ((EXTENDS IDENTIFIER) | identified);
identified: (IDENTIFIED IDENTIFIER);
classBody
: '{' classBodyDeclaration* '}';
classBodyDeclaration
: ';'
| fieldDeclaration
;
fieldDeclaration
: stringField identifier defaultString? regexDeclaration? OPTIONAL?
| booleanField identifier defaultBoolean? OPTIONAL?
| numericField identifier defaultNumber? rangeValidation? OPTIONAL?
| dateField identifier defaultDate? OPTIONAL?
| identifierField identifier
| reference identifier;
identifierField
: VAR IDENTIFIER (square)*;
numericField
: VAR numericPrimitive (square)*;
numericPrimitive
: DOUBLE
| INTEGER
| LONG
;
booleanField
: VAR BOOLEAN (square)*;
dateField
: VAR DATE_TIME (square)*;
defaultDate
: DEFAULT ASSIGN DATE_TIME_LITERAL;
regexDeclaration
: REGEX ASSIGN REGEX_EXPR;
stringField
: VAR STRING (square)*;
reference
: REF IDENTIFIER (square)*;
qualifiedName
: IDENTIFIER ('.' IDENTIFIER)*;
rangeValidation
: RANGE ASSIGN rangeDeclaration;
rangeDeclaration
: ('[' numberLiteral ',' ']')
| ('[' ',' numberLiteral ']')
| ('[' numberLiteral ',' numberLiteral ']');
defaultBoolean
: (DEFAULT ASSIGN BOOL_LITERAL);
defaultString
: (DEFAULT ASSIGN stringLiteral);
defaultNumber
: (DEFAULT ASSIGN numberLiteral);
identifier: IDENTIFIER | ASSET | PARTICIPANT;
literal
: numberLiteral
| stringLiteral
| BOOL_LITERAL
;
numberLiteral
: integerLiteral
| floatLiteral;
stringLiteral
: CHAR_LITERAL
| STRING_LITERAL
;
integerLiteral
: DECIMAL_LITERAL
| OCT_LITERAL
;
floatLiteral
: FLOAT_LITERAL;
decorator
: AT qualifiedName ('(' elementValuePair ')')?;
elementValuePair
: literal (',' literal)*;
square: '[' ']';
|
/*
[The "BSD licence"]
Copyright (c) 2018 Mario Schroeder
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 Hyperledger Composer Modeling Language
https://hyperledger.github.io/composer/latest/reference/cto_language.html
*/
parser grammar CtoParser;
options { tokenVocab=CtoLexer; }
modelUnit
: namespaceDeclaration? importDeclaration* typeDeclaration* EOF
;
namespaceDeclaration
: NAMESPACE qualifiedName
;
importDeclaration
: IMPORT qualifiedName ('.' '*')?
;
typeDeclaration
: (assetDeclaration
| conceptDeclaration
| enumDeclaration
| participantDeclaration
| transactionDeclaration
| eventDeclaration)
;
classModifier
: decorator
| ABSTRACT
;
assetDeclaration
: classModifier*
ASSET IDENTIFIER
extendsOrIdentified
classBody
;
conceptDeclaration
: classModifier*
CONCEPT IDENTIFIER
(EXTENDS IDENTIFIER)?
classBody
;
enumDeclaration
: ENUM IDENTIFIER '{' enumConstant* '}';
enumConstant
: VAR IDENTIFIER;
eventDeclaration
: EVENT IDENTIFIER
classBody
;
participantDeclaration
: classModifier*
PARTICIPANT IDENTIFIER
extendsOrIdentified
classBody
;
transactionDeclaration
: classModifier*
TRANSACTION IDENTIFIER
classBody
;
extendsOrIdentified: ((EXTENDS IDENTIFIER) | identified);
identified: (IDENTIFIED IDENTIFIER);
classBody
: '{' classBodyDeclaration* '}';
classBodyDeclaration
: ';'
| fieldDeclaration
;
fieldDeclaration
: stringField identifier defaultString? regexDeclaration? OPTIONAL?
| booleanField identifier defaultBoolean? OPTIONAL?
| numericField identifier defaultNumber? rangeValidation? OPTIONAL?
| dateField identifier defaultDate? OPTIONAL?
| identifierField identifier
| reference identifier;
identifierField
: VAR IDENTIFIER (square)*;
numericField
: VAR numericPrimitive (square)*;
numericPrimitive
: DOUBLE
| INTEGER
| LONG
;
booleanField
: VAR BOOLEAN (square)*;
dateField
: VAR DATE_TIME (square)*;
defaultDate
: DEFAULT ASSIGN DATE_TIME_LITERAL;
regexDeclaration
: REGEX ASSIGN REGEX_EXPR;
stringField
: VAR STRING (square)*;
reference
: REF IDENTIFIER (square)*;
qualifiedName
: IDENTIFIER ('.' IDENTIFIER)*;
rangeValidation
: RANGE ASSIGN rangeDeclaration;
rangeDeclaration
: ('[' numberLiteral ',' ']')
| ('[' ',' numberLiteral ']')
| ('[' numberLiteral ',' numberLiteral ']');
defaultBoolean
: (DEFAULT ASSIGN BOOL_LITERAL);
defaultString
: (DEFAULT ASSIGN stringLiteral);
defaultNumber
: (DEFAULT ASSIGN numberLiteral);
identifier: IDENTIFIER | ASSET | PARTICIPANT;
literal
: numberLiteral
| stringLiteral
| BOOL_LITERAL
;
numberLiteral
: integerLiteral
| floatLiteral;
stringLiteral
: CHAR_LITERAL
| STRING_LITERAL
;
integerLiteral
: DECIMAL_LITERAL
| OCT_LITERAL
;
floatLiteral
: FLOAT_LITERAL;
decorator
: AT qualifiedName ('(' elementValuePair ')')?;
elementValuePair
: literal (',' literal)*;
square: '[' ']';
|
remove EOL
|
remove EOL
|
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
|
8740d0b37b215555ac55982920a0248f76dd79ca
|
sharding-jdbc-ddl-parser/src/main/antlr4/imports/MySQLCreateIndex.g4
|
sharding-jdbc-ddl-parser/src/main/antlr4/imports/MySQLCreateIndex.g4
|
grammar MySQLCreateIndex;
import MySQLKeyword, Keyword, MySQLBase, BaseRule, Symbol;
createIndex:
CREATE (UNIQUE | FULLTEXT | SPATIAL)? INDEX indexName
indexType?
ON tableName keyPartsWithParen
;
|
grammar MySQLCreateIndex;
import MySQLKeyword, Keyword, MySQLBase, BaseRule, Symbol;
createIndex:
CREATE (UNIQUE | FULLTEXT | SPATIAL)? INDEX indexName
indexType?
ON tableName
;
|
optimize mysql create index
|
optimize mysql create index
|
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
|
778c5982f9e6248d07497759e4135225416dbaf6
|
VineScript/Compiler/VineParser.g4
|
VineScript/Compiler/VineParser.g4
|
parser grammar VineParser;
/*
// django syntax: https://docs.djangoproject.com/en/1.10/topics/templates/#the-django-template-language
// django:
// * var: {{ foo }}
// * code: {% if foo %}
// * comment: {# comment #}
// detail: https://github.com/benjohnson/atom-django-templates/blob/master/grammars/html%20(django).cson
grammar VineScript;
script: sequence+ EOF;
sequence: text
| code
|
;
code: stmt
| text
;
// conditionStmt or controlStmt (control structure)
stmt: conditionStmt
| assign
| print
| stmt ';'
| variable
;
// {{ foo }} is equal to << print foo >>
// built-in filters:
// * upper
// * lower
// * truncatechars:8
// * truncatewords:2
// * pluralize
// * default:"nothing"
// * length
// * random
// * stringformat:"#.0"
// * yesno:"yeah,no,maybe"
// ---- added by myself: ----
// * min
// * max
// built-in functions:
// * ParseInt(string)
// * ParseNumber(string)
// * Range(int):[]
// custom template tags
// https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-tags
// custom template filters :
// https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-filters
//<< autoescape off >>
// {{ body }}
// << autoescape on >>
// {{ foo }}
// << endautoescape >>
//<< endautoescape >>
// preformatted: (on by default)
<< formatted on >>
<< formatted off >>
// or like html:
<< pre on >>
<< pre off >>
// maybe:
<< tab >>
<< br >>
'<<' 'set' ID ('='|'to') expr '>>'
*/
@members{
public enum EVineParseMode {
SINGLE_PASSAGE,
EVAL_EXPR
}
// by default, parse as a single passage
public EVineParseMode ParseMode = EVineParseMode.SINGLE_PASSAGE;
internal static readonly string errReservedChar000B =
"'\\v' (vertical tabulation) is a reserved character and is not allowed to be used!";
internal static readonly string errReservedChar001E =
"'\\u001E' (record separator) is a reserved character and is not allowed to be used!";
internal static readonly string errReservedChar001F =
"'\\u001F' (unit separator) is a reserved character and is not allowed to be used!";
internal static readonly string errVarDefReservedKw =
"Can't use a reserved keyword as a variable name!";
internal static readonly string errMissingSpaceBefore = "Missing space before ";
internal static readonly string errMissingSpaceAfter = "Missing space after ";
private void ReservedChar()
{
var token = _input.Lt(-1);
ReservedChar(token);
}
private void ReservedChar(IToken token)
{
string msg = "";
if (token.Text.Contains("\u000B")) {
msg = errReservedChar000B;
}
else if (token.Text.Contains("\u001E")) {
msg = errReservedChar001E;
}
else if (token.Text.Contains("\u001F")) {
msg = errReservedChar001F;
}
NotifyPrev(token, msg);
}
private void NotifyPrev(string msg)
{
var token = _input.Lt(-1);
NotifyPrev(token, msg);
}
private void NotifyPrev(IToken token, string msg)
{
NotifyErrorListeners(token, msg, null);
}
}
options { tokenVocab=VineLexer; }
/*
* Parser Rules
*/
passage
: {ParseMode == EVineParseMode.EVAL_EXPR}? evalExprMode NL? EOF // active only if we're expr parse mode
| block* NL? EOF
| RESERVED_CHARS { ReservedChar(); }
| { NotifyErrorListeners("Error char"); } ERROR_CHAR
;
evalExprMode
: expr
;
// directOutput will add the text/code markups to the output.
// The output will then be parsed by the formatter.
block
: NL # directOutput
| verbatimStmt # noOutput // `as it is, escape << tags >> too`
| text # directOutput // foobar
| display # noOutput // {{ foo }}
| controlStmt # noOutput // << open stmt >> something << close stmt >>
| simpleStmtBlock # noOutput // << set foo = 0 >>
| link # noOutput // [[label|link]]
| collapseStmt # noOutput // { foo\nbar } => foobar
| BLOCK_COMMENT # directOutput // /* comment */
| LINE_COMMENT # directOutput // // inline comment
| RESERVED_CHARS { ReservedChar(); } # blockError
;
text
: TXT
;
simpleStmtBlock
: '<<' setStmt '>>'
| '<<' unsetStmt '>>'
| '<<' funcCall '>>'
;
link
: LLINK title=linkContent+ RLINK
| LLINK title=linkContent+ '|' destination=linkContent+ RLINK
| LLINK title=linkContent+ '|' destination=linkContent+ '|' code=block* CLOSE_LINK
;
linkContent
: LINK_TEXT+
| RESERVED_CHARS { ReservedChar(); }
;
verbatimStmt
: VERBATIM
;
collapseStmt
: LCOLLAPSE
| RCOLLAPSE
//| LCOLLAPSE block* RCOLLAPSE // could use this rule if we want to be more strict
;
/**
* Display something in the text (variable, expression, function return, ...)
**/
display
: LOUTPUT expr ROUTPUT
;
setStmt
: 'set' assignList
;
assignList
: assign (',' assign)*
| assignList { NotifyErrorListeners("Missing ',' separator"); } assign (',' assign)*
| assignList { NotifyErrorListeners("Too many ','"); } ',' ',' assignList
;
assign
: variable (sequenceAccess)* op=('='|'to') expr
| variable (sequenceAccess)* op=('+='|'-='|'*='|'/='|'%=') expr
| variable (sequenceAccess)* { NotifyErrorListeners("Missing assignation operator"); } expr
| variable (sequenceAccess)* op=('='|'to'|'+='|'-='|'*='|'/='|'%=')
{ NotifyErrorListeners("Missing expression after the operator"); }
;
unsetStmt
: 'unset' unsetList
;
unsetList
: variable (',' variable)*
| unsetList { NotifyErrorListeners("Missing ',' separator"); } variable (',' variable)*
| unsetList { NotifyErrorListeners("Too many ','"); } ',' ',' unsetList
;
funcCall
: ID '(' expressionList? ')'
| ID '(' expressionList? ')' { NotifyErrorListeners("Too many parentheses"); } ')'
| ID '(' expressionList? { NotifyErrorListeners("Missing closing ')'"); }
;
newSequence
: LBRACK expressionList? RBRACK # newArray
| LBRACE keyValueList? RBRACE # newDict
// array errors:
| LBRACK expressionList? RBRACK { NotifyErrorListeners("Too many brackets"); } RBRACK # newArrayError
| LBRACK expressionList? { NotifyErrorListeners("Missing closing ']'"); } # newArrayError
// dict errors:
| LBRACE keyValueList? RBRACE { NotifyErrorListeners("Too many braces"); } RBRACE # newDictError
| LBRACE keyValueList? { NotifyErrorListeners("Missing closing '}'"); } # newDictError
;
// if, elif, else, for, end
controlStmt
: ifStmt (elifStmt)* (elseStmt)? endStmt # ifCtrlStmt
| forStmt endStmt # forCtrlStmt
| ifStmt (elifStmt)* (elseStmt)? {NotifyErrorListeners("'if' statement is missing a closing '<< end >>'");} # ctrlStmtError
| ifStmt (elifStmt)* elseStmt {NotifyErrorListeners("Too many 'else' statements");} (elseStmt)+ # ctrlStmtError
| ifStmt {NotifyErrorListeners("Misplaced '<< else >>'");} (elseStmt) (elifStmt)+ endStmt # ctrlStmtError
| forStmt {NotifyErrorListeners("'for' statement is missing a closing '<< end >>'");} # ctrlStmtError
;
ifStmt
: '<<' 'if' wsa expr '>>' block*
;
elifStmt
: '<<' 'elif' wsa expr '>>' block*
;
elseStmt
: '<<' 'else' '>>' block*
;
endStmt
: '<<' 'end' '>>'
;
forStmt
: '<<' 'for' wsa variable 'in' expr '>>' NL? block* # forValueStmt
| '<<' 'for' wsa variable 'in' interval '>>' NL? block* # forValueStmt
| '<<' 'for' wsa key=variable ',' val=variable 'in' expr '>>' NL? block* # forKeyValueStmt
;
expr
: <assoc=right> left=expr '^' right=expr # powExpr
| op=(MINUS|'!') expr # unaryExpr
| left=expr op=('*' | DIV | '%') right=expr # mulDivModExpr
| left=expr op=('+'|MINUS) right=expr # addSubExpr
| left=expr op=(LT|GT|'<='|'>=') right=expr # relationalExpr
| left=expr op=('=='|'!=') right=expr # equalityExpr
| left=expr ('&&'|wsb 'and' wsa) right=expr # andExpr
| left=expr ('||'|wsb 'or' wsa) right=expr # orExpr
| '(' expr ')' # parensExpr
| newSequence # sequenceExpr
| expr (sequenceAccess)+ # anonymSequence
| funcCall # funcCallExpr
| atom # atomExpr
| variable (sequenceAccess)* # varExpr
;
expressionList
: expr (',' expr)*
| expr (',' { NotifyErrorListeners("Too many comma separators"); } ','+ expr)+
| expr (',' expr)* { NotifyErrorListeners("Too many comma separators"); } ','
;
keyValue
: stringLiteral ':' expr
| { NotifyErrorListeners("Invalid key value: it should look like this: '\"key\": value'"); } .
;
keyValueList
: keyValue (',' keyValue)*
| keyValue (',' { NotifyErrorListeners("Too many comma separators"); } ','+ keyValue)+
| keyValue (',' keyValue)* { NotifyErrorListeners("Too many comma separators"); } ','
;
atom: INT # intAtom
| FLOAT # floatAtom
| (TRUE | FALSE) # boolAtom
| stringLiteral # stringAtom
| NULL # nullAtom
;
stringLiteral
: STRING
| ILLEGAL_STRING { ReservedChar(); }
;
// Variable access. The '$' prefix is optional
variable
: '$'? ID ('.' ID)*
| { NotifyErrorListeners(errVarDefReservedKw); }
reservedKeyword
;
sequenceAccess
: LBRACK expr RBRACK
;
interval
: left=expr '...' right=expr
;
// Call to force whitespace. Kind of hacky?
// If the current token is not a white space => error.
// We use semantic predicates here because WS is in a different
// channel and the parser can't access directly
wsb // before
: {
if (_input.Get(_input.Index - 1).Type != WS) {
string offendingSymbol = _input.Get(_input.Index).Text;
NotifyErrorListeners(errMissingSpaceBefore + "'" + offendingSymbol + "'");
}
}
;
wsa // after
: {
if (_input.Get(_input.Index - 1).Type != WS) {
string offendingSymbol = _input.Get(_input.Index - 1).Text;
NotifyErrorListeners(errMissingSpaceAfter + "'" + offendingSymbol + "'");
}
}
;
reservedKeyword
: IF
| ELIF
| ELSE
| END
| KW_AND
| KW_OR
| TO
| SET
| UNSET
| TRUE
| FALSE
| NULL
;
|
parser grammar VineParser;
/*
// django syntax: https://docs.djangoproject.com/en/1.10/topics/templates/#the-django-template-language
// django:
// * var: {{ foo }}
// * code: {% if foo %}
// * comment: {# comment #}
// detail: https://github.com/benjohnson/atom-django-templates/blob/master/grammars/html%20(django).cson
grammar VineScript;
script: sequence+ EOF;
sequence: text
| code
|
;
code: stmt
| text
;
// conditionStmt or controlStmt (control structure)
stmt: conditionStmt
| assign
| print
| stmt ';'
| variable
;
// {{ foo }} is equal to << print foo >>
// built-in filters:
// * upper
// * lower
// * truncatechars:8
// * truncatewords:2
// * pluralize
// * default:"nothing"
// * length
// * random
// * stringformat:"#.0"
// * yesno:"yeah,no,maybe"
// ---- added by myself: ----
// * min
// * max
// built-in functions:
// * ParseInt(string)
// * ParseNumber(string)
// * Range(int):[]
// custom template tags
// https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-tags
// custom template filters :
// https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-filters
//<< autoescape off >>
// {{ body }}
// << autoescape on >>
// {{ foo }}
// << endautoescape >>
//<< endautoescape >>
// preformatted: (on by default)
<< formatted on >>
<< formatted off >>
// or like html:
<< pre on >>
<< pre off >>
// maybe:
<< tab >>
<< br >>
'<<' 'set' ID ('='|'to') expr '>>'
*/
@members{
public enum EVineParseMode {
SINGLE_PASSAGE,
EVAL_EXPR
}
// by default, parse as a single passage
public EVineParseMode ParseMode = EVineParseMode.SINGLE_PASSAGE;
internal static readonly string errReservedChar000B =
"'\\v' (vertical tabulation) is a reserved character and is not allowed to be used!";
internal static readonly string errReservedChar001E =
"'\\u001E' (record separator) is a reserved character and is not allowed to be used!";
internal static readonly string errReservedChar001F =
"'\\u001F' (unit separator) is a reserved character and is not allowed to be used!";
internal static readonly string errVarDefReservedKw =
"Can't use a reserved keyword as a variable name!";
internal static readonly string errMissingSpaceBefore = "Missing space before ";
internal static readonly string errMissingSpaceAfter = "Missing space after ";
private void ReservedChar()
{
var token = _input.Lt(-1);
ReservedChar(token);
}
private void ReservedChar(IToken token)
{
string msg = "";
if (token.Text.Contains("\u000B")) {
msg = errReservedChar000B;
}
else if (token.Text.Contains("\u001E")) {
msg = errReservedChar001E;
}
else if (token.Text.Contains("\u001F")) {
msg = errReservedChar001F;
}
NotifyPrev(token, msg);
}
private void NotifyPrev(string msg)
{
var token = _input.Lt(-1);
NotifyPrev(token, msg);
}
private void NotifyPrev(IToken token, string msg)
{
NotifyErrorListeners(token, msg, null);
}
}
options { tokenVocab=VineLexer; }
/*
* Parser Rules
*/
passage
: {ParseMode == EVineParseMode.EVAL_EXPR}? evalExprMode NL? EOF // active only if we're expr parse mode
| block* NL? EOF
| RESERVED_CHARS { ReservedChar(); }
| { NotifyErrorListeners("Error char"); } ERROR_CHAR
;
evalExprMode
: expr
;
// directOutput will add the text/code markups to the output.
// The output will then be parsed by the formatter.
block
: NL # directOutput
| verbatimStmt # noOutput // `as it is, escape << tags >> too`
| text # directOutput // foobar
| display # noOutput // {{ foo }}
| controlStmt # noOutput // << open stmt >> something << close stmt >>
| simpleStmtBlock # noOutput // << set foo = 0 >>
| link # noOutput // [[label|link]]
| collapseStmt # noOutput // { foo\nbar } => foobar
| BLOCK_COMMENT # directOutput // /* comment */
| LINE_COMMENT # directOutput // // inline comment
| RESERVED_CHARS { ReservedChar(); } # blockError
;
text
: TXT
;
simpleStmtBlock
: '<<' setStmt '>>'
| '<<' unsetStmt '>>'
| '<<' funcCall '>>'
;
link
: LLINK title=linkContent+ RLINK
| LLINK title=linkContent+ '|' '|' code=block* CLOSE_LINK
| LLINK title=linkContent+ '|' destination=linkContent+ RLINK
| LLINK title=linkContent+ '|' destination=linkContent+ '|' code=block* CLOSE_LINK
;
linkContent
: LINK_TEXT+
| RESERVED_CHARS { ReservedChar(); }
;
verbatimStmt
: VERBATIM
;
collapseStmt
: LCOLLAPSE
| RCOLLAPSE
//| LCOLLAPSE block* RCOLLAPSE // could use this rule if we want to be more strict
;
/**
* Display something in the text (variable, expression, function return, ...)
**/
display
: LOUTPUT expr ROUTPUT
;
setStmt
: 'set' assignList
;
assignList
: assign (',' assign)*
| assignList { NotifyErrorListeners("Missing ',' separator"); } assign (',' assign)*
| assignList { NotifyErrorListeners("Too many ','"); } ',' ',' assignList
;
assign
: variable (sequenceAccess)* op=('='|'to') expr
| variable (sequenceAccess)* op=('+='|'-='|'*='|'/='|'%=') expr
| variable (sequenceAccess)* { NotifyErrorListeners("Missing assignation operator"); } expr
| variable (sequenceAccess)* op=('='|'to'|'+='|'-='|'*='|'/='|'%=')
{ NotifyErrorListeners("Missing expression after the operator"); }
;
unsetStmt
: 'unset' unsetList
;
unsetList
: variable (',' variable)*
| unsetList { NotifyErrorListeners("Missing ',' separator"); } variable (',' variable)*
| unsetList { NotifyErrorListeners("Too many ','"); } ',' ',' unsetList
;
funcCall
: ID '(' expressionList? ')'
| ID '(' expressionList? ')' { NotifyErrorListeners("Too many parentheses"); } ')'
| ID '(' expressionList? { NotifyErrorListeners("Missing closing ')'"); }
;
newSequence
: LBRACK expressionList? RBRACK # newArray
| LBRACE keyValueList? RBRACE # newDict
// array errors:
| LBRACK expressionList? RBRACK { NotifyErrorListeners("Too many brackets"); } RBRACK # newArrayError
| LBRACK expressionList? { NotifyErrorListeners("Missing closing ']'"); } # newArrayError
// dict errors:
| LBRACE keyValueList? RBRACE { NotifyErrorListeners("Too many braces"); } RBRACE # newDictError
| LBRACE keyValueList? { NotifyErrorListeners("Missing closing '}'"); } # newDictError
;
// if, elif, else, for, end
controlStmt
: ifStmt (elifStmt)* (elseStmt)? endStmt # ifCtrlStmt
| forStmt endStmt # forCtrlStmt
| ifStmt (elifStmt)* (elseStmt)? {NotifyErrorListeners("'if' statement is missing a closing '<< end >>'");} # ctrlStmtError
| ifStmt (elifStmt)* elseStmt {NotifyErrorListeners("Too many 'else' statements");} (elseStmt)+ # ctrlStmtError
| ifStmt {NotifyErrorListeners("Misplaced '<< else >>'");} (elseStmt) (elifStmt)+ endStmt # ctrlStmtError
| forStmt {NotifyErrorListeners("'for' statement is missing a closing '<< end >>'");} # ctrlStmtError
;
ifStmt
: '<<' 'if' wsa expr '>>' block*
;
elifStmt
: '<<' 'elif' wsa expr '>>' block*
;
elseStmt
: '<<' 'else' '>>' block*
;
endStmt
: '<<' 'end' '>>'
;
forStmt
: '<<' 'for' wsa variable 'in' expr '>>' NL? block* # forValueStmt
| '<<' 'for' wsa variable 'in' interval '>>' NL? block* # forValueStmt
| '<<' 'for' wsa key=variable ',' val=variable 'in' expr '>>' NL? block* # forKeyValueStmt
;
expr
: <assoc=right> left=expr '^' right=expr # powExpr
| op=(MINUS|'!') expr # unaryExpr
| left=expr op=('*' | DIV | '%') right=expr # mulDivModExpr
| left=expr op=('+'|MINUS) right=expr # addSubExpr
| left=expr op=(LT|GT|'<='|'>=') right=expr # relationalExpr
| left=expr op=('=='|'!=') right=expr # equalityExpr
| left=expr ('&&'|wsb 'and' wsa) right=expr # andExpr
| left=expr ('||'|wsb 'or' wsa) right=expr # orExpr
| '(' expr ')' # parensExpr
| newSequence # sequenceExpr
| expr (sequenceAccess)+ # anonymSequence
| funcCall # funcCallExpr
| atom # atomExpr
| variable (sequenceAccess)* # varExpr
;
expressionList
: expr (',' expr)*
| expr (',' { NotifyErrorListeners("Too many comma separators"); } ','+ expr)+
| expr (',' expr)* { NotifyErrorListeners("Too many comma separators"); } ','
;
keyValue
: stringLiteral ':' expr
| { NotifyErrorListeners("Invalid key value: it should look like this: '\"key\": value'"); } .
;
keyValueList
: keyValue (',' keyValue)*
| keyValue (',' { NotifyErrorListeners("Too many comma separators"); } ','+ keyValue)+
| keyValue (',' keyValue)* { NotifyErrorListeners("Too many comma separators"); } ','
;
atom: INT # intAtom
| FLOAT # floatAtom
| (TRUE | FALSE) # boolAtom
| stringLiteral # stringAtom
| NULL # nullAtom
;
stringLiteral
: STRING
| ILLEGAL_STRING { ReservedChar(); }
;
// Variable access. The '$' prefix is optional
variable
: '$'? ID ('.' ID)*
| { NotifyErrorListeners(errVarDefReservedKw); }
reservedKeyword
;
sequenceAccess
: LBRACK expr RBRACK
;
interval
: left=expr '...' right=expr
;
// Call to force whitespace. Kind of hacky?
// If the current token is not a white space => error.
// We use semantic predicates here because WS is in a different
// channel and the parser can't access directly
wsb // before
: {
if (_input.Get(_input.Index - 1).Type != WS) {
string offendingSymbol = _input.Get(_input.Index).Text;
NotifyErrorListeners(errMissingSpaceBefore + "'" + offendingSymbol + "'");
}
}
;
wsa // after
: {
if (_input.Get(_input.Index - 1).Type != WS) {
string offendingSymbol = _input.Get(_input.Index - 1).Text;
NotifyErrorListeners(errMissingSpaceAfter + "'" + offendingSymbol + "'");
}
}
;
reservedKeyword
: IF
| ELIF
| ELSE
| END
| KW_AND
| KW_OR
| TO
| SET
| UNSET
| TRUE
| FALSE
| NULL
;
|
allow empty destination when code is provided
|
Links: allow empty destination when code is provided
The link's destination will be the same as the title:
[[my title||my code]]
is the same as:
[[my title|my title|my code]]
|
ANTLR
|
mit
|
julsam/VineScript
|
d72f3900972c0dbb066c91d6ec9aaf672e91f2ac
|
watertemplate-engine/grammar.g4
|
watertemplate-engine/grammar.g4
|
prop_name_head
: [a-zA-Z]
;
prop_name_body_char
: '_'
| [0-9]
| prop_name_head
;
prop_name_body
: prop_name_body_char
| prop_name_body_char prop_name_body
prop_name
: prop_name_head
| prop_name_head prop_name_body
;
id
: prop_name
| prop_name '.' id
;
// ---------------------------------------------
prop_eval
: '~' id '~'
;
if
: '~if' id ':' statements ':~'
| '~if' id ':' statements ':else:' statements ':~'
;
for
: '~for' prop_name 'in' id ':' statements ':~'
| '~for' prop_name 'in' id ':' statements ':else:' statements ':~'
;
text
: Any string
;
// ---------------------------------------------
statement
: prop_eval
| if
| for
| text
| ε
;
statements
: statement
| statement statements
;
|
prop_name_head
: [a-zA-Z]
;
prop_name_body_char
: '_'
| [0-9]
| prop_name_head
;
prop_name_body
: prop_name_body_char
| prop_name_body_char prop_name_body
;
prop_name
: prop_name_head
| prop_name_head prop_name_body
;
id
: prop_name
| prop_name '.' id
;
// ---------------------------------------------
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
|
4cfc17560c3b71a71542d7609bf489a1f6756150
|
python/PythonParser.g4
|
python/PythonParser.g4
|
// Header included from Python site:
/*
* Grammar for Python
*
* Note: Changing the grammar specified in this file will most likely
* require corresponding changes in the parser module
* (../Modules/parsermodule.c). If you can't make the changes to
* that module yourself, please co-ordinate the required changes
* with someone who can; ask around on python-dev for help. Fred
* Drake <[email protected]> will probably be listening there.
*
* NOTE WELL: You should also follow all the steps listed in PEP 306,
* "How to Change Python's Grammar"
*
* Start symbols for the grammar:
* single_input is a single interactive statement;
* file_input is a module or sequence of commands read from an input file;
* eval_input is the input for the eval() and input() functions.
* NB: compound_stmt in single_input is followed by extra NEWLINE!
*/
parser grammar PythonParser;
options { tokenVocab=PythonLexer; }
root
: (single_input
| file_input
| eval_input)? EOF
;
single_input
: NEWLINE
| simple_stmt
| compound_stmt NEWLINE
;
file_input
: (NEWLINE | stmt)+
;
eval_input
: testlist NEWLINE*
;
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
| NEWLINE INDENT stmt+ DEDENT
;
decorator
: AT dotted_name (OPEN_PAREN arglist? CLOSE_PAREN)? NEWLINE
;
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? (NEWLINE | 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
| dotted_name
| 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 NEWLINE!
*/
parser grammar PythonParser;
options { tokenVocab=PythonLexer; }
root
: (single_input
| file_input
| eval_input)? EOF
;
single_input
: NEWLINE
| simple_stmt
| compound_stmt NEWLINE
;
file_input
: (NEWLINE | stmt)+
;
eval_input
: testlist NEWLINE*
;
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
| NEWLINE INDENT stmt+ DEDENT
;
decorator
: AT dotted_name (OPEN_PAREN arglist? CLOSE_PAREN)? NEWLINE
;
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? (NEWLINE | 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?
;
//----------------------------------------------------------------------------------------------------------------------
|
Fix trailer in PythonParser
|
Fix trailer in PythonParser
|
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
|
b7d0083649f5ad161e2dd00134c9e7816469dbea
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DCLStatement.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DCLStatement.g4
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DCLStatement;
import Symbol, Keyword, Literals, BaseRule;
grant
: GRANT (proxyClause_ | privilegeClause_ | roleClause_) TO
;
revoke
: REVOKE (proxyClause_ | privilegeClause_ | allClause_ | roleClause_) FROM
;
proxyClause_
: PROXY ON
;
privilegeClause_
: privileges_ ON onObjectClause_
;
roleClause_
: ignoredIdentifiers_
;
allClause_
: ALL PRIVILEGES? COMMA_ GRANT OPTION
;
privileges_
: privilegeType_ columnNames? (COMMA_ privilegeType_ columnNames?)*
;
privilegeType_
: ALL PRIVILEGES?
| ALTER ROUTINE?
| CREATE
| CREATE ROUTINE
| CREATE TABLESPACE
| CREATE TEMPORARY TABLES
| CREATE USER
| CREATE VIEW
| DELETE
| DROP
| EVENT
| EXECUTE
| FILE
| GRANT OPTION
| INDEX
| INSERT
| LOCK TABLES
| PROCESS
| PROXY
| REFERENCES
| RELOAD
| REPLICATION CLIENT
| REPLICATION SLAVE
| SELECT
| SHOW DATABASES
| SHOW VIEW
| SHUTDOWN
| SUPER
| TRIGGER
| UPDATE
| USAGE
| AUDIT_ADMIN
| BINLOG_ADMIN
| CONNECTION_ADMIN
| ENCRYPTION_KEY_ADMIN
| FIREWALL_ADMIN
| FIREWALL_USER
| GROUP_REPLICATION_ADMIN
| REPLICATION_SLAVE_ADMIN
| ROLE_ADMIN
| SET_USER_ID
| SYSTEM_VARIABLES_ADMIN
| VERSION_TOKEN_ADMIN
;
onObjectClause_
: objectType_? privilegeLevel_
;
objectType_
: TABLE | FUNCTION | PROCEDURE
;
privilegeLevel_
: ASTERISK_ | ASTERISK_ DOT_ASTERISK_ | identifier_ DOT_ASTERISK_ | tableName
;
createUser
: CREATE USER
;
dropUser
: DROP USER
;
alterUser
: ALTER USER
;
renameUser
: RENAME USER
;
createRole
: CREATE ROLE
;
dropRole
: DROP ROLE
;
setRole
: SET DEFAULT? ROLE
;
setPassword
: SET PASSWORD
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DCLStatement;
import Symbol, Keyword, Literals, BaseRule;
grant
: GRANT (proxyClause_ | privilegeClause_ | roleClause_)
;
revoke
: REVOKE (proxyClause_ | privilegeClause_ | allClause_ | roleClause_)
;
proxyClause_
: PROXY ON
;
privilegeClause_
: privileges_ ON onObjectClause_
;
roleClause_
: ignoredIdentifiers_
;
allClause_
: ALL PRIVILEGES? COMMA_ GRANT OPTION
;
privileges_
: privilegeType_ columnNames? (COMMA_ privilegeType_ columnNames?)*
;
privilegeType_
: ALL PRIVILEGES?
| ALTER ROUTINE?
| CREATE
| CREATE ROUTINE
| CREATE TABLESPACE
| CREATE TEMPORARY TABLES
| CREATE USER
| CREATE VIEW
| DELETE
| DROP
| EVENT
| EXECUTE
| FILE
| GRANT OPTION
| INDEX
| INSERT
| LOCK TABLES
| PROCESS
| PROXY
| REFERENCES
| RELOAD
| REPLICATION CLIENT
| REPLICATION SLAVE
| SELECT
| SHOW DATABASES
| SHOW VIEW
| SHUTDOWN
| SUPER
| TRIGGER
| UPDATE
| USAGE
| AUDIT_ADMIN
| BINLOG_ADMIN
| CONNECTION_ADMIN
| ENCRYPTION_KEY_ADMIN
| FIREWALL_ADMIN
| FIREWALL_USER
| GROUP_REPLICATION_ADMIN
| REPLICATION_SLAVE_ADMIN
| ROLE_ADMIN
| SET_USER_ID
| SYSTEM_VARIABLES_ADMIN
| VERSION_TOKEN_ADMIN
;
onObjectClause_
: objectType_? privilegeLevel_
;
objectType_
: TABLE | FUNCTION | PROCEDURE
;
privilegeLevel_
: ASTERISK_ | ASTERISK_ DOT_ASTERISK_ | identifier_ DOT_ASTERISK_ | tableName
;
createUser
: CREATE USER
;
dropUser
: DROP USER
;
alterUser
: ALTER USER
;
renameUser
: RENAME USER
;
createRole
: CREATE ROLE
;
dropRole
: DROP ROLE
;
setRole
: SET DEFAULT? ROLE
;
setPassword
: SET PASSWORD
;
|
delete `to` `from`
|
delete `to` `from`
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
b567ab3e64875226c436dc13ed1603dbf9d4e4ed
|
VineScript/Compiler/VineLexer.g4
|
VineScript/Compiler/VineLexer.g4
|
lexer grammar VineLexer;
@header {
using System;
}
@members{
//public override IToken Emit(){
// switch (_type) {
// case RESERVED_CHARS:
// //setType(RESERVED_CHARS);
// IToken result = base.Emit();
// // you'll need to define this method
// System.Console.WriteLine("Unterminated string literal");
// //reportError(result, "Unterminated string literal");
// return result;
// default:
// return base.Emit();
// }
//}
public static bool IsVerbatim(string str)
{
if (ToVerbatim(str) != null) {
return true;
} else {
return false;
}
}
public static string ToVerbatim(string str)
{
try {
while ( str.Length >= 3 && str.StartsWith("`") && str.EndsWith("`")
&& !Escape.IsCharAtEscaped(str, str.Length - 1)
) {
str = str.Remove(0, 1);
str = str.Remove(str.Length - 1, 1);
}
if ( str.Length > 0 && !str.StartsWith("`")
&& (!str.EndsWith("`") || Escape.IsCharAtEscaped(str, str.Length - 1))
) {
return str;
} else {
return null;
}
} catch (Exception) {
throw new Exception("Internal error VineLexer:ToVerbatim");
}
}
}
/*
* Lexer Rules
*/
// Default "mode" (text mode) : Everything that is outside of tags '{{ .. }}', '<< .. >>' or '/* .. */'
// Escape '\' or '`'. For every char added here, must think to add it to UnescapeVineSequence too
TXT_ESC
: ('\\\\' | '\\`') -> type(TXT)
;
// Escape everything between ` ` or `` `` or ``` ```, etc
VERBATIM
: ('`')+ ALL_BUT_RESERVED_CHARS*? ('`')+ {IsVerbatim(Text)}?
;
LOUTPUT: '{{' -> pushMode(VineCode) ;
LSTMT: '<<' -> pushMode(VineCode) ;
LLINK: '[[' -> pushMode(LinkMode) ;
BLOCK_COMMENT: '/*' .*? '*/' ;
LINE_COMMENT: '//' ~[\r\n]* ;
CLOSE_STMT
: '}}'
| '>>'
| ']]'
| '*/'
;
NL: '\r'? '\n' ;
LCOLLAPSE: '{' ;
RCOLLAPSE: '}' ;
// Reserved / illegal characters:
// * '\u000B': \v vertical tabulation, marks '\n' in strings returned by a function
// and then used by LinesFormatter to keep those '\n' in place
// * '\u001E': marks the start of the output of the display command
// * '\u001F': marks the end of the output of the display command
RESERVED_CHARS: [\u000B\u001E\u001F] ;
fragment
ALL_BUT_RESERVED_CHARS: ~[\u000B\u001E\u001F] ;
TXT_SPECIALS
: [`\\<>*\[\]/] -> type(TXT)
;
TXT : ~[`\\<>*\[\]{}/\r\n\u000B\u001E\u001F]+
;
ERROR_CHAR: . ;
// ----------------------------------------------------------
mode LinkMode;
LINK_ESC
: ( '\\\\' // [[my \\ title|mylink]]
| '\\]' // [[my [[own\]] title|mylink]]
| '\\|' // [[my \| title|mylink]]
| '\\<' // [[mylink<-my \<- title]]
| '\\-' // [[my \-> title->mylink]]
)
-> type(LINK_TEXT)
;
RLINK: ']]' -> popMode ;
LINK_RESERVED_CHARS: RESERVED_CHARS -> type(RESERVED_CHARS) ;
LINK_PIPE: '|' ;
LINK_LEFT: '<-' ;
LINK_RIGHT: '->' ;
LINK_TEXT_SPECIALS: [\\<\]-] -> type(LINK_TEXT) ;
LINK_TEXT: ~[\\|<\]\r\n\u000B\u001E\u001F-]+ ;
LinkMode_ERROR_CHAR: ERROR_CHAR -> type(ERROR_CHAR) ;
// ----------------------------------------------------------
mode VineCode;
ROUTPUT: '}}' -> popMode ;
RSTMT: '>>' -> popMode ;
// Parentheses, square brackets, curly braces
LPAREN: '(' ;
RPAREN: ')' ;
LBRACK: '[' ;
RBRACK: ']' ;
LBRACE: '{' ;
RBRACE: '}' ;
// Reserved keywords
IF: 'if' ;
ELIF: 'elif' ;
ELSE: 'else' ;
END: 'end' ;
FOR: 'for' ;
IN: 'in' ;
KW_AND: 'and' ;
KW_OR: 'or' ;
TO: 'to' ;
SET: 'set' ;
UNSET: 'unset' ;
// Separators
INTERVAL_SEP: '...' ;
DOT: '.' ;
COMMA: ',' ;
COLON: ':' ;
// Assign
ADDASSIGN: '+=' ;
SUBASSIGN: '-=' ;
MULASSIGN: '*=' ;
DIVASSIGN: '/=' ;
MODASSIGN: '%=' ;
ASSIGN: '=' ;
// Unary op
MINUS: '-' ;
NOT: '!' ;
POW: '^' ; // right assoc
// Arithmetic op
MUL: '*' ;
DIV: '/' ;
ADD: '+' ;
MOD: '%' ;
// Equality op
EQ: '==' ;
NEQ: '!=' ;
// Logical op
AND: '&&' ;
OR: '||' ;
// Comparison op
LT: '<' ;
GT: '>' ;
LTE: '<=' ;
GTE: '>=' ;
// TODO complete list. Commands are built-in functions
COMMAND: 'array' | 'TODO' ;
// Atoms
TRUE: 'true' ;
FALSE: 'false' ;
NULL: 'null' ;
STRING: '"' (ESC | ALL_BUT_RESERVED_CHARS)*? '"' ;
// catches strings containing '\u000B' or '\u001E' or '\u001F':
ILLEGAL_STRING: '"' .*? '"' ;
//tokens { STRING }
//DOUBLE : '"' .*? '"' -> type(STRING) ;
//SINGLE : '\'' .*? '\'' -> type(STRING) ;
//STRING_SQUOTE: '\'' (ESC_SQUOTE|.)*? '\'' ;
//STRING_DQUOTE: '"' (ESC_DQUOTE|.)*? '"' ;
// Antlr defined unicode whitespace (only in Antlr >= 4.6 or 4.7)
// https://github.com/antlr/antlr4/blob/master/doc/lexer-rules.md
//UNICODE_WS : [\p{White_Space}] -> skip; // match all Unicode whitespace
WS: (WS_Restricted|WS_SpaceSeparator|WS_LineSeparator|WS_ParagraphSeparator)+ -> channel(HIDDEN) ;
// ** WHITE SPACE DEFINITIONS **
// http://www.unicode.org/Public/UNIDATA/UnicodeData.txt
// https://msdn.microsoft.com/en-us/library/system.char.iswhitespace(v=vs.110).aspx
// https://en.wikipedia.org/wiki/Whitespace_character
// Contains SPACE (0020), CHARACTER TABULATION (0009), FORM FEED (U+000C),
// CARRIAGE RETURN (U+000D) and LINE FEED (000A)
// It's missing:
// * LINE TABULATION (U+000B aka \v), used as a reserved char
// * NEXT LINE (U+0085), which i'm not sure I should include
fragment WS_Restricted: [ \t\f\r\n] ;
// SpaceSeparator "Zs" from the unicode list:
// 0020;SPACE;Zs;0;WS;;;;;N;;;;;
// 00A0;NO-BREAK SPACE;Zs;0;CS;<noBreak> 0020;;;;N;NON-BREAKING SPACE;;;;
// 1680;OGHAM SPACE MARK;Zs;0;WS;;;;;N;;;;;
// 2000;EN QUAD;Zs;0;WS;2002;;;;N;;;;;
// 2001;EM QUAD;Zs;0;WS;2003;;;;N;;;;;
// 2002;EN SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 2003;EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 2004;THREE-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 2005;FOUR-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 2006;SIX-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 2007;FIGURE SPACE;Zs;0;WS;<noBreak> 0020;;;;N;;;;;
// 2008;PUNCTUATION SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 2009;THIN SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 200A;HAIR SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 202F;NARROW NO-BREAK SPACE;Zs;0;CS;<noBreak> 0020;;;;N;;;;;
// 205F;MEDIUM MATHEMATICAL SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 3000;IDEOGRAPHIC SPACE;Zs;0;WS;<wide> 0020;;;;N;;;;;
// Does not include SPACE (it's in rule WS_Restricted)
// and OGHAM SPACE MARK (does not look like a space)
fragment WS_SpaceSeparator: [\u00A0\u2000-\u200A\u202F\u205F\u3000] ;
//LineSeparator "Zl" from the unicode list:
// 2028;LINE SEPARATOR;Zl;0;WS;;;;;N;;;;;
fragment WS_LineSeparator: '\u2028' ;
//ParagraphSeparator "Zp" from the unicode list:
// 2029;PARAGRAPH SEPARATOR;Zp;0;B;;;;;N;;;;;
fragment WS_ParagraphSeparator: '\u2029' ;
// ** IDENTIFIERS **
VAR_PREFIX: '$' ;
// Unicode ID https://github.com/antlr/antlr4/blob/master/doc/lexer-rules.md
// match full Unicode alphabetic ids (only in Antlr >= 4.6 or 4.7)
//UNICODE_ID : [\p{Alpha}\p{General_Category=Other_Letter}] [\p{Alnum}\p{General_Category=Other_Letter}]* ;
ID: ID_LETTER (ID_LETTER | DIGIT)* ;
INT: DIGIT+ ;
FLOAT: DIGIT+ '.' DIGIT+ ;
VineCode_ERROR_CHAR: ERROR_CHAR -> type(ERROR_CHAR) ;
// fragments
fragment ESC: '\\"' | '\\\\' ; // 2-char sequences \" and \\
//fragment ESC_SQUOTE: '\\\'' | '\\\\' ; // 2-char sequences \" and \\
//fragment ESC_DQUOTE: '\\"' | '\\\\' ; // 2-char sequences \" and \\
fragment DIGIT: [0-9] ;
// From Harlowe:
// https://bitbucket.org/_L_/harlowe/src/e6e8f2e0382f716c64a124db360f6095e230db9e/js/markup/patterns.js?at=v2.0.1&fileviewer=file-view-default#patterns.js-81
fragment ID_LETTER: [A-Za-z\u00C0-\u00DE\u00DF-\u00FF\u0150\u0170\u0151\u0171\uD800-\uDFFF_] ;
|
lexer grammar VineLexer;
@header {
using System;
}
@members{
//public override IToken Emit(){
// switch (_type) {
// case RESERVED_CHARS:
// //setType(RESERVED_CHARS);
// IToken result = base.Emit();
// // you'll need to define this method
// System.Console.WriteLine("Unterminated string literal");
// //reportError(result, "Unterminated string literal");
// return result;
// default:
// return base.Emit();
// }
//}
// Nested dictionary declaration, like { "a": true, "b": { "c": false }}
private static int nestedDictionaryDecl = 0;
public static bool IsVerbatim(string str)
{
if (ToVerbatim(str) != null) {
return true;
} else {
return false;
}
}
public static string ToVerbatim(string str)
{
try {
while ( str.Length >= 3 && str.StartsWith("`") && str.EndsWith("`")
&& !Escape.IsCharAtEscaped(str, str.Length - 1)
) {
str = str.Remove(0, 1);
str = str.Remove(str.Length - 1, 1);
}
if ( str.Length > 0 && !str.StartsWith("`")
&& (!str.EndsWith("`") || Escape.IsCharAtEscaped(str, str.Length - 1))
) {
return str;
} else {
return null;
}
} catch (Exception) {
throw new Exception("Internal error VineLexer:ToVerbatim");
}
}
}
/*
* Lexer Rules
*/
// Default "mode" (text mode) : Everything that is outside of tags '{{ .. }}', '<< .. >>' or '/* .. */'
// Escape '\' or '`'. For every char added here, must think to add it to UnescapeVineSequence too
TXT_ESC
: ('\\\\' | '\\`') -> type(TXT)
;
// Escape everything between ` ` or `` `` or ``` ```, etc
VERBATIM
: ('`')+ ALL_BUT_RESERVED_CHARS*? ('`')+ {IsVerbatim(Text)}?
;
LOUTPUT: '{{' -> pushMode(VineCode) ;
LSTMT: '<<' -> pushMode(VineCode) ;
LLINK: '[[' -> pushMode(LinkMode) ;
BLOCK_COMMENT: '/*' .*? '*/' ;
LINE_COMMENT: '//' ~[\r\n]* ;
CLOSE_STMT
: '}}'
| '>>'
| ']]'
| '*/'
;
NL: '\r'? '\n' ;
LCOLLAPSE: '{' ;
RCOLLAPSE: '}' ;
// Reserved / illegal characters:
// * '\u000B': \v vertical tabulation, marks '\n' in strings returned by a function
// and then used by LinesFormatter to keep those '\n' in place
// * '\u001E': marks the start of the output of the display command
// * '\u001F': marks the end of the output of the display command
RESERVED_CHARS: [\u000B\u001E\u001F] ;
fragment
ALL_BUT_RESERVED_CHARS: ~[\u000B\u001E\u001F] ;
TXT_SPECIALS
: [`\\<>*\[\]/] -> type(TXT)
;
TXT : ~[`\\<>*\[\]{}/\r\n\u000B\u001E\u001F]+
;
ERROR_CHAR: . ;
// ----------------------------------------------------------
mode LinkMode;
LINK_ESC
: ( '\\\\' // [[my \\ title|mylink]]
| '\\]' // [[my [[own\]] title|mylink]]
| '\\|' // [[my \| title|mylink]]
| '\\<' // [[mylink<-my \<- title]]
| '\\-' // [[my \-> title->mylink]]
)
-> type(LINK_TEXT)
;
RLINK: ']]' -> popMode ;
LINK_RESERVED_CHARS: RESERVED_CHARS -> type(RESERVED_CHARS) ;
LINK_PIPE: '|' ;
LINK_LEFT: '<-' ;
LINK_RIGHT: '->' ;
LINK_TEXT_SPECIALS: [\\<\]-] -> type(LINK_TEXT) ;
LINK_TEXT: ~[\\|<\]\r\n\u000B\u001E\u001F-]+ ;
LinkMode_ERROR_CHAR: ERROR_CHAR -> type(ERROR_CHAR) ;
// ----------------------------------------------------------
mode VineCode;
ROUTPUT: '}}' { nestedDictionaryDecl == 0 }? -> popMode ;
RSTMT: '>>' -> popMode ;
// Parentheses, square brackets, curly braces
LPAREN: '(' ;
RPAREN: ')' ;
LBRACK: '[' ;
RBRACK: ']' ;
LBRACE: '{' { nestedDictionaryDecl++; } ;
RBRACE: '}' { nestedDictionaryDecl--; } ;
// Reserved keywords
IF: 'if' ;
ELIF: 'elif' ;
ELSE: 'else' ;
END: 'end' ;
FOR: 'for' ;
IN: 'in' ;
KW_AND: 'and' ;
KW_OR: 'or' ;
TO: 'to' ;
SET: 'set' ;
UNSET: 'unset' ;
// Separators
INTERVAL_SEP: '...' ;
DOT: '.' ;
COMMA: ',' ;
COLON: ':' ;
// Assign
ADDASSIGN: '+=' ;
SUBASSIGN: '-=' ;
MULASSIGN: '*=' ;
DIVASSIGN: '/=' ;
MODASSIGN: '%=' ;
ASSIGN: '=' ;
// Unary op
MINUS: '-' ;
NOT: '!' ;
POW: '^' ; // right assoc
// Arithmetic op
MUL: '*' ;
DIV: '/' ;
ADD: '+' ;
MOD: '%' ;
// Equality op
EQ: '==' ;
NEQ: '!=' ;
// Logical op
AND: '&&' ;
OR: '||' ;
// Comparison op
LT: '<' ;
GT: '>' ;
LTE: '<=' ;
GTE: '>=' ;
// TODO complete list. Commands are built-in functions
COMMAND: 'array' | 'TODO' ;
// Atoms
TRUE: 'true' ;
FALSE: 'false' ;
NULL: 'null' ;
STRING: '"' (ESC | ALL_BUT_RESERVED_CHARS)*? '"' ;
// catches strings containing '\u000B' or '\u001E' or '\u001F':
ILLEGAL_STRING: '"' .*? '"' ;
//tokens { STRING }
//DOUBLE : '"' .*? '"' -> type(STRING) ;
//SINGLE : '\'' .*? '\'' -> type(STRING) ;
//STRING_SQUOTE: '\'' (ESC_SQUOTE|.)*? '\'' ;
//STRING_DQUOTE: '"' (ESC_DQUOTE|.)*? '"' ;
// Antlr defined unicode whitespace (only in Antlr >= 4.6 or 4.7)
// https://github.com/antlr/antlr4/blob/master/doc/lexer-rules.md
//UNICODE_WS : [\p{White_Space}] -> skip; // match all Unicode whitespace
WS: (WS_Restricted|WS_SpaceSeparator|WS_LineSeparator|WS_ParagraphSeparator)+ -> channel(HIDDEN) ;
// ** WHITE SPACE DEFINITIONS **
// http://www.unicode.org/Public/UNIDATA/UnicodeData.txt
// https://msdn.microsoft.com/en-us/library/system.char.iswhitespace(v=vs.110).aspx
// https://en.wikipedia.org/wiki/Whitespace_character
// Contains SPACE (0020), CHARACTER TABULATION (0009), FORM FEED (U+000C),
// CARRIAGE RETURN (U+000D) and LINE FEED (000A)
// It's missing:
// * LINE TABULATION (U+000B aka \v), used as a reserved char
// * NEXT LINE (U+0085), which i'm not sure I should include
fragment WS_Restricted: [ \t\f\r\n] ;
// SpaceSeparator "Zs" from the unicode list:
// 0020;SPACE;Zs;0;WS;;;;;N;;;;;
// 00A0;NO-BREAK SPACE;Zs;0;CS;<noBreak> 0020;;;;N;NON-BREAKING SPACE;;;;
// 1680;OGHAM SPACE MARK;Zs;0;WS;;;;;N;;;;;
// 2000;EN QUAD;Zs;0;WS;2002;;;;N;;;;;
// 2001;EM QUAD;Zs;0;WS;2003;;;;N;;;;;
// 2002;EN SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 2003;EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 2004;THREE-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 2005;FOUR-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 2006;SIX-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 2007;FIGURE SPACE;Zs;0;WS;<noBreak> 0020;;;;N;;;;;
// 2008;PUNCTUATION SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 2009;THIN SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 200A;HAIR SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 202F;NARROW NO-BREAK SPACE;Zs;0;CS;<noBreak> 0020;;;;N;;;;;
// 205F;MEDIUM MATHEMATICAL SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
// 3000;IDEOGRAPHIC SPACE;Zs;0;WS;<wide> 0020;;;;N;;;;;
// Does not include SPACE (it's in rule WS_Restricted)
// and OGHAM SPACE MARK (does not look like a space)
fragment WS_SpaceSeparator: [\u00A0\u2000-\u200A\u202F\u205F\u3000] ;
//LineSeparator "Zl" from the unicode list:
// 2028;LINE SEPARATOR;Zl;0;WS;;;;;N;;;;;
fragment WS_LineSeparator: '\u2028' ;
//ParagraphSeparator "Zp" from the unicode list:
// 2029;PARAGRAPH SEPARATOR;Zp;0;B;;;;;N;;;;;
fragment WS_ParagraphSeparator: '\u2029' ;
// ** IDENTIFIERS **
VAR_PREFIX: '$' ;
// Unicode ID https://github.com/antlr/antlr4/blob/master/doc/lexer-rules.md
// match full Unicode alphabetic ids (only in Antlr >= 4.6 or 4.7)
//UNICODE_ID : [\p{Alpha}\p{General_Category=Other_Letter}] [\p{Alnum}\p{General_Category=Other_Letter}]* ;
ID: ID_LETTER (ID_LETTER | DIGIT)* ;
INT: DIGIT+ ;
FLOAT: DIGIT+ '.' DIGIT+ ;
VineCode_ERROR_CHAR: ERROR_CHAR -> type(ERROR_CHAR) ;
// fragments
fragment ESC: '\\"' | '\\\\' ; // 2-char sequences \" and \\
//fragment ESC_SQUOTE: '\\\'' | '\\\\' ; // 2-char sequences \" and \\
//fragment ESC_DQUOTE: '\\"' | '\\\\' ; // 2-char sequences \" and \\
fragment DIGIT: [0-9] ;
// From Harlowe:
// https://bitbucket.org/_L_/harlowe/src/e6e8f2e0382f716c64a124db360f6095e230db9e/js/markup/patterns.js?at=v2.0.1&fileviewer=file-view-default#patterns.js-81
fragment ID_LETTER: [A-Za-z\u00C0-\u00DE\u00DF-\u00FF\u0150\u0170\u0151\u0171\uD800-\uDFFF_] ;
|
Fix nested dictionary declaration. In the case of a nested dictionary declaration, if the 2 endings '}' were not separated, it would cause a syntax error (it would enter the rule ROUTPUT). For example, this declaration would cause a syntax error: { "a": true, "b": { "c": false }}
|
Fix nested dictionary declaration.
In the case of a nested dictionary declaration, if the 2 endings '}' were not separated, it would cause a syntax error (it would enter the rule ROUTPUT).
For example, this declaration would cause a syntax error: { "a": true, "b": { "c": false }}
|
ANTLR
|
mit
|
julsam/VineScript
|
e3660b447ff8ed770587e8985d321451b0020803
|
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
|
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
|
/* Todo:
* - Comments justifying and explaining every rule.
*/
lexer grammar CreoleTokens;
options { superClass=ContextSensitiveLexer; }
@members {
Formatting bold;
Formatting italic;
Formatting strike;
public void setupFormatting() {
bold = new Formatting("**");
italic = new Formatting("//");
strike = new Formatting("--");
inlineFormatting.add(bold);
inlineFormatting.add(italic);
inlineFormatting.add(strike);
}
public boolean inHeader = false;
public boolean start = false;
public int listLevel = 0;
boolean nowiki = false;
boolean cpp = false;
boolean html = false;
boolean java = false;
boolean xhtml = false;
boolean xml = false;
boolean intr = false;
public void doHdr() {
String prefix = getText().trim();
boolean seekback = false;
if(!prefix.substring(prefix.length() - 1).equals("=")) {
prefix = prefix.substring(0, prefix.length() - 1);
seekback = true;
}
if(prefix.length() <= 6) {
if(seekback) {
seek(-1);
}
setText(prefix);
inHeader = true;
} else {
setType(Any);
}
}
public void setStart() {
String next1 = next();
String next2 = get(1);
start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#"));
}
public void doList(int level) {
listLevel = level;
seek(-1);
setStart();
resetFormatting();
}
public void doUrl() {
String url = getText();
String last = url.substring(url.length()-1);
String next = next();
if(url.endsWith("://") || url.endsWith("mailto:")) { setType(Any); }
while((last + next).equals("//") || last.matches("[\\.,)\"';:]")) {
seek(-1);
url = url.substring(0, url.length() - 1);
last = url.substring(url.length()-1);
next = next();
}
setText(url);
}
public void breakOut() {
resetFormatting();
listLevel = 0;
inHeader = false;
intr = false;
nowiki = false;
cpp = false;
html = false;
java = false;
xhtml = false;
xml = false;
}
public String[] thisKillsTheFormatting() {
String[] ends = new String[7];
if(inHeader || intr) {
ends[0] = "\n";
ends[1] = "\r\n";
} else {
ends[0] = null;
ends[1] = null;
}
if(intr) {
ends[2] = "|";
} else {
ends[2] = null;
}
ends[3] = "\n\n";
ends[4] = "\r\n\r\n";
if(listLevel > 0) {
// \L (when at the start) matches the start of a line.
ends[5] = "\\L*";
ends[6] = "\\L#";
} else {
ends[5] = null;
ends[6] = null;
}
return ends;
}
}
/* ***** Headings ***** */
HSt : LINE '='+ ~'=' {doHdr();} ;
HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ;
/* ***** Lists ***** */
U1 : START '*' ~'*' {doList(1);} ;
U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ;
U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ;
U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ;
U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ;
U6 : START '******' ~'*' {listLevel >= 5}? {doList(6);} ;
U7 : START '*******' ~'*' {listLevel >= 6}? {doList(7);} ;
U8 : START '********' ~'*' {listLevel >= 7}? {doList(8);} ;
U9 : START '*********' ~'*' {listLevel >= 8}? {doList(9);} ;
U10 : START '**********' ~'*' {listLevel >= 9}? {doList(10);} ;
O1 : START '#' ~'#' {doList(1);} ;
O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ;
O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ;
O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ;
O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ;
O6 : START '######' ~'#' {listLevel >= 5}? {doList(6);} ;
O7 : START '#######' ~'#' {listLevel >= 6}? {doList(7);} ;
O8 : START '########' ~'#' {listLevel >= 7}? {doList(8);} ;
O9 : START '#########' ~'#' {listLevel >= 8}? {doList(9);} ;
O10 : START '##########' ~'#' {listLevel >= 9}? {doList(10);} ;
/* ***** Horizontal Rules ***** */
Rule : LINE '---' '-'+ {breakOut();} ;
/* ***** Tables ***** */
TdStartLn : LINE '|'+ {intr=true; setType(TdStart);} ;
ThStartLn : LINE '|'+ '=' {intr=true; setType(ThStart);} ;
RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ;
TdStart : '|'+ {intr}? {breakOut(); intr=true;} ;
ThStart : '|'+ '=' {intr}? {breakOut(); intr=true;} ;
/* ***** Inline Formatting ***** */
BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ;
ISt : '//' {!italic.active && !prior().matches("[a-zA-Z0-9]:")}? {setFormatting(italic, Any);} ;
SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ;
BEnd : '**' {bold.active}? {unsetFormatting(bold);} ;
IEnd : '//' {italic.active && !prior().matches("[a-zA-Z0-9]:")}? {unsetFormatting(italic);} ;
SEnd : '--' {strike.active}? {unsetFormatting(strike);} ;
NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ;
StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ;
StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ;
StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ;
StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ;
StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ;
/* ***** Links ***** */
LiSt : '[[' -> mode(LINK) ;
ImSt : '{{' -> mode(LINK) ;
/* ***** Breaks ***** */
InlineBrk : '\\\\' ;
ParBreak : LineBreak WS? LineBreak+ {breakOut();} ;
LineBreak : '\r'? '\n' ;
/* ***** Links ***** */
RawUrl : PROTOCOL (~(' '|'\t'|'\r'|'\n'|'|'|'['|']')+ '/'?)+ {doUrl();} ;
fragment PROTOCOL : ('http' 's'? | 'file' | 'ftp') '://' | 'file:/' | 'mailto:' ;
Attachment : ALNUM+ '.' ALNUM+ ;
WikiWords : (UPPER (ABBR | CAMEL) | INTERWIKI ALNUM+) {checkBounds("[\\.\\w:]", "\\w")}? ;
fragment INTERWIKI : ALPHA ALNUM+ ':' ;
fragment ABBR : UPPER UPPER+ ;
fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ;
/* ***** Macros ***** */
MacroSt : '<<' -> mode(MACRO) ;
/* ***** Miscellaneous ***** */
Any : . ;
WS : (' '|'\t')+ ;
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 : ~(':'|'>')+ ;
MacroEndNoArgs : '>>' -> mode(DEFAULT_MODE) ;
MacroSep : ':' -> mode(MACRO_ARGS) ;
mode MACRO_ARGS;
MacroArgs : . -> more ;
MacroEnd : '>>' -> mode(DEFAULT_MODE) ;
mode CODE_INLINE;
AnyInline : ~('\r'|'\n') -> more;
OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ;
EndNoWikiInline : '}}}' ~'}' {nowiki}? {nowiki=false; seek(-1);} -> mode(DEFAULT_MODE) ;
EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ;
EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ;
EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ;
EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ;
EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
mode CODE_BLOCK;
AnyText : . -> more ;
EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ;
EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ;
EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ;
EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ;
EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ;
EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
|
/* Todo:
* - Comments justifying and explaining every rule.
*/
lexer grammar CreoleTokens;
options { superClass=ContextSensitiveLexer; }
@members {
Formatting bold;
Formatting italic;
Formatting strike;
public void setupFormatting() {
bold = new Formatting("**");
italic = new Formatting("//");
strike = new Formatting("--");
inlineFormatting.add(bold);
inlineFormatting.add(italic);
inlineFormatting.add(strike);
}
public boolean inHeader = false;
public boolean start = false;
public int listLevel = 0;
boolean nowiki = false;
boolean cpp = false;
boolean html = false;
boolean java = false;
boolean xhtml = false;
boolean xml = false;
boolean intr = false;
public void doHdr() {
String prefix = getText().trim();
boolean seekback = false;
if(!prefix.substring(prefix.length() - 1).equals("=")) {
prefix = prefix.substring(0, prefix.length() - 1);
seekback = true;
}
if(prefix.length() <= 6) {
if(seekback) {
seek(-1);
}
setText(prefix);
inHeader = true;
} else {
setType(Any);
}
}
public void setStart() {
String next1 = next();
String next2 = get(1);
start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#"));
}
public void doList(int level) {
listLevel = level;
seek(-1);
setStart();
resetFormatting();
}
public void doUrl() {
String url = getText();
String last = url.substring(url.length()-1);
String next = next();
if(url.endsWith("://") || url.endsWith("mailto:")) { setType(Any); }
while((last + next).equals("//") || last.matches("[\\.,)\"';:]")) {
seek(-1);
url = url.substring(0, url.length() - 1);
last = url.substring(url.length()-1);
next = next();
}
setText(url);
}
public void breakOut() {
resetFormatting();
listLevel = 0;
inHeader = false;
intr = false;
nowiki = false;
cpp = false;
html = false;
java = false;
xhtml = false;
xml = false;
}
public String[] thisKillsTheFormatting() {
String[] ends = new String[7];
if(inHeader || intr) {
ends[0] = "\n";
ends[1] = "\r\n";
} else {
ends[0] = null;
ends[1] = null;
}
if(intr) {
ends[2] = "|";
} else {
ends[2] = null;
}
ends[3] = "\n\n";
ends[4] = "\r\n\r\n";
if(listLevel > 0) {
// \L (when at the start) matches the start of a line.
ends[5] = "\\L*";
ends[6] = "\\L#";
} else {
ends[5] = null;
ends[6] = null;
}
return ends;
}
}
/* ***** Headings ***** */
HSt : LINE '='+ ~'=' {doHdr();} ;
HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ;
/* ***** Lists ***** */
U1 : START '*' ~'*' {doList(1);} ;
U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ;
U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ;
U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ;
U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ;
U6 : START '******' ~'*' {listLevel >= 5}? {doList(6);} ;
U7 : START '*******' ~'*' {listLevel >= 6}? {doList(7);} ;
U8 : START '********' ~'*' {listLevel >= 7}? {doList(8);} ;
U9 : START '*********' ~'*' {listLevel >= 8}? {doList(9);} ;
U10 : START '**********' ~'*' {listLevel >= 9}? {doList(10);} ;
O1 : START '#' ~'#' {doList(1);} ;
O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ;
O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ;
O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ;
O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ;
O6 : START '######' ~'#' {listLevel >= 5}? {doList(6);} ;
O7 : START '#######' ~'#' {listLevel >= 6}? {doList(7);} ;
O8 : START '########' ~'#' {listLevel >= 7}? {doList(8);} ;
O9 : START '#########' ~'#' {listLevel >= 8}? {doList(9);} ;
O10 : START '##########' ~'#' {listLevel >= 9}? {doList(10);} ;
/* ***** Horizontal Rules ***** */
Rule : LINE '---' '-'+ {breakOut();} ;
/* ***** Tables ***** */
TdStartLn : LINE '|'+ {intr=true; setType(TdStart);} ;
ThStartLn : LINE '|'+ '=' {intr=true; setType(ThStart);} ;
RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ;
TdStart : '|'+ {intr}? {breakOut(); intr=true;} ;
ThStart : '|'+ '=' {intr}? {breakOut(); intr=true;} ;
/* ***** Inline Formatting ***** */
BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ;
ISt : '//' {!italic.active && !prior().matches("[a-zA-Z0-9]:")}? {setFormatting(italic, Any);} ;
SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ;
BEnd : '**' {bold.active}? {unsetFormatting(bold);} ;
IEnd : '//' {italic.active && !prior().matches("[a-zA-Z0-9]:")}? {unsetFormatting(italic);} ;
SEnd : '--' {strike.active}? {unsetFormatting(strike);} ;
NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ;
StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ;
StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ;
StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ;
StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ;
StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ;
/* ***** Links ***** */
LiSt : '[[' -> mode(LINK) ;
ImSt : '{{' -> mode(LINK) ;
/* ***** Breaks ***** */
InlineBrk : '\\\\' ;
ParBreak : LineBreak WS? LineBreak+ {breakOut();} ;
LineBreak : '\r'? '\n' ;
/* ***** Links ***** */
RawUrl : PROTOCOL (~(' '|'\t'|'\r'|'\n'|'|'|'['|']')+ '/'?)+ {doUrl();} ;
fragment PROTOCOL : ('http' 's'? | 'file' | 'ftp') '://' | 'file:/' | 'mailto:' ;
Attachment : ALNUM+ '.' ALNUM+ ;
WikiWords : (UPPER (ABBR | CAMEL) | INTERWIKI ALNUM+) {checkBounds("[\\.\\w:]", "\\w")}? ;
fragment INTERWIKI : ALPHA ALNUM+ ':' ;
fragment ABBR : UPPER UPPER+ ;
fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ;
/* ***** Macros ***** */
MacroSt : '<<' -> mode(MACRO) ;
/* ***** Miscellaneous ***** */
Any : . ;
WS : (' '|'\t')+ ;
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 : ~(':'|'>')+ ;
MacroEndNoArgs : '>>' -> mode(DEFAULT_MODE) ;
MacroSep : ':' -> mode(MACRO_ARGS) ;
mode MACRO_ARGS;
MacroArgs : . -> more ;
MacroEnd : '>>' -> mode(DEFAULT_MODE) ;
mode CODE_INLINE;
AnyInline : ~('\r'|'\n') -> more;
OopsItsABlock : ('\r'|'\n') {seek(-1);} -> mode(CODE_BLOCK), more ;
EndNoWikiInline : '}}}' ~'}' {nowiki}? {nowiki=false; seek(-1);} -> mode(DEFAULT_MODE) ;
EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ;
EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ;
EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ;
EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ;
EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
mode CODE_BLOCK;
AnyText : . -> more ;
EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ;
EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ;
EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ;
EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ;
EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ;
EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
|
Handle empty code/nowiki blocks
|
Handle empty code/nowiki blocks
|
ANTLR
|
apache-2.0
|
strr/reviki,ashirley/reviki,CoreFiling/reviki,ashirley/reviki,CoreFiling/reviki,strr/reviki,strr/reviki,CoreFiling/reviki,strr/reviki,CoreFiling/reviki,strr/reviki,ashirley/reviki,ashirley/reviki,ashirley/reviki,CoreFiling/reviki
|
81b6b2a50a680280177b069958f6634c0b07d4cd
|
Heroc.g4
|
Heroc.g4
|
/**
* Define a grammar called Hello
*/
grammar Heroc;
import Lexer;
options {
language=Python3;
}
sourcefile
: source? EOF
;
source
: variableDeclaration
| functionDefinition
| source variableDeclaration
| source functionDefinition
;
variableDeclaration
: LONG initVariableDeclarationList SEMI
;
initVariableDeclarationList
: initDeclaratorVariable (',' initDeclaratorVariable)*
;
initDeclaratorVariable
: pointer? initDeclaratorVariableSimple
| pointer? initDeclaratorVariableSimpleWithValue
| pointer? initDeclaratorArray
| pointer? initDeclaratorArrayWithValue
;
initDeclaratorVariableSimple
: IDENTIFIER
;
initDeclaratorVariableSimpleWithValue
: IDENTIFIER '=' assignmentExpression
;
initDeclaratorArray
: IDENTIFIER ('[' assignmentExpression? ']')+
;
initDeclaratorArrayWithValue
: IDENTIFIER ('[' assignmentExpression? ']')+ '=' initializer
;
initializer
: assignmentExpression
| '{' initializerList '}'
| '{' initializerList ',' '}'
;
initializerList
: initializer (',' initializer)*
;
pointer
: '*'+
;
identifierList
: IDENTIFIER (',' IDENTIFIER)*
;
functionDefinition
: IDENTIFIER '(' identifierList? ')' compoundStatement
;
// ------------------------------------------------------------------
// EXPRESSIONS
// ------------------------------------------------------------------
unaryOperator
: '&' | '*' | '+' | '-' | '~' | '!'
;
assignmentOperator
: '=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '&=' | '^=' | '|='
;
// If expression is constant skip assignment operators in priorities table
constantExpression
: conditionalExpression
;
// Start table of operators from bottom (from lowest priority)
expression
: assignmentExpression
| expression ',' assignmentExpression
;
// Continue to conditionalExpressions in table or create assignment
assignmentExpression
: conditionalExpression
| unaryExpression assignmentOperator assignmentExpression
;
// Conditional Expression is next in table of priority, we can skip to logical or expression
conditionalExpression
: logicalOrExpression ('?' expression ':' conditionalExpression)?
;
// Possible skip to AND expression or loop
logicalOrExpression
: logicalAndExpression
| logicalOrExpression '||' logicalAndExpression
;
// Possible skip to Bitwise OR expression or loop
logicalAndExpression
: bitwiseOrExpression
| logicalAndExpression '&&' bitwiseOrExpression
;
bitwiseOrExpression
: bitwiseXOrExpression
| bitwiseOrExpression '|' bitwiseXOrExpression
;
bitwiseXOrExpression
: andExpression
| bitwiseXOrExpression '^' andExpression
;
andExpression
: equalityExpression
| andExpression '&' equalityExpression
;
equalityExpression
: relationalExpression
| equalityExpression '==' relationalExpression
| equalityExpression '!=' relationalExpression
;
relationalExpression
: shiftExpression
| relationalExpression '<' shiftExpression
| relationalExpression '>' shiftExpression
| relationalExpression '<=' shiftExpression
| relationalExpression '>=' shiftExpression
;
shiftExpression
: additiveExpression
| shiftExpression '<<' additiveExpression
| shiftExpression '>>' additiveExpression
;
additiveExpression
: multiplicativeExpression
| additiveExpression '+' multiplicativeExpression
| additiveExpression '-' multiplicativeExpression
;
// Skipping castExpression here becouse of Heroc
multiplicativeExpression
: unaryExpression
| multiplicativeExpression '*' unaryExpression
| multiplicativeExpression '/' unaryExpression
| multiplicativeExpression '%' unaryExpression
;
unaryExpression
: postfixExpression
| '++' unaryExpression
| '--' unaryExpression
| unaryOperator unaryExpression
| 'sizeof' '(' LONG ')'
| '&&' IDENTIFIER // GCC extension address of label - IDK if we need it for HEROC
// | 'sizeof' unaryExpression - NOT POSSIBLE IN HEROC
;
postfixExpression
: primaryExpression
| postfixExpression '[' expression ']'
| postfixExpression '(' argumentExpressionList? ')'
| postfixExpression '++'
| postfixExpression '--'
// Assign array to variable
| '{' initializerList '}'
| '{' initializerList ',' '}'
// | postfixExpression '.' IDENTIFIER -- NOT POSSIBLE IN HEROC
// | postfixExpression '->' IDENTIFIER -- NOT POSSIBLE IN HEROC
;
argumentExpressionList
: assignmentExpression (',' assignmentExpression)*
// | argumentExpressionList ',' assignmentExpression
;
primaryExpression
: IDENTIFIER
| CONSTANT
| STRING+
| '(' expression ')'
;
// ------------------------------------------------------------------
// Main block of codes
// ------------------------------------------------------------------
statement
: compoundStatement
| functionCallStatement
| expressionStatement
| selectionStatement
| iterationStatement
| jumpStatement
;
compoundStatement
: '{' blockItemList? '}'
;
blockItemList
: blockItem+
;
blockItem
: variableDeclaration
| statement
;
functionCallStatement
: IDENTIFIER '(' argumentExpressionList? ')' SEMI
;
expressionStatement
: expression? SEMI
;
selectionStatement
: 'if' '(' expression ')' compoundStatement ('else' compoundStatement)?
;
iterationStatement
: 'while' '(' expression ')' statement
| 'do' statement 'while' '(' expression ')' SEMI
| 'for' '(' expression? SEMI expression? SEMI expression? ')' statement
| 'for' '(' variableDeclaration expression? SEMI expression? ')' statement
;
jumpStatement
: 'continue' SEMI
| 'break' SEMI
| 'return' expression? SEMI
;
|
/**
* Define a grammar called Hello
*/
grammar Heroc;
import Lexer;
options {
language=Python3;
}
sourcefile
: source? EOF
;
source
: variableDeclaration
| functionDefinition
| source variableDeclaration
| source functionDefinition
;
variableDeclaration
: LONG initVariableDeclarationList SEMI
;
initVariableDeclarationList
: initDeclaratorVariable (',' initDeclaratorVariable)*
;
initDeclaratorVariable
: pointer? initDeclaratorVariableSimple
| pointer? initDeclaratorVariableSimpleWithValue
| pointer? initDeclaratorArray
| pointer? initDeclaratorArrayWithValue
;
initDeclaratorVariableSimple
: IDENTIFIER
;
initDeclaratorVariableSimpleWithValue
: IDENTIFIER '=' expression
;
initDeclaratorArray
: IDENTIFIER ('[' expression? ']')+
;
initDeclaratorArrayWithValue
: IDENTIFIER ('[' expression? ']')+ '=' initializer
;
initializer
: expression
| '{' initializerList '}'
| '{' initializerList ',' '}'
;
initializerList
: initializer (',' initializer)*
;
pointer
: '*'+
;
identifierList
: IDENTIFIER (',' IDENTIFIER)*
;
functionDefinition
: IDENTIFIER '(' identifierList? ')' compoundStatement
;
// ------------------------------------------------------------------
// EXPRESSIONS
// ------------------------------------------------------------------
unaryOperator
: '&' | '*' | '+' | '-' | '~' | '!'
;
assignmentOperator
: '=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '&=' | '^=' | '|='
;
// If expression is constant skip assignment operators in priorities table
constantExpression
: conditionalExpression
;
// Start table of operators from bottom (from lowest priority)
//expression
// : assignmentExpression
// | expression ',' assignmentExpression
// ;
// Continue to conditionalExpressions in table or create assignment
expression
: conditionalExpression
| unaryExpression assignmentOperator expression
;
// Conditional Expression is next in table of priority, we can skip to logical or expression
conditionalExpression
: logicalOrExpression ('?' expression ':' conditionalExpression)?
;
// Possible skip to AND expression or loop
logicalOrExpression
: logicalAndExpression
| logicalOrExpression '||' logicalAndExpression
;
// Possible skip to Bitwise OR expression or loop
logicalAndExpression
: bitwiseOrExpression
| logicalAndExpression '&&' bitwiseOrExpression
;
bitwiseOrExpression
: bitwiseXOrExpression
| bitwiseOrExpression '|' bitwiseXOrExpression
;
bitwiseXOrExpression
: andExpression
| bitwiseXOrExpression '^' andExpression
;
andExpression
: equalityExpression
| andExpression '&' equalityExpression
;
equalityExpression
: relationalExpression
| equalityExpression '==' relationalExpression
| equalityExpression '!=' relationalExpression
;
relationalExpression
: shiftExpression
| relationalExpression '<' shiftExpression
| relationalExpression '>' shiftExpression
| relationalExpression '<=' shiftExpression
| relationalExpression '>=' shiftExpression
;
shiftExpression
: additiveExpression
| shiftExpression '<<' additiveExpression
| shiftExpression '>>' additiveExpression
;
additiveExpression
: multiplicativeExpression
| additiveExpression '+' multiplicativeExpression
| additiveExpression '-' multiplicativeExpression
;
// Skipping castExpression here becouse of Heroc
multiplicativeExpression
: unaryExpression
| multiplicativeExpression '*' unaryExpression
| multiplicativeExpression '/' unaryExpression
| multiplicativeExpression '%' unaryExpression
;
unaryExpression
: postfixExpression
| '++' unaryExpression
| '--' unaryExpression
| unaryOperator unaryExpression
| 'sizeof' '(' LONG ')'
| '&&' IDENTIFIER // GCC extension address of label - IDK if we need it for HEROC
// | 'sizeof' unaryExpression - NOT POSSIBLE IN HEROC
;
postfixExpression
: primaryExpression
| postfixExpression '[' expression ']'
| postfixExpression '(' argumentExpressionList? ')'
| postfixExpression '++'
| postfixExpression '--'
// Assign array to variable
| '{' initializerList '}'
| '{' initializerList ',' '}'
// | postfixExpression '.' IDENTIFIER -- NOT POSSIBLE IN HEROC
// | postfixExpression '->' IDENTIFIER -- NOT POSSIBLE IN HEROC
;
argumentExpressionList
: expression (',' expression)*
// | argumentExpressionList ',' assignmentExpression
;
primaryExpression
: IDENTIFIER
| CONSTANT
| STRING+
| '(' expression ')'
;
// ------------------------------------------------------------------
// Main block of codes
// ------------------------------------------------------------------
statement
: compoundStatement
| functionCallStatement
| expressionStatement
| selectionStatement
| iterationStatement
| jumpStatement
;
compoundStatement
: '{' blockItemList? '}'
;
blockItemList
: blockItem+
;
blockItem
: variableDeclaration
| statement
;
functionCallStatement
: IDENTIFIER '(' argumentExpressionList? ')' SEMI
;
expressionStatement
: expression? SEMI
;
selectionStatement
: 'if' '(' expression ')' compoundStatement ('else' compoundStatement)?
;
iterationStatement
: 'while' '(' expression ')' statement
| 'do' statement 'while' '(' expression ')' SEMI
| 'for' '(' expression? SEMI expression? SEMI expression? ')' statement
| 'for' '(' variableDeclaration expression? SEMI expression? ')' statement
;
jumpStatement
: 'continue' SEMI
| 'break' SEMI
| 'return' expression? SEMI
;
|
Disable ‘,’ as expression.
|
Disable ‘,’ as expression.
|
ANTLR
|
mit
|
wilima/herocomp,wilima/herocomp,wilima/herocomp
|
4476dc6f64708a37641a061c31fff019784f333e
|
src/main/antlr/ConnectorLexer.g4
|
src/main/antlr/ConnectorLexer.g4
|
lexer grammar ConnectorLexer;
@ header {
}
INSERT
: 'insert' | 'INSERT'
;
UPSERT
: 'upsert' | 'UPSERT'
;
INTO
: 'into' | 'INTO'
;
SELECT
: 'select' | 'SELECT'
;
FROM
: 'from' | 'FROM'
;
IGNORE
: 'ignore' | 'IGNORE'
;
AS
: 'as' | 'AS'
;
AUTOCREATE
: 'autocreate' | 'AUTOCREATE'
;
AUTOEVOLVE
: 'autoevolve' | 'AUTOEVOLVE'
;
CLUSTERBY
: 'clusterby' | 'CLUSTERBY'
;
BUCKETS
: 'buckets'|'BUCKETS'
;
BATCH
: 'batch' | 'BATCH'
;
CAPITALIZE
: 'capitalize' | 'CAPITALIZE'
;
INITIALIZE
: 'initialize' | 'INITIALIZE'
;
PARTITIONBY
: 'partitionby' | 'PARTITIONBY'
;
DISTRIBUTEBY
: 'distributeby' | 'DISTRIBUTEBY'
;
TIMESTAMP
: 'withtimestamp' | 'WITHTIMESTAMP'
;
SYS_TIME
: 'sys_time()' | 'SYS_TIME()'
;
WITHGROUP
: 'withgroup' | 'WITHGROUP'
;
WITHOFFSET
: 'withoffset' | 'WITHOFFSET'
;
PK
: 'pk' | 'PK'
;
SAMPLE
: 'sample' | 'SAMPLE'
;
EVERY
: 'every'|'EVERY'
;
WITHFORMAT
: 'WITHFORMAT'|'withformat'
;
FORMAT
: 'avro'|'AVRO'|'text'|'TEXT'|'binary'|'BINARY'|'json'|'JSON'
;
PROJECTTO
: 'projectTo'|'PROJECTTO'|'projectto'
;
DATABASE
: ''
EQUAL
: '='
;
INT
: '0' .. '9'+
;
ASTERISK
: '*'
;
COMMA
: ','
;
DOT
: '.'
;
LEFT_PARAN
: '('
;
RIGHT_PARAN
: ')'
;
ID
: ( 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' )+
;
TOPICNAME
: ( 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9'| '.' | '-' | '+' )+
;
NEWLINE
: '\r'? '\n' -> skip
;
WS
: ( ' ' | '\t' | '\n' | '\r' )+ -> skip
;
|
lexer grammar ConnectorLexer;
@ header {
}
INSERT
: 'insert' | 'INSERT'
;
UPSERT
: 'upsert' | 'UPSERT'
;
INTO
: 'into' | 'INTO'
;
SELECT
: 'select' | 'SELECT'
;
FROM
: 'from' | 'FROM'
;
IGNORE
: 'ignore' | 'IGNORE'
;
AS
: 'as' | 'AS'
;
AUTOCREATE
: 'autocreate' | 'AUTOCREATE'
;
AUTOEVOLVE
: 'autoevolve' | 'AUTOEVOLVE'
;
CLUSTERBY
: 'clusterby' | 'CLUSTERBY'
;
BUCKETS
: 'buckets'|'BUCKETS'
;
BATCH
: 'batch' | 'BATCH'
;
CAPITALIZE
: 'capitalize' | 'CAPITALIZE'
;
INITIALIZE
: 'initialize' | 'INITIALIZE'
;
PARTITIONBY
: 'partitionby' | 'PARTITIONBY'
;
DISTRIBUTEBY
: 'distributeby' | 'DISTRIBUTEBY'
;
TIMESTAMP
: 'withtimestamp' | 'WITHTIMESTAMP'
;
SYS_TIME
: 'sys_time()' | 'SYS_TIME()'
;
WITHGROUP
: 'withgroup' | 'WITHGROUP'
;
WITHOFFSET
: 'withoffset' | 'WITHOFFSET'
;
PK
: 'pk' | 'PK'
;
SAMPLE
: 'sample' | 'SAMPLE'
;
EVERY
: 'every'|'EVERY'
;
WITHFORMAT
: 'WITHFORMAT'|'withformat'
;
FORMAT
: 'avro'|'AVRO'|'text'|'TEXT'|'binary'|'BINARY'|'json'|'JSON'
;
PROJECTTO
: 'projectTo'|'PROJECTTO'|'projectto'
;
EQUAL
: '='
;
INT
: '0' .. '9'+
;
ASTERISK
: '*'
;
COMMA
: ','
;
DOT
: '.'
;
LEFT_PARAN
: '('
;
RIGHT_PARAN
: ')'
;
ID
: ( 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' )+
;
TOPICNAME
: ( 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9'| '.' | '-' | '+' )+
;
NEWLINE
: '\r'? '\n' -> skip
;
WS
: ( ' ' | '\t' | '\n' | '\r' )+ -> skip
;
|
add support for initialize
|
add support for initialize
|
ANTLR
|
apache-2.0
|
datamountaineer/kafka-connect-query-language,datamountaineer/kafka-connect-query-language
|
7f117294f5a372680e55caa9663ec09ab9318d16
|
sharding-jdbc-ddl-parser/src/main/resources/io/shardingsphere/parser/antlr/mysql/MySQLDML.g4
|
sharding-jdbc-ddl-parser/src/main/resources/io/shardingsphere/parser/antlr/mysql/MySQLDML.g4
|
grammar MySQLDML;
import MySQLBase,MySQLKeyword,DMLBase,SQLBase,Keyword,Symbol;
@header{
package io.shardingsphere.parser.antlr.mysql;
}
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?
;
//https://dev.mysql.com/doc/refman/8.0/en/join.html
tableReferences:
tableReference(COMMA tableReference)*
;
tableReference:
(tableFactor joinTable)+
| tableFactor joinTable+
| tableFactor
;
tableFactor:
tableName (PARTITION itemList)?
(AS? alias)? indexHintList?
| subquery AS? alias
| LEFT_PAREN tableReferences RIGHT_PAREN
;
joinTable:
(INNER | CROSS)? JOIN tableFactor joinCondition?
| STRAIGHT_JOIN tableFactor
| STRAIGHT_JOIN tableFactor joinCondition
| (LEFT|RIGHT) OUTER? JOIN tableFactor joinCondition
| NATURAL (INNER | (LEFT|RIGHT) (OUTER))? JOIN tableFactor
;
joinCondition:
ON expr
| USING itemList
;
indexHintList:
indexHint(COMMA indexHint)*
;
indexHint:
USE (INDEX|KEY) (FOR (JOIN|ORDER BY|GROUP BY))* itemList
| IGNORE (INDEX|KEY) (FOR (JOIN|ORDER BY|GROUP BY))* itemList
;
//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
;
partitionClause:
PARTITION itemList
;
columnClause:
itemListWithEmpty? (valueClause | select)
;
valueClause:
(VALUES | VALUE) valueList (COMMA valueList)*
;
setClause:
SET assignmentList
;
onDuplicateClause:
ON DUPLICATE KEY UPDATE assignmentList
;
itemListWithEmpty:
(LEFT_PAREN RIGHT_PAREN)
|itemList
;
assignmentList:
assignment (COMMA assignment)*
;
assignment:
columnName EQ_OR_ASSIGN value;
//override update rule
updateClause:
UPDATE updateSpec tableReferences
;
updateSpec:
LOW_PRIORITY? IGNORE?
;
item: ID;
|
grammar MySQLDML;
import MySQLBase,MySQLKeyword,DMLBase,SQLBase,Keyword,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?
;
//https://dev.mysql.com/doc/refman/8.0/en/join.html
tableReferences:
tableReference(COMMA tableReference)*
;
tableReference:
(tableFactor joinTable)+
| tableFactor joinTable+
| tableFactor
;
tableFactor:
tableName (PARTITION itemList)?
(AS? alias)? indexHintList?
| subquery AS? alias
| LEFT_PAREN tableReferences RIGHT_PAREN
;
joinTable:
(INNER | CROSS)? JOIN tableFactor joinCondition?
| STRAIGHT_JOIN tableFactor
| STRAIGHT_JOIN tableFactor joinCondition
| (LEFT|RIGHT) OUTER? JOIN tableFactor joinCondition
| NATURAL (INNER | (LEFT|RIGHT) (OUTER))? JOIN tableFactor
;
joinCondition:
ON expr
| USING itemList
;
indexHintList:
indexHint(COMMA indexHint)*
;
indexHint:
USE (INDEX|KEY) (FOR (JOIN|ORDER BY|GROUP BY))* itemList
| IGNORE (INDEX|KEY) (FOR (JOIN|ORDER BY|GROUP BY))* itemList
;
//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
;
partitionClause:
PARTITION itemList
;
columnClause:
itemListWithEmpty? (valueClause | select)
;
valueClause:
(VALUES | VALUE) valueList (COMMA valueList)*
;
setClause:
SET assignmentList
;
onDuplicateClause:
ON DUPLICATE KEY UPDATE assignmentList
;
itemListWithEmpty:
(LEFT_PAREN RIGHT_PAREN)
|itemList
;
assignmentList:
assignment (COMMA assignment)*
;
assignment:
columnName EQ_OR_ASSIGN value;
//override update rule
updateClause:
UPDATE updateSpec tableReferences
;
updateSpec:
LOW_PRIORITY? IGNORE?
;
item: ID;
|
remove package
|
remove package
|
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
|
f8552a886d053a8943e5986e74d73ca59d53da5d
|
dsl-parser/src/main/antlr4/com/mattunderscore/specky/parser/Specky.g4
|
dsl-parser/src/main/antlr4/com/mattunderscore/specky/parser/Specky.g4
|
/* Copyright © 2016 Matthew Champion
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of mattunderscore.com nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL MATTHEW CHAMPION BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
parser grammar Specky;
options { tokenVocab=SpeckyLexer; }
string_value
: (StringLiteral | MULTILINE_STRING_LITERAL)
;
construction
: CONSTRUCTOR
| MUTABLE_BUILDER
| IMMUTABLE_BUILDER
;
default_value
: DEFAULT LITERAL_INLINE_WS ANYTHING
;
typeParameters
: OPEN_TYPE_PARAMETERS Identifier (INLINE_WS Identifier)* CLOSE_TYPE_PARAMETERS
;
propertyName
: Identifier
| VALUE
| BEAN
| TYPE
| CONSTRUCTOR
| MUTABLE_BUILDER
| OPTIONAL
| PROPERTIES
| IMPORT
| OPTIONS
| AUTHOR
| LICENCE
| SECTION
;
constraint_operator
: GREATER_THAN
| LESS_THAN
| GREATER_THAN_OR_EQUAL
| LESS_THAN_OR_EQUAL
| EQUAL_TO
;
constraint_literal
: REAL_LITERAL
| INTEGER_LITERAL
| STRING_LITERAL
;
constraint_predicate
: constraint_operator CONSTRAINT_INLINE_WS constraint_literal
;
constraint_expression
: constraint_predicate
| NEGATION CONSTRAINT_INLINE_WS constraint_expression
| SIZE_OF CONSTRAINT_INLINE_WS constraint_expression
| HAS_SOME CONSTRAINT_INLINE_WS constraint_expression
;
constraint_disjunctions_expression
: constraint_expression
| OPEN_PARENTHESIS CONSTRAINT_INLINE_WS? constraint_expression (CONSTRAINT_INLINE_WS DISJUNCTION CONSTRAINT_INLINE_WS constraint_expression)* CONSTRAINT_INLINE_WS? CLOSE_PARENTHESIS
;
constraint_conjunctions_expression
: constraint_disjunctions_expression (CONSTRAINT_INLINE_WS CONJUNCTION CONSTRAINT_INLINE_WS constraint_disjunctions_expression)*
;
constraint_statement
: CONSTRAINT_EXPRESSION CONSTRAINT_INLINE_WS constraint_conjunctions_expression CONSTRAINT_END
;
property
: (OPTIONAL INLINE_WS)? Identifier typeParameters? INLINE_WS propertyName (INLINE_WS default_value)? (INLINE_WS constraint_statement)? (INLINE_WS StringLiteral)?
;
qualifiedName
: Identifier (PACKAGE_SEPARATOR Identifier)*
;
package_name
: PACKAGE INLINE_WS qualifiedName
;
singleImport
: qualifiedName (INLINE_WS default_value)?
;
imports
: IMPORT LINE_BREAK
(INLINE_WS? singleImport LINE_BREAK)+
;
props
: PROPERTIES LINE_BREAK
(INLINE_WS? property LINE_BREAK)+
;
opts
: OPTIONS LINE_BREAK
INLINE_WS? construction? LINE_BREAK
;
supertypes
: EXTENDS (INLINE_WS Identifier)+
;
implementationSpec
: (VALUE | BEAN ) INLINE_WS Identifier (INLINE_WS supertypes)? (INLINE_WS StringLiteral)? LINE_BREAK
(INLINE_WS? props)?
(INLINE_WS? opts)?
;
typeSpec
: TYPE INLINE_WS Identifier (INLINE_WS supertypes)? (INLINE_WS StringLiteral)? LINE_BREAK
(INLINE_WS? props)?
;
author
: AUTHOR INLINE_WS string_value
;
licence
: LICENCE INLINE_WS string_value
;
sectionContent
: (licence LINE_BREAK+)?
(author LINE_BREAK+)?
package_name LINE_BREAK+
(imports LINE_BREAK*)?
((typeSpec | implementationSpec) LINE_BREAK*)+
;
spec
: LINE_BREAK* sectionContent? (SECTION string_value? LINE_BREAK* sectionContent)*
;
|
/* Copyright © 2016 Matthew Champion
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of mattunderscore.com nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL MATTHEW CHAMPION BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
parser grammar Specky;
options { tokenVocab=SpeckyLexer; }
string_value
: (StringLiteral | MULTILINE_STRING_LITERAL)
;
construction
: CONSTRUCTOR
| MUTABLE_BUILDER
| IMMUTABLE_BUILDER
;
default_value
: DEFAULT LITERAL_INLINE_WS ANYTHING
;
typeParameters
: OPEN_TYPE_PARAMETERS Identifier (INLINE_WS Identifier)* CLOSE_TYPE_PARAMETERS
;
propertyName
: Identifier
| VALUE
| BEAN
| TYPE
| CONSTRUCTOR
| MUTABLE_BUILDER
| OPTIONAL
| PROPERTIES
| IMPORT
| OPTIONS
| AUTHOR
| LICENCE
| SECTION
;
constraint_operator
: GREATER_THAN
| LESS_THAN
| GREATER_THAN_OR_EQUAL
| LESS_THAN_OR_EQUAL
| EQUAL_TO
;
constraint_literal
: REAL_LITERAL
| INTEGER_LITERAL
| STRING_LITERAL
;
constraint_predicate
: constraint_operator CONSTRAINT_INLINE_WS constraint_literal
;
constraint_expression
: constraint_predicate
| NEGATION CONSTRAINT_INLINE_WS constraint_expression
| SIZE_OF CONSTRAINT_INLINE_WS constraint_expression
| HAS_SOME CONSTRAINT_INLINE_WS constraint_expression
;
constraint_disjunctions_expression
: constraint_expression
| OPEN_PARENTHESIS CONSTRAINT_INLINE_WS? constraint_expression (CONSTRAINT_INLINE_WS DISJUNCTION CONSTRAINT_INLINE_WS constraint_expression)* CONSTRAINT_INLINE_WS? CLOSE_PARENTHESIS
;
constraint_conjunctions_expression
: constraint_disjunctions_expression (CONSTRAINT_INLINE_WS CONJUNCTION CONSTRAINT_INLINE_WS constraint_disjunctions_expression)*
;
constraint_statement
: CONSTRAINT_EXPRESSION CONSTRAINT_INLINE_WS constraint_conjunctions_expression CONSTRAINT_END
;
property
: (OPTIONAL INLINE_WS)? Identifier typeParameters? INLINE_WS propertyName (INLINE_WS default_value)? (INLINE_WS constraint_statement)? (INLINE_WS StringLiteral)?
;
qualifiedName
: Identifier (PACKAGE_SEPARATOR Identifier)*
;
package_name
: PACKAGE INLINE_WS qualifiedName
;
singleImport
: qualifiedName (INLINE_WS default_value)?
;
imports
: IMPORT LINE_BREAK
(INLINE_WS? singleImport LINE_BREAK)+
;
props
: PROPERTIES LINE_BREAK
(INLINE_WS? property LINE_BREAK)+
;
opts
: OPTIONS LINE_BREAK
INLINE_WS? construction? LINE_BREAK
;
supertypes
: EXTENDS (INLINE_WS Identifier)+
;
implementationSpec
: (VALUE | BEAN ) INLINE_WS Identifier (INLINE_WS supertypes)? (INLINE_WS StringLiteral)? LINE_BREAK
(INLINE_WS? props)?
(INLINE_WS? opts)?
;
typeSpec
: TYPE INLINE_WS Identifier (INLINE_WS supertypes)? (INLINE_WS StringLiteral)? LINE_BREAK
(INLINE_WS? props)?
;
author
: AUTHOR INLINE_WS string_value
;
licence
: LICENCE INLINE_WS string_value
;
sectionContent
: (licence LINE_BREAK+)?
(author LINE_BREAK+)?
package_name LINE_BREAK+
(imports LINE_BREAK*)?
((typeSpec | implementationSpec) LINE_BREAK*)+
;
spec
: LINE_BREAK* sectionContent? (SECTION (INLINE_WS string_value)? LINE_BREAK+ sectionContent)*
;
|
Fix syntax parsing issue. Require inline whitespace between the section keyword and section description.
|
Fix syntax parsing issue. Require inline whitespace between the section keyword and section description.
|
ANTLR
|
bsd-3-clause
|
mattunderscorechampion/specky,mattunderscorechampion/specky,mattunderscorechampion/specky
|
3850e6baa26a0290064a5e03e22cf5287c12e1db
|
DecisionModel/src/antlr/DeciLan.g4
|
DecisionModel/src/antlr/DeciLan.g4
|
/**
* Define a grammar called OuhangFirst
* this grammar is similar to Java while much simpler
*/
grammar DeciLan;
/**
* Package.
*/
packageDeclaration
: 'package' Identifier (DOT Identifier)* ';'
;
/**
* Import model.
*/
importModelDeclaration
: 'import-model' Identifier (DOT Identifier)* ('.*')? ';'
;
/**
* Import java.
*/
importJavaDeclaration
: 'import' Identifier (DOT Identifier)* ('.*')? ';'
;
/**
* Inject.
*/
injectDeclaration
: 'inject' '{' fieldStatement* '}'
;
/**
* Input.
*/
inputDeclaration
: 'input' '{' fieldStatement* '}'
;
fieldStatement
: Identifier ':' (Identifier | TypeWithParameters) ';'
;
/**
* Function.
*/
functionDeclaration
: 'func' (Identifier | TypeWithParameters) Identifier parameterList '{' statement* '}'
;
/**
* Model.
*/
modelDeclaration
: 'model' (Identifier | TypeWithParameters) Identifier '{' statement* '}'
;
parameterList
: '(' ((parameterDeclaration ',')* parameterDeclaration)? ')'
;
parameterDeclaration
: (Identifier | TypeWithParameters) Identifier
;
/**
* Statement.
*/
statement
: localVariableDeclarationStatement
| variableAssignmentStatement
| exprCallMethod ';'
| '{' statement '}'
| 'if' '(' expr ')' statement
('elif' '(' expr ')' statement)?
( 'else' statement )?
| returnStatement
;
returnStatement
: 'return' expr ';'
;
localVariableDeclarationStatement
: (Identifier | TypeWithParameters) Identifier ';'
| (Identifier | TypeWithParameters) variableAssignmentStatement
;
variableAssignmentStatement
: Identifier ASSIGN expr ';'
| Identifier ADD_ASSIGN expr ';'
| Identifier SUB_ASSIGN expr ';'
| Identifier MUL_ASSIGN expr ';'
| Identifier DIV_ASSIGN expr ';'
| Identifier MOD_ASSIGN expr ';'
;
expr // Expression will always have a value
: exprBooleanOper | exprAddSub | exprMulDivMod | exprNot | exprAtom
;
exprBooleanOper
: (exprAtom | exprNot | exprMulDivMod | exprAddSub)
((LT | LTE | GT | GTE | EQ | NEQ | AND | OR)
(exprAtom | exprNot | exprMulDivMod | exprAddSub))+
;
exprAddSub
: (exprAtom | exprNot | exprMulDivMod) ((ADD | SUB) (exprAtom | exprNot | exprMulDivMod))+
;
exprMulDivMod
: (exprAtom | exprNot) ((MUL | DIV | MOD) (exprAtom | exprNot))+
;
exprNot
: NOT exprAtom
;
exprAtom
: Identifier | NULL | NAN | literal
| exprCallMethod
| '(' expr ')'
;
exprCallMethod
: (Identifier '.')? Identifier '(' ((expr ',')* expr)?')'
;
/**
* Tokens, include:
* identifiers, types, literals, operators, separators and esc.
*/
Identifier // For Variable, Model or Function name
: [a-zA-Z] [a-zA-Z_0-9]* // must start with letter
;
TypeWithParameters
: Identifier TypeParameters
;
TypeParameters // doesn't support "extends", "super", template and array [] in type
: '<' (Identifier | TypeWithParameters) (',' (Identifier | TypeWithParameters))* '>'
;
/**
* Literals, a much more simple version than Java literals.
* For numeric literals, only support decimal.
* Doesn't support scientific notation currently.
*/
literal
: StringLiteral
| BooleanLiteral
| IntegerLiteral
| LongLiteral
| FloatLiteral
| DoubleLiteral
;
StringLiteral //? support unicode should check
: '"' StringCharacters? '"'
;
CharLiteral
: '\'' SingleCharacter '\''
| '\'' EscapeSequence '\''
;
BooleanLiteral
: TRUE | FALSE
;
IntegerLiteral
: NumericSign? (NonZeroDigits+ '0'*)* Digits
;
LongLiteral
: IntegerLiteral 'L'
;
FloatLiteral
: NumericSign? (NonZeroDigits+ '0'*)* Digits '.' Digits+ 'f'?
;
DoubleLiteral
: NumericSign? (NonZeroDigits+ '0'*)* Digits '.' Digits+ 'd'
;
fragment NumericSign
: [+-]
;
fragment Digits
: [0-9]
;
fragment NonZeroDigits
: [1-9]
;
fragment StringCharacters
: StringCharacter+
;
fragment StringCharacter
: ~["\\]
;
fragment SingleCharacter
: ~['\\]
;
fragment EscapeSequence
: '\\' [btnfr"'\\]
| '\\' OctalDigit // Octal Escape
| '\\' OctalDigit OctalDigit // Octal Escape
| '\\' [0-3] OctalDigit OctalDigit // Octal Escape
| '\\' 'u' HexDigit HexDigit HexDigit HexDigit // Unicode Escape
;
fragment OctalDigit
: [0-7]
;
fragment HexDigit
: [0-9a-fA-F]
;
/**
* Keywords.
*/
TRUE : 'true' ;
FALSE : 'false';
NULL : 'null' ;
NAN : 'nan' ;
VOID : 'void' ;
// Operators
GT : '>' ;
LT : '<' ;
GTE : '>=' ;
LTE : '<=' ;
EQ : '==' ;
NEQ : '!=' ;
ADD : '+' ;
SUB : '-' ;
MUL : '*' ;
DIV : '/' ;
MOD : '%' ;
AND : '&&' ;
OR : '||' ;
NOT : '!' ;
COLON : ':' ;
ASSIGN : '=' ;
ADD_ASSIGN : '+=' ;
SUB_ASSIGN : '-=' ;
MUL_ASSIGN : '*=' ;
DIV_ASSIGN : '/=' ;
MOD_ASSIGN : '%=' ;
// Separators
LPAREN : '(' ;
RPAREN : ')' ;
LBRACE : '{' ;
RBRACE : '}' ;
LBRACK : '[' ;
RBRACK : ']' ;
SEMI : ';' ;
COMMA : ',' ;
DOT : '.' ;
// Ignore
WS : [ \t\n\r\u000c]+ -> skip;
COMMENT : '/*' .*? '*/' -> skip;
LINE_COMMENT : '//' ~[\r\n]* -> skip;
/**
* CR (Carriage Return): \r, used in Mac OS before X
* LF (Line Feed): \n, used in Unix/Max OS X
* CR + LF: \r\n, used in Windows
*/
|
/**
* Define a grammar called OuhangFirst
* this grammar is similar to Java while much simpler
*/
grammar DeciLan;
/**
* Package.
*/
packageDeclaration
: 'package' Identifier (DOT Identifier)* ';'
;
/**
* Import model.
*/
importModelDeclaration
: 'import-model' Identifier (DOT Identifier)* ('.*')? ';'
;
/**
* Import java.
*/
importJavaDeclaration
: 'import' Identifier (DOT Identifier)* ('.*')? ';'
;
/**
* Inject.
*/
injectDeclaration
: 'inject' '{' fieldStatement* '}'
;
/**
* Input.
*/
inputDeclaration
: 'input' '{' fieldStatement* '}'
;
fieldStatement
: Identifier ':' (Identifier | TypeWithParameters) ';'
;
/**
* Function.
*/
functionDeclaration
: 'func' (Identifier | TypeWithParameters) Identifier parameterList '{' statement* '}'
;
/**
* Signal Attributes.
*/
signalAttributesDeclaration
: Identifier '{' variableAssignmentStatement+ '}'
;
/**
* Model.
*/
modelDeclaration
: 'model' (Identifier | TypeWithParameters) Identifier '{' statement* '}'
;
parameterList
: '(' ((parameterDeclaration ',')* parameterDeclaration)? ')'
;
parameterDeclaration
: (Identifier | TypeWithParameters) Identifier
;
/**
* Statement.
*/
statement
: localVariableDeclarationStatement
| variableAssignmentStatement
| exprCallMethod ';'
| '{' statement '}'
| 'if' '(' expr ')' statement
('elif' '(' expr ')' statement)?
( 'else' statement )?
| returnStatement
;
returnStatement
: 'return' expr ';'
;
localVariableDeclarationStatement
: (Identifier | TypeWithParameters) Identifier ';'
| (Identifier | TypeWithParameters) variableAssignmentStatement
;
variableAssignmentStatement
: Identifier ASSIGN expr ';'
| Identifier ADD_ASSIGN expr ';'
| Identifier SUB_ASSIGN expr ';'
| Identifier MUL_ASSIGN expr ';'
| Identifier DIV_ASSIGN expr ';'
| Identifier MOD_ASSIGN expr ';'
;
expr // Expression will always have a value
: exprBooleanOper | exprAddSub | exprMulDivMod | exprNot | exprAtom
;
exprBooleanOper
: (exprAtom | exprNot | exprMulDivMod | exprAddSub)
((LT | LTE | GT | GTE | EQ | NEQ | AND | OR)
(exprAtom | exprNot | exprMulDivMod | exprAddSub))+
;
exprAddSub
: (exprAtom | exprNot | exprMulDivMod) ((ADD | SUB) (exprAtom | exprNot | exprMulDivMod))+
;
exprMulDivMod
: (exprAtom | exprNot) ((MUL | DIV | MOD) (exprAtom | exprNot))+
;
exprNot
: NOT exprAtom
;
exprAtom
: Identifier | NULL | NAN | literal
| exprCallMethod
| '(' expr ')'
;
exprCallMethod
: (Identifier '.')? Identifier '(' ((expr ',')* expr)?')'
;
/**
* Tokens, include:
* identifiers, types, literals, operators, separators and esc.
*/
Identifier // For Variable, Model or Function name
: [a-zA-Z] [a-zA-Z_0-9]* // must start with letter
;
TypeWithParameters
: Identifier TypeParameters
;
TypeParameters // doesn't support "extends", "super", template and array [] in type
: '<' (Identifier | TypeWithParameters) (',' (Identifier | TypeWithParameters))* '>'
;
/**
* Literals, a much more simple version than Java literals.
* For numeric literals, only support decimal.
* Doesn't support scientific notation currently.
*/
literal
: StringLiteral
| BooleanLiteral
| IntegerLiteral
| LongLiteral
| FloatLiteral
| DoubleLiteral
;
StringLiteral //? support unicode should check
: '"' StringCharacters? '"'
;
CharLiteral
: '\'' SingleCharacter '\''
| '\'' EscapeSequence '\''
;
BooleanLiteral
: TRUE | FALSE
;
IntegerLiteral
: NumericSign? (NonZeroDigits+ '0'*)* Digits
;
LongLiteral
: IntegerLiteral 'L'
;
FloatLiteral
: NumericSign? (NonZeroDigits+ '0'*)* Digits '.' Digits+ 'f'?
;
DoubleLiteral
: NumericSign? (NonZeroDigits+ '0'*)* Digits '.' Digits+ 'd'
;
fragment NumericSign
: [+-]
;
fragment Digits
: [0-9]
;
fragment NonZeroDigits
: [1-9]
;
fragment StringCharacters
: StringCharacter+
;
fragment StringCharacter
: ~["\\]
;
fragment SingleCharacter
: ~['\\]
;
fragment EscapeSequence
: '\\' [btnfr"'\\]
| '\\' OctalDigit // Octal Escape
| '\\' OctalDigit OctalDigit // Octal Escape
| '\\' [0-3] OctalDigit OctalDigit // Octal Escape
| '\\' 'u' HexDigit HexDigit HexDigit HexDigit // Unicode Escape
;
fragment OctalDigit
: [0-7]
;
fragment HexDigit
: [0-9a-fA-F]
;
/**
* Keywords.
*/
TRUE : 'true' ;
FALSE : 'false';
NULL : 'null' ;
NAN : 'nan' ;
VOID : 'void' ;
// Operators
GT : '>' ;
LT : '<' ;
GTE : '>=' ;
LTE : '<=' ;
EQ : '==' ;
NEQ : '!=' ;
ADD : '+' ;
SUB : '-' ;
MUL : '*' ;
DIV : '/' ;
MOD : '%' ;
AND : '&&' ;
OR : '||' ;
NOT : '!' ;
COLON : ':' ;
ASSIGN : '=' ;
ADD_ASSIGN : '+=' ;
SUB_ASSIGN : '-=' ;
MUL_ASSIGN : '*=' ;
DIV_ASSIGN : '/=' ;
MOD_ASSIGN : '%=' ;
// Separators
LPAREN : '(' ;
RPAREN : ')' ;
LBRACE : '{' ;
RBRACE : '}' ;
LBRACK : '[' ;
RBRACK : ']' ;
SEMI : ';' ;
COMMA : ',' ;
DOT : '.' ;
// Ignore
WS : [ \t\n\r\u000c]+ -> skip;
COMMENT : '/*' .*? '*/' -> skip;
LINE_COMMENT : '//' ~[\r\n]* -> skip;
/**
* CR (Carriage Return): \r, used in Mac OS before X
* LF (Line Feed): \n, used in Unix/Max OS X
* CR + LF: \r\n, used in Windows
*/
|
Add signal attribute grammar
|
Add signal attribute grammar
|
ANTLR
|
mit
|
OuHangKresnik/Ninja,OuHangKresnik/Ninja
|
e8204272efd709f0c41cdefe733915d66b0ebea2
|
terraform/terraform.g4
|
terraform/terraform.g4
|
/*
BSD License
Copyright (c) 2020, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar terraform;
file
: (local | module | output | provider | variable | data | resource | terraform)+
;
terraform
: 'terraform' blockbody
;
resource
: 'resource' resourcetype name blockbody
;
data
: 'data' resourcetype name blockbody
;
provider
: 'provider' resourcetype blockbody
;
output
: 'output' name blockbody
;
local
: 'locals' blockbody
;
module
: 'module' name blockbody
;
variable
: 'variable' name blockbody
;
block
: blocktype label* blockbody
;
blocktype
: IDENTIFIER
;
resourcetype
: STRING
;
name
: STRING
;
label
: STRING
;
blockbody
: '{' (argument | block)* '}'
;
argument
: identifier '=' expression
;
identifier
: IDENTIFIER
;
expression
: RESOURCEREFERENCE
| section
| expression OPERATOR expression
| LPAREN expression RPAREN
| expression '?' expression ':' expression
| map
;
RESOURCEREFERENCE
: [a-zA-Z] [a-zA-Z0-9_-]* RESOURCEINDEX? '.' ([a-zA-Z0-9_.-] RESOURCEINDEX?)+
;
RESOURCEINDEX
: '[' [0-9]+ ']'
;
section
: list
| map
| val
;
val
: NULL
| SIGNED_NUMBER
| string
| BOOL
| IDENTIFIER index?
| DESCRIPTION
| filedecl
| functioncall
| EOF_
;
functioncall
: functionname LPAREN functionarguments RPAREN
;
functionname
: IDENTIFIER
;
functionarguments
: //no arguments
| expression (',' expression)*
;
index
: '[' expression ']'
;
filedecl
: 'file' '(' expression ')'
;
list
: '[' expression (',' expression)* ','? ']'
;
map
: '{' argument* (',' argument)* '}'
;
string
: STRING
| MULTILINESTRING
;
fragment DIGIT
: [0-9]
;
SIGNED_NUMBER
: '+' NUMBER
| '-' NUMBER
| NUMBER
;
OPERATOR
: '*'
| '/'
| '%'
| '+'
| '-'
| '>'
| '>='
| '<'
| '<='
| '=='
| '!='
| '&&'
| '||'
;
LCURL
: '{'
;
RCURL
: '}'
;
LPAREN
: '('
;
RPAREN
: ')'
;
EOF_
: '<<EOF' .*? 'EOF'
;
NULL
: 'nul'
;
NUMBER
: DIGIT+ ('.' DIGIT+)?
;
BOOL
: 'true'
| 'false'
;
DESCRIPTION
: '<<DESCRIPTION' .*? 'DESCRIPTION'
;
MULTILINESTRING
: '<<-EOF' .*? 'EOF'
;
STRING
: '"' (~ [\r\n"] | '""')* '"'
;
IDENTIFIER
: [a-zA-Z] ([a-zA-Z0-9_-])*
;
COMMENT
: ('#' | '//') ~ [\r\n]* -> channel(HIDDEN)
;
BLOCKCOMMENT
: '/*' .*? '*/' -> channel(HIDDEN)
;
WS
: [ \r\n\t]+ -> skip
;
|
/*
BSD License
Copyright (c) 2020, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar terraform;
file
: (local | module | output | provider | variable | data | resource | terraform)+
;
terraform
: 'terraform' blockbody
;
resource
: 'resource' resourcetype name blockbody
;
data
: 'data' resourcetype name blockbody
;
provider
: 'provider' resourcetype blockbody
;
output
: 'output' name blockbody
;
local
: 'locals' blockbody
;
module
: 'module' name blockbody
;
variable
: 'variable' name blockbody
;
block
: blocktype label* blockbody
;
blocktype
: IDENTIFIER
;
resourcetype
: STRING
;
name
: STRING
;
label
: STRING
;
blockbody
: LCURL (argument | block)* RCURL
;
argument
: identifier '=' expression
;
identifier
: IDENTIFIER
;
expression
: RESOURCEREFERENCE
| section
| expression OPERATOR expression
| LPAREN expression RPAREN
| expression '?' expression ':' expression
| map
;
RESOURCEREFERENCE
: [a-zA-Z] [a-zA-Z0-9_-]* RESOURCEINDEX? '.' ([a-zA-Z0-9_.-] RESOURCEINDEX?)+
;
RESOURCEINDEX
: '[' [0-9]+ ']'
;
section
: list
| map
| val
;
val
: NULL
| SIGNED_NUMBER
| string
| BOOL
| IDENTIFIER index?
| DESCRIPTION
| filedecl
| functioncall
| EOF_
;
functioncall
: functionname LPAREN functionarguments RPAREN
;
functionname
: IDENTIFIER
;
functionarguments
: //no arguments
| expression (',' expression)*
;
index
: '[' expression ']'
;
filedecl
: 'file' '(' expression ')'
;
list
: '[' expression (',' expression)* ','? ']'
;
map
: LCURL argument* (',' argument)* LCURL
;
string
: STRING
| MULTILINESTRING
;
fragment DIGIT
: [0-9]
;
SIGNED_NUMBER
: '+' NUMBER
| '-' NUMBER
| NUMBER
;
OPERATOR
: '*'
| '/'
| '%'
| '+'
| '-'
| '>'
| '>='
| '<'
| '<='
| '=='
| '!='
| '&&'
| '||'
;
LCURL
: '{'
;
RCURL
: '}'
;
LPAREN
: '('
;
RPAREN
: ')'
;
EOF_
: '<<EOF' .*? 'EOF'
;
NULL
: 'nul'
;
NUMBER
: DIGIT+ ('.' DIGIT+)?
;
BOOL
: 'true'
| 'false'
;
DESCRIPTION
: '<<DESCRIPTION' .*? 'DESCRIPTION'
;
MULTILINESTRING
: '<<-EOF' .*? 'EOF'
;
STRING
: '"' (~ [\r\n"] | '""')* '"'
;
IDENTIFIER
: [a-zA-Z] ([a-zA-Z0-9_-])*
;
COMMENT
: ('#' | '//') ~ [\r\n]* -> channel(HIDDEN)
;
BLOCKCOMMENT
: '/*' .*? '*/' -> channel(HIDDEN)
;
WS
: [ \r\n\t]+ -> skip
;
|
Replace curly braces by constant
|
Replace curly braces by constant
|
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
|
a464aa195c8469f954115fa061e1148742e1361b
|
dsl-parser/src/main/antlr4/com/mattunderscore/specky/parser/Specky.g4
|
dsl-parser/src/main/antlr4/com/mattunderscore/specky/parser/Specky.g4
|
/* Copyright © 2016 Matthew Champion
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of mattunderscore.com nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL MATTHEW CHAMPION BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
parser grammar Specky;
options { tokenVocab=SpeckyLexer; }
construction
: CONSTRUCTOR
| MUTABLE_BUILDER
| IMMUTABLE_BUILDER
;
default_value
: DEFAULT ANYTHING
;
typeParameters
: OPEN_TYPE_PARAMETERS Identifier (INLINE_WS+ Identifier)* CLOSE_TYPE_PARAMETERS
;
property
: (OPTIONAL INLINE_WS+)? Identifier typeParameters? INLINE_WS+ Identifier (INLINE_WS+ default_value)?
;
qualifiedName
: Identifier (PACKAGE_SEPARATOR Identifier)*
;
package_name
: PACKAGE INLINE_WS+ qualifiedName
;
imports
: IMPORT INLINE_WS+ OPEN_BLOCK LINE_BREAK (INLINE_WS* qualifiedName)+ LINE_BREAK CLOSE_BLOCK
;
opts
: OPTIONS INLINE_WS+ OPEN_BLOCK LINE_BREAK
INLINE_WS* construction? LINE_BREAK
INLINE_WS* CLOSE_BLOCK LINE_BREAK
;
implementationSpec
: (VALUE | BEAN ) INLINE_WS+ Identifier INLINE_WS+ (EXTENDS INLINE_WS+ Identifier INLINE_WS+)? OPEN_BLOCK LINE_BREAK
(INLINE_WS* property LINE_BREAK)*
(INLINE_WS* opts)? INLINE_WS* CLOSE_BLOCK
;
typeSpec
: TYPE INLINE_WS+ Identifier INLINE_WS+ OPEN_BLOCK LINE_BREAK
(INLINE_WS+ property LINE_BREAK)*
INLINE_WS* CLOSE_BLOCK
;
spec
: (LINE_BREAK | INLINE_WS)*
package_name (LINE_BREAK | INLINE_WS)+
(imports (LINE_BREAK | INLINE_WS)+)?
((typeSpec | implementationSpec) LINE_BREAK+)+
;
|
/* Copyright © 2016 Matthew Champion
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of mattunderscore.com nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL MATTHEW CHAMPION BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
parser grammar Specky;
options { tokenVocab=SpeckyLexer; }
construction
: CONSTRUCTOR
| MUTABLE_BUILDER
| IMMUTABLE_BUILDER
;
default_value
: DEFAULT ANYTHING
;
typeParameters
: OPEN_TYPE_PARAMETERS Identifier (INLINE_WS+ Identifier)* CLOSE_TYPE_PARAMETERS
;
property
: (OPTIONAL INLINE_WS+)? Identifier typeParameters? INLINE_WS+ Identifier (INLINE_WS+ default_value)?
;
qualifiedName
: Identifier (PACKAGE_SEPARATOR Identifier)*
;
package_name
: PACKAGE INLINE_WS+ qualifiedName
;
imports
: IMPORT INLINE_WS+ OPEN_BLOCK LINE_BREAK
(INLINE_WS* qualifiedName)+ LINE_BREAK
CLOSE_BLOCK
;
opts
: OPTIONS INLINE_WS+ OPEN_BLOCK LINE_BREAK
INLINE_WS* construction? LINE_BREAK
INLINE_WS* CLOSE_BLOCK
;
implementationSpec
: (VALUE | BEAN ) INLINE_WS+ Identifier INLINE_WS+ (EXTENDS INLINE_WS+ Identifier INLINE_WS+)? OPEN_BLOCK LINE_BREAK
(INLINE_WS* property LINE_BREAK)*
(INLINE_WS* opts LINE_BREAK)?
INLINE_WS* CLOSE_BLOCK
;
typeSpec
: TYPE INLINE_WS+ Identifier INLINE_WS+ OPEN_BLOCK LINE_BREAK
(INLINE_WS+ property LINE_BREAK)*
INLINE_WS* CLOSE_BLOCK
;
spec
: (LINE_BREAK | INLINE_WS)*
package_name (LINE_BREAK | INLINE_WS)+
(imports (LINE_BREAK | INLINE_WS)+)?
((typeSpec | implementationSpec) LINE_BREAK+)+
;
|
Make the spec more readable.
|
Make the spec more readable.
|
ANTLR
|
bsd-3-clause
|
mattunderscorechampion/specky,mattunderscorechampion/specky,mattunderscorechampion/specky
|
8560b4bfbbdbc0f177122e5230f5628c2317d09d
|
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 alterDefinitionClause_
;
alterIndex
: ALTER INDEX (indexName | ALL) ON tableName
;
dropTable
: DROP TABLE tableExistClause_ tableNames
;
dropIndex
: DROP INDEX indexExistClause_ 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)?
;
alterDefinitionClause_
: modifyColumnSpecification | addColumnSpecification | alterDrop | alterCheckConstraint | alterTrigger | alterSwitch | alterSet | alterTableOption | REBUILD
;
modifyColumnSpecification
: alterColumnOperation dataType (COLLATE collationName)? (NULL | NOT NULL)? SPARSE?
;
alterColumnOperation
: ALTER COLUMN columnName
;
addColumnSpecification
: (WITH (CHECK | NOCHECK))? ADD (alterColumnAddOptions | generatedColumnNamesClause)
;
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)?
;
generatedColumnNamesClause
: generatedColumnNameClause COMMA_ periodClause | periodClause COMMA_ generatedColumnNameClause
;
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 | ON alterSetOnClause?)
;
alterSetOnClause
: LP_ (HISTORY_TABLE EQ_ tableName)? dataConsistencyCheckClause_? historyRetentionPeriodClause_? RP_
;
dataConsistencyCheckClause_
: COMMA_? DATA_CONSISTENCY_CHECK EQ_ (ON | OFF)
;
historyRetentionPeriodClause_
: COMMA_? HISTORY_RETENTION_PERIOD EQ_ historyRetentionPeriod
;
historyRetentionPeriod
: INFINITE | (NUMBER_ (DAY | DAYS | WEEK | WEEKS | MONTH | MONTHS | YEAR | YEARS))
;
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?
;
alterTableOption
: 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_)?
;
tableExistClause_
: (IF EXISTS)?
;
indexExistClause_
: (IF EXISTS)?
;
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_
;
|
/*
* 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 alterDefinitionClause_
;
alterIndex
: ALTER INDEX (indexName | ALL) ON tableName
;
dropTable
: DROP TABLE tableExistClause_ tableNames
;
dropIndex
: DROP INDEX indexExistClause_ 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 encryptedOptions_
| columnConstraint (COMMA_ columnConstraint)*
| columnIndex
;
encryptedOptions_
: LP_ COLUMN_ENCRYPTION_KEY EQ_ ignoredIdentifier_ COMMA_ ENCRYPTION_TYPE EQ_ (DETERMINISTIC | RANDOMIZED) COMMA_ ALGORITHM EQ_ STRING_ RP_
;
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)? withIndexOption_? indexOnClause? fileStreamOn_?
;
withIndexOption_
: WITH LP_ indexOption (COMMA_ indexOption)* RP_
;
indexOnClause
: onSchemaColumn | onFileGroup | onDefault
;
onDefault
: ON DEFAULT
;
fileStreamOn_
: FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_)
;
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)?
;
alterDefinitionClause_
: modifyColumnSpecification | addColumnSpecification | alterDrop | alterCheckConstraint | alterTrigger | alterSwitch | alterSet | alterTableOption | REBUILD
;
modifyColumnSpecification
: alterColumnOperation dataType (COLLATE collationName)? (NULL | NOT NULL)? SPARSE?
;
alterColumnOperation
: ALTER COLUMN columnName
;
addColumnSpecification
: (WITH (CHECK | NOCHECK))? ADD (alterColumnAddOptions | generatedColumnNamesClause)
;
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)?
;
generatedColumnNamesClause
: generatedColumnNameClause COMMA_ periodClause | periodClause COMMA_ generatedColumnNameClause
;
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 | ON alterSetOnClause?)
;
alterSetOnClause
: LP_ (HISTORY_TABLE EQ_ tableName)? dataConsistencyCheckClause_? historyRetentionPeriodClause_? RP_
;
dataConsistencyCheckClause_
: COMMA_? DATA_CONSISTENCY_CHECK EQ_ (ON | OFF)
;
historyRetentionPeriodClause_
: COMMA_? HISTORY_RETENTION_PERIOD EQ_ historyRetentionPeriod
;
historyRetentionPeriod
: INFINITE | (NUMBER_ (DAY | DAYS | WEEK | WEEKS | MONTH | MONTHS | YEAR | YEARS))
;
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?
;
alterTableOption
: 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_)?
;
tableExistClause_
: (IF EXISTS)?
;
indexExistClause_
: (IF EXISTS)?
;
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_
;
|
add fileStreamOn_
|
add fileStreamOn_
|
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
|
870be7f2a9a8103bbe6692274eb063417ed36847
|
projects/batfish/src/main/antlr4/org/batfish/grammar/flatjuniper/FlatJuniper_routing_instances.g4
|
projects/batfish/src/main/antlr4/org/batfish/grammar/flatjuniper/FlatJuniper_routing_instances.g4
|
parser grammar FlatJuniper_routing_instances;
import
FlatJuniper_common, FlatJuniper_forwarding_options, FlatJuniper_protocols, FlatJuniper_snmp;
options {
tokenVocab = FlatJuniperLexer;
}
ri_common
:
apply
| ri_description
| s_forwarding_options
| s_routing_options
;
ri_description
:
description
;
ri_instance_type
:
INSTANCE_TYPE
(
FORWARDING
| L2VPN
| VIRTUAL_ROUTER
| VIRTUAL_SWITCH
| VRF
)
;
ri_interface
:
INTERFACE id = interface_id
;
ri_named_routing_instance
:
name = variable
(
ri_common
| ri_instance_type
| ri_interface
| ri_null
| ri_protocols
| ri_route_distinguisher
| ri_snmp
| ri_vrf_export
| ri_vrf_import
| ri_vrf_table_label
| ri_vrf_target
| ri_vtep_source_interface
)
;
ri_null
:
(
BRIDGE_DOMAINS
| CHASSIS
| CLASS_OF_SERVICE
| EVENT_OPTIONS
| PROVIDER_TUNNEL
| SERVICES
) null_filler
;
ri_protocols
:
s_protocols
;
ri_route_distinguisher
:
ROUTE_DISTINGUISHER
(
DEC
| IP_ADDRESS
) COLON DEC
;
ri_snmp
:
s_snmp
;
ri_vrf_export
:
VRF_EXPORT name = variable
;
ri_vrf_import
:
VRF_IMPORT name = variable
;
ri_vrf_table_label
:
VRF_TABLE_LABEL
;
ri_vrf_target
:
VRF_TARGET
(
riv_community
| riv_export
| riv_import
)
;
ri_vtep_source_interface
:
VTEP_SOURCE_INTERFACE iface = interface_id
;
riv_community
:
extended_community
;
riv_export
:
EXPORT extended_community
;
riv_import
:
IMPORT extended_community
;
ro_aggregate
:
AGGREGATE
(
apply
| roa_defaults
| roa_route
)
;
ro_auto_export
:
AUTO_EXPORT
;
ro_autonomous_system
:
AUTONOMOUS_SYSTEM asn = bgp_asn?
(
apply
|
(
roas_asdot_notation
| roas_loops
)*
)
;
ro_bmp
:
BMP
(
rob_station_address
| rob_station_port
)
;
ro_confederation
:
CONFEDERATION num = DEC?
(
MEMBERS member += DEC
)*
;
ro_forwarding_table
:
FORWARDING_TABLE
(
rof_export
| rof_no_ecmp_fast_reroute
| rof_null
)
;
ro_generate
:
GENERATE
(
apply
| rog_defaults
| rog_route
)
;
ro_interface_routes
:
INTERFACE_ROUTES
(
roi_family
| roi_rib_group
)
;
ro_martians
:
MARTIANS null_filler
;
ro_null
:
(
GRACEFUL_RESTART
| LSP_TELEMETRY
| MULTICAST
| MULTIPATH
| NONSTOP_ROUTING
| OPTIONS
| PPM
| RESOLUTION
| TRACEOPTIONS
) null_filler
;
ro_rib
:
RIB name = VARIABLE
(
apply
| ro_aggregate
| ro_generate
| ro_static
)
;
ro_rib_groups
:
RIB_GROUPS name = variable
(
ror_export_rib
| ror_import_policy
| ror_import_rib
)
;
ro_route_distinguisher_id
:
ROUTE_DISTINGUISHER_ID addr = IP_ADDRESS
;
ro_router_id
:
ROUTER_ID id = IP_ADDRESS
;
ro_srlg
:
SRLG name = variable
(
roslrg_srlg_cost
| roslrg_srlg_value
)
;
ro_static
:
STATIC
(
ros_rib_group
| ros_route
)
;
roa_active
:
ACTIVE
;
roa_as_path
:
AS_PATH?
(
roaa_aggregator
| roaa_origin
| roaa_path
)
;
roa_common
:
apply
| roa_active
| roa_as_path
| roa_community
| roa_discard
| roa_passive
| roa_policy
| roa_preference
| roa_tag
;
roa_community
:
COMMUNITY community = COMMUNITY_LITERAL
;
roa_defaults
:
DEFAULTS roa_common
;
roa_discard
:
DISCARD
;
roa_passive
:
PASSIVE
;
roa_policy
:
POLICY name = variable
;
roa_preference
:
PREFERENCE preference = DEC
;
roa_route
:
ROUTE
(
prefix = IP_PREFIX
| prefix6 = IPV6_PREFIX
)
roa_common
;
roa_tag
:
TAG tag = DEC
;
roaa_aggregator
:
AGGREGATOR as = DEC ip = IP_ADDRESS
;
roaa_origin
:
ORIGIN IGP
;
roaa_path
:
PATH path = as_path_expr
;
roas_asdot_notation
:
ASDOT_NOTATION
;
roas_loops
:
LOOPS DEC
;
rob_station_address
:
STATION_ADDRESS IP_ADDRESS
;
rob_station_port
:
STATION_PORT DEC
;
roa_route
:
ROUTE
(
prefix = IP_PREFIX
| prefix6 = IPV6_PREFIX
)
(
apply
| roa_common
)
;
rof_export
:
EXPORT name = variable
;
rof_no_ecmp_fast_reroute
:
NO_ECMP_FAST_REROUTE
;
rof_null
:
(
INDIRECT_NEXT_HOP
| INDIRECT_NEXT_HOP_CHANGE_ACKNOWLEDGEMENTS
) null_filler
;
rog_active
:
ACTIVE
;
rog_common
:
apply
| rog_active
| rog_community
| rog_discard
| rog_metric
| rog_passive
| rog_policy
;
rog_community
:
COMMUNITY standard_community
;
rog_defaults
:
DEFAULTS rog_common
;
rog_discard
:
DISCARD
;
rog_metric
:
METRIC metric = DEC
;
rog_passive
:
PASSIVE
;
rog_policy
:
POLICY policy = variable
;
rog_route
:
ROUTE
(
IP_PREFIX
| IPV6_PREFIX
) rog_common
;
roi_family
:
FAMILY
(
roif_inet
| roif_null
)
;
roi_rib_group
:
RIB_GROUP (INET | INET6) name = variable
;
roif_inet
:
INET
(
roifi_export
)
;
roif_null
:
INET6 null_filler
;
roifi_export
:
EXPORT
(
roifie_lan
| roifie_point_to_point
)
;
roifie_lan
:
LAN
;
roifie_point_to_point
:
POINT_TO_POINT
;
ror_export_rib
:
EXPORT_RIB rib = variable
;
ror_import_policy
:
IMPORT_POLICY name = variable
;
ror_import_rib
:
IMPORT_RIB rib = variable
;
ros_rib_group
:
RIB_GROUP name = variable
;
ros_route
:
ROUTE
(
IP_PREFIX
| IPV6_PREFIX
)
(
rosr_common
| rosr_qualified_next_hop
)
;
roslrg_srlg_cost
:
SRLG_COST cost = DEC
;
roslrg_srlg_value
:
SRLG_VALUE value = DEC
;
rosr_active
:
ACTIVE
;
rosr_as_path
:
AS_PATH PATH
(
path += DEC
)+
;
rosr_common
:
rosr_active
| rosr_as_path
| rosr_community
| rosr_discard
| rosr_install
| rosr_no_install
| rosr_metric
| rosr_next_hop
| rosr_next_table
| rosr_no_readvertise
| rosr_no_retain
| rosr_passive
| rosr_preference
| rosr_readvertise
| rosr_reject
| rosr_resolve
| rosr_retain
| rosr_tag
;
rosr_community
:
COMMUNITY standard_community
;
rosr_discard
:
DISCARD
;
rosr_install
:
INSTALL
;
rosr_metric
:
METRIC metric = DEC
(
TYPE DEC
)?
;
rosr_next_hop
:
NEXT_HOP
(
IP_ADDRESS
| IPV6_ADDRESS
| interface_id
)
;
rosr_next_table
:
NEXT_TABLE name = variable
;
rosr_no_install
:
NO_INSTALL
;
rosr_no_readvertise
:
NO_READVERTISE
;
rosr_no_retain
:
NO_RETAIN
;
rosr_passive
:
PASSIVE
;
rosr_preference
:
PREFERENCE pref = DEC
;
rosr_qualified_next_hop
:
QUALIFIED_NEXT_HOP nexthop = IP_ADDRESS rosr_common?
;
rosr_readvertise
:
READVERTISE
;
rosr_reject
:
REJECT
;
rosr_resolve
:
RESOLVE
;
rosr_retain
:
RETAIN
;
rosr_tag
:
TAG tag = DEC
;
s_routing_instances
:
ROUTING_INSTANCES
(
ri_common
| ri_named_routing_instance
)
;
s_routing_options
:
ROUTING_OPTIONS
(
ro_aggregate
| ro_auto_export
| ro_autonomous_system
| ro_bmp
| ro_confederation
| ro_forwarding_table
| ro_generate
| ro_interface_routes
| ro_martians
| ro_null
| ro_rib
| ro_rib_groups
| ro_route_distinguisher_id
| ro_router_id
| ro_srlg
| ro_static
)
;
|
parser grammar FlatJuniper_routing_instances;
import
FlatJuniper_common, FlatJuniper_forwarding_options, FlatJuniper_protocols, FlatJuniper_snmp;
options {
tokenVocab = FlatJuniperLexer;
}
ri_common
:
apply
| ri_description
| s_forwarding_options
| s_routing_options
;
ri_description
:
description
;
ri_instance_type
:
INSTANCE_TYPE
(
FORWARDING
| L2VPN
| VIRTUAL_ROUTER
| VIRTUAL_SWITCH
| VRF
)
;
ri_interface
:
INTERFACE id = interface_id
;
ri_named_routing_instance
:
name = variable
(
ri_common
| ri_instance_type
| ri_interface
| ri_null
| ri_protocols
| ri_route_distinguisher
| ri_snmp
| ri_vrf_export
| ri_vrf_import
| ri_vrf_table_label
| ri_vrf_target
| ri_vtep_source_interface
)
;
ri_null
:
(
BRIDGE_DOMAINS
| CHASSIS
| CLASS_OF_SERVICE
| EVENT_OPTIONS
| PROVIDER_TUNNEL
| SERVICES
) null_filler
;
ri_protocols
:
s_protocols
;
ri_route_distinguisher
:
ROUTE_DISTINGUISHER
(
DEC
| IP_ADDRESS
) COLON DEC
;
ri_snmp
:
s_snmp
;
ri_vrf_export
:
VRF_EXPORT name = variable
;
ri_vrf_import
:
VRF_IMPORT name = variable
;
ri_vrf_table_label
:
VRF_TABLE_LABEL
;
ri_vrf_target
:
VRF_TARGET
(
riv_community
| riv_export
| riv_import
)
;
ri_vtep_source_interface
:
VTEP_SOURCE_INTERFACE iface = interface_id
;
riv_community
:
extended_community
;
riv_export
:
EXPORT extended_community
;
riv_import
:
IMPORT extended_community
;
ro_aggregate
:
AGGREGATE
(
apply
| roa_defaults
| roa_route
)
;
ro_auto_export
:
AUTO_EXPORT
;
ro_autonomous_system
:
AUTONOMOUS_SYSTEM asn = bgp_asn?
(
apply
|
(
roas_asdot_notation
| roas_loops
)*
)
;
ro_bmp
:
BMP
(
rob_station_address
| rob_station_port
)
;
ro_confederation
:
CONFEDERATION num = DEC?
(
MEMBERS member += DEC
)*
;
ro_forwarding_table
:
FORWARDING_TABLE
(
rof_export
| rof_no_ecmp_fast_reroute
| rof_null
)
;
ro_generate
:
GENERATE
(
apply
| rog_defaults
| rog_route
)
;
ro_interface_routes
:
INTERFACE_ROUTES
(
roi_family
| roi_rib_group
)
;
ro_martians
:
MARTIANS null_filler
;
ro_null
:
(
GRACEFUL_RESTART
| LSP_TELEMETRY
| MULTICAST
| MULTIPATH
| NONSTOP_ROUTING
| OPTIONS
| PPM
| RESOLUTION
| TRACEOPTIONS
) null_filler
;
ro_rib
:
RIB name = VARIABLE
(
apply
| ro_aggregate
| ro_generate
| ro_static
)
;
ro_rib_groups
:
RIB_GROUPS name = variable
(
ror_export_rib
| ror_import_policy
| ror_import_rib
)
;
ro_route_distinguisher_id
:
ROUTE_DISTINGUISHER_ID addr = IP_ADDRESS
;
ro_router_id
:
ROUTER_ID id = IP_ADDRESS
;
ro_srlg
:
SRLG name = variable
(
roslrg_srlg_cost
| roslrg_srlg_value
)
;
ro_static
:
STATIC
(
ros_rib_group
| ros_route
)
;
roa_active
:
ACTIVE
;
roa_as_path
:
AS_PATH?
(
roaa_aggregator
| roaa_origin
| roaa_path
)
;
roa_common
:
apply
| roa_active
| roa_as_path
| roa_community
| roa_discard
| roa_passive
| roa_policy
| roa_preference
| roa_tag
;
roa_community
:
COMMUNITY community = COMMUNITY_LITERAL
;
roa_defaults
:
DEFAULTS roa_common
;
roa_discard
:
DISCARD
;
roa_passive
:
PASSIVE
;
roa_policy
:
POLICY name = variable
;
roa_preference
:
PREFERENCE preference = DEC
;
roa_tag
:
TAG tag = DEC
;
roaa_aggregator
:
AGGREGATOR as = DEC ip = IP_ADDRESS
;
roaa_origin
:
ORIGIN IGP
;
roaa_path
:
PATH path = as_path_expr
;
roas_asdot_notation
:
ASDOT_NOTATION
;
roas_loops
:
LOOPS DEC
;
rob_station_address
:
STATION_ADDRESS IP_ADDRESS
;
rob_station_port
:
STATION_PORT DEC
;
roa_route
:
ROUTE
(
prefix = IP_PREFIX
| prefix6 = IPV6_PREFIX
)
(
apply
| roa_common
)
;
rof_export
:
EXPORT name = variable
;
rof_no_ecmp_fast_reroute
:
NO_ECMP_FAST_REROUTE
;
rof_null
:
(
INDIRECT_NEXT_HOP
| INDIRECT_NEXT_HOP_CHANGE_ACKNOWLEDGEMENTS
) null_filler
;
rog_active
:
ACTIVE
;
rog_common
:
apply
| rog_active
| rog_community
| rog_discard
| rog_metric
| rog_passive
| rog_policy
;
rog_community
:
COMMUNITY standard_community
;
rog_defaults
:
DEFAULTS rog_common
;
rog_discard
:
DISCARD
;
rog_metric
:
METRIC metric = DEC
;
rog_passive
:
PASSIVE
;
rog_policy
:
POLICY policy = variable
;
rog_route
:
ROUTE
(
IP_PREFIX
| IPV6_PREFIX
) rog_common
;
roi_family
:
FAMILY
(
roif_inet
| roif_null
)
;
roi_rib_group
:
RIB_GROUP (INET | INET6) name = variable
;
roif_inet
:
INET
(
roifi_export
)
;
roif_null
:
INET6 null_filler
;
roifi_export
:
EXPORT
(
roifie_lan
| roifie_point_to_point
)
;
roifie_lan
:
LAN
;
roifie_point_to_point
:
POINT_TO_POINT
;
ror_export_rib
:
EXPORT_RIB rib = variable
;
ror_import_policy
:
IMPORT_POLICY name = variable
;
ror_import_rib
:
IMPORT_RIB rib = variable
;
ros_rib_group
:
RIB_GROUP name = variable
;
ros_route
:
ROUTE
(
IP_PREFIX
| IPV6_PREFIX
)
(
rosr_common
| rosr_qualified_next_hop
)
;
roslrg_srlg_cost
:
SRLG_COST cost = DEC
;
roslrg_srlg_value
:
SRLG_VALUE value = DEC
;
rosr_active
:
ACTIVE
;
rosr_as_path
:
AS_PATH PATH
(
path += DEC
)+
;
rosr_common
:
rosr_active
| rosr_as_path
| rosr_community
| rosr_discard
| rosr_install
| rosr_no_install
| rosr_metric
| rosr_next_hop
| rosr_next_table
| rosr_no_readvertise
| rosr_no_retain
| rosr_passive
| rosr_preference
| rosr_readvertise
| rosr_reject
| rosr_resolve
| rosr_retain
| rosr_tag
;
rosr_community
:
COMMUNITY standard_community
;
rosr_discard
:
DISCARD
;
rosr_install
:
INSTALL
;
rosr_metric
:
METRIC metric = DEC
(
TYPE DEC
)?
;
rosr_next_hop
:
NEXT_HOP
(
IP_ADDRESS
| IPV6_ADDRESS
| interface_id
)
;
rosr_next_table
:
NEXT_TABLE name = variable
;
rosr_no_install
:
NO_INSTALL
;
rosr_no_readvertise
:
NO_READVERTISE
;
rosr_no_retain
:
NO_RETAIN
;
rosr_passive
:
PASSIVE
;
rosr_preference
:
PREFERENCE pref = DEC
;
rosr_qualified_next_hop
:
QUALIFIED_NEXT_HOP nexthop = IP_ADDRESS rosr_common?
;
rosr_readvertise
:
READVERTISE
;
rosr_reject
:
REJECT
;
rosr_resolve
:
RESOLVE
;
rosr_retain
:
RETAIN
;
rosr_tag
:
TAG tag = DEC
;
s_routing_instances
:
ROUTING_INSTANCES
(
ri_common
| ri_named_routing_instance
)
;
s_routing_options
:
ROUTING_OPTIONS
(
ro_aggregate
| ro_auto_export
| ro_autonomous_system
| ro_bmp
| ro_confederation
| ro_forwarding_table
| ro_generate
| ro_interface_routes
| ro_martians
| ro_null
| ro_rib
| ro_rib_groups
| ro_route_distinguisher_id
| ro_router_id
| ro_srlg
| ro_static
)
;
|
Remove duplicate definition of roa_route (#3021)
|
Remove duplicate definition of roa_route (#3021)
|
ANTLR
|
apache-2.0
|
dhalperi/batfish,batfish/batfish,intentionet/batfish,dhalperi/batfish,intentionet/batfish,arifogel/batfish,batfish/batfish,arifogel/batfish,intentionet/batfish,dhalperi/batfish,intentionet/batfish,arifogel/batfish,intentionet/batfish,batfish/batfish
|
4b91e60bb2cb01b141fdd90d6e8575b5cf9ba0b3
|
src/main/antlr/Trinity.g4
|
src/main/antlr/Trinity.g4
|
grammar Trinity;
import LexerRules; // includes all rules from LexerRules.g4
prog: (functionDecl /*| constDecl*/ | stmt)* ;
// Declarations
constDecl: TYPE ID '=' expr ';';
functionDecl: TYPE ID '(' formalParameters? ')' block; // Scalar f(Vector x) {...} ;
formalParameters: formalParameter (',' formalParameter)* ;
formalParameter: TYPE ID;
// Statements
block: BLOCKSTART stmt* BLOCKEND ; // possibly empty statement block
stmt: block // mega nice block scope
| constDecl
| 'for' TYPE ID 'in' expr ('by' NUMBER)? block
| ifBlock
| 'return' expr? ';'
| expr ';' // including function call
;
// TODO: inconsistent grammar design
ifBlock: ifStmt elseIfStmt* elseStmt? 'end' ;
ifStmt: 'if' expr 'do' stmt* ;
elseIfStmt: 'elseif' expr 'do' stmt* ;
elseStmt: 'else' 'do' stmt*;
// Expressions
// TODO: no sub-matrix sub-vector indexing (range) for now (maybe we don't need it)
expr: ID '(' exprList? ')' # FunctionCall
| expr '[' expr ']' # VectorIndexing
| expr '[' expr ',' expr ']' # MatrixIndexing
| '-' expr # Negate
| '!' expr # Not
| expr '\'' # Transpose
| <assoc=right> expr '^' expr # Exponent
| expr ('*'|'/'|'%') expr # MultDivMod
| expr ('+'|'-') expr # AddSub
| expr ('<'|'>'|'<='|'>=') expr # Relation
| expr ('=='|'!=') expr # Equality
| expr 'and' expr # And
| expr 'or' expr # Or
| ID # Const
| NUMBER # Number
| BOOL # Boolean
| matrix # MatrixLit
| vector # VectorLit // TODO: naming
| '(' expr ')' # Parens
;
exprList: expr (',' expr)* ;
vector: '[' (exprList | RANGE) ']' ;
matrix: vector vector+ ; // [][]...[]
|
grammar Trinity;
import LexerRules; // includes all rules from LexerRules.g4
prog: (functionDecl | stmt)* ;
// Declarations
constDecl: TYPE ID '=' expr ';';
functionDecl: TYPE ID '(' formalParameters? ')' block; // Scalar f(Vector x) {...} ;
formalParameters: formalParameter (',' formalParameter)* ;
formalParameter: TYPE ID;
// Statements
block: BLOCKSTART stmt* BLOCKEND ; // possibly empty statement block
stmt: block // mega nice block scope
| constDecl
| 'for' TYPE ID 'in' expr ('by' NUMBER)? block
| ifBlock
| 'return' expr? ';'
| expr ';' // including function call
;
// TODO: inconsistent grammar design
ifBlock: ifStmt elseIfStmt* elseStmt? 'end' ;
ifStmt: 'if' expr 'do' stmt* ;
elseIfStmt: 'elseif' expr 'do' stmt* ;
elseStmt: 'else' 'do' stmt*;
// Expressions
// TODO: no sub-matrix sub-vector indexing (range) for now (maybe we don't need it)
expr: ID '(' exprList? ')' # FunctionCall
| expr '[' expr ']' # VectorIndexing
| expr '[' expr ',' expr ']' # MatrixIndexing
| '-' expr # Negate
| '!' expr # Not
| expr '\'' # Transpose
| <assoc=right> expr '^' expr # Exponent
| expr ('*'|'/'|'%') expr # MultDivMod
| expr ('+'|'-') expr # AddSub
| expr ('<'|'>'|'<='|'>=') expr # Relation
| expr ('=='|'!=') expr # Equality
| expr 'and' expr # And
| expr 'or' expr # Or
| ID # Const
| NUMBER # Number
| BOOL # Boolean
| matrix # MatrixLit
| vector # VectorLit // TODO: naming
| '(' expr ')' # Parens
;
exprList: expr (',' expr)* ;
vector: '[' (exprList | RANGE) ']' ;
matrix: vector vector+ ; // [][]...[]
|
remove comment
|
remove comment
|
ANTLR
|
mit
|
Medeah/Trinity,Medeah/Trinity
|
80fca38c39f4e796366cdb1327a700d7533ac2dd
|
Src/java-quickstart/src/main/resources/cql.g4
|
Src/java-quickstart/src/main/resources/cql.g4
|
grammar cql;
/*
* Parser Rules
*/
logic
:
libraryDefinition?
usingDefinition*
includeDefinition*
(parameterDefinition | valuesetDefinition)*
statement+
;
/*
* Definitions
*/
libraryDefinition
: 'library' IDENTIFIER ('version' STRING)?
;
usingDefinition
: 'using' IDENTIFIER ('version' STRING)?
;
includeDefinition
: 'include' IDENTIFIER ('version' STRING)? 'as' IDENTIFIER
;
parameterDefinition
: 'parameter' IDENTIFIER (':' typeSpecifier)? ('default' expression)?
;
valuesetDefinition
: 'valueset' VALUESET '=' expression
;
/*
* Type Specifiers
*/
typeSpecifier
: atomicTypeSpecifier
| listTypeSpecifier
| intervalTypeSpecifier
| tupleTypeSpecifier
;
atomicTypeSpecifier
: IDENTIFIER // TODO: specify atomic type names as part of the grammar?
;
listTypeSpecifier
: 'list' '<' typeSpecifier '>'
;
intervalTypeSpecifier
: 'interval' '<' typeSpecifier '>'
;
tupleTypeSpecifier
: 'tuple' '{' tupleElementDefinition (',' tupleElementDefinition)* '}'
;
tupleElementDefinition
: IDENTIFIER ':' typeSpecifier
;
/*
* Statements
*/
statement
: letStatement
| contextDefinition
| functionDefinition
| retrieveDefinition
;
letStatement
: 'let' IDENTIFIER '=' expression
;
contextDefinition
: 'context' IDENTIFIER
;
functionDefinition
: 'define' 'function' IDENTIFIER '(' (operandDefinition (',' operandDefinition)*)? ')' functionBody
;
operandDefinition
: IDENTIFIER ':' typeSpecifier
;
functionBody
: '{' returnStatement '}'
;
returnStatement
: 'return' expression
;
retrieveDefinition
: 'define' 'retrieve' '[' (occurrence 'of')? topic (',' modality)? (':' valuesetPathIdentifier 'in' valuesetIdentifier)? (',' duringPathIdentifier 'during' duringIdentifier)? ']' functionBody
;
valuesetPathIdentifier
: IDENTIFIER
;
valuesetIdentifier
: IDENTIFIER
;
duringPathIdentifier
: IDENTIFIER
;
duringIdentifier
: IDENTIFIER
;
/*
* Expressions
*/
querySource
: retrieve
| qualifiedIdentifier
| '(' expression ')'
;
aliasedQuerySource
: querySource alias
;
alias
: IDENTIFIER
;
queryInclusionClause
: 'with' aliasedQuerySource 'where' expression
| 'without' aliasedQuerySource 'where' expression
//| 'combine' aliasedQuerySource 'where' expression // TODO: Determine whether combine should be allowed
;
retrieve
: '[' (occurrence 'of')? topic (',' modality)? (':' (valuesetPathIdentifier 'in')? valueset)? (',' duringPathIdentifier? 'during' expression)? ']'
;
occurrence
: IDENTIFIER
;
topic
: qualifiedIdentifier
;
modality
: IDENTIFIER
;
valueset
: (qualifier '.')? (VALUESET | IDENTIFIER)
;
qualifier
: IDENTIFIER
;
query
: aliasedQuerySource queryInclusionClause* whereClause? returnClause? sortClause?
;
whereClause
: 'where' expression
;
returnClause
: 'return' expression
;
sortClause
: 'sort' ( sortDirection | ('by' sortByItem (',' sortByItem)*) )
;
sortDirection // TODO: use full words instead of abbreviations?
: 'asc'
| 'desc'
;
sortByItem
: qualifiedIdentifier sortDirection?
;
qualifiedIdentifier
: (qualifier '.')? IDENTIFIER
;
expression
: expressionTerm # termExpression
| retrieve # retrieveExpression
| query # queryExpression
| expression 'is' 'not'? ( 'null' | 'true' | 'false' ) # booleanExpression
| expression ('is' | 'as') typeSpecifier # typeExpression
| ('not' | 'exists') expression # existenceExpression
| expression 'properly'? 'between' expressionTerm 'and' expressionTerm # rangeExpression
| pluralDateTimePrecision 'between' expressionTerm 'and' expressionTerm # timeRangeExpression
| expression ('<=' | '<' | '>' | '>=') expression # inequalityExpression
| expression intervalOperatorPhrase expression # timingExpression
| expression ('=' | '<>') expression # equalityExpression
| expression ('in' | 'contains' | 'like') expression # membershipExpression
| expression 'and' expression # andExpression
| expression ('or' | 'xor') expression # orExpression
;
dateTimePrecision
: 'year' | 'month' | 'day' | 'hour' | 'minute' | 'second' | 'millisecond'
;
dateTimeComponent
: dateTimePrecision
| 'date'
| 'time'
| 'timezone'
;
pluralDateTimePrecision
: 'years' | 'months' | 'days' | 'hours' | 'minutes' | 'seconds' | 'milliseconds'
;
expressionTerm
: term # termExpressionTerm
| expressionTerm '.' (IDENTIFIER | VALUESET) # accessorExpressionTerm
| expressionTerm '[' expression ']' # indexedExpressionTerm
| expressionTerm '(' (expression (',' expression)*)? ')' # methodExpressionTerm
| 'convert' expression 'to' typeSpecifier # conversionExpressionTerm
| ('+' | '-') expressionTerm # polarityExpressionTerm
| ('start' | 'end') 'of' expressionTerm # timeBoundaryExpressionTerm
| dateTimeComponent 'of' expressionTerm # timeUnitExpressionTerm
| 'duration' 'in' pluralDateTimePrecision 'of' expressionTerm # durationExpressionTerm
| 'width' 'of' expressionTerm # widthExpressionTerm
| 'successor' 'of' expressionTerm # successorExpressionTerm
| 'predecessor' 'of' expressionTerm # predecessorExpressionTerm
| expressionTerm '^' expressionTerm # powerExpressionTerm
| expressionTerm ('*' | '/' | 'div' | 'mod') expressionTerm # multiplicationExpressionTerm
| expressionTerm ('+' | '-') expressionTerm # additionExpressionTerm
| 'if' expression 'then' expression 'else' expression # ifThenElseExpressionTerm
| 'case' expression? caseExpressionItem+ 'else' expression 'end' # caseExpressionTerm
| 'coalesce' '(' expression (',' expression)+ ')' # coalesceExpressionTerm
| ('distinct' | 'collapse' | 'expand') expression # aggregateExpressionTerm
| expressionTerm ('union' | 'intersect' | 'except') expressionTerm # inFixSetExpressionTerm
;
caseExpressionItem
: 'when' expression 'then' expression
;
relativeQualifier
: 'at most'
| 'at least'
;
intervalOperatorPhrase
: ('starts' | 'ends')? relativeQualifier? 'same' dateTimePrecision? 'as' ('start' | 'end')?
#concurrentWithIntervalOperatorPhrase
| 'properly'? 'includes' ('start' | 'end')? #includesIntervalOperatorPhrase
| ('starts' | 'ends')? 'properly'? ('during' | 'included in') #includedInIntervalOperatorPhrase
| ('starts' | 'ends')? quantityOffset? ('before' | 'after') ('start' | 'end')? #beforeOrAfterIntervalOperatorPhrase
| ('starts' | 'ends')? 'properly'? 'within' quantityLiteral 'of' ('start' | 'end')? #withinIntervalOperatorPhrase
| 'meets' ('before' | 'after')? #meetsIntervalOperatorPhrase
| 'overlaps' ('before' | 'after')? #overlapsIntervalOperatorPhrase
| 'starts' #startsIntervalOperatorPhrase
| 'started by' #startedByIntervalOperatorPhrase
| 'ends' #endsIntervalOperatorPhrase
| 'ended by' #endedByIntervalOperatorPhrase
;
quantityOffset
: relativeQualifier? quantityLiteral
;
term
: IDENTIFIER #identifierTerm
| literal #literalTerm
| intervalSelector #intervalSelectorTerm
| tupleSelector #tupleSelectorTerm
| listSelector #listSelectorTerm
| '(' expression ')' #parenthesizedTerm
;
intervalSelector
: // TODO: Consider this as an alternative syntax for intervals... (would need to be moved up to expression to make it work)
//expression ( '..' | '*.' | '.*' | '**' ) expression;
'interval' ('['|'(') expression ',' expression (']'|')')
;
tupleSelector
: 'tuple'? '{' (':' | (tupleElementSelector (',' tupleElementSelector)*)) '}'
;
tupleElementSelector
: IDENTIFIER ':' expression
;
listSelector
: ('list' ('<' typeSpecifier '>')?)? '{' expression? (',' expression)* '}'
;
literal
: nullLiteral
| booleanLiteral
| stringLiteral
| valuesetLiteral
| quantityLiteral
;
nullLiteral
: 'null'
;
booleanLiteral
: 'true'
| 'false'
;
stringLiteral
: STRING
;
valuesetLiteral
: VALUESET
;
quantityLiteral
: QUANTITY unit?
;
unit // NOTE: Using plurals here because that's the most common case, we could add singulars, but that would allow "within 5 day"
: 'years'
| 'months'
| 'weeks'
| 'days'
| 'hours'
| 'minutes'
| 'seconds'
| 'milliseconds'
| 'u'STRING // UCUM syntax for units of measure
;
/*
* Lexer Rules
*/
IDENTIFIER
: ([A-Za-z] | '_')([A-Za-z0-9] | '_')*
;
QUANTITY
: [0-9]+('.'[0-9]+)?
;
VALUESET
: '"' ( ~[\\"] )* '"'
;
STRING
: ('\'') ( ~[\\'] )* ('\'')
;
WS
: (' ' | '\r' | '\t') -> channel(HIDDEN)
;
NEWLINE
: ('\n') -> channel(HIDDEN)
;
COMMENT
: '/*' .*? '*/' -> skip
;
LINE_COMMENT
: '//' ~[\r\n]* -> skip
;
|
grammar cql;
/*
* Parser Rules
*/
logic
:
libraryDefinition?
usingDefinition*
includeDefinition*
(parameterDefinition | valuesetDefinition)*
statement+
;
/*
* Definitions
*/
libraryDefinition
: 'library' IDENTIFIER ('version' STRING)?
;
usingDefinition
: 'using' IDENTIFIER ('version' STRING)?
;
includeDefinition
: 'include' IDENTIFIER ('version' STRING)? 'as' IDENTIFIER
;
parameterDefinition
: 'parameter' IDENTIFIER (':' typeSpecifier)? ('default' expression)?
;
valuesetDefinition
: 'valueset' VALUESET '=' expression
;
/*
* Type Specifiers
*/
typeSpecifier
: atomicTypeSpecifier
| listTypeSpecifier
| intervalTypeSpecifier
| tupleTypeSpecifier
;
atomicTypeSpecifier
: IDENTIFIER
;
listTypeSpecifier
: 'list' '<' typeSpecifier '>'
;
intervalTypeSpecifier
: 'interval' '<' typeSpecifier '>'
;
tupleTypeSpecifier
: 'tuple' '{' tupleElementDefinition (',' tupleElementDefinition)* '}'
;
tupleElementDefinition
: IDENTIFIER ':' typeSpecifier
;
/*
* Statements
*/
statement
: letStatement
| contextDefinition
| functionDefinition
| retrieveDefinition
;
letStatement
: 'let' IDENTIFIER '=' expression
;
contextDefinition
: 'context' IDENTIFIER
;
functionDefinition
: 'define' 'function' IDENTIFIER '(' (operandDefinition (',' operandDefinition)*)? ')' functionBody
;
operandDefinition
: IDENTIFIER ':' typeSpecifier
;
functionBody
: '{' returnStatement '}'
;
returnStatement
: 'return' expression
;
retrieveDefinition
: 'define' 'retrieve' '[' (occurrence 'of')? topic (',' modality)? (':' valuesetPathIdentifier 'in' valuesetIdentifier)? (',' duringPathIdentifier 'during' duringIdentifier)? ']' functionBody
;
valuesetPathIdentifier
: IDENTIFIER
;
valuesetIdentifier
: IDENTIFIER
;
duringPathIdentifier
: IDENTIFIER
;
duringIdentifier
: IDENTIFIER
;
/*
* Expressions
*/
querySource
: retrieve
| qualifiedIdentifier
| '(' expression ')'
;
aliasedQuerySource
: querySource alias
;
alias
: IDENTIFIER
;
queryInclusionClause
: 'with' aliasedQuerySource 'where' expression
| 'without' aliasedQuerySource 'where' expression
//| 'combine' aliasedQuerySource 'where' expression // TODO: Determine whether combine should be allowed
;
retrieve
: '[' (occurrence 'of')? topic (',' modality)? (':' (valuesetPathIdentifier 'in')? valueset)? (',' duringPathIdentifier? 'during' expression)? ']'
;
occurrence
: IDENTIFIER
;
topic
: qualifiedIdentifier
;
modality
: IDENTIFIER
;
valueset
: (qualifier '.')? (VALUESET | IDENTIFIER)
;
qualifier
: IDENTIFIER
;
query
: aliasedQuerySource queryInclusionClause* whereClause? returnClause? sortClause?
;
whereClause
: 'where' expression
;
returnClause
: 'return' expression
;
sortClause
: 'sort' ( sortDirection | ('by' sortByItem (',' sortByItem)*) )
;
sortDirection // TODO: use full words instead of abbreviations?
: 'asc'
| 'desc'
;
sortByItem
: expressionTerm sortDirection?
;
qualifiedIdentifier
: (qualifier '.')? IDENTIFIER
;
expression
: expressionTerm # termExpression
| retrieve # retrieveExpression
| query # queryExpression
| expression 'is' 'not'? ( 'null' | 'true' | 'false' ) # booleanExpression
| expression ('is' | 'as') typeSpecifier # typeExpression
| ('not' | 'exists') expression # existenceExpression
| expression 'properly'? 'between' expressionTerm 'and' expressionTerm # rangeExpression
| pluralDateTimePrecision 'between' expressionTerm 'and' expressionTerm # timeRangeExpression
| expression ('<=' | '<' | '>' | '>=') expression # inequalityExpression
| expression intervalOperatorPhrase expression # timingExpression
| expression ('=' | '<>') expression # equalityExpression
| expression ('in' | 'contains' | 'like') expression # membershipExpression
| expression 'and' expression # andExpression
| expression ('or' | 'xor') expression # orExpression
;
dateTimePrecision
: 'year' | 'month' | 'day' | 'hour' | 'minute' | 'second' | 'millisecond'
;
dateTimeComponent
: dateTimePrecision
| 'date'
| 'time'
| 'timezone'
;
pluralDateTimePrecision
: 'years' | 'months' | 'days' | 'hours' | 'minutes' | 'seconds' | 'milliseconds'
;
expressionTerm
: term # termExpressionTerm
| expressionTerm '.' (IDENTIFIER | VALUESET) # accessorExpressionTerm
| expressionTerm '[' expression ']' # indexedExpressionTerm
| expressionTerm '(' (expression (',' expression)*)? ')' # methodExpressionTerm
| 'convert' expression 'to' typeSpecifier # conversionExpressionTerm
| ('+' | '-') expressionTerm # polarityExpressionTerm
| ('start' | 'end') 'of' expressionTerm # timeBoundaryExpressionTerm
| dateTimeComponent 'of' expressionTerm # timeUnitExpressionTerm
| 'duration' 'in' pluralDateTimePrecision 'of' expressionTerm # durationExpressionTerm
| 'width' 'of' expressionTerm # widthExpressionTerm
| 'successor' 'of' expressionTerm # successorExpressionTerm
| 'predecessor' 'of' expressionTerm # predecessorExpressionTerm
| expressionTerm '^' expressionTerm # powerExpressionTerm
| expressionTerm ('*' | '/' | 'div' | 'mod') expressionTerm # multiplicationExpressionTerm
| expressionTerm ('+' | '-') expressionTerm # additionExpressionTerm
| 'if' expression 'then' expression 'else' expression # ifThenElseExpressionTerm
| 'case' expression? caseExpressionItem+ 'else' expression 'end' # caseExpressionTerm
| 'coalesce' '(' expression (',' expression)+ ')' # coalesceExpressionTerm
| ('distinct' | 'collapse' | 'expand') expression # aggregateExpressionTerm
| expressionTerm ('union' | 'intersect' | 'except') expressionTerm # inFixSetExpressionTerm
;
caseExpressionItem
: 'when' expression 'then' expression
;
relativeQualifier
: 'at most'
| 'at least'
;
intervalOperatorPhrase
: ('starts' | 'ends')? relativeQualifier? 'same' dateTimePrecision? 'as' ('start' | 'end')?
#concurrentWithIntervalOperatorPhrase
| 'properly'? 'includes' ('start' | 'end')? #includesIntervalOperatorPhrase
| ('starts' | 'ends')? 'properly'? ('during' | 'included in') #includedInIntervalOperatorPhrase
| ('starts' | 'ends')? quantityOffset? ('before' | 'after') ('start' | 'end')? #beforeOrAfterIntervalOperatorPhrase
| ('starts' | 'ends')? 'properly'? 'within' quantityLiteral 'of' ('start' | 'end')? #withinIntervalOperatorPhrase
| 'meets' ('before' | 'after')? #meetsIntervalOperatorPhrase
| 'overlaps' ('before' | 'after')? #overlapsIntervalOperatorPhrase
| 'starts' #startsIntervalOperatorPhrase
| 'started by' #startedByIntervalOperatorPhrase
| 'ends' #endsIntervalOperatorPhrase
| 'ended by' #endedByIntervalOperatorPhrase
;
quantityOffset
: relativeQualifier? quantityLiteral
;
term
: IDENTIFIER #identifierTerm
| literal #literalTerm
| intervalSelector #intervalSelectorTerm
| tupleSelector #tupleSelectorTerm
| listSelector #listSelectorTerm
| '(' expression ')' #parenthesizedTerm
;
intervalSelector
: // TODO: Consider this as an alternative syntax for intervals... (would need to be moved up to expression to make it work)
//expression ( '..' | '*.' | '.*' | '**' ) expression;
'interval' ('['|'(') expression ',' expression (']'|')')
;
tupleSelector
: 'tuple'? '{' (':' | (tupleElementSelector (',' tupleElementSelector)*)) '}'
;
tupleElementSelector
: IDENTIFIER ':' expression
;
listSelector
: ('list' ('<' typeSpecifier '>')?)? '{' expression? (',' expression)* '}'
;
literal
: nullLiteral
| booleanLiteral
| stringLiteral
| valuesetLiteral
| quantityLiteral
;
nullLiteral
: 'null'
;
booleanLiteral
: 'true'
| 'false'
;
stringLiteral
: STRING
;
valuesetLiteral
: VALUESET
;
quantityLiteral
: QUANTITY unit?
;
unit // NOTE: Using plurals here because that's the most common case, we could add singulars, but that would allow "within 5 day"
: dateTimePrecision
| pluralDateTimePrecision
| 'week'
| 'weeks'
| 'u'STRING // UCUM syntax for units of measure
;
/*
* Lexer Rules
*/
IDENTIFIER
: ([A-Za-z] | '_')([A-Za-z0-9] | '_')*
;
QUANTITY
: [0-9]+('.'[0-9]+)?
;
VALUESET
: '"' ( ~[\\"] )* '"'
;
STRING
: ('\'') ( ~[\\'] )* ('\'')
;
WS
: (' ' | '\r' | '\t') -> channel(HIDDEN)
;
NEWLINE
: ('\n') -> channel(HIDDEN)
;
COMMENT
: '/*' .*? '*/' -> skip
;
LINE_COMMENT
: '//' ~[\r\n]* -> skip
;
|
Update java-quickstart cql.g4 file to match the latest in CQL/Src/grammar
|
Update java-quickstart cql.g4 file to match the latest in CQL/Src/grammar
|
ANTLR
|
apache-2.0
|
wanghaisheng/clinical_quality_language-Research,DBCG/cql_engine,MeasureAuthoringTool/clinical_quality_language,cqframework/clinical_quality_language,wanghaisheng/clinical_quality_language-Research,cqframework/clinical_quality_language,wanghaisheng/clinical_quality_language-Research,MeasureAuthoringTool/clinical_quality_language,MeasureAuthoringTool/clinical_quality_language,MeasureAuthoringTool/clinical_quality_language,DBCG/cql_engine
|
0a34d7a422ecd893449e4dc772f90a3a139d44f9
|
java/java/JavaParser.g4
|
java/java/JavaParser.g4
|
/*
[The "BSD licence"]
Copyright (c) 2013 Terence Parr, Sam Harwell
Copyright (c) 2017 Ivan Kochurkin (upgrade to Java 8)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
parser grammar JavaParser;
options { tokenVocab=JavaLexer; }
compilationUnit
: packageDeclaration? importDeclaration* typeDeclaration* EOF
;
packageDeclaration
: annotation* PACKAGE qualifiedName ';'
;
importDeclaration
: IMPORT STATIC? qualifiedName ('.' '*')? ';'
;
typeDeclaration
: classOrInterfaceModifier*
(classDeclaration | enumDeclaration | interfaceDeclaration | annotationTypeDeclaration)
| ';'
;
modifier
: classOrInterfaceModifier
| NATIVE
| SYNCHRONIZED
| TRANSIENT
| VOLATILE
;
classOrInterfaceModifier
: annotation
| PUBLIC
| PROTECTED
| PRIVATE
| STATIC
| ABSTRACT
| FINAL // FINAL for class only -- does not apply to interfaces
| STRICTFP
;
variableModifier
: FINAL
| annotation
;
classDeclaration
: CLASS IDENTIFIER typeParameters?
(EXTENDS typeType)?
(IMPLEMENTS typeList)?
classBody
;
typeParameters
: '<' typeParameter (',' typeParameter)* '>'
;
typeParameter
: annotation* IDENTIFIER (EXTENDS typeBound)?
;
typeBound
: typeType ('&' typeType)*
;
enumDeclaration
: ENUM IDENTIFIER (IMPLEMENTS typeList)? '{' enumConstants? ','? enumBodyDeclarations? '}'
;
enumConstants
: enumConstant (',' enumConstant)*
;
enumConstant
: annotation* IDENTIFIER arguments? classBody?
;
enumBodyDeclarations
: ';' classBodyDeclaration*
;
interfaceDeclaration
: INTERFACE IDENTIFIER typeParameters? (EXTENDS typeList)? interfaceBody
;
classBody
: '{' classBodyDeclaration* '}'
;
interfaceBody
: '{' interfaceBodyDeclaration* '}'
;
classBodyDeclaration
: ';'
| STATIC? block
| modifier* memberDeclaration
;
memberDeclaration
: methodDeclaration
| genericMethodDeclaration
| fieldDeclaration
| constructorDeclaration
| genericConstructorDeclaration
| interfaceDeclaration
| annotationTypeDeclaration
| classDeclaration
| enumDeclaration
;
/* We use rule this even for void methods which cannot have [] after parameters.
This simplifies grammar and we can consider void to be a type, which
renders the [] matching as a context-sensitive issue or a semantic check
for invalid return type after parsing.
*/
methodDeclaration
: typeTypeOrVoid IDENTIFIER formalParameters ('[' ']')*
(THROWS qualifiedNameList)?
methodBody
;
methodBody
: block
| ';'
;
typeTypeOrVoid
: typeType
| VOID
;
genericMethodDeclaration
: typeParameters methodDeclaration
;
genericConstructorDeclaration
: typeParameters constructorDeclaration
;
constructorDeclaration
: IDENTIFIER formalParameters (THROWS qualifiedNameList)? constructorBody=block
;
fieldDeclaration
: typeType variableDeclarators ';'
;
interfaceBodyDeclaration
: modifier* interfaceMemberDeclaration
| ';'
;
interfaceMemberDeclaration
: constDeclaration
| interfaceMethodDeclaration
| genericInterfaceMethodDeclaration
| interfaceDeclaration
| annotationTypeDeclaration
| classDeclaration
| enumDeclaration
;
constDeclaration
: typeType constantDeclarator (',' constantDeclarator)* ';'
;
constantDeclarator
: IDENTIFIER ('[' ']')* '=' variableInitializer
;
// see matching of [] comment in methodDeclaratorRest
// methodBody from Java8
interfaceMethodDeclaration
: interfaceMethodModifier* (typeTypeOrVoid | typeParameters annotation* typeTypeOrVoid)
IDENTIFIER formalParameters ('[' ']')* (THROWS qualifiedNameList)? methodBody
;
// Java8
interfaceMethodModifier
: annotation
| PUBLIC
| ABSTRACT
| DEFAULT
| STATIC
| STRICTFP
;
genericInterfaceMethodDeclaration
: typeParameters interfaceMethodDeclaration
;
variableDeclarators
: variableDeclarator (',' variableDeclarator)*
;
variableDeclarator
: variableDeclaratorId ('=' variableInitializer)?
;
variableDeclaratorId
: IDENTIFIER ('[' ']')*
;
variableInitializer
: arrayInitializer
| expression
;
arrayInitializer
: '{' (variableInitializer (',' variableInitializer)* (',')? )? '}'
;
classOrInterfaceType
: IDENTIFIER typeArguments? ('.' IDENTIFIER typeArguments?)*
;
typeArgument
: typeType
| '?' ((EXTENDS | SUPER) typeType)?
;
qualifiedNameList
: qualifiedName (',' qualifiedName)*
;
formalParameters
: '(' formalParameterList? ')'
;
formalParameterList
: formalParameter (',' formalParameter)* (',' lastFormalParameter)?
| lastFormalParameter
;
formalParameter
: variableModifier* typeType variableDeclaratorId
;
lastFormalParameter
: variableModifier* typeType '...' variableDeclaratorId
;
qualifiedName
: IDENTIFIER ('.' IDENTIFIER)*
;
literal
: integerLiteral
| floatLiteral
| CHAR_LITERAL
| STRING_LITERAL
| BOOL_LITERAL
| NULL_LITERAL
;
integerLiteral
: DECIMAL_LITERAL
| HEX_LITERAL
| OCT_LITERAL
| BINARY_LITERAL
;
floatLiteral
: FLOAT_LITERAL
| HEX_FLOAT_LITERAL
;
// ANNOTATIONS
altAnnotationQualifiedName
: (IDENTIFIER DOT)* '@' IDENTIFIER
;
annotation
: ('@' qualifiedName | altAnnotationQualifiedName) ('(' ( elementValuePairs | elementValue )? ')')?
;
elementValuePairs
: elementValuePair (',' elementValuePair)*
;
elementValuePair
: IDENTIFIER '=' elementValue
;
elementValue
: expression
| annotation
| elementValueArrayInitializer
;
elementValueArrayInitializer
: '{' (elementValue (',' elementValue)*)? (',')? '}'
;
annotationTypeDeclaration
: '@' INTERFACE IDENTIFIER annotationTypeBody
;
annotationTypeBody
: '{' (annotationTypeElementDeclaration)* '}'
;
annotationTypeElementDeclaration
: modifier* annotationTypeElementRest
| ';' // this is not allowed by the grammar, but apparently allowed by the actual compiler
;
annotationTypeElementRest
: typeType annotationMethodOrConstantRest ';'
| classDeclaration ';'?
| interfaceDeclaration ';'?
| enumDeclaration ';'?
| annotationTypeDeclaration ';'?
;
annotationMethodOrConstantRest
: annotationMethodRest
| annotationConstantRest
;
annotationMethodRest
: IDENTIFIER '(' ')' defaultValue?
;
annotationConstantRest
: variableDeclarators
;
defaultValue
: DEFAULT elementValue
;
// STATEMENTS / BLOCKS
block
: '{' blockStatement* '}'
;
blockStatement
: localVariableDeclaration ';'
| statement
| localTypeDeclaration
;
localVariableDeclaration
: variableModifier* typeType variableDeclarators
;
localTypeDeclaration
: classOrInterfaceModifier*
(classDeclaration | interfaceDeclaration)
| ';'
;
statement
: blockLabel=block
| ASSERT expression (':' expression)? ';'
| IF parExpression statement (ELSE statement)?
| FOR '(' forControl ')' statement
| WHILE parExpression statement
| DO statement WHILE parExpression ';'
| TRY block (catchClause+ finallyBlock? | finallyBlock)
| TRY resourceSpecification block catchClause* finallyBlock?
| SWITCH parExpression '{' switchBlockStatementGroup* switchLabel* '}'
| SYNCHRONIZED parExpression block
| RETURN expression? ';'
| THROW expression ';'
| BREAK IDENTIFIER? ';'
| CONTINUE IDENTIFIER? ';'
| SEMI
| statementExpression=expression ';'
| identifierLabel=IDENTIFIER ':' statement
;
catchClause
: CATCH '(' variableModifier* catchType IDENTIFIER ')' block
;
catchType
: qualifiedName ('|' qualifiedName)*
;
finallyBlock
: FINALLY block
;
resourceSpecification
: '(' resources ';'? ')'
;
resources
: resource (';' resource)*
;
resource
: variableModifier* classOrInterfaceType variableDeclaratorId '=' expression
;
/** Matches cases then statements, both of which are mandatory.
* To handle empty cases at the end, we add switchLabel* to statement.
*/
switchBlockStatementGroup
: switchLabel+ blockStatement+
;
switchLabel
: CASE (constantExpression=expression | enumConstantName=IDENTIFIER) ':'
| DEFAULT ':'
;
forControl
: enhancedForControl
| forInit? ';' expression? ';' forUpdate=expressionList?
;
forInit
: localVariableDeclaration
| expressionList
;
enhancedForControl
: variableModifier* typeType variableDeclaratorId ':' expression
;
// EXPRESSIONS
parExpression
: '(' expression ')'
;
expressionList
: expression (',' expression)*
;
methodCall
: IDENTIFIER '(' expressionList? ')'
| THIS '(' expressionList? ')'
| SUPER '(' expressionList? ')'
;
expression
: primary
| expression bop='.'
( IDENTIFIER
| methodCall
| THIS
| NEW nonWildcardTypeArguments? innerCreator
| SUPER superSuffix
| explicitGenericInvocation
)
| expression '[' expression ']'
| methodCall
| NEW creator
| '(' typeType ')' expression
| expression postfix=('++' | '--')
| prefix=('+'|'-'|'++'|'--') expression
| prefix=('~'|'!') expression
| expression bop=('*'|'/'|'%') expression
| expression bop=('+'|'-') expression
| expression ('<' '<' | '>' '>' '>' | '>' '>') expression
| expression bop=('<=' | '>=' | '>' | '<') expression
| expression bop=INSTANCEOF typeType
| expression bop=('==' | '!=') expression
| expression bop='&' expression
| expression bop='^' expression
| expression bop='|' expression
| expression bop='&&' expression
| expression bop='||' expression
| <assoc=right> expression bop='?' expression ':' expression
| <assoc=right> expression
bop=('=' | '+=' | '-=' | '*=' | '/=' | '&=' | '|=' | '^=' | '>>=' | '>>>=' | '<<=' | '%=')
expression
| lambdaExpression // Java8
// Java 8 methodReference
| expression '::' typeArguments? IDENTIFIER
| typeType '::' (typeArguments? IDENTIFIER | NEW)
| classType '::' typeArguments? NEW
;
// Java8
lambdaExpression
: lambdaParameters '->' lambdaBody
;
// Java8
lambdaParameters
: IDENTIFIER
| '(' formalParameterList? ')'
| '(' IDENTIFIER (',' IDENTIFIER)* ')'
;
// Java8
lambdaBody
: expression
| block
;
primary
: '(' expression ')'
| THIS
| SUPER
| literal
| IDENTIFIER
| typeTypeOrVoid '.' CLASS
| nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments)
;
classType
: (classOrInterfaceType '.')? annotation* IDENTIFIER typeArguments?
;
creator
: nonWildcardTypeArguments createdName classCreatorRest
| createdName (arrayCreatorRest | classCreatorRest)
;
createdName
: IDENTIFIER typeArgumentsOrDiamond? ('.' IDENTIFIER typeArgumentsOrDiamond?)*
| primitiveType
;
innerCreator
: IDENTIFIER nonWildcardTypeArgumentsOrDiamond? classCreatorRest
;
arrayCreatorRest
: '[' (']' ('[' ']')* arrayInitializer | expression ']' ('[' expression ']')* ('[' ']')*)
;
classCreatorRest
: arguments classBody?
;
explicitGenericInvocation
: nonWildcardTypeArguments explicitGenericInvocationSuffix
;
typeArgumentsOrDiamond
: '<' '>'
| typeArguments
;
nonWildcardTypeArgumentsOrDiamond
: '<' '>'
| nonWildcardTypeArguments
;
nonWildcardTypeArguments
: '<' typeList '>'
;
typeList
: typeType (',' typeType)*
;
typeType
: annotation? (classOrInterfaceType | primitiveType) ('[' ']')*
;
primitiveType
: BOOLEAN
| CHAR
| BYTE
| SHORT
| INT
| LONG
| FLOAT
| DOUBLE
;
typeArguments
: '<' typeArgument (',' typeArgument)* '>'
;
superSuffix
: arguments
| '.' IDENTIFIER arguments?
;
explicitGenericInvocationSuffix
: SUPER superSuffix
| IDENTIFIER arguments
;
arguments
: '(' expressionList? ')'
;
|
/*
[The "BSD licence"]
Copyright (c) 2013 Terence Parr, Sam Harwell
Copyright (c) 2017 Ivan Kochurkin (upgrade to Java 8)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
parser grammar JavaParser;
options { tokenVocab=JavaLexer; }
compilationUnit
: packageDeclaration? importDeclaration* typeDeclaration* EOF
;
packageDeclaration
: annotation* PACKAGE qualifiedName ';'
;
importDeclaration
: IMPORT STATIC? qualifiedName ('.' '*')? ';'
;
typeDeclaration
: classOrInterfaceModifier*
(classDeclaration | enumDeclaration | interfaceDeclaration | annotationTypeDeclaration)
| ';'
;
modifier
: classOrInterfaceModifier
| NATIVE
| SYNCHRONIZED
| TRANSIENT
| VOLATILE
;
classOrInterfaceModifier
: annotation
| PUBLIC
| PROTECTED
| PRIVATE
| STATIC
| ABSTRACT
| FINAL // FINAL for class only -- does not apply to interfaces
| STRICTFP
;
variableModifier
: FINAL
| annotation
;
classDeclaration
: CLASS IDENTIFIER typeParameters?
(EXTENDS typeType)?
(IMPLEMENTS typeList)?
classBody
;
typeParameters
: '<' typeParameter (',' typeParameter)* '>'
;
typeParameter
: annotation* IDENTIFIER (EXTENDS typeBound)?
;
typeBound
: typeType ('&' typeType)*
;
enumDeclaration
: ENUM IDENTIFIER (IMPLEMENTS typeList)? '{' enumConstants? ','? enumBodyDeclarations? '}'
;
enumConstants
: enumConstant (',' enumConstant)*
;
enumConstant
: annotation* IDENTIFIER arguments? classBody?
;
enumBodyDeclarations
: ';' classBodyDeclaration*
;
interfaceDeclaration
: INTERFACE IDENTIFIER typeParameters? (EXTENDS typeList)? interfaceBody
;
classBody
: '{' classBodyDeclaration* '}'
;
interfaceBody
: '{' interfaceBodyDeclaration* '}'
;
classBodyDeclaration
: ';'
| STATIC? block
| modifier* memberDeclaration
;
memberDeclaration
: methodDeclaration
| genericMethodDeclaration
| fieldDeclaration
| constructorDeclaration
| genericConstructorDeclaration
| interfaceDeclaration
| annotationTypeDeclaration
| classDeclaration
| enumDeclaration
;
/* We use rule this even for void methods which cannot have [] after parameters.
This simplifies grammar and we can consider void to be a type, which
renders the [] matching as a context-sensitive issue or a semantic check
for invalid return type after parsing.
*/
methodDeclaration
: typeTypeOrVoid IDENTIFIER formalParameters ('[' ']')*
(THROWS qualifiedNameList)?
methodBody
;
methodBody
: block
| ';'
;
typeTypeOrVoid
: typeType
| VOID
;
genericMethodDeclaration
: typeParameters methodDeclaration
;
genericConstructorDeclaration
: typeParameters constructorDeclaration
;
constructorDeclaration
: IDENTIFIER formalParameters (THROWS qualifiedNameList)? constructorBody=block
;
fieldDeclaration
: typeType variableDeclarators ';'
;
interfaceBodyDeclaration
: modifier* interfaceMemberDeclaration
| ';'
;
interfaceMemberDeclaration
: constDeclaration
| interfaceMethodDeclaration
| genericInterfaceMethodDeclaration
| interfaceDeclaration
| annotationTypeDeclaration
| classDeclaration
| enumDeclaration
;
constDeclaration
: typeType constantDeclarator (',' constantDeclarator)* ';'
;
constantDeclarator
: IDENTIFIER ('[' ']')* '=' variableInitializer
;
// Early versions of Java allows brackets after the method name, eg.
// public int[] return2DArray() [] { ... }
// is the same as
// public int[][] return2DArray() { ... }
interfaceMethodDeclaration
: interfaceMethodModifier* (typeTypeOrVoid | typeParameters annotation* typeTypeOrVoid)
IDENTIFIER formalParameters ('[' ']')* (THROWS qualifiedNameList)? methodBody
;
// Java8
interfaceMethodModifier
: annotation
| PUBLIC
| ABSTRACT
| DEFAULT
| STATIC
| STRICTFP
;
genericInterfaceMethodDeclaration
: typeParameters interfaceMethodDeclaration
;
variableDeclarators
: variableDeclarator (',' variableDeclarator)*
;
variableDeclarator
: variableDeclaratorId ('=' variableInitializer)?
;
variableDeclaratorId
: IDENTIFIER ('[' ']')*
;
variableInitializer
: arrayInitializer
| expression
;
arrayInitializer
: '{' (variableInitializer (',' variableInitializer)* (',')? )? '}'
;
classOrInterfaceType
: IDENTIFIER typeArguments? ('.' IDENTIFIER typeArguments?)*
;
typeArgument
: typeType
| '?' ((EXTENDS | SUPER) typeType)?
;
qualifiedNameList
: qualifiedName (',' qualifiedName)*
;
formalParameters
: '(' formalParameterList? ')'
;
formalParameterList
: formalParameter (',' formalParameter)* (',' lastFormalParameter)?
| lastFormalParameter
;
formalParameter
: variableModifier* typeType variableDeclaratorId
;
lastFormalParameter
: variableModifier* typeType '...' variableDeclaratorId
;
qualifiedName
: IDENTIFIER ('.' IDENTIFIER)*
;
literal
: integerLiteral
| floatLiteral
| CHAR_LITERAL
| STRING_LITERAL
| BOOL_LITERAL
| NULL_LITERAL
;
integerLiteral
: DECIMAL_LITERAL
| HEX_LITERAL
| OCT_LITERAL
| BINARY_LITERAL
;
floatLiteral
: FLOAT_LITERAL
| HEX_FLOAT_LITERAL
;
// ANNOTATIONS
altAnnotationQualifiedName
: (IDENTIFIER DOT)* '@' IDENTIFIER
;
annotation
: ('@' qualifiedName | altAnnotationQualifiedName) ('(' ( elementValuePairs | elementValue )? ')')?
;
elementValuePairs
: elementValuePair (',' elementValuePair)*
;
elementValuePair
: IDENTIFIER '=' elementValue
;
elementValue
: expression
| annotation
| elementValueArrayInitializer
;
elementValueArrayInitializer
: '{' (elementValue (',' elementValue)*)? (',')? '}'
;
annotationTypeDeclaration
: '@' INTERFACE IDENTIFIER annotationTypeBody
;
annotationTypeBody
: '{' (annotationTypeElementDeclaration)* '}'
;
annotationTypeElementDeclaration
: modifier* annotationTypeElementRest
| ';' // this is not allowed by the grammar, but apparently allowed by the actual compiler
;
annotationTypeElementRest
: typeType annotationMethodOrConstantRest ';'
| classDeclaration ';'?
| interfaceDeclaration ';'?
| enumDeclaration ';'?
| annotationTypeDeclaration ';'?
;
annotationMethodOrConstantRest
: annotationMethodRest
| annotationConstantRest
;
annotationMethodRest
: IDENTIFIER '(' ')' defaultValue?
;
annotationConstantRest
: variableDeclarators
;
defaultValue
: DEFAULT elementValue
;
// STATEMENTS / BLOCKS
block
: '{' blockStatement* '}'
;
blockStatement
: localVariableDeclaration ';'
| statement
| localTypeDeclaration
;
localVariableDeclaration
: variableModifier* typeType variableDeclarators
;
localTypeDeclaration
: classOrInterfaceModifier*
(classDeclaration | interfaceDeclaration)
| ';'
;
statement
: blockLabel=block
| ASSERT expression (':' expression)? ';'
| IF parExpression statement (ELSE statement)?
| FOR '(' forControl ')' statement
| WHILE parExpression statement
| DO statement WHILE parExpression ';'
| TRY block (catchClause+ finallyBlock? | finallyBlock)
| TRY resourceSpecification block catchClause* finallyBlock?
| SWITCH parExpression '{' switchBlockStatementGroup* switchLabel* '}'
| SYNCHRONIZED parExpression block
| RETURN expression? ';'
| THROW expression ';'
| BREAK IDENTIFIER? ';'
| CONTINUE IDENTIFIER? ';'
| SEMI
| statementExpression=expression ';'
| identifierLabel=IDENTIFIER ':' statement
;
catchClause
: CATCH '(' variableModifier* catchType IDENTIFIER ')' block
;
catchType
: qualifiedName ('|' qualifiedName)*
;
finallyBlock
: FINALLY block
;
resourceSpecification
: '(' resources ';'? ')'
;
resources
: resource (';' resource)*
;
resource
: variableModifier* classOrInterfaceType variableDeclaratorId '=' expression
;
/** Matches cases then statements, both of which are mandatory.
* To handle empty cases at the end, we add switchLabel* to statement.
*/
switchBlockStatementGroup
: switchLabel+ blockStatement+
;
switchLabel
: CASE (constantExpression=expression | enumConstantName=IDENTIFIER) ':'
| DEFAULT ':'
;
forControl
: enhancedForControl
| forInit? ';' expression? ';' forUpdate=expressionList?
;
forInit
: localVariableDeclaration
| expressionList
;
enhancedForControl
: variableModifier* typeType variableDeclaratorId ':' expression
;
// EXPRESSIONS
parExpression
: '(' expression ')'
;
expressionList
: expression (',' expression)*
;
methodCall
: IDENTIFIER '(' expressionList? ')'
| THIS '(' expressionList? ')'
| SUPER '(' expressionList? ')'
;
expression
: primary
| expression bop='.'
( IDENTIFIER
| methodCall
| THIS
| NEW nonWildcardTypeArguments? innerCreator
| SUPER superSuffix
| explicitGenericInvocation
)
| expression '[' expression ']'
| methodCall
| NEW creator
| '(' typeType ')' expression
| expression postfix=('++' | '--')
| prefix=('+'|'-'|'++'|'--') expression
| prefix=('~'|'!') expression
| expression bop=('*'|'/'|'%') expression
| expression bop=('+'|'-') expression
| expression ('<' '<' | '>' '>' '>' | '>' '>') expression
| expression bop=('<=' | '>=' | '>' | '<') expression
| expression bop=INSTANCEOF typeType
| expression bop=('==' | '!=') expression
| expression bop='&' expression
| expression bop='^' expression
| expression bop='|' expression
| expression bop='&&' expression
| expression bop='||' expression
| <assoc=right> expression bop='?' expression ':' expression
| <assoc=right> expression
bop=('=' | '+=' | '-=' | '*=' | '/=' | '&=' | '|=' | '^=' | '>>=' | '>>>=' | '<<=' | '%=')
expression
| lambdaExpression // Java8
// Java 8 methodReference
| expression '::' typeArguments? IDENTIFIER
| typeType '::' (typeArguments? IDENTIFIER | NEW)
| classType '::' typeArguments? NEW
;
// Java8
lambdaExpression
: lambdaParameters '->' lambdaBody
;
// Java8
lambdaParameters
: IDENTIFIER
| '(' formalParameterList? ')'
| '(' IDENTIFIER (',' IDENTIFIER)* ')'
;
// Java8
lambdaBody
: expression
| block
;
primary
: '(' expression ')'
| THIS
| SUPER
| literal
| IDENTIFIER
| typeTypeOrVoid '.' CLASS
| nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments)
;
classType
: (classOrInterfaceType '.')? annotation* IDENTIFIER typeArguments?
;
creator
: nonWildcardTypeArguments createdName classCreatorRest
| createdName (arrayCreatorRest | classCreatorRest)
;
createdName
: IDENTIFIER typeArgumentsOrDiamond? ('.' IDENTIFIER typeArgumentsOrDiamond?)*
| primitiveType
;
innerCreator
: IDENTIFIER nonWildcardTypeArgumentsOrDiamond? classCreatorRest
;
arrayCreatorRest
: '[' (']' ('[' ']')* arrayInitializer | expression ']' ('[' expression ']')* ('[' ']')*)
;
classCreatorRest
: arguments classBody?
;
explicitGenericInvocation
: nonWildcardTypeArguments explicitGenericInvocationSuffix
;
typeArgumentsOrDiamond
: '<' '>'
| typeArguments
;
nonWildcardTypeArgumentsOrDiamond
: '<' '>'
| nonWildcardTypeArguments
;
nonWildcardTypeArguments
: '<' typeList '>'
;
typeList
: typeType (',' typeType)*
;
typeType
: annotation? (classOrInterfaceType | primitiveType) ('[' ']')*
;
primitiveType
: BOOLEAN
| CHAR
| BYTE
| SHORT
| INT
| LONG
| FLOAT
| DOUBLE
;
typeArguments
: '<' typeArgument (',' typeArgument)* '>'
;
superSuffix
: arguments
| '.' IDENTIFIER arguments?
;
explicitGenericInvocationSuffix
: SUPER superSuffix
| IDENTIFIER arguments
;
arguments
: '(' expressionList? ')'
;
|
Fix comment, give a concrete example
|
Fix comment, give a concrete example
|
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
|
62b57cb06ec71b2b2cc22007a8280ae2e7a22644
|
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 : 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 : ',';
|
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 : ',';
|
make 4. parse as FloatValue
|
make 4. parse as FloatValue
|
ANTLR
|
mit
|
fderose/graphql-java,fderose/graphql-java,dminkovsky/graphql-java,graphql-java/graphql-java,dminkovsky/graphql-java,blevandowski-lv/graphql-java,blevandowski-lv/graphql-java,graphql-java/graphql-java
|
9b815ebb198b84f4fb38ed98f2fdd179737dd7f9
|
xpath/yang-xpath-impl/src/main/antlr4/org/opendaylight/yangtools/yang/xpath/antlr/xpath.g4
|
xpath/yang-xpath-impl/src/main/antlr4/org/opendaylight/yangtools/yang/xpath/antlr/xpath.g4
|
grammar xpath;
/*
XPath 1.0 grammar. Should conform to the official spec at
http://www.w3.org/TR/1999/REC-xpath-19991116. The grammar
rules have been kept as close as possible to those in the
spec, but some adjustmewnts were unavoidable. These were
mainly removing left recursion (spec seems to be based on
LR), and to deal with the double nature of the '*' token
(node wildcard and multiplication operator). See also
section 3.7 in the spec. These rule changes should make
no difference to the strings accepted by the grammar.
Written by Jan-Willem van den Broek
Version 1.0
Do with this code as you will.
*/
/*
Ported to Antlr4 by Tom Everett <[email protected]>
*/
main : expr
;
locationPath
: relativeLocationPath
| absoluteLocationPathNoroot
;
absoluteLocationPathNoroot
: '/' relativeLocationPath
| '//' relativeLocationPath
;
relativeLocationPath
: step (('/'|'//') step)*
;
step : axisSpecifier nodeTest predicate*
| abbreviatedStep
;
axisSpecifier
: AxisName '::'
| AT?
;
nodeTest: nameTest
| NodeType '(' ')'
| 'processing-instruction' '(' Literal ')'
;
predicate
: '[' expr ']'
;
abbreviatedStep
: '.'
| '..'
;
expr : orExpr
;
primaryExpr
: variableReference
| '(' expr ')'
| Literal
| Number
| functionCall
;
functionCall
: functionName '(' ( expr ( ',' expr )* )? ')'
;
unionExprNoRoot
: pathExprNoRoot ('|' unionExprNoRoot)?
| '/' '|' unionExprNoRoot
;
pathExprNoRoot
: locationPath
| filterExpr (('/'|'//') relativeLocationPath)?
;
filterExpr
: primaryExpr predicate*
;
orExpr : andExpr (OR andExpr)*
;
andExpr : equalityExpr (AND equalityExpr)*
;
equalityExpr
: relationalExpr (('='|'!=') relationalExpr)*
;
relationalExpr
: additiveExpr (('<'|'>'|'<='|'>=') additiveExpr)*
;
additiveExpr
: multiplicativeExpr (('+'|'-') multiplicativeExpr)*
;
multiplicativeExpr
: unaryExprNoRoot (('*'|DIV|MOD) multiplicativeExpr)?
| '/' ((DIV|MOD) multiplicativeExpr)?
;
unaryExprNoRoot
: '-'* unionExprNoRoot
;
qName : nCName (':' nCName)?
;
// Does not match NodeType, as per spec.
functionName
: nCName ':' nCName
| NCName
| AxisName
| AND
| OR
| DIV
| MOD
;
variableReference
: '$' qName
;
nameTest: '*'
| nCName ':' '*'
| qName
;
nCName : NCName
| AxisName
| NodeType
| AND
| OR
| DIV
| MOD
;
NodeType: 'comment'
| 'text'
| 'processing-instruction'
| 'node'
;
Number : Digits ('.' Digits?)?
| '.' Digits
;
fragment
Digits : ('0'..'9')+
;
AxisName: 'ancestor'
| 'ancestor-or-self'
| 'attribute'
| 'child'
| 'descendant'
| 'descendant-or-self'
| 'following'
| 'following-sibling'
| 'namespace'
| 'parent'
| 'preceding'
| 'preceding-sibling'
| 'self'
;
PATHSEP
:'/';
ABRPATH
: '//';
LPAR
: '(';
RPAR
: ')';
LBRAC
: '[';
RBRAC
: ']';
MINUS
: '-';
PLUS
: '+';
DOT
: '.';
MUL
: '*';
DOTDOT
: '..';
AT
: '@';
COMMA
: ',';
PIPE
: '|';
LESS
: '<';
MORE_
: '>';
LE
: '<=';
GE
: '>=';
COLON
: ':';
CC
: '::';
APOS
: '\'';
QUOT
: '"';
AND
: 'and';
OR
: 'or';
DIV
: 'div';
MOD
: 'mod';
Literal : '"' ~'"'* '"'
| '\'' ~'\''* '\''
;
Whitespace
: (' '|'\t'|'\n'|'\r')+ ->skip
;
NCName : NCNameStartChar NCNameChar*
;
fragment
NCNameStartChar
: 'A'..'Z'
| '_'
| 'a'..'z'
| '\u00C0'..'\u00D6'
| '\u00D8'..'\u00F6'
| '\u00F8'..'\u02FF'
| '\u0370'..'\u037D'
| '\u037F'..'\u1FFF'
| '\u200C'..'\u200D'
| '\u2070'..'\u218F'
| '\u2C00'..'\u2FEF'
| '\u3001'..'\uD7FF'
| '\uF900'..'\uFDCF'
| '\uFDF0'..'\uFFFD'
// Unfortunately, java escapes can't handle this conveniently,
// as they're limited to 4 hex digits. TODO.
// | '\U010000'..'\U0EFFFF'
;
fragment
NCNameChar
: NCNameStartChar | '-' | '.' | '0'..'9'
| '\u00B7' | '\u0300'..'\u036F'
| '\u203F'..'\u2040'
;
|
grammar xpath;
/*
XPath 1.0 grammar. Should conform to the official spec at
http://www.w3.org/TR/1999/REC-xpath-19991116. The grammar
rules have been kept as close as possible to those in the
spec, but some adjustmewnts were unavoidable. These were
mainly removing left recursion (spec seems to be based on
LR), and to deal with the double nature of the '*' token
(node wildcard and multiplication operator). See also
section 3.7 in the spec. These rule changes should make
no difference to the strings accepted by the grammar.
Written by Jan-Willem van den Broek
Version 1.0
Do with this code as you will.
*/
/*
Ported to Antlr4 by Tom Everett <[email protected]>
*/
main : expr
;
locationPath
: relativeLocationPath
| absoluteLocationPathNoroot
;
absoluteLocationPathNoroot
: '/' relativeLocationPath
| '//' relativeLocationPath
;
relativeLocationPath
: step (('/'|'//') step)*
;
step : axisSpecifier nodeTest predicate*
| abbreviatedStep
;
axisSpecifier
: AxisName '::'
| AT?
;
nodeTest: nameTest
| NodeType '(' ')'
| 'processing-instruction' '(' Literal ')'
;
predicate
: '[' expr ']'
;
abbreviatedStep
: '.'
| '..'
;
expr : orExpr
;
primaryExpr
: variableReference
| '(' expr ')'
| Literal
| Number
| functionCall
;
functionCall
: functionName '(' ( expr ( ',' expr )* )? ')'
;
unionExprNoRoot
: pathExprNoRoot ('|' unionExprNoRoot)?
| '/' '|' unionExprNoRoot
;
pathExprNoRoot
: locationPath
| filterExpr (('/'|'//') relativeLocationPath)?
;
filterExpr
: primaryExpr predicate*
;
orExpr : andExpr (OR andExpr)*
;
andExpr : equalityExpr (AND equalityExpr)*
;
equalityExpr
: relationalExpr (('='|'!=') relationalExpr)*
;
relationalExpr
: additiveExpr (('<'|'>'|'<='|'>=') additiveExpr)*
;
additiveExpr
: multiplicativeExpr (('+'|'-') multiplicativeExpr)*
;
multiplicativeExpr
: unaryExprNoRoot (('*'|DIV|MOD) multiplicativeExpr)?
| '/' ((DIV|MOD) multiplicativeExpr)?
;
unaryExprNoRoot
: '-'* unionExprNoRoot
;
qName : nCName (':' nCName)?
;
// Does not match NodeType, as per spec.
functionName
: nCName ':' nCName
| NCName
| AxisName
| AND
| OR
| DIV
| MOD
;
variableReference
: '$' qName
;
nameTest: '*'
| nCName ':' '*'
| qName
;
nCName : NCName
| AxisName
| NodeType
| AND
| OR
| DIV
| MOD
;
NodeType: 'comment'
| 'text'
| 'processing-instruction'
| 'node'
;
Number : Digits ('.' Digits?)?
| '.' Digits
;
fragment
Digits : ('0'..'9')+
;
AxisName: 'ancestor'
| 'ancestor-or-self'
| 'attribute'
| 'child'
| 'descendant'
| 'descendant-or-self'
| 'following'
| 'following-sibling'
| 'namespace'
| 'parent'
| 'preceding'
| 'preceding-sibling'
| 'self'
;
PATHSEP
:'/';
ABRPATH
: '//';
LPAR
: '(';
RPAR
: ')';
LBRAC
: '[';
RBRAC
: ']';
MINUS
: '-';
PLUS
: '+';
DOT
: '.';
MUL
: '*';
DOTDOT
: '..';
AT
: '@';
COMMA
: ',';
PIPE
: '|';
LESS
: '<';
MORE_
: '>';
LE
: '<=';
GE
: '>=';
COLON
: ':';
CC
: '::';
APOS
: '\'';
QUOT
: '"';
AND
: 'and';
OR
: 'or';
DIV
: 'div';
MOD
: 'mod';
Literal : '"' ~'"'* '"'
| '\'' ~'\''* '\''
;
Whitespace
: (' '|'\t'|'\n'|'\r')+ ->skip
;
NCName : NCNameStartChar NCNameChar*
;
fragment
NCNameStartChar
: 'A'..'Z'
| '_'
| 'a'..'z'
| '\u00C0'..'\u00D6'
| '\u00D8'..'\u00F6'
| '\u00F8'..'\u02FF'
| '\u0370'..'\u037D'
| '\u037F'..'\u1FFF'
| '\u200C'..'\u200D'
| '\u2070'..'\u218F'
| '\u2C00'..'\u2FEF'
| '\u3001'..'\uD7FF'
| '\uF900'..'\uFDCF'
| '\uFDF0'..'\uFFFD'
| '\u{10000}'..'\u{EFFFF}'
;
fragment
NCNameChar
: NCNameStartChar | '-' | '.' | '0'..'9'
| '\u00B7' | '\u0300'..'\u036F'
| '\u203F'..'\u2040'
;
|
Address XPath unicode range TODO
|
Address XPath unicode range TODO
This is a port of
https://github.com/antlr/grammars-v4/commit/3edc28b7a1f1ff4a40ef1ebb8c14bb28848d34bf
addressing a leftover omission.
Change-Id: Ic5460c1ec2dd4865fb25f858f107da89e0be284b
Signed-off-by: Robert Varga <[email protected]>
|
ANTLR
|
epl-1.0
|
opendaylight/yangtools,opendaylight/yangtools
|
2b363eed5b52bfd703ab08139f8ca400cc37e04b
|
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 UNIQUE? (CLUSTERED | NONCLUSTERED)? 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_))?
;
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 fileTableSpecification__ createDefinitionClause_
;
createIndex
: CREATE UNIQUE? (CLUSTERED | NONCLUSTERED)? 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
;
fileTableSpecification__
: (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_))?
;
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_)?
;
|
rename to fileTableSpecification__
|
rename to fileTableSpecification__
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
|
2022097d5b8fa6a6f144e4565021858ce76d5a61
|
wren/WrenParser.g4
|
wren/WrenParser.g4
|
/*
[The "BSD licence"]
Copyright (c) 2022 Boris Zhguchev
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
parser grammar WrenParser;
options { tokenVocab=WrenLexer; }
script: fileAtom+ EOF;
fileAtom
: class
| function
| importModule
| statement
| block
;
// assignment
assignment: VAR? expression assignOp (expression | assignment+);
assignmentNull: VAR id;
assignOp
: ASSIGN
| ADD_ASSIGN
| SUB_ASSIGN
| MUL_ASSIGN
| DIV_ASSIGN
| AND_ASSIGN
| OR_ASSIGN
| XOR_ASSIGN
| MOD_ASSIGN
| LSHIFT_ASSIGN
| RSHIFT_ASSIGN
| URSHIFT_ASSIGN
;
// flow
if: ifCond bodyFlow elseIf* else?;
ifCond: IF LPAREN expression RPAREN;
elseIf: ELSE ifCond bodyFlow;
else : ELSE bodyFlow;
while: WHILE LPAREN (expression | assignment) RPAREN bodyFlow;
for: FOR LPAREN id IN expression RPAREN bodyFlow;
bodyFlow
: block
| statement
;
// statements
statement
: expression
| assignment
| assignmentNull
| if
| while
| for
| block
| return
;
lambdaParameters: BITOR (id (COMMA id)*) BITOR;
block: LBRACE lambdaParameters? statement* RBRACE;
return: RETURN expression;
// class
class: attributes? FOREIGN? CLASS id inheritance? LBRACE classBody RBRACE;
inheritance: IS id ;
// class atributes
attribute
: simpleAttribute
| groupAttribute
;
attributes: attribute+;
attributeValue: id (ASSIGN atomExpression)?;
simpleAttribute:HASH BANG? attributeValue ;
groupAttribute:HASH BANG? id LPAREN attributeValue (COMMA attributeValue)* RPAREN;
// class body
classBody:(attributes? classBodyTpe? classStatement)*;
classBodyTpe
: FOREIGN
| STATIC
| STATIC FOREIGN
| FOREIGN STATIC
;
// class statement
classStatement
: function
| classGetter
| classSetter
| classSubscriptGet
| classSubscriptSet
| classOpGetter
| classOpSetter
| classConstructor
;
classConstructor: CONSTRUCT id arguments block;
operatorGetter
: SUB
| TILDE
| BANG
| id
;
operatorSetter
: SUB
| MUL
| DIV
| MOD
| ADD
| ELLIPSIS_OUT
| ELLIPSIS_IN
| LSHIFT
| RSHIFT
| BITAND
| CARET
| BITOR
| GT
| LT
| EQUAL
| LE
| GE
| NOTEQUAL
| IS
| id
;
classOpGetter: operatorGetter block;
classOpSetter: operatorSetter oneArgument block;
oneArgument: LPAREN id RPAREN;
subscript: LBRACK enumeration RBRACK;
classSubscriptGet: subscript block;
classSubscriptSet: subscript ASSIGN oneArgument block;
classGetter: id block?;
classSetter: id assignmentSetter block;
assignmentSetter:ASSIGN oneArgument;
arguments: LPAREN (id (COMMA id)*)? RPAREN;
function: id arguments block?;
// imports
importModule: IMPORT STRING_LITERAL importVariables?;
importVariable: id (AS id)?;
importVariables: FOR importVariable (COMMA importVariable);
// call
call: callHead (DOT call)*;
callBlock: id block;
callSignature: id LPAREN enumeration? RPAREN;
callHead
: callSignature
| callBlock
| id
;
// expressions
expression
: expression logic
| expression arithBit
| expression arithShift
| expression arithRange
| expression arithAdd
| expression arithMul
| expression DOT call
| expression IS expression
| BANG expression
| LPAREN expression RPAREN
| expression elvis
| atomExpression
;
atomExpression
: id
| bool
| char
| string
| num
| null
| listInit
| mapInit
| call
| range
| collectionElem
| BREAK
| CONTINUE
| importModule
| SUB atomExpression
;
enumeration: (expression (COMMA expression)*);
pairEnumeration: (expression COLON expression (COMMA expression COLON expression)*);
range:rangeExpression (ELLIPSIS_IN | ELLIPSIS_OUT) rangeExpression;
listInit: LBRACK enumeration? RBRACK;
mapInit: LBRACE pairEnumeration? RBRACE;
elem
: id
| string
| call
;
collectionElem: elem listInit ;
rangeExpression
: id
| num
| call
;
// arithmetic expressions
arithMul: (MUL | DIV | MOD) expression;
arithAdd: (SUB | ADD) (arithMul | expression);
arithRange:(ELLIPSIS_IN | ELLIPSIS_OUT) (arithAdd | expression);
arithShift:(LSHIFT | RSHIFT) (arithRange | expression);
arithBit: (BITAND | BITOR | CARET) (arithShift | expression);
// logic expressions
logicOp
: GT
| LT
| EQUAL
| LE
| GE
| NOTEQUAL
;
atomLogic
: logicOp expression
| (AND | OR) expression
;
andLogic: atomLogic (AND expression atomLogic)*;
logic: andLogic (OR expression andLogic)*;
elvis: QUESTION expression COLON expression;
// primitives
id: IDENTIFIER;
bool: TRUE | FALSE ;
char: CHAR_LITERAL;
string: STRING_LITERAL | TEXT_BLOCK ;
num
: DECIMAL_LITERAL
| HEX_LITERAL
| FLOAT_LITERAL
| HEX_FLOAT_LITERAL
;
null: NULL;
|
/*
[The "BSD licence"]
Copyright (c) 2022 Boris Zhguchev
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
parser grammar WrenParser;
options { tokenVocab=WrenLexer; }
script: fileAtom+ EOF;
fileAtom
: classDefinition
| function
| importModule
| statement
| block
;
// assignment
assignment: VAR? expression assignOp (expression | assignment+);
assignmentNull: VAR id;
assignOp
: ASSIGN
| ADD_ASSIGN
| SUB_ASSIGN
| MUL_ASSIGN
| DIV_ASSIGN
| AND_ASSIGN
| OR_ASSIGN
| XOR_ASSIGN
| MOD_ASSIGN
| LSHIFT_ASSIGN
| RSHIFT_ASSIGN
| URSHIFT_ASSIGN
;
// flow
ifSt: ifCond bodyFlow elseIf* elseSt?;
ifCond: IF LPAREN expression RPAREN;
elseIf: ELSE ifCond bodyFlow;
elseSt : ELSE bodyFlow;
whileSt: WHILE LPAREN (expression | assignment) RPAREN bodyFlow;
forSt: FOR LPAREN id IN expression RPAREN bodyFlow;
bodyFlow
: block
| statement
;
// statements
statement
: expression
| assignment
| assignmentNull
| ifSt
| whileSt
| forSt
| block
| returnSt
;
lambdaParameters: BITOR (id (COMMA id)*) BITOR;
block: LBRACE lambdaParameters? statement* RBRACE;
returnSt: RETURN expression;
// class
classDefinition: attributes? FOREIGN? CLASS id inheritance? LBRACE classBody RBRACE;
inheritance: IS id ;
// class atributes
attribute
: simpleAttribute
| groupAttribute
;
attributes: attribute+;
attributeValue: id (ASSIGN atomExpression)?;
simpleAttribute:HASH BANG? attributeValue ;
groupAttribute:HASH BANG? id LPAREN attributeValue (COMMA attributeValue)* RPAREN;
// class body
classBody:(attributes? classBodyTpe? classStatement)*;
classBodyTpe
: FOREIGN
| STATIC
| STATIC FOREIGN
| FOREIGN STATIC
;
// class statement
classStatement
: function
| classGetter
| classSetter
| classSubscriptGet
| classSubscriptSet
| classOpGetter
| classOpSetter
| classConstructor
;
classConstructor: CONSTRUCT id arguments block;
operatorGetter
: SUB
| TILDE
| BANG
| id
;
operatorSetter
: SUB
| MUL
| DIV
| MOD
| ADD
| ELLIPSIS_OUT
| ELLIPSIS_IN
| LSHIFT
| RSHIFT
| BITAND
| CARET
| BITOR
| GT
| LT
| EQUAL
| LE
| GE
| NOTEQUAL
| IS
| id
;
classOpGetter: operatorGetter block;
classOpSetter: operatorSetter oneArgument block;
oneArgument: LPAREN id RPAREN;
subscript: LBRACK enumeration RBRACK;
classSubscriptGet: subscript block;
classSubscriptSet: subscript ASSIGN oneArgument block;
classGetter: id block?;
classSetter: id assignmentSetter block;
assignmentSetter:ASSIGN oneArgument;
arguments: LPAREN (id (COMMA id)*)? RPAREN;
function: id arguments block?;
// imports
importModule: IMPORT STRING_LITERAL importVariables?;
importVariable: id (AS id)?;
importVariables: FOR importVariable (COMMA importVariable);
// call
call: callHead (DOT call)*;
callBlock: id block;
callSignature: id LPAREN enumeration? RPAREN;
callHead
: callSignature
| callBlock
| id
;
// expressions
expression
: expression compoundExpression
| BANG expression
| LPAREN expression RPAREN
| atomExpression
;
compoundExpression
: logic
| arithBit
| arithShift
| arithRange
| arithAdd
| arithMul
| DOT call
| IS expression
| elvis
;
atomExpression
: id
| boolE
| charE
| stringE
| numE
| nullE
| listInit
| mapInit
| call
| range
| collectionElem
| BREAK
| CONTINUE
| importModule
| SUB atomExpression
;
enumeration: (expression (COMMA expression)*);
pairEnumeration: (expression COLON expression (COMMA expression COLON expression)*);
range:rangeExpression (ELLIPSIS_IN | ELLIPSIS_OUT) rangeExpression;
listInit: LBRACK enumeration? RBRACK;
mapInit: LBRACE pairEnumeration? RBRACE;
elem
: id
| stringE
| call
;
collectionElem: elem listInit ;
rangeExpression
: id
| numE
| call
;
// arithmetic expressions
arithMul: (MUL | DIV | MOD) expression;
arithAdd: (SUB | ADD) (arithMul | expression);
arithRange:(ELLIPSIS_IN | ELLIPSIS_OUT) (arithAdd | expression);
arithShift:(LSHIFT | RSHIFT) (arithRange | expression);
arithBit: (BITAND | BITOR | CARET) (arithShift | expression);
// logic expressions
logicOp
: GT
| LT
| EQUAL
| LE
| GE
| NOTEQUAL
;
atomLogic
: logicOp expression
| (AND | OR) expression
;
andLogic: atomLogic (AND expression atomLogic)*;
logic: andLogic (OR expression andLogic)*;
elvis: QUESTION expression COLON expression;
// primitives
id: IDENTIFIER;
boolE: TRUE | FALSE ;
charE: CHAR_LITERAL;
stringE: STRING_LITERAL | TEXT_BLOCK ;
numE
: DECIMAL_LITERAL
| HEX_LITERAL
| FLOAT_LITERAL
| HEX_FLOAT_LITERAL
;
nullE: NULL;
|
correct grammar
|
correct 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
|
e16c9d6c0eddd83d043277431fe0c3f2dcaed081
|
source/Owin.Scim.Antlr/ScimFilter.g4
|
source/Owin.Scim.Antlr/ScimFilter.g4
|
grammar ScimFilter;
parse
: filter
;
filter
: attrPath SP PR #presentExp
| attrPath SP COMPAREOPERATOR SP VALUE #operatorExp
| NOT? SP* '(' filter ')' #braceExp
| attrPath '[' valPathFilter ']' #valPathExp
| filter SP AND SP filter #andExp
| filter SP OR SP filter #orExp
;
valPathFilter
: attrPath SP PR #valPathPresentExp
| attrPath SP COMPAREOPERATOR SP VALUE #valPathOperatorExp
| NOT? SP* '(' valPathFilter ')' #valPathBraceExp
| valPathFilter SP AND SP valPathFilter #valPathAndExp
| valPathFilter SP OR SP valPathFilter #valPathOrExp
;
attrPath
: (SCHEMA)? ATTRNAME ('.' ATTRNAME)?
;
COMPAREOPERATOR : EQ | NE | CO | SW | EW | GT | GE | LT | LE;
EQ : [eE][qQ];
NE : [nN][eE];
CO : [cC][oO];
SW : [sS][wW];
EW : [eE][wW];
PR : [pP][rR];
GT : [gG][tT];
GE : [gG][eE];
LT : [lL][tT];
LE : [lL][eE];
NOT : [nN][oO][tT];
AND : [aA][nN][dD];
OR : [oO][rR];
SP : ' ';
SCHEMA : 'urn:' (SEGMENT ':')+;
ATTRNAME : ALPHA (ALPHA | DIGIT | '_' | '-')+;
fragment SEGMENT : (ALPHA | DIGIT | '_' | '-' | '.')+;
fragment DIGIT : [0-9];
fragment ALPHA : [a-z] | [A-Z];
fragment DATETIME: (ALPHA | DIGIT | '_' | '-' | '.' | ':')+;
ESCAPED_QUOTE : '\\"';
VALUE : '"'(ESCAPED_QUOTE | ~'"')*'"' | 'true' | 'false' | 'null' | DIGIT+('.'DIGIT+)? | DATETIME+('.'DATETIME+)?;
EXCLUDE : [\b | \t | \r | \n]+ -> skip;
|
grammar ScimFilter;
parse
: filter
;
filter
: attrPath SP PR #presentExp
| attrPath SP COMPAREOPERATOR SP VALUE #operatorExp
| NOT? SP* '(' filter ')' #braceExp
| attrPath '[' valPathFilter ']' #valPathExp
| filter SP AND SP filter #andExp
| filter SP OR SP filter #orExp
;
valPathFilter
: attrPath SP PR #valPathPresentExp
| attrPath SP COMPAREOPERATOR SP VALUE #valPathOperatorExp
| NOT? SP* '(' valPathFilter ')' #valPathBraceExp
| valPathFilter SP AND SP valPathFilter #valPathAndExp
| valPathFilter SP OR SP valPathFilter #valPathOrExp
;
attrPath
: (SCHEMA)? ATTRNAME ('.' ATTRNAME)?
;
COMPAREOPERATOR : EQ | NE | CO | SW | EW | GT | GE | LT | LE;
EQ : [eE][qQ];
NE : [nN][eE];
CO : [cC][oO];
SW : [sS][wW];
EW : [eE][wW];
PR : [pP][rR];
GT : [gG][tT];
GE : [gG][eE];
LT : [lL][tT];
LE : [lL][eE];
NOT : [nN][oO][tT];
AND : [aA][nN][dD];
OR : [oO][rR];
SP : ' ';
SCHEMA : 'urn:' (SEGMENT ':')+;
ATTRNAME : ALPHA (ALPHA | DIGIT | '_' | '-')+;
fragment SEGMENT : (ALPHA | DIGIT | '_' | '-' | '.')+;
fragment DIGIT : [0-9];
fragment ALPHA : [a-z] | [A-Z];
ESCAPED_QUOTE : '\\"';
VALUE : '"'(ESCAPED_QUOTE | ~'"')*'"' | 'true' | 'false' | 'null' | DIGIT+('.'DIGIT+)?;
EXCLUDE : [\b | \t | \r | \n]+ -> skip;
|
Revert "Added support for filtering on datetime (meta.lastModified and meta.created)"
|
Revert "Added support for filtering on datetime (meta.lastModified and meta.created)"
|
ANTLR
|
mit
|
PowerDMS/Owin.Scim,PowerDMS/Owin.Scim,PowerDMS/Owin.Scim
|
285a499f6047330d59f14d90aab3824d8e1d2a34
|
sharding-core/src/main/antlr4/imports/MySQLDCLStatement.g4
|
sharding-core/src/main/antlr4/imports/MySQLDCLStatement.g4
|
grammar MySQLDCLStatement;
import MySQLKeyword, Keyword, BaseRule, DataType, Symbol;
grant
: GRANT privType columnList? (COMMA privType columnList?)*
ON objectType? privLevel
TO userOrRoles
(WITH GRANT OPTION)?
;
privType
: ALL PRIVILEGES?
| ALTER ROUTINE?
| CREATE (ROUTINE | TEMPORARY TABLES? | USER | VIEW)?
| DELETE
| DROP
| EVENT
| EXECUTE
| FILE
| GRANT OPTION
| INDEX
| INSERT
| LOCK TABLES
| PROCESS
| PROXY
| REFERENCES
| RELOAD
| REPLICATION CLIENT
| REPLICATION SLAVE
| SELECT
| SHOW DATABASES
| SHOW VIEW
| SHUTDOWN
| SUPER
| TRIGGER
| UPDATE
| USAGE
| AUDIT_ADMIN
| BINLOG_ADMIN
| CONNECTION_ADMIN
| ENCRYPTION_KEY_ADMIN
| FIREWALL_ADMIN
| FIREWALL_USER
| GROUP_REPLICATION_ADMIN
| REPLICATION_SLAVE_ADMIN
| ROLE_ADMIN
| SET_USER_ID
| SYSTEM_VARIABLES_ADMIN
| VERSION_TOKEN_ADMIN
;
objectType
: TABLE | FUNCTION | PROCEDURE
;
privLevel
: ASTERISK
| ASTERISK DOT ASTERISK
| schemaName DOT ASTERISK
| schemaName DOT tableName
| tableName
| schemaName DOT routineName
;
user
: STRING AT_ STRING | STRING | ID
;
users
: user (COMMA user)*
;
role
: STRING AT_ STRING | STRING | ID
;
roles
: role (COMMA role)*
;
userOrRole
: user | role
;
userOrRoles
: userOrRole (COMMA userOrRole)*
;
grantProxy
: GRANT PROXY ON userOrRole TO userOrRoles (WITH GRANT OPTION)?
;
grantRole
: GRANT roleNames TO userOrRoles (WITH ADMIN OPTION)?
;
revoke
: REVOKE privType columnList? (COMMA privType columnList?)*
ON objectType? privLevel
FROM userOrRoles
;
revokeAll
: REVOKE ALL PRIVILEGES? COMMA GRANT OPTION
FROM userOrRoles
;
revokeProxy
: REVOKE PROXY ON userOrRole
FROM userOrRoles
;
revokeRole
: REVOKE roleNames
FROM userOrRoles
;
createUser
: CREATE USER (IF NOT EXISTS)?
user authOptions?
DEFAULT ROLE roles
(REQUIRE (NONE | tlsOption (COMMA AND? tlsOption)*))?
(WITH resourceOption (COMMA resourceOption)*)?
(passwordOption | lockOption)*
;
authOption
: IDENTIFIED BY STRING (REPLACE STRING)? (RETAIN CURRENT PASSWORD)?
| IDENTIFIED WITH authPlugin
| IDENTIFIED WITH authPlugin BY STRING (REPLACE STRING)? (RETAIN CURRENT PASSWORD)?
| IDENTIFIED WITH authPlugin AS STRING
| DISCARD OLD PASSWORD
;
authOptions
: authOption (COMMA authOption)*
;
authPlugin
: ID
;
tlsOption
: SSL | CIPHER STRING | ISSUER STRING | SUBJECT STRING | ID
;
resourceOption
: MAX_QUERIES_PER_HOUR NUMBER
MAX_UPDATES_PER_HOUR NUMBER
MAX_CONNECTIONS_PER_HOUR NUMBER
MAX_USER_CONNECTIONS NUMBER
;
passwordOption
: PASSWORD EXPIRE (DEFAULT | NEVER | INTERVAL NUMBER DAY)?
| PASSWORD HISTORY (DEFAULT | NUMBER)
| PASSWORD REUSE INTERVAL (DEFAULT | NUMBER DAY)
| PASSWORD REQUIRE CURRENT (DEFAULT | OPTIONAL)?
;
lockOption
: ACCOUNT (LOCK | UNLOCK)
;
alterUser
: ALTER USER (IF EXISTS)?
user authOptions
(REQUIRE (NONE | tlsOption (COMMA AND? tlsOption)*))?
(WITH resourceOption (COMMA resourceOption)*)?
(passwordOption | lockOption)*
;
alterCurrentUser
: ALTER USER (IF EXISTS)? USER() userFuncAuthOption
;
userFuncAuthOption
: IDENTIFIED BY STRING (REPLACE STRING)? (RETAIN CURRENT PASSWORD)?
| DISCARD OLD PASSWORD
;
alterUserRole
: ALTER USER (IF EXISTS)?
user DEFAULT ROLE
(NONE | ALL | roles)
;
dropUser
: DROP USER (IF EXISTS)? users
;
renameUser
: RENAME USER user TO user (user TO user)*
;
createRole
: CREATE ROLE (IF NOT EXISTS)? roles
;
dropRole
: DROP ROLE (IF EXISTS)? roles
;
setPassword
: SET PASSWORD (FOR user)? EQ STRING (REPLACE STRING)? (RETAIN CURRENT PASSWORD)?
;
setDefaultRole
: SET DEFAULT ROLE (NONE | ALL | roles) TO users
;
setRole
: SET ROLE (DEFAULT | NONE | ALL | ALL EXCEPT roles | roles)
;
|
grammar MySQLDCLStatement;
import MySQLKeyword, Keyword, BaseRule, DataType, Symbol;
grant
: GRANT privType columnList? (COMMA privType columnList?)*
ON objectType? privLevel
TO userOrRoles
(WITH GRANT OPTION)?
;
privType
: ALL PRIVILEGES?
| ALTER ROUTINE?
| CREATE
| CREATE ROUTINE
| CREATE TABLESPACE
| CREATE TEMPORARY TABLES
| CREATE USER
| CREATE VIEW
| DELETE
| DROP
| EVENT
| EXECUTE
| FILE
| GRANT OPTION
| INDEX
| INSERT
| LOCK TABLES
| PROCESS
| PROXY
| REFERENCES
| RELOAD
| REPLICATION CLIENT
| REPLICATION SLAVE
| SELECT
| SHOW DATABASES
| SHOW VIEW
| SHUTDOWN
| SUPER
| TRIGGER
| UPDATE
| USAGE
| AUDIT_ADMIN
| BINLOG_ADMIN
| CONNECTION_ADMIN
| ENCRYPTION_KEY_ADMIN
| FIREWALL_ADMIN
| FIREWALL_USER
| GROUP_REPLICATION_ADMIN
| REPLICATION_SLAVE_ADMIN
| ROLE_ADMIN
| SET_USER_ID
| SYSTEM_VARIABLES_ADMIN
| VERSION_TOKEN_ADMIN
;
objectType
: TABLE | FUNCTION | PROCEDURE
;
privLevel
: ASTERISK
| ASTERISK DOT ASTERISK
| schemaName DOT ASTERISK
| schemaName DOT tableName
| tableName
| schemaName DOT routineName
;
user
: STRING AT_ STRING | STRING | ID
;
users
: user (COMMA user)*
;
role
: STRING AT_ STRING | STRING | ID
;
roles
: role (COMMA role)*
;
userOrRole
: user | role
;
userOrRoles
: userOrRole (COMMA userOrRole)*
;
grantProxy
: GRANT PROXY ON userOrRole TO userOrRoles (WITH GRANT OPTION)?
;
grantRole
: GRANT roleNames TO userOrRoles (WITH ADMIN OPTION)?
;
revoke
: REVOKE privType columnList? (COMMA privType columnList?)*
ON objectType? privLevel
FROM userOrRoles
;
revokeAll
: REVOKE ALL PRIVILEGES? COMMA GRANT OPTION
FROM userOrRoles
;
revokeProxy
: REVOKE PROXY ON userOrRole
FROM userOrRoles
;
revokeRole
: REVOKE roleNames
FROM userOrRoles
;
createUser
: CREATE USER (IF NOT EXISTS)?
user authOptions?
DEFAULT ROLE roles
(REQUIRE (NONE | tlsOption (COMMA AND? tlsOption)*))?
(WITH resourceOption (COMMA resourceOption)*)?
(passwordOption | lockOption)*
;
authOption
: IDENTIFIED BY STRING (REPLACE STRING)? (RETAIN CURRENT PASSWORD)?
| IDENTIFIED WITH authPlugin
| IDENTIFIED WITH authPlugin BY STRING (REPLACE STRING)? (RETAIN CURRENT PASSWORD)?
| IDENTIFIED WITH authPlugin AS STRING
| DISCARD OLD PASSWORD
;
authOptions
: authOption (COMMA authOption)*
;
authPlugin
: ID
;
tlsOption
: SSL | CIPHER STRING | ISSUER STRING | SUBJECT STRING | ID
;
resourceOption
: MAX_QUERIES_PER_HOUR NUMBER
MAX_UPDATES_PER_HOUR NUMBER
MAX_CONNECTIONS_PER_HOUR NUMBER
MAX_USER_CONNECTIONS NUMBER
;
passwordOption
: PASSWORD EXPIRE (DEFAULT | NEVER | INTERVAL NUMBER DAY)?
| PASSWORD HISTORY (DEFAULT | NUMBER)
| PASSWORD REUSE INTERVAL (DEFAULT | NUMBER DAY)
| PASSWORD REQUIRE CURRENT (DEFAULT | OPTIONAL)?
;
lockOption
: ACCOUNT (LOCK | UNLOCK)
;
alterUser
: ALTER USER (IF EXISTS)?
user authOptions
(REQUIRE (NONE | tlsOption (COMMA AND? tlsOption)*))?
(WITH resourceOption (COMMA resourceOption)*)?
(passwordOption | lockOption)*
;
alterCurrentUser
: ALTER USER (IF EXISTS)? USER() userFuncAuthOption
;
userFuncAuthOption
: IDENTIFIED BY STRING (REPLACE STRING)? (RETAIN CURRENT PASSWORD)?
| DISCARD OLD PASSWORD
;
alterUserRole
: ALTER USER (IF EXISTS)?
user DEFAULT ROLE
(NONE | ALL | roles)
;
dropUser
: DROP USER (IF EXISTS)? users
;
renameUser
: RENAME USER user TO user (user TO user)*
;
createRole
: CREATE ROLE (IF NOT EXISTS)? roles
;
dropRole
: DROP ROLE (IF EXISTS)? roles
;
setPassword
: SET PASSWORD (FOR user)? EQ STRING (REPLACE STRING)? (RETAIN CURRENT PASSWORD)?
;
setDefaultRole
: SET DEFAULT ROLE (NONE | ALL | roles) TO users
;
setRole
: SET ROLE (DEFAULT | NONE | ALL | ALL EXCEPT roles | roles)
;
|
fix mysql privType
|
fix mysql privType
|
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
|
9f7e5e87a2621a606351a6cd75ace0e181edc986
|
src/main/antlr/MiniJava.g4
|
src/main/antlr/MiniJava.g4
|
grammar MiniJava;
program : mainClassDecl (classDecl)* ;
mainClassDecl : 'class' ID '{' 'public' 'static' 'void' 'main' '(' 'String' '[' ']' ID')' '{' (stmt)* '}' '}' ;
classDecl : 'class' ID ('extends' ID)? '{' (classVarDecl)* (methodDecl)* '}' ;
classVarDecl : type ID ';' ;
methodDecl : 'public' type ID (LPAREN (formal (',' formal)*)? RPAREN | PAREN) '{' (stmt)* 'return' expr ';' '}' ;
formal : type ID;
type : INT_TYPE | BOOL_TYPE | ID ;
stmt : varDecl
| block
| ifElse
| whileDecl
| print
| assigment ;
varDecl : type ID '=' expr ';' ;
block : '{' (stmt)* '}' ;
ifElse : 'if' '(' expr ')' stmt 'else' stmt ;
whileDecl : 'while' '(' expr ')' stmt ;
print : 'System.out.println' '(' expr ')' ';' ;
assigment : ID '=' expr ';' ;
expr : logicalOr ;
logicalOr :
logicalAnd OR logicalOr
| logicalAnd ;
logicalAnd :
equalsOrNotEquals AND logicalAnd
| equalsOrNotEquals;
equalsOrNotEquals :
relation (EEQ|NEQ) equalsOrNotEquals
| relation ;
relation :
plusOrMinus (LEQ|GEQ|LT|GT) relation
| plusOrMinus ;
plusOrMinus :
multOrDiv (ADD|SUB) plusOrMinus
| multOrDiv ;
multOrDiv :
unary (MUL|DIV) multOrDiv
| unary ;
unary :
(BANG|SUB) expr
| methodCall ;
methodCall :
methodCall DOT ID (LPAREN expr (COMMA expr)* RPAREN | PAREN)
| atom ;
atom :
INT
| BOOL
| NULL
| THIS
| NEW ID (PAREN | LPAREN RPAREN)
| ID
| LPAREN expr RPAREN ;
// Reserved Words
NULL : 'null' ;
THIS : 'this' ;
NEW : 'new' ;
BOOL_TYPE : 'boolean';
INT_TYPE : 'int';
// Types
INT : NONZERODIGIT DIGIT* | '0' ;
DIGIT : [0-9] ;
NONZERODIGIT : [1-9] ;
BOOL : TRUE | FALSE ;
FALSE : 'false' ;
TRUE : 'true' ;
// Identifier
ID : LETTER (LETTER | DIGIT)* ;
LETTER : [a-z] | [A-Z] ;
// Logic operators
AND : '&&' ;
OR : '||' ;
// Relational operators
EEQ : '==' ;
NEQ : '!=' ;
LEQ : '<=' ;
GEQ : '>=' ;
LT : '<' ;
GT : '>' ;
// Arithmetic operators
ADD : '+' ;
SUB : '-' ;
MUL : '*' ;
DIV : '/' ;
// Unary operators
BANG : '!' ;
//NEGATIVE : SUB ;
// Delimeters
LPAREN : '(' ;
RPAREN : ')' ;
PAREN : '()';
DOT : '.' ;
COMMA : ',' ;
Whitespace : (' ' | '\t' | '\n' | '\r' | Comment) -> channel(HIDDEN);
Comment : ('//' ~('\r' | '\n')* | '/*' .*? '*/') -> channel(HIDDEN);
|
grammar MiniJava;
program : mainClassDecl (classDecl)* ;
mainClassDecl : 'class' ID '{' 'public' 'static' 'void' 'main' '(' 'String' '[' ']' ID')' '{' (stmt)* '}' '}' ;
classDecl : 'class' ID ('extends' ID)? '{' (classVarDecl)* (methodDecl)* '}' ;
classVarDecl : type ID ';' ;
methodDecl : 'public' type ID (LPAREN (formal (',' formal)*)? RPAREN | PAREN) '{' (stmt)* 'return' expr ';' '}' ;
formal : type ID;
type : INT_TYPE | BOOL_TYPE | ID ;
stmt : varDecl
| block
| ifElse
| whileDecl
| print
| assigment ;
varDecl : type ID '=' expr ';' ;
block : '{' (stmt)* '}' ;
ifElse : 'if' '(' expr ')' stmt 'else' stmt ;
whileDecl : 'while' '(' expr ')' stmt ;
print : 'System.out.println' '(' expr ')' ';' ;
assigment : ID '=' expr ';' ;
expr : logicalOr ;
logicalOr :
logicalAnd OR logicalOr
| logicalAnd ;
logicalAnd :
equalsOrNotEquals AND logicalAnd
| equalsOrNotEquals;
equalsOrNotEquals :
relation (EEQ|NEQ) equalsOrNotEquals
| relation ;
relation :
plusOrMinus (LEQ|GEQ|LT|GT) relation
| plusOrMinus ;
plusOrMinus :
plusOrMinus (ADD|SUB) multOrDiv
| multOrDiv ;
multOrDiv :
multOrDiv (MUL|DIV) unary
| unary ;
unary :
(BANG|SUB) expr
| methodCall ;
methodCall :
methodCall DOT ID (LPAREN expr (COMMA expr)* RPAREN | PAREN)
| atom ;
atom :
INT
| BOOL
| NULL
| THIS
| NEW ID (PAREN | LPAREN RPAREN)
| ID
| LPAREN expr RPAREN ;
// Reserved Words
NULL : 'null' ;
THIS : 'this' ;
NEW : 'new' ;
BOOL_TYPE : 'boolean';
INT_TYPE : 'int';
// Types
INT : NONZERODIGIT DIGIT* | '0' ;
DIGIT : [0-9] ;
NONZERODIGIT : [1-9] ;
BOOL : TRUE | FALSE ;
FALSE : 'false' ;
TRUE : 'true' ;
// Identifier
ID : LETTER (LETTER | DIGIT)* ;
LETTER : [a-z] | [A-Z] ;
// Logic operators
AND : '&&' ;
OR : '||' ;
// Relational operators
EEQ : '==' ;
NEQ : '!=' ;
LEQ : '<=' ;
GEQ : '>=' ;
LT : '<' ;
GT : '>' ;
// Arithmetic operators
ADD : '+' ;
SUB : '-' ;
MUL : '*' ;
DIV : '/' ;
// Unary operators
BANG : '!' ;
//NEGATIVE : SUB ;
// Delimeters
LPAREN : '(' ;
RPAREN : ')' ;
PAREN : '()';
DOT : '.' ;
COMMA : ',' ;
Whitespace : (' ' | '\t' | '\n' | '\r' | Comment) -> channel(HIDDEN);
Comment : ('//' ~('\r' | '\n')* | '/*' .*? '*/') -> channel(HIDDEN);
|
Fix association of +- and */
|
Fix association of +- and */
|
ANTLR
|
mit
|
rockwotj/mjc
|
3864c983a94112e1257f8d14e32f574f3f9c4336
|
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
;
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
;
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_)*
;
|
add unreserve keyword 'NAME' for mysql
|
add unreserve keyword 'NAME' for mysql
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
f21cbe7415f575d736d5434696dd9580c2f24ddc
|
src/main/antlr4/nl/eernie/jmoribus/Gherkins.g4
|
src/main/antlr4/nl/eernie/jmoribus/Gherkins.g4
|
grammar Gherkins;
story
: prologue? scenario*;
prologue
: NEWLINE? prologue_keyword (NEWLINE step)+;
scenario
: NEWLINE? scenario_keyword title (NEWLINE step)+;
title
: line;
step
: step_keyword line (NEWLINE SPACE SPACE line)*;
line
: (SPACE|TEXT)*;
feature_keyword
: 'Feature:';
prologue_keyword
: 'Prologue:';
scenario_keyword
: 'Scenario:';
step_keyword
: 'Given' | 'When' | 'Then' | 'And' | 'Revering:';
SPACE : ' ' | '\t';
NEWLINE : '\r'? '\n';
TEXT
: (UPPERCASE_LETTER | LOWERCASE_LETTER | DIGIT| SYMBOL )
;
fragment UPPERCASE_LETTER
: 'A'..'Z'
;
fragment LOWERCASE_LETTER
: 'a'..'z'
;
fragment DIGIT
: '0'..'9'
;
fragment SYMBOL
: '\u0021'..'\u0027'
| '\u002a'..'\u002f'
| '\u003a'..'\u0040'
| '\u005e'..'\u0060'
| '\u00a1'..'\u00FF'
| '\u0152'..'\u0192'
| '\u2013'..'\u2122'
| '\u2190'..'\u21FF'
| '\u2200'..'\u22FF'
| '('..')'
;
WS : [ \t\n\r]+ -> skip ;
|
grammar Gherkins;
story
: feature? prologue? scenario*;
feature
: feature_keyword title
;
prologue
: NEWLINE? prologue_keyword (NEWLINE step)+;
scenario
: NEWLINE? scenario_keyword title (NEWLINE step)+;
title
: line;
step
: step_keyword line (NEWLINE SPACE SPACE line)*;
line
: (SPACE|TEXT)*;
feature_keyword
: 'Feature:';
prologue_keyword
: 'Prologue:';
scenario_keyword
: 'Scenario:';
step_keyword
: 'Given' | 'When' | 'Then' | 'And' | 'Revering:';
SPACE : ' ' | '\t';
NEWLINE : '\r'? '\n';
TEXT
: (UPPERCASE_LETTER | LOWERCASE_LETTER | DIGIT| SYMBOL )
;
fragment UPPERCASE_LETTER
: 'A'..'Z'
;
fragment LOWERCASE_LETTER
: 'a'..'z'
;
fragment DIGIT
: '0'..'9'
;
fragment SYMBOL
: '\u0021'..'\u0027'
| '\u002a'..'\u002f'
| '\u003a'..'\u0040'
| '\u005e'..'\u0060'
| '\u00a1'..'\u00FF'
| '\u0152'..'\u0192'
| '\u2013'..'\u2122'
| '\u2190'..'\u21FF'
| '\u2200'..'\u22FF'
| '('..')'
;
COMMENT
: '/*' .*? '*/' -> skip
;
LINE_COMMENT
: '#--' ~[\r\n] -> skip
;
WS : [ \t\n\r]+ -> skip ;
|
Add the feature plus title to the grammer file
|
Add the feature plus title to the grammer file
I wasn't able to seperate the two files.
When I made the keywords a LEXER rule the parser couldn't match them anymore and when I tried to keep it a Parser rule it also gave errors.
Something about implicit literal. I combined the two again en voila.
It isn't what I hoped to do but it seems this is the good way of doing making the gramer.
|
ANTLR
|
mit
|
Eernie/JMoribus
|
ce0c3d77b800ca334712fd9632a5aa5fe232f221
|
sharding-core/src/main/antlr4/imports/BaseRule.g4
|
sharding-core/src/main/antlr4/imports/BaseRule.g4
|
grammar BaseRule;
import DataType, Keyword, Symbol;
ID:
(BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_? DOT)? (BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_?)
| [a-zA-Z_$0-9]+ DOT ASTERISK
;
schemaName
: ID
;
databaseName
: ID
;
domainName
: ID
;
tableName
: ID
;
columnName
: ID
;
sequenceName
: ID
;
tablespaceName
: ID
;
collationName
: STRING
| ID
;
indexName
: ID
;
alias
: ID
;
cteName
: ID
;
parserName
: ID
;
extensionName
: ID
;
rowName
: ID
;
opclass
: ID
;
fileGroup
: ID
;
groupName
: ID
;
constraintName
: ID
;
keyName
: ID
;
typeName
: ID
;
xmlSchemaCollection
: ID
;
columnSetName
: ID
;
directoryName
: ID
;
triggerName
: ID
;
routineName
: ID
;
roleName
: STRING | ID
;
partitionName
: ID
;
rewriteRuleName
: ID
;
ownerName
: ID
;
userName
: STRING | ID
;
serverName
: ID
;
databaseName
: ID
;
dataTypeLength
: LP_ (NUMBER (COMMA NUMBER)?)? RP_
;
primaryKey
: PRIMARY? KEY
;
matchNone
: 'Default does not match anything'
;
ids
: ID (COMMA ID)*
;
idList
: LP_ ids RP_
;
rangeClause
: NUMBER (COMMA NUMBER)* | NUMBER OFFSET NUMBER
;
schemaNames
: schemaName (COMMA schemaName)*
;
databaseNames
: databaseName (COMMA databaseName)*
;
domainNames
: domainName (COMMA domainName)*
;
tableNamesWithParen
: LP_ tableNames RP_
;
tableNames
: tableName (COMMA tableName)*
;
columnNamesWithParen
: LP_ columnNames RP_
;
columnNames
: columnName (COMMA columnName)*
;
columnList
: LP_ columnNames RP_
;
sequenceNames
: sequenceName (COMMA sequenceName)*
;
tablespaceNames
: tablespaceName (COMMA tablespaceName)*
;
indexNames
: indexName (COMMA indexName)*
;
typeNames
: typeName (COMMA typeName)*
;
rowNames
: rowName (COMMA rowName)*
;
roleNames
: roleName (COMMA roleName)*
;
userNames
: userName (COMMA userName)*
;
serverNames
: serverName (COMMA serverName)*
;
bitExprs:
bitExpr (COMMA bitExpr)*
;
exprs
: expr (COMMA expr)*
;
exprsWithParen
: LP_ exprs RP_
;
expr
: expr 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)?
;
|
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
;
databaseName
: ID
;
domainName
: ID
;
tableName
: ID
;
columnName
: ID
;
sequenceName
: ID
;
tablespaceName
: ID
;
collationName
: STRING
| ID
;
indexName
: ID
;
alias
: ID
;
cteName
: ID
;
parserName
: ID
;
extensionName
: ID
;
rowName
: ID
;
opclass
: ID
;
fileGroup
: ID
;
groupName
: ID
;
constraintName
: ID
;
keyName
: ID
;
typeName
: ID
;
xmlSchemaCollection
: ID
;
columnSetName
: ID
;
directoryName
: ID
;
triggerName
: ID
;
routineName
: ID
;
roleName
: STRING | ID
;
partitionName
: ID
;
rewriteRuleName
: ID
;
ownerName
: ID
;
userName
: STRING | ID
;
serverName
: ID
;
dataTypeLength
: LP_ (NUMBER (COMMA NUMBER)?)? RP_
;
primaryKey
: PRIMARY? KEY
;
matchNone
: 'Default does not match anything'
;
ids
: ID (COMMA ID)*
;
idList
: LP_ ids RP_
;
rangeClause
: NUMBER (COMMA NUMBER)* | NUMBER OFFSET NUMBER
;
schemaNames
: schemaName (COMMA schemaName)*
;
databaseNames
: databaseName (COMMA databaseName)*
;
domainNames
: domainName (COMMA domainName)*
;
tableNamesWithParen
: LP_ tableNames RP_
;
tableNames
: tableName (COMMA tableName)*
;
columnNamesWithParen
: LP_ columnNames RP_
;
columnNames
: columnName (COMMA columnName)*
;
columnList
: LP_ columnNames RP_
;
sequenceNames
: sequenceName (COMMA sequenceName)*
;
tablespaceNames
: tablespaceName (COMMA tablespaceName)*
;
indexNames
: indexName (COMMA indexName)*
;
typeNames
: typeName (COMMA typeName)*
;
rowNames
: rowName (COMMA rowName)*
;
roleNames
: roleName (COMMA roleName)*
;
userNames
: userName (COMMA userName)*
;
serverNames
: serverName (COMMA serverName)*
;
bitExprs:
bitExpr (COMMA bitExpr)*
;
exprs
: expr (COMMA expr)*
;
exprsWithParen
: LP_ exprs RP_
;
expr
: expr 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)?
;
|
remove databaseName
|
remove databaseName
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
|
04aa1517aa281679ace73369f8968aa5746820f8
|
java8-pt/JavaParser.g4
|
java8-pt/JavaParser.g4
|
/*
[The "BSD licence"]
Copyright (c) 2013 Terence Parr, Sam Harwell
Copyright (c) 2017 Ivan Kochurkin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
parser grammar JavaParser;
options { tokenVocab=JavaLexer; }
compilationUnit
: packageDeclaration? importDeclaration* typeDeclaration* EOF
;
packageDeclaration
: annotation* PACKAGE qualifiedName ';'
;
importDeclaration
: IMPORT STATIC? qualifiedName ('.' '*')? ';'
;
typeDeclaration
: classOrInterfaceModifier*
(classDeclaration | enumDeclaration | interfaceDeclaration | annotationTypeDeclaration)
| ';'
;
modifier
: classOrInterfaceModifier
| NATIVE
| SYNCHRONIZED
| TRANSIENT
| VOLATILE
;
classOrInterfaceModifier
: annotation
| PUBLIC
| PROTECTED
| PRIVATE
| STATIC
| ABSTRACT
| FINAL // FINAL for class only -- does not apply to interfaces
| STRICTFP
;
variableModifier
: FINAL
| annotation
;
classDeclaration
: CLASS IDENTIFIER typeParameters?
(EXTENDS typeType)?
(IMPLEMENTS typeList)?
classBody
;
typeParameters
: '<' typeParameter (',' typeParameter)* '>'
;
typeParameter
: annotation* IDENTIFIER (EXTENDS typeBound)?
;
typeBound
: typeType ('&' typeType)*
;
enumDeclaration
: ENUM IDENTIFIER (IMPLEMENTS typeList)? '{' enumConstants? ','? enumBodyDeclarations? '}'
;
enumConstants
: enumConstant (',' enumConstant)*
;
enumConstant
: annotation* IDENTIFIER arguments? classBody?
;
enumBodyDeclarations
: ';' classBodyDeclaration*
;
interfaceDeclaration
: INTERFACE IDENTIFIER typeParameters? (EXTENDS typeList)? interfaceBody
;
classBody
: '{' classBodyDeclaration* '}'
;
interfaceBody
: '{' interfaceBodyDeclaration* '}'
;
classBodyDeclaration
: ';'
| STATIC? block
| modifier* memberDeclaration
;
memberDeclaration
: methodDeclaration
| genericMethodDeclaration
| fieldDeclaration
| constructorDeclaration
| genericConstructorDeclaration
| interfaceDeclaration
| annotationTypeDeclaration
| classDeclaration
| enumDeclaration
;
/* We use rule this even for void methods which cannot have [] after parameters.
This simplifies grammar and we can consider void to be a type, which
renders the [] matching as a context-sensitive issue or a semantic check
for invalid return type after parsing.
*/
methodDeclaration
: typeTypeOrVoid IDENTIFIER formalParameters ('[' ']')*
(THROWS qualifiedNameList)?
methodBody
;
methodBody
: block
| ';'
;
typeTypeOrVoid
: typeType | VOID
;
genericMethodDeclaration
: typeParameters methodDeclaration
;
genericConstructorDeclaration
: typeParameters constructorDeclaration
;
constructorDeclaration
: IDENTIFIER formalParameters (THROWS qualifiedNameList)? constructorBody=block
;
fieldDeclaration
: typeType variableDeclarators ';'
;
interfaceBodyDeclaration
: modifier* interfaceMemberDeclaration
| ';'
;
interfaceMemberDeclaration
: constDeclaration
| interfaceMethodDeclaration
| genericInterfaceMethodDeclaration
| interfaceDeclaration
| annotationTypeDeclaration
| classDeclaration
| enumDeclaration
;
constDeclaration
: typeType constantDeclarator (',' constantDeclarator)* ';'
;
constantDeclarator
: IDENTIFIER ('[' ']')* '=' variableInitializer
;
// see matching of [] comment in methodDeclaratorRest
// methodBody from Java 8
interfaceMethodDeclaration
: interfaceMethodModifier* typeTypeOrVoid IDENTIFIER formalParameters ('[' ']')* (THROWS qualifiedNameList)? methodBody
;
// Java8
interfaceMethodModifier
: annotation
| PUBLIC
| ABSTRACT
| DEFAULT
| STATIC
| STRICTFP
;
genericInterfaceMethodDeclaration
: typeParameters interfaceMethodDeclaration
;
variableDeclarators
: variableDeclarator (',' variableDeclarator)*
;
variableDeclarator
: variableDeclaratorId ('=' variableInitializer)?
;
variableDeclaratorId
: IDENTIFIER ('[' ']')*
;
variableInitializer
: arrayInitializer
| expression
;
arrayInitializer
: '{' (variableInitializer (',' variableInitializer)* (',')? )? '}'
;
classOrInterfaceType
: IDENTIFIER typeArguments? ('.' IDENTIFIER typeArguments?)*
;
typeArgument
: typeType
| '?' ((EXTENDS | SUPER) typeType)?
;
qualifiedNameList
: qualifiedName (',' qualifiedName)*
;
formalParameters
: '(' formalParameterList? ')'
;
formalParameterList
: formalParameter (',' formalParameter)* (',' lastFormalParameter)?
| lastFormalParameter
;
formalParameter
: variableModifier* typeType variableDeclaratorId
;
lastFormalParameter
: variableModifier* typeType '...' variableDeclaratorId
;
qualifiedName
: IDENTIFIER ('.' IDENTIFIER)*
;
literal
: integerLiteral
| FLOAT_LITERAL
| CHAR_LITERAL
| STRING_LITERAL
| BOOL_LITERAL
| NULL_LITERAL
;
integerLiteral
: DECIMAL_LITERAL
| HEX_LITERAL
| OCT_LITERAL
| BINARY_LITERAL
;
// ANNOTATIONS
annotation
: '@' qualifiedName ('(' ( elementValuePairs | elementValue )? ')')?
;
elementValuePairs
: elementValuePair (',' elementValuePair)*
;
elementValuePair
: IDENTIFIER '=' elementValue
;
elementValue
: expression
| annotation
| elementValueArrayInitializer
;
elementValueArrayInitializer
: '{' (elementValue (',' elementValue)*)? (',')? '}'
;
annotationTypeDeclaration
: '@' INTERFACE IDENTIFIER annotationTypeBody
;
annotationTypeBody
: '{' (annotationTypeElementDeclaration)* '}'
;
annotationTypeElementDeclaration
: modifier* annotationTypeElementRest
| ';' // this is not allowed by the grammar, but apparently allowed by the actual compiler
;
annotationTypeElementRest
: typeType annotationMethodOrConstantRest ';'
| classDeclaration ';'?
| interfaceDeclaration ';'?
| enumDeclaration ';'?
| annotationTypeDeclaration ';'?
;
annotationMethodOrConstantRest
: annotationMethodRest
| annotationConstantRest
;
annotationMethodRest
: IDENTIFIER '(' ')' defaultValue?
;
annotationConstantRest
: variableDeclarators
;
defaultValue
: DEFAULT elementValue
;
// STATEMENTS / BLOCKS
block
: '{' blockStatement* '}'
;
blockStatement
: localVariableDeclaration ';'
| statement
| localTypeDeclaration
;
localVariableDeclaration
: variableModifier* typeType variableDeclarators
;
localTypeDeclaration
: classOrInterfaceModifier*
(classDeclaration | interfaceDeclaration)
| ';'
;
statement
: blockLabel=block
| ASSERT expression (':' expression)? ';'
| IF parExpression statement (ELSE statement)?
| FOR '(' forControl ')' statement
| WHILE parExpression statement
| DO statement WHILE parExpression ';'
| TRY block (catchClause+ finallyBlock? | finallyBlock)
| TRY resourceSpecification block catchClause* finallyBlock?
| SWITCH parExpression '{' switchBlockStatementGroup* switchLabel* '}'
| SYNCHRONIZED parExpression block
| RETURN expression? ';'
| THROW expression ';'
| BREAK IDENTIFIER? ';'
| CONTINUE IDENTIFIER? ';'
| SEMI
| statementExpression=expression ';'
| identifierLabel=IDENTIFIER ':' statement
;
catchClause
: CATCH '(' variableModifier* catchType IDENTIFIER ')' block
;
catchType
: qualifiedName ('|' qualifiedName)*
;
finallyBlock
: FINALLY block
;
resourceSpecification
: '(' resources ';'? ')'
;
resources
: resource (';' resource)*
;
resource
: variableModifier* classOrInterfaceType variableDeclaratorId '=' expression
;
/** Matches cases then statements, both of which are mandatory.
* To handle empty cases at the end, we add switchLabel* to statement.
*/
switchBlockStatementGroup
: switchLabel+ blockStatement+
;
switchLabel
: CASE (constantExpression=expression | enumConstantName=IDENTIFIER) ':'
| DEFAULT ':'
;
forControl
: enhancedForControl
| forInit? ';' expression? ';' forUpdate=expressionList?
;
forInit
: localVariableDeclaration
| expressionList
;
enhancedForControl
: variableModifier* typeType variableDeclaratorId ':' expression
;
// EXPRESSIONS
parExpression
: '(' expression ')'
;
expressionList
: expression (',' expression)*
;
expression
: primary
| expression bop='.'
(IDENTIFIER
| THIS
| NEW nonWildcardTypeArguments? innerCreator
| SUPER superSuffix
| explicitGenericInvocation
)
| expression '[' expression ']'
| expression '(' expressionList? ')'
| NEW creator
| '(' typeType ')' expression
| expression postfix=('++' | '--')
| prefix=('+'|'-'|'++'|'--') expression
| prefix=('~'|'!') expression
| expression bop=('*'|'/'|'%') expression
| expression bop=('+'|'-') expression
| expression ('<' '<' | '>' '>' '>' | '>' '>') expression
| expression bop=('<=' | '>=' | '>' | '<') expression
| expression bop=INSTANCEOF typeType
| expression bop=('==' | '!=') expression
| expression bop='&' expression
| expression bop='^' expression
| expression bop='|' expression
| expression bop='&&' expression
| expression bop='||' expression
| expression bop='?' expression ':' expression
| <assoc=right> expression
bop=('=' | '+=' | '-=' | '*=' | '/=' | '&=' | '|=' | '^=' | '>>=' | '>>>=' | '<<=' | '%=')
expression
| lambdaExpression // Java8
;
// Java8
lambdaExpression
: lambdaParameters '->' lambdaBody
;
// Java8
lambdaParameters
: IDENTIFIER
| '(' formalParameterList? ')'
| '(' IDENTIFIER (',' IDENTIFIER)* ')'
;
// Java8
lambdaBody
: expression
| block
;
primary
: '(' expression ')'
| THIS
| SUPER
| literal
| IDENTIFIER
| typeTypeOrVoid '.' CLASS
| nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments)
| methodReference // Java 8
;
methodReference
: (typeType | qualifiedName ('.' (SUPER | THIS | methodReferenceMethodCall))?
| (SUPER | THIS | methodReferenceMethodCall))
'::' typeArguments? IDENTIFIER
| classType '::' typeArguments? NEW
| typeType '::' NEW
;
methodReferenceMethodCall
: IDENTIFIER LPAREN expressionList? RPAREN (DOT IDENTIFIER LPAREN expressionList? RPAREN)*
;
classType
: (classOrInterfaceType '.')? annotation* IDENTIFIER typeArguments?
;
creator
: nonWildcardTypeArguments createdName classCreatorRest
| createdName (arrayCreatorRest | classCreatorRest)
;
createdName
: IDENTIFIER typeArgumentsOrDiamond? ('.' IDENTIFIER typeArgumentsOrDiamond?)*
| primitiveType
;
innerCreator
: IDENTIFIER nonWildcardTypeArgumentsOrDiamond? classCreatorRest
;
arrayCreatorRest
: '[' (']' ('[' ']')* arrayInitializer | expression ']' ('[' expression ']')* ('[' ']')*)
;
classCreatorRest
: arguments classBody?
;
explicitGenericInvocation
: nonWildcardTypeArguments explicitGenericInvocationSuffix
;
typeArgumentsOrDiamond
: '<' '>'
| typeArguments
;
nonWildcardTypeArgumentsOrDiamond
: '<' '>'
| nonWildcardTypeArguments
;
nonWildcardTypeArguments
: '<' typeList '>'
;
typeList
: typeType (',' typeType)*
;
typeType
: (classOrInterfaceType | primitiveType) ('[' ']')*
;
primitiveType
: BOOLEAN
| CHAR
| BYTE
| SHORT
| INT
| LONG
| FLOAT
| DOUBLE
;
typeArguments
: '<' typeArgument (',' typeArgument)* '>'
;
superSuffix
: arguments
| '.' IDENTIFIER arguments?
;
explicitGenericInvocationSuffix
: SUPER superSuffix
| IDENTIFIER arguments
;
arguments
: '(' expressionList? ')'
;
|
/*
[The "BSD licence"]
Copyright (c) 2013 Terence Parr, Sam Harwell
Copyright (c) 2017 Ivan Kochurkin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
parser grammar JavaParser;
options { tokenVocab=JavaLexer; }
compilationUnit
: packageDeclaration? importDeclaration* typeDeclaration* EOF
;
packageDeclaration
: annotation* PACKAGE qualifiedName ';'
;
importDeclaration
: IMPORT STATIC? qualifiedName ('.' '*')? ';'
;
typeDeclaration
: classOrInterfaceModifier*
(classDeclaration | enumDeclaration | interfaceDeclaration | annotationTypeDeclaration)
| ';'
;
modifier
: classOrInterfaceModifier
| NATIVE
| SYNCHRONIZED
| TRANSIENT
| VOLATILE
;
classOrInterfaceModifier
: annotation
| PUBLIC
| PROTECTED
| PRIVATE
| STATIC
| ABSTRACT
| FINAL // FINAL for class only -- does not apply to interfaces
| STRICTFP
;
variableModifier
: FINAL
| annotation
;
classDeclaration
: CLASS IDENTIFIER typeParameters?
(EXTENDS typeType)?
(IMPLEMENTS typeList)?
classBody
;
typeParameters
: '<' typeParameter (',' typeParameter)* '>'
;
typeParameter
: annotation* IDENTIFIER (EXTENDS typeBound)?
;
typeBound
: typeType ('&' typeType)*
;
enumDeclaration
: ENUM IDENTIFIER (IMPLEMENTS typeList)? '{' enumConstants? ','? enumBodyDeclarations? '}'
;
enumConstants
: enumConstant (',' enumConstant)*
;
enumConstant
: annotation* IDENTIFIER arguments? classBody?
;
enumBodyDeclarations
: ';' classBodyDeclaration*
;
interfaceDeclaration
: INTERFACE IDENTIFIER typeParameters? (EXTENDS typeList)? interfaceBody
;
classBody
: '{' classBodyDeclaration* '}'
;
interfaceBody
: '{' interfaceBodyDeclaration* '}'
;
classBodyDeclaration
: ';'
| STATIC? block
| modifier* memberDeclaration
;
memberDeclaration
: methodDeclaration
| genericMethodDeclaration
| fieldDeclaration
| constructorDeclaration
| genericConstructorDeclaration
| interfaceDeclaration
| annotationTypeDeclaration
| classDeclaration
| enumDeclaration
;
/* We use rule this even for void methods which cannot have [] after parameters.
This simplifies grammar and we can consider void to be a type, which
renders the [] matching as a context-sensitive issue or a semantic check
for invalid return type after parsing.
*/
methodDeclaration
: typeTypeOrVoid IDENTIFIER formalParameters ('[' ']')*
(THROWS qualifiedNameList)?
methodBody
;
methodBody
: block
| ';'
;
typeTypeOrVoid
: typeType | VOID
;
genericMethodDeclaration
: typeParameters methodDeclaration
;
genericConstructorDeclaration
: typeParameters constructorDeclaration
;
constructorDeclaration
: IDENTIFIER formalParameters (THROWS qualifiedNameList)? constructorBody=block
;
fieldDeclaration
: typeType variableDeclarators ';'
;
interfaceBodyDeclaration
: modifier* interfaceMemberDeclaration
| ';'
;
interfaceMemberDeclaration
: constDeclaration
| interfaceMethodDeclaration
| genericInterfaceMethodDeclaration
| interfaceDeclaration
| annotationTypeDeclaration
| classDeclaration
| enumDeclaration
;
constDeclaration
: typeType constantDeclarator (',' constantDeclarator)* ';'
;
constantDeclarator
: IDENTIFIER ('[' ']')* '=' variableInitializer
;
// see matching of [] comment in methodDeclaratorRest
// methodBody from Java 8
interfaceMethodDeclaration
: interfaceMethodModifier* typeTypeOrVoid IDENTIFIER formalParameters ('[' ']')* (THROWS qualifiedNameList)? methodBody
;
// Java8
interfaceMethodModifier
: annotation
| PUBLIC
| ABSTRACT
| DEFAULT
| STATIC
| STRICTFP
;
genericInterfaceMethodDeclaration
: typeParameters interfaceMethodDeclaration
;
variableDeclarators
: variableDeclarator (',' variableDeclarator)*
;
variableDeclarator
: variableDeclaratorId ('=' variableInitializer)?
;
variableDeclaratorId
: IDENTIFIER ('[' ']')*
;
variableInitializer
: arrayInitializer
| expression
;
arrayInitializer
: '{' (variableInitializer (',' variableInitializer)* (',')? )? '}'
;
classOrInterfaceType
: IDENTIFIER typeArguments? ('.' IDENTIFIER typeArguments?)*
;
typeArgument
: typeType
| '?' ((EXTENDS | SUPER) typeType)?
;
qualifiedNameList
: qualifiedName (',' qualifiedName)*
;
formalParameters
: '(' formalParameterList? ')'
;
formalParameterList
: formalParameter (',' formalParameter)* (',' lastFormalParameter)?
| lastFormalParameter
;
formalParameter
: variableModifier* typeType variableDeclaratorId
;
lastFormalParameter
: variableModifier* typeType '...' variableDeclaratorId
;
qualifiedName
: IDENTIFIER ('.' IDENTIFIER)*
;
literal
: integerLiteral
| FLOAT_LITERAL
| CHAR_LITERAL
| STRING_LITERAL
| BOOL_LITERAL
| NULL_LITERAL
;
integerLiteral
: DECIMAL_LITERAL
| HEX_LITERAL
| OCT_LITERAL
| BINARY_LITERAL
;
// ANNOTATIONS
annotation
: '@' qualifiedName ('(' ( elementValuePairs | elementValue )? ')')?
;
elementValuePairs
: elementValuePair (',' elementValuePair)*
;
elementValuePair
: IDENTIFIER '=' elementValue
;
elementValue
: expression
| annotation
| elementValueArrayInitializer
;
elementValueArrayInitializer
: '{' (elementValue (',' elementValue)*)? (',')? '}'
;
annotationTypeDeclaration
: '@' INTERFACE IDENTIFIER annotationTypeBody
;
annotationTypeBody
: '{' (annotationTypeElementDeclaration)* '}'
;
annotationTypeElementDeclaration
: modifier* annotationTypeElementRest
| ';' // this is not allowed by the grammar, but apparently allowed by the actual compiler
;
annotationTypeElementRest
: typeType annotationMethodOrConstantRest ';'
| classDeclaration ';'?
| interfaceDeclaration ';'?
| enumDeclaration ';'?
| annotationTypeDeclaration ';'?
;
annotationMethodOrConstantRest
: annotationMethodRest
| annotationConstantRest
;
annotationMethodRest
: IDENTIFIER '(' ')' defaultValue?
;
annotationConstantRest
: variableDeclarators
;
defaultValue
: DEFAULT elementValue
;
// STATEMENTS / BLOCKS
block
: '{' blockStatement* '}'
;
blockStatement
: localVariableDeclaration ';'
| statement
| localTypeDeclaration
;
localVariableDeclaration
: variableModifier* typeType variableDeclarators
;
localTypeDeclaration
: classOrInterfaceModifier*
(classDeclaration | interfaceDeclaration)
| ';'
;
statement
: blockLabel=block
| ASSERT expression (':' expression)? ';'
| IF parExpression statement (ELSE statement)?
| FOR '(' forControl ')' statement
| WHILE parExpression statement
| DO statement WHILE parExpression ';'
| TRY block (catchClause+ finallyBlock? | finallyBlock)
| TRY resourceSpecification block catchClause* finallyBlock?
| SWITCH parExpression '{' switchBlockStatementGroup* switchLabel* '}'
| SYNCHRONIZED parExpression block
| RETURN expression? ';'
| THROW expression ';'
| BREAK IDENTIFIER? ';'
| CONTINUE IDENTIFIER? ';'
| SEMI
| statementExpression=expression ';'
| identifierLabel=IDENTIFIER ':' statement
;
catchClause
: CATCH '(' variableModifier* catchType IDENTIFIER ')' block
;
catchType
: qualifiedName ('|' qualifiedName)*
;
finallyBlock
: FINALLY block
;
resourceSpecification
: '(' resources ';'? ')'
;
resources
: resource (';' resource)*
;
resource
: variableModifier* classOrInterfaceType variableDeclaratorId '=' expression
;
/** Matches cases then statements, both of which are mandatory.
* To handle empty cases at the end, we add switchLabel* to statement.
*/
switchBlockStatementGroup
: switchLabel+ blockStatement+
;
switchLabel
: CASE (constantExpression=expression | enumConstantName=IDENTIFIER) ':'
| DEFAULT ':'
;
forControl
: enhancedForControl
| forInit? ';' expression? ';' forUpdate=expressionList?
;
forInit
: localVariableDeclaration
| expressionList
;
enhancedForControl
: variableModifier* typeType variableDeclaratorId ':' expression
;
// EXPRESSIONS
parExpression
: '(' expression ')'
;
expressionList
: expression (',' expression)*
;
expression
: primary
| expression bop='.'
(IDENTIFIER
| THIS
| NEW nonWildcardTypeArguments? innerCreator
| SUPER superSuffix
| explicitGenericInvocation
)
| expression '[' expression ']'
| expression '(' expressionList? ')'
| NEW creator
| '(' typeType ')' expression
| expression postfix=('++' | '--')
| prefix=('+'|'-'|'++'|'--') expression
| prefix=('~'|'!') expression
| expression bop=('*'|'/'|'%') expression
| expression bop=('+'|'-') expression
| expression ('<' '<' | '>' '>' '>' | '>' '>') expression
| expression bop=('<=' | '>=' | '>' | '<') expression
| expression bop=INSTANCEOF typeType
| expression bop=('==' | '!=') expression
| expression bop='&' expression
| expression bop='^' expression
| expression bop='|' expression
| expression bop='&&' expression
| expression bop='||' expression
| expression bop='?' expression ':' expression
| <assoc=right> expression
bop=('=' | '+=' | '-=' | '*=' | '/=' | '&=' | '|=' | '^=' | '>>=' | '>>>=' | '<<=' | '%=')
expression
| lambdaExpression // Java8
;
// Java8
lambdaExpression
: lambdaParameters '->' lambdaBody
;
// Java8
lambdaParameters
: IDENTIFIER
| '(' formalParameterList? ')'
| '(' IDENTIFIER (',' IDENTIFIER)* ')'
;
// Java8
lambdaBody
: expression
| block
;
primary
: '(' expression ')'
| THIS
| SUPER
| literal
| IDENTIFIER
| typeTypeOrVoid '.' CLASS
| nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments)
| methodReference // Java 8
;
methodReference
: (typeType | qualifiedName ('.' accessorOrMethodRefCall)? | accessorOrMethodRefCall) '::' typeArguments? IDENTIFIER
| classType '::' typeArguments? NEW
| typeType '::' NEW
;
accessorOrMethodRefCall
: SUPER
| THIS
| IDENTIFIER LPAREN expressionList? RPAREN (DOT IDENTIFIER LPAREN expressionList? RPAREN)*
;
classType
: (classOrInterfaceType '.')? annotation* IDENTIFIER typeArguments?
;
creator
: nonWildcardTypeArguments createdName classCreatorRest
| createdName (arrayCreatorRest | classCreatorRest)
;
createdName
: IDENTIFIER typeArgumentsOrDiamond? ('.' IDENTIFIER typeArgumentsOrDiamond?)*
| primitiveType
;
innerCreator
: IDENTIFIER nonWildcardTypeArgumentsOrDiamond? classCreatorRest
;
arrayCreatorRest
: '[' (']' ('[' ']')* arrayInitializer | expression ']' ('[' expression ']')* ('[' ']')*)
;
classCreatorRest
: arguments classBody?
;
explicitGenericInvocation
: nonWildcardTypeArguments explicitGenericInvocationSuffix
;
typeArgumentsOrDiamond
: '<' '>'
| typeArguments
;
nonWildcardTypeArgumentsOrDiamond
: '<' '>'
| nonWildcardTypeArguments
;
nonWildcardTypeArguments
: '<' typeList '>'
;
typeList
: typeType (',' typeType)*
;
typeType
: (classOrInterfaceType | primitiveType) ('[' ']')*
;
primitiveType
: BOOLEAN
| CHAR
| BYTE
| SHORT
| INT
| LONG
| FLOAT
| DOUBLE
;
typeArguments
: '<' typeArgument (',' typeArgument)* '>'
;
superSuffix
: arguments
| '.' IDENTIFIER arguments?
;
explicitGenericInvocationSuffix
: SUPER superSuffix
| IDENTIFIER arguments
;
arguments
: '(' expressionList? ')'
;
|
Rewrite Java8PT methodReference rule (courtesy @KvanTTT)
|
Rewrite Java8PT methodReference rule (courtesy @KvanTTT)
|
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
|
28e78176d5f492f1c1d3b5d320b37fed4c188ae7
|
sharding-core/src/main/antlr4/io/shardingsphere/core/parsing/antlr/autogen/OracleStatement.g4
|
sharding-core/src/main/antlr4/io/shardingsphere/core/parsing/antlr/autogen/OracleStatement.g4
|
grammar OracleStatement;
import OracleKeyword, Keyword, OracleBase, OracleCreateIndex, OracleAlterIndex
, OracleDropIndex, OracleCreateTable, OracleAlterTable, OracleDropTable, OracleTruncateTable
, OracleTCLStatement, OracleDCLStatement
;
execute
: createIndex
| alterIndex
| dropIndex
| createTable
| alterTable
| dropTable
| truncateTable
| setTransaction
| commit
| rollback
| savepoint
| grant
| revoke
| createUser
| alterUser
| dropUser
| createRole
;
|
grammar OracleStatement;
import OracleKeyword, Keyword, OracleBase, OracleCreateIndex, OracleAlterIndex
, OracleDropIndex, OracleCreateTable, OracleAlterTable, OracleDropTable, OracleTruncateTable
, OracleTCLStatement, OracleDCLStatement
;
execute
: createIndex
| alterIndex
| dropIndex
| createTable
| alterTable
| dropTable
| truncateTable
| setTransaction
| commit
| rollback
| savepoint
| grant
| revoke
| createUser
| alterUser
| dropUser
| createRole
| alterRole
;
|
add alter role statement
|
add alter role statement
|
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
|
c2edcc4688a7394ed486853a3ec6690b9c3099e8
|
smalltalk/smalltalk.g4
|
smalltalk/smalltalk.g4
|
/*
Converted to ANTLR 4 by James Ladd (Redline Smalltalk Project http://redline.st).
Adapted from the Amber Smalltalk grammar perser.pegjs
2013/11/27 James Ladd ([email protected])
*/
grammar smalltalk;
script : sequence EOF;
sequence : ws temps? ws statements? ws;
ws : (SEPARATOR | COMMENT)*;
temps : PIPE (ws IDENTIFIER)* ws PIPE;
statements : answer
| expressions ws PERIOD ws answer
| expressions PERIOD?;
answer : CARROT ws expression ws PERIOD?;
expression : assignment | cascade | keywordSend | binarySend | primitive;
expressions : expression expressionList*;
expressionList : ws PERIOD ws expression;
cascade : ws (keywordSend | binarySend) (ws SEMI_COLON ws message ws)+;
message : binaryMessage | unaryMessage | keywordMessage;
assignment : variable ws ASSIGNMENT ws expression;
variable : IDENTIFIER;
binarySend : unarySend binaryTail?;
unarySend : operand ws unaryTail?;
keywordSend : binarySend keywordMessage;
keywordMessage : ws (keywordPair ws)+;
keywordPair : KEYWORD ws binarySend ws;
operand : literal | reference | subexpression;
subexpression : OPEN_PAREN ws expression ws CLOSE_PAREN;
literal : runtimeLiteral | parsetimeLiteral;
runtimeLiteral : dynamicDictionary | dynamicArray | block;
block : BLOCK_START blockParamList? sequence? ws BLOCK_END;
blockParamList : (ws BLOCK_PARAM)+ ws PIPE?;
dynamicDictionary : DYNDICT_START ws expressions? ws DYNARR_END;
dynamicArray : DYNARR_START ws expressions? ws DYNARR_END;
parsetimeLiteral : pseudoVariable | number | charConstant | literalArray | string | symbol;
number : numberExp | hex | stFloat | stInteger;
numberExp : (stFloat | stInteger) EXP stInteger;
charConstant : CHARACTER_CONSTANT;
hex : MINUS? HEX HEXDIGIT+;
stInteger : MINUS? DIGITS;
stFloat : MINUS? DIGITS PERIOD DIGITS;
pseudoVariable : RESERVED_WORD;
string : STRING;
symbol : HASH bareSymbol;
primitive : LT ws KEYWORD ws DIGITS ws GT;
bareSymbol : (IDENTIFIER | BINARY_SELECTOR) | string;
literalArray : LITARR_START literalArrayRest;
literalArrayRest : ws ((parsetimeLiteral | bareLiteralArray | bareSymbol) ws)* CLOSE_PAREN;
bareLiteralArray : OPEN_PAREN literalArrayRest;
parseTimeLiteral : pseudoVariable | number | literalArray | string | symbol;
unaryTail : unaryMessage ws unaryTail? ws;
unaryMessage : ws unarySelector ~COLON;
unarySelector : IDENTIFIER;
reference : variable;
binaryTail : binaryMessage binaryTail?;
binaryMessage : ws BINARY_SELECTOR ws (unarySend | operand);
PIPE : '|';
PERIOD : '.';
CARROT : '^';
COLON : ':';
SEMI_COLON : ';';
ASSIGNMENT : ':=';
MINUS : '-';
HASH : '#';
DOLLAR : '$';
EXP : 'e';
HEX : '16r';
LITARR_START : '#(';
CLOSE_PAREN : ')';
OPEN_PAREN : '(';
DYNDICT_START : '#{';
DYNARR_END : '}';
DYNARR_START : '{';
BLOCK_START : '[';
BLOCK_END : ']';
LT : '<';
GT : '>';
RESERVED_WORD : 'self' | 'nil' | 'true' | 'false' | 'super';
DIGIT : '0'..'9';
DIGITS : ('0'..'9')+;
HEXDIGIT : 'a'..'z' | 'A'..'Z' | DIGIT;
BINARY_SELECTOR : ('-' | '\\' | '+' | '*' | '/' | '=' | '>' | '<' | ',' | '@' | '%' | '~' | '|' | '&' | '?')+;
IDENTIFIER : ('a'..'z' | 'A'..'Z') ('a'..'z' | 'A'..'Z' | '0'..'9' | '_')*;
KEYWORD : IDENTIFIER COLON;
BLOCK_PARAM : COLON IDENTIFIER;
CHARACTER_CONSTANT : DOLLAR (HEXDIGIT | DOLLAR);
SEPARATOR : (' ' | '\t' | '\r' | '\n' | '\u00A0' | '\uFEFF' | '\u2028' | '\u2029')+;
STRING : '\'' (.)*? '\'';
COMMENT : '"' (.)*? '"';
|
/*
Converted to ANTLR 4 by James Ladd (Redline Smalltalk Project http://redline.st).
Adapted from the Amber Smalltalk grammar perser.pegjs
2013/11/27 James Ladd ([email protected])
*/
grammar Smalltalk;
script : sequence EOF;
sequence : ws temps? ws statements? ws;
ws : (SEPARATOR | COMMENT)*;
temps : PIPE (ws IDENTIFIER)* ws PIPE;
statements : answer
| expressions ws PERIOD ws answer
| expressions PERIOD?;
answer : CARROT ws expression ws PERIOD?;
expression : assignment | cascade | keywordSend | binarySend | primitive;
expressions : expression expressionList*;
expressionList : ws PERIOD ws expression;
cascade : ws (keywordSend | binarySend) (ws SEMI_COLON ws message ws)+;
message : binaryMessage | unaryMessage | keywordMessage;
assignment : variable ws ASSIGNMENT ws expression;
variable : IDENTIFIER;
binarySend : unarySend binaryTail?;
unarySend : operand ws unaryTail?;
keywordSend : binarySend keywordMessage;
keywordMessage : ws (keywordPair ws)+;
keywordPair : KEYWORD ws binarySend ws;
operand : literal | reference | subexpression;
subexpression : OPEN_PAREN ws expression ws CLOSE_PAREN;
literal : runtimeLiteral | parsetimeLiteral;
runtimeLiteral : dynamicDictionary | dynamicArray | block;
block : BLOCK_START blockParamList? sequence? ws BLOCK_END;
blockParamList : (ws BLOCK_PARAM)+ ws PIPE?;
dynamicDictionary : DYNDICT_START ws expressions? ws DYNARR_END;
dynamicArray : DYNARR_START ws expressions? ws DYNARR_END;
parsetimeLiteral : pseudoVariable | number | charConstant | literalArray | string | symbol;
number : numberExp | hex | stFloat | stInteger;
numberExp : (stFloat | stInteger) EXP stInteger;
charConstant : CHARACTER_CONSTANT;
hex : MINUS? HEX HEXDIGIT+;
stInteger : MINUS? DIGITS;
stFloat : MINUS? DIGITS PERIOD DIGITS;
pseudoVariable : RESERVED_WORD;
string : STRING;
symbol : HASH bareSymbol;
primitive : LT ws KEYWORD ws DIGITS ws GT;
bareSymbol : (IDENTIFIER | BINARY_SELECTOR) | string;
literalArray : LITARR_START literalArrayRest;
literalArrayRest : ws ((parsetimeLiteral | bareLiteralArray | bareSymbol) ws)* CLOSE_PAREN;
bareLiteralArray : OPEN_PAREN literalArrayRest;
parseTimeLiteral : pseudoVariable | number | literalArray | string | symbol;
unaryTail : unaryMessage ws unaryTail? ws;
unaryMessage : ws unarySelector ~COLON;
unarySelector : IDENTIFIER;
reference : variable;
binaryTail : binaryMessage binaryTail?;
binaryMessage : ws BINARY_SELECTOR ws (unarySend | operand);
PIPE : '|';
PERIOD : '.';
CARROT : '^';
COLON : ':';
SEMI_COLON : ';';
ASSIGNMENT : ':=';
MINUS : '-';
HASH : '#';
DOLLAR : '$';
EXP : 'e';
HEX : '16r';
LITARR_START : '#(';
CLOSE_PAREN : ')';
OPEN_PAREN : '(';
DYNDICT_START : '#{';
DYNARR_END : '}';
DYNARR_START : '{';
BLOCK_START : '[';
BLOCK_END : ']';
LT : '<';
GT : '>';
RESERVED_WORD : 'self' | 'nil' | 'true' | 'false' | 'super';
DIGIT : '0'..'9';
DIGITS : ('0'..'9')+;
HEXDIGIT : 'a'..'z' | 'A'..'Z' | DIGIT;
BINARY_SELECTOR : ('-' | '\\' | '+' | '*' | '/' | '=' | '>' | '<' | ',' | '@' | '%' | '~' | '|' | '&' | '?')+;
IDENTIFIER : ('a'..'z' | 'A'..'Z') ('a'..'z' | 'A'..'Z' | '0'..'9' | '_')*;
KEYWORD : IDENTIFIER COLON;
BLOCK_PARAM : COLON IDENTIFIER;
CHARACTER_CONSTANT : DOLLAR (HEXDIGIT | DOLLAR);
SEPARATOR : (' ' | '\t' | '\r' | '\n' | '\u00A0' | '\uFEFF' | '\u2028' | '\u2029')+;
STRING : '\'' (.)*? '\'';
COMMENT : '"' (.)*? '"';
|
rename to cap S
|
rename to cap S
|
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
|
af88ef57597ab7e3de02b09ab8400489124cc02a
|
antlr/KalangLexer.g4
|
antlr/KalangLexer.g4
|
lexer grammar KalangLexer;
@lexer::members {
public static final int WHITESPACE = 3;
public static final int COMMENTS = 4;
private boolean inString = false;
}
// LEXER
// §3.9 Keywords
DOUBLE_COLON : '::' ;
AS:'as';
CONSTRUCTOR:'constructor';
VAR:'var';
VAL: 'val';
FOREACH:'foreach';
ARROW:'->';
START_DOT: '*.';
OVERRIDE : 'override' ;
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';
// §3.10.1 Integer Literals
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'
| NonZeroDigit (Digits? | Underscores Digits)
;
fragment
Digits
: Digit (DigitOrUnderscore* Digit)?
;
fragment
Digit
: '0'
| NonZeroDigit
;
fragment
NonZeroDigit
: [1-9]
;
fragment
DigitOrUnderscore
: Digit
| '_'
;
fragment
Underscores
: '_'+
;
fragment
HexNumeral
: '0' [xX] HexDigits
;
fragment
HexDigits
: HexDigit (HexDigitOrUnderscore* HexDigit)?
;
fragment
HexDigit
: [0-9a-fA-F]
;
fragment
HexDigitOrUnderscore
: HexDigit
| '_'
;
fragment
OctalNumeral
: '0' Underscores? OctalDigits
;
fragment
OctalDigits
: OctalDigit (OctalDigitOrUnderscore* OctalDigit)?
;
fragment
OctalDigit
: [0-7]
;
fragment
OctalDigitOrUnderscore
: OctalDigit
| '_'
;
fragment
BinaryNumeral
: '0' [bB] BinaryDigits
;
fragment
BinaryDigits
: BinaryDigit (BinaryDigitOrUnderscore* BinaryDigit)?
;
fragment
BinaryDigit
: [01]
;
fragment
BinaryDigitOrUnderscore
: BinaryDigit
| '_'
;
// §3.10.2 Floating-Point Literals
FloatingPointLiteral
: DecimalFloatingPointLiteral
| HexadecimalFloatingPointLiteral
;
fragment
DecimalFloatingPointLiteral
: Digits '.' Digits? ExponentPart? FloatTypeSuffix?
| '.' Digits ExponentPart? FloatTypeSuffix?
| Digits ExponentPart FloatTypeSuffix?
| Digits FloatTypeSuffix
;
fragment
ExponentPart
: ExponentIndicator SignedInteger
;
fragment
ExponentIndicator
: [eE]
;
fragment
SignedInteger
: Sign? Digits
;
fragment
Sign
: [+-]
;
fragment
FloatTypeSuffix
: [fFdD]
;
fragment
HexadecimalFloatingPointLiteral
: HexSignificand BinaryExponent FloatTypeSuffix?
;
fragment
HexSignificand
: HexNumeral '.'?
| '0' [xX] HexDigits? '.' HexDigits
;
fragment
BinaryExponent
: BinaryExponentIndicator SignedInteger
;
fragment
BinaryExponentIndicator
: [pP]
;
// §3.10.3 Boolean Literals
BooleanLiteral
: 'true'
| 'false'
;
// §3.10.4 Character Literals
CharacterLiteral
: '\'' SingleCharacter '\''
| '\'' EscapeSequence '\''
;
fragment
SingleCharacter
: ~['\\]
;
// §3.10.5 String Literals
StringLiteral
: '"' StringCharacters? '"'
;
MultiLineStringLiteral
: '\'\'\'' MultiLineStringCharacters? '\'\'\''
;
fragment
StringCharacters
: StringCharacter+
;
fragment
MultiLineStringCharacters
: MultiLineStringCharacter+
;
fragment
StringCharacter
: ~["\\\$\{]
| '$' ~[\{]
| EscapeSequence
;
fragment
MultiLineStringCharacter
: ~[\'\\]
| '\'' ~[\']
| '\'\'' ~[\']
| EscapeSequence
;
// §3.10.6 Escape Sequences for Character and String Literals
fragment
EscapeSequence
: '\\' [btnfr"'\\]
| OctalEscape
| UnicodeEscape
;
fragment
OctalEscape
: '\\' OctalDigit
| '\\' OctalDigit OctalDigit
| '\\' ZeroToThree OctalDigit OctalDigit
;
fragment
UnicodeEscape
: '\\' 'u' HexDigit HexDigit HexDigit HexDigit
;
fragment
ZeroToThree
: [0-3]
;
// §3.10.7 The Null Literal
NullLiteral
: 'null'
;
// §3.11 Separators
LPAREN : '(';
RPAREN : ')';
LBRACE : '{';
RBRACE : '}'
{
if(inString) pushMode(STRING);
}
;
LBRACK : '[';
RBRACK : ']';
SEMI : ';';
COMMA : ',';
DOT : '.';
// §3.12 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 : '>>>=';
//Inline elements
InterpolationPreffixString
: '"' StringCharacters? '${'
{
inString = true;
}
;
// §3.8 Identifiers (must appear after all keywords in the grammar)
Identifier
: JavaLetter JavaLetterOrDigit*
;
fragment
JavaLetter
: [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)))}?
;
//
// Additional symbols not defined in the lexical specification
//
AT : '@';
ELLIPSIS : '...';
COMPILE_OPTION_LINE : '#' ~[\r\n]+;
//
// Whitespace and comments
//
WS : [ \t\r\n\u000C]+ -> channel(WHITESPACE)
;
COMMENT
: '/*' .*? '*/' -> channel(COMMENTS)
;
LINE_COMMENT
: '//' ~[\r\n]* -> channel(COMMENTS)
;
PACKAGE_DELIMITER : '\\';
mode STRING;
INTERPOLATION_INTERUPT
: '${' -> popMode
;
INTERPOLATION_END
: '"'
{
popMode();
inString = false;
}
;
INTERPOLATION_STRING
: (~[\$\{\"] ) +
| '$' ~[\{]
;
|
lexer grammar KalangLexer;
@lexer::members {
public static final int WHITESPACE = 3;
public static final int COMMENTS = 4;
private boolean inString = false;
}
// LEXER
// §3.9 Keywords
DOUBLE_COLON : '::' ;
AS:'as';
CONSTRUCTOR:'constructor';
VAR:'var';
VAL: 'val';
FOREACH:'foreach';
ARROW:'->';
START_DOT: '*.';
OVERRIDE : 'override' ;
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';
// §3.10.1 Integer Literals
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'
| NonZeroDigit (Digits? | Underscores Digits)
;
fragment
Digits
: Digit (DigitOrUnderscore* Digit)?
;
fragment
Digit
: '0'
| NonZeroDigit
;
fragment
NonZeroDigit
: [1-9]
;
fragment
DigitOrUnderscore
: Digit
| '_'
;
fragment
Underscores
: '_'+
;
fragment
HexNumeral
: '0' [xX] HexDigits
;
fragment
HexDigits
: HexDigit (HexDigitOrUnderscore* HexDigit)?
;
fragment
HexDigit
: [0-9a-fA-F]
;
fragment
HexDigitOrUnderscore
: HexDigit
| '_'
;
fragment
OctalNumeral
: '0' Underscores? OctalDigits
;
fragment
OctalDigits
: OctalDigit (OctalDigitOrUnderscore* OctalDigit)?
;
fragment
OctalDigit
: [0-7]
;
fragment
OctalDigitOrUnderscore
: OctalDigit
| '_'
;
fragment
BinaryNumeral
: '0' [bB] BinaryDigits
;
fragment
BinaryDigits
: BinaryDigit (BinaryDigitOrUnderscore* BinaryDigit)?
;
fragment
BinaryDigit
: [01]
;
fragment
BinaryDigitOrUnderscore
: BinaryDigit
| '_'
;
// §3.10.2 Floating-Point Literals
FloatingPointLiteral
: DecimalFloatingPointLiteral
| HexadecimalFloatingPointLiteral
;
fragment
DecimalFloatingPointLiteral
: Digits '.' Digits? ExponentPart? FloatTypeSuffix?
| '.' Digits ExponentPart? FloatTypeSuffix?
| Digits ExponentPart FloatTypeSuffix?
| Digits FloatTypeSuffix
;
fragment
ExponentPart
: ExponentIndicator SignedInteger
;
fragment
ExponentIndicator
: [eE]
;
fragment
SignedInteger
: Sign? Digits
;
fragment
Sign
: [+-]
;
fragment
FloatTypeSuffix
: [fFdD]
;
fragment
HexadecimalFloatingPointLiteral
: HexSignificand BinaryExponent FloatTypeSuffix?
;
fragment
HexSignificand
: HexNumeral '.'?
| '0' [xX] HexDigits? '.' HexDigits
;
fragment
BinaryExponent
: BinaryExponentIndicator SignedInteger
;
fragment
BinaryExponentIndicator
: [pP]
;
// §3.10.3 Boolean Literals
BooleanLiteral
: 'true'
| 'false'
;
// §3.10.4 Character Literals
CharacterLiteral
: '\'' SingleCharacter '\''
| '\'' EscapeSequence '\''
;
fragment
SingleCharacter
: ~['\\]
;
// §3.10.5 String Literals
StringLiteral
: '"' StringCharacters? '"'
;
MultiLineStringLiteral
: '\'\'\'' MultiLineStringCharacters? '\'\'\''
;
fragment
StringCharacters
: StringCharacter+
;
fragment
MultiLineStringCharacters
: MultiLineStringCharacter+
;
fragment
StringCharacter
: ~["\\\$]
| '$' ~[\{]
| EscapeSequence
;
fragment
MultiLineStringCharacter
: ~[\'\\]
| '\'' ~[\']
| '\'\'' ~[\']
| EscapeSequence
;
// §3.10.6 Escape Sequences for Character and String Literals
fragment
EscapeSequence
: '\\' [btnfr"'\\]
| OctalEscape
| UnicodeEscape
;
fragment
OctalEscape
: '\\' OctalDigit
| '\\' OctalDigit OctalDigit
| '\\' ZeroToThree OctalDigit OctalDigit
;
fragment
UnicodeEscape
: '\\' 'u' HexDigit HexDigit HexDigit HexDigit
;
fragment
ZeroToThree
: [0-3]
;
// §3.10.7 The Null Literal
NullLiteral
: 'null'
;
// §3.11 Separators
LPAREN : '(';
RPAREN : ')';
LBRACE : '{';
RBRACE : '}'
{
if(inString) pushMode(STRING);
}
;
LBRACK : '[';
RBRACK : ']';
SEMI : ';';
COMMA : ',';
DOT : '.';
// §3.12 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 : '>>>=';
//Inline elements
InterpolationPreffixString
: '"' StringCharacters? '${'
{
inString = true;
}
;
// §3.8 Identifiers (must appear after all keywords in the grammar)
Identifier
: JavaLetter JavaLetterOrDigit*
;
fragment
JavaLetter
: [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)))}?
;
//
// Additional symbols not defined in the lexical specification
//
AT : '@';
ELLIPSIS : '...';
COMPILE_OPTION_LINE : '#' ~[\r\n]+;
//
// Whitespace and comments
//
WS : [ \t\r\n\u000C]+ -> channel(WHITESPACE)
;
COMMENT
: '/*' .*? '*/' -> channel(COMMENTS)
;
LINE_COMMENT
: '//' ~[\r\n]* -> channel(COMMENTS)
;
PACKAGE_DELIMITER : '\\';
mode STRING;
INTERPOLATION_INTERUPT
: '${' -> popMode
;
INTERPOLATION_END
: '"'
{
popMode();
inString = false;
}
;
INTERPOLATION_STRING
: (~[\$\{\"] ) +
| '$' ~[\{]
;
|
fix StringCharacter rule
|
fix: fix StringCharacter rule
|
ANTLR
|
mit
|
kasonyang/kalang
|
e7b23a6c29c7cd9b5d3b126ab52c29f372a71780
|
molecule/molecule.g4
|
molecule/molecule.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 molecule;
molecule
: part_ ('·' part_)*
;
part_
: (count? structure)+;
structure
: symbol count?
;
symbol
:
element
| group
| ion
;
group
: '(' structure+ ')'
;
ion
: '[' structure+ ']'
;
element
: ELEMENT
;
ELEMENT
: 'H' | 'He' | 'Li' | 'Be' | 'B' | 'C' | 'N' | 'O' | 'F' | 'Ne' | 'Na' | 'Mg' | 'Al' | 'Si' | 'P' | 'S' | 'Cl' | 'Ar' | 'K' | 'Ca' | 'Sc' | 'Ti' | 'V' | 'Cr' | 'Mn' | 'Fe' | 'Co' | 'Ni' | 'Cu' | 'Zn' | 'Ga' | 'Ge' | 'As' | 'Se' | 'Br' | 'Kr' | 'Rb' | 'Sr' | 'Y' | 'Zr' | 'Nb' | 'Mo' | 'Tc' | 'Ru' | 'Rh' | 'Pd' | 'Ag' | 'Cd' | 'In' | 'Sn' | 'Sb' | 'Te' | 'I' | 'Xe' | 'Cs' | 'Ba' | 'La' | 'Ce' | 'Pr' | 'Nd' | 'Pm' | 'Sm' | 'Eu' | 'Gd' | 'Tb' | 'Dy' | 'Ho' | 'Er' | 'Tm' | 'Yb' | 'Lu' | 'Hf' | 'Ta' | 'W' | 'Re' | 'Os' | 'Ir' | 'Pt' | 'Au' | 'Hg' | 'Tl' | 'Pb' | 'Bi' | 'Po' | 'At' | 'Rn' | 'Fr' | 'Ra' | 'Ac' | 'Th' | 'Pa' | 'U' | 'Np' | 'Pu' | 'Am' | 'Cm' | 'Bk' | 'Cf' | 'Es' | 'Fm' | 'Md' | 'No' | 'Lr' | 'Rf' | 'Db' | 'Sg' | 'Bh' | 'Hs' | 'Mt' | 'Ds' | 'Rg' | 'Cn' | 'Uut' | 'Fl' | 'Uup' | 'Lv' | 'Uus' | 'Uuo'
;
count
: NUMBER
;
NUMBER
: ('0' .. '9') +
;
WS
: [ \t\r\n] + -> skip
;
|
/*
BSD License
Copyright (c) 2017, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar molecule;
molecule
: part_ ('·' part_)*
;
part_
: (count? structure)+;
structure
: symbol count?
;
symbol
:
element
| group
| ion
;
group
: '(' structure+ ')'
;
ion
: '[' structure+ ']'
;
element
: ELEMENT
;
ELEMENT
: 'H' | 'He' | 'Li' | 'Be' | 'B' | 'C' | 'N' | 'O' | 'F' | 'Ne' | 'Na' | 'Mg' | 'Al' | 'Si' | 'P' | 'S' | 'Cl' | 'Ar' | 'K' | 'Ca' | 'Sc' | 'Ti' | 'V' | 'Cr' | 'Mn' | 'Fe' | 'Co' | 'Ni' | 'Cu' | 'Zn' | 'Ga' | 'Ge' | 'As' | 'Se' | 'Br' | 'Kr' | 'Rb' | 'Sr' | 'Y' | 'Zr' | 'Nb' | 'Mo' | 'Tc' | 'Ru' | 'Rh' | 'Pd' | 'Ag' | 'Cd' | 'In' | 'Sn' | 'Sb' | 'Te' | 'I' | 'Xe' | 'Cs' | 'Ba' | 'La' | 'Ce' | 'Pr' | 'Nd' | 'Pm' | 'Sm' | 'Eu' | 'Gd' | 'Tb' | 'Dy' | 'Ho' | 'Er' | 'Tm' | 'Yb' | 'Lu' | 'Hf' | 'Ta' | 'W' | 'Re' | 'Os' | 'Ir' | 'Pt' | 'Au' | 'Hg' | 'Tl' | 'Pb' | 'Bi' | 'Po' | 'At' | 'Rn' | 'Fr' | 'Ra' | 'Ac' | 'Th' | 'Pa' | 'U' | 'Np' | 'Pu' | 'Am' | 'Cm' | 'Bk' | 'Cf' | 'Es' | 'Fm' | 'Md' | 'No' | 'Lr' | 'Rf' | 'Db' | 'Sg' | 'Bh' | 'Hs' | 'Mt' | 'Ds' | 'Rg' | 'Cn' | 'Nh' | 'Fl' | 'Mc' | 'Lv' | 'Ts' | 'Og'
;
count
: NUMBER
;
NUMBER
: ('0' .. '9') +
;
WS
: [ \t\r\n] + -> skip
;
|
Update element symbols
|
Update element symbols
|
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
|
e6fc4955833c44d557415b99face9d304eba5db8
|
Solidity.g4
|
Solidity.g4
|
// Copyright 2016-2019 Federico Bond <[email protected]>
// Licensed under the MIT license. See LICENSE file in the project root for details.
grammar Solidity;
sourceUnit
: (pragmaDirective | importDirective | contractDefinition)* EOF ;
pragmaDirective
: 'pragma' pragmaName pragmaValue ';' ;
pragmaName
: identifier ;
pragmaValue
: version | expression ;
version
: versionConstraint versionConstraint? ;
versionOperator
: '^' | '~' | '>=' | '>' | '<' | '<=' | '=' ;
versionConstraint
: versionOperator? VersionLiteral ;
importDeclaration
: identifier ('as' identifier)? ;
importDirective
: 'import' StringLiteral ('as' identifier)? ';'
| 'import' ('*' | identifier) ('as' identifier)? 'from' StringLiteral ';'
| 'import' '{' importDeclaration ( ',' importDeclaration )* '}' 'from' StringLiteral ';' ;
contractDefinition
: ( 'contract' | 'interface' | 'library' ) identifier
( 'is' inheritanceSpecifier (',' inheritanceSpecifier )* )?
'{' contractPart* '}' ;
inheritanceSpecifier
: userDefinedTypeName ( '(' expression ( ',' expression )* ')' )? ;
contractPart
: stateVariableDeclaration
| usingForDeclaration
| structDefinition
| constructorDefinition
| modifierDefinition
| functionDefinition
| eventDefinition
| enumDefinition ;
stateVariableDeclaration
: typeName
( PublicKeyword | InternalKeyword | PrivateKeyword | ConstantKeyword )*
identifier ('=' expression)? ';' ;
usingForDeclaration
: 'using' identifier 'for' ('*' | typeName) ';' ;
structDefinition
: 'struct' identifier
'{' ( variableDeclaration ';' (variableDeclaration ';')* )? '}' ;
constructorDefinition
: 'constructor' parameterList modifierList block ;
modifierDefinition
: 'modifier' identifier parameterList? block ;
modifierInvocation
: identifier ( '(' expressionList? ')' )? ;
functionDefinition
: 'function' identifier? parameterList modifierList returnParameters? ( ';' | block ) ;
returnParameters
: 'returns' parameterList ;
modifierList
: ( modifierInvocation | stateMutability | ExternalKeyword
| PublicKeyword | InternalKeyword | PrivateKeyword )* ;
eventDefinition
: 'event' identifier eventParameterList AnonymousKeyword? ';' ;
enumValue
: identifier ;
enumDefinition
: 'enum' identifier '{' enumValue? (',' enumValue)* '}' ;
parameterList
: '(' ( parameter (',' parameter)* )? ')' ;
parameter
: typeName storageLocation? identifier? ;
eventParameterList
: '(' ( eventParameter (',' eventParameter)* )? ')' ;
eventParameter
: typeName IndexedKeyword? identifier? ;
functionTypeParameterList
: '(' ( functionTypeParameter (',' functionTypeParameter)* )? ')' ;
functionTypeParameter
: typeName storageLocation? ;
variableDeclaration
: typeName storageLocation? identifier ;
typeName
: elementaryTypeName
| userDefinedTypeName
| mapping
| typeName '[' expression? ']'
| functionTypeName
| 'address' 'payable' ;
userDefinedTypeName
: identifier ( '.' identifier )* ;
mapping
: 'mapping' '(' elementaryTypeName '=>' typeName ')' ;
functionTypeName
: 'function' functionTypeParameterList
( InternalKeyword | ExternalKeyword | stateMutability )*
( 'returns' functionTypeParameterList )? ;
storageLocation
: 'memory' | 'storage' | 'calldata';
stateMutability
: PureKeyword | ConstantKeyword | ViewKeyword | PayableKeyword ;
block
: '{' statement* '}' ;
statement
: ifStatement
| whileStatement
| forStatement
| block
| inlineAssemblyStatement
| doWhileStatement
| continueStatement
| breakStatement
| returnStatement
| throwStatement
| emitStatement
| simpleStatement ;
expressionStatement
: expression ';' ;
ifStatement
: 'if' '(' expression ')' statement ( 'else' statement )? ;
whileStatement
: 'while' '(' expression ')' statement ;
simpleStatement
: ( variableDeclarationStatement | expressionStatement ) ;
forStatement
: 'for' '(' ( simpleStatement | ';' ) ( expressionStatement | ';' ) expression? ')' statement ;
inlineAssemblyStatement
: 'assembly' StringLiteral? assemblyBlock ;
doWhileStatement
: 'do' statement 'while' '(' expression ')' ';' ;
continueStatement
: 'continue' ';' ;
breakStatement
: 'break' ';' ;
returnStatement
: 'return' expression? ';' ;
throwStatement
: 'throw' ';' ;
emitStatement
: 'emit' functionCall ';' ;
variableDeclarationStatement
: ( 'var' identifierList | variableDeclaration | '(' variableDeclarationList ')' ) ( '=' expression )? ';';
variableDeclarationList
: variableDeclaration? (',' variableDeclaration? )* ;
identifierList
: '(' ( identifier? ',' )* identifier? ')' ;
elementaryTypeName
: 'address' | 'bool' | 'string' | 'var' | Int | Uint | 'byte' | Byte | Fixed | Ufixed ;
Int
: 'int' | 'int8' | 'int16' | 'int24' | 'int32' | 'int40' | 'int48' | 'int56' | 'int64' | 'int72' | 'int80' | 'int88' | 'int96' | 'int104' | 'int112' | 'int120' | 'int128' | 'int136' | 'int144' | 'int152' | 'int160' | 'int168' | 'int176' | 'int184' | 'int192' | 'int200' | 'int208' | 'int216' | 'int224' | 'int232' | 'int240' | 'int248' | 'int256' ;
Uint
: 'uint' | 'uint8' | 'uint16' | 'uint24' | 'uint32' | 'uint40' | 'uint48' | 'uint56' | 'uint64' | 'uint72' | 'uint80' | 'uint88' | 'uint96' | 'uint104' | 'uint112' | 'uint120' | 'uint128' | 'uint136' | 'uint144' | 'uint152' | 'uint160' | 'uint168' | 'uint176' | 'uint184' | 'uint192' | 'uint200' | 'uint208' | 'uint216' | 'uint224' | 'uint232' | 'uint240' | 'uint248' | 'uint256' ;
Byte
: 'bytes' | 'bytes1' | 'bytes2' | 'bytes3' | 'bytes4' | 'bytes5' | 'bytes6' | 'bytes7' | 'bytes8' | 'bytes9' | 'bytes10' | 'bytes11' | 'bytes12' | 'bytes13' | 'bytes14' | 'bytes15' | 'bytes16' | 'bytes17' | 'bytes18' | 'bytes19' | 'bytes20' | 'bytes21' | 'bytes22' | 'bytes23' | 'bytes24' | 'bytes25' | 'bytes26' | 'bytes27' | 'bytes28' | 'bytes29' | 'bytes30' | 'bytes31' | 'bytes32' ;
Fixed
: 'fixed' | ( 'fixed' [0-9]+ 'x' [0-9]+ ) ;
Ufixed
: 'ufixed' | ( 'ufixed' [0-9]+ 'x' [0-9]+ ) ;
expression
: expression ('++' | '--')
| 'new' typeName
| expression '[' expression ']'
| expression '(' functionCallArguments ')'
| expression '.' identifier
| '(' expression ')'
| ('++' | '--') expression
| ('+' | '-') expression
| ('after' | 'delete') expression
| '!' expression
| '~' expression
| expression '**' expression
| expression ('*' | '/' | '%') expression
| expression ('+' | '-') expression
| expression ('<<' | '>>') expression
| expression '&' expression
| expression '^' expression
| expression '|' expression
| expression ('<' | '>' | '<=' | '>=') expression
| expression ('==' | '!=') expression
| expression '&&' expression
| expression '||' expression
| expression '?' expression ':' expression
| expression ('=' | '|=' | '^=' | '&=' | '<<=' | '>>=' | '+=' | '-=' | '*=' | '/=' | '%=') expression
| primaryExpression ;
primaryExpression
: BooleanLiteral
| numberLiteral
| HexLiteral
| StringLiteral
| identifier ('[' ']')?
| TypeKeyword
| tupleExpression
| elementaryTypeNameExpression ('[' ']')? ;
expressionList
: expression (',' expression)* ;
nameValueList
: nameValue (',' nameValue)* ','? ;
nameValue
: identifier ':' expression ;
functionCallArguments
: '{' nameValueList? '}'
| expressionList? ;
functionCall
: expression '(' functionCallArguments ')' ;
assemblyBlock
: '{' assemblyItem* '}' ;
assemblyItem
: identifier
| assemblyBlock
| assemblyExpression
| assemblyLocalDefinition
| assemblyAssignment
| assemblyStackAssignment
| labelDefinition
| assemblySwitch
| assemblyFunctionDefinition
| assemblyFor
| assemblyIf
| BreakKeyword
| ContinueKeyword
| subAssembly
| numberLiteral
| StringLiteral
| HexLiteral ;
assemblyExpression
: assemblyCall | assemblyLiteral ;
assemblyCall
: ( 'return' | 'address' | 'byte' | identifier ) ( '(' assemblyExpression? ( ',' assemblyExpression )* ')' )? ;
assemblyLocalDefinition
: 'let' assemblyIdentifierOrList ( ':=' assemblyExpression )? ;
assemblyAssignment
: assemblyIdentifierOrList ':=' assemblyExpression ;
assemblyIdentifierOrList
: identifier | '(' assemblyIdentifierList ')' ;
assemblyIdentifierList
: identifier ( ',' identifier )* ;
assemblyStackAssignment
: '=:' identifier ;
labelDefinition
: identifier ':' ;
assemblySwitch
: 'switch' assemblyExpression assemblyCase* ;
assemblyCase
: 'case' assemblyLiteral assemblyBlock
| 'default' assemblyBlock ;
assemblyFunctionDefinition
: 'function' identifier '(' assemblyIdentifierList? ')'
assemblyFunctionReturns? assemblyBlock ;
assemblyFunctionReturns
: ( '->' assemblyIdentifierList ) ;
assemblyFor
: 'for' ( assemblyBlock | assemblyExpression )
assemblyExpression ( assemblyBlock | assemblyExpression ) assemblyBlock ;
assemblyIf
: 'if' assemblyExpression assemblyBlock ;
assemblyLiteral
: StringLiteral | DecimalNumber | HexNumber | HexLiteral ;
subAssembly
: 'assembly' identifier assemblyBlock ;
tupleExpression
: '(' ( expression? ( ',' expression? )* ) ')'
| '[' ( expression ( ',' expression )* )? ']' ;
elementaryTypeNameExpression
: elementaryTypeName ;
numberLiteral
: (DecimalNumber | HexNumber) NumberUnit? ;
identifier
: ('from' | 'calldata' | Identifier) ;
VersionLiteral
: [0-9]+ '.' [0-9]+ '.' [0-9]+ ;
BooleanLiteral
: 'true' | 'false' ;
DecimalNumber
: ( DecimalDigits | (DecimalDigits? '.' DecimalDigits) ) ( [eE] DecimalDigits )? ;
fragment
DecimalDigits
: [0-9] ( '_'? [0-9] )* ;
HexNumber
: '0' [xX] HexDigits ;
fragment
HexDigits
: HexCharacter ( '_'? HexCharacter )* ;
NumberUnit
: 'wei' | 'szabo' | 'finney' | 'ether'
| 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'years' ;
HexLiteral : 'hex' ('"' HexPair* '"' | '\'' HexPair* '\'') ;
fragment
HexPair
: HexCharacter HexCharacter ;
fragment
HexCharacter
: [0-9A-Fa-f] ;
ReservedKeyword
: 'abstract'
| 'after'
| 'case'
| 'catch'
| 'default'
| 'final'
| 'in'
| 'inline'
| 'let'
| 'match'
| 'null'
| 'of'
| 'relocatable'
| 'static'
| 'switch'
| 'try'
| 'typeof' ;
AnonymousKeyword : 'anonymous' ;
BreakKeyword : 'break' ;
ConstantKeyword : 'constant' ;
ContinueKeyword : 'continue' ;
ExternalKeyword : 'external' ;
IndexedKeyword : 'indexed' ;
InternalKeyword : 'internal' ;
PayableKeyword : 'payable' ;
PrivateKeyword : 'private' ;
PublicKeyword : 'public' ;
PureKeyword : 'pure' ;
TypeKeyword : 'type' ;
ViewKeyword : 'view' ;
Identifier
: IdentifierStart IdentifierPart* ;
fragment
IdentifierStart
: [a-zA-Z$_] ;
fragment
IdentifierPart
: [a-zA-Z0-9$_] ;
StringLiteral
: '"' DoubleQuotedStringCharacter* '"'
| '\'' SingleQuotedStringCharacter* '\'' ;
fragment
DoubleQuotedStringCharacter
: ~["\r\n\\] | ('\\' .) ;
fragment
SingleQuotedStringCharacter
: ~['\r\n\\] | ('\\' .) ;
WS
: [ \t\r\n\u000C]+ -> skip ;
COMMENT
: '/*' .*? '*/' -> channel(HIDDEN) ;
LINE_COMMENT
: '//' ~[\r\n]* -> channel(HIDDEN) ;
|
// Copyright 2016-2019 Federico Bond <[email protected]>
// Licensed under the MIT license. See LICENSE file in the project root for details.
grammar Solidity;
sourceUnit
: (pragmaDirective | importDirective | contractDefinition)* EOF ;
pragmaDirective
: 'pragma' pragmaName pragmaValue ';' ;
pragmaName
: identifier ;
pragmaValue
: version | expression ;
version
: versionConstraint versionConstraint? ;
versionOperator
: '^' | '~' | '>=' | '>' | '<' | '<=' | '=' ;
versionConstraint
: versionOperator? VersionLiteral ;
importDeclaration
: identifier ('as' identifier)? ;
importDirective
: 'import' StringLiteral ('as' identifier)? ';'
| 'import' ('*' | identifier) ('as' identifier)? 'from' StringLiteral ';'
| 'import' '{' importDeclaration ( ',' importDeclaration )* '}' 'from' StringLiteral ';' ;
NatSpecSingleLine
: ('///' .*? [\r\n]) + ;
NatSpecMultiLine
: '/**' .*? '*/' ;
natSpec
: NatSpecSingleLine
| NatSpecMultiLine ;
contractDefinition
: natSpec? ( 'contract' | 'interface' | 'library' ) identifier
( 'is' inheritanceSpecifier (',' inheritanceSpecifier )* )?
'{' contractPart* '}' ;
inheritanceSpecifier
: userDefinedTypeName ( '(' expression ( ',' expression )* ')' )? ;
contractPart
: stateVariableDeclaration
| usingForDeclaration
| structDefinition
| constructorDefinition
| modifierDefinition
| functionDefinition
| eventDefinition
| enumDefinition ;
stateVariableDeclaration
: typeName
( PublicKeyword | InternalKeyword | PrivateKeyword | ConstantKeyword )*
identifier ('=' expression)? ';' ;
usingForDeclaration
: 'using' identifier 'for' ('*' | typeName) ';' ;
structDefinition
: 'struct' identifier
'{' ( variableDeclaration ';' (variableDeclaration ';')* )? '}' ;
constructorDefinition
: 'constructor' parameterList modifierList block ;
modifierDefinition
: 'modifier' identifier parameterList? block ;
modifierInvocation
: identifier ( '(' expressionList? ')' )? ;
functionDefinition
: natSpec? 'function' identifier? parameterList modifierList returnParameters? ( ';' | block ) ;
returnParameters
: 'returns' parameterList ;
modifierList
: ( modifierInvocation | stateMutability | ExternalKeyword
| PublicKeyword | InternalKeyword | PrivateKeyword )* ;
eventDefinition
: natSpec? 'event' identifier eventParameterList AnonymousKeyword? ';' ;
enumValue
: identifier ;
enumDefinition
: 'enum' identifier '{' enumValue? (',' enumValue)* '}' ;
parameterList
: '(' ( parameter (',' parameter)* )? ')' ;
parameter
: typeName storageLocation? identifier? ;
eventParameterList
: '(' ( eventParameter (',' eventParameter)* )? ')' ;
eventParameter
: typeName IndexedKeyword? identifier? ;
functionTypeParameterList
: '(' ( functionTypeParameter (',' functionTypeParameter)* )? ')' ;
functionTypeParameter
: typeName storageLocation? ;
variableDeclaration
: typeName storageLocation? identifier ;
typeName
: elementaryTypeName
| userDefinedTypeName
| mapping
| typeName '[' expression? ']'
| functionTypeName
| 'address' 'payable' ;
userDefinedTypeName
: identifier ( '.' identifier )* ;
mapping
: 'mapping' '(' elementaryTypeName '=>' typeName ')' ;
functionTypeName
: 'function' functionTypeParameterList
( InternalKeyword | ExternalKeyword | stateMutability )*
( 'returns' functionTypeParameterList )? ;
storageLocation
: 'memory' | 'storage' | 'calldata';
stateMutability
: PureKeyword | ConstantKeyword | ViewKeyword | PayableKeyword ;
block
: '{' statement* '}' ;
statement
: ifStatement
| whileStatement
| forStatement
| block
| inlineAssemblyStatement
| doWhileStatement
| continueStatement
| breakStatement
| returnStatement
| throwStatement
| emitStatement
| simpleStatement ;
expressionStatement
: expression ';' ;
ifStatement
: 'if' '(' expression ')' statement ( 'else' statement )? ;
whileStatement
: 'while' '(' expression ')' statement ;
simpleStatement
: ( variableDeclarationStatement | expressionStatement ) ;
forStatement
: 'for' '(' ( simpleStatement | ';' ) ( expressionStatement | ';' ) expression? ')' statement ;
inlineAssemblyStatement
: 'assembly' StringLiteral? assemblyBlock ;
doWhileStatement
: 'do' statement 'while' '(' expression ')' ';' ;
continueStatement
: 'continue' ';' ;
breakStatement
: 'break' ';' ;
returnStatement
: 'return' expression? ';' ;
throwStatement
: 'throw' ';' ;
emitStatement
: 'emit' functionCall ';' ;
variableDeclarationStatement
: ( 'var' identifierList | variableDeclaration | '(' variableDeclarationList ')' ) ( '=' expression )? ';';
variableDeclarationList
: variableDeclaration? (',' variableDeclaration? )* ;
identifierList
: '(' ( identifier? ',' )* identifier? ')' ;
elementaryTypeName
: 'address' | 'bool' | 'string' | 'var' | Int | Uint | 'byte' | Byte | Fixed | Ufixed ;
Int
: 'int' | 'int8' | 'int16' | 'int24' | 'int32' | 'int40' | 'int48' | 'int56' | 'int64' | 'int72' | 'int80' | 'int88' | 'int96' | 'int104' | 'int112' | 'int120' | 'int128' | 'int136' | 'int144' | 'int152' | 'int160' | 'int168' | 'int176' | 'int184' | 'int192' | 'int200' | 'int208' | 'int216' | 'int224' | 'int232' | 'int240' | 'int248' | 'int256' ;
Uint
: 'uint' | 'uint8' | 'uint16' | 'uint24' | 'uint32' | 'uint40' | 'uint48' | 'uint56' | 'uint64' | 'uint72' | 'uint80' | 'uint88' | 'uint96' | 'uint104' | 'uint112' | 'uint120' | 'uint128' | 'uint136' | 'uint144' | 'uint152' | 'uint160' | 'uint168' | 'uint176' | 'uint184' | 'uint192' | 'uint200' | 'uint208' | 'uint216' | 'uint224' | 'uint232' | 'uint240' | 'uint248' | 'uint256' ;
Byte
: 'bytes' | 'bytes1' | 'bytes2' | 'bytes3' | 'bytes4' | 'bytes5' | 'bytes6' | 'bytes7' | 'bytes8' | 'bytes9' | 'bytes10' | 'bytes11' | 'bytes12' | 'bytes13' | 'bytes14' | 'bytes15' | 'bytes16' | 'bytes17' | 'bytes18' | 'bytes19' | 'bytes20' | 'bytes21' | 'bytes22' | 'bytes23' | 'bytes24' | 'bytes25' | 'bytes26' | 'bytes27' | 'bytes28' | 'bytes29' | 'bytes30' | 'bytes31' | 'bytes32' ;
Fixed
: 'fixed' | ( 'fixed' [0-9]+ 'x' [0-9]+ ) ;
Ufixed
: 'ufixed' | ( 'ufixed' [0-9]+ 'x' [0-9]+ ) ;
expression
: expression ('++' | '--')
| 'new' typeName
| expression '[' expression ']'
| expression '(' functionCallArguments ')'
| expression '.' identifier
| '(' expression ')'
| ('++' | '--') expression
| ('+' | '-') expression
| ('after' | 'delete') expression
| '!' expression
| '~' expression
| expression '**' expression
| expression ('*' | '/' | '%') expression
| expression ('+' | '-') expression
| expression ('<<' | '>>') expression
| expression '&' expression
| expression '^' expression
| expression '|' expression
| expression ('<' | '>' | '<=' | '>=') expression
| expression ('==' | '!=') expression
| expression '&&' expression
| expression '||' expression
| expression '?' expression ':' expression
| expression ('=' | '|=' | '^=' | '&=' | '<<=' | '>>=' | '+=' | '-=' | '*=' | '/=' | '%=') expression
| primaryExpression ;
primaryExpression
: BooleanLiteral
| numberLiteral
| HexLiteral
| StringLiteral
| identifier ('[' ']')?
| TypeKeyword
| tupleExpression
| elementaryTypeNameExpression ('[' ']')? ;
expressionList
: expression (',' expression)* ;
nameValueList
: nameValue (',' nameValue)* ','? ;
nameValue
: identifier ':' expression ;
functionCallArguments
: '{' nameValueList? '}'
| expressionList? ;
functionCall
: expression '(' functionCallArguments ')' ;
assemblyBlock
: '{' assemblyItem* '}' ;
assemblyItem
: identifier
| assemblyBlock
| assemblyExpression
| assemblyLocalDefinition
| assemblyAssignment
| assemblyStackAssignment
| labelDefinition
| assemblySwitch
| assemblyFunctionDefinition
| assemblyFor
| assemblyIf
| BreakKeyword
| ContinueKeyword
| subAssembly
| numberLiteral
| StringLiteral
| HexLiteral ;
assemblyExpression
: assemblyCall | assemblyLiteral ;
assemblyCall
: ( 'return' | 'address' | 'byte' | identifier ) ( '(' assemblyExpression? ( ',' assemblyExpression )* ')' )? ;
assemblyLocalDefinition
: 'let' assemblyIdentifierOrList ( ':=' assemblyExpression )? ;
assemblyAssignment
: assemblyIdentifierOrList ':=' assemblyExpression ;
assemblyIdentifierOrList
: identifier | '(' assemblyIdentifierList ')' ;
assemblyIdentifierList
: identifier ( ',' identifier )* ;
assemblyStackAssignment
: '=:' identifier ;
labelDefinition
: identifier ':' ;
assemblySwitch
: 'switch' assemblyExpression assemblyCase* ;
assemblyCase
: 'case' assemblyLiteral assemblyBlock
| 'default' assemblyBlock ;
assemblyFunctionDefinition
: 'function' identifier '(' assemblyIdentifierList? ')'
assemblyFunctionReturns? assemblyBlock ;
assemblyFunctionReturns
: ( '->' assemblyIdentifierList ) ;
assemblyFor
: 'for' ( assemblyBlock | assemblyExpression )
assemblyExpression ( assemblyBlock | assemblyExpression ) assemblyBlock ;
assemblyIf
: 'if' assemblyExpression assemblyBlock ;
assemblyLiteral
: StringLiteral | DecimalNumber | HexNumber | HexLiteral ;
subAssembly
: 'assembly' identifier assemblyBlock ;
tupleExpression
: '(' ( expression? ( ',' expression? )* ) ')'
| '[' ( expression ( ',' expression )* )? ']' ;
elementaryTypeNameExpression
: elementaryTypeName ;
numberLiteral
: (DecimalNumber | HexNumber) NumberUnit? ;
identifier
: ('from' | 'calldata' | Identifier) ;
VersionLiteral
: [0-9]+ '.' [0-9]+ '.' [0-9]+ ;
BooleanLiteral
: 'true' | 'false' ;
DecimalNumber
: ( DecimalDigits | (DecimalDigits? '.' DecimalDigits) ) ( [eE] DecimalDigits )? ;
fragment
DecimalDigits
: [0-9] ( '_'? [0-9] )* ;
HexNumber
: '0' [xX] HexDigits ;
fragment
HexDigits
: HexCharacter ( '_'? HexCharacter )* ;
NumberUnit
: 'wei' | 'szabo' | 'finney' | 'ether'
| 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'years' ;
HexLiteral : 'hex' ('"' HexPair* '"' | '\'' HexPair* '\'') ;
fragment
HexPair
: HexCharacter HexCharacter ;
fragment
HexCharacter
: [0-9A-Fa-f] ;
ReservedKeyword
: 'abstract'
| 'after'
| 'case'
| 'catch'
| 'default'
| 'final'
| 'in'
| 'inline'
| 'let'
| 'match'
| 'null'
| 'of'
| 'relocatable'
| 'static'
| 'switch'
| 'try'
| 'typeof' ;
AnonymousKeyword : 'anonymous' ;
BreakKeyword : 'break' ;
ConstantKeyword : 'constant' ;
ContinueKeyword : 'continue' ;
ExternalKeyword : 'external' ;
IndexedKeyword : 'indexed' ;
InternalKeyword : 'internal' ;
PayableKeyword : 'payable' ;
PrivateKeyword : 'private' ;
PublicKeyword : 'public' ;
PureKeyword : 'pure' ;
TypeKeyword : 'type' ;
ViewKeyword : 'view' ;
Identifier
: IdentifierStart IdentifierPart* ;
fragment
IdentifierStart
: [a-zA-Z$_] ;
fragment
IdentifierPart
: [a-zA-Z0-9$_] ;
StringLiteral
: '"' DoubleQuotedStringCharacter* '"'
| '\'' SingleQuotedStringCharacter* '\'' ;
fragment
DoubleQuotedStringCharacter
: ~["\r\n\\] | ('\\' .) ;
fragment
SingleQuotedStringCharacter
: ~['\r\n\\] | ('\\' .) ;
WS
: [ \t\r\n\u000C]+ -> skip ;
COMMENT
: '/*' .*? '*/' -> channel(HIDDEN) ;
LINE_COMMENT
: '//' ~[\r\n]* -> channel(HIDDEN) ;
|
Add support for natspec comments
|
Add support for natspec comments
|
ANTLR
|
mit
|
federicobond/solidity-antlr4,solidityj/solidity-antlr4
|
37f563de09c382a32e59d5ae8ad05f5892b383fd
|
projects/batfish/src/main/antlr4/org/batfish/grammar/cisco/Cisco_line.g4
|
projects/batfish/src/main/antlr4/org/batfish/grammar/cisco/Cisco_line.g4
|
parser grammar Cisco_line;
import Cisco_common;
options {
tokenVocab = CiscoLexer;
}
l_access_class
:
IPV6? ACCESS_CLASS
(
(
(
EGRESS
| INGRESS
) name = variable
)
|
(
name = variable
(
IN
| OUT
)?
)
) VRF_ALSO? NEWLINE
;
l_exec_timeout
:
EXEC_TIMEOUT minutes = DEC seconds = DEC? NEWLINE
;
l_login
:
LOGIN
(
l_login_authentication
| l_login_local
)
;
l_login_authentication
:
AUTHENTICATION
(
DEFAULT
| name = variable
) NEWLINE
;
l_login_local
:
LOCAL NEWLINE
;
l_null
:
NO?
(
ABSOLUTE_TIMEOUT
| ACTIVATION_CHARACTER
| AUTHORIZATION
| AUTOHANGUP
| AUTOSELECT
| DATABITS
| ESCAPE_CHARACTER
| EXEC
| FLOWCONTROL
| FLUSH_AT_ACTIVATION
| HISTORY
| IPV6
| LENGTH DEC
| LOCATION
| LOGGING
| LOGOUT_WARNING
| MODEM
| NOTIFY
| PASSWORD
| PRIVILEGE
| ROTARY
| SESSION_DISCONNECT_WARNING
| SESSION_LIMIT
| SESSION_TIMEOUT
| STOPBITS
| TERMINAL_TYPE
| TIMEOUT
| TIMESTAMP
| VACANT_MESSAGE
) ~NEWLINE* NEWLINE
;
l_transport
:
TRANSPORT
(
INPUT
| OUTPUT
| PREFERRED
) prot += variable+ NEWLINE
;
s_line
:
LINE line_type
(
(
slot1 = DEC FORWARD_SLASH
(
port1 = DEC FORWARD_SLASH
)?
)? first = DEC
(
(
slot2 = DEC FORWARD_SLASH
(
port2 = DEC FORWARD_SLASH
)?
)? last = DEC
)?
)? NEWLINE
(
l_access_class
| l_exec_timeout
| l_login
| l_null
| l_transport
| description_line
)*
;
|
parser grammar Cisco_line;
import Cisco_common;
options {
tokenVocab = CiscoLexer;
}
l_access_class
:
IPV6? ACCESS_CLASS
(
(
(
EGRESS
| INGRESS
) name = variable
)
|
(
name = variable
(
IN
| OUT
)?
)
) VRF_ALSO? NEWLINE
;
l_exec_timeout
:
EXEC_TIMEOUT minutes = DEC seconds = DEC? NEWLINE
;
l_length
:
(LENGTH DEC NEWLINE)
|
(NO LENGTH NEWLINE)
;
l_login
:
LOGIN
(
l_login_authentication
| l_login_local
)
;
l_login_authentication
:
AUTHENTICATION
(
DEFAULT
| name = variable
) NEWLINE
;
l_login_local
:
LOCAL NEWLINE
;
l_null
:
NO?
(
ABSOLUTE_TIMEOUT
| ACTIVATION_CHARACTER
| AUTHORIZATION
| AUTOHANGUP
| AUTOSELECT
| DATABITS
| ESCAPE_CHARACTER
| EXEC
| FLOWCONTROL
| FLUSH_AT_ACTIVATION
| HISTORY
| IPV6
| LOCATION
| LOGGING
| LOGOUT_WARNING
| MODEM
| NOTIFY
| PASSWORD
| PRIVILEGE
| ROTARY
| SESSION_DISCONNECT_WARNING
| SESSION_LIMIT
| SESSION_TIMEOUT
| STOPBITS
| TERMINAL_TYPE
| TIMEOUT
| TIMESTAMP
| VACANT_MESSAGE
) ~NEWLINE* NEWLINE
;
l_transport
:
TRANSPORT
(
INPUT
| OUTPUT
| PREFERRED
) prot += variable+ NEWLINE
;
s_line
:
LINE line_type
(
(
slot1 = DEC FORWARD_SLASH
(
port1 = DEC FORWARD_SLASH
)?
)? first = DEC
(
(
slot2 = DEC FORWARD_SLASH
(
port2 = DEC FORWARD_SLASH
)?
)? last = DEC
)?
)? NEWLINE
(
l_access_class
| l_exec_timeout
| l_length
| l_login
| l_null
| l_transport
| description_line
)*
;
|
add support for console line length
|
cisco: add support for console line length
https://www.cisco.com/c/en/us/td/docs/ios/12_2/configfun/command/reference/ffun_r/frf003.html\#wpmkr1018163
|
ANTLR
|
apache-2.0
|
intentionet/batfish,dhalperi/batfish,batfish/batfish,intentionet/batfish,batfish/batfish,dhalperi/batfish,arifogel/batfish,dhalperi/batfish,arifogel/batfish,intentionet/batfish,arifogel/batfish,batfish/batfish,intentionet/batfish,intentionet/batfish
|
6fa864164766490ab0371b306667b5bcafed5cf8
|
sharding-core/src/main/antlr4/imports/OracleKeyword.g4
|
sharding-core/src/main/antlr4/imports/OracleKeyword.g4
|
lexer grammar OracleKeyword;
import Symbol;
ACCOUNT
: A C C O U N T
;
ADMIN
: A D M I N
;
AT
: A T
;
AUTHENTICATION
: A U T H E N T I C A T I O N
;
BATCH
: B A T C H
;
BITMAP
: B I T M A P
;
CACHE
: C A C H E
;
CASE
: C A S E
;
CHECKPOINT
: C H E C K P O I N T
;
COMMENT
: C O M M E N T
;
CONNECT
: C O N N E C T
;
CONSTRAINTS
: C O N S T R A I N T S
;
CONTAINER
: C O N T A I N E R
;
CONTAINER_DATA
: C O N T A I N E R UL_ D A T A
;
CURRENT
: C U R R E N T
;
CYCLE
: C Y C L E
;
DAY
: D A Y
;
DBTIMEZONE
: D B T I M E Z O N E
;
DECRYPT
: D E C R Y P T
;
DEFERRABLE
: D E F E R R A B L E
;
DEFERRED
: D E F E R R E D
;
DELEGATE
: D E L E G A T E
;
DIRECTORY
: D I R E C T O R Y
;
DOUBLE
: D O U B L E
;
EDITION
: E D I T I O N
;
EDITIONS
: E D I T I O N S
;
ELEMENT
: E L E M E N T
;
ELSE
: E L S E
;
ENCRYPT
: E N C R Y P T
;
END
: E N D
;
ENTERPRISE
: E N T E R P R I S E
;
EXCEPT
: E X C E P T
;
EXCEPTIONS
: E X C E P T I O N S
;
EXPIRE
: E X P I R E
;
EXTERNALLY
: E X T E R N A L L Y
;
FOR
: F O R
;
FORCE
: F O R C E
;
FUNCTION
: F U N C T I O N
;
GLOBAL
: G L O B A L
;
GLOBALLY
: G L O B A L L Y
;
GRANT
: G R A N T
;
HIERARCHY
: H I E R A R C H Y
;
IDENTIFIED
: I D E N T I F I E D
;
IDENTITY
: I D E N T I T Y
;
IMMEDIATE
: I M M E D I A T E
;
INCREMENT
: I N C R E M E N T
;
INITIALLY
: I N I T I A L L Y
;
INTERVAL
: I N T E R V A L
;
INTO
: I N T O
;
INVALIDATE
: I N V A L I D A T E
;
JAVA
: J A V A
;
KEEP
: K E E P
;
LEVELS
: L E V E L S
;
LOCAL
: L O C A L
;
LOCK
: L O C K
;
MAXVALUE
: M A X V A L U E
;
MINING
: M I N I N G
;
MINVALUE
: M I N V A L U E
;
MODEL
: M O D E L
;
MODIFY
: M O D I F Y
;
MONTH
: M O N T H
;
NAME
: N A M E
;
NATIONAL
: N A T I O N A L
;
NEW
: N E W
;
NOCACHE
: N O C A C H E
;
NOCYCLE
: N O C Y C L E
;
NOMAXVALUE
: N O M A X V A L U E
;
NOMINVALUE
: N O M I N V A L U E
;
NONE
: N O N E
;
NOORDER
: N O O R D E R
;
NORELY
: N O R E L Y
;
NOVALIDATE
: N O V A L I D A T E
;
NOWAIT
: N O W A I T
;
OF
: O F
;
ONLY
: O N L Y
;
OPTION
: O P T I O N
;
PACKAGE
: P A C K A G E
;
PASSWORD
: P A S S W O R D
;
PRECISION
: P R E C I S I O N
;
PRESERVE
: P R E S E R V E
;
PRIOR
: P R I O R
;
PRIVILEGES
: P R I V I L E G E S
;
PROCEDURE
: P R O C E D U R E
;
PROFILE
: P R O F I L E
;
PUBLIC
: P U B L I C
;
QUOTA
: Q U O T A
;
REF
: R E F
;
REKEY
: R E K E Y
;
RELY
: R E L Y
;
REMOVE
: R E M O V E
;
RENAME
: R E N A M E
;
REPLACE
: R E P L A C E
;
REQUIRED
: R E Q U I R E D
;
RESOURCE
: R E S O U R C E
;
REVOKE
: R E V O K E
;
ROLE
: R O L E
;
ROLES
: R O L E S
;
ROWID
: R O W I D
;
ROWS
: R O W S
;
SALT
: S A L T
;
SAVEPOINT
: S A V E P O I N T
;
SCOPE
: S C O P E
;
SECOND
: S E C O N D
;
SEGMENT
: S E G M E N T
;
SORT
: S O R T
;
SOURCE
: S O U R C E
;
SQL
: S Q L
;
SQLRF
: S Q L R F
;
SUBSTITUTABLE
: S U B S T I T U T A B L E
;
TABLESPACE
: T A B L E S P A C E
;
TEMPORARY
: T E M P O R A R Y
;
THEN
: T H E N
;
THROUGH
: T H R O U G H
;
TRANSLATION
: T R A N S L A T I O N
;
TREAT
: T R E A T
;
TYPE
: T Y P E
;
UNLIMITED
: U N L I M I T E D
;
UNLOCK
: U N L O C K
;
UNUSED
: U N U S E D
;
USE
: U S E
;
USER
: U S E R
;
USERS
: U S E R S
;
USING
: U S I N G
;
VALIDATE
: V A L I D A T E
;
VALUE
: V A L U E
;
VARYING
: V A R Y I N G
;
VIRTUAL
: V I R T U A L
;
WAIT
: W A I T
;
WHEN
: W H E N
;
WRITE
: W R I T E
;
ZONE
: Z O N E
;
|
lexer grammar OracleKeyword;
import Symbol;
ACCOUNT
: A C C O U N T
;
ADMIN
: A D M I N
;
AT
: A T
;
AUTHENTICATION
: A U T H E N T I C A T I O N
;
BATCH
: B A T C H
;
BITMAP
: B I T M A P
;
CACHE
: C A C H E
;
CASE
: C A S E
;
CHECKPOINT
: C H E C K P O I N T
;
COMMENT
: C O M M E N T
;
CONNECT
: C O N N E C T
;
CONSTRAINTS
: C O N S T R A I N T S
;
CONTAINER
: C O N T A I N E R
;
CONTAINER_DATA
: C O N T A I N E R UL_ D A T A
;
CYCLE
: C Y C L E
;
DBTIMEZONE
: D B T I M E Z O N E
;
DECRYPT
: D E C R Y P T
;
DEFERRABLE
: D E F E R R A B L E
;
DEFERRED
: D E F E R R E D
;
DELEGATE
: D E L E G A T E
;
DIRECTORY
: D I R E C T O R Y
;
DOUBLE
: D O U B L E
;
EDITION
: E D I T I O N
;
EDITIONS
: E D I T I O N S
;
ELEMENT
: E L E M E N T
;
ELSE
: E L S E
;
ENCRYPT
: E N C R Y P T
;
END
: E N D
;
ENTERPRISE
: E N T E R P R I S E
;
EXCEPT
: E X C E P T
;
EXCEPTIONS
: E X C E P T I O N S
;
EXPIRE
: E X P I R E
;
EXTERNALLY
: E X T E R N A L L Y
;
FOR
: F O R
;
FORCE
: F O R C E
;
FUNCTION
: F U N C T I O N
;
GLOBAL
: G L O B A L
;
GLOBALLY
: G L O B A L L Y
;
GRANT
: G R A N T
;
HIERARCHY
: H I E R A R C H Y
;
IDENTIFIED
: I D E N T I F I E D
;
IDENTITY
: I D E N T I T Y
;
IMMEDIATE
: I M M E D I A T E
;
INCREMENT
: I N C R E M E N T
;
INITIALLY
: I N I T I A L L Y
;
INTERVAL
: I N T E R V A L
;
INTO
: I N T O
;
INVALIDATE
: I N V A L I D A T E
;
JAVA
: J A V A
;
KEEP
: K E E P
;
LEVELS
: L E V E L S
;
LOCAL
: L O C A L
;
LOCK
: L O C K
;
MAXVALUE
: M A X V A L U E
;
MINING
: M I N I N G
;
MINVALUE
: M I N V A L U E
;
MODEL
: M O D E L
;
MODIFY
: M O D I F Y
;
MONTH
: M O N T H
;
NAME
: N A M E
;
NATIONAL
: N A T I O N A L
;
NEW
: N E W
;
NOCACHE
: N O C A C H E
;
NOCYCLE
: N O C Y C L E
;
NOMAXVALUE
: N O M A X V A L U E
;
NOMINVALUE
: N O M I N V A L U E
;
NONE
: N O N E
;
NOORDER
: N O O R D E R
;
NORELY
: N O R E L Y
;
NOVALIDATE
: N O V A L I D A T E
;
NOWAIT
: N O W A I T
;
OF
: O F
;
ONLY
: O N L Y
;
OPTION
: O P T I O N
;
PACKAGE
: P A C K A G E
;
PASSWORD
: P A S S W O R D
;
PRECISION
: P R E C I S I O N
;
PRESERVE
: P R E S E R V E
;
PRIOR
: P R I O R
;
PRIVILEGES
: P R I V I L E G E S
;
PROCEDURE
: P R O C E D U R E
;
PROFILE
: P R O F I L E
;
PUBLIC
: P U B L I C
;
QUOTA
: Q U O T A
;
REF
: R E F
;
REKEY
: R E K E Y
;
RELY
: R E L Y
;
REMOVE
: R E M O V E
;
RENAME
: R E N A M E
;
REPLACE
: R E P L A C E
;
REQUIRED
: R E Q U I R E D
;
RESOURCE
: R E S O U R C E
;
REVOKE
: R E V O K E
;
ROLE
: R O L E
;
ROLES
: R O L E S
;
ROWID
: R O W I D
;
ROWS
: R O W S
;
SALT
: S A L T
;
SAVEPOINT
: S A V E P O I N T
;
SCOPE
: S C O P E
;
SECOND
: S E C O N D
;
SEGMENT
: S E G M E N T
;
SORT
: S O R T
;
SOURCE
: S O U R C E
;
SQL
: S Q L
;
SQLRF
: S Q L R F
;
SUBSTITUTABLE
: S U B S T I T U T A B L E
;
TABLESPACE
: T A B L E S P A C E
;
TEMPORARY
: T E M P O R A R Y
;
THEN
: T H E N
;
THROUGH
: T H R O U G H
;
TRANSLATION
: T R A N S L A T I O N
;
TREAT
: T R E A T
;
TYPE
: T Y P E
;
UNLIMITED
: U N L I M I T E D
;
UNLOCK
: U N L O C K
;
UNUSED
: U N U S E D
;
USE
: U S E
;
USERS
: U S E R S
;
USING
: U S I N G
;
VALIDATE
: V A L I D A T E
;
VALUE
: V A L U E
;
VARYING
: V A R Y I N G
;
VIRTUAL
: V I R T U A L
;
WAIT
: W A I T
;
WHEN
: W H E N
;
WRITE
: W R I T E
;
ZONE
: Z O N E
;
|
remove common keyword
|
remove common keyword
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
|
58703df046e500da66c7ab682adbd1a27260f94d
|
cto/CtoLexer.g4
|
cto/CtoLexer.g4
|
/*
[The "BSD licence"]
Copyright (c) 2018 Mario Schroeder
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 Hyperledger Composer Modeling Language
https://hyperledger.github.io/composer/latest/reference/cto_language.html
*/
lexer grammar CtoLexer;
// Keywords
ABSTRACT: 'abstract';
ASSET: 'asset';
CONCEPT: 'concept';
DEFAULT: 'default';
ENUM: 'enum';
EVENT: 'event';
EXTENDS: 'extends';
IDENTIFIED: 'identified by';
IMPORT: 'import';
NAMESPACE: 'namespace';
OPTIONAL: 'optional';
PARTICIPANT: 'participant';
RANGE: 'range';
REGEX: 'regex';
TRANSACTION: 'transaction';
//primitive types
BOOLEAN: 'Boolean';
DATE_TIME: 'DateTime';
DOUBLE: 'Double';
INTEGER: 'Integer';
LONG: 'Long';
STRING: 'String';
// Separators
LPAREN: '(';
RPAREN: ')';
LBRACE: '{';
RBRACE: '}';
LBRACK: '[';
RBRACK: ']';
SEMI: ';';
COMMA: ',';
DOT: '.';
COLON: ':';
// Operators
ASSIGN: '=';
MUL: '*';
// Additional symbols
AT: '@';
ELLIPSIS: '...';
REF: '--> ';
VAR: 'o ';
// Literals
DECIMAL_LITERAL: ('0' | [1-9] (Digits? | '_'+ Digits)) [lL]?;
OCT_LITERAL: '0' '_'* [0-7] ([0-7_]* [0-7])? [lL]?;
FLOAT_LITERAL: (Digits '.' Digits? | '.' Digits) ExponentPart? [fFdD]?
| Digits (ExponentPart [fFdD]? | [fFdD])
;
BOOL_LITERAL: 'true'
| 'false'
;
DATE_TIME_LITERAL: Bound FullDate 'T' FullTime Bound;
// Whitespace and comments
WS: [ \t\r\n\u000C]+ -> channel(HIDDEN);
LINE_COMMENT: '//' ~[\r\n]* -> channel(HIDDEN);
COMMENT: '/*' .*? '*/' -> channel(HIDDEN);
EOL: [\r\n];
//REGEX Expr
REGEX_EXPR: '/'.*?'/';
fragment Bound: '"' | '\'';
fragment FullDate: Year '-' Month '-' Day;
fragment Year: Digit Digit Digit Digit;
fragment Month: [0][0-9]|[1][0-2];
fragment Day: [0-2][0-9]|[0-3][01];
fragment FullTime
: PartialTime TimeOffset;
fragment TimeOffset
: 'Z' | TimeNumOffset;
fragment TimeNumOffset
: '-' [01][0-2] (':' (HalfHour))?
| '+' [01][0-5] (':' (HalfHour | [4][5]))?
;
fragment HalfHour: [0][0] | [3][0];
fragment PartialTime
: [0-2][0-3] ':' Sixty ':' Sixty ('.' [0-9]*)?;
fragment Sixty: [0-5] Digit;
fragment Digit: [0-9];
IDENTIFIER: Letter LetterOrDigit*;
CHAR_LITERAL: '\'' (~["\\\r\n] | EscapeSequence)* '\'';
STRING_LITERAL: '"' (~["\\\r\n] | EscapeSequence)* '"';
// 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 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) 2018 Mario Schroeder
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 Hyperledger Composer Modeling Language
https://hyperledger.github.io/composer/latest/reference/cto_language.html
*/
lexer grammar CtoLexer;
// Keywords
ABSTRACT: 'abstract';
ASSET: 'asset';
CONCEPT: 'concept';
DEFAULT: 'default';
ENUM: 'enum';
EVENT: 'event';
EXTENDS: 'extends';
IDENTIFIED: 'identified by';
IMPORT: 'import';
NAMESPACE: 'namespace';
OPTIONAL: 'optional';
PARTICIPANT: 'participant';
RANGE: 'range';
REGEX: 'regex';
TRANSACTION: 'transaction';
//primitive types
BOOLEAN: 'Boolean';
DATE_TIME: 'DateTime';
DOUBLE: 'Double';
INTEGER: 'Integer';
LONG: 'Long';
STRING: 'String';
// Separators
LPAREN: '(';
RPAREN: ')';
LBRACE: '{';
RBRACE: '}';
LBRACK: '[';
RBRACK: ']';
SEMI: ';';
COMMA: ',';
DOT: '.';
COLON: ':';
// Operators
ASSIGN: '=';
MUL: '*';
// Additional symbols
AT: '@';
ELLIPSIS: '...';
REF: '--> ';
VAR: 'o ';
// Literals
DECIMAL_LITERAL: ('0' | [1-9] (Digits? | '_'+ Digits)) [lL]?;
OCT_LITERAL: '0' '_'* [0-7] ([0-7_]* [0-7])? [lL]?;
FLOAT_LITERAL: (Digits '.' Digits? | '.' Digits) ExponentPart? [fFdD]?
| Digits (ExponentPart [fFdD]? | [fFdD])
;
BOOL_LITERAL: 'true'
| 'false'
;
DATE_TIME_LITERAL: Bound FullDate 'T' FullTime Bound;
// Whitespace and comments
WS: [ \t\r\n\u000C]+ -> channel(HIDDEN);
LINE_COMMENT: '//' ~[\r\n]* -> channel(HIDDEN);
COMMENT: '/*' .*? '*/' -> channel(HIDDEN);
EOL: [\r\n];
//REGEX Expr
REGEX_EXPR: '/'.*?'/';
fragment Bound: '"' | '\'';
fragment FullDate: Year '-' Month '-' Day;
fragment Year: Digit Digit Digit Digit;
fragment Month: [0][0-9]|[1][0-2];
fragment Day: [0-2][0-9]|[0-3][01];
fragment FullTime
: PartialTime TimeOffset;
fragment TimeOffset
: 'Z' | TimeNumOffset;
fragment TimeNumOffset
: '-' [01][0-2] (':' (HalfHour))?
| '+' [01][0-5] (':' (HalfHour | [4][5]))?
;
fragment HalfHour: [0][0] | [3][0];
fragment PartialTime
: [0-2][0-3] ':' Sixty ':' Sixty ('.' [0-9]*)?;
fragment Sixty: [0-5] Digit;
fragment Digit: [0-9];
IDENTIFIER: LetterOrDigit*;
CHAR_LITERAL: '\'' (~["\\\r\n] | EscapeSequence)* '\'';
STRING_LITERAL: '"' (~["\\\r\n] | EscapeSequence)* '"';
// 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 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
;
|
remove letter
|
remove letter
|
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
|
bf1c3f03fa6740f0e59eec78f411bbfe2404dabf
|
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)* (',')? )? '}'
;
program : 'Main ' '{' signalDeclaration* variableDeclaration* blockStatement* '}';
blockStatement
: atom #AtomPro // Atomic
| blockStatement '|' blockStatement #NonCh // non-deterministrate choice
| blockStatement '||' blockStatement #ParaCom // parallel composition
| blockStatement ';' blockStatement #SeqCom // sequential composition
| '(' blockStatement '<' expr '>' blockStatement ')' #ConCh // conditional choice
| equation 'until' guard #Ode // differential equation
| 'when' '(' guardedchoice ')' #WhenPro // when program
| 'while' parExpression parStatement #LoopPro // loop
| 'if' parExpression parStatement
'else' parStatement #IfPro // if statement
| ID '(' exprList? ')' #CallTem // call template
| parStatement #ParPro // program with paraentheses outside
;
parStatement
: '{' blockStatement '}'
| '(' blockStatement ')'
;
exprList
: expr (',' expr)* ; // arg list
atom
: 'skip'
| ID ':=' expr
| '!' ID
| 'suspend' '(' time=expr ')'
;
expr
: ID
| INT
| FLOAT
|'true'
| 'false'
| ('-' | '~') expr // negtive and negation
| expr ('*'|'/'|'mod') expr // % is mod
| expr ('+'|'-') expr
| expr ('>=' | '>' | '==' | '<' | '<=') expr
| expr 'and' expr
| expr 'or' expr
| 'floor' '(' expr ')'
| 'ceil' '(' expr ')'
;
parExpression
: '(' expr ')'
;
equation
: relation
| relation 'init' expr
| equation '||' equation
;
relation
: 'dot' ID '=' expr;
guard
: 'eps'
| signal
| expr
| 'timeout' '(' expr ')'
| guard '<and>' guard
| guard '<or>' guard
| '(' guard ')'
;
signal
: ID ('[' expr ']')?;
guardedchoice
: guard '&' program
| guardedchoice '[]' guardedchoice
;
COMOP
: '>='
| '>'
| '=='
| '<'
| '<='
;
ID : (LETTER | '_') (LETTER|DIGIT|'_')*
;
fragment LETTER : [a-zA-Z] ;
INT : DIGIT+ ;
FLOAT : DIGIT+ '.' DIGIT+
;
fragment
DIGIT: '0'..'9' ;
COMMENT
: '/*' .*? '*/' -> channel(HIDDEN) // match anything between /* and */
;
LINE_COMMENT
: '//' ~[\r\n]* '\r'? '\n' -> channel(HIDDEN)
;
WS : [ \r\t\u000C\n]+ -> channel(HIDDEN)
;
|
grammar HML;
hybridModel
: signalDeclaration* variableDeclaration* template* program EOF;
template
: 'Template' ID formalParameters parStatement;
formalParameters
: '(' formalParameterDecls? ')'
;
formalParameterDecls
: type formalParameterDeclsRest
;
formalParameterDeclsRest
: variableDeclaratorId (',' formalParameterDecls)?
;
variableDeclaratorId
: ID ('[' ']')*
;
type
: primitiveType ('[' ']')*
;
primitiveType
: 'boolean'
| 'int'
| 'float'
;
signalDeclaration
: 'Signal' ('[' size=INT ']')? ID (',' ID)* ';'
;
modifier
: 'final' // used for the vars that cannot be modified
;
variableDeclaration
: modifier? type variableDeclarators ';'
;
variableDeclarators
: variableDeclarator (',' variableDeclarator)*
;
variableDeclarator
: variableDeclaratorId ('=' variableInitializer)?
;
variableInitializer
: arrayInitializer
| expr
;
arrayInitializer
: '{' (variableInitializer (',' variableInitializer)* (',')? )? '}'
;
program : 'Main ' '{' signalDeclaration* variableDeclaration* blockStatement* '}';
blockStatement
: atom #AtomPro // Atomic
| blockStatement '|' blockStatement #NonCh // non-deterministrate choice
| blockStatement '||' blockStatement #ParaCom // parallel composition
| blockStatement ';' blockStatement #SeqCom // sequential composition
| '(' blockStatement '<' expr '>' blockStatement ')' #ConCh // conditional choice
| equation 'until' guard #Ode // differential equation
| 'when' '(' guardedchoice ')' #WhenPro // when program
| 'while' parExpression parStatement #LoopPro // loop
| 'if' parExpression parStatement
'else' parStatement #IfPro // if statement
| ID '(' exprList? ')' #CallTem // call template
| parStatement #ParPro // program with paraentheses outside
;
parStatement
: '{' blockStatement '}'
| '(' blockStatement ')'
;
exprList
: expr (',' expr)* ; // arg list
atom
: 'skip'
| ID ':=' expr
| '!' ID
| 'suspend' '(' time=expr ')'
;
expr
: ID
| INT
| FLOAT
|'true'
| 'false'
| ('-' | '~') expr // negtive and negation
| expr ('*'|'/'|'mod') expr // % is mod
| expr ('+'|'-') expr
| expr ('>=' | '>' | '==' | '<' | '<=') expr
| expr 'and' expr
| expr 'or' expr
| 'floor' '(' expr ')'
| 'ceil' '(' expr ')'
;
parExpression
: '(' expr ')'
;
equation
: relation
| relation 'init' expr
| equation '||' equation
;
relation
: 'dot' ID '=' expr;
guard
: 'eps'
| signal
| expr
| 'timeout' '(' expr ')'
| guard '<and>' guard
| guard '<or>' guard
| '(' guard ')'
;
signal
: ID ('[' expr ']')*;
guardedchoice
: guard '&' program
| guardedchoice '[]' guardedchoice
;
COMOP
: '>='
| '>'
| '=='
| '<'
| '<='
;
ID : (LETTER | '_') (LETTER|DIGIT|'_')*
;
fragment LETTER : [a-zA-Z] ;
INT : DIGIT+ ;
FLOAT : DIGIT+ '.' DIGIT+
;
fragment
DIGIT: '0'..'9' ;
COMMENT
: '/*' .*? '*/' -> channel(HIDDEN) // match anything between /* and */
;
LINE_COMMENT
: '//' ~[\r\n]* '\r'? '\n' -> channel(HIDDEN)
;
WS : [ \r\t\u000C\n]+ -> channel(HIDDEN)
;
|
add multi-array supporting for signals
|
add multi-array supporting for signals
|
ANTLR
|
mit
|
fanghuixing/HML
|
cf2ebcbfe310e50a7386d3e67db262bdadc19419
|
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 nl_or_comment ',' array_values comment_or_nl) | comment_or_nl value nl_or_comment ','? ;
comment_or_nl : (COMMENT? NL)* ;
nl_or_comment : (NL COMMENT?)* ;
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 nl_or_comment ',' array_values comment_or_nl) | comment_or_nl value nl_or_comment ','? ;
comment_or_nl : (COMMENT? NL)* ;
nl_or_comment : (NL COMMENT?)* ;
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 space in addition to T and t as time separator
|
[TOML] allow space in addition to T and t as time separator
|
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
|
b944390b0be2117038d8e53bbb05ff29dc095416
|
dsl-parser/src/main/antlr4/com/mattunderscore/specky/parser/SpeckyLexer.g4
|
dsl-parser/src/main/antlr4/com/mattunderscore/specky/parser/SpeckyLexer.g4
|
/* Copyright © 2016 Matthew Champion
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of mattunderscore.com nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL MATTHEW CHAMPION BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
lexer grammar SpeckyLexer;
fragment
UpperCaseLetter
: [A-Z]
;
fragment
Letter
: [a-zA-Z$_]
| ~[\u0000-\u007F\uD800-\uDBFF]
{Character.isJavaIdentifierStart(_input.LA(-1))}?
| [\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 "java letters or digits" below 0x7F
| ~[\u0000-\u007F\uD800-\uDBFF]
{Character.isJavaIdentifierPart(_input.LA(-1))}?
| [\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
SECTION
: 'section'
;
LICENCE
: 'licence'
;
VALUE
: 'value'
;
BEAN
: 'bean'
;
TYPE
: 'type'
;
CONSTRUCTOR
: 'constructor'
;
MUTABLE_BUILDER
: 'builder'
;
IMMUTABLE_BUILDER
: 'immutable builder'
;
FROM_DEFAULTS
: 'from defaults'
;
WITH_MODIFICATION
: 'with modification'
;
OPTIONAL
: 'optional'
;
OPEN_TYPE_PARAMETERS
: '<'
;
CLOSE_TYPE_PARAMETERS
: '>'
;
PACKAGE
: 'package'
;
PACKAGE_SEPARATOR
: '.'
;
DEFAULT
: 'default' -> pushMode(LITERAL)
;
OPTIONS
: 'options'
;
EXTENDS
: ':'
;
IMPORT
: 'imports'
;
PROPERTIES
: 'properties'
;
AUTHOR
: 'author'
;
COPYRIGHT_HOLDER
: 'copyright holder'
;
NOTE
: 'note'
;
INLINE_WS
: [ ]+ -> channel(HIDDEN)
;
LINE_BREAK
: ('\n' | '\r\n') -> channel(HIDDEN)
;
LINE_COMMENT
: '//' ~[\r\n]* -> skip
;
QUALIFIED_NAME
: Letter LetterOrDigit* (PACKAGE_SEPARATOR LetterOrDigit+)+
;
Identifier
: Letter LetterOrDigit*
;
CONSTRAINT_EXPRESSION
: '[constraint' -> pushMode(CONSTRAINT_MODE)
;
STRING_START
: '"' -> more, pushMode(STR)
;
MULTILINE_STRING_START
: '"""' -> more, pushMode(ML_STR)
;
mode STR;
STRING_LITERAL
: '"' -> popMode
;
STR_TEXT
: ~[\r\n] -> more
;
mode ML_STR;
MULTILINE_STRING_LITERAL
: '"""' -> popMode
;
ML_STR_TEXT
: . -> more
;
mode LITERAL;
LITERAL_INLINE_WS
: [ ]+ -> channel(HIDDEN)
;
ANYTHING
: ~[ \t\r\n\u000C]+ -> popMode
;
mode CONSTRAINT_MODE;
CONSTRAINT_INLINE_WS
: [ ]+ -> channel(HIDDEN)
;
GREATER_THAN_OR_EQUAL
: '>='
;
LESS_THAN_OR_EQUAL
: '<='
;
GREATER_THAN
: '>'
;
LESS_THAN
: '<'
;
CONJUNCTION
: '&'
;
DISJUNCTION
: '|'
;
SIZE_OF
: '#'
;
HAS_SOME
: 'e'
;
REAL_LITERAL
: ('+'|'-')? [0-9]* '.' [0-9]+
;
INTEGER_LITERAL
: ('+'|'-')? [0-9]+
;
CONSTRAINT_STRING_LITERAL
: '"' ~[\r\n"]+ '"'
;
NEGATION
: '!'
;
OPEN_PARENTHESIS
: '('
;
CLOSE_PARENTHESIS
: ')'
;
EQUAL_TO
: '='
;
CONSTRAINT_END
: ']' -> popMode
;
|
/* Copyright © 2016 Matthew Champion
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of mattunderscore.com nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL MATTHEW CHAMPION BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
lexer grammar SpeckyLexer;
fragment
UpperCaseLetter
: [A-Z]
;
fragment
Letter
: [a-zA-Z$_]
| ~[\u0000-\u007F\uD800-\uDBFF]
{Character.isJavaIdentifierStart(_input.LA(-1))}?
| [\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 "java letters or digits" below 0x7F
| ~[\u0000-\u007F\uD800-\uDBFF]
{Character.isJavaIdentifierPart(_input.LA(-1))}?
| [\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
SECTION
: 'section'
;
LICENCE
: 'licence'
;
VALUE
: 'value'
;
BEAN
: 'bean'
;
TYPE
: 'type'
;
CONSTRUCTOR
: 'constructor'
;
MUTABLE_BUILDER
: 'builder'
;
IMMUTABLE_BUILDER
: 'immutable builder'
;
FROM_DEFAULTS
: 'from defaults'
;
WITH_MODIFICATION
: 'with modification'
;
OPTIONAL
: 'optional'
;
OPEN_TYPE_PARAMETERS
: '<'
;
CLOSE_TYPE_PARAMETERS
: '>'
;
PACKAGE
: 'package'
;
PACKAGE_SEPARATOR
: '.'
;
DEFAULT
: 'default' -> pushMode(LITERAL)
;
OPTIONS
: 'options'
;
EXTENDS
: ':'
;
IMPORT
: 'imports'
;
PROPERTIES
: 'properties'
;
AUTHOR
: 'author'
;
COPYRIGHT_HOLDER
: 'copyright holder'
;
NOTE
: 'note'
;
INLINE_WS
: [ ]+ -> channel(HIDDEN)
;
LINE_BREAK
: ('\n' | '\r\n') -> channel(HIDDEN)
;
LINE_COMMENT
: '//' ~[\r\n]* -> skip
;
QUALIFIED_NAME
: Letter LetterOrDigit* (PACKAGE_SEPARATOR LetterOrDigit+)+
;
Identifier
: Letter LetterOrDigit*
;
INLINE_EXPRESSION
: '[' -> more, pushMode(EXPRESSION_MODE)
;
STRING_START
: '"' -> more, pushMode(STR)
;
MULTILINE_STRING_START
: '"""' -> more, pushMode(ML_STR)
;
mode EXPRESSION_MODE;
CONSTRAINT_EXPRESSION
: 'constraint' -> mode(CONSTRAINT_MODE)
;
mode STR;
STRING_LITERAL
: '"' -> popMode
;
STR_TEXT
: ~[\r\n] -> more
;
mode ML_STR;
MULTILINE_STRING_LITERAL
: '"""' -> popMode
;
ML_STR_TEXT
: . -> more
;
mode LITERAL;
LITERAL_INLINE_WS
: [ ]+ -> channel(HIDDEN)
;
ANYTHING
: ~[ \t\r\n\u000C]+ -> popMode
;
mode CONSTRAINT_MODE;
CONSTRAINT_INLINE_WS
: [ ]+ -> channel(HIDDEN)
;
GREATER_THAN_OR_EQUAL
: '>='
;
LESS_THAN_OR_EQUAL
: '<='
;
GREATER_THAN
: '>'
;
LESS_THAN
: '<'
;
CONJUNCTION
: '&'
;
DISJUNCTION
: '|'
;
SIZE_OF
: '#'
;
HAS_SOME
: 'e'
;
REAL_LITERAL
: ('+'|'-')? [0-9]* '.' [0-9]+
;
INTEGER_LITERAL
: ('+'|'-')? [0-9]+
;
CONSTRAINT_STRING_LITERAL
: '"' ~[\r\n"]+ '"'
;
NEGATION
: '!'
;
OPEN_PARENTHESIS
: '('
;
CLOSE_PARENTHESIS
: ')'
;
EQUAL_TO
: '='
;
CONSTRAINT_END
: ']' -> popMode
;
|
Support different expression parsing modes.
|
Support different expression parsing modes.
|
ANTLR
|
bsd-3-clause
|
mattunderscorechampion/specky,mattunderscorechampion/specky,mattunderscorechampion/specky
|
5b35354441d1c546e75b595582d7987dd43ec81f
|
powerbuilder/powerbuilderParser.g4
|
powerbuilder/powerbuilderParser.g4
|
/*
BSD License
Copyright (c) 2018, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
parser grammar powerbuilderParser;
options
{ tokenVocab = powerbuilderLexer; }
start_rule
: header_rule? body_rule + EOF
;
header_rule
: EXPORT_HEADER* release_information? window_property*
;
body_rule
: datatype_decl
| access_modif
| forward_decl
| type_variables_decl
| global_variables_decl
| variable_decl
| constant_decl
| function_forward_decl
| functions_forward_decl
| function_body
| on_body
| event_body
;
release_information
: RELEASE NUMBER SEMI
;
window_property
: (attribute_name array_decl_sub? LPAREN window_property_attributes_sub? RPAREN)
;
window_property_attributes_sub
: window_property_attribute_sub +
;
window_property_attribute_sub
: ((NULL | numeric_atom | DQUOTED_STRING | DATE | TIME) COMMA?)
| (attribute_name eq = EQ (attribute_value array_decl_sub? | LPAREN window_property_attributes_sub RPAREN)) COMMA?
;
attribute_name
: (identifier_name | TYPE | UPDATE) NUMBER? (DOT (identifier_name | CASE | TYPE | ON | DYNAMIC))*
;
attribute_value
: (atom_sub_call1)
| (atom_sub_member1)
| (MINUS)? numeric_atom
| boolean_atom
| ENUM
| DQUOTED_STRING
| QUOTED_STRING
| DATE
| TIME
| TYPE
| TO
| FROM
| REF
| NULL
| OPEN
| LPAREN LPAREN (expression | data_type_sub) (COMMA (expression | data_type_sub))? RPAREN (COMMA LPAREN (expression | data_type_sub) (COMMA (expression | data_type_sub))? RPAREN)* RPAREN
| data_type_sub (LPAREN NUMBER RPAREN)?
;
forward_decl
: FORWARD (datatype_decl | variable_decl) + END FORWARD
;
datatype_decl
: scope_modif? TYPE identifier_name FROM (identifier_name TICK)? data_type_name (WITHIN identifier_name)? (AUTOINSTANTIATE)? (DESCRIPTOR DQUOTED_STRING EQ DQUOTED_STRING)? (variable_decl | event_forward_decl)* END TYPE
;
type_variables_decl
: TYPE VARIABLES (access_modif | variable_decl | constant_decl)* END VARIABLES
;
global_variables_decl
: (GLOBAL | SHARED) VARIABLES (variable_decl | constant_decl)* END VARIABLES
;
variable_decl_sub
: (INDIRECT)? access_modif_part? scope_modif?
;
variable_decl
: variable_decl_sub (SEMI)
;
decimal_decl_sub
: LCURLY NUMBER RCURLY
;
array_decl_sub
: BRACES
| LBRACE ((PLUS | MINUS)? NUMBER (TO (PLUS | MINUS)? NUMBER)? (COMMA (PLUS | MINUS)? NUMBER (TO (PLUS | MINUS)? NUMBER)?)*)? RBRACE
;
constant_decl_sub
:
// TODO EQ is mandatory for constants 'CONSTANT' variable_decl_sub
;
constant_decl
: constant_decl_sub SEMI
;
function_forward_decl
: access_modif_part? scope_modif? (FUNCTION data_type_name | SUBROUTINE) identifier_name LPAREN parameters_list_sub? RPAREN (LIBRARY (DQUOTED_STRING | QUOTED_STRING) (ALIAS FOR (DQUOTED_STRING | QUOTED_STRING))?)? (RPCFUNC ALIAS FOR (DQUOTED_STRING | QUOTED_STRING))? (THROWS identifier_name)?
;
parameter_sub
: READONLY? REF? data_type_name decimal_decl_sub? identifier_name array_decl_sub?
;
parameters_list_sub
: parameter_sub (COMMA parameter_sub)* (COMMA DOTDOTDOT)?
;
functions_forward_decl
: (FORWARD | TYPE) PROTOTYPES function_forward_decl + END PROTOTYPES
;
function_body
: access_type? scope_modif? (FUNCTION data_type_name | SUBROUTINE) identifier_name LPAREN parameters_list_sub? RPAREN (THROWS identifier_name)? (SEMI statement)* END (FUNCTION | SUBROUTINE)
;
on_body
: ON (identifier | OPEN | CLOSE)
;
event_forward_decl_sub
: EVENT (identifier_name | CREATE | DESTROY) identifier_name? (LPAREN parameters_list_sub? RPAREN)?
| EVENT TYPE data_type_name identifier_name (LPAREN parameters_list_sub? RPAREN)
;
event_forward_decl
: event_forward_decl_sub
;
event_body
: EVENT (TYPE data_type_name)? (identifier_name COLONCOLON)? (identifier_name | OPEN | CLOSE) (LPAREN parameters_list_sub? RPAREN)? (SEMI statement)* END EVENT
;
access_type
: PUBLIC
| PRIVATE
| PROTECTED
;
access_modif
: access_type ':'
;
access_modif_part
: PUBLIC
| PRIVATE
| PRIVATEREAD
| PRIVATEWRITE
| PROTECTED
| PROTECTEDREAD
| PROTECTEDWRITE
;
scope_modif
: GLOBAL
| LOCAL
;
expression
: (close_call_sub)
| (LCURLY)
;
expression_list
: (REF? expression) (COMMA REF? expression)*
;
boolean_expression
: condition_or
;
condition_or
: condition_and (OR condition_and)*
;
condition_and
: condition_not (AND condition_not)*
;
condition_not
: (NOT)? condition_comparison
;
condition_comparison
: add_expr ((EQ | GT | LT | GTLT | GTE | LTE) add_expr)?
;
add_expr
: mul_expr ((MINUS | PLUS) mul_expr)*
;
mul_expr
: unary_sign_expr ((MULT | DIV | CARAT) unary_sign_expr)*
;
unary_sign_expr
: (LPAREN expression RPAREN)
| (MINUS | PLUS)? atom
;
statement
: (if_simple_statement)
| (DESCRIBE identifier_name)
| (assignment_statement)
| (statement_sub SEMI)
| (if_statement)
| (TRY)
| (post_event)
| (function_call_statement)
| (event_call_statement)
| (constant_decl)
| (variable_decl)
| (super_call_statement)
| (do_loop_while_statement)
| (do_while_loop_statement)
| (create_call_statement)
| (destroy_call_statement)
| (label_stat)
| (identifier)
| throw_stat
| goto_stat
| choose_statement
| return_statement
| for_loop_statement
| continue_statement
| exit_statement
| atom
;
statement_sub
: (function_virtual_call_expression_sub)
| (function_call_expression_sub)
| (return_sub)
| (open_call_sub)
| (close_call_sub)
| (variable_decl_sub)
| (super_call_sub)
| (create_call_sub)
| (destroy_call_sub)
| (continue_sub)
| (goto_stat_sub)
| (assignment_sub)
;
assignment_sub
: lvalue_sub (EQ | PLUSEQ | MINUSEQ | MULTEQ | DIVEQ) ((NOT) | (LCURLY) | (boolean_expression) | expression)
;
assignment_statement
: assignment_sub SEMI?
;
lvalue_sub
: (atom_sub (DOT identifier_name_ex))
| (atom_sub_call1)
| (atom_sub_array1)
| (atom_sub_ref1)
| (atom_sub_member1)
;
return_sub
: RETURN expression?
;
return_statement
: return_sub
;
function_call_expression_sub
: (atom_sub (DOT identifier_name_ex))
| atom_sub_call1
;
function_virtual_call_expression_sub
: identifier_name DOT DYNAMIC (EVENT)? function_call_expression_sub
| identifier_name DOT EVENT DYNAMIC function_call_expression_sub
;
open_call_sub
: OPEN LPAREN expression_list RPAREN
;
close_call_sub
: CLOSE LPAREN expression_list RPAREN
| HALT CLOSE
;
function_call_statement
: (function_call_expression_sub | function_virtual_call_expression_sub | open_call_sub | close_call_sub)
;
super_call_sub
: CALL (identifier_name TICK)? ((atom_sub_call1) | atom_sub_member1)
;
super_call_statement
: super_call_sub
;
event_call_statement_sub
: ((identifier_name DOT (identifier_name DOT)?) | (SUPER COLONCOLON))? EVENT atom_sub_call1
;
event_call_statement
: event_call_statement_sub
;
create_call_sub
: CREATE (USING)? (identifier_name DOT)? data_type_name (LPAREN expression_list? RPAREN)?
;
create_call_statement
: create_call_sub
;
destroy_call_sub
: DESTROY expression
;
destroy_call_statement
: destroy_call_sub
;
for_loop_statement
: FOR lvalue_sub EQ expression TO expression (STEP expression)? statement NEXT
;
do_while_loop_statement
: DO (WHILE | UNTIL) boolean_expression statement* LOOP
;
do_loop_while_statement
: DO statement* LOOP (WHILE | UNTIL) boolean_expression
;
if_statement
: IF boolean_expression THEN statement* (ELSEIF boolean_expression THEN statement*)* (ELSE statement*)? END IF (SEMI |)
;
if_simple_statement
: IF boolean_expression THEN statement
;
continue_sub
: CONTINUE
;
continue_statement
: continue_sub
;
post_event_sub
: (atom_sub_member1 DOT)? (POST | TRIGGER) (EVENT)? identifier_name_ex LPAREN expression_list? RPAREN
;
post_event
: post_event_sub
;
exit_statement_sub
: EXIT
;
exit_statement
: exit_statement_sub
;
choose_statement
: CHOOSE CASE expression ((choose_case_range_sub) | (choose_case_cond_sub) | (choose_case_else_sub) | choose_case_value_sub) + END CHOOSE
;
choose_case_value_sub
: CASE expression (COMMA expression)* statement*
;
choose_case_cond_sub
: CASE IS (EQ | GT | LT | GTLT | GTE | LTE) expression statement*
;
choose_case_range_sub
: CASE atom TO atom statement*
;
choose_case_else_sub
: CASE ELSE statement*
;
goto_stat_sub
: GOTO identifier_name
;
goto_stat
: goto_stat_sub
;
label_stat
: identifier_name COLON
;
try_catch_block
: TRY statement* (CATCH LPAREN variable_decl_sub RPAREN statement*)* (FINALLY statement*)? END TRY
;
throw_stat_sub
: THROW expression
;
throw_stat
: throw_stat_sub
;
identifier
: identifier_name
| SUPER COLONCOLON (CREATE | DESTROY | identifier_name_ex)
| identifier_name COLONCOLON (CREATE | DESTROY)
| identifier_name DOT (CREATE | DESTROY)
| identifier_name COLONCOLON identifier_name_ex
;
identifier_name
: ID
;
identifier_name_ex
: identifier_name
| SELECT
| TYPE
| UPDATE
| DELETE
| OPEN
| CLOSE
| GOTO
| INSERT
| DESCRIBE
| TIME2
| READONLY
;
atom_sub
: (((array_access_atom) | (identifier_name LPAREN expression_list? RPAREN) | identifier_name))
;
atom_sub_call1
: (identifier | DESCRIBE) LPAREN expression_list? RPAREN
;
atom_sub_array1
: identifier_name LBRACE expression_list RBRACE
;
atom_sub_ref1
: identifier_name BRACES
;
atom_sub_member1
: identifier
;
atom
: (event_call_statement_sub)
| (atom_sub (DOT identifier_name_ex))
| (cast_expression)
| (atom_sub_call1)
| (atom_sub_array1)
| (atom_sub_ref1)
| (atom_sub_member1)
| numeric_atom
| boolean_atom
| ENUM
| DQUOTED_STRING
| QUOTED_STRING
| DATE
| TIME
;
array_access_atom
: identifier_name LBRACE expression_list RBRACE
;
numeric_atom
: NUMBER
;
boolean_atom
: BOOLEAN_ATOM
;
cast_expression
: data_type_sub LPAREN expression (COMMA expression)* RPAREN
;
data_type_sub
: DATA_TYPE_SUB
;
data_type_name
: data_type_sub
| identifier_name
;
|
/*
BSD License
Copyright (c) 2018, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
parser grammar powerbuilderParser;
options { tokenVocab = powerbuilderLexer; }
start_rule
: header_rule? body_rule+ EOF
;
header_rule
: EXPORT_HEADER* (RELEASE NUMBER SEMI)? window_property+
;
body_rule
: datatype_decl
| access_modif
| forward_decl
| type_variables_decl
| global_variables_decl
| variable_decl
| constant_decl
| function_forward_decl
| functions_forward_decl
| function_body
| on_body
| event_body
;
window_property
: attribute_name array_decl_sub? LPAREN window_property_attribute_sub* RPAREN
;
window_property_attribute_sub
: ( NULL
| numeric_atom
| DQUOTED_STRING
| DATE
| TIME
| attribute_name eq=EQ (attribute_value array_decl_sub? | LPAREN window_property_attribute_sub+ RPAREN)
) COMMA?
;
attribute_name
: (identifier_name | TYPE | UPDATE) NUMBER? (DOT (identifier_name | CASE | TYPE | ON | DYNAMIC))*
;
attribute_value
: atom_sub_call1
| atom_sub_member1
| MINUS? numeric_atom
| boolean_atom
| ENUM
| DQUOTED_STRING
| QUOTED_STRING
| DATE
| TIME
| TYPE
| TO
| FROM
| REF
| NULL
| OPEN
| LPAREN LPAREN (expression | DATA_TYPE_SUB) (COMMA (expression | DATA_TYPE_SUB))? RPAREN (COMMA LPAREN (expression | DATA_TYPE_SUB) (COMMA (expression | DATA_TYPE_SUB))? RPAREN)* RPAREN
| DATA_TYPE_SUB (LPAREN NUMBER RPAREN)?
;
forward_decl
: FORWARD (datatype_decl | variable_decl)+ END FORWARD
;
datatype_decl
: scope_modif? TYPE identifier_name FROM (identifier_name TICK)? data_type_name (WITHIN identifier_name)? AUTOINSTANTIATE? (DESCRIPTOR DQUOTED_STRING EQ DQUOTED_STRING)?
(variable_decl | event_forward_decl)*
END TYPE
;
type_variables_decl
: TYPE VARIABLES (access_modif | variable_decl | constant_decl)* END VARIABLES
;
global_variables_decl
: (GLOBAL | SHARED) VARIABLES (variable_decl | constant_decl)* END VARIABLES
;
variable_decl
: variable_decl_sub SEMI
;
variable_decl_sub
: INDIRECT? access_modif_part? scope_modif?
;
decimal_decl_sub
: LCURLY NUMBER RCURLY
;
array_decl_sub
: BRACES
| LBRACE ((PLUS | MINUS)? NUMBER (TO (PLUS | MINUS)? NUMBER)? (COMMA (PLUS | MINUS)? NUMBER (TO (PLUS | MINUS)? NUMBER)?)*)? RBRACE
;
constant_decl_sub
:
// TODO EQ is mandatory for constants 'CONSTANT' variable_decl_sub
;
constant_decl
: constant_decl_sub SEMI
;
function_forward_decl
: access_modif_part? scope_modif? (FUNCTION data_type_name | SUBROUTINE) identifier_name LPAREN parameters_list_sub? RPAREN (LIBRARY (DQUOTED_STRING | QUOTED_STRING) (ALIAS FOR (DQUOTED_STRING | QUOTED_STRING))?)? (RPCFUNC ALIAS FOR (DQUOTED_STRING | QUOTED_STRING))? (THROWS identifier_name)?
;
parameter_sub
: READONLY? REF? data_type_name decimal_decl_sub? identifier_name array_decl_sub?
;
parameters_list_sub
: parameter_sub (COMMA parameter_sub)* (COMMA DOTDOTDOT)?
;
functions_forward_decl
: (FORWARD | TYPE) PROTOTYPES function_forward_decl+ END PROTOTYPES
;
function_body
: access_type? scope_modif? (FUNCTION data_type_name | SUBROUTINE) identifier_name LPAREN parameters_list_sub? RPAREN (THROWS identifier_name)? (SEMI statement)* END (FUNCTION | SUBROUTINE)
;
on_body
: ON (identifier | OPEN | CLOSE)
;
event_forward_decl
: EVENT (identifier_name | CREATE | DESTROY) identifier_name? (LPAREN parameters_list_sub? RPAREN)?
| EVENT TYPE data_type_name identifier_name (LPAREN parameters_list_sub? RPAREN)
;
event_body
: EVENT (TYPE data_type_name)? (identifier_name COLONCOLON)? (identifier_name | OPEN | CLOSE) (LPAREN parameters_list_sub? RPAREN)? (SEMI statement)* END EVENT
;
access_type
: PUBLIC
| PRIVATE
| PROTECTED
;
access_modif
: access_type ':'
;
access_modif_part
: PUBLIC
| PRIVATE
| PRIVATEREAD
| PRIVATEWRITE
| PROTECTED
| PROTECTEDREAD
| PROTECTEDWRITE
;
scope_modif
: GLOBAL
| LOCAL
;
expression
: close_call_sub
| LCURLY
;
expression_list
: (REF? expression) (COMMA REF? expression)*
;
boolean_expression
: condition_or
;
condition_or
: condition_and (OR condition_and)*
;
condition_and
: condition_not (AND condition_not)*
;
condition_not
: NOT? condition_comparison
;
condition_comparison
: add_expr ((EQ | GT | LT | GTLT | GTE | LTE) add_expr)?
;
add_expr
: mul_expr ((MINUS | PLUS) mul_expr)*
;
mul_expr
: unary_sign_expr ((MULT | DIV | CARAT) unary_sign_expr)*
;
unary_sign_expr
: (LPAREN expression RPAREN)
| (MINUS | PLUS)? atom
;
statement
: if_simple_statement
| DESCRIBE identifier_name
| assignment_statement
| statement_sub SEMI
| if_statement
| TRY
| post_event
| function_call_statement
| event_call_statement
| constant_decl
| variable_decl
| super_call_statement
| do_loop_while_statement
| do_while_loop_statement
| create_call_statement
| destroy_call_statement
| label_stat
| identifier
| throw_stat
| goto_stat
| choose_statement
| return_statement
| for_loop_statement
| continue_statement
| exit_statement
| atom
;
statement_sub
: function_virtual_call_expression_sub
| function_call_expression_sub
| return_statement
| open_call_sub
| close_call_sub
| variable_decl_sub
| super_call_statement
| create_call_sub
| destroy_call_sub
| continue_sub
| goto_stat
| assignment_sub
;
assignment_sub
: lvalue_sub (EQ | PLUSEQ | MINUSEQ | MULTEQ | DIVEQ) (NOT | LCURLY | boolean_expression | expression)
;
assignment_statement
: assignment_sub SEMI?
;
lvalue_sub
: atom_sub DOT identifier_name_ex
| atom_sub_call1
| atom_sub_array1
| atom_sub_ref1
| atom_sub_member1
;
return_statement
: RETURN expression?
;
function_call_expression_sub
: atom_sub DOT identifier_name_ex
| atom_sub_call1
;
function_virtual_call_expression_sub
: identifier_name DOT (DYNAMIC EVENT? | EVENT DYNAMIC) function_call_expression_sub
;
open_call_sub
: OPEN LPAREN expression_list RPAREN
;
close_call_sub
: CLOSE LPAREN expression_list RPAREN
| HALT CLOSE
;
function_call_statement
: function_call_expression_sub
| function_virtual_call_expression_sub
| open_call_sub
| close_call_sub
;
super_call_statement
: CALL (identifier_name TICK)? (atom_sub_call1 | atom_sub_member1)
;
event_call_statement_sub
: (identifier_name DOT (identifier_name DOT)? | SUPER COLONCOLON)? EVENT atom_sub_call1
;
event_call_statement
: event_call_statement_sub
;
create_call_sub
: CREATE USING? (identifier_name DOT)? data_type_name (LPAREN expression_list? RPAREN)?
;
create_call_statement
: create_call_sub
;
destroy_call_sub
: DESTROY expression
;
destroy_call_statement
: destroy_call_sub
;
for_loop_statement
: FOR lvalue_sub EQ expression TO expression (STEP expression)? statement NEXT
;
do_while_loop_statement
: DO (WHILE | UNTIL) boolean_expression statement* LOOP
;
do_loop_while_statement
: DO statement* LOOP (WHILE | UNTIL) boolean_expression
;
if_statement
: IF boolean_expression THEN statement* (ELSEIF boolean_expression THEN statement*)* (ELSE statement*)? END IF SEMI?
;
if_simple_statement
: IF boolean_expression THEN statement
;
continue_statement
: CONTINUE
;
continue_sub
: CONTINUE
;
post_event
: (atom_sub_member1 DOT)? (POST | TRIGGER) EVENT? identifier_name_ex LPAREN expression_list? RPAREN
;
exit_statement
: EXIT
;
choose_statement
: CHOOSE CASE expression ( choose_case_range_sub
| choose_case_cond_sub
| choose_case_else_sub
| choose_case_value_sub)+
END CHOOSE
;
choose_case_value_sub
: CASE expression (COMMA expression)* statement*
;
choose_case_cond_sub
: CASE IS (EQ | GT | LT | GTLT | GTE | LTE) expression statement*
;
choose_case_range_sub
: CASE atom TO atom statement*
;
choose_case_else_sub
: CASE ELSE statement*
;
goto_stat
: GOTO identifier_name
;
label_stat
: identifier_name COLON
;
try_catch_block
: TRY statement* (CATCH LPAREN variable_decl_sub RPAREN statement*)* (FINALLY statement*)? END TRY
;
throw_stat
: THROW expression
;
identifier
: identifier_name
| SUPER COLONCOLON (CREATE | DESTROY | identifier_name_ex)
| identifier_name COLONCOLON (CREATE | DESTROY)
| identifier_name DOT (CREATE | DESTROY)
| identifier_name COLONCOLON identifier_name_ex
;
identifier_name_ex
: identifier_name
| SELECT
| TYPE
| UPDATE
| DELETE
| OPEN
| CLOSE
| GOTO
| INSERT
| DESCRIBE
| TIME2
| READONLY
;
identifier_name
: ID
;
atom_sub
: array_access_atom
| identifier_name (LPAREN expression_list? RPAREN)?
;
atom_sub_call1
: (identifier | DESCRIBE) LPAREN expression_list? RPAREN
;
atom_sub_array1
: identifier_name LBRACE expression_list RBRACE
;
atom_sub_ref1
: identifier_name BRACES
;
atom_sub_member1
: identifier
;
atom
: event_call_statement_sub
| atom_sub (DOT identifier_name_ex)
| cast_expression
| atom_sub_call1
| atom_sub_array1
| atom_sub_ref1
| atom_sub_member1
| numeric_atom
| boolean_atom
| ENUM
| DQUOTED_STRING
| QUOTED_STRING
| DATE
| TIME
;
array_access_atom
: identifier_name LBRACE expression_list RBRACE
;
numeric_atom
: NUMBER
;
boolean_atom
: BOOLEAN_ATOM
;
cast_expression
: DATA_TYPE_SUB LPAREN expression (COMMA expression)* RPAREN
;
data_type_name
: DATA_TYPE_SUB
| identifier_name
;
|
Simplify powerbuilderParser grammar, remove useless parentheses
|
Simplify powerbuilderParser grammar, remove useless parentheses
|
ANTLR
|
mit
|
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
|
506ee1921cbdde108b764b2382625fc2343384af
|
Twee2Z/Analyzer/Twee.g4
|
Twee2Z/Analyzer/Twee.g4
|
parser grammar Twee;
options { tokenVocab = LEX; }
start
: ignoreFirst passage*
;
ignoreFirst
: passage
| ~PASS ignoreFirst
;
passage
: PASS PMODEWORD TAG? ~PMODE_END* PMODE_END passageContent?
;
passageContent
: (macro|text|link) passageContent?
;
link
: LINK_START ((LTARGET|LEXCLUDE)+ PIPE)? (FUNC_LINK|LTARGET) ((SQ_BRACKET_CLOSE SQ_BRACKET_OPEN expression)|LINK_END)
;
macro
: MACRO_START (DISPLAY|SET|PRINT) expression
| MACRO_START (ACTIONS text | CHOICE link?) MACRO_END
| macroBranchIf macroBranchIfElse* macroBranchElse? macroBranchPop
| MACRO_START NOBR MACRO_END passageContent MACRO_START ENDNOBR MACRO_END
| MACRO_START SILENTLY MACRO_END passageContent MACRO_START ENDSILENTLY MACRO_END
;
macroBranchIf
: MACRO_START IF expression passageContent
;
macroBranchIfElse
: MACRO_START ELSE_IF expression passageContent
;
macroBranchElse
: MACRO_START ELSE MACRO_END passageContent
;
macroBranchPop
: MACRO_START ENDIF MACRO_END
;
expression
: EXPRESSION
;
/*function
: (FUNC_START FUNC_BRACKET_OPEN (EXPRESSION|EXPRESSION FUNC_PARAM+)? FUNC_BRACKET_CLOSE)
;
variable
: VAR_NAME
;
*/
zeichenkette
: WORD+
;
text
: (zeichenkette|SPACE+|NEW_LINE|INT|FORMAT|EXCLUDE)
;
|
parser grammar Twee;
options { tokenVocab = LEX; }
start
: ignoreFirst passage*
;
ignoreFirst
: passage
| ~PASS ignoreFirst
;
passage
: PASS PMODEWORD TAG? ~PMODE_END* PMODE_END passageContent?
;
passageContent
: innerPassageContent+
;
innerPassageContent
: (macro|text|link)
;
link
: LINK_START ((LTARGET|LEXCLUDE)+ PIPE)? (FUNC_LINK|LTARGET) ((SQ_BRACKET_CLOSE SQ_BRACKET_OPEN expression)|LINK_END)
;
macro
: MACRO_START (DISPLAY|SET|PRINT) expression
| MACRO_START (ACTIONS text | CHOICE link?) MACRO_END
| macroBranchIf macroBranchIfElse* macroBranchElse? macroBranchPop
| MACRO_START NOBR MACRO_END passageContent MACRO_START ENDNOBR MACRO_END
| MACRO_START SILENTLY MACRO_END passageContent MACRO_START ENDSILENTLY MACRO_END
;
macroBranchIf
: MACRO_START IF expression passageContent
;
macroBranchIfElse
: MACRO_START ELSE_IF expression passageContent
;
macroBranchElse
: MACRO_START ELSE MACRO_END passageContent
;
macroBranchPop
: MACRO_START ENDIF MACRO_END
;
expression
: EXPRESSION
;
/*function
: (FUNC_START FUNC_BRACKET_OPEN (EXPRESSION|EXPRESSION FUNC_PARAM+)? FUNC_BRACKET_CLOSE)
;
variable
: VAR_NAME
;
*/
zeichenkette
: WORD+
;
text
: (zeichenkette|SPACE+|NEW_LINE|INT|FORMAT|EXCLUDE)
;
|
remove call stack overflow exception
|
remove call stack overflow exception
|
ANTLR
|
mit
|
humsp/uebersetzerbauSWP
|
dd24ba79d5167cc53e0b087143e0688ce3a3d873
|
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 (alterTableProperties | columnClauses | constraintClauses | alterExternalTable)?
;
// TODO hongjun throw exeption when alter index on oracle
alterIndex
: ALTER INDEX indexName (RENAME TO indexName)?
;
dropTable
: DROP TABLE tableName
;
dropIndex
: DROP INDEX indexName
;
truncateTable
: TRUNCATE TABLE tableName
;
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 LP_ columnSortClause_ (COMMA_ columnSortClause_)* RP_ FROM tableName alias? (COMMA_ tableName alias?)* WHERE expr
;
columnSortClause_
: tableName alias? columnName (ASC | DESC)?
;
tableProperties
: columnProperties? (AS unionSelect)?
;
unionSelect
: matchNone
;
alterTableProperties
: renameTableSpecification_ | REKEY encryptionSpecification_
;
renameTableSpecification_
: RENAME TO newTableName
;
newTableName
: IDENTIFIER_
;
columnClauses
: opColumnClause+ | renameColumnSpecification
;
opColumnClause
: addColumnSpecification | modifyColumnSpecification | dropColumnClause
;
addColumnSpecification
: ADD columnOrVirtualDefinitions columnProperties?
;
columnOrVirtualDefinitions
: LP_ columnOrVirtualDefinition (COMMA_ columnOrVirtualDefinition)* RP_ | columnOrVirtualDefinition
;
columnOrVirtualDefinition
: columnDefinition | virtualColumnDefinition
;
modifyColumnSpecification
: MODIFY (LP_? modifyColProperties (COMMA_ modifyColProperties)* RP_? | modifyColSubstitutable)
;
modifyColProperties
: columnName dataType? (DEFAULT expr)? (ENCRYPT 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_
;
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
constraintClauses
: addConstraintSpecification | modifyConstraintClause | renameConstraintClause | dropConstraintClause+
;
addConstraintSpecification
: ADD (outOfLineConstraint+ | outOfLineRefConstraint)
;
modifyConstraintClause
: MODIFY constraintOption constraintState+ CASCADE?
;
constraintWithName
: CONSTRAINT ignoredIdentifier_
;
constraintOption
: constraintWithName | constraintPrimaryOrUnique
;
constraintPrimaryOrUnique
: primaryKey | UNIQUE columnNames
;
renameConstraintClause
: RENAME constraintWithName TO ignoredIdentifier_
;
dropConstraintClause
: DROP
(
constraintPrimaryOrUnique CASCADE? ((KEEP | DROP) INDEX)? | (CONSTRAINT ignoredIdentifier_ CASCADE?)
)
;
alterExternalTable
: (addColumnSpecification | modifyColumnSpecification | dropColumnSpecification)+
;
objectProperties
: objectProperty (COMMA_ objectProperty)*
;
objectProperty
: (columnName | attributeName) (DEFAULT expr)? (inlineConstraint* | inlineRefConstraint?) | outOfLineConstraint | outOfLineRefConstraint
;
columnProperties
: columnProperty+
;
columnProperty
: objectTypeColProperties
;
objectTypeColProperties
: COLUMN columnName substitutableColumnClause
;
substitutableColumnClause
: ELEMENT? IS OF TYPE? LP_ ONLY? dataTypeName_ RP_ | NOT? SUBSTITUTABLE AT ALL LEVELS
;
|
/*
* 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 (alterTableProperties | columnClauses | constraintClauses | alterExternalTable)?
;
// TODO hongjun throw exeption when alter index on oracle
alterIndex
: ALTER INDEX indexName (RENAME TO indexName)?
;
dropTable
: DROP TABLE tableName
;
dropIndex
: DROP INDEX indexName
;
truncateTable
: TRUNCATE TABLE tableName
;
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?)*
;
tableProperties
: columnProperties? (AS unionSelect)?
;
unionSelect
: matchNone
;
alterTableProperties
: renameTableSpecification_ | REKEY encryptionSpecification_
;
renameTableSpecification_
: RENAME TO newTableName
;
newTableName
: IDENTIFIER_
;
columnClauses
: opColumnClause+ | renameColumnSpecification
;
opColumnClause
: addColumnSpecification | modifyColumnSpecification | dropColumnClause
;
addColumnSpecification
: ADD columnOrVirtualDefinitions columnProperties?
;
columnOrVirtualDefinitions
: LP_ columnOrVirtualDefinition (COMMA_ columnOrVirtualDefinition)* RP_ | columnOrVirtualDefinition
;
columnOrVirtualDefinition
: columnDefinition | virtualColumnDefinition
;
modifyColumnSpecification
: MODIFY (LP_? modifyColProperties (COMMA_ modifyColProperties)* RP_? | modifyColSubstitutable)
;
modifyColProperties
: columnName dataType? (DEFAULT expr)? (ENCRYPT 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_
;
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
constraintClauses
: addConstraintSpecification | modifyConstraintClause | renameConstraintClause | dropConstraintClause+
;
addConstraintSpecification
: ADD (outOfLineConstraint+ | outOfLineRefConstraint)
;
modifyConstraintClause
: MODIFY constraintOption constraintState+ CASCADE?
;
constraintWithName
: CONSTRAINT ignoredIdentifier_
;
constraintOption
: constraintWithName | constraintPrimaryOrUnique
;
constraintPrimaryOrUnique
: primaryKey | UNIQUE columnNames
;
renameConstraintClause
: RENAME constraintWithName TO ignoredIdentifier_
;
dropConstraintClause
: DROP
(
constraintPrimaryOrUnique CASCADE? ((KEEP | DROP) INDEX)? | (CONSTRAINT ignoredIdentifier_ CASCADE?)
)
;
alterExternalTable
: (addColumnSpecification | modifyColumnSpecification | dropColumnSpecification)+
;
objectProperties
: objectProperty (COMMA_ objectProperty)*
;
objectProperty
: (columnName | attributeName) (DEFAULT expr)? (inlineConstraint* | inlineRefConstraint?) | outOfLineConstraint | outOfLineRefConstraint
;
columnProperties
: columnProperty+
;
columnProperty
: objectTypeColProperties
;
objectTypeColProperties
: COLUMN columnName substitutableColumnClause
;
substitutableColumnClause
: ELEMENT? IS OF TYPE? LP_ ONLY? dataTypeName_ RP_ | NOT? SUBSTITUTABLE AT ALL LEVELS
;
|
add tableAlias
|
add tableAlias
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
2aecc5c0eb4e2d20e43dbee9697cf23a94433b18
|
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;
programUnit
: (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID
;
|
grammar OracleDCLStatement;
import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol;
grantRolesToPrograms
: roleName (COMMA roleName)* TO programUnit ( COMMA programUnit )*
;
programUnit
: (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID
;
|
add grantRolesToPrograms
|
add grantRolesToPrograms
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
|
29013531cff633f1203d32b4bfabed133dcfc280
|
projects/batfish/src/main/antlr4/org/batfish/grammar/cisco_xr/CiscoXr_rpl.g4
|
projects/batfish/src/main/antlr4/org/batfish/grammar/cisco_xr/CiscoXr_rpl.g4
|
parser grammar CiscoXr_routemap;
import CiscoXr_common;
options {
tokenVocab = CiscoXrLexer;
}
apply_rp_stanza
:
APPLY name = variable
(
PAREN_LEFT varlist = route_policy_params_list PAREN_RIGHT
)? NEWLINE
;
as_expr
:
DEC
| AUTO
| RP_VARIABLE
;
as_path_set_elem
:
IOS_REGEX AS_PATH_SET_REGEX
;
as_path_set_expr
:
inline = as_path_set_inline
| rpvar = RP_VARIABLE
| named = variable
;
as_path_set_inline
:
PAREN_LEFT elems += as_path_set_elem
(
COMMA elems += as_path_set_elem
)* PAREN_RIGHT
;
as_range_expr
:
SINGLE_QUOTE
(
subranges += rp_subrange
)+ SINGLE_QUOTE EXACT?
;
boolean_and_rp_stanza
:
boolean_not_rp_stanza
| boolean_and_rp_stanza AND boolean_not_rp_stanza
;
boolean_apply_rp_stanza
:
APPLY name = variable
(
PAREN_LEFT varlist = route_policy_params_list PAREN_RIGHT
)?
;
boolean_as_path_in_rp_stanza
:
AS_PATH IN expr = as_path_set_expr
;
boolean_as_path_is_local_rp_stanza
:
AS_PATH IS_LOCAL
;
boolean_as_path_neighbor_is_rp_stanza
:
AS_PATH NEIGHBOR_IS as_range_expr
;
boolean_as_path_originates_from_rp_stanza
:
AS_PATH ORIGINATES_FROM as_range_expr
;
boolean_as_path_passes_through_rp_stanza
:
AS_PATH PASSES_THROUGH as_range_expr
;
boolean_community_matches_any_rp_stanza
:
COMMUNITY MATCHES_ANY rp_community_set
;
boolean_community_matches_every_rp_stanza
:
COMMUNITY MATCHES_EVERY rp_community_set
;
boolean_destination_rp_stanza
:
DESTINATION IN rp_prefix_set
;
boolean_local_preference_rp_stanza
:
LOCAL_PREFERENCE int_comp rhs = int_expr
;
boolean_med_rp_stanza
:
MED int_comp rhs = int_expr
;
boolean_next_hop_in_rp_stanza
:
NEXT_HOP IN rp_prefix_set
;
boolean_not_rp_stanza
:
boolean_simple_rp_stanza
| NOT boolean_simple_rp_stanza
;
boolean_rib_has_route_rp_stanza
:
RIB_HAS_ROUTE IN rp_prefix_set
;
boolean_route_type_is_rp_stanza
:
ROUTE_TYPE IS type = rp_route_type
;
boolean_rp_stanza
:
boolean_and_rp_stanza
| boolean_rp_stanza OR boolean_and_rp_stanza
;
boolean_simple_rp_stanza
:
PAREN_LEFT boolean_rp_stanza PAREN_RIGHT
| boolean_apply_rp_stanza
| boolean_as_path_in_rp_stanza
| boolean_as_path_is_local_rp_stanza
| boolean_as_path_neighbor_is_rp_stanza
| boolean_as_path_originates_from_rp_stanza
| boolean_as_path_passes_through_rp_stanza
| boolean_community_matches_any_rp_stanza
| boolean_community_matches_every_rp_stanza
| boolean_destination_rp_stanza
| boolean_local_preference_rp_stanza
| boolean_med_rp_stanza
| boolean_next_hop_in_rp_stanza
| boolean_rib_has_route_rp_stanza
| boolean_route_type_is_rp_stanza
| boolean_tag_is_rp_stanza
;
boolean_tag_is_rp_stanza
:
TAG int_comp int_expr
;
delete_community_rp_stanza
:
DELETE COMMUNITY
(
ALL
| NOT? IN rp_community_set
) NEWLINE
;
disposition_rp_stanza
:
(
DONE
| DROP
| PASS
| UNSUPPRESS_ROUTE
) NEWLINE
;
elseif_rp_stanza
:
ELSEIF boolean_rp_stanza THEN NEWLINE rp_stanza*
;
else_rp_stanza
:
ELSE NEWLINE rp_stanza*
;
if_rp_stanza
:
IF boolean_rp_stanza THEN NEWLINE rp_stanza* elseif_rp_stanza*
else_rp_stanza?
(
ENDIF
| EXIT
) NEWLINE
;
int_comp
:
EQ
| IS
| GE
| LE
;
isis_level_expr
:
isis_level
| RP_VARIABLE
;
origin_expr
:
origin_expr_literal
| RP_VARIABLE
;
origin_expr_literal
:
(
EGP bgp_asn
)
| IGP
| INCOMPLETE
;
prepend_as_path_rp_stanza
:
PREPEND AS_PATH as = as_expr
(
number = int_expr
)? NEWLINE
;
route_policy_stanza
:
ROUTE_POLICY name = variable
(
PAREN_LEFT varlist = route_policy_params_list PAREN_RIGHT
)? NEWLINE
(
stanzas += rp_stanza
)*
END_POLICY NEWLINE
;
route_policy_params_list
:
params_list += variable
(
COMMA params_list += variable
)*
;
rp_community_set
:
name = variable
| PAREN_LEFT elems += community_set_elem
(
COMMA elems += community_set_elem
)* PAREN_RIGHT
;
rp_extcommunity_set_rt
:
name = variable
| PAREN_LEFT elems += extcommunity_set_rt_elem
(
COMMA elems += extcommunity_set_rt_elem
)* PAREN_RIGHT
;
rp_isis_metric_type
:
EXTERNAL
| INTERNAL
| RIB_METRIC_AS_EXTERNAL
| RIB_METRIC_AS_INTERNAL
;
rp_metric_type
:
rp_isis_metric_type
| rp_ospf_metric_type
| RP_VARIABLE
;
rp_ospf_metric_type
:
TYPE_1
| TYPE_2
;
rp_prefix_set
:
name = variable
| PAREN_LEFT elems += prefix_set_elem
(
COMMA elems += prefix_set_elem
)* PAREN_RIGHT
;
rp_route_type
:
LOCAL
| INTERAREA
| INTERNAL
| LEVEL_1
| LEVEL_1_2
| LEVEL_2
| LOCAL
| OSPF_EXTERNAL_TYPE_1
| OSPF_EXTERNAL_TYPE_2
| OSPF_INTER_AREA
| OSPF_INTRA_AREA
| OSPF_NSSA_TYPE_1
| OSPF_NSSA_TYPE_2
| RP_VARIABLE
| TYPE_1
| TYPE_2
;
rp_stanza
:
apply_rp_stanza
| delete_community_rp_stanza
| disposition_rp_stanza
|
(
hash_comment NEWLINE
)
| if_rp_stanza
| set_rp_stanza
;
set_community_rp_stanza
:
SET COMMUNITY rp_community_set ADDITIVE? NEWLINE
;
set_extcommunity_rp_stanza
:
SET EXTCOMMUNITY
(
set_extcommunity_rt
// TODO all the other extended community types
)
;
set_extcommunity_rt
:
RT rp_extcommunity_set_rt ADDITIVE? NEWLINE
;
set_isis_metric_rp_stanza
:
SET ISIS_METRIC int_expr NEWLINE
;
set_level_rp_stanza
:
SET LEVEL isis_level_expr NEWLINE
;
set_local_preference_rp_stanza
:
SET LOCAL_PREFERENCE pref = int_expr NEWLINE
;
set_med_rp_stanza
:
SET MED med = int_expr NEWLINE
;
set_metric_type_rp_stanza
:
SET METRIC_TYPE type = rp_metric_type NEWLINE
;
set_next_hop_rp_stanza
:
SET NEXT_HOP
(
DISCARD
| IP_ADDRESS
| IPV6_ADDRESS
| PEER_ADDRESS
) DESTINATION_VRF? NEWLINE
;
set_next_hop_self_rp_stanza
:
SET NEXT_HOP SELF NEWLINE
;
set_origin_rp_stanza
:
SET ORIGIN origin_expr NEWLINE
;
set_path_selection_rp_stanza
:
SET PATH_SELECTION null_rest_of_line
;
set_tag_rp_stanza
:
SET TAG tag = int_expr NEWLINE
;
set_weight_rp_stanza
:
SET WEIGHT weight = int_expr NEWLINE
;
set_rp_stanza
:
prepend_as_path_rp_stanza
| set_community_rp_stanza
| set_extcommunity_rp_stanza
| set_isis_metric_rp_stanza
| set_level_rp_stanza
| set_local_preference_rp_stanza
| set_med_rp_stanza
| set_metric_type_rp_stanza
| set_next_hop_rp_stanza
| set_next_hop_self_rp_stanza
| set_origin_rp_stanza
| set_path_selection_rp_stanza
| set_tag_rp_stanza
| set_weight_rp_stanza
;
|
parser grammar CiscoXr_routemap;
import CiscoXr_common;
options {
tokenVocab = CiscoXrLexer;
}
apply_rp_stanza
:
APPLY name = variable
(
PAREN_LEFT varlist = route_policy_params_list PAREN_RIGHT
)? NEWLINE
;
as_expr
:
DEC
| AUTO
| RP_VARIABLE
;
as_path_set_elem
:
IOS_REGEX AS_PATH_SET_REGEX
;
as_path_set_expr
:
inline = as_path_set_inline
| rpvar = RP_VARIABLE
| named = variable
;
as_path_set_inline
:
PAREN_LEFT elems += as_path_set_elem
(
COMMA elems += as_path_set_elem
)* PAREN_RIGHT
;
as_range_expr
:
SINGLE_QUOTE
(
subranges += rp_subrange
)+ SINGLE_QUOTE EXACT?
;
boolean_and_rp_stanza
:
boolean_not_rp_stanza
| boolean_and_rp_stanza AND boolean_not_rp_stanza
;
boolean_apply_rp_stanza
:
APPLY name = variable
(
PAREN_LEFT varlist = route_policy_params_list PAREN_RIGHT
)?
;
boolean_as_path_in_rp_stanza
:
AS_PATH IN expr = as_path_set_expr
;
boolean_as_path_is_local_rp_stanza
:
AS_PATH IS_LOCAL
;
boolean_as_path_neighbor_is_rp_stanza
:
AS_PATH NEIGHBOR_IS as_range_expr
;
boolean_as_path_originates_from_rp_stanza
:
AS_PATH ORIGINATES_FROM as_range_expr
;
boolean_as_path_passes_through_rp_stanza
:
AS_PATH PASSES_THROUGH as_range_expr
;
boolean_community_matches_any_rp_stanza
:
COMMUNITY MATCHES_ANY rp_community_set
;
boolean_community_matches_every_rp_stanza
:
COMMUNITY MATCHES_EVERY rp_community_set
;
boolean_destination_rp_stanza
:
DESTINATION IN rp_prefix_set
;
boolean_local_preference_rp_stanza
:
LOCAL_PREFERENCE int_comp rhs = int_expr
;
boolean_med_rp_stanza
:
MED int_comp rhs = int_expr
;
boolean_next_hop_in_rp_stanza
:
NEXT_HOP IN rp_prefix_set
;
boolean_not_rp_stanza
:
boolean_simple_rp_stanza
| NOT boolean_simple_rp_stanza
;
boolean_rib_has_route_rp_stanza
:
RIB_HAS_ROUTE IN rp_prefix_set
;
boolean_route_type_is_rp_stanza
:
ROUTE_TYPE IS type = rp_route_type
;
boolean_rp_stanza
:
boolean_and_rp_stanza
| boolean_rp_stanza OR boolean_and_rp_stanza
;
boolean_simple_rp_stanza
:
PAREN_LEFT boolean_rp_stanza PAREN_RIGHT
| boolean_apply_rp_stanza
| boolean_as_path_in_rp_stanza
| boolean_as_path_is_local_rp_stanza
| boolean_as_path_neighbor_is_rp_stanza
| boolean_as_path_originates_from_rp_stanza
| boolean_as_path_passes_through_rp_stanza
| boolean_community_matches_any_rp_stanza
| boolean_community_matches_every_rp_stanza
| boolean_destination_rp_stanza
| boolean_local_preference_rp_stanza
| boolean_med_rp_stanza
| boolean_next_hop_in_rp_stanza
| boolean_rib_has_route_rp_stanza
| boolean_route_type_is_rp_stanza
| boolean_tag_is_rp_stanza
;
boolean_tag_is_rp_stanza
:
TAG int_comp int_expr
;
delete_community_rp_stanza
:
DELETE COMMUNITY
(
ALL
| NOT? IN rp_community_set
) NEWLINE
;
disposition_rp_stanza
:
(
DONE
| DROP
| PASS
| UNSUPPRESS_ROUTE
) NEWLINE
;
elseif_rp_stanza
:
ELSEIF boolean_rp_stanza THEN NEWLINE rp_stanza*
;
else_rp_stanza
:
ELSE NEWLINE rp_stanza*
;
if_rp_stanza
:
IF boolean_rp_stanza THEN NEWLINE rp_stanza* elseif_rp_stanza*
else_rp_stanza?
(
ENDIF
| EXIT
) NEWLINE
;
int_comp
:
EQ
| IS
| GE
| LE
;
isis_level_expr
:
isis_level
| RP_VARIABLE
;
origin_expr
:
origin_expr_literal
| RP_VARIABLE
;
origin_expr_literal
:
(
EGP bgp_asn
)
| IGP
| INCOMPLETE
;
prepend_as_path_rp_stanza
:
PREPEND AS_PATH as = as_expr
(
number = int_expr
)? NEWLINE
;
route_policy_stanza
:
ROUTE_POLICY name = variable
(
PAREN_LEFT varlist = route_policy_params_list PAREN_RIGHT
)? NEWLINE
(
stanzas += rp_stanza
)*
END_POLICY NEWLINE
;
route_policy_params_list
:
params_list += variable
(
COMMA params_list += variable
)*
;
rp_community_set
:
name = variable
| PAREN_LEFT elems += community_set_elem
(
COMMA elems += community_set_elem
)* PAREN_RIGHT
;
rp_extcommunity_set_rt
:
name = variable
| PAREN_LEFT elems += extcommunity_set_rt_elem
(
COMMA elems += extcommunity_set_rt_elem
)* PAREN_RIGHT
;
rp_isis_metric_type
:
EXTERNAL
| INTERNAL
| RIB_METRIC_AS_EXTERNAL
| RIB_METRIC_AS_INTERNAL
;
rp_metric_type
:
rp_isis_metric_type
| rp_ospf_metric_type
| RP_VARIABLE
;
rp_ospf_metric_type
:
TYPE_1
| TYPE_2
;
rp_prefix_set
:
name = variable
| PAREN_LEFT elems += prefix_set_elem
(
COMMA elems += prefix_set_elem
)* PAREN_RIGHT
;
rp_route_type
:
LOCAL
| INTERAREA
| INTERNAL
| LEVEL_1
| LEVEL_1_2
| LEVEL_2
| LOCAL
| OSPF_EXTERNAL_TYPE_1
| OSPF_EXTERNAL_TYPE_2
| OSPF_INTER_AREA
| OSPF_INTRA_AREA
| OSPF_NSSA_TYPE_1
| OSPF_NSSA_TYPE_2
| RP_VARIABLE
| TYPE_1
| TYPE_2
;
rp_stanza
:
apply_rp_stanza
| delete_community_rp_stanza
| disposition_rp_stanza
|
(
hash_comment NEWLINE
)
| if_rp_stanza
| set_rp_stanza
;
set_community_rp_stanza
:
SET COMMUNITY rp_community_set ADDITIVE? NEWLINE
;
set_extcommunity_rp_stanza
:
SET EXTCOMMUNITY
(
set_extcommunity_rt
// TODO all the other extended community types. Until then, the ? prevents NPE on recovery.
)?
;
set_extcommunity_rt
:
RT rp_extcommunity_set_rt ADDITIVE? NEWLINE
;
set_isis_metric_rp_stanza
:
SET ISIS_METRIC int_expr NEWLINE
;
set_level_rp_stanza
:
SET LEVEL isis_level_expr NEWLINE
;
set_local_preference_rp_stanza
:
SET LOCAL_PREFERENCE pref = int_expr NEWLINE
;
set_med_rp_stanza
:
SET MED med = int_expr NEWLINE
;
set_metric_type_rp_stanza
:
SET METRIC_TYPE type = rp_metric_type NEWLINE
;
set_next_hop_rp_stanza
:
SET NEXT_HOP
(
DISCARD
| IP_ADDRESS
| IPV6_ADDRESS
| PEER_ADDRESS
) DESTINATION_VRF? NEWLINE
;
set_next_hop_self_rp_stanza
:
SET NEXT_HOP SELF NEWLINE
;
set_origin_rp_stanza
:
SET ORIGIN origin_expr NEWLINE
;
set_path_selection_rp_stanza
:
SET PATH_SELECTION null_rest_of_line
;
set_tag_rp_stanza
:
SET TAG tag = int_expr NEWLINE
;
set_weight_rp_stanza
:
SET WEIGHT weight = int_expr NEWLINE
;
set_rp_stanza
:
prepend_as_path_rp_stanza
| set_community_rp_stanza
| set_extcommunity_rp_stanza
| set_isis_metric_rp_stanza
| set_level_rp_stanza
| set_local_preference_rp_stanza
| set_med_rp_stanza
| set_metric_type_rp_stanza
| set_next_hop_rp_stanza
| set_next_hop_self_rp_stanza
| set_origin_rp_stanza
| set_path_selection_rp_stanza
| set_tag_rp_stanza
| set_weight_rp_stanza
;
|
work around a crash in route policy evaluation (#5636)
|
IOS-XR: work around a crash in route policy evaluation (#5636)
The code needs reworking: it's never safe for a parent to recurse into its child's context
if recovery is enabled.
For now, this works around a crash when recovery kicked in.
See https://github.com/batfish/batfish/issues/5625
|
ANTLR
|
apache-2.0
|
intentionet/batfish,batfish/batfish,arifogel/batfish,arifogel/batfish,intentionet/batfish,batfish/batfish,dhalperi/batfish,arifogel/batfish,dhalperi/batfish,intentionet/batfish,dhalperi/batfish,intentionet/batfish,intentionet/batfish,batfish/batfish
|
96818a178ce4c8d9cba9b396a703925b4c7bd00d
|
src/main/antlr4/JmesPath.g4
|
src/main/antlr4/JmesPath.g4
|
grammar JmesPath;
import JSON;
query : expression EOF ;
expression
: expression '.' (IDENTIFIER | multi_select_list | multi_select_hash | function_expression | '*')
| expression bracket_specifier
| bracket_specifier
| expression '||' expression
| IDENTIFIER
| expression '&&' expression
| expression COMPARATOR expression
| not_expression
| paren_expression
| '*'
| multi_select_list
| multi_select_hash
| literal
| function_expression
| expression '|' expression
| RAW_STRING
| current_node
;
not_expression : '!' expression ;
paren_expression : '(' expression ')' ;
multi_select_list : '[' expression (',' expression)* ']' ;
multi_select_hash : '{' keyval_expr (',' keyval_expr)* '}' ;
keyval_expr : IDENTIFIER ':' expression ;
bracket_specifier
: '[' (NUMBER | '*' | SLICE_EXPRESSION) ']'
| '[]'
| '[' '?' expression ']'
;
SLICE_EXPRESSION : NUMBER? ':' NUMBER? (':' NUMBER?)? ;
COMPARATOR
: '<'
| '<='
| '=='
| '>='
| '>'
| '!='
;
// TODO: should be UNQUOTED_STRING and not IDENTIFIER, but that doesn't work
function_expression : IDENTIFIER (no_args | one_or_more_args) ;
no_args : '(' ')' ;
one_or_more_args : '(' function_arg (',' function_arg)* ')' ;
function_arg
: expression
| expression_type
;
current_node : '@' ;
expression_type : '&' expression ;
RAW_STRING : '\'' (ESCAPE '\'' | ~['\\])* '\'' ;
literal : '`' value '`' ;
NUMBER : '-'? DIGIT+ ;
fragment ESCAPE : '\\' ;
DIGIT : [0-9] ;
LETTER : [a-zA-Z] ;
IDENTIFIER
: UNQUOTED_STRING
| QUOTED_STRING
;
fragment UNQUOTED_STRING : LETTER (LETTER | DIGIT | '_')* ;
fragment QUOTED_STRING : '"' (STRING_ESCAPE | ~["\\])* '"' ;
fragment STRING_ESCAPE : ESCAPE (["\\/bfnrt] | 'u' HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT) ;
fragment HEXDIGIT : DIGIT | [a-fA-F] ;
WS : [ \t\r\n]+ -> skip ;
|
grammar JmesPath;
import JSON;
query : expression EOF ;
expression
: expression '.' (IDENTIFIER | multi_select_list | multi_select_hash | function_expression | '*')
| expression bracket_specifier
| bracket_specifier
| expression '||' expression
| IDENTIFIER
| expression '&&' expression
| expression COMPARATOR expression
| not_expression
| paren_expression
| '*'
| multi_select_list
| multi_select_hash
| literal
| function_expression
| expression '|' expression
| RAW_STRING
| current_node
;
not_expression : '!' expression ;
paren_expression : '(' expression ')' ;
multi_select_list : '[' expression (',' expression)* ']' ;
multi_select_hash : '{' keyval_expr (',' keyval_expr)* '}' ;
keyval_expr : IDENTIFIER ':' expression ;
bracket_specifier
: '[' (SIGNED_INT | '*' | SLICE_EXPRESSION) ']'
| '[]'
| '[' '?' expression ']'
;
SLICE_EXPRESSION : SIGNED_INT? ':' SIGNED_INT? (':' SIGNED_INT?)? ;
COMPARATOR
: '<'
| '<='
| '=='
| '>='
| '>'
| '!='
;
// TODO: should be UNQUOTED_STRING and not IDENTIFIER, but that doesn't work
function_expression : IDENTIFIER (no_args | one_or_more_args) ;
no_args : '(' ')' ;
one_or_more_args : '(' function_arg (',' function_arg)* ')' ;
function_arg
: expression
| expression_type
;
current_node : '@' ;
expression_type : '&' expression ;
RAW_STRING : '\'' (ESCAPE '\'' | ~['\\])* '\'' ;
literal : '`' value '`' ;
SIGNED_INT : '-'? DIGIT+ ;
fragment ESCAPE : '\\' ;
DIGIT : [0-9] ;
LETTER : [a-zA-Z] ;
IDENTIFIER
: UNQUOTED_STRING
| QUOTED_STRING
;
fragment UNQUOTED_STRING : LETTER (LETTER | DIGIT | '_')* ;
fragment QUOTED_STRING : '"' (STRING_ESCAPE | ~["\\])* '"' ;
fragment STRING_ESCAPE : ESCAPE (["\\/bfnrt] | 'u' HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT) ;
fragment HEXDIGIT : DIGIT | [a-fA-F] ;
WS : [ \t\r\n]+ -> skip ;
|
Rename NUMBER in JmesPath.g4 to avoid conflics with NUMBER in JSON.g4
|
Rename NUMBER in JmesPath.g4 to avoid conflics with NUMBER in JSON.g4
|
ANTLR
|
bsd-3-clause
|
burtcorp/jmespath-java
|
20db36cf76d7160a3d870d7e0dca878aa440fdba
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/Keyword.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/Keyword.g4
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
lexer grammar Keyword;
import Alphabet;
WS
: [ \t\r\n] + ->skip
;
SELECT
: S E L E C T
;
INSERT
: I N S E R T
;
UPDATE
: U P D A T E
;
DELETE
: D E L E T E
;
CREATE
: C R E A T E
;
ALTER
: A L T E R
;
DROP
: D R O P
;
TRUNCATE
: T R U N C A T E
;
SCHEMA
: S C H E M A
;
GRANT
: G R A N T
;
REVOKE
: R E V O K E
;
ADD
: A D D
;
SET
: S E T
;
TABLE
: T A B L E
;
COLUMN
: C O L U M N
;
INDEX
: I N D E X
;
CONSTRAINT
: C O N S T R A I N T
;
PRIMARY
: P R I M A R Y
;
UNIQUE
: U N I Q U E
;
FOREIGN
: F O R E I G N
;
KEY
: K E Y
;
POSITION
: P O S I T I O N
;
PRECISION
: P R E C I S I O N
;
FUNCTION
: F U N C T I O N
;
TRIGGER
: T R I G G E R
;
PROCEDURE
: P R O C E D U R E
;
VIEW
: V I E W
;
INTO
: I N T O
;
VALUES
: V A L U E S
;
WITH
: W I T H
;
UNION
: U N I O N
;
DISTINCT
: D I S T I N C T
;
CASE
: C A S E
;
WHEN
: W H E N
;
CAST
: C A S T
;
TRIM
: T R I M
;
SUBSTRING
: S U B S T R I N G
;
FROM
: F R O M
;
NATURAL
: N A T U R A L
;
JOIN
: J O I N
;
FULL
: F U L L
;
INNER
: I N N E R
;
OUTER
: O U T E R
;
LEFT
: L E F T
;
RIGHT
: R I G H T
;
CROSS
: C R O S S
;
USING
: U S I N G
;
WHERE
: W H E R E
;
AS
: A S
;
ON
: O N
;
IF
: I F
;
ELSE
: E L S E
;
THEN
: T H E N
;
FOR
: F O R
;
TO
: T O
;
AND
: A N D
;
OR
: O R
;
IS
: I S
;
NOT
: N O T
;
NULL
: N U L L
;
TRUE
: T R U E
;
FALSE
: F A L S E
;
EXISTS
: E X I S T S
;
BETWEEN
: B E T W E E N
;
IN
: I N
;
ALL
: A L L
;
ANY
: A N Y
;
LIKE
: L I K E
;
ORDER
: O R D E R
;
GROUP
: G R O U P
;
BY
: B Y
;
ASC
: A S C
;
DESC
: D E S C
;
HAVING
: H A V I N G
;
LIMIT
: L I M I T
;
OFFSET
: O F F S E T
;
BEGIN
: B E G I N
;
COMMIT
: C O M M I T
;
ROLLBACK
: R O L L B A C K
;
SAVEPOINT
: S A V E P O I N T
;
BOOLEAN
: B O O L E A N
;
DOUBLE
: D O U B L E
;
CHAR
: C H A R
;
CHARACTER
: C H A R A C T E R
;
ARRAY
: A R R A Y
;
INTERVAL
: I N T E R V A L
;
DATE
: D A T E
;
TIME
: T I M E
;
TIMESTAMP
: T I M E S T A M P
;
LOCALTIME
: L O C A L T I M E
;
LOCALTIMESTAMP
: L O C A L T I M E S T A M P
;
YEAR
: Y E A R
;
QUARTER
: Q U A R T E R
;
MONTH
: M O N T H
;
WEEK
: W E E K
;
DAY
: D A Y
;
HOUR
: H O U R
;
MINUTE
: M I N U T E
;
SECOND
: S E C O N D
;
MICROSECOND
: M I C R O S E C O N D
;
MAX
: M A X
;
MIN
: M I N
;
SUM
: S U M
;
COUNT
: C O U N T
;
AVG
: A V G
;
DEFAULT
: D E F A U L T
;
CURRENT
: C U R R E N T
;
ENABLE
: E N A B L E
;
DISABLE
: D I S A B L E
;
CALL
: C A L L
;
INSTANCE
: I N S T A N C E
;
PRESERVE
: P R E S E R V E
;
DO
: D O
;
DEFINER
: D E F I N E R
;
CURRENT_USER
: C U R R E N T UL_ U S E R
;
SQL
: S Q L
;
CASCADED
: C A S C A D E D
;
LOCAL
: L O C A L
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
lexer grammar Keyword;
import Alphabet;
WS
: [ \t\r\n] + ->skip
;
SELECT
: S E L E C T
;
INSERT
: I N S E R T
;
UPDATE
: U P D A T E
;
DELETE
: D E L E T E
;
CREATE
: C R E A T E
;
ALTER
: A L T E R
;
DROP
: D R O P
;
TRUNCATE
: T R U N C A T E
;
SCHEMA
: S C H E M A
;
GRANT
: G R A N T
;
REVOKE
: R E V O K E
;
ADD
: A D D
;
SET
: S E T
;
TABLE
: T A B L E
;
COLUMN
: C O L U M N
;
INDEX
: I N D E X
;
CONSTRAINT
: C O N S T R A I N T
;
PRIMARY
: P R I M A R Y
;
UNIQUE
: U N I Q U E
;
FOREIGN
: F O R E I G N
;
KEY
: K E Y
;
POSITION
: P O S I T I O N
;
PRECISION
: P R E C I S I O N
;
FUNCTION
: F U N C T I O N
;
TRIGGER
: T R I G G E R
;
PROCEDURE
: P R O C E D U R E
;
VIEW
: V I E W
;
INTO
: I N T O
;
VALUES
: V A L U E S
;
WITH
: W I T H
;
UNION
: U N I O N
;
DISTINCT
: D I S T I N C T
;
CASE
: C A S E
;
WHEN
: W H E N
;
CAST
: C A S T
;
TRIM
: T R I M
;
SUBSTRING
: S U B S T R I N G
;
FROM
: F R O M
;
NATURAL
: N A T U R A L
;
JOIN
: J O I N
;
FULL
: F U L L
;
INNER
: I N N E R
;
OUTER
: O U T E R
;
LEFT
: L E F T
;
RIGHT
: R I G H T
;
CROSS
: C R O S S
;
USING
: U S I N G
;
WHERE
: W H E R E
;
AS
: A S
;
ON
: O N
;
IF
: I F
;
ELSE
: E L S E
;
THEN
: T H E N
;
FOR
: F O R
;
TO
: T O
;
AND
: A N D
;
OR
: O R
;
IS
: I S
;
NOT
: N O T
;
NULL
: N U L L
;
TRUE
: T R U E
;
FALSE
: F A L S E
;
EXISTS
: E X I S T S
;
BETWEEN
: B E T W E E N
;
IN
: I N
;
ALL
: A L L
;
ANY
: A N Y
;
LIKE
: L I K E
;
ORDER
: O R D E R
;
GROUP
: G R O U P
;
BY
: B Y
;
ASC
: A S C
;
DESC
: D E S C
;
HAVING
: H A V I N G
;
LIMIT
: L I M I T
;
OFFSET
: O F F S E T
;
BEGIN
: B E G I N
;
COMMIT
: C O M M I T
;
ROLLBACK
: R O L L B A C K
;
SAVEPOINT
: S A V E P O I N T
;
BOOLEAN
: B O O L E A N
;
DOUBLE
: D O U B L E
;
CHAR
: C H A R
;
CHARACTER
: C H A R A C T E R
;
ARRAY
: A R R A Y
;
INTERVAL
: I N T E R V A L
;
DATE
: D A T E
;
TIME
: T I M E
;
TIMESTAMP
: T I M E S T A M P
;
LOCALTIME
: L O C A L T I M E
;
LOCALTIMESTAMP
: L O C A L T I M E S T A M P
;
YEAR
: Y E A R
;
QUARTER
: Q U A R T E R
;
MONTH
: M O N T H
;
WEEK
: W E E K
;
DAY
: D A Y
;
HOUR
: H O U R
;
MINUTE
: M I N U T E
;
SECOND
: S E C O N D
;
MICROSECOND
: M I C R O S E C O N D
;
MAX
: M A X
;
MIN
: M I N
;
SUM
: S U M
;
COUNT
: C O U N T
;
AVG
: A V G
;
DEFAULT
: D E F A U L T
;
CURRENT
: C U R R E N T
;
ENABLE
: E N A B L E
;
DISABLE
: D I S A B L E
;
CALL
: C A L L
;
INSTANCE
: I N S T A N C E
;
PRESERVE
: P R E S E R V E
;
DO
: D O
;
DEFINER
: D E F I N E R
;
CURRENT_USER
: C U R R E N T UL_ U S E R
;
SQL
: S Q L
;
CASCADED
: C A S C A D E D
;
LOCAL
: L O C A L
;
|
fix mysql/Keyword.g4
|
fix mysql/Keyword.g4
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
|
d848b2e37bcdc638842319a33f668fcfef0857dd
|
shardingsphere-distsql-parser/shardingsphere-distsql-parser-engine/src/main/antlr4/imports/Keyword.g4
|
shardingsphere-distsql-parser/shardingsphere-distsql-parser-engine/src/main/antlr4/imports/Keyword.g4
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
lexer grammar Keyword;
import Alphabet;
WS
: [ \t\r\n] + ->skip
;
ADD
: A D D
;
CREATE
: C R E A T E
;
ALTER
: A L T E R
;
DROP
: D R O P
;
SHOW
: S H O W
;
START
: S T A R T
;
STOP
: S T O P
;
RESET
: R E S E T
;
CHECK
: C H E C K
;
RESOURCE
: R E S O U R C E
;
RESOURCES
: R E S O U R C E S
;
RULE
: R U L E
;
FROM
: F R O M
;
ENCRYPT
: E N C R Y P T
;
SHADOW
: S H A D O W
;
SCALING
: S C A L I N G
;
JOB
: J O B
;
LIST
: L I S T
;
STATUS
: S T A T U S
;
HOST
: H O S T
;
PORT
: P O R T
;
DB
: D B
;
USER
: U S E R
;
PASSWORD
: P A S S W O R D
;
TABLE
: T A B L E
;
TYPE
: T Y P E
;
NAME
: N A M E
;
PROPERTIES
: P R O P E R T I E S
;
COLUMN
: C O L U M N
;
RULES
: R U L E S
;
COLUMNS
: C O L U M N S
;
CIPHER
: C I P H E R
;
PLAIN
: P L A I N
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
lexer grammar Keyword;
import Alphabet;
WS
: [ \t\r\n] + ->skip
;
ADD
: A D D
;
DROP
: D R O P
;
SHOW
: S H O W
;
START
: S T A R T
;
STOP
: S T O P
;
RESET
: R E S E T
;
CHECK
: C H E C K
;
RESOURCE
: R E S O U R C E
;
RESOURCES
: R E S O U R C E S
;
FROM
: F R O M
;
SCALING
: S C A L I N G
;
JOB
: J O B
;
LIST
: L I S T
;
STATUS
: S T A T U S
;
HOST
: H O S T
;
PORT
: P O R T
;
DB
: D B
;
USER
: U S E R
;
PASSWORD
: P A S S W O R D
;
NAME
: N A M E
;
|
Rename ResourceStatement.g4 (#10819)
|
Rename ResourceStatement.g4 (#10819)
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
|
1a8db12a86027e2ab957cf50152859eff0f700c4
|
src/br/ufscar/compiladores2/t3/antlr/jaSON.g4
|
src/br/ufscar/compiladores2/t3/antlr/jaSON.g4
|
grammar JaSON;
program :
(class_definition)*;
class_definition :
'class' IDENT '{' class_body '}';
class_body :
variables* constructors+ main_function?;
variables :
type IDENT;
constructors :
IDENT '(' arguments? ')' '{' constructor_body '}' ;
constructor_body :
assignment*;
assignment :
attribute '=' (IDENT | STRING | NUM_INT | NUM_FLOAT | BOOLEAN) ;
attribute :
('this' '.')? IDENT;
arguments:
;
type:
'String' | 'int' | 'float' | 'boolean' ;
function_main:
'public' 'static' 'void' 'main' '(' 'String' 'args' '[]' ')' '{' function_body '}';
function_body:
'new'
;
IDENT:
('a'..'z' | 'A'..'Z' | '_') ('a'..'z' | 'A'..'Z' | '0'..'9' | '_')*;
NUM_INT:
'0'..'9'+;
NUM_FLOAT:
'0'..'9'+ '.' '0'..'9'+;
BOOLEAN:
'true' | 'false';
STRING:
'\'' ~('\n' | '\r' | '\'')* '\''
| '"' ~('\n' | '\r' | '"')* '"';
WS:
(' ' | '\n' | '\r' | '\t') -> skip;
COMMENTS:
'{' ~('\n')* '}' -> skip;
|
grammar JaSON;
program :
(class_definition)*;
class_definition :
'class' IDENT '{' class_body '}';
class_body :
variables* constructors+ main_function?;
variables :
type IDENT;
constructors :
IDENT '(' arguments? ')' '{' constructor_body '}' ;
constructor_body :
assignment*;
assignment :
attribute '=' (IDENT | STRING | NUM_INT | NUM_FLOAT | BOOLEAN) ;
attribute :
('this' '.')? IDENT;
arguments:
;
grammar jaSON;
program :
(class_definition)*;
class_definition :
'class' IDENT ('extends' IDENT)? '{' class_body '}';
class_body :
variables* constructors+ function_main?;
variables :
type IDENT mais_var ';';
mais_var: ',' IDENT mais_var |
;
constructors :
IDENT '(' (arguments)?(','arguments)* ')' '{' constructor_body '}' ;
constructor_body :
assignment*;
assignment :
attribute '=' (IDENT /*argumentos do construtor*/ | STRING | NUM_INT | NUM_FLOAT | BOOLEAN) ';' ;
attribute :
('this' '.')? IDENT/*variaveis da classe*/;
arguments:
type IDENT/* nome do argumento*/
;
type:
'String' | 'int' | 'float' | 'boolean' | IDENT/* Uma classe criada pode ser um tipo para uma variavel de outra classe*/ ;
function_main:
'public' 'static' 'void' 'main' '(' 'String' 'args' '[]' ')' '{' function_body '}';
function_body:
variables*
(IDENT/*tipo*/ IDENT /*objeto*/ '=' 'new' IDENT /*construtor*/ '(' (IDENT)?(','IDENT)*
/* aqui são as variaveis que serão passadas por parametro para o construtor*/ ')' )+ ';'
;
IDENT:
('a'..'z' | 'A'..'Z' | '_') ('a'..'z' | 'A'..'Z' | '0'..'9' | '_')*;
NUM_INT:
'0'..'9'+;
NUM_FLOAT:
'0'..'9'+ '.''0'..'9'+;
BOOLEAN:
'true' | 'false';
STRING:
'\'' ~('\n' | '\r' | '\'')* '\''
| '"' ~('\n' | '\r' | '"')* '"';
WS:
(' ' | '\n' | '\r' | '\t') -> skip;
COMMENTS:
'{' ~('\n')* '}' -> skip;
type:
'String' | 'int' | 'float' | 'boolean' ;
function_main:
'public' 'static' 'void' 'main' '(' 'String' 'args' '[]' ')' '{' function_body '}';
function_body:
'new'
;
IDENT:
('a'..'z' | 'A'..'Z' | '_') ('a'..'z' | 'A'..'Z' | '0'..'9' | '_')*;
NUM_INT:
'0'..'9'+;
NUM_FLOAT:
'0'..'9'+ '.' '0'..'9'+;
BOOLEAN:
'true' | 'false';
STRING:
'\'' ~('\n' | '\r' | '\'')* '\''
| '"' ~('\n' | '\r' | '"')* '"';
WS:
(' ' | '\n' | '\r' | '\t') -> skip;
COMMENTS:
'{' ~('\n')* '}' -> skip;
|
update grammar
|
update grammar
|
ANTLR
|
mit
|
leobronza/compiladores2-t3
|
4f66c2f416bc20fb735ca2c1681d6aa7f40129c5
|
VineScriptLib/Compilers/Vine/VineParser.g4
|
VineScriptLib/Compilers/Vine/VineParser.g4
|
parser grammar VineParser;
/*
// django syntax: https://docs.djangoproject.com/en/1.10/topics/templates/#the-django-template-language
// django:
// * var: {{ foo }}
// * code: {% if foo %}
// * comment: {# comment #}
// detail: https://github.com/benjohnson/atom-django-templates/blob/master/grammars/html%20(django).cson
grammar VineScript;
script: sequence+ EOF;
sequence: text
| code
|
;
code: stmt
| text
;
// conditionStmt or controlStmt (control structure)
stmt: conditionStmt
| assign
| print
| stmt ';'
| variable
;
// {{ foo }} is equal to {% print foo %}
// built-in filters:
// * upper
// * lower
// * truncatechars:8
// * truncatewords:2
// * pluralize
// * default:"nothing"
// * length
// * random
// * stringformat:"#.0"
// * yesno:"yeah,no,maybe"
// ---- added by myself: ----
// * min
// * max
// built-in functions:
// * ParseInt(string)
// * ParseNumber(string)
// * Range(int):[]
// custom template tags
// https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-tags
// custom template filters :
// https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-filters
//{% autoescape off %}
// {{ body }}
// {% autoescape on %}
// {{ foo }}
// {% endautoescape %}
//{% endautoescape %}
// preformatted: (on by default)
{% formatted on %}
{% formatted off %}
// or like html:
{% pre on %}
{% pre off %}
// maybe:
{% tab %}
{% br %}
'{%' 'set' ID ('='|'to') expr '%}'
*/
@members{
public enum EVineParseMode {
FULL,
EXPR
}
// by default, parse as a passage (full mode)
public EVineParseMode ParseMode = EVineParseMode.FULL;
private static readonly string errReservedChar =
"'\u000B' (vertical tabulation) is a reserved character and is not allowed to be used!";
private static readonly string errVarDefReservedKw =
"Can't use a reserved keyword as a variable name!";
}
options { tokenVocab=VineLexer; }
/*
* Parser Rules
*/
passage
: {ParseMode == EVineParseMode.EXPR}? evalExprMode NL? EOF // active only if we're expr parse mode
| block* NL? EOF
| { NotifyErrorListeners(errReservedChar); } RESERVED_CHARS
//| { NotifyErrorListeners("Error char"); } ERROR_CHAR
;
evalExprMode
: expr
;
block
: /*stmtBlock+ NL (stmtBlock* NL+) # noPrintBlock
| stmtBlock+ NL # noPrintBlock
| stmt text (stmt|text)* NL # printBlockLn
| text stmt (stmt|text)* NL # printBlockLn
| text NL # printBlockLn
| */NL # printBlockLn
| text # printBlock
| stmt # noPrintBlock
;
text: TXT
;
stmt: display
| stmtBlock
;
stmtBlock
: controlStmt
| command
| '{%' funcCall '%}'
//| LINE_COMMENT
| BLOCK_COMMENT
;
/**
* Display something in the text (variable, expression, function return, ...)
**/
display: '{{' expr '}}' ;
command
: '{%' 'set' variable ('='|'to') expr '%}' # assignStmt
| '{%' COMMAND expressionList? '%}' # langCmd // {% formatted on %}, {% br %}, ...
;
funcCall
: ID '(' expressionList? ')'
| ID '(' expressionList? ')' { NotifyErrorListeners("Too many parentheses"); } ')'
| ID '(' expressionList? { NotifyErrorListeners("Missing closing ')'"); }
;
newCollection
: '[' expressionList? ']' # newArray
| LBRACE keyValueList? RBRACE # newDict
// array errors:
| '[' expressionList? ']' { NotifyErrorListeners("Too many brackets"); } ']' # newArrayError
| '[' expressionList? { NotifyErrorListeners("Missing closing ']'"); } # newArrayError
// dict errors:
| LBRACE keyValueList? RBRACE { NotifyErrorListeners("Too many braces"); } ']' # newDictError
| LBRACE keyValueList? { NotifyErrorListeners("Missing closing '}'"); } # newDictError
;
// if, elif, else, for, end
controlStmt
: ifStmt (elifStmt)* (elseStmt)? endIfStmt
//| '{%' 'for' ID 'in' expr '%}'
;
ifStmt
: '{%' 'if' ws expr '%}' block*
;
elifStmt
: '{%' 'elif' ws expr '%}' block*
;
elseStmt
: '{%' 'else' '%}' block*
;
endIfStmt
: '{%' 'endif' '%}'
;
expr: <assoc=right> left=expr '^' right=expr # powExpr
| op=(MINUS|NOT) expr # unaryExpr
| left=expr op=('*' | '/' | '%') right=expr # mulDivModExpr
| left=expr op=('+'|'-') right=expr # addSubExpr
| left=expr op=('<'|'>'|'<='|'>=') right=expr # relationalExpr
| left=expr op=('=='|'!=') right=expr # equalityExpr
| left=expr ('&&'|ws 'and' ws) right=expr # andExpr
| left=expr ('||'|ws 'or' ws) right=expr # orExpr
| '(' expr ')' # parensExpr
| newCollection # collectionExpr
| funcCall # funcCallExpr
| atom # atomExpr
| variable # varExpr
| { NotifyErrorListeners("Invalid expression"); } . # errorExpr
;
expressionList
: expr (',' expr)*
| expr (',' { NotifyErrorListeners("Too many comma separators"); } ','+ expr)+
| expr (',' expr)* { NotifyErrorListeners("Too many comma separators"); } ','
;
keyValue
: stringLiteral ':' expr
| { NotifyErrorListeners("Invalid key value: it should look like this: '\"key\": value'"); } .
;
keyValueList
: keyValue (',' keyValue)*
| keyValue (',' { NotifyErrorListeners("Too many comma separators"); } ','+ keyValue)+
| keyValue (',' keyValue)* { NotifyErrorListeners("Too many comma separators"); } ','
;
atom: INT # intAtom
| FLOAT # floatAtom
| (TRUE | FALSE) # boolAtom
| stringLiteral # stringAtom
| NULL # nullAtom
;
stringLiteral
: STRING
| { NotifyErrorListeners(errReservedChar); } ILLEGAL_STRING
;
// Variable access. The '$' prefix is optional
variable
: '$'? ID ('.' ID)* # simpleVar
// | variable ('[' expr ']')+ # collectionVar
// Call to force whitespace. Kind of hacky?
ws
: {
// If the current token is not a white space => error.
// We use semantic predicates here because WS is in a different
// channel that the parser can't access directly
if (_input.Get(_input.Index - 1).Type != WS) {
NotifyErrorListeners("Yo, you need to use a separation space here!");
}
}
;
reservedKeyword
: IF
| ELIF
| ELSE
| ENDIF
| KW_AND
| KW_OR
| TO
| SET
| TRUE
| FALSE
| NULL
;
/*
variable: ID # variableValue
| variable Dot variable # combinedVariable
// | ID[expr]+
;
postfixExpression
: atom //should be ID (and maybe allow STRING too)
| postfixExpression '[' expr ']'
| postfixExpression '(' argumentExpressionList? ')'
| postfixExpression '.' ID # attributeLookup
| postfixExpression '++'
| postfixExpression '--'
;
*/
|
parser grammar VineParser;
/*
// django syntax: https://docs.djangoproject.com/en/1.10/topics/templates/#the-django-template-language
// django:
// * var: {{ foo }}
// * code: {% if foo %}
// * comment: {# comment #}
// detail: https://github.com/benjohnson/atom-django-templates/blob/master/grammars/html%20(django).cson
grammar VineScript;
script: sequence+ EOF;
sequence: text
| code
|
;
code: stmt
| text
;
// conditionStmt or controlStmt (control structure)
stmt: conditionStmt
| assign
| print
| stmt ';'
| variable
;
// {{ foo }} is equal to {% print foo %}
// built-in filters:
// * upper
// * lower
// * truncatechars:8
// * truncatewords:2
// * pluralize
// * default:"nothing"
// * length
// * random
// * stringformat:"#.0"
// * yesno:"yeah,no,maybe"
// ---- added by myself: ----
// * min
// * max
// built-in functions:
// * ParseInt(string)
// * ParseNumber(string)
// * Range(int):[]
// custom template tags
// https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-tags
// custom template filters :
// https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-filters
//{% autoescape off %}
// {{ body }}
// {% autoescape on %}
// {{ foo }}
// {% endautoescape %}
//{% endautoescape %}
// preformatted: (on by default)
{% formatted on %}
{% formatted off %}
// or like html:
{% pre on %}
{% pre off %}
// maybe:
{% tab %}
{% br %}
'{%' 'set' ID ('='|'to') expr '%}'
*/
@members{
public enum EVineParseMode {
FULL,
EXPR
}
// by default, parse as a passage (full mode)
public EVineParseMode ParseMode = EVineParseMode.FULL;
private static readonly string errReservedChar =
"'\u000B' (vertical tabulation) is a reserved character and is not allowed to be used!";
private static readonly string errVarDefReservedKw =
"Can't use a reserved keyword as a variable name!";
}
options { tokenVocab=VineLexer; }
/*
* Parser Rules
*/
passage
: {ParseMode == EVineParseMode.EXPR}? evalExprMode NL? EOF // active only if we're expr parse mode
| block* NL? EOF
| { NotifyErrorListeners(errReservedChar); } RESERVED_CHARS
//| { NotifyErrorListeners("Error char"); } ERROR_CHAR
;
evalExprMode
: expr
;
block
: /*stmtBlock+ NL (stmtBlock* NL+) # noPrintBlock
| stmtBlock+ NL # noPrintBlock
| stmt text (stmt|text)* NL # printBlockLn
| text stmt (stmt|text)* NL # printBlockLn
| text NL # printBlockLn
| */NL # printBlockLn
| text # printBlock
| stmt # noPrintBlock
;
text: TXT
;
stmt: display
| stmtBlock
;
stmtBlock
: controlStmt
| command
| '{%' funcCall '%}'
//| LINE_COMMENT
| BLOCK_COMMENT
;
/**
* Display something in the text (variable, expression, function return, ...)
**/
display: '{{' expr '}}' ;
command
: '{%' 'set' variable ('='|'to') expr '%}' # assignStmt
| '{%' COMMAND expressionList? '%}' # langCmd // {% formatted on %}, {% br %}, ...
;
funcCall
: ID '(' expressionList? ')'
| ID '(' expressionList? ')' { NotifyErrorListeners("Too many parentheses"); } ')'
| ID '(' expressionList? { NotifyErrorListeners("Missing closing ')'"); }
;
newCollection
: '[' expressionList? ']' # newArray
| LBRACE keyValueList? RBRACE # newDict
// array errors:
| '[' expressionList? ']' { NotifyErrorListeners("Too many brackets"); } ']' # newArrayError
| '[' expressionList? { NotifyErrorListeners("Missing closing ']'"); } # newArrayError
// dict errors:
| LBRACE keyValueList? RBRACE { NotifyErrorListeners("Too many braces"); } ']' # newDictError
| LBRACE keyValueList? { NotifyErrorListeners("Missing closing '}'"); } # newDictError
;
// if, elif, else, for, end
controlStmt
: ifStmt (elifStmt)* (elseStmt)? endIfStmt
//| '{%' 'for' ID 'in' expr '%}'
;
ifStmt
: '{%' 'if' ws expr '%}' block*
;
elifStmt
: '{%' 'elif' ws expr '%}' block*
;
elseStmt
: '{%' 'else' '%}' block*
;
endIfStmt
: '{%' 'endif' '%}'
;
expr: <assoc=right> left=expr '^' right=expr # powExpr
| op=(MINUS|NOT) expr # unaryExpr
| left=expr op=('*' | '/' | '%') right=expr # mulDivModExpr
| left=expr op=('+'|'-') right=expr # addSubExpr
| left=expr op=('<'|'>'|'<='|'>=') right=expr # relationalExpr
| left=expr op=('=='|'!=') right=expr # equalityExpr
| left=expr ('&&'|ws 'and' ws) right=expr # andExpr
| left=expr ('||'|ws 'or' ws) right=expr # orExpr
| '(' expr ')' # parensExpr
| newCollection # collectionExpr
| funcCall # funcCallExpr
| atom # atomExpr
| variable # varExpr
| { NotifyErrorListeners("Invalid expression"); } . # errorExpr
;
expressionList
: expr (',' expr)*
| expr (',' { NotifyErrorListeners("Too many comma separators"); } ','+ expr)+
| expr (',' expr)* { NotifyErrorListeners("Too many comma separators"); } ','
;
keyValue
: stringLiteral ':' expr
| { NotifyErrorListeners("Invalid key value: it should look like this: '\"key\": value'"); } .
;
keyValueList
: keyValue (',' keyValue)*
| keyValue (',' { NotifyErrorListeners("Too many comma separators"); } ','+ keyValue)+
| keyValue (',' keyValue)* { NotifyErrorListeners("Too many comma separators"); } ','
;
atom: INT # intAtom
| FLOAT # floatAtom
| (TRUE | FALSE) # boolAtom
| stringLiteral # stringAtom
| NULL # nullAtom
;
stringLiteral
: STRING
| { NotifyErrorListeners(errReservedChar); } ILLEGAL_STRING
;
// Variable access. The '$' prefix is optional
variable
: '$'? ID ('.' ID)* # simpleVar
// | variable ('[' expr ']')+ # collectionVar
| { NotifyErrorListeners(errVarDefReservedKw); }
reservedKeyword # errVariable
;
// Call to force whitespace. Kind of hacky?
ws
: {
// If the current token is not a white space => error.
// We use semantic predicates here because WS is in a different
// channel that the parser can't access directly
if (_input.Get(_input.Index - 1).Type != WS) {
NotifyErrorListeners("Yo, you need to use a separation space here!");
}
}
;
reservedKeyword
: IF
| ELIF
| ELSE
| ENDIF
| KW_AND
| KW_OR
| TO
| SET
| TRUE
| FALSE
| NULL
;
/*
variable: ID # variableValue
| variable Dot variable # combinedVariable
// | ID[expr]+
;
postfixExpression
: atom //should be ID (and maybe allow STRING too)
| postfixExpression '[' expr ']'
| postfixExpression '(' argumentExpressionList? ')'
| postfixExpression '.' ID # attributeLookup
| postfixExpression '++'
| postfixExpression '--'
;
*/
|
Handle error when a keyword is used as a variable name
|
Handle error when a keyword is used as a variable name
|
ANTLR
|
mit
|
julsam/VineScript
|
c770b1a13f1007ecbd643cb6f42dc5c726580272
|
python/PythonParser.g4
|
python/PythonParser.g4
|
// Header included from Python site:
/*
* Grammar for Python
*
* Note: Changing the grammar specified in this file will most likely
* require corresponding changes in the parser module
* (../Modules/parsermodule.c). If you can't make the changes to
* that module yourself, please co-ordinate the required changes
* with someone who can; ask around on python-dev for help. Fred
* Drake <[email protected]> will probably be listening there.
*
* NOTE WELL: You should also follow all the steps listed in PEP 306,
* "How to Change Python's Grammar"
*
* Start symbols for the grammar:
* single_input is a single interactive statement;
* file_input is a module or sequence of commands read from an input file;
* eval_input is the input for the eval() and input() functions.
* NB: compound_stmt in single_input is followed by extra NEWLINE!
*/
parser grammar PythonParser;
options { tokenVocab=PythonLexer; }
root: single_input
| file_input
| eval_input;
single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
;
file_input: (NEWLINE | stmt)* EOF
;
eval_input: testlist NEWLINE* EOF
;
decorator: AT dotted_name ( OPEN_PAREN (arglist)? CLOSE_PAREN )? NEWLINE
;
decorators: decorator+
;
decorated: decorators (classdef | funcdef)
;
funcdef: (ASYNC)? DEF NAME parameters (func_annotation)? COLON suite
;
func_annotation: ARROW test
;
parameters: OPEN_PAREN (typedargslist)? CLOSE_PAREN
;
//python 3 paramters
typedargslist
: (def_parameters COMMA)? args (COMMA def_parameters)? (COMMA kwargs)?
|(def_parameters COMMA)? kwargs
| def_parameters;
args: STAR named_parameter;
kwargs: POWER named_parameter;
def_parameters: def_parameter (COMMA def_parameter)*;
vardef_parameters: vardef_parameter (COMMA vardef_parameter)*;
def_parameter: (named_parameter (ASSIGN test)?) | STAR;
vardef_parameter: NAME (ASSIGN test)?;
named_parameter: NAME (COLON test)?;
//python 2 paramteters
varargslist
: (vardef_parameters COMMA)? varargs (COMMA vardef_parameters)? (COMMA varkwargs)
| vardef_parameters;
varargs: STAR NAME;
varkwargs: POWER NAME;
vfpdef: NAME;
stmt: simple_stmt | compound_stmt
;
simple_stmt: small_stmt (SEMI_COLON small_stmt)* (SEMI_COLON)? (NEWLINE | EOF)
;
small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
import_stmt | global_stmt | exec_stmt | assert_stmt | nonlocal_stmt)
;
//Python 3
nonlocal_stmt: NONLOCAL NAME (COMMA NAME)*;
expr_stmt: testlist_star_expr | annassign | augassign | assign;
// if left expression in assign is bool literal, it's mean that is Python 2 here
assign: testlist_star_expr (ASSIGN (yield_expr|testlist_star_expr))*;
//Only Pytnoh 3 supports annotations for variables
annassign: testlist_star_expr COLON test (ASSIGN test)? (yield_expr|testlist);
testlist_star_expr: (test|star_expr) (COMMA (test|star_expr))* (COMMA)?;
augassign: testlist_star_expr op=('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' |
'<<=' | '>>=' | '**=' | '//=') (yield_expr|testlist);
//print_stmt: 'print' ( ( test (COMMA test)* (COMMA)? )? |
// '>>' test ( (COMMA test)+ (COMMA)? )? )
// ;
// python 2
print_stmt: PRINT
NAME ( ( test (COMMA test)* (COMMA)? )? |
'>>' test ( (COMMA test)+ (COMMA)? )? )
;
del_stmt: DEL exprlist
;
pass_stmt: PASS
;
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
;
break_stmt: BREAK
;
continue_stmt: CONTINUE
;
return_stmt: RETURN (testlist)?
;
yield_stmt: yield_expr
;
raise_stmt: RAISE (test (COMMA test (COMMA test)?)?)? (FROM test)?
;
import_stmt: import_name | import_from
;
import_name: IMPORT dotted_as_names
;
import_from: (FROM ((DOT | ELLIPSIS)* dotted_name | (DOT | ELLIPSIS)+)
IMPORT (STAR | OPEN_PAREN import_as_names CLOSE_PAREN | import_as_names))
;
import_as_name: NAME (AS NAME)?
;
dotted_as_name: dotted_name (AS NAME)?
;
import_as_names: import_as_name (COMMA import_as_name)* (COMMA)?
;
dotted_as_names: dotted_as_name (COMMA dotted_as_name)*
;
dotted_name
: dotted_name DOT dotted_name
| NAME
;
global_stmt: GLOBAL NAME (COMMA NAME)*
;
exec_stmt: EXEC expr (IN test (COMMA test)?)?
;
assert_stmt: ASSERT test (COMMA test)?
;
compound_stmt:
if_stmt
| while_stmt
| for_stmt
| try_stmt
| with_stmt
| funcdef
| classdef
| decorated
| async_stmt
;
async_stmt: ASYNC (funcdef | with_stmt | for_stmt);
if_stmt: IF test COLON suite (elif_clause)* (else_clause)?
;
elif_clause: ELIF test COLON suite
;
else_clause: ELSE COLON suite
;
while_stmt: WHILE test COLON suite (else_clause)?
;
for_stmt: FOR exprlist IN testlist COLON suite (else_clause)?
;
try_stmt: (TRY COLON suite
((except_clause+ else_clause? finaly_clause?)
|finaly_clause))
;
finaly_clause: FINALLY COLON suite
;
with_stmt: WITH with_item (COMMA with_item)* COLON suite
;
with_item: test (AS expr)?
// NB compile.c makes sure that the default except clause is last
;
// Python 2 : EXCEPT test COMMA NAME, Python 3 : EXCEPT test AS NAME
except_clause: EXCEPT (test ((COMMA NAME) | (AS NAME))?)? COLON suite
;
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
;
// Backward compatibility cruft to support:
// [ x for x in lambda: True, lambda: False if x() ]
// even while also allowing:
// lambda x: 5 if x else 2
// (But not a mix of the two)
testlist_safe: old_test ((COMMA old_test)+ (COMMA)?)?
;
old_test: logical_test | old_lambdef
;
old_lambdef: LAMBDA (varargslist)? COLON old_test
;
test: logical_test (IF logical_test ELSE test)? | lambdef
;
test_nocond: logical_test | lambdef_nocond
;
lambdef_nocond: LAMBDA (varargslist)? COLON test_nocond
;
logical_test
: logical_test op=OR logical_test
| logical_test op=AND logical_test
| NOT logical_test
| comparison
;
// <> isn't actually a valid comparison operator in Python. It's here for the
// sake of a __future__ import described in PEP 401 (which really works :-)
comparison
: comparison op=(LESS_THAN|GREATER_THAN|EQUALS|GT_EQ|LT_EQ|NOT_EQ_1|NOT_EQ_2|IN|IS|NOT) comparison
| comparison (NOT IN | IS NOT) comparison
| expr
;
star_expr: STAR expr
;
expr
: expr op=OR_OP expr
| expr op=XOR expr
| expr op=AND_OP expr
| expr op=(LEFT_SHIFT | RIGHT_SHIFT) expr
| expr op=(ADD | MINUS) expr
| expr op=(STAR|'/'|'%'|'//') expr
| expr op=('+'|'-') expr
| expr op=POWER expr
| op=('+'|'-'|'~') expr
| atom_expr
;
atom_expr: (AWAIT)? atom trailer*
;
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 | // tt: added elipses.
dotted_name | NAME | NUMBER | MINUS NUMBER | NONE |STRING+)
;
testlist_comp: (test|star_expr) ( comp_for | (COMMA (test|star_expr))* (COMMA)? )
;
lambdef: LAMBDA (varargslist)? COLON test
;
trailer: OPEN_PAREN (arglist)? CLOSE_PAREN | '[' subscriptlist ']' | '.' NAME
;
subscriptlist: subscript (COMMA subscript)* (COMMA)?
;
subscript: ELLIPSIS | test | (test)? COLON (test)? (sliceop)?
;
sliceop: COLON (test)?
;
exprlist: expr (COMMA expr)* (COMMA)?
;
testlist: test (COMMA test)* (COMMA)?
;
dictorsetmaker: ( (test COLON test (comp_for | (COMMA test COLON test)* (COMMA)?)) |
(test (comp_for | (COMMA test)* (COMMA)?)) )
;
classdef: CLASS NAME (OPEN_PAREN (arglist)? CLOSE_PAREN)? COLON suite
;
arglist: argument (COMMA argument)* (COMMA)?
// The reason that keywords are test nodes instead of NAME is that using NAME
// results in an ambiguity. ast.c makes sure it's a NAME.
;
argument: ( test (comp_for)? |
test ASSIGN test |
POWER test |
STAR test );
list_iter: list_for | list_if
;
list_for: FOR exprlist IN testlist_safe (list_iter)?
;
list_if: IF old_test (list_iter)?
;
comp_iter: comp_for | comp_if
;
comp_for: FOR exprlist IN logical_test (comp_iter)?
;
comp_if: IF old_test (comp_iter)?
;
// not used in grammar, but may appear in "node" passed from Parser to Compiler
encoding_decl: NAME
;
yield_expr: YIELD (yield_arg)?;
yield_arg: FROM test | testlist;
|
// Header included from Python site:
/*
* Grammar for Python
*
* Note: Changing the grammar specified in this file will most likely
* require corresponding changes in the parser module
* (../Modules/parsermodule.c). If you can't make the changes to
* that module yourself, please co-ordinate the required changes
* with someone who can; ask around on python-dev for help. Fred
* Drake <[email protected]> will probably be listening there.
*
* NOTE WELL: You should also follow all the steps listed in PEP 306,
* "How to Change Python's Grammar"
*
* Start symbols for the grammar:
* single_input is a single interactive statement;
* file_input is a module or sequence of commands read from an input file;
* eval_input is the input for the eval() and input() functions.
* NB: compound_stmt in single_input is followed by extra NEWLINE!
*/
parser grammar PythonParser;
options { tokenVocab=PythonLexer; }
root: single_input
| file_input
| eval_input;
single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
;
file_input: (NEWLINE | stmt)* EOF
;
eval_input: testlist NEWLINE* EOF
;
decorator: AT dotted_name ( OPEN_PAREN (arglist)? CLOSE_PAREN )? NEWLINE
;
decorators: decorator+
;
decorated: decorators (classdef | funcdef)
;
funcdef: (ASYNC)? DEF NAME parameters (func_annotation)? COLON suite
;
func_annotation: ARROW test
;
parameters: OPEN_PAREN (typedargslist)? CLOSE_PAREN
;
//python 3 paramters
typedargslist
: (def_parameters COMMA)? args (COMMA def_parameters)? (COMMA kwargs)?
|(def_parameters COMMA)? kwargs
| def_parameters;
args: STAR named_parameter;
kwargs: POWER named_parameter;
def_parameters: def_parameter (COMMA def_parameter)*;
vardef_parameters: vardef_parameter (COMMA vardef_parameter)*;
def_parameter: (named_parameter (ASSIGN test)?) | STAR;
vardef_parameter: NAME (ASSIGN test)?;
named_parameter: NAME (COLON test)?;
//python 2 paramteters
varargslist
: (vardef_parameters COMMA)? varargs (COMMA vardef_parameters)? (COMMA varkwargs)
| vardef_parameters;
varargs: STAR NAME;
varkwargs: POWER NAME;
vfpdef: NAME;
stmt: simple_stmt | compound_stmt
;
simple_stmt: small_stmt (SEMI_COLON small_stmt)* (SEMI_COLON)? (NEWLINE | EOF)
;
small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
import_stmt | global_stmt | exec_stmt | assert_stmt | nonlocal_stmt)
;
//Python 3
nonlocal_stmt: NONLOCAL NAME (COMMA NAME)*;
expr_stmt: testlist_star_expr | annassign | augassign | assign;
// if left expression in assign is bool literal, it's mean that is Python 2 here
assign: testlist_star_expr (ASSIGN (yield_expr|testlist_star_expr))*;
//Only Pytnoh 3 supports annotations for variables
annassign: testlist_star_expr COLON test (ASSIGN test)? (yield_expr|testlist);
testlist_star_expr: (test|star_expr) (COMMA (test|star_expr))* (COMMA)?;
augassign: testlist_star_expr op=('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' |
'<<=' | '>>=' | '**=' | '//=') (yield_expr|testlist);
//print_stmt: 'print' ( ( test (COMMA test)* (COMMA)? )? |
// '>>' test ( (COMMA test)+ (COMMA)? )? )
// ;
// python 2
print_stmt: PRINT
( ( test (COMMA test)* (COMMA)? ) |
'>>' test ( (COMMA test)+ (COMMA)? ) )
;
del_stmt: DEL exprlist
;
pass_stmt: PASS
;
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
;
break_stmt: BREAK
;
continue_stmt: CONTINUE
;
return_stmt: RETURN (testlist)?
;
yield_stmt: yield_expr
;
raise_stmt: RAISE (test (COMMA test (COMMA test)?)?)? (FROM test)?
;
import_stmt: import_name | import_from
;
import_name: IMPORT dotted_as_names
;
import_from: (FROM ((DOT | ELLIPSIS)* dotted_name | (DOT | ELLIPSIS)+)
IMPORT (STAR | OPEN_PAREN import_as_names CLOSE_PAREN | import_as_names))
;
import_as_name: NAME (AS NAME)?
;
dotted_as_name: dotted_name (AS NAME)?
;
import_as_names: import_as_name (COMMA import_as_name)* (COMMA)?
;
dotted_as_names: dotted_as_name (COMMA dotted_as_name)*
;
dotted_name
: dotted_name DOT dotted_name
| NAME
;
global_stmt: GLOBAL NAME (COMMA NAME)*
;
exec_stmt: EXEC expr (IN test (COMMA test)?)?
;
assert_stmt: ASSERT test (COMMA test)?
;
compound_stmt:
if_stmt
| while_stmt
| for_stmt
| try_stmt
| with_stmt
| funcdef
| classdef
| decorated
| async_stmt
;
async_stmt: ASYNC (funcdef | with_stmt | for_stmt);
if_stmt: IF test COLON suite (elif_clause)* (else_clause)?
;
elif_clause: ELIF test COLON suite
;
else_clause: ELSE COLON suite
;
while_stmt: WHILE test COLON suite (else_clause)?
;
for_stmt: FOR exprlist IN testlist COLON suite (else_clause)?
;
try_stmt: (TRY COLON suite
((except_clause+ else_clause? finaly_clause?)
|finaly_clause))
;
finaly_clause: FINALLY COLON suite
;
with_stmt: WITH with_item (COMMA with_item)* COLON suite
;
with_item: test (AS expr)?
// NB compile.c makes sure that the default except clause is last
;
// Python 2 : EXCEPT test COMMA NAME, Python 3 : EXCEPT test AS NAME
except_clause: EXCEPT (test ((COMMA NAME) | (AS NAME))?)? COLON suite
;
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
;
// Backward compatibility cruft to support:
// [ x for x in lambda: True, lambda: False if x() ]
// even while also allowing:
// lambda x: 5 if x else 2
// (But not a mix of the two)
testlist_safe: old_test ((COMMA old_test)+ (COMMA)?)?
;
old_test: logical_test | old_lambdef
;
old_lambdef: LAMBDA (varargslist)? COLON old_test
;
test: logical_test (IF logical_test ELSE test)? | lambdef
;
test_nocond: logical_test | lambdef_nocond
;
lambdef_nocond: LAMBDA (varargslist)? COLON test_nocond
;
logical_test
: logical_test op=OR logical_test
| logical_test op=AND logical_test
| NOT logical_test
| comparison
;
// <> isn't actually a valid comparison operator in Python. It's here for the
// sake of a __future__ import described in PEP 401 (which really works :-)
comparison
: comparison op=(LESS_THAN|GREATER_THAN|EQUALS|GT_EQ|LT_EQ|NOT_EQ_1|NOT_EQ_2|IN|IS|NOT) comparison
| comparison (NOT IN | IS NOT) comparison
| expr
;
star_expr: STAR expr
;
expr
: expr op=OR_OP expr
| expr op=XOR expr
| expr op=AND_OP expr
| expr op=(LEFT_SHIFT | RIGHT_SHIFT) expr
| expr op=(ADD | MINUS) expr
| expr op=(STAR|'/'|'%'|'//') expr
| expr op=('+'|'-') expr
| expr op=POWER expr
| op=('+'|'-'|'~') expr
| atom_expr
;
atom_expr: (AWAIT)? atom trailer*
;
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 | // tt: added elipses.
dotted_name | NAME | PRINT | EXEC | NUMBER | MINUS NUMBER | NONE |STRING+)
;
testlist_comp: (test|star_expr) ( comp_for | (COMMA (test|star_expr))* (COMMA)? )
;
lambdef: LAMBDA (varargslist)? COLON test
;
trailer: OPEN_PAREN (arglist)? CLOSE_PAREN | '[' subscriptlist ']' | '.' NAME
;
subscriptlist: subscript (COMMA subscript)* (COMMA)?
;
subscript: ELLIPSIS | test | (test)? COLON (test)? (sliceop)?
;
sliceop: COLON (test)?
;
exprlist: expr (COMMA expr)* (COMMA)?
;
testlist: test (COMMA test)* (COMMA)?
;
dictorsetmaker: ( (test COLON test (comp_for | (COMMA test COLON test)* (COMMA)?)) |
(test (comp_for | (COMMA test)* (COMMA)?)) )
;
classdef: CLASS NAME (OPEN_PAREN (arglist)? CLOSE_PAREN)? COLON suite
;
arglist: argument (COMMA argument)* (COMMA)?
// The reason that keywords are test nodes instead of NAME is that using NAME
// results in an ambiguity. ast.c makes sure it's a NAME.
;
argument: ( test (comp_for)? |
test ASSIGN test |
POWER test |
STAR test );
list_iter: list_for | list_if
;
list_for: FOR exprlist IN testlist_safe (list_iter)?
;
list_if: IF old_test (list_iter)?
;
comp_iter: comp_for | comp_if
;
comp_for: FOR exprlist IN logical_test (comp_iter)?
;
comp_if: IF old_test (comp_iter)?
;
// not used in grammar, but may appear in "node" passed from Parser to Compiler
encoding_decl: NAME
;
yield_expr: YIELD (yield_arg)?;
yield_arg: FROM test | testlist;
|
fix print_stmt
|
fix print_stmt
|
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
|
de813dc89b36f08f2ea86d573d684abf8b7d072c
|
sharding-core/src/main/antlr4/imports/Keyword.g4
|
sharding-core/src/main/antlr4/imports/Keyword.g4
|
lexer grammar Keyword;
import Symbol;
ALL
: A L L
;
AND
: A N D
;
ANY
: A N Y
;
AS
: A S
;
ASC
: A S C
;
BETWEEN
: B E T W E E N;
BINARY
: B I N A R Y
;
BIT_INCLUSIVE_OR
: B I T UL_ I N C L U S I V E UL_ O R
;
BIT_NUM
: B I T UL_ N U M
;
BY
: B Y
;
DATE
: D A T E
;
DESC
: D E S C
;
ESCAPE
: E S C A P E
;
EXISTS
: E X I S T S
;
FALSE
: F A L S E
;
FROM
: F R O M
;
GROUP
: G R O U P
;
HAVING
: H A V I N G
;
IF
: I F
;
IN
: I N
;
IS
: I S
;
KEY
: K E Y
;
LIKE
: L I K E
;
LIMIT
: L I M I T
;
MOD
: M O D
;
NOT
: N O T
;
NULL
: N U L L
;
OFFSET
: O F F S E T
;
OR
: O R
;
ORDER
: O R D E R
;
PARTITION
: P A R T I T I O N
;
PRIMARY
: P R I M A R Y
;
RECURSIVE
: R E C U R S I V E
;
REGEXP
: R E G E X P
;
ROLLUP
: R O L L U P
;
ROW
: R O W
;
SELECT
: S E L E C T
;
SET
: S E T
;
SOUNDS
: S O U N D S
;
TIME
: T I M E
;
TIMESTAMP
: T I M E S T A M P
;
TRUE
: T R U E
;
UNION
: U N I O N
;
UNKNOWN
: U N K N O W N
;
WHERE
: W H E R E
;
WITH
: W I T H
;
XOR
: X O R
;
ADD
: A D D
;
ALTER
: A L T E R
;
ALWAYS
: A L W A Y S
;
CASCADE
: C A S C A D E
;
CHECK
: C H E C K
;
COLUMN
: C O L U M N
;
COMMIT
: C O M M I T
;
COMMITTED
: C O M M I T T E D
;
CONSTRAINT
: C O N S T R A I N T
;
CREATE
: C R E A T E
;
DEFAULT
: D E F A U L T
;
DELETE
: D E L E T E
;
DISABLE
: D I S A B L E
;
DROP
: D R O P
;
ENABLE
: E N A B L E
;
FOREIGN
: F O R E I G N
;
GENERATED
: G E N E R A T E D
;
INDEX
: I N D E X
;
ISOLATION
: I S O L A T I O N
;
LEVEL
: L E V E L
;
NO
: N O
;
ON
: O N
;
READ
: R E A D
;
REFERENCES
: R E F E R E N C E S
;
ROLLBACK
: R O L L B A C K
;
SERIALIZABLE
: S E R I A L I Z A B L E
;
START
: S T A R T
;
TABLE
: T A B L E
;
TO
: T O
;
TRANSACTION
: T R A N S A C T I O N
;
TRUNCATE
: T R U N C A T E
;
UNIQUE
: U N I Q U E
;
WORK
: W O R K
;
YEAR
: Y E A R
;
|
lexer grammar Keyword;
import Symbol;
ADD
: A D D
;
ALL
: A L L
;
ALTER
: A L T E R
;
ALWAYS
: A L W A Y S
;
AND
: A N D
;
ANY
: A N Y
;
AS
: A S
;
ASC
: A S C
;
BETWEEN
: B E T W E E N
;
BINARY
: B I N A R Y
;
BIT_INCLUSIVE_OR
: B I T UL_ I N C L U S I V E UL_ O R
;
BIT_NUM
: B I T UL_ N U M
;
BY
: B Y
;
CASCADE
: C A S C A D E
;
CHECK
: C H E C K
;
COLUMN
: C O L U M N
;
COMMIT
: C O M M I T
;
COMMITTED
: C O M M I T T E D
;
CONSTRAINT
: C O N S T R A I N T
;
CREATE
: C R E A T E
;
DATE
: D A T E
;
DEFAULT
: D E F A U L T
;
DELETE
: D E L E T E
;
DESC
: D E S C
;
DISABLE
: D I S A B L E
;
DROP
: D R O P
;
ENABLE
: E N A B L E
;
ESCAPE
: E S C A P E
;
EXISTS
: E X I S T S
;
FALSE
: F A L S E
;
FOREIGN
: F O R E I G N
;
FROM
: F R O M
;
GENERATED
: G E N E R A T E D
;
GROUP
: G R O U P
;
HAVING
: H A V I N G
;
IF
: I F
;
IN
: I N
;
INDEX
: I N D E X
;
IS
: I S
;
ISOLATION
: I S O L A T I O N
;
KEY
: K E Y
;
LEVEL
: L E V E L
;
LIKE
: L I K E
;
LIMIT
: L I M I T
;
MOD
: M O D
;
NO
: N O
;
NOT
: N O T
;
NULL
: N U L L
;
OFFSET
: O F F S E T
;
ON
: O N
;
OR
: O R
;
ORDER
: O R D E R
;
PARTITION
: P A R T I T I O N
;
PRIMARY
: P R I M A R Y
;
READ
: R E A D
;
RECURSIVE
: R E C U R S I V E
;
REFERENCES
: R E F E R E N C E S
;
REGEXP
: R E G E X P
;
ROLLBACK
: R O L L B A C K
;
ROLLUP
: R O L L U P
;
ROW
: R O W
;
SELECT
: S E L E C T
;
SERIALIZABLE
: S E R I A L I Z A B L E
;
SET
: S E T
;
SOUNDS
: S O U N D S
;
START
: S T A R T
;
TABLE
: T A B L E
;
TIME
: T I M E
;
TIMESTAMP
: T I M E S T A M P
;
TO
: T O
;
TRANSACTION
: T R A N S A C T I O N
;
TRUE
: T R U E
;
TRUNCATE
: T R U N C A T E
;
UNION
: U N I O N
;
UNIQUE
: U N I Q U E
;
UNKNOWN
: U N K N O W N
;
WHERE
: W H E R E
;
WITH
: W I T H
;
WORK
: W O R K
;
XOR
: X O R
;
YEAR
: Y E A R
;
CURRENT
: C U R R E N T
;
DAY
: D A Y
;
USER
: U S E R
;
|
add keyword
|
add keyword
|
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
|
d0d92e948a902923e33c08aad3b38479f17edf5c
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE createTableSpecification_ TABLE tableNotExistClause_ tableName (createDefinitionClause_ | createLikeClause_)
;
createIndex
: CREATE createIndexSpecification_ INDEX indexName indexType_? ON tableName
;
alterTable
: ALTER TABLE tableName alterDefinitionClause_?
;
dropTable
: DROP dropTableSpecification_ TABLE tableExistClause_ tableNames
;
dropIndex
: DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName
;
truncateTable
: TRUNCATE TABLE? tableName
;
createTableSpecification_
: TEMPORARY?
;
tableNotExistClause_
: (IF NOT EXISTS)?
;
createDefinitionClause_
: LP_ createDefinitions_ RP_
;
createDefinitions_
: createDefinition_ (COMMA_ createDefinition_)*
;
createDefinition_
: columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_
;
columnDefinition
: columnName dataType (inlineDataType_* | generatedDataType_*)
;
inlineDataType_
: commonDataTypeOption_
| AUTO_INCREMENT
| DEFAULT (literals | expr)
| COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT)
| STORAGE (DISK | MEMORY | DEFAULT)
;
commonDataTypeOption_
: primaryKey | UNIQUE KEY? | NOT? NULL | collateClause_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_
;
checkConstraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)?
;
referenceDefinition_
: REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)*
;
referenceOption_
: RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT
;
generatedDataType_
: commonDataTypeOption_
| (GENERATED ALWAYS)? AS expr
| (VIRTUAL | STORED)
;
indexDefinition_
: (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
indexType_
: USING (BTREE | HASH)
;
keyParts_
: LP_ keyPart_ (COMMA_ keyPart_)* RP_
;
keyPart_
: (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)?
;
indexOption_
: KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE
;
constraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_)
;
primaryKeyOption_
: primaryKey indexType_? columnNames indexOption_*
;
primaryKey
: PRIMARY? KEY
;
uniqueOption_
: UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
foreignKeyOption_
: FOREIGN KEY indexName? columnNames referenceDefinition_
;
createLikeClause_
: LP_? LIKE tableName RP_?
;
createIndexSpecification_
: (UNIQUE | FULLTEXT | SPATIAL)?
;
alterDefinitionClause_
: alterSpecification_ (COMMA_ alterSpecification_)*
;
alterSpecification_
: tableOptions_
| addColumnSpecification
| addIndexSpecification
| addConstraintSpecification
| ADD checkConstraintDefinition_
| DROP CHECK ignoredIdentifier_
| ALTER CHECK ignoredIdentifier_ NOT? ENFORCED
| ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY)
| ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT)
| ALTER INDEX indexName (VISIBLE | INVISIBLE)
| changeColumnSpecification
| DEFAULT? characterSet_ collateClause_?
| CONVERT TO characterSet_ collateClause_?
| (DISABLE | ENABLE) KEYS
| (DISCARD | IMPORT_) TABLESPACE
| dropColumnSpecification
| dropIndexSpecification
| dropPrimaryKeySpecification
| DROP FOREIGN KEY ignoredIdentifier_
| FORCE
| LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE)
| modifyColumnSpecification
// TODO hongjun investigate ORDER BY col_name [, col_name] ...
| ORDER BY columnNames
| renameColumnSpecification
| renameIndexSpecification
| renameTableSpecification_
| (WITHOUT | WITH) VALIDATION
| ADD PARTITION LP_ partitionDefinition_ RP_
| DROP PARTITION ignoredIdentifiers_
| DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| TRUNCATE PARTITION (ignoredIdentifiers_ | ALL)
| COALESCE PARTITION NUMBER_
| REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_
| EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)?
| ANALYZE PARTITION (ignoredIdentifiers_ | ALL)
| CHECK PARTITION (ignoredIdentifiers_ | ALL)
| OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL)
| REBUILD PARTITION (ignoredIdentifiers_ | ALL)
| REPAIR PARTITION (ignoredIdentifiers_ | ALL)
| REMOVE PARTITIONING
| UPGRADE PARTITIONING
;
tableOptions_
: tableOption_ (COMMA_? tableOption_)*
;
tableOption_
: AUTO_INCREMENT EQ_? NUMBER_
| AVG_ROW_LENGTH EQ_? NUMBER_
| DEFAULT? (characterSet_ | collateClause_)
| CHECKSUM EQ_? NUMBER_
| COMMENT EQ_? STRING_
| COMPRESSION EQ_? STRING_
| CONNECTION EQ_? STRING_
| (DATA | INDEX) DIRECTORY EQ_? STRING_
| DELAY_KEY_WRITE EQ_? NUMBER_
| ENCRYPTION EQ_? STRING_
| ENGINE EQ_? ignoredIdentifier_
| INSERT_METHOD EQ_? (NO | FIRST | LAST)
| KEY_BLOCK_SIZE EQ_? NUMBER_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| PACK_KEYS EQ_? (NUMBER_ | DEFAULT)
| PASSWORD EQ_? STRING_
| ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT)
| STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_)
| STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_)
| STATS_SAMPLE_PAGES EQ_? NUMBER_
| TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))?
| UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_
;
addColumnSpecification
: ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_)
;
firstOrAfterColumn
: FIRST | AFTER columnName
;
addIndexSpecification
: ADD indexDefinition_
;
addConstraintSpecification
: ADD constraintDefinition_
;
changeColumnSpecification
: CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn?
;
dropColumnSpecification
: DROP COLUMN? columnName
;
dropIndexSpecification
: DROP (INDEX | KEY) indexName
;
dropPrimaryKeySpecification
: DROP primaryKey
;
modifyColumnSpecification
: MODIFY COLUMN? columnDefinition firstOrAfterColumn?
;
// TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
// TODO hongjun: should support renameIndexSpecification on mysql
renameIndexSpecification
: RENAME (INDEX | KEY) indexName TO indexName
;
// TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table
renameTableSpecification_
: RENAME (TO | AS)? newTableName
;
newTableName
: identifier_
;
partitionDefinitions_
: LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_
;
partitionDefinition_
: PARTITION identifier_
(VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))?
partitionDefinitionOption_*
(LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)?
;
partitionLessThanValue_
: LP_ (expr | partitionValueList_) RP_ | MAXVALUE
;
partitionValueList_
: literals (COMMA_ literals)*
;
partitionDefinitionOption_
: STORAGE? ENGINE EQ_? identifier_
| COMMENT EQ_? STRING_
| DATA DIRECTORY EQ_? STRING_
| INDEX DIRECTORY EQ_? STRING_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| TABLESPACE EQ_? identifier_
;
subpartitionDefinition_
: SUBPARTITION identifier_ partitionDefinitionOption_*
;
dropTableSpecification_
: TEMPORARY?
;
tableExistClause_
: (IF EXISTS)?
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE createTableSpecification_ TABLE tableNotExistClause_ tableName (createDefinitionClause_ | createLikeClause_)
;
createIndex
: CREATE createIndexSpecification_ INDEX indexName indexType_? ON tableName
;
alterTable
: ALTER TABLE tableName alterDefinitionClause_?
;
dropTable
: DROP dropTableSpecification_ TABLE tableExistClause_ tableNames
;
dropIndex
: DROP INDEX dropIndexSpecification_ indexName ON tableName
;
truncateTable
: TRUNCATE TABLE? tableName
;
createTableSpecification_
: TEMPORARY?
;
tableNotExistClause_
: (IF NOT EXISTS)?
;
createDefinitionClause_
: LP_ createDefinitions_ RP_
;
createDefinitions_
: createDefinition_ (COMMA_ createDefinition_)*
;
createDefinition_
: columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_
;
columnDefinition
: columnName dataType (inlineDataType_* | generatedDataType_*)
;
inlineDataType_
: commonDataTypeOption_
| AUTO_INCREMENT
| DEFAULT (literals | expr)
| COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT)
| STORAGE (DISK | MEMORY | DEFAULT)
;
commonDataTypeOption_
: primaryKey | UNIQUE KEY? | NOT? NULL | collateClause_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_
;
checkConstraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)?
;
referenceDefinition_
: REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)*
;
referenceOption_
: RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT
;
generatedDataType_
: commonDataTypeOption_
| (GENERATED ALWAYS)? AS expr
| (VIRTUAL | STORED)
;
indexDefinition_
: (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
indexType_
: USING (BTREE | HASH)
;
keyParts_
: LP_ keyPart_ (COMMA_ keyPart_)* RP_
;
keyPart_
: (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)?
;
indexOption_
: KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE
;
constraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_)
;
primaryKeyOption_
: primaryKey indexType_? columnNames indexOption_*
;
primaryKey
: PRIMARY? KEY
;
uniqueOption_
: UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
foreignKeyOption_
: FOREIGN KEY indexName? columnNames referenceDefinition_
;
createLikeClause_
: LP_? LIKE tableName RP_?
;
createIndexSpecification_
: (UNIQUE | FULLTEXT | SPATIAL)?
;
alterDefinitionClause_
: alterSpecification_ (COMMA_ alterSpecification_)*
;
alterSpecification_
: tableOptions_
| addColumnSpecification
| addIndexSpecification
| addConstraintSpecification
| ADD checkConstraintDefinition_
| DROP CHECK ignoredIdentifier_
| ALTER CHECK ignoredIdentifier_ NOT? ENFORCED
| ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY)
| ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT)
| ALTER INDEX indexName (VISIBLE | INVISIBLE)
| changeColumnSpecification
| DEFAULT? characterSet_ collateClause_?
| CONVERT TO characterSet_ collateClause_?
| (DISABLE | ENABLE) KEYS
| (DISCARD | IMPORT_) TABLESPACE
| dropColumnSpecification
| dropIndexSpecification
| dropPrimaryKeySpecification
| DROP FOREIGN KEY ignoredIdentifier_
| FORCE
| LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE)
| modifyColumnSpecification
// TODO hongjun investigate ORDER BY col_name [, col_name] ...
| ORDER BY columnNames
| renameColumnSpecification
| renameIndexSpecification
| renameTableSpecification_
| (WITHOUT | WITH) VALIDATION
| ADD PARTITION LP_ partitionDefinition_ RP_
| DROP PARTITION ignoredIdentifiers_
| DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| TRUNCATE PARTITION (ignoredIdentifiers_ | ALL)
| COALESCE PARTITION NUMBER_
| REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_
| EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)?
| ANALYZE PARTITION (ignoredIdentifiers_ | ALL)
| CHECK PARTITION (ignoredIdentifiers_ | ALL)
| OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL)
| REBUILD PARTITION (ignoredIdentifiers_ | ALL)
| REPAIR PARTITION (ignoredIdentifiers_ | ALL)
| REMOVE PARTITIONING
| UPGRADE PARTITIONING
;
tableOptions_
: tableOption_ (COMMA_? tableOption_)*
;
tableOption_
: AUTO_INCREMENT EQ_? NUMBER_
| AVG_ROW_LENGTH EQ_? NUMBER_
| DEFAULT? (characterSet_ | collateClause_)
| CHECKSUM EQ_? NUMBER_
| COMMENT EQ_? STRING_
| COMPRESSION EQ_? STRING_
| CONNECTION EQ_? STRING_
| (DATA | INDEX) DIRECTORY EQ_? STRING_
| DELAY_KEY_WRITE EQ_? NUMBER_
| ENCRYPTION EQ_? STRING_
| ENGINE EQ_? ignoredIdentifier_
| INSERT_METHOD EQ_? (NO | FIRST | LAST)
| KEY_BLOCK_SIZE EQ_? NUMBER_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| PACK_KEYS EQ_? (NUMBER_ | DEFAULT)
| PASSWORD EQ_? STRING_
| ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT)
| STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_)
| STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_)
| STATS_SAMPLE_PAGES EQ_? NUMBER_
| TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))?
| UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_
;
addColumnSpecification
: ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_)
;
firstOrAfterColumn
: FIRST | AFTER columnName
;
addIndexSpecification
: ADD indexDefinition_
;
addConstraintSpecification
: ADD constraintDefinition_
;
changeColumnSpecification
: CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn?
;
dropColumnSpecification
: DROP COLUMN? columnName
;
dropIndexSpecification
: DROP (INDEX | KEY) indexName
;
dropPrimaryKeySpecification
: DROP primaryKey
;
modifyColumnSpecification
: MODIFY COLUMN? columnDefinition firstOrAfterColumn?
;
// TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
// TODO hongjun: should support renameIndexSpecification on mysql
renameIndexSpecification
: RENAME (INDEX | KEY) indexName TO indexName
;
// TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table
renameTableSpecification_
: RENAME (TO | AS)? newTableName
;
newTableName
: identifier_
;
partitionDefinitions_
: LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_
;
partitionDefinition_
: PARTITION identifier_
(VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))?
partitionDefinitionOption_*
(LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)?
;
partitionLessThanValue_
: LP_ (expr | partitionValueList_) RP_ | MAXVALUE
;
partitionValueList_
: literals (COMMA_ literals)*
;
partitionDefinitionOption_
: STORAGE? ENGINE EQ_? identifier_
| COMMENT EQ_? STRING_
| DATA DIRECTORY EQ_? STRING_
| INDEX DIRECTORY EQ_? STRING_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| TABLESPACE EQ_? identifier_
;
subpartitionDefinition_
: SUBPARTITION identifier_ partitionDefinitionOption_*
;
dropTableSpecification_
: TEMPORARY?
;
tableExistClause_
: (IF EXISTS)?
;
dropIndexSpecification_
: (ONLINE | OFFLINE)?
;
|
modify dropIndex rule
|
modify dropIndex rule
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
8aae72b5f1a0096fc6d4e880345b0ecebfe81950
|
graphql/GraphQL.g4
|
graphql/GraphQL.g4
|
/*
The MIT License (MIT)
Copyright (c) 2015 Joseph T. McBride
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
GraphQL grammar derived from:
GraphQL Draft Specification - July 2015
http://facebook.github.io/graphql/ https://github.com/facebook/graphql
AB:10-sep19: replaced type with type_ to resolve conflict for golang generator
AB: 13-oct-19: added type system as per June 2018 specs
AB: 26-oct-19: added ID type
AB: 30-Oct-19: description, boolean, schema & Block string fix.
now parses: https://raw.githubusercontent.com/graphql-cats/graphql-cats/master/scenarios/validation/validation.schema.graphql
*/
grammar GraphQL;
document: description* definition+;
definition:
execDefinition
| typeSystemDefinition
| typeSystemExtension;
// https://graphql.github.io/graphql-spec/June2018/#TypeSystemDefinition
typeSystemDefinition:
schemaDefinition
| typeDefinition
| directiveDefinition;
// https://graphql.github.io/graphql-spec/June2018/#sec-Schema
schemaDefinition:
'schema' directives? rootOperationTypeDefinitionList;
rootOperationTypeDefinitionList:
'{' rootOperationTypeDefinition (
','? rootOperationTypeDefinition
)* '}';
rootOperationTypeDefinition: operationType ':' namedType;
namedType: NAME;
//https://graphql.github.io/graphql-spec/June2018/#TypeDefinition
typeDefinition:
scalarTypeDefinition
| objectTypeDefinition
| interfaceTypeDefinition
| unionTypeDefinition
| enumTypeDefinition
| inputObjectTypeDefinition;
scalarTypeDefinition: description? 'scalar' NAME directives;
description: String_;
// https://graphql.github.io/graphql-spec/June2018/#sec-Objects
objectTypeDefinition
: description? 'type' NAME
implementsInterfaces?
directives?
fieldsDefinitions?;
implementsInterfaces: 'implements' '&'? type_ |
implementsInterfaces '&' type_;
fieldsDefinitions: '{' fieldsDefinition+'}';
fieldsDefinition: description? NAME argumentsDefinition? ':' type_ directives? ;
argumentsDefinition: '(' inputValueDefinition (',' inputValueDefinition)* ')';
inputValueDefinition: description? NAME ':' type_ defaultValue? directives?;
//https://graphql.github.io/graphql-spec/June2018/#sec-Interfaces
interfaceTypeDefinition
: description? 'interface' NAME directives? fieldsDefinitions?;
// https://graphql.github.io/graphql-spec/June2018/#sec-Unions
unionTypeDefinition: description? 'union' NAME directives? unionMemberTypes?;
unionMemberTypes: '=' type_ ('|' type_)* ;
unionTypeExtension : 'extend' unionTypeDefinition;
enumTypeDefinition: description? 'enum' NAME directives? enumValuesDefinitions?;
enumValuesDefinitions: '{' ( description? enumValue directives?)+ '}';
enumValue: NAME ;// not (nullValue | booleanValue)
enumTypeExtension: 'extend' enumTypeDefinition;
//https://graphql.github.io/graphql-spec/June2018/#InputObjectTypeDefinition
inputObjectTypeDefinition: description? 'input' NAME directives? inputFieldsDefinition?;
inputFieldsDefinition: '{' inputValueDefinition+ '}';
directiveDefinition: description? 'directive' '@' NAME argumentsDefinition? 'on' directiveLocations;
directiveLocations: directiveLocation ('|' directiveLocations)*;
directiveLocation: executableDirectiveLocation | typeSystemDirectiveLocation;
executableDirectiveLocation:
'QUERY' |
'MUTATION' |
'SUBSCRIPTION' |
'FIELD' |
'FRAGMENT_DEFINITION' |
'FRAGMENT_SPREAD' |
'INLINE_FRAGMENT';
typeSystemDirectiveLocation:
'SCHEMA' |
'SCALAR' |
'OBJECT' |
'FIELD_DEFINITION' |
'ARGUMENT_DEFINITION' |
'INTERFACE' |
'UNION' |
'ENUM' |
'ENUM_VALUE' |
'INPUT_OBJECT' |
'INPUT_FIELD_DEFINITION';
// https://graphql.github.io/graphql-spec/June2018/#sec-Type-System-Extensions
typeSystemExtension: schemaExtension | typeExtension;
schemaExtension: 'extend' schemaDefinition ;
typeExtension: 'extend' typeDefinition;
// original code: execution definitions
// GraphQL Draft Specification - July 2015
execDefinition: operationDefinition | fragmentDefinition;
operationDefinition:
selectionSet
| operationType NAME variableDefinitions? directives? selectionSet;
selectionSet: '{' selection ( ','? selection)* '}';
operationType: 'query' | 'mutation' | 'subscription';
selection: field | fragmentSpread | inlineFragment;
field: fieldName arguments? directives? selectionSet?;
fieldName: alias | NAME;
alias: NAME ':' NAME;
arguments: '(' argument ( ',' argument)* ')';
argument: NAME ':' valueOrVariable;
fragmentSpread: '...' fragmentName directives?;
inlineFragment:
'...' 'on' typeCondition directives? selectionSet;
fragmentDefinition:
'fragment' fragmentName 'on' typeCondition directives? selectionSet;
fragmentName: NAME;
directives: directive+;
directive:
'@' NAME ':' valueOrVariable
| '@' NAME
| '@' NAME '(' argument ')';
typeCondition: typeName;
variableDefinitions:
'(' variableDefinition (',' variableDefinition)* ')';
variableDefinition: variable ':' type_ defaultValue?;
variable: '$' NAME;
defaultValue: '=' value;
valueOrVariable: value | variable;
value:
String_ # stringValue
| NUMBER # numberValue
| BooleanLiteral # booleanValue
| array # arrayValue
| ID # idValue //The ID scalar type represents a unique identifier, often used to refetch an object or as the key for a cache. The ID type is serialized in the same way as a String; however, defining it as an ID signifies that it is not intended to be human‐readable.
| 'null' # nullValue
;
BooleanLiteral
: 'true'
| 'false'
;
type_: typeName nonNullType? | listType nonNullType?;
typeName: NAME;
listType: '[' type_ ']';
nonNullType: '!';
array: '[' value ( ',' value)* ']' | '[' ']';
NAME: [_A-Za-z] [_0-9A-Za-z]*;
String_ : STRING | BLOCK_STRING;
STRING: '"' ( ESC | ~ ["\\])* '"';
BLOCK_STRING
: '"""' .*? '"""'
;
ID: STRING;
fragment ESC: '\\' ( ["\\/bfnrt] | UNICODE);
fragment UNICODE: 'u' HEX HEX HEX HEX;
fragment HEX: [0-9a-fA-F];
NUMBER: '-'? INT '.' [0-9]+ EXP? | '-'? INT EXP | '-'? INT;
fragment INT: '0' | [1-9] [0-9]*;
// no leading zeros
fragment EXP: [Ee] [+\-]? INT;
// \- since - means "range" inside [...]
WS: [ \t\n\r]+ -> skip;
LineComment
: '#' ~[\r\n]*
-> skip
;
|
/*
The MIT License (MIT)
Copyright (c) 2015 Joseph T. McBride
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
GraphQL grammar derived from:
GraphQL Draft Specification - July 2015
http://facebook.github.io/graphql/ https://github.com/facebook/graphql
AB:10-sep19: replaced type with type_ to resolve conflict for golang generator
AB: 13-oct-19: added type system as per June 2018 specs
AB: 26-oct-19: added ID type
AB: 30-Oct-19: description, boolean, schema & Block string fix.
now parses: https://raw.githubusercontent.com/graphql-cats/graphql-cats/master/scenarios/validation/validation.schema.graphql
*/
grammar GraphQL;
document: description* definition+;
definition:
execDefinition
| typeSystemDefinition
| typeSystemExtension;
// https://graphql.github.io/graphql-spec/June2018/#TypeSystemDefinition
typeSystemDefinition:
schemaDefinition
| typeDefinition
| directiveDefinition;
// https://graphql.github.io/graphql-spec/June2018/#sec-Schema
schemaDefinition:
'schema' directives? rootOperationTypeDefinitionList;
rootOperationTypeDefinitionList:
'{' rootOperationTypeDefinition (
','? rootOperationTypeDefinition
)* '}';
rootOperationTypeDefinition: operationType ':' namedType;
namedType: NAME;
//https://graphql.github.io/graphql-spec/June2018/#TypeDefinition
typeDefinition:
scalarTypeDefinition
| objectTypeDefinition
| interfaceTypeDefinition
| unionTypeDefinition
| enumTypeDefinition
| inputObjectTypeDefinition;
scalarTypeDefinition: description? 'scalar' NAME directives;
description: String_;
// https://graphql.github.io/graphql-spec/June2018/#sec-Objects
objectTypeDefinition
: description? 'type' NAME
implementsInterfaces?
directives?
fieldsDefinitions?;
implementsInterfaces: 'implements' '&'? type_ |
implementsInterfaces '&' type_;
fieldsDefinitions: '{' fieldsDefinition+'}';
fieldsDefinition: description? NAME argumentsDefinition? ':' type_ directives? ;
argumentsDefinition: '(' inputValueDefinition (',' inputValueDefinition)* ')';
inputValueDefinition: description? NAME ':' type_ defaultValue? directives?;
//https://graphql.github.io/graphql-spec/June2018/#sec-Interfaces
interfaceTypeDefinition
: description? 'interface' NAME directives? fieldsDefinitions?;
// https://graphql.github.io/graphql-spec/June2018/#sec-Unions
unionTypeDefinition: description? 'union' NAME directives? unionMemberTypes?;
unionMemberTypes: '=' type_ ('|' type_)* ;
unionTypeExtension : 'extend' unionTypeDefinition;
enumTypeDefinition: description? 'enum' NAME directives? enumValuesDefinitions?;
enumValuesDefinitions: '{' ( description? enumElementValue directives?)+ '}';
enumElementValue: NAME ;// not (nullValue | booleanValue)
enumTypeExtension: 'extend' enumTypeDefinition;
//https://graphql.github.io/graphql-spec/June2018/#InputObjectTypeDefinition
inputObjectTypeDefinition: description? 'input' NAME directives? inputFieldsDefinition?;
inputFieldsDefinition: '{' inputValueDefinition+ '}';
directiveDefinition: description? 'directive' '@' NAME argumentsDefinition? 'on' directiveLocations;
directiveLocations: directiveLocation ('|' directiveLocations)*;
directiveLocation: executableDirectiveLocation | typeSystemDirectiveLocation;
executableDirectiveLocation:
'QUERY' |
'MUTATION' |
'SUBSCRIPTION' |
'FIELD' |
'FRAGMENT_DEFINITION' |
'FRAGMENT_SPREAD' |
'INLINE_FRAGMENT';
typeSystemDirectiveLocation:
'SCHEMA' |
'SCALAR' |
'OBJECT' |
'FIELD_DEFINITION' |
'ARGUMENT_DEFINITION' |
'INTERFACE' |
'UNION' |
'ENUM' |
'ENUM_VALUE' |
'INPUT_OBJECT' |
'INPUT_FIELD_DEFINITION';
// https://graphql.github.io/graphql-spec/June2018/#sec-Type-System-Extensions
typeSystemExtension: schemaExtension | typeExtension;
schemaExtension: 'extend' schemaDefinition ;
typeExtension: 'extend' typeDefinition;
// original code: execution definitions
// GraphQL Draft Specification - July 2015
execDefinition: operationDefinition | fragmentDefinition;
operationDefinition:
selectionSet
| operationType NAME variableDefinitions? directives? selectionSet;
selectionSet: '{' selection ( ','? selection)* '}';
operationType: 'query' | 'mutation' | 'subscription';
selection: field | fragmentSpread | inlineFragment;
field: fieldName arguments? directives? selectionSet?;
fieldName: alias | NAME;
alias: NAME ':' NAME;
arguments: '(' argument ( ',' argument)* ')';
argument: NAME ':' valueOrVariable;
fragmentSpread: '...' fragmentName directives?;
inlineFragment:
'...' 'on' typeCondition directives? selectionSet;
fragmentDefinition:
'fragment' fragmentName 'on' typeCondition directives? selectionSet;
fragmentName: NAME;
directives: directive+;
directive:
'@' NAME ':' valueOrVariable
| '@' NAME
| '@' NAME '(' argument ')';
typeCondition: typeName;
variableDefinitions:
'(' variableDefinition (',' variableDefinition)* ')';
variableDefinition: variable ':' type_ defaultValue?;
variable: '$' NAME;
defaultValue: '=' value;
valueOrVariable: value | variable;
value:
String_ # stringValue
| NAME # enumValue
| NUMBER # numberValue
| BooleanLiteral # booleanValue
| array # arrayValue
| ID # idValue //The ID scalar type represents a unique identifier, often used to refetch an object or as the key for a cache. The ID type is serialized in the same way as a String; however, defining it as an ID signifies that it is not intended to be human‐readable.
| 'null' # nullValue
;
BooleanLiteral
: 'true'
| 'false'
;
type_: typeName nonNullType? | listType nonNullType?;
typeName: NAME;
listType: '[' type_ ']';
nonNullType: '!';
array: '[' value ( ',' value)* ']' | '[' ']';
NAME: [_A-Za-z] [_0-9A-Za-z]*;
String_ : STRING | BLOCK_STRING;
STRING: '"' ( ESC | ~ ["\\])* '"';
BLOCK_STRING
: '"""' .*? '"""'
;
ID: STRING;
fragment ESC: '\\' ( ["\\/bfnrt] | UNICODE);
fragment UNICODE: 'u' HEX HEX HEX HEX;
fragment HEX: [0-9a-fA-F];
NUMBER: '-'? INT '.' [0-9]+ EXP? | '-'? INT EXP | '-'? INT;
fragment INT: '0' | [1-9] [0-9]*;
// no leading zeros
fragment EXP: [Ee] [+\-]? INT;
// \- since - means "range" inside [...]
WS: [ \t\n\r]+ -> skip;
LineComment
: '#' ~[\r\n]*
-> skip
;
|
Add enum value to array
|
Add enum value to array
Add ability to add enum values in an array
|
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
|
edbc5416a9bb266194435a0fa2251e8f0666e843
|
parser/Cel.g4
|
parser/Cel.g4
|
// Common Expression Language grammar for C++
// Based on Java grammar with the following changes:
// - rename grammar from CEL to Cel to generate C++ style compatible names.
grammar Cel;
// Grammar Rules
// =============
start
: e=expr EOF
;
expr
: e=conditionalOr (op='?' e1=conditionalOr ':' e2=expr)?
;
conditionalOr
: e=conditionalAnd (ops+='||' e1+=conditionalAnd)*
;
conditionalAnd
: e=relation (ops+='&&' e1+=relation)*
;
relation
: calc
| relation op=('<'|'<='|'>='|'>'|'=='|'!='|'in') relation
;
calc
: unary
| calc op=('*'|'/'|'%') calc
| calc op=('+'|'-') calc
;
unary
: member # MemberExpr
| (ops+='!')+ member # LogicalNot
| (ops+='-')+ member # Negate
;
member
: primary # PrimaryExpr
| member op='.' id=IDENTIFIER (open='(' args=exprList? ')')? # SelectOrCall
| member op='[' index=expr ']' # Index
| member op='{' entries=fieldInitializerList? ','? '}' # CreateMessage
;
primary
: leadingDot='.'? id=IDENTIFIER (op='(' args=exprList? ')')? # IdentOrGlobalCall
| '(' e=expr ')' # Nested
| op='[' elems=exprList? ','? ']' # CreateList
| op='{' entries=mapInitializerList? ','? '}' # CreateStruct
| literal # ConstantLiteral
;
exprList
: e+=expr (',' e+=expr)*
;
fieldInitializerList
: fields+=IDENTIFIER cols+=':' values+=expr (',' fields+=IDENTIFIER cols+=':' values+=expr)*
;
mapInitializerList
: keys+=expr cols+=':' values+=expr (',' keys+=expr cols+=':' values+=expr)*
;
literal
: sign=MINUS? tok=NUM_INT # Int
| tok=NUM_UINT # Uint
| sign=MINUS? tok=NUM_FLOAT # Double
| tok=STRING # String
| tok=BYTES # Bytes
| tok=TRUE # BoolTrue
| tok=FALSE # BoolFalse
| tok=NUL # Null
;
// Lexer Rules
// ===========
EQUALS : '==';
NOT_EQUALS : '!=';
LESS : '<';
LESS_EQUALS : '<=';
GREATER_EQUALS : '>=';
GREATER : '>';
LOGICAL_AND : '&&';
LOGICAL_OR : '||';
LBRACKET : '[';
RPRACKET : ']';
LBRACE : '{';
RBRACE : '}';
LPAREN : '(';
RPAREN : ')';
DOT : '.';
COMMA : ',';
MINUS : '-';
EXCLAM : '!';
QUESTIONMARK : '?';
COLON : ':';
PLUS : '+';
STAR : '*';
SLASH : '/';
PERCENT : '%';
TRUE : 'true';
FALSE : 'false';
NUL : 'null';
fragment BACKSLASH : '\\';
fragment LETTER : 'A'..'Z' | 'a'..'z' ;
fragment DIGIT : '0'..'9' ;
fragment EXPONENT : ('e' | 'E') ( '+' | '-' )? DIGIT+ ;
fragment HEXDIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ;
fragment RAW : 'r' | 'R';
fragment ESC_SEQ
: ESC_CHAR_SEQ
| ESC_BYTE_SEQ
| ESC_UNI_SEQ
| ESC_OCT_SEQ
;
fragment ESC_CHAR_SEQ
: BACKSLASH ('a'|'b'|'f'|'n'|'r'|'t'|'v'|'"'|'\''|'\\'|'?'|'`')
;
fragment ESC_OCT_SEQ
: BACKSLASH ('0'..'3') ('0'..'7') ('0'..'7')
;
fragment ESC_BYTE_SEQ
: BACKSLASH ( 'x' | 'X' ) HEXDIGIT HEXDIGIT
;
fragment ESC_UNI_SEQ
: BACKSLASH 'u' HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT
| BACKSLASH 'U' HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT
;
WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ -> channel(HIDDEN) ;
COMMENT : '//' (~'\n')* -> channel(HIDDEN) ;
NUM_FLOAT
: ( DIGIT+ ('.' DIGIT+) EXPONENT?
| DIGIT+ EXPONENT
| '.' DIGIT+ EXPONENT?
)
;
NUM_INT
: ( DIGIT+ | '0x' HEXDIGIT+ );
NUM_UINT
: DIGIT+ ( 'u' | 'U' )
| '0x' HEXDIGIT+ ( 'u' | 'U' )
;
STRING
: '"' (ESC_SEQ | ~('\\'|'"'|'\n'|'\r'))* '"'
| '\'' (ESC_SEQ | ~('\\'|'\''|'\n'|'\r'))* '\''
| '"""' (ESC_SEQ | ~('\\'))*? '"""'
| '\'\'\'' (ESC_SEQ | ~('\\'))*? '\'\'\''
| RAW '"' ~('"'|'\n'|'\r')* '"'
| RAW '\'' ~('\''|'\n'|'\r')* '\''
| RAW '"""' .*? '"""'
| RAW '\'\'\'' .*? '\'\'\''
;
BYTES : ('b' | 'B') STRING;
IDENTIFIER : (LETTER | '_') ( LETTER | DIGIT | '_')*;
|
// Common Expression Language grammar for C++
// Based on Java grammar with the following changes:
// - rename grammar from CEL to Cel to generate C++ style compatible names.
grammar Cel;
// Grammar Rules
// =============
start
: e=expr EOF
;
expr
: e=conditionalOr (op='?' e1=conditionalOr ':' e2=expr)?
;
conditionalOr
: e=conditionalAnd (ops+='||' e1+=conditionalAnd)*
;
conditionalAnd
: e=relation (ops+='&&' e1+=relation)*
;
relation
: calc
| relation op=('<'|'<='|'>='|'>'|'=='|'!='|'in') relation
;
calc
: unary
| calc op=('*'|'/'|'%') calc
| calc op=('+'|'-') calc
;
unary
: member # MemberExpr
| (ops+='!')+ member # LogicalNot
| (ops+='-')+ member # Negate
;
member
: primary # PrimaryExpr
| member op='.' id=IDENTIFIER (open='(' args=exprList? ')')? # SelectOrCall
| member op='[' index=expr ']' # Index
| member op='{' entries=fieldInitializerList? ','? '}' # CreateMessage
;
primary
: leadingDot='.'? id=IDENTIFIER (op='(' args=exprList? ')')? # IdentOrGlobalCall
| '(' e=expr ')' # Nested
| op='[' elems=exprList? ','? ']' # CreateList
| op='{' entries=mapInitializerList? ','? '}' # CreateStruct
| literal # ConstantLiteral
;
exprList
: e+=expr (',' e+=expr)*
;
fieldInitializerList
: fields+=IDENTIFIER cols+=':' values+=expr (',' fields+=IDENTIFIER cols+=':' values+=expr)*
;
mapInitializerList
: keys+=expr cols+=':' values+=expr (',' keys+=expr cols+=':' values+=expr)*
;
literal
: sign=MINUS? tok=NUM_INT # Int
| tok=NUM_UINT # Uint
| sign=MINUS? tok=NUM_FLOAT # Double
| tok=STRING # String
| tok=BYTES # Bytes
| tok=CELTRUE # BoolTrue
| tok=CELFALSE # BoolFalse
| tok=NUL # Null
;
// Lexer Rules
// ===========
EQUALS : '==';
NOT_EQUALS : '!=';
LESS : '<';
LESS_EQUALS : '<=';
GREATER_EQUALS : '>=';
GREATER : '>';
LOGICAL_AND : '&&';
LOGICAL_OR : '||';
LBRACKET : '[';
RPRACKET : ']';
LBRACE : '{';
RBRACE : '}';
LPAREN : '(';
RPAREN : ')';
DOT : '.';
COMMA : ',';
MINUS : '-';
EXCLAM : '!';
QUESTIONMARK : '?';
COLON : ':';
PLUS : '+';
STAR : '*';
SLASH : '/';
PERCENT : '%';
CELTRUE : 'true';
CELFALSE : 'false';
NUL : 'null';
fragment BACKSLASH : '\\';
fragment LETTER : 'A'..'Z' | 'a'..'z' ;
fragment DIGIT : '0'..'9' ;
fragment EXPONENT : ('e' | 'E') ( '+' | '-' )? DIGIT+ ;
fragment HEXDIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ;
fragment RAW : 'r' | 'R';
fragment ESC_SEQ
: ESC_CHAR_SEQ
| ESC_BYTE_SEQ
| ESC_UNI_SEQ
| ESC_OCT_SEQ
;
fragment ESC_CHAR_SEQ
: BACKSLASH ('a'|'b'|'f'|'n'|'r'|'t'|'v'|'"'|'\''|'\\'|'?'|'`')
;
fragment ESC_OCT_SEQ
: BACKSLASH ('0'..'3') ('0'..'7') ('0'..'7')
;
fragment ESC_BYTE_SEQ
: BACKSLASH ( 'x' | 'X' ) HEXDIGIT HEXDIGIT
;
fragment ESC_UNI_SEQ
: BACKSLASH 'u' HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT
| BACKSLASH 'U' HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT
;
WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ -> channel(HIDDEN) ;
COMMENT : '//' (~'\n')* -> channel(HIDDEN) ;
NUM_FLOAT
: ( DIGIT+ ('.' DIGIT+) EXPONENT?
| DIGIT+ EXPONENT
| '.' DIGIT+ EXPONENT?
)
;
NUM_INT
: ( DIGIT+ | '0x' HEXDIGIT+ );
NUM_UINT
: DIGIT+ ( 'u' | 'U' )
| '0x' HEXDIGIT+ ( 'u' | 'U' )
;
STRING
: '"' (ESC_SEQ | ~('\\'|'"'|'\n'|'\r'))* '"'
| '\'' (ESC_SEQ | ~('\\'|'\''|'\n'|'\r'))* '\''
| '"""' (ESC_SEQ | ~('\\'))*? '"""'
| '\'\'\'' (ESC_SEQ | ~('\\'))*? '\'\'\''
| RAW '"' ~('"'|'\n'|'\r')* '"'
| RAW '\'' ~('\''|'\n'|'\r')* '\''
| RAW '"""' .*? '"""'
| RAW '\'\'\'' .*? '\'\'\''
;
BYTES : ('b' | 'B') STRING;
IDENTIFIER : (LETTER | '_') ( LETTER | DIGIT | '_')*;
|
Rename TRUE and FALSE
|
Rename TRUE and FALSE
This avoids conflicts with default macros defined by the Windows and
macOS SDKs.
Fixes: https://github.com/google/cel-cpp/issues/121
|
ANTLR
|
apache-2.0
|
google/cel-cpp,google/cel-cpp
|
b1dfc0a1eef158cb74fc7e2781a5c62f29a9e5ee
|
refal/refal.g4
|
refal/refal.g4
|
/*
BSD License
Copyright (c) 2021, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar refal;
program
: f_definition (';'? program)?
| external_decl ';' program
| program external_decl ';'
;
f_definition
: f_name '{' block_ '}'
| '$ENTRY' f_name '{' block_ '}'
;
external_decl
: ('$EXTERNAL' | '$EXTERN' | '$EXTRN') f_name_list
;
f_name_list
: f_name (',' f_name_list ';')?
;
f_name
: identifier
;
block_
: sentence
| sentence ';'
| sentence ';' block_
;
sentence
: left_side conditions ('=' right_side | ',' block_ending)
;
left_side
: pattern
;
conditions
: (',' arg_ ':' pattern conditions)?
;
pattern
: expression_
;
arg_
: expression_
;
right_side
: expression_
;
expression_
: (term_ expression_)?
;
term_
: symbol
| variable
| '<' expression_ '>'
;
block_ending
: arg_ ':' '{' block_ '}'
;
symbol
: identifier
| DIGITS
| STRING
| STRING2
| CHAR
;
identifier
: IDENTIFER
| STRING
;
variable
: svar
| tvar
| evar
;
svar
: 's' '.' index
;
tvar
: 't' '.' index
;
evar
: 'e' '.' index
;
index
: identifier
| DIGITS
;
DIGITS
: [0-9]+
;
IDENTIFER
: [a-zA-Z] [a-zA-Z0-9_-]*
;
STRING
: '"' ~ '"'* '"'
;
STRING2
: '\'' ~ '\''* '\''
;
CHAR
: '\\\''
| '\\"'
| '\\\\'
| '\\n'
| '\\r'
| '\\t'
| '\\x' [0-9] [0-9]
;
WS
: [ \r\n\t]+ -> skip
;
|
/*
BSD License
Copyright (c) 2021, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar refal;
program
: f_definition (';'? program)?
| external_decl ';' program
| program external_decl ';'
;
f_definition
: f_name '{' block_ '}'
| '$ENTRY' f_name '{' block_ '}'
;
external_decl
: ('$EXTERNAL' | '$EXTERN' | '$EXTRN') f_name_list
;
f_name_list
: f_name (',' f_name_list ';')?
;
f_name
: identifier
;
block_
: sentence (';' block_?)?
;
sentence
: left_side conditions ('=' right_side | ',' block_ending)
;
left_side
: pattern
;
conditions
: (',' arg_ ':' pattern conditions)?
;
pattern
: expression_
;
arg_
: expression_
;
right_side
: expression_
;
expression_
: (term_ expression_)?
;
term_
: symbol
| variable
| '<' expression_ '>'
;
block_ending
: arg_ ':' '{' block_ '}'
;
symbol
: identifier
| DIGITS
| STRING
| STRING2
| CHAR
;
identifier
: IDENTIFER
| STRING
;
variable
: svar
| tvar
| evar
;
svar
: 's' '.' index
;
tvar
: 't' '.' index
;
evar
: 'e' '.' index
;
index
: identifier
| DIGITS
;
DIGITS
: [0-9]+
;
IDENTIFER
: [a-zA-Z] [a-zA-Z0-9_-]*
;
STRING
: '"' ~ '"'* '"'
;
STRING2
: '\'' ~ '\''* '\''
;
CHAR
: '\\\''
| '\\"'
| '\\\\'
| '\\n'
| '\\r'
| '\\t'
| '\\x' [0-9] [0-9]
;
WS
: [ \r\n\t]+ -> skip
;
|
Update refal/refal.g4
|
Update refal/refal.g4
Co-authored-by: Ivan Kochurkin <[email protected]>
|
ANTLR
|
mit
|
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
|
6346c20e313b5e261f4683c115055160b02da0c0
|
powerbuilder/powerbuilderLexer.g4
|
powerbuilder/powerbuilderLexer.g4
|
/*
BSD License
Copyright (c) 2018, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
lexer grammar powerbuilderLexer;
DATA_TYPE_SUB
: (A N Y) | (B L O B) | (B O O L E A N) | (B Y T E) | (C H A R A C T E R) | (C H A R) | (D A T E) | (D A T E T I M E) | (D E C I M A L) | (D E C) | (D O U B L E) | (I N T E G E R) | (I N T) | (L O N G) | (L O N G L O N G) | (R E A L) | (S T R I N G) | (T I M E) | (U N S I G N E D I N T E G E R) | (U I N T) | (U N S I G N E D L O N G) | (U L O N G) | (W I N D O W)
;
BOOLEAN_ATOM
: (T R U E) | (F A L S E)
;
GLOBAL
: G L O B A L
;
SHARED
: S H A R E D
;
END
: E N D
;
INDIRECT
: I N D I R E C T
;
VARIABLES
: V A R I A B L E S
;
FORWARD
: F O R W A R D
;
PUBLIC
: P U B L I C
;
PRIVATE
: P R I V A T E
;
FUNCTION
: F U N C T I O N
;
SUBROUTINE
: S U B R O U T I N E
;
READONLY
: R E A D O N L Y
;
PROTOTYPES
: P R O T O T Y P E S
;
TYPE
: T Y P E
;
ON
: O N
;
TO
: T O
;
FROM
: F R O M
;
REF
: R E F
;
NULL
: N U L L
;
UPDATE
: U P D A T E
;
CASE
: C A S E
;
DYNAMIC
: D Y N A M I C
;
WITHIN
: W I T H I N
;
PRIVATEWRITE
: P R I V A T E W R I T E
;
PROTECTED
: P R O T E C T E D
;
PRIVATEREAD
: P R I V A T E R E A D
;
PROTECTEDREAD
: P R O T E C T E D R E A D
;
PROTECTEDWRITE
: P R O T E C T E D W R I T E
;
LOCAL
: L O C A L
;
EVENT
: E V E N T
;
OPEN
: O P E N
;
GOTO
: G O T O
;
ELSE
: E L S E
;
IF
: I F
;
THEN
: T H E N
;
ELSEIF
: E L S E I F
;
TRY
: T R Y
;
EXIT
: E X I T
;
CHOOSE
: C H O O S E
;
IS
: I S
;
CONTINUE
: C O N T I N U E
;
DO
: D O
;
WHILE
: W H I L E
;
FOR
: F O R
;
CLOSE
: C L O S E
;
NEXT
: N E X T
;
LOOP
: L O O P
;
UNTIL
: U N T I L
;
STEP
: S T E P
;
CATCH
: C A T C H
;
FINALLY
: F I N A L L Y
;
THROW
: T H R O W
;
RELEASE
: R E L E A S E
;
CREATE
: C R E A T E
;
DESTROY
: D E S T R O Y
;
USING
: U S I N G
;
POST
: P O S T
;
TRIGGER
: T R I G G E R
;
SELECT
: S E L E C T
;
DELETE
: D E L E T E
;
INSERT
: I N S E R T
;
TIME2
: T I M E
;
DESCRIBE
: D E S C R I B E
;
RETURN
: R E T U R N
;
OR
: O R
;
AND
: A N D
;
NOT
: N O T
;
CALL
: C A L L
;
HALT
: H A L T
;
SUPER
: S U P E R
;
LIBRARY
: L I B R A R Y
;
SYSTEM
: S Y S T E M
;
RPCFUNC
: R P C F U N C
;
ALIAS
: A L I A S
;
THROWS
: T H R O W S
;
EQ
: '='
;
GT
: '>'
;
GTE
: '>='
;
LT
: '<'
;
LTE
: '<='
;
GTLT
: '<>'
;
PLUS
: '+'
;
MINUS
: '-'
;
PLUSEQ
: '+='
;
MINUSEQ
: '-='
;
COLONCOLON
: '::'
;
MULT
: '*'
;
DIV
: '/'
;
MULTEQ
: '*='
;
DIVEQ
: '/='
;
CARAT
: '^'
;
LCURLY
: '{'
;
RCURLY
: '}'
;
LBRACE
: '['
;
RBRACE
: ']'
;
BRACES
: '[]'
;
TICK
: '`'
;
AUTOINSTANTIATE
: A U T O I N S T A N T I A T E
;
DESCRIPTOR
: D E S C R I P T O R
;
DQUOTED_STRING
: '"' (E_TILDE | ~ ('"') | E_DOUBLE_QUOTE)* '"'
;
QUOTED_STRING
: '\'' (~ ('\'') | E_QUOTE)* '\''
;
fragment ID_PARTS
: [a-zA-Z] ([a-zA-Z] | DIGIT | '-' | '$' | '#' | '%' | '_')*
;
ENUM
: ID_PARTS '!'
;
COMMA
: ','
;
ID
: ID_PARTS
;
SEMI
: ';'
;
LPAREN
: '('
;
RPAREN
: ')'
;
COLON
: ':'
;
NUMBER
: ((NUM POINT NUM) | POINT NUM | NUM) ('E' ('+' | '-')? NUM)? ('D' | 'F')?
;
fragment NUM
: DIGIT (DIGIT)*
;
DOT
: POINT
;
fragment POINT
: '.'
;
DQUOTE
: '"'
;
fragment TAB
: '~t'
;
fragment CR
: '~r'
;
fragment LF
: '~n'
;
fragment E_DOUBLE_QUOTE
: '~"'
;
fragment E_QUOTE
: '~\''
;
fragment E_TILDE
: '~~'
;
fragment DIGIT
: '0' .. '9'
;
DATE
: DIGIT DIGIT DIGIT DIGIT '-' DIGIT DIGIT '-' DIGIT DIGIT
;
TIME
: DIGIT DIGIT ':' DIGIT DIGIT ':' DIGIT DIGIT (':' DIGIT DIGIT DIGIT DIGIT DIGIT DIGIT)?
;
BINDPAR
: ':' ID_PARTS
;
TQ
: '???'
;
DOUBLE_PIPE
: '||'
;
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')
;
LINE_CONTINUATION
: '&' WS* [\r\n] -> skip
;
DOTDOTDOT
: '...'
;
fragment LETTER
: 'A' .. 'Z' | 'a' .. 'z'
;
EXPORT_HEADER
: '$' 'A' .. 'Z' ((LETTER | DIGIT | '-' | '#' | '%' | '_'))* '$' (LETTER | DIGIT | '.' | ' ') + ~ [\r\n]
;
SL_COMMENT
: '//' ~ [\r\n]* -> skip
;
ML_COMMENT
: '/*' (.)*? '*/' -> skip
;
WS
: [ \t\r\n] + -> skip
;
|
/*
BSD License
Copyright (c) 2018, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
lexer grammar powerbuilderLexer;
// Keywords
DATA_TYPE_SUB: 'ANY'
| 'BLOB'
| 'BOOLEAN'
| 'BYTE'
| 'CHARACTER'
| 'CHAR'
| 'DATE'
| 'DATETIME'
| 'DECIMAL'
| 'DEC'
| 'DOUBLE'
| 'INTEGER'
| 'INT'
| 'LONG'
| 'LONGLONG'
| 'REAL'
| 'STRING'
| 'TIME'
| 'UNSIGNEDINTEGER'
| 'UINT'
| 'UNSIGNEDLONG'
| 'ULONG'
| 'WINDOW'
;
BOOLEAN_ATOM: 'TRUE'
| 'FALSE';
GLOBAL: 'GLOBAL';
SHARED: 'SHARED';
END: 'END';
INDIRECT : 'INDIRECT';
VARIABLES: 'VARIABLES';
FORWARD: 'FORWARD';
PUBLIC: 'PUBLIC';
PRIVATE: 'PRIVATE';
FUNCTION: 'FUNCTION';
SUBROUTINE: 'SUBROUTINE';
READONLY: 'READONLY';
PROTOTYPES: 'PROTOTYPES';
TYPE: 'TYPE';
ON: 'ON';
TO: 'TO';
FROM: 'FROM';
REF: 'REF';
NULL: 'NULL';
UPDATE: 'UPDATE';
CASE: 'CASE';
DYNAMIC: 'DYNAMIC';
WITHIN: 'WITHIN';
PRIVATEWRITE: 'PRIVATEWRITE';
PROTECTED: 'PROTECTED';
PRIVATEREAD: 'PRIVATEREAD';
PROTECTEDREAD: 'PROTECTEDREAD';
PROTECTEDWRITE: 'PROTECTEDWRITE';
LOCAL: 'LOCAL';
EVENT: 'EVENT';
OPEN: 'OPEN';
GOTO: 'GOTO';
ELSE: 'ELSE';
IF: 'IF';
THEN: 'THEN';
ELSEIF: 'ELSEIF';
TRY: 'TRY';
EXIT: 'EXIT';
CHOOSE: 'CHOOSE';
IS: 'IS';
CONTINUE: 'CONTINUE';
DO: 'DO';
WHILE: 'WHILE';
FOR: 'FOR';
CLOSE: 'CLOSE';
NEXT: 'NEXT';
LOOP: 'LOOP';
UNTIL: 'UNTIL';
STEP: 'STEP';
CATCH: 'CATCH';
FINALLY: 'FINALLY';
THROW: 'THROW';
RELEASE: 'RELEASE';
CREATE: 'CREATE';
DESTROY: 'DESTROY';
USING: 'USING';
POST: 'POST';
TRIGGER: 'TRIGGER';
SELECT: 'SELECT';
DELETE: 'DELETE';
INSERT: 'INSERT';
TIME2: 'TIME';
DESCRIBE: 'DESCRIBE';
RETURN: 'RETURN';
OR: 'OR';
AND: 'AND';
NOT: 'NOT';
CALL: 'CALL';
HALT: 'HALT';
SUPER: 'SUPER';
LIBRARY: 'LIBRARY';
SYSTEM: 'SYSTEM';
RPCFUNC: 'RPCFUNC';
ALIAS: 'ALIAS';
THROWS: 'THROWS';
AUTOINSTANTIATE: 'AUTOINSTANTIATE';
DESCRIPTOR: 'DESCRIPTOR';
// Operators
EQ: '=';
GT: '>';
GTE: '>=';
LT: '<';
LTE: '<=';
GTLT: '<>';
PLUS: '+';
MINUS: '-';
PLUSEQ: '+=';
MINUSEQ: '-=';
COLONCOLON: '::';
MULT: '*';
DIV: '/';
MULTEQ: '*=';
DIVEQ: '/=';
CARAT: '^';
LCURLY: '{';
RCURLY: '}';
LBRACE: '[';
RBRACE: ']';
BRACES: '[]';
TICK: '`';
DQUOTED_STRING: '"' ('~~' | ~'"' | '~"')* '"';
QUOTED_STRING: '\'' (~'\'' | '~\'')* '\'';
COMMA: ',';
SEMI: ';';
LPAREN: '(';
RPAREN: ')';
COLON: ':';
DQUOTE: '"';
TQ: '???';
DOUBLE_PIPE: '||';
DOTDOTDOT: '...';
// Literals
NUMBER: (NUM '.' NUM | '.' NUM | NUM) ('E' ('+' | '-')? NUM)? ('D' | 'F')?;
DOT: '.';
DATE: DIGIT DIGIT DIGIT DIGIT '-' DIGIT DIGIT '-' DIGIT DIGIT;
TIME: DIGIT DIGIT ':' DIGIT DIGIT ':' DIGIT DIGIT (':' DIGIT DIGIT DIGIT DIGIT DIGIT DIGIT)?;
BINDPAR: ':' ID_PARTS;
EXPORT_HEADER: '$' LETTER ((LETTER | DIGIT | '-' | '#' | '%' | '_'))* '$' (LETTER | DIGIT | '.' | ' ')+ ~[\r\n];
ENUM: ID_PARTS '!';
ID: ID_PARTS;
// Hidden
LINE_CONTINUATION: '&' WS* [\r\n] -> channel(HIDDEN);
SL_COMMENT: '//' ~ [\r\n]* -> channel(HIDDEN);
ML_COMMENT: '/*' .*? '*/' -> channel(HIDDEN);
WS: [ \t\r\n]+ -> channel(HIDDEN);
// Fragments
fragment ID_PARTS
: [A-Z] ([A-Z] | DIGIT | '-' | '$' | '#' | '%' | '_')*
;
fragment NUM
: DIGIT+
;
fragment DIGIT
: '0' .. '9'
;
fragment LETTER
: 'A' .. 'Z'
;
|
Simplify powerbuilderLexer.g4
|
Simplify powerbuilderLexer.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
|
dd5fcea8645319abb22479b3551564f126d86781
|
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;
ifExists
: IF EXISTS;
ifNotExists
: IF NOT EXISTS;
dataTypeLength
: LEFT_PAREN (NUMBER (COMMA NUMBER)?)? RIGHT_PAREN
;
nullNotnull
: NULL
| NOT NULL
;
primaryKey
: PRIMARY? KEY
;
matchNone
: 'Default does not match anything'
;
idList
: LEFT_PAREN ID (COMMA ID)* RIGHT_PAREN
;
rangeClause
: NUMBER (COMMA NUMBER)*
| NUMBER OFFSET NUMBER
;
tableNamesWithParen
: LEFT_PAREN tableNames RIGHT_PAREN
;
tableNames
: tableName (COMMA tableName)*
;
columnNamesWithParen
: LEFT_PAREN columnNames RIGHT_PAREN
;
columnNames
: columnName (COMMA columnName)*
;
columnList
: LEFT_PAREN columnNames RIGHT_PAREN
;
indexNames
: indexName (COMMA indexName)*
;
rowNames
: rowName (COMMA rowName)*
;
bitExprs:
bitExpr (COMMA bitExpr)*
;
exprs
: expr (COMMA expr)*
;
exprsWithParen
: LEFT_PAREN exprs RIGHT_PAREN
;
//https://dev.mysql.com/doc/refman/8.0/en/expressions.html
expr
: expr OR expr
| expr OR_SYM expr
| expr XOR expr
| expr AND expr
| expr AND_SYM expr
| LEFT_PAREN expr RIGHT_PAREN
| NOT expr
| NOT_SYM expr
| booleanPrimary
| exprRecursive
;
exprRecursive
: matchNone
;
booleanPrimary
: booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL)
| booleanPrimary SAFE_EQ predicate
| booleanPrimary comparisonOperator predicate
| booleanPrimary comparisonOperator (ALL | ANY) subquery
| predicate
;
comparisonOperator
: EQ_OR_ASSIGN
| GTE
| GT
| LTE
| LT
| NEQ_SYM
| NEQ
;
predicate
: bitExpr NOT? IN subquery
| bitExpr NOT? IN LEFT_PAREN simpleExpr ( COMMA simpleExpr)* RIGHT_PAREN
| bitExpr NOT? BETWEEN simpleExpr AND predicate
| bitExpr SOUNDS LIKE simpleExpr
| bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)*
| bitExpr NOT? REGEXP simpleExpr
| bitExpr
;
bitExpr
: bitExpr BIT_INCLUSIVE_OR bitExpr
| bitExpr BIT_AND bitExpr
| bitExpr SIGNED_LEFT_SHIFT bitExpr
| bitExpr SIGNED_RIGHT_SHIFT bitExpr
| bitExpr PLUS bitExpr
| bitExpr MINUS bitExpr
| bitExpr ASTERISK bitExpr
| bitExpr SLASH bitExpr
| bitExpr MOD bitExpr
| bitExpr MOD_SYM bitExpr
| bitExpr BIT_EXCLUSIVE_OR bitExpr
//| bitExpr '+' interval_expr
//| bitExpr '-' interval_expr
| simpleExpr
;
simpleExpr
: functionCall
| liter
| ID
| simpleExpr collateClause
//| param_marker
//| variable
| simpleExpr AND_SYM simpleExpr
| PLUS simpleExpr
| MINUS simpleExpr
| UNARY_BIT_COMPLEMENT simpleExpr
| NOT_SYM simpleExpr
| BINARY simpleExpr
| LEFT_PAREN expr RIGHT_PAREN
| ROW LEFT_PAREN simpleExpr( COMMA simpleExpr)* RIGHT_PAREN
| subquery
| EXISTS subquery
// | (identifier expr)
//| match_expr
//| case_expr
// | interval_expr
|privateExprOfDb
;
functionCall
: ID LEFT_PAREN( bitExprs?) RIGHT_PAREN
;
privateExprOfDb
: matchNone
;
liter
: QUESTION
| NUMBER
| TRUE
| FALSE
| NULL
| LEFT_BRACE ID STRING RIGHT_BRACE
| HEX_DIGIT
| ID? STRING collateClause?
| (DATE | TIME |TIMESTAMP) STRING
| ID? BIT_NUM collateClause?
;
subquery
: matchNone
;
collateClause
: matchNone
;
orderByClause
: ORDER BY groupByItem (COMMA groupByItem)*
;
groupByItem
: (columnName | NUMBER |expr) (ASC|DESC)?
;
|
//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)*
;
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)?
;
|
add userName
|
add userName
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
|
482bce7bafa47aa5456fc70609562395204b38bb
|
sharding-core/src/main/antlr4/imports/MySQLKeyword.g4
|
sharding-core/src/main/antlr4/imports/MySQLKeyword.g4
|
lexer grammar MySQLKeyword;
import Symbol;
ACTION
: A C T I O N
;
AFTER
: A F T E R
;
ALGORITHM
: A L G O R I T H M
;
ANALYZE
: A N A L Y Z E
;
AUTO_INCREMENT
: A U T O UL_ I N C R E M E N T
;
AVG_ROW_LENGTH
: A V G UL_ R O W UL_ L E N G T H
;
BEGIN
: B E G I N
;
BTREE
: B T R E E
;
CASE
: C A S E
;
CHAIN
: C H A I N
;
CHANGE
: C H A N G E
;
CHAR
: C H A R
;
CHARACTER
: C H A R A C T E R
;
CHARSET
: C H A R S E T
;
CHECKSUM
: C H E C K S U M
;
COALESCE
: C O A L E S C E
;
COLLATE
: C O L L A T E
;
COLUMNS
: C O L U M N S
;
COLUMN_FORMAT
: C O L U M N UL_ F O R M A T
;
COMMENT
: C O M M E N T
;
COMPACT
: C O M P A C T
;
COMPRESSED
: C O M P R E S S E D
;
COMPRESSION
: C O M P R E S S I O N
;
CONNECTION
: C O N N E C T I O N
;
CONSISTENT
: C O N S I S T E N T
;
CONVERT
: C O N V E R T
;
COPY
: C O P Y
;
CROSS
: C R O S S
;
CURRENT_TIMESTAMP
: C U R R E N T UL_ T I M E S T A M P
;
DATA
: D A T A
;
DELAYED
: D E L A Y E D
;
DELAY_KEY_WRITE
: D E L A Y UL_ K E Y UL_ W R I T E
;
DIRECTORY
: D I R E C T O R Y
;
DISCARD
: D I S C A R D
;
DISK
: D I S K
;
DISTINCT
: D I S T I N C T
;
DISTINCTROW
: D I S T I N C T R O W
;
DOUBLE
: D O U B L E
;
DUPLICATE
: D U P L I C A T E
;
DYNAMIC
: D Y N A M I C
;
ELSE
: E L S E
;
ENCRYPTION
: E N C R Y P T I O N
;
END
: E N D
;
ENGINE
: E N G I N E
;
EXCHANGE
: E X C H A N G E
;
EXCLUSIVE
: E X C L U S I V E
;
FIRST
: F I R S T
;
FIXED
: F I X E D
;
FOR
: F O R
;
FORCE
: F O R C E
;
FULL
: F U L L
;
FULLTEXT
: F U L L T E X T
;
GLOBAL
: G L O B A L
;
HASH
: H A S H
;
HIGH_PRIORITY
: H I G H UL_ P R I O R I T Y
;
IGNORE
: I G N O R E
;
IMPORT_
: I M P O R T UL_
;
INNER
: I N N E R
;
INPLACE
: I N P L A C E
;
INSERT
: I N S E R T
;
INSERT_METHOD
: I N S E R T UL_ M E T H O D
;
INTO
: I N T O
;
JOIN
: J O I N
;
KEYS
: K E Y S
;
KEY_BLOCK_SIZE
: K E Y UL_ B L O C K UL_ S I Z E
;
LAST
: L A S T
;
LEFT
: L E F T
;
LESS
: L E S S
;
LINEAR
: L I N E A R
;
LIST
: L I S T
;
LOCALTIME
: L O C A L T I M E
;
LOCALTIMESTAMP
: L O C A L T I M E S T A M P
;
LOCK
: L O C K
;
LOW_PRIORITY
: L O W UL_ P R I O R I T Y
;
MATCH
: M A T C H
;
MAXVALUE
: M A X V A L U E
;
MAX_ROWS
: M A X UL_ R O W S
;
MEMORY
: M E M O R Y
;
MIN_ROWS
: M I N UL_ R O W S
;
MODIFY
: M O D I F Y
;
NATURAL
: N A T U R A L
;
NONE
: N O N E
;
NOW
: N O W
;
OFFLINE
: O F F L I N E
;
ONLINE
: O N L I N E
;
ONLY
: O N L Y
;
OPTIMIZE
: O P T I M I Z E
;
OUTER
: O U T E R
;
PACK_KEYS
: P A C K UL_ K E Y S
;
PARSER
: P A R S E R
;
PARTIAL
: P A R T I A L
;
PARTITIONING
: P A R T I T I O N I N G
;
PARTITIONS
: P A R T I T I O N S
;
PASSWORD
: P A S S W O R D
;
PERSIST
: P E R S I S T
;
PERSIST_ONLY
: P E R S I S T UL_ O N L Y
;
PRECISION
: P R E C I S I O N
;
QUICK
: Q U I C K
;
RANGE
: R A N G E
;
REBUILD
: R E B U I L D
;
REDUNDANT
: R E D U N D A N T
;
RELEASE
: R E L E A S E
;
REMOVE
: R E M O V E
;
RENAME
: R E N A M E
;
REORGANIZE
: R E O R G A N I Z E
;
REPAIR
: R E P A I R
;
REPEATABLE
: R E P E A T A B L E
;
REPLACE
: R E P L A C E
;
RESTRICT
: R E S T R I C T
;
RIGHT
: R I G H T
;
ROW_FORMAT
: R O W UL_ F O R M A T
;
SAVEPOINT
: S A V E P O I N T
;
SESSION
: S E S S I O N
;
SHARED
: S H A R E D
;
SIMPLE
: S I M P L E
;
SNAPSHOT
: S N A P S H O T
;
SPATIAL
: S P A T I A L
;
SQLDML
: S Q L D M L
;
SQLDQL
: S Q L D Q L
;
SQL_BIG_RESULT
: S Q L UL_ B I G UL_ R E S U L T
;
SQL_BUFFER_RESULT
: S Q L UL_ B U F F E R UL_ R E S U L T
;
SQL_CACHE
: S Q L UL_ C A C H E
;
SQL_CALC_FOUND_ROWS
: S Q L UL_ C A L C UL_ F O U N D UL_ R O W S
;
SQL_NO_CACHE
: S Q L UL_ N O UL_ C A C H E
;
SQL_SMALL_RESULT
: S Q L UL_ S M A L L UL_ R E S U L T
;
STATS_AUTO_RECALC
: S T A T S UL_ A U T O UL_ R E C A L C
;
STATS_PERSISTENT
: S T A T S UL_ P E R S I S T E N T
;
STATS_SAMPLE_PAGES
: S T A T S UL_ S A M P L E UL_ P A G E S
;
STORAGE
: S T O R A G E
;
STORED
: S T O R E D
;
STRAIGHT_JOIN
: S T R A I G H T UL_ J O I N
;
SUBPARTITION
: S U B P A R T I T I O N
;
SUBPARTITIONS
: S U B P A R T I T I O N S
;
TABLESPACE
: T A B L E S P A C E
;
TEMPORARY
: T E M P O R A R Y
;
THAN
: T H A N
;
THEN
: T H E N
;
UNCOMMITTED
: U N C O M M I T T E D
;
UNSIGNED
: U N S I G N E D
;
UPDATE
: U P D A T E
;
UPGRADE
: U P G R A D E
;
USE
: U S E
;
USING
: U S I N G
;
VALIDATION
: V A L I D A T I O N
;
VALUE
: V A L U E
;
VALUES
: V A L U E S
;
VIRTUAL
: V I R T U A L
;
WHEN
: W H E N
;
WITHOUT
: W I T H O U T
;
WRITE
: W R I T E
;
ZEROFILL
: Z E R O F I L L
;
|
lexer grammar MySQLKeyword;
import Symbol;
ACTION
: A C T I O N
;
ADMIN
: A D M I N
;
AFTER
: A F T E R
;
ALGORITHM
: A L G O R I T H M
;
ANALYZE
: A N A L Y Z E
;
AT_
: A T UL_
;
AUDIT_ADMIN
: A U D I T UL_ A D M I N
;
AUTO_INCREMENT
: A U T O UL_ I N C R E M E N T
;
AVG_ROW_LENGTH
: A V G UL_ R O W UL_ L E N G T H
;
BEGIN
: B E G I N
;
BINLOG_ADMIN
: B I N L O G UL_ A D M I N
;
BTREE
: B T R E E
;
CASE
: C A S E
;
CHAIN
: C H A I N
;
CHANGE
: C H A N G E
;
CHAR
: C H A R
;
CHARACTER
: C H A R A C T E R
;
CHARSET
: C H A R S E T
;
CHECKSUM
: C H E C K S U M
;
CLIENT
: C L I E N T
;
COALESCE
: C O A L E S C E
;
COLLATE
: C O L L A T E
;
COLUMNS
: C O L U M N S
;
COLUMN_FORMAT
: C O L U M N UL_ F O R M A T
;
COMMENT
: C O M M E N T
;
COMPACT
: C O M P A C T
;
COMPRESSED
: C O M P R E S S E D
;
COMPRESSION
: C O M P R E S S I O N
;
CONNECTION
: C O N N E C T I O N
;
CONNECTION_ADMIN
: C O N N E C T I O N UL_ A D M I N
;
CONSISTENT
: C O N S I S T E N T
;
CONVERT
: C O N V E R T
;
COPY
: C O P Y
;
CROSS
: C R O S S
;
CURRENT_TIMESTAMP
: C U R R E N T UL_ T I M E S T A M P
;
DATA
: D A T A
;
DATABASES
: D A T A B A S E S
;
DELAYED
: D E L A Y E D
;
DELAY_KEY_WRITE
: D E L A Y UL_ K E Y UL_ W R I T E
;
DIRECTORY
: D I R E C T O R Y
;
DISCARD
: D I S C A R D
;
DISK
: D I S K
;
DISTINCT
: D I S T I N C T
;
DISTINCTROW
: D I S T I N C T R O W
;
DOUBLE
: D O U B L E
;
DUPLICATE
: D U P L I C A T E
;
DYNAMIC
: D Y N A M I C
;
ELSE
: E L S E
;
ENCRYPTION
: E N C R Y P T I O N
;
ENCRYPTION_KEY_ADMIN
: E N C R Y P T I O N UL_ K E Y UL_ A D M I N
;
END
: E N D
;
ENGINE
: E N G I N E
;
EVENT
: E V E N T
;
EXCHANGE
: E X C H A N G E
;
EXCLUSIVE
: E X C L U S I V E
;
EXECUTE
: E X E C U T E
;
FILE
: F I L E
;
FIREWALL_ADMIN
: F I R E W A L L UL_ A D M I N
;
FIREWALL_USER
: F I R E W A L L UL_ U S E R
;
FIRST
: F I R S T
;
FIXED
: F I X E D
;
FOR
: F O R
;
FORCE
: F O R C E
;
FULL
: F U L L
;
FULLTEXT
: F U L L T E X T
;
FUNCTION
: F U N C T I O N
;
GLOBAL
: G L O B A L
;
GRANT
: G R A N T
;
GROUP_REPLICATION_ADMIN
: G R O U P UL_ R E P L I C A T I O N UL_ A D M I N
;
HASH
: H A S H
;
HIGH_PRIORITY
: H I G H UL_ P R I O R I T Y
;
IGNORE
: I G N O R E
;
IMPORT_
: I M P O R T UL_
;
INNER
: I N N E R
;
INPLACE
: I N P L A C E
;
INSERT
: I N S E R T
;
INSERT_METHOD
: I N S E R T UL_ M E T H O D
;
INTO
: I N T O
;
JOIN
: J O I N
;
KEYS
: K E Y S
;
KEY_BLOCK_SIZE
: K E Y UL_ B L O C K UL_ S I Z E
;
LAST
: L A S T
;
LEFT
: L E F T
;
LESS
: L E S S
;
LINEAR
: L I N E A R
;
LIST
: L I S T
;
LOCALTIME
: L O C A L T I M E
;
LOCALTIMESTAMP
: L O C A L T I M E S T A M P
;
LOCK
: L O C K
;
LOW_PRIORITY
: L O W UL_ P R I O R I T Y
;
MATCH
: M A T C H
;
MAXVALUE
: M A X V A L U E
;
MAX_ROWS
: M A X UL_ R O W S
;
MEMORY
: M E M O R Y
;
MIN_ROWS
: M I N UL_ R O W S
;
MODIFY
: M O D I F Y
;
NATURAL
: N A T U R A L
;
NONE
: N O N E
;
NOW
: N O W
;
OFFLINE
: O F F L I N E
;
ONLINE
: O N L I N E
;
ONLY
: O N L Y
;
OPTIMIZE
: O P T I M I Z E
;
OPTION
: O P T I O N
;
OUTER
: O U T E R
;
PACK_KEYS
: P A C K UL_ K E Y S
;
PARSER
: P A R S E R
;
PARTIAL
: P A R T I A L
;
PARTITIONING
: P A R T I T I O N I N G
;
PARTITIONS
: P A R T I T I O N S
;
PASSWORD
: P A S S W O R D
;
PERSIST
: P E R S I S T
;
PERSIST_ONLY
: P E R S I S T UL_ O N L Y
;
PRECISION
: P R E C I S I O N
;
PRIVILEGES
: P R I V I L E G E S
;
PROCEDURE
: P R O C E D U R E
;
PROCESS
: P R O C E S S
;
PROXY
: P R O X Y
;
QUICK
: Q U I C K
;
RANGE
: R A N G E
;
REBUILD
: R E B U I L D
;
REDUNDANT
: R E D U N D A N T
;
RELEASE
: R E L E A S E
;
RELOAD
: R E L O A D
;
REMOVE
: R E M O V E
;
RENAME
: R E N A M E
;
REORGANIZE
: R E O R G A N I Z E
;
REPAIR
: R E P A I R
;
REPEATABLE
: R E P E A T A B L E
;
REPLACE
: R E P L A C E
;
REPLICATION
: R E P L I C A T I O N
;
REPLICATION_SLAVE_ADMIN
: R E P L I C A T I O N UL_ S L A V E UL_ A D M I N
;
RESTRICT
: R E S T R I C T
;
RIGHT
: R I G H T
;
ROLE_ADMIN
: R O L E UL_ A D M I N
;
ROUTINE
: R O U T I N E
;
ROW_FORMAT
: R O W UL_ F O R M A T
;
SAVEPOINT
: S A V E P O I N T
;
SESSION
: S E S S I O N
;
SET_USER_ID
: S E T UL_ U S E R UL_ I D
;
SHARED
: S H A R E D
;
SHOW
: S H O W
;
SHUTDOWN
: S H U T D O W N
;
SIMPLE
: S I M P L E
;
SLAVE
: S L A V E
;
SNAPSHOT
: S N A P S H O T
;
SPATIAL
: S P A T I A L
;
SQLDML
: S Q L D M L
;
SQLDQL
: S Q L D Q L
;
SQL_BIG_RESULT
: S Q L UL_ B I G UL_ R E S U L T
;
SQL_BUFFER_RESULT
: S Q L UL_ B U F F E R UL_ R E S U L T
;
SQL_CACHE
: S Q L UL_ C A C H E
;
SQL_CALC_FOUND_ROWS
: S Q L UL_ C A L C UL_ F O U N D UL_ R O W S
;
SQL_NO_CACHE
: S Q L UL_ N O UL_ C A C H E
;
SQL_SMALL_RESULT
: S Q L UL_ S M A L L UL_ R E S U L T
;
STATS_AUTO_RECALC
: S T A T S UL_ A U T O UL_ R E C A L C
;
STATS_PERSISTENT
: S T A T S UL_ P E R S I S T E N T
;
STATS_SAMPLE_PAGES
: S T A T S UL_ S A M P L E UL_ P A G E S
;
STORAGE
: S T O R A G E
;
STORED
: S T O R E D
;
STRAIGHT_JOIN
: S T R A I G H T UL_ J O I N
;
SUBPARTITION
: S U B P A R T I T I O N
;
SUBPARTITIONS
: S U B P A R T I T I O N S
;
SUPER
: S U P E R
;
SYSTEM_VARIABLES_ADMIN
: S Y S T E M UL_ V A R I A B L E S UL_ A D M I N
;
TABLES
: T A B L E S
;
TABLESPACE
: T A B L E S P A C E
;
TEMPORARY
: T E M P O R A R Y
;
THAN
: T H A N
;
THEN
: T H E N
;
TRIGGER
: T R I G G E R
;
UNCOMMITTED
: U N C O M M I T T E D
;
UNSIGNED
: U N S I G N E D
;
UPDATE
: U P D A T E
;
UPGRADE
: U P G R A D E
;
USAGE
: U S A G E
;
USE
: U S E
;
USER
: U S E R
;
USING
: U S I N G
;
VALIDATION
: V A L I D A T I O N
;
VALUE
: V A L U E
;
VALUES
: V A L U E S
;
VERSION_TOKEN_ADMIN
: V E R S I O N UL_ T O K E N UL_ A D M I N
;
VIEW
: V I E W
;
VIRTUAL
: V I R T U A L
;
WHEN
: W H E N
;
WITHOUT
: W I T H O U T
;
WRITE
: W R I T E
;
ZEROFILL
: Z E R O F I L L
;
|
add mysql keywords
|
add mysql keywords
|
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
|
3d15523e7c671662db00f9eb7ff5986e94f6dd79
|
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 alterDefinitionClause_
;
alterIndex
: ALTER INDEX (indexName | ALL) ON tableName
;
dropTable
: DROP TABLE tableExistClause_ tableNames
;
dropIndex
: DROP INDEX indexExistClause_ 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 encryptedOptions_
| columnConstraint (COMMA_ columnConstraint)*
| columnIndex
;
encryptedOptions_
: LP_ COLUMN_ENCRYPTION_KEY EQ_ ignoredIdentifier_ COMMA_ ENCRYPTION_TYPE EQ_ (DETERMINISTIC | RANDOMIZED) COMMA_ ALGORITHM EQ_ STRING_ RP_
;
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)? withIndexOption_? indexOnClause? fileStreamOn_?
;
withIndexOption_
: WITH LP_ indexOption (COMMA_ indexOption)* RP_
;
indexOnClause
: onSchemaColumn | onFileGroup | onDefault
;
onDefault
: ON DEFAULT
;
fileStreamOn_
: FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_)
;
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)?
;
alterDefinitionClause_
: modifyColumnSpecification | addColumnSpecification | alterDrop | alterCheckConstraint | alterTrigger | alterSwitch | alterSet | alterTableOption | REBUILD
;
modifyColumnSpecification
: alterColumnOperation dataType (COLLATE collationName)? (NULL | NOT NULL)? SPARSE?
;
alterColumnOperation
: ALTER COLUMN columnName
;
addColumnSpecification
: (WITH (CHECK | NOCHECK))? ADD (alterColumnAddOptions | generatedColumnNamesClause)
;
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)?
;
generatedColumnNamesClause
: generatedColumnNameClause COMMA_ periodClause | periodClause COMMA_ generatedColumnNameClause
;
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 | ON alterSetOnClause?)
;
alterSetOnClause
: LP_ (HISTORY_TABLE EQ_ tableName)? dataConsistencyCheckClause_? historyRetentionPeriodClause_? RP_
;
dataConsistencyCheckClause_
: COMMA_? DATA_CONSISTENCY_CHECK EQ_ (ON | OFF)
;
historyRetentionPeriodClause_
: COMMA_? HISTORY_RETENTION_PERIOD EQ_ historyRetentionPeriod
;
historyRetentionPeriod
: INFINITE | (NUMBER_ (DAY | DAYS | WEEK | WEEKS | MONTH | MONTHS | YEAR | YEARS))
;
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?
;
alterTableOption
: 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_)?
;
tableExistClause_
: (IF EXISTS)?
;
indexExistClause_
: (IF EXISTS)?
;
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_
;
|
/*
* 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 alterDefinitionClause_
;
alterIndex
: ALTER INDEX (indexName | ALL) ON tableName
;
dropTable
: DROP TABLE tableExistClause_ tableNames
;
dropIndex
: DROP INDEX indexExistClause_ 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 encryptedOptions_
| columnConstraint (COMMA_ columnConstraint)*
| columnIndex
;
encryptedOptions_
: LP_ COLUMN_ENCRYPTION_KEY EQ_ ignoredIdentifier_ COMMA_ ENCRYPTION_TYPE EQ_ (DETERMINISTIC | RANDOMIZED) COMMA_ ALGORITHM EQ_ STRING_ RP_
;
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)? withIndexOption_? indexOnClause? fileStreamOn_?
;
withIndexOption_
: WITH LP_ indexOption (COMMA_ indexOption)* RP_
;
indexOnClause
: onSchemaColumn | onFileGroup | onDefault
;
onDefault
: ON DEFAULT
;
fileStreamOn_
: FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_)
;
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 indexNameOption_ (WITH indexOptions_)? indexOnClause? fileStreamOn_?
;
indexNameOption_
: (CLUSTERED | NONCLUSTERED)? columnNames | CLUSTERED COLUMNSTORE | NONCLUSTERED? COLUMNSTORE columnNames
;
indexOptions_
: LP_ indexOption (COMMA_ indexOption)* RP_
;
periodClause
: PERIOD FOR SYSTEM_TIME LP_ columnName COMMA_ columnName RP_
;
partitionScheme_
: (ON (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_))?
;
fileGroup_
: (TEXTIMAGE_ON (ignoredIdentifier_ | STRING_))? ((FILESTREAM_ON (schemaName) | ignoredIdentifier_ STRING_))? (WITH tableOptions)?
;
tableOptions
: LP_ tableOption (COMMA_ tableOption)* RP_
;
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 onHistoryTableClause?
| REMOTE_DATA_ARCHIVE EQ_ (ON tableStretchOptions? | OFF migrationState_)
| tableOperationOption
| distributionOption
| dataWareHouseTableOption
;
tableStretchOptions
: LP_ tableStretchOptions (COMMA_ tableStretchOptions)* RP_
;
tableStretchOption
: (FILTER_PREDICATE EQ_ (NULL | functionCall) COMMA_)? MIGRATION_STATE EQ_ (OUTBOUND | INBOUND | PAUSED)
;
migrationState_
: LP_ MIGRATION_STATE EQ_ PAUSED RP_
;
tableOperationOption
: (MEMORY_OPTIMIZED EQ_ ON) | (DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA)) | (SYSTEM_VERSIONING EQ_ ON onHistoryTableClause?)
;
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_)
;
createIndexSpecification_
: UNIQUE? (CLUSTERED | NONCLUSTERED)?
;
alterDefinitionClause_
: modifyColumnSpecification | addColumnSpecification | alterDrop | alterCheckConstraint | alterTrigger | alterSwitch | alterSet | alterTableOption | REBUILD
;
modifyColumnSpecification
: alterColumnOperation dataType (COLLATE collationName)? (NULL | NOT NULL)? SPARSE?
;
alterColumnOperation
: ALTER COLUMN columnName
;
addColumnSpecification
: (WITH (CHECK | NOCHECK))? ADD (alterColumnAddOptions | generatedColumnNamesClause)
;
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)?
;
generatedColumnNamesClause
: generatedColumnNameClause COMMA_ periodClause | periodClause COMMA_ generatedColumnNameClause
;
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 | ignoredIdentifiers_)
;
alterTrigger
: (ENABLE| DISABLE) TRIGGER (ALL | ignoredIdentifiers_)
;
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 | ON alterSetOnClause?)
;
alterSetOnClause
: LP_ (HISTORY_TABLE EQ_ tableName)? dataConsistencyCheckClause_? historyRetentionPeriodClause_? RP_
;
dataConsistencyCheckClause_
: COMMA_? DATA_CONSISTENCY_CHECK EQ_ (ON | OFF)
;
historyRetentionPeriodClause_
: COMMA_? HISTORY_RETENTION_PERIOD EQ_ historyRetentionPeriod
;
historyRetentionPeriod
: INFINITE | (NUMBER_ (DAY | DAYS | WEEK | WEEKS | MONTH | MONTHS | YEAR | YEARS))
;
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?
;
alterTableOption
: SET LP_ LOCK_ESCALATION EQ_ (AUTO | TABLE | DISABLE) RP_
| MEMORY_OPTIMIZED EQ_ ON
| DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA)
| SYSTEM_VERSIONING EQ_ ON onHistoryTableClause?
;
onHistoryTableClause
: LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_
;
tableExistClause_
: (IF EXISTS)?
;
indexExistClause_
: (IF EXISTS)?
;
|
modify tableIndex rule
|
modify tableIndex rule
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
4b32d205a425e03354b3679c14886a832560a7bb
|
lua/Lua.g4
|
lua/Lua.g4
|
/*
BSD License
Copyright (c) 2013, Kazunori Sakamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the NAME of Rainer Schuster nor the NAMEs of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This grammar file derived from:
Lua 5.2 Reference Manual
http://www.lua.org/manual/5.2/manual.html
Lua 5.1 grammar written by Nicolai Mainiero
http://www.antlr3.org/grammar/1178608849736/Lua.g
I tested my grammar with Test suite for Lua 5.2 (http://www.lua.org/tests/5.2/)
*/
grammar Lua;
chunk
: block EOF
;
block
: stat* retstat?
;
stat
: ';'
| varlist '=' explist
| functioncall
| label
| 'break'
| 'goto' NAME
| 'do' block 'end'
| 'while' exp 'do' block 'end'
| 'repeat' block 'until' exp
| 'if' exp 'then' block ('elseif' exp 'then' block)* ('else' block)? 'end'
| 'for' NAME '=' exp ',' exp (',' exp)? 'do' block 'end'
| 'for' namelist 'in' explist 'do' block 'end'
| 'function' funcname funcbody
| 'local' 'function' NAME funcbody
| 'local' namelist ('=' explist)?
;
retstat
: 'return' explist? ';'?
;
label
: '::' NAME '::'
;
funcname
: NAME ('.' NAME)* (':' NAME)?
;
varlist
: var (',' var)*
;
namelist
: NAME (',' NAME)*
;
explist
: exp (',' exp)*
;
exp
: 'nil' | 'false' | 'true' | number | string | '...' | functiondef
| prefixexp | tableconstructor | exp binop exp | unop exp
;
var
: (NAME | '(' exp ')' varSuffix) varSuffix*
;
prefixexp
: varOrExp nameAndArgs*
;
functioncall
: varOrExp nameAndArgs+
;
varOrExp
: var | '(' exp ')'
;
nameAndArgs
: (':' NAME)? args
;
varSuffix
: nameAndArgs* ('[' exp ']' | '.' NAME)
;
/*
var
: NAME | prefixexp '[' exp ']' | prefixexp '.' NAME
;
prefixexp
: var | functioncall | '(' exp ')'
;
functioncall
: prefixexp args | prefixexp ':' NAME args
;
*/
args
: '(' explist? ')' | tableconstructor | string
;
functiondef
: 'function' funcbody
;
funcbody
: '(' parlist? ')' block 'end'
;
parlist
: namelist (',' '...')? | '...'
;
tableconstructor
: '{' fieldlist? '}'
;
fieldlist
: field (fieldsep field)* fieldsep?
;
field
: '[' exp ']' '=' exp | NAME '=' exp | exp
;
fieldsep
: ',' | ';'
;
binop
: '+' | '-' | '*' | '/' | '^' | '%' | '..'
| '<' | '<=' | '>' | '>=' | '==' | '~='
| 'and' | 'or'
;
unop
: '-' | 'not' | '#'
;
number
: INT | HEX | FLOAT | HEX_FLOAT
;
string
: NORMALSTRING | CHARSTRING | LONGSTRING
;
// LEXER
NAME
: [a-zA-Z_][a-zA-Z_0-9]*
;
NORMALSTRING
: '"' ( EscapeSequence | ~('\\'|'"') )* '"'
;
CHARSTRING
: '\'' ( EscapeSequence | ~('\''|'\\') )* '\''
;
LONGSTRING
: '[' NESTED_STR ']'
;
fragment
NESTED_STR
: '=' NESTED_STR '='
| '[' .*? ']'
;
INT
: Digit+
;
HEX
: '0' [xX] HexDigit+
;
FLOAT
: Digit+ '.' Digit* ExponentPart?
| '.' Digit+ ExponentPart?
| Digit+ ExponentPart
;
HEX_FLOAT
: '0' [xX] HexDigit+ '.' HexDigit* HexExponentPart?
| '0' [xX] '.' HexDigit+ HexExponentPart?
| '0' [xX] HexDigit+ HexExponentPart
;
fragment
ExponentPart
: [eE] [+-]? Digit+
;
fragment
HexExponentPart
: [pP] [+-]? Digit+
;
fragment
EscapeSequence
: '\\' [abfnrtvz"'\\]
| DecimalEscape
| HexEscape
;
fragment
DecimalEscape
: '\\' Digit
| '\\' Digit Digit
| '\\' [0-2] Digit Digit
;
fragment
HexEscape
: '\\' 'x' HexDigit HexDigit
;
fragment
Digit
: [0-9]
;
fragment
HexDigit
: [0-9a-fA-F]
;
COMMENT
: '--[[' .*? ']]'-> channel(HIDDEN)
;
LINE_COMMENT
: '--' '['? (~('['|'\n'|'\r') ~('\n'|'\r')*)? ('\n'|'\r')* -> channel(HIDDEN)
;
WS
: [ \t\u000C]+ -> skip
;
NEWLINE
: '\r'? '\n' -> skip
;
|
/*
BSD License
Copyright (c) 2013, Kazunori Sakamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the NAME of Rainer Schuster nor the NAMEs of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This grammar file derived from:
Lua 5.2 Reference Manual
http://www.lua.org/manual/5.2/manual.html
Lua 5.1 grammar written by Nicolai Mainiero
http://www.antlr3.org/grammar/1178608849736/Lua.g
I tested my grammar with Test suite for Lua 5.2 (http://www.lua.org/tests/5.2/)
*/
grammar Lua;
chunk
: block EOF
;
block
: stat* retstat?
;
stat
: ';'
| varlist '=' explist
| functioncall
| label
| 'break'
| 'goto' NAME
| 'do' block 'end'
| 'while' exp 'do' block 'end'
| 'repeat' block 'until' exp
| 'if' exp 'then' block ('elseif' exp 'then' block)* ('else' block)? 'end'
| 'for' NAME '=' exp ',' exp (',' exp)? 'do' block 'end'
| 'for' namelist 'in' explist 'do' block 'end'
| 'function' funcname funcbody
| 'local' 'function' NAME funcbody
| 'local' namelist ('=' explist)?
;
retstat
: 'return' explist? ';'?
;
label
: '::' NAME '::'
;
funcname
: NAME ('.' NAME)* (':' NAME)?
;
varlist
: var (',' var)*
;
namelist
: NAME (',' NAME)*
;
explist
: exp (',' exp)*
;
exp
: 'nil' | 'false' | 'true' | number | string | '...' | functiondef
| prefixexp | tableconstructor | exp binop exp | unop exp
;
var
: (NAME | '(' exp ')' varSuffix) varSuffix*
;
prefixexp
: varOrExp nameAndArgs*
;
functioncall
: varOrExp nameAndArgs+
;
varOrExp
: var | '(' exp ')'
;
nameAndArgs
: (':' NAME)? args
;
varSuffix
: nameAndArgs* ('[' exp ']' | '.' NAME)
;
/*
var
: NAME | prefixexp '[' exp ']' | prefixexp '.' NAME
;
prefixexp
: var | functioncall | '(' exp ')'
;
functioncall
: prefixexp args | prefixexp ':' NAME args
;
*/
args
: '(' explist? ')' | tableconstructor | string
;
functiondef
: 'function' funcbody
;
funcbody
: '(' parlist? ')' block 'end'
;
parlist
: namelist (',' '...')? | '...'
;
tableconstructor
: '{' fieldlist? '}'
;
fieldlist
: field (fieldsep field)* fieldsep?
;
field
: '[' exp ']' '=' exp | NAME '=' exp | exp
;
fieldsep
: ',' | ';'
;
binop
: '+' | '-' | '*' | '/' | '^' | '%' | '..'
| '<' | '<=' | '>' | '>=' | '==' | '~='
| 'and' | 'or'
;
unop
: '-' | 'not' | '#'
;
number
: INT | HEX | FLOAT | HEX_FLOAT
;
string
: NORMALSTRING | CHARSTRING | LONGSTRING
;
// LEXER
NAME
: [a-zA-Z_][a-zA-Z_0-9]*
;
NORMALSTRING
: '"' ( EscapeSequence | ~('\\'|'"') )* '"'
;
CHARSTRING
: '\'' ( EscapeSequence | ~('\''|'\\') )* '\''
;
LONGSTRING
: '[' NESTED_STR ']'
;
fragment
NESTED_STR
: '=' NESTED_STR '='
| '[' .*? ']'
;
INT
: Digit+
;
HEX
: '0' [xX] HexDigit+
;
FLOAT
: Digit+ '.' Digit* ExponentPart?
| '.' Digit+ ExponentPart?
| Digit+ ExponentPart
;
HEX_FLOAT
: '0' [xX] HexDigit+ '.' HexDigit* HexExponentPart?
| '0' [xX] '.' HexDigit+ HexExponentPart?
| '0' [xX] HexDigit+ HexExponentPart
;
fragment
ExponentPart
: [eE] [+-]? Digit+
;
fragment
HexExponentPart
: [pP] [+-]? Digit+
;
fragment
EscapeSequence
: '\\' [abfnrtvz"'\\]
| '\\' '\r'? '\n'
| DecimalEscape
| HexEscape
;
fragment
DecimalEscape
: '\\' Digit
| '\\' Digit Digit
| '\\' [0-2] Digit Digit
;
fragment
HexEscape
: '\\' 'x' HexDigit HexDigit
;
fragment
Digit
: [0-9]
;
fragment
HexDigit
: [0-9a-fA-F]
;
COMMENT
: '--[[' .*? ']]'-> channel(HIDDEN)
;
LINE_COMMENT
: '--' '['? (~('['|'\n'|'\r') ~('\n'|'\r')*)? ('\n'|'\r')* -> channel(HIDDEN)
;
WS
: [ \t\u000C]+ -> skip
;
NEWLINE
: '\r'? '\n' -> skip
;
SHEBANG
: '#' '!' ~('\n'|'\r')* -> channel(HIDDEN)
;
|
Improve Lua gramma for supporting string contatination with '\' and shebang (#!).
|
Improve Lua gramma for supporting string contatination with '\' and shebang (#!).
|
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
|
1dd663416df71593839e919b007ba117c201186f
|
dshellLexer.g4
|
dshellLexer.g4
|
lexer grammar dshellLexer;
@header {
package dshell.internal.parser;
import dshell.internal.parser.Node;
import dshell.internal.parser.ParserUtils;
import dshell.internal.parser.TypeSymbol;
}
@members {
private boolean trace = false;
@Override
public Token nextToken() {
Token token = super.nextToken();
if(this.trace) {
System.err.println("@nextToken: " + token);
}
return token;
}
public void setTrace(boolean trace) {
this.trace = trace;
}
}
// ######################
// # lexer #
// ######################
// reserved keyword
Assert : 'assert';
Break : 'break';
Boolean : 'boolean';
Catch : 'catch';
Continue : 'continue';
Class : 'class';
Constructor : 'constructor';
Do : 'do';
Else : 'else';
Extends : 'extends';
ExportEnv : 'export-env';
Func : 'Func';
Function : 'function';
Finally : 'finally';
Float : 'float';
For : 'for';
If : 'if';
ImportCmd : 'import-command';
ImportEnv : 'import-env';
In : 'in';
Int : 'int';
Instanceof : 'instanceof';
Let : 'let';
New : 'new';
Return : 'return';
Super : 'super';
Try : 'try';
Throw : 'throw';
Var : 'var';
Void : 'void';
While : 'while';
LeftParenthese : '(';
RightParenthese : ')';
LeftBracket : '[';
RightBracket : ']';
LeftBrace : '{';
RightBrace : '}';
Colon : ':';
Semicolon : ';';
Comma : ',';
Period : '.';
BackSlash : '\\';
Dollar : '$';
At : '@';
SingleQuote : '\'';
DoubleQuote : '"' -> pushMode(InString);
BackQuote : '`';
// operator
// binary op
ADD : '+';
SUB : '-';
MUL : '*';
DIV : '/';
MOD : '%';
LT : '<';
GT : '>';
LE : '<=';
GE : '>=';
EQ : '==';
NE : '!=';
AND : '&';
OR : '|';
XOR : '^';
COND_AND : '&&';
COND_OR : '||';
REGEX_MATCH : '=~';
REGEX_UNMATCH : '!~';
// prefix op
BIT_NOT : '~';
NOT : '!';
// suffix op
INC : '++';
DEC : '--';
// assign op
ASSIGN : '=';
ADD_ASSIGN : '+=';
SUB_ASSIGN : '-=';
MUL_ASSIGN : '*=';
DIV_ASSIGN : '/=';
MOD_ASSIGN : '%=';
// literal
// int literal //TODO: hex, oct number
fragment
Number
: '0'
| [1-9] [0-9]*
;
IntLiteral
: Number
;
// float literal
FloatLiteral
: Number '.' Number FloatSuffix?
;
fragment
FloatSuffix
: [eE] [+-]? Number
;
// boolean literal
BooleanLiteral
: 'true'
| 'false'
;
// String literal
StringLiteral
: '\'' SingleQuoteStringChar* '\''
;
fragment
SingleQuoteStringChar
: ~[\r\n'\\]
| SingleEscapeSequence
;
fragment
SingleEscapeSequence // TODO: unicode escape
: '\\' [btnfr'\\]
;
// symbol , class and command name
Identifier
: [_a-zA-Z] [_0-9a-zA-Z]*
;
// back quoted command
BackquotedLiteral
: '`' BackquotedChar+ '`'
;
fragment
BackquotedChar
: '\\' '`'
| ~[`\n\r]
;
Dollar_At
: '$@'
;
// unicode character
UTF8Chars
: UTF8Char+
;
fragment
UTF8Char
: [\u0080-\u07FF]
| [\u0800-\uFFFF]
;
// comment & space
Comment
: '#' ~[\r\n]* -> skip
;
fragment
WhiteSpaceFragment
: [\t\u000B\u000C\u0020\u00A0]
;
WhiteSpace
: WhiteSpaceFragment+
;
fragment
LineEndFragment
: [\r\n]
;
LineEnd
: LineEndFragment+
;
EscapedSymbol
: '\\' '#'
| '\\' LineEndFragment
| '\\' WhiteSpaceFragment
| '\\' '`'
| '\\' '$'
;
StartSubCmd
: '$('
;
StartInterp
: '${'
;
mode InString;
CloseString : '"' -> popMode;
StringElement
: DoubleQuoteStringChar+
;
fragment
DoubleQuoteStringChar
: ~[\r\n`$"\\]
| DoubleEscapeSequence
;
fragment
DoubleEscapeSequence // TODO: unicode escape
: '\\' [$btnfr"`\\]
;
InnerCmd
: '$' InnerCmdBody
;
fragment
InnerCmdBody
: '(' ( ~[()] | InnerCmdBody)+ ')'
;
InnerExpr
: '$' InnerExprBody
;
fragment
InnerExprBody
: '{' ( ~[{}] | InnerExprBody)+ '}'
;
InnerCmdBackQuote
: BackquotedLiteral
;
|
lexer grammar dshellLexer;
@header {
package dshell.internal.parser;
import dshell.internal.parser.Node;
import dshell.internal.parser.ParserUtils;
import dshell.internal.parser.TypeSymbol;
}
@members {
private boolean trace = false;
@Override
public Token nextToken() {
Token token = super.nextToken();
if(this.trace) {
System.err.println("@nextToken: " + token);
}
return token;
}
public void setTrace(boolean trace) {
this.trace = trace;
}
}
// ######################
// # lexer #
// ######################
// reserved keyword
Assert : 'assert';
Break : 'break';
Boolean : 'boolean';
Catch : 'catch';
Continue : 'continue';
Class : 'class';
Constructor : 'constructor';
Do : 'do';
Else : 'else';
Extends : 'extends';
ExportEnv : 'export-env';
Func : 'Func';
Function : 'function';
Finally : 'finally';
Float : 'float';
For : 'for';
If : 'if';
ImportCmd : 'import-command';
ImportEnv : 'import-env';
In : 'in';
Int : 'int';
Instanceof : 'instanceof';
Let : 'let';
New : 'new';
Return : 'return';
Super : 'super';
Try : 'try';
Throw : 'throw';
Var : 'var';
Void : 'void';
While : 'while';
LeftParenthese : '(';
RightParenthese : ')';
LeftBracket : '[';
RightBracket : ']';
LeftBrace : '{';
RightBrace : '}';
Colon : ':';
Semicolon : ';';
Comma : ',';
Period : '.';
BackSlash : '\\';
Dollar : '$';
At : '@';
Question : '?';
SingleQuote : '\'';
DoubleQuote : '"' -> pushMode(InString);
BackQuote : '`';
// operator
// binary op
ADD : '+';
SUB : '-';
MUL : '*';
DIV : '/';
MOD : '%';
LT : '<';
GT : '>';
LE : '<=';
GE : '>=';
EQ : '==';
NE : '!=';
AND : '&';
OR : '|';
XOR : '^';
COND_AND : '&&';
COND_OR : '||';
REGEX_MATCH : '=~';
REGEX_UNMATCH : '!~';
// prefix op
BIT_NOT : '~';
NOT : '!';
// suffix op
INC : '++';
DEC : '--';
// assign op
ASSIGN : '=';
ADD_ASSIGN : '+=';
SUB_ASSIGN : '-=';
MUL_ASSIGN : '*=';
DIV_ASSIGN : '/=';
MOD_ASSIGN : '%=';
// literal
// int literal //TODO: hex, oct number
fragment
Number
: '0'
| [1-9] [0-9]*
;
IntLiteral
: Number
;
// float literal
FloatLiteral
: Number '.' Number FloatSuffix?
;
fragment
FloatSuffix
: [eE] [+-]? Number
;
// boolean literal
BooleanLiteral
: 'true'
| 'false'
;
// String literal
StringLiteral
: '\'' SingleQuoteStringChar* '\''
;
fragment
SingleQuoteStringChar
: ~[\r\n'\\]
| SingleEscapeSequence
;
fragment
SingleEscapeSequence // TODO: unicode escape
: '\\' [btnfr'\\]
;
// symbol , class and command name
Identifier
: [_a-zA-Z] [_0-9a-zA-Z]*
;
// back quoted command
BackquotedLiteral
: '`' BackquotedChar+ '`'
;
fragment
BackquotedChar
: '\\' '`'
| ~[`\n\r]
;
Dollar_At
: '$@'
;
// unicode character
UTF8Chars
: UTF8Char+
;
fragment
UTF8Char
: [\u0080-\u07FF]
| [\u0800-\uFFFF]
;
// comment & space
Comment
: '#' ~[\r\n]* -> skip
;
fragment
WhiteSpaceFragment
: [\t\u000B\u000C\u0020\u00A0]
;
WhiteSpace
: WhiteSpaceFragment+
;
fragment
LineEndFragment
: [\r\n]
;
LineEnd
: LineEndFragment+
;
EscapedSymbol
: '\\' '#'
| '\\' LineEndFragment
| '\\' WhiteSpaceFragment
| '\\' '`'
| '\\' '$'
;
StartSubCmd
: '$('
;
StartInterp
: '${'
;
mode InString;
CloseString : '"' -> popMode;
StringElement
: DoubleQuoteStringChar+
;
fragment
DoubleQuoteStringChar
: ~[\r\n`$"\\]
| DoubleEscapeSequence
;
fragment
DoubleEscapeSequence // TODO: unicode escape
: '\\' [$btnfr"`\\]
;
InnerCmd
: '$' InnerCmdBody
;
fragment
InnerCmdBody
: '(' ( ~[()] | InnerCmdBody)+ ')'
;
InnerExpr
: '$' InnerExprBody
;
fragment
InnerExprBody
: '{' ( ~[{}] | InnerExprBody)+ '}'
;
InnerCmdBackQuote
: BackquotedLiteral
;
|
fix unrecognized token error
|
fix unrecognized token error
|
ANTLR
|
bsd-3-clause
|
sekiguchi-nagisa/DShell,sekiguchi-nagisa/DShell
|
d65e1d80731a44d94d129ea0d0d6f76ac90c2ba5
|
src/main/antlr4/nl/bigo/pp/PGN.g4
|
src/main/antlr4/nl/bigo/pp/PGN.g4
|
/*
* Copyright (c) 2013 by Bart Kiers
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Project : A Portable Game Notation (PGN) ANTLR 4 grammar
* and parser.
* Developed by : Bart Kiers, [email protected]
*/
//
// A Portable Game Notation (PGN) grammar based on:
// http://www.thechessdrum.net/PGN_Reference.txt
//
// The inline comments starting with "///" in this grammar are direct
// copy-pastes from the PGN reference linked above.
//
grammar PGN;
// The entry point of the grammar.
parse
: pgn_database EOF
;
/// <PGN-database> ::= <PGN-game> <PGN-database>
/// <empty>
pgn_database
: pgn_game*
;
/// <PGN-game> ::= <tag-section> <movetext-section>
pgn_game
: tag_section movetext_section
;
/// <tag-section> ::= <tag-pair> <tag-section>
/// <empty>
tag_section
: tag_pair*
;
/// <tag-pair> ::= [ <tag-name> <tag-value> ]
tag_pair
: LEFT_BRACKET tag_name tag_value RIGHT_BRACKET
;
/// <tag-name> ::= <identifier>
tag_name
: SYMBOL
;
/// <tag-value> ::= <string>
tag_value
: STRING
;
/// <movetext-section> ::= <element-sequence> <game-termination>
movetext_section
: element_sequence game_termination
;
/// <element-sequence> ::= <element> <element-sequence>
/// <recursive-variation> <element-sequence>
/// <empty>
element_sequence
: (element | recursive_variation)*
;
/// <element> ::= <move-number-indication>
/// <SAN-move>
/// <numeric-annotation-glyph>
element
: move_number_indication
| san_move
| NUMERIC_ANNOTATION_GLYPH
;
move_number_indication
: INTEGER PERIOD?
;
san_move
: SYMBOL
;
/// <recursive-variation> ::= ( <element-sequence> )
recursive_variation
: LEFT_PARENTHESIS element_sequence RIGHT_PARENTHESIS
;
/// <game-termination> ::= 1-0
/// 0-1
/// 1/2-1/2
/// *
game_termination
: WHITE_WINS
| BLACK_WINS
| DRAWN_GAME
| ASTERISK
;
WHITE_WINS
: '1-0'
;
BLACK_WINS
: '0-1'
;
DRAWN_GAME
: '1/2-1/2'
;
/// Comment text may appear in PGN data. There are two kinds of comments. The
/// first kind is the "rest of line" comment; this comment type starts with a
/// semicolon character and continues to the end of the line. The second kind
/// starts with a left brace character and continues to the next right brace
/// character. Comments cannot appear inside any token.
REST_OF_LINE_COMMENT
: ';' ~[\r\n]* -> skip
;
/// Brace comments do not nest; a left brace character appearing in a brace comment
/// loses its special meaning and is ignored. A semicolon appearing inside of a
/// brace comment loses its special meaning and is ignored. Braces appearing
/// inside of a semicolon comments lose their special meaning and are ignored.
BRACE_COMMENT
: '{' ~'}'* '}' -> skip
;
/// There is a special escape mechanism for PGN data. This mechanism is triggered
/// by a percent sign character ("%") appearing in the first column of a line; the
/// data on the rest of the line is ignored by publicly available PGN scanning
/// software. This escape convention is intended for the private use of software
/// developers and researchers to embed non-PGN commands and data in PGN streams.
///
/// A percent sign appearing in any other place other than the first position in a
/// line does not trigger the escape mechanism.
ESCAPE
: {getCharPositionInLine() == 0}? '%' ~[\r\n]* -> skip
;
SPACES
: [ \t\r\n]+ -> skip
;
/// A string token is a sequence of zero or more printing characters delimited by a
/// pair of quote characters (ASCII decimal value 34, hexadecimal value 0x22). An
/// empty string is represented by two adjacent quotes. (Note: an apostrophe is
/// not a quote.) A quote inside a string is represented by the backslash
/// immediately followed by a quote. A backslash inside a string is represented by
/// two adjacent backslashes. Strings are commonly used as tag pair values (see
/// below). Non-printing characters like newline and tab are not permitted inside
/// of strings. A string token is terminated by its closing quote. Currently, a
/// string is limited to a maximum of 255 characters of data.
STRING
: '"' ('\\\\' | '\\"' | ~[\\"])* '"'
;
/// An integer token is a sequence of one or more decimal digit characters. It is
/// a special case of the more general "symbol" token class described below.
/// Integer tokens are used to help represent move number indications (see below).
/// An integer token is terminated just prior to the first non-symbol character
/// following the integer digit sequence.
INTEGER
: [0-9]+
;
/// A period character (".") is a token by itself. It is used for move number
/// indications (see below). It is self terminating.
PERIOD
: '.'
;
/// An asterisk character ("*") is a token by itself. It is used as one of the
/// possible game termination markers (see below); it indicates an incomplete game
/// or a game with an unknown or otherwise unavailable result. It is self
/// terminating.
ASTERISK
: '*'
;
/// The left and right bracket characters ("[" and "]") are tokens. They are used
/// to delimit tag pairs (see below). Both are self terminating.
LEFT_BRACKET
: '['
;
RIGHT_BRACKET
: ']'
;
/// The left and right parenthesis characters ("(" and ")") are tokens. They are
/// used to delimit Recursive Annotation Variations (see below). Both are self
/// terminating.
LEFT_PARENTHESIS
: '('
;
RIGHT_PARENTHESIS
: ')'
;
/// The left and right angle bracket characters ("<" and ">") are tokens. They are
/// reserved for future expansion. Both are self terminating.
LEFT_ANGLE_BRACKET
: '<'
;
RIGHT_ANGLE_BRACKET
: '>'
;
/// A Numeric Annotation Glyph ("NAG", see below) is a token; it is composed of a
/// dollar sign character ("$") immediately followed by one or more digit
/// characters. It is terminated just prior to the first non-digit character
/// following the digit sequence.
NUMERIC_ANNOTATION_GLYPH
: '$' [0-9]+
;
/// A symbol token starts with a letter or digit character and is immediately
/// followed by a sequence of zero or more symbol continuation characters. These
/// continuation characters are letter characters ("A-Za-z"), digit characters
/// ("0-9"), the underscore ("_"), the plus sign ("+"), the octothorpe sign ("#"),
/// the equal sign ("="), the colon (":"), and the hyphen ("-"). Symbols are used
/// for a variety of purposes. All characters in a symbol are significant. A
/// symbol token is terminated just prior to the first non-symbol character
/// following the symbol character sequence. Currently, a symbol is limited to a
/// maximum of 255 characters in length.
SYMBOL
: [a-zA-Z0-9] [a-zA-Z0-9_+#=:-]*
;
/// Import format PGN allows for the use of traditional suffix annotations for
/// moves. There are exactly six such annotations available: "!", "?", "!!", "!?",
/// "?!", and "??". At most one such suffix annotation may appear per move, and if
/// present, it is always the last part of the move symbol.
SUFFIX_ANNOTATION
: [?!] [?!]?
;
// A fall through rule that will catch any character not matched by any of the
// previous lexer rules.
UNEXPECTED_CHAR
: .
;
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 by Bart Kiers
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Project : A Portable Game Notation (PGN) ANTLR 4 grammar
* and parser.
* Developed by : Bart Kiers, [email protected]
*/
//
// A Portable Game Notation (PGN) grammar based on:
// http://www.thechessdrum.net/PGN_Reference.txt
//
// The inline comments starting with "///" in this grammar are direct
// copy-pastes from the PGN reference linked above.
//
grammar PGN;
// The entry point of the grammar.
parse
: pgn_database EOF
;
/// <PGN-database> ::= <PGN-game> <PGN-database>
/// <empty>
pgn_database
: pgn_game*
;
/// <PGN-game> ::= <tag-section> <movetext-section>
pgn_game
: tag_section movetext_section
;
/// <tag-section> ::= <tag-pair> <tag-section>
/// <empty>
tag_section
: tag_pair*
;
/// <tag-pair> ::= [ <tag-name> <tag-value> ]
tag_pair
: LEFT_BRACKET tag_name tag_value RIGHT_BRACKET
;
/// <tag-name> ::= <identifier>
tag_name
: SYMBOL
;
/// <tag-value> ::= <string>
tag_value
: STRING
;
/// <movetext-section> ::= <element-sequence> <game-termination>
movetext_section
: element_sequence game_termination
;
/// <element-sequence> ::= <element> <element-sequence>
/// <recursive-variation> <element-sequence>
/// <empty>
element_sequence
: (element | recursive_variation)*
;
/// <element> ::= <move-number-indication>
/// <SAN-move>
/// <numeric-annotation-glyph>
element
: move_number_indication
| san_move
| NUMERIC_ANNOTATION_GLYPH
;
move_number_indication
: INTEGER PERIOD?
;
san_move
: SYMBOL
;
/// <recursive-variation> ::= ( <element-sequence> )
recursive_variation
: LEFT_PARENTHESIS element_sequence RIGHT_PARENTHESIS
;
/// <game-termination> ::= 1-0
/// 0-1
/// 1/2-1/2
/// *
game_termination
: WHITE_WINS
| BLACK_WINS
| DRAWN_GAME
| ASTERISK
;
WHITE_WINS
: '1-0'
;
BLACK_WINS
: '0-1'
;
DRAWN_GAME
: '1/2-1/2'
;
/// Comment text may appear in PGN data. There are two kinds of comments. The
/// first kind is the "rest of line" comment; this comment type starts with a
/// semicolon character and continues to the end of the line. The second kind
/// starts with a left brace character and continues to the next right brace
/// character. Comments cannot appear inside any token.
REST_OF_LINE_COMMENT
: ';' ~[\r\n]* -> skip
;
/// Brace comments do not nest; a left brace character appearing in a brace comment
/// loses its special meaning and is ignored. A semicolon appearing inside of a
/// brace comment loses its special meaning and is ignored. Braces appearing
/// inside of a semicolon comments lose their special meaning and are ignored.
BRACE_COMMENT
: '{' ~'}'* '}' -> skip
;
/// There is a special escape mechanism for PGN data. This mechanism is triggered
/// by a percent sign character ("%") appearing in the first column of a line; the
/// data on the rest of the line is ignored by publicly available PGN scanning
/// software. This escape convention is intended for the private use of software
/// developers and researchers to embed non-PGN commands and data in PGN streams.
///
/// A percent sign appearing in any other place other than the first position in a
/// line does not trigger the escape mechanism.
ESCAPE
: {getCharPositionInLine() == 0}? '%' ~[\r\n]* -> skip
;
SPACES
: [ \t\r\n]+ -> skip
;
/// A string token is a sequence of zero or more printing characters delimited by a
/// pair of quote characters (ASCII decimal value 34, hexadecimal value 0x22). An
/// empty string is represented by two adjacent quotes. (Note: an apostrophe is
/// not a quote.) A quote inside a string is represented by the backslash
/// immediately followed by a quote. A backslash inside a string is represented by
/// two adjacent backslashes. Strings are commonly used as tag pair values (see
/// below). Non-printing characters like newline and tab are not permitted inside
/// of strings. A string token is terminated by its closing quote. Currently, a
/// string is limited to a maximum of 255 characters of data.
STRING
: '"' ('\\\\' | '\\"' | ~[\\"])* '"'
;
/// An integer token is a sequence of one or more decimal digit characters. It is
/// a special case of the more general "symbol" token class described below.
/// Integer tokens are used to help represent move number indications (see below).
/// An integer token is terminated just prior to the first non-symbol character
/// following the integer digit sequence.
INTEGER
: [0-9]+
;
/// A period character (".") is a token by itself. It is used for move number
/// indications (see below). It is self terminating.
PERIOD
: '.'
;
/// An asterisk character ("*") is a token by itself. It is used as one of the
/// possible game termination markers (see below); it indicates an incomplete game
/// or a game with an unknown or otherwise unavailable result. It is self
/// terminating.
ASTERISK
: '*'
;
/// The left and right bracket characters ("[" and "]") are tokens. They are used
/// to delimit tag pairs (see below). Both are self terminating.
LEFT_BRACKET
: '['
;
RIGHT_BRACKET
: ']'
;
/// The left and right parenthesis characters ("(" and ")") are tokens. They are
/// used to delimit Recursive Annotation Variations (see below). Both are self
/// terminating.
LEFT_PARENTHESIS
: '('
;
RIGHT_PARENTHESIS
: ')'
;
/// The left and right angle bracket characters ("<" and ">") are tokens. They are
/// reserved for future expansion. Both are self terminating.
LEFT_ANGLE_BRACKET
: '<'
;
RIGHT_ANGLE_BRACKET
: '>'
;
/// A Numeric Annotation Glyph ("NAG", see below) is a token; it is composed of a
/// dollar sign character ("$") immediately followed by one or more digit
/// characters. It is terminated just prior to the first non-digit character
/// following the digit sequence.
NUMERIC_ANNOTATION_GLYPH
: '$' [0-9]+
;
/// A symbol token starts with a letter or digit character and is immediately
/// followed by a sequence of zero or more symbol continuation characters. These
/// continuation characters are letter characters ("A-Za-z"), digit characters
/// ("0-9"), the underscore ("_"), the plus sign ("+"), the octothorpe sign ("#"),
/// the equal sign ("="), the colon (":"), and the hyphen ("-"). Symbols are used
/// for a variety of purposes. All characters in a symbol are significant. A
/// symbol token is terminated just prior to the first non-symbol character
/// following the symbol character sequence. Currently, a symbol is limited to a
/// maximum of 255 characters in length.
SYMBOL
: [a-zA-Z0-9] [a-zA-Z0-9_+#=:-]*
;
/// Import format PGN allows for the use of traditional suffix annotations for
/// moves. There are exactly six such annotations available: "!", "?", "!!", "!?",
/// "?!", and "??". At most one such suffix annotation may appear per move, and if
/// present, it is always the last part of the move symbol.
SUFFIX_ANNOTATION
: [?!] [?!]?
;
// A fall through rule that will catch any character not matched by any of the
// previous lexer rules.
UNEXPECTED_CHAR
: .
;
|
Update PGN.g4
|
Update PGN.g4
|
ANTLR
|
mit
|
bkiers/PGN-parser
|
1126a91f8b1fbb6e354340bf8c0af3efa5fea88e
|
Solidity.g4
|
Solidity.g4
|
// Copyright 2016-2017 Federico Bond <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
grammar Solidity;
sourceUnit
: (pragmaDirective | importDirective | contractDefinition)* EOF ;
pragmaDirective
: 'pragma' pragmaName pragmaValue ';' ;
pragmaName
: identifier ;
pragmaValue
: version | expression ;
version
: versionConstraint versionConstraint? ;
versionOperator
: '^' | '~' | '>=' | '>' | '<' | '<=' | '=' ;
versionConstraint
: versionOperator? VersionLiteral ;
importDeclaration
: identifier ('as' identifier)? ;
importDirective
: 'import' StringLiteral ('as' identifier)? ';'
| 'import' ('*' | identifier) ('as' identifier)? 'from' StringLiteral ';'
| 'import' '{' importDeclaration ( ',' importDeclaration )* '}' 'from' StringLiteral ';' ;
contractDefinition
: ( 'contract' | 'interface' | 'library' ) identifier
( 'is' inheritanceSpecifier (',' inheritanceSpecifier )* )?
'{' contractPart* '}' ;
inheritanceSpecifier
: userDefinedTypeName ( '(' expression ( ',' expression )* ')' )? ;
contractPart
: stateVariableDeclaration
| usingForDeclaration
| structDefinition
| constructorDefinition
| modifierDefinition
| functionDefinition
| eventDefinition
| enumDefinition ;
stateVariableDeclaration
: typeName
( PublicKeyword | InternalKeyword | PrivateKeyword | ConstantKeyword )*
identifier ('=' expression)? ';' ;
usingForDeclaration
: 'using' identifier 'for' ('*' | typeName) ';' ;
structDefinition
: 'struct' identifier
'{' ( variableDeclaration ';' (variableDeclaration ';')* )? '}' ;
constructorDefinition
: 'constructor' parameterList modifierList block ;
modifierDefinition
: 'modifier' identifier parameterList? block ;
modifierInvocation
: identifier ( '(' expressionList? ')' )? ;
functionDefinition
: 'function' identifier? parameterList modifierList returnParameters? ( ';' | block ) ;
returnParameters
: 'returns' parameterList ;
modifierList
: ( modifierInvocation | stateMutability | ExternalKeyword
| PublicKeyword | InternalKeyword | PrivateKeyword )* ;
eventDefinition
: 'event' identifier eventParameterList AnonymousKeyword? ';' ;
enumValue
: identifier ;
enumDefinition
: 'enum' identifier '{' enumValue? (',' enumValue)* '}' ;
parameterList
: '(' ( parameter (',' parameter)* )? ')' ;
parameter
: typeName storageLocation? identifier? ;
eventParameterList
: '(' ( eventParameter (',' eventParameter)* )? ')' ;
eventParameter
: typeName IndexedKeyword? identifier? ;
functionTypeParameterList
: '(' ( functionTypeParameter (',' functionTypeParameter)* )? ')' ;
functionTypeParameter
: typeName storageLocation? ;
variableDeclaration
: typeName storageLocation? identifier ;
typeName
: elementaryTypeName
| userDefinedTypeName
| mapping
| typeName '[' expression? ']'
| functionTypeName ;
userDefinedTypeName
: identifier ( '.' identifier )* ;
mapping
: 'mapping' '(' elementaryTypeName '=>' typeName ')' ;
functionTypeName
: 'function' functionTypeParameterList
( InternalKeyword | ExternalKeyword | stateMutability )*
( 'returns' functionTypeParameterList )? ;
storageLocation
: 'memory' | 'storage' ;
stateMutability
: PureKeyword | ConstantKeyword | ViewKeyword | PayableKeyword ;
block
: '{' statement* '}' ;
statement
: ifStatement
| whileStatement
| forStatement
| block
| inlineAssemblyStatement
| doWhileStatement
| continueStatement
| breakStatement
| returnStatement
| throwStatement
| emitStatement
| simpleStatement ;
expressionStatement
: expression ';' ;
ifStatement
: 'if' '(' expression ')' statement ( 'else' statement )? ;
whileStatement
: 'while' '(' expression ')' statement ;
simpleStatement
: ( variableDeclarationStatement | expressionStatement ) ;
forStatement
: 'for' '(' ( simpleStatement | ';' ) expression? ';' expression? ')' statement ;
inlineAssemblyStatement
: 'assembly' StringLiteral? assemblyBlock ;
doWhileStatement
: 'do' statement 'while' '(' expression ')' ';' ;
continueStatement
: 'continue' ';' ;
breakStatement
: 'break' ';' ;
returnStatement
: 'return' expression? ';' ;
throwStatement
: 'throw' ';' ;
emitStatement
: 'emit' functionCall ';' ;
variableDeclarationStatement
: ( 'var' identifierList | variableDeclaration ) ( '=' 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? ;
functionCall
: expression '(' functionCallArguments ')' ;
assemblyBlock
: '{' assemblyItem* '}' ;
assemblyItem
: identifier
| assemblyBlock
| assemblyExpression
| assemblyLocalDefinition
| assemblyAssignment
| assemblyStackAssignment
| labelDefinition
| assemblySwitch
| assemblyFunctionDefinition
| assemblyFor
| assemblyIf
| BreakKeyword
| ContinueKeyword
| subAssembly
| numberLiteral
| StringLiteral
| HexLiteral ;
assemblyExpression
: assemblyCall | assemblyLiteral ;
assemblyCall
: ( 'return' | 'address' | 'byte' | identifier ) ( '(' assemblyExpression? ( ',' assemblyExpression )* ')' )? ;
assemblyLocalDefinition
: 'let' assemblyIdentifierOrList ( ':=' assemblyExpression )? ;
assemblyAssignment
: assemblyIdentifierOrList ':=' assemblyExpression ;
assemblyIdentifierOrList
: identifier | '(' assemblyIdentifierList ')' ;
assemblyIdentifierList
: identifier ( ',' identifier )* ;
assemblyStackAssignment
: '=:' identifier ;
labelDefinition
: identifier ':' ;
assemblySwitch
: 'switch' assemblyExpression assemblyCase* ;
assemblyCase
: 'case' assemblyLiteral assemblyBlock
| 'default' assemblyBlock ;
assemblyFunctionDefinition
: 'function' identifier '(' assemblyIdentifierList? ')'
assemblyFunctionReturns? assemblyBlock ;
assemblyFunctionReturns
: ( '->' assemblyIdentifierList ) ;
assemblyFor
: 'for' ( assemblyBlock | assemblyExpression )
assemblyExpression ( assemblyBlock | assemblyExpression ) assemblyBlock ;
assemblyIf
: 'if' assemblyExpression assemblyBlock ;
assemblyLiteral
: StringLiteral | DecimalNumber | HexNumber | HexLiteral ;
subAssembly
: 'assembly' identifier assemblyBlock ;
tupleExpression
: '(' ( expression? ( ',' expression? )* ) ')'
| '[' ( expression ( ',' expression )* )? ']' ;
elementaryTypeNameExpression
: elementaryTypeName ;
numberLiteral
: (DecimalNumber | HexNumber) NumberUnit? ;
identifier
: ('from' | Identifier) ;
VersionLiteral
: [0-9]+ '.' [0-9]+ '.' [0-9]+ ;
BooleanLiteral
: 'true' | 'false' ;
DecimalNumber
: [0-9]+ ( '.' [0-9]* )? ( [eE] [0-9]+ )? ;
HexNumber
: '0x' HexCharacter+ ;
NumberUnit
: 'wei' | 'szabo' | 'finney' | 'ether'
| 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'years' ;
HexLiteral : 'hex' ('"' HexPair* '"' | '\'' HexPair* '\'') ;
fragment
HexPair
: HexCharacter HexCharacter ;
fragment
HexCharacter
: [0-9A-Fa-f] ;
ReservedKeyword
: 'abstract'
| 'after'
| 'case'
| 'catch'
| 'default'
| 'final'
| 'in'
| 'inline'
| 'let'
| 'match'
| 'null'
| 'of'
| 'relocatable'
| 'static'
| 'switch'
| 'try'
| 'type'
| 'typeof' ;
AnonymousKeyword : 'anonymous' ;
BreakKeyword : 'break' ;
ConstantKeyword : 'constant' ;
ContinueKeyword : 'continue' ;
ExternalKeyword : 'external' ;
IndexedKeyword : 'indexed' ;
InternalKeyword : 'internal' ;
PayableKeyword : 'payable' ;
PrivateKeyword : 'private' ;
PublicKeyword : 'public' ;
PureKeyword : 'pure' ;
ViewKeyword : 'view' ;
Identifier
: IdentifierStart IdentifierPart* ;
fragment
IdentifierStart
: [a-zA-Z$_] ;
fragment
IdentifierPart
: [a-zA-Z0-9$_] ;
StringLiteral
: '"' DoubleQuotedStringCharacter* '"'
| '\'' SingleQuotedStringCharacter* '\'' ;
fragment
DoubleQuotedStringCharacter
: ~["\r\n\\] | ('\\' .) ;
fragment
SingleQuotedStringCharacter
: ~['\r\n\\] | ('\\' .) ;
WS
: [ \t\r\n\u000C]+ -> skip ;
COMMENT
: '/*' .*? '*/' -> channel(HIDDEN) ;
LINE_COMMENT
: '//' ~[\r\n]* -> channel(HIDDEN) ;
|
// Copyright 2016-2017 Federico Bond <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
grammar Solidity;
sourceUnit
: (pragmaDirective | importDirective | contractDefinition)* EOF ;
pragmaDirective
: 'pragma' pragmaName pragmaValue ';' ;
pragmaName
: identifier ;
pragmaValue
: version | expression ;
version
: versionConstraint versionConstraint? ;
versionOperator
: '^' | '~' | '>=' | '>' | '<' | '<=' | '=' ;
versionConstraint
: versionOperator? VersionLiteral ;
importDeclaration
: identifier ('as' identifier)? ;
importDirective
: 'import' StringLiteral ('as' identifier)? ';'
| 'import' ('*' | identifier) ('as' identifier)? 'from' StringLiteral ';'
| 'import' '{' importDeclaration ( ',' importDeclaration )* '}' 'from' StringLiteral ';' ;
contractDefinition
: ( 'contract' | 'interface' | 'library' ) identifier
( 'is' inheritanceSpecifier (',' inheritanceSpecifier )* )?
'{' contractPart* '}' ;
inheritanceSpecifier
: userDefinedTypeName ( '(' expression ( ',' expression )* ')' )? ;
contractPart
: stateVariableDeclaration
| usingForDeclaration
| structDefinition
| constructorDefinition
| modifierDefinition
| functionDefinition
| eventDefinition
| enumDefinition ;
stateVariableDeclaration
: typeName
( PublicKeyword | InternalKeyword | PrivateKeyword | ConstantKeyword )*
identifier ('=' expression)? ';' ;
usingForDeclaration
: 'using' identifier 'for' ('*' | typeName) ';' ;
structDefinition
: 'struct' identifier
'{' ( variableDeclaration ';' (variableDeclaration ';')* )? '}' ;
constructorDefinition
: 'constructor' parameterList modifierList block ;
modifierDefinition
: 'modifier' identifier parameterList? block ;
modifierInvocation
: identifier ( '(' expressionList? ')' )? ;
functionDefinition
: 'function' identifier? parameterList modifierList returnParameters? ( ';' | block ) ;
returnParameters
: 'returns' parameterList ;
modifierList
: ( modifierInvocation | stateMutability | ExternalKeyword
| PublicKeyword | InternalKeyword | PrivateKeyword )* ;
eventDefinition
: 'event' identifier eventParameterList AnonymousKeyword? ';' ;
enumValue
: identifier ;
enumDefinition
: 'enum' identifier '{' enumValue? (',' enumValue)* '}' ;
parameterList
: '(' ( parameter (',' parameter)* )? ')' ;
parameter
: typeName storageLocation? identifier? ;
eventParameterList
: '(' ( eventParameter (',' eventParameter)* )? ')' ;
eventParameter
: typeName IndexedKeyword? identifier? ;
functionTypeParameterList
: '(' ( functionTypeParameter (',' functionTypeParameter)* )? ')' ;
functionTypeParameter
: typeName storageLocation? ;
variableDeclaration
: typeName storageLocation? identifier ;
typeName
: elementaryTypeName
| userDefinedTypeName
| mapping
| typeName '[' expression? ']'
| functionTypeName ;
userDefinedTypeName
: identifier ( '.' identifier )* ;
mapping
: 'mapping' '(' elementaryTypeName '=>' typeName ')' ;
functionTypeName
: 'function' functionTypeParameterList
( InternalKeyword | ExternalKeyword | stateMutability )*
( 'returns' functionTypeParameterList )? ;
storageLocation
: 'memory' | 'storage' | 'calldata';
stateMutability
: PureKeyword | ConstantKeyword | ViewKeyword | PayableKeyword ;
block
: '{' statement* '}' ;
statement
: ifStatement
| whileStatement
| forStatement
| block
| inlineAssemblyStatement
| doWhileStatement
| continueStatement
| breakStatement
| returnStatement
| throwStatement
| emitStatement
| simpleStatement ;
expressionStatement
: expression ';' ;
ifStatement
: 'if' '(' expression ')' statement ( 'else' statement )? ;
whileStatement
: 'while' '(' expression ')' statement ;
simpleStatement
: ( variableDeclarationStatement | expressionStatement ) ;
forStatement
: 'for' '(' ( simpleStatement | ';' ) expression? ';' expression? ')' statement ;
inlineAssemblyStatement
: 'assembly' StringLiteral? assemblyBlock ;
doWhileStatement
: 'do' statement 'while' '(' expression ')' ';' ;
continueStatement
: 'continue' ';' ;
breakStatement
: 'break' ';' ;
returnStatement
: 'return' expression? ';' ;
throwStatement
: 'throw' ';' ;
emitStatement
: 'emit' functionCall ';' ;
variableDeclarationStatement
: ( 'var' identifierList | variableDeclaration ) ( '=' 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? ;
functionCall
: expression '(' functionCallArguments ')' ;
assemblyBlock
: '{' assemblyItem* '}' ;
assemblyItem
: identifier
| assemblyBlock
| assemblyExpression
| assemblyLocalDefinition
| assemblyAssignment
| assemblyStackAssignment
| labelDefinition
| assemblySwitch
| assemblyFunctionDefinition
| assemblyFor
| assemblyIf
| BreakKeyword
| ContinueKeyword
| subAssembly
| numberLiteral
| StringLiteral
| HexLiteral ;
assemblyExpression
: assemblyCall | assemblyLiteral ;
assemblyCall
: ( 'return' | 'address' | 'byte' | identifier ) ( '(' assemblyExpression? ( ',' assemblyExpression )* ')' )? ;
assemblyLocalDefinition
: 'let' assemblyIdentifierOrList ( ':=' assemblyExpression )? ;
assemblyAssignment
: assemblyIdentifierOrList ':=' assemblyExpression ;
assemblyIdentifierOrList
: identifier | '(' assemblyIdentifierList ')' ;
assemblyIdentifierList
: identifier ( ',' identifier )* ;
assemblyStackAssignment
: '=:' identifier ;
labelDefinition
: identifier ':' ;
assemblySwitch
: 'switch' assemblyExpression assemblyCase* ;
assemblyCase
: 'case' assemblyLiteral assemblyBlock
| 'default' assemblyBlock ;
assemblyFunctionDefinition
: 'function' identifier '(' assemblyIdentifierList? ')'
assemblyFunctionReturns? assemblyBlock ;
assemblyFunctionReturns
: ( '->' assemblyIdentifierList ) ;
assemblyFor
: 'for' ( assemblyBlock | assemblyExpression )
assemblyExpression ( assemblyBlock | assemblyExpression ) assemblyBlock ;
assemblyIf
: 'if' assemblyExpression assemblyBlock ;
assemblyLiteral
: StringLiteral | DecimalNumber | HexNumber | HexLiteral ;
subAssembly
: 'assembly' identifier assemblyBlock ;
tupleExpression
: '(' ( expression? ( ',' expression? )* ) ')'
| '[' ( expression ( ',' expression )* )? ']' ;
elementaryTypeNameExpression
: elementaryTypeName ;
numberLiteral
: (DecimalNumber | HexNumber) NumberUnit? ;
identifier
: ('from' | Identifier) ;
VersionLiteral
: [0-9]+ '.' [0-9]+ '.' [0-9]+ ;
BooleanLiteral
: 'true' | 'false' ;
DecimalNumber
: [0-9]+ ( '.' [0-9]* )? ( [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) ;
|
Allow calldata in storageLocation
|
Allow calldata in storageLocation
|
ANTLR
|
mit
|
solidityj/solidity-antlr4,federicobond/solidity-antlr4
|
55c0683afdb7994129ee9769d019bff815da83b0
|
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
|
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
|
lexer grammar CreoleTokens;
options { superClass=ContextSensitiveLexer; }
@members {
// We keep track of whether we're in bold or not with this state. It's not
// ideal, but as the start/end formatting tokens are all the same, this is
// probably the best we can do (short of going crazy with lexer modes).
Formatting bold;
Formatting italic;
Formatting strike;
public java.util.List<Formatting> setupFormatting() {
bold = new Formatting("**", BSt, BEnd);
italic = new Formatting("//", ISt, IEnd);
strike = new Formatting("--", SSt, SEnd);
return com.google.common.collect.ImmutableList.of(bold, italic, strike);
}
public boolean inHeader = false;
public boolean start = false;
public int listLevel = 0;
boolean intr = false;
// Start matching a list item: this updates the list level (allowing deeper
// list tokens to be matched), and breaks out of any formatting we may have
// going on - which may trigger parser error-correction.
public void doList(int level) {
seek(-1);
listLevel = level;
resetFormatting();
String next1 = get(0);
String next2 = get(1);
start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#"));
}
// When we think we've matched a URL, seek back through it until we have
// something more reasonable looking.
public void doUrl() {
String url = getText();
String last = url.substring(url.length()-1);
String next = next(1);
String badEnds = inHeader ? "[\\.,)\"';:\\\\=-]" : "[\\.,)\"';:\\\\-]";
while((last + next).equals("//") || last.matches(badEnds)) {
seek(-1);
url = url.substring(0, url.length() - 1);
last = url.substring(url.length()-1);
next = next(1);
// Break out if we no longer have a URL
if(url.endsWith(":/") || url.endsWith("mailto:")) {
setType(Any);
break;
}
}
setText(url);
}
// Reset all special lexer state.
public void breakOut() {
resetFormatting();
listLevel = 0;
inHeader = false;
intr = false;
}
// Determine which tokens can, at this stage, break out of any inline
// formatting.
public java.util.List<String> thisKillsTheFormatting() {
java.util.List<String> ends = new java.util.ArrayList<String>();
if(inHeader || intr) {
ends.add("\n");
ends.add("\r\n");
}
else {
ends.add("\n\n");
ends.add("\r\n\r\n");
}
if(intr) {
ends.add("|");
}
if(listLevel > 0) {
// \L (when at the start) matches the start of a line.
ends.add("\\L*");
ends.add("\\L#");
}
return ends;
}
// Handle a link target or title ending with a ']' or '}'.
public void doLinkEnd() {
String txt = getText().trim();
int len = txt.length();
if(len > 2) {
String lastButTwo = txt.substring(len - 3, len - 2);
if(lastButTwo.equals("]") || lastButTwo.equals("}")) {
txt = txt.substring(0, len - 2);
seek(-2);
}
}
setText(txt);
}
}
/* ***** Headings ***** */
HSt : LINE ('=' | '==' | '===' | '====' | '=====' | '======') ~'=' {inHeader=true; seek(-1);} ;
HEnd : WS? '='* WS? (LineBreak | ParBreak) {inHeader}? {breakOut();} ;
/* ***** Lists ***** */
// Lists are messy, as in the parser. One notable trait is that sublists can
// start with any combination of *s and #s, which is perhaps too flexible, but
// it works (and was easy to specify). It means we can do things like this:
// * Level 1 Unordered
// *# Sublist which is ordered
// *#* Sublist which is unordered
// #** Item of same unordered sublist
// ##* Item of same unordered sublist
U1 : START U {doList(1);} ;
U2 : START L U {listLevel >= 1}? {doList(2);} ;
U3 : START L L U {listLevel >= 2}? {doList(3);} ;
U4 : START L L L U {listLevel >= 3}? {doList(4);} ;
U5 : START L L L L U {listLevel >= 4}? {doList(5);} ;
U6 : START L L L L L U {listLevel >= 5}? {doList(6);} ;
U7 : START L L L L L L U {listLevel >= 6}? {doList(7);} ;
U8 : START L L L L L L L U {listLevel >= 7}? {doList(8);} ;
U9 : START L L L L L L L L U {listLevel >= 8}? {doList(9);} ;
U10 : START L L L L L L L L L U {listLevel >= 9}? {doList(10);} ;
O1 : START O {doList(1);} ;
O2 : START L O {listLevel >= 1}? {doList(2);} ;
O3 : START L L O {listLevel >= 2}? {doList(3);} ;
O4 : START L L L O {listLevel >= 3}? {doList(4);} ;
O5 : START L L L L O {listLevel >= 4}? {doList(5);} ;
O6 : START L L L L L O {listLevel >= 5}? {doList(6);} ;
O7 : START L L L L L L O {listLevel >= 6}? {doList(7);} ;
O8 : START L L L L L L L O {listLevel >= 7}? {doList(8);} ;
O9 : START L L L L L L L L O {listLevel >= 8}? {doList(9);} ;
O10 : START L L L L L L L L L O {listLevel >= 9}? {doList(10);} ;
fragment U : '*' ~('*'|'\r'|'\n') ;
fragment O : '#' ~('#'|'\r'|'\n') ;
fragment L : '*' | '#' ;
/* ***** 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 ***** */
Bold : '**' {toggleFormatting(bold, Any);} ;
Italic : '//' {prior() == null || (prior() != ':' || !Character.isLetterOrDigit(priorprior()))}? {toggleFormatting(italic, Any);} ;
Strike : '--' {toggleFormatting(strike, Any);} ;
NoWiki : '{{{' -> mode(NOWIKI_INLINE) ;
StartCpp : '[<c++>]' -> mode(CPP_INLINE) ;
StartHtml : '[<html>]' -> mode(HTML_INLINE) ;
StartJava : '[<java>]' -> mode(JAVA_INLINE) ;
StartXhtml : '[<xhtml>]' -> mode(XHTML_INLINE) ;
StartXml : '[<xml>]' -> mode(XML_INLINE) ;
/* ***** Links ***** */
LiSt : '[[' -> mode(LINK) ;
ImSt : '{{' -> mode(LINK) ;
AnSt : '[[#' -> mode(ANCHOR) ;
/* ***** Breaks ***** */
InlineBrk : '\\\\' ;
ParBreak : LineBreak WS? LineBreak+ {breakOut();} ;
LineBreak : '\r'? '\n' ;
/* ***** Links ***** */
RawUrl : PROTOCOL (~(' '|'\t'|'\r'|'\n'|'|'|'['|']'|'"'|'/')+ '/'?)+ {doUrl();} ;
fragment PROTOCOL : ('http' 's'? | 'file' | 'ftp') '://' | 'file:/' | 'mailto:' ;
Attachment : UPPER CAMEL '.' ALNUM+ ;
WikiWords : (UPPER (ABBR | CAMEL) REVISION? | INTERWIKI ALNUM+) NOTALNUM {prior() == null || prior() != '.' && prior() != ':' && !Character.isLetterOrDigit(prior()) && !(last() == '.' && Character.isLetter(next()))}? {seek(-1);} ;
fragment INTERWIKI : ALPHA ALNUM+ ':' ;
fragment ABBR : UPPER UPPER+ ;
fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ;
fragment REVISION : '?revision=' DIGIT+ ;
/* ***** Macros ***** */
MacroSt : '<<' -> mode(MACRO) ;
DirectiveEnable : '<<+' -> mode(MACRO) ;
DirectiveDisable : '<<-' -> mode(MACRO) ;
/* ***** Quotes ***** */
BlockquoteSt : '[<blockquote>]' ;
BlockquoteEnd : '[</blockquote>]' ;
/* ***** Miscellaneous ***** */
Any : ALNUM+ | . ;
WS : (' '|'\t')+ ;
// Skip empty links like [[]] and {{}}. These are commonly used to break up WikiWords.
EmptyLink : ('[[' WS? ']]' | '{{' WS? '}}' |'[[' WS? '|' WS? ']]' | '{{' WS? '|' WS? '}}') -> skip ;
fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ;
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') ;
// 'START' matches something which is start-of-line-like. Currently that's upon
// entering a list item or table cell
fragment START : {start}? | {intr && priorTokId == TdStart}? WS* | LINE ;
fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*;
/* ***** Contextual stuff ***** */
mode LINK;
LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
Sep : ' '* '|'+ ' '* -> mode(LINK_END);
InLink : (~('|'|'\r'|'\n'|']'|'}') | (']' ~']' | '}' ~'}'))+ {doLinkEnd();} ;
mode LINK_END;
InLinkEnd : (~('\r'|'\n'|']'|'}') | (']' ~']' | '}' ~'}'))+ {doLinkEnd();} ;
LiEnd2 : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
ImEnd2 : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
mode ANCHOR;
InAnchor : ~('#'|']')+ ;
AnEnd : ']]' -> mode(DEFAULT_MODE);
mode MACRO;
MacroName : ~(':'|'>')+ ;
MacroEndNoArgs : '>>' -> mode(DEFAULT_MODE) ;
MacroSep : ':' -> mode(MACRO_ARGS) ;
mode MACRO_ARGS;
MacroArgs : . -> more ;
MacroEnd : '>>' -> mode(DEFAULT_MODE) ;
// ***** NoWiki
mode NOWIKI_INLINE;
fragment INLINE : ~('\r'|'\n') ;
fragment BLOCK : . ;
fragment TOBLOCK : ('\r'|'\n') ;
NoWikiInline : INLINE -> more ;
NoWikiToBlock : TOBLOCK -> mode(NOWIKI_BLOCK), more ;
EndNoWikiInline : '}}}' ~'}' {seek(-1);} -> mode(DEFAULT_MODE) ;
mode NOWIKI_BLOCK;
NoWikiAny : BLOCK -> more ;
EndNoWikiBlock : (~' ' '}}}' | ' }}}' '\r'? '\n' {seek(-1);}) -> mode(DEFAULT_MODE) ;
// ***** C++
mode CPP_INLINE;
CppInline : INLINE -> more ;
CppToBlock : TOBLOCK -> mode(CPP_BLOCK), more ;
EndCppInline : '[</c++>]' -> mode(DEFAULT_MODE) ;
mode CPP_BLOCK;
CppAny : BLOCK -> more ;
EndCppBlock : ~' ' '[</c++>]' -> mode(DEFAULT_MODE) ;
// ***** HTML
mode HTML_INLINE;
HtmlInline : INLINE -> more ;
HtmlToBlock : TOBLOCK -> mode(HTML_BLOCK), more ;
EndHtmlInline : '[</html>]'-> mode(DEFAULT_MODE) ;
mode HTML_BLOCK;
HtmlAny : BLOCK -> more ;
EndHtmlBlock : ~' ' '[</html>]' -> mode(DEFAULT_MODE) ;
// ***** Java
mode JAVA_INLINE;
JavaInline : INLINE -> more ;
JavaToBlock : TOBLOCK -> mode(JAVA_BLOCK), more ;
EndJavaInline : '[</java>]'-> mode(DEFAULT_MODE) ;
mode JAVA_BLOCK;
JavaAny : BLOCK -> more ;
EndJavaBlock : ~' ' '[</java>]' -> mode(DEFAULT_MODE) ;
// ***** XHTML
mode XHTML_INLINE;
XhtmlInline : INLINE -> more ;
XhtmlToBlock : TOBLOCK -> mode(XHTML_BLOCK), more ;
EndXhtmlInline : '[</xhtml>]' -> mode(DEFAULT_MODE) ;
mode XHTML_BLOCK;
XhtmlAny : BLOCK -> more ;
EndXhtmlBlock : ~' ' '[</xhtml>]' -> mode(DEFAULT_MODE) ;
// ***** XML
mode XML_INLINE;
XmlInline : INLINE -> more ;
XmlToBlock : TOBLOCK -> mode(XML_BLOCK), more ;
EndXmlInline : '[</xml>]' -> mode(DEFAULT_MODE) ;
mode XML_BLOCK;
XmlAny : BLOCK -> more ;
EndXmlBlock : ~' ' '[</xml>]' -> mode(DEFAULT_MODE) ;
// Helper token types, not directly matched, but seta s the type of other tokens.
mode HELPERS;
BSt : ;
ISt : ;
SSt : ;
BEnd : ;
IEnd : ;
SEnd : ;
|
lexer grammar CreoleTokens;
options { superClass=ContextSensitiveLexer; }
@members {
// We keep track of whether we're in bold or not with this state. It's not
// ideal, but as the start/end formatting tokens are all the same, this is
// probably the best we can do (short of going crazy with lexer modes).
Formatting bold;
Formatting italic;
Formatting strike;
public java.util.List<Formatting> setupFormatting() {
bold = new Formatting("**", BSt, BEnd);
italic = new Formatting("//", ISt, IEnd);
strike = new Formatting("--", SSt, SEnd);
return com.google.common.collect.ImmutableList.of(bold, italic, strike);
}
public boolean inHeader = false;
public boolean start = false;
public int listLevel = 0;
boolean intr = false;
// Start matching a list item: this updates the list level (allowing deeper
// list tokens to be matched), and breaks out of any formatting we may have
// going on - which may trigger parser error-correction.
public void doList(int level) {
seek(-1);
listLevel = level;
resetFormatting();
String next1 = get(0);
String next2 = get(1);
start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#"));
}
// When we think we've matched a URL, seek back through it until we have
// something more reasonable looking.
public void doUrl() {
String url = getText();
String last = url.substring(url.length()-1);
String next = next(1);
String badEnds = inHeader ? "[\\.,)\"';:\\\\=-]" : "[\\.,)\"';:\\\\-]";
while((last + next).equals("//") || last.matches(badEnds)) {
seek(-1);
url = url.substring(0, url.length() - 1);
last = url.substring(url.length()-1);
next = next(1);
// Break out if we no longer have a URL
if(url.endsWith(":/") || url.endsWith("mailto:")) {
setType(Any);
break;
}
}
setText(url);
}
// Reset all special lexer state.
public void breakOut() {
resetFormatting();
listLevel = 0;
inHeader = false;
intr = false;
}
// Determine which tokens can, at this stage, break out of any inline
// formatting.
public java.util.List<String> thisKillsTheFormatting() {
java.util.List<String> ends = new java.util.ArrayList<String>();
if(inHeader || intr) {
ends.add("\n");
ends.add("\r\n");
}
else {
ends.add("\n\n");
ends.add("\r\n\r\n");
}
if(intr) {
ends.add("|");
}
if(listLevel > 0) {
// \L (when at the start) matches the start of a line.
ends.add("\\L*");
ends.add("\\L#");
}
return ends;
}
// Handle a link target or title ending with a ']' or '}'.
public void doLinkEnd() {
String txt = getText().trim();
int len = txt.length();
if(len > 2) {
String lastButTwo = txt.substring(len - 3, len - 2);
if(lastButTwo.equals("]") || lastButTwo.equals("}")) {
txt = txt.substring(0, len - 2);
seek(-2);
}
}
setText(txt);
}
}
/* ***** Headings ***** */
HSt : LINE ('=' | '==' | '===' | '====' | '=====' | '======') ~'=' {inHeader=true; seek(-1);} ;
HEnd : WS? '='* WS? (LineBreak | ParBreak) {inHeader}? {breakOut();} ;
/* ***** Lists ***** */
// Lists are messy, as in the parser. One notable trait is that sublists can
// start with any combination of *s and #s, which is perhaps too flexible, but
// it works (and was easy to specify). It means we can do things like this:
// * Level 1 Unordered
// *# Sublist which is ordered
// *#* Sublist which is unordered
// #** Item of same unordered sublist
// ##* Item of same unordered sublist
U1 : START U {doList(1);} ;
U2 : START L U {listLevel >= 1}? {doList(2);} ;
U3 : START L L U {listLevel >= 2}? {doList(3);} ;
U4 : START L L L U {listLevel >= 3}? {doList(4);} ;
U5 : START L L L L U {listLevel >= 4}? {doList(5);} ;
U6 : START L L L L L U {listLevel >= 5}? {doList(6);} ;
U7 : START L L L L L L U {listLevel >= 6}? {doList(7);} ;
U8 : START L L L L L L L U {listLevel >= 7}? {doList(8);} ;
U9 : START L L L L L L L L U {listLevel >= 8}? {doList(9);} ;
U10 : START L L L L L L L L L U {listLevel >= 9}? {doList(10);} ;
O1 : START O {doList(1);} ;
O2 : START L O {listLevel >= 1}? {doList(2);} ;
O3 : START L L O {listLevel >= 2}? {doList(3);} ;
O4 : START L L L O {listLevel >= 3}? {doList(4);} ;
O5 : START L L L L O {listLevel >= 4}? {doList(5);} ;
O6 : START L L L L L O {listLevel >= 5}? {doList(6);} ;
O7 : START L L L L L L O {listLevel >= 6}? {doList(7);} ;
O8 : START L L L L L L L O {listLevel >= 7}? {doList(8);} ;
O9 : START L L L L L L L L O {listLevel >= 8}? {doList(9);} ;
O10 : START L L L L L L L L L O {listLevel >= 9}? {doList(10);} ;
fragment U : '*' ~('*'|'\r'|'\n') ;
fragment O : '#' ~('#'|'\r'|'\n') ;
fragment L : '*' | '#' ;
/* ***** 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 ***** */
Bold : '**' {toggleFormatting(bold, Any);} ;
Italic : '//' {prior() == null || (prior() != ':' || !Character.isLetterOrDigit(priorprior()))}? {toggleFormatting(italic, Any);} ;
Strike : '--' {toggleFormatting(strike, Any);} ;
NoWiki : '{{{' -> mode(NOWIKI_INLINE) ;
StartCpp : '[<c++>]' -> mode(CPP_INLINE) ;
StartHtml : '[<html>]' -> mode(HTML_INLINE) ;
StartJava : '[<java>]' -> mode(JAVA_INLINE) ;
StartXhtml : '[<xhtml>]' -> mode(XHTML_INLINE) ;
StartXml : '[<xml>]' -> mode(XML_INLINE) ;
/* ***** Links ***** */
LiSt : '[[' -> mode(LINK) ;
ImSt : '{{' -> mode(LINK) ;
AnSt : '[[#' -> mode(ANCHOR) ;
/* ***** Breaks ***** */
InlineBrk : '\\\\' ;
ParBreak : LineBreak WS? LineBreak+ {breakOut();} ;
LineBreak : '\r'? '\n' ;
/* ***** Links ***** */
RawUrl : PROTOCOL (~(' '|'\t'|'\r'|'\n'|'|'|'['|']'|'"'|'/')+ '/'?)+ {doUrl();} ;
fragment PROTOCOL : ('http' 's'? | 'file' | 'ftp') '://' | 'file:/' | 'mailto:' ;
Attachment : UPPER CAMEL '.' ALNUM+ ;
WikiWords : (UPPER (ABBR | CAMEL) REVISION? | INTERWIKI IWTARGET+) NOTALNUM {prior() == null || prior() != '.' && prior() != ':' && !Character.isLetterOrDigit(prior()) && !(last() == '.' && Character.isLetter(next()))}? {seek(-1);} ;
fragment IWTARGET : ALNUM (('.' | '-') ALNUM)? ;
fragment INTERWIKI : ALPHA ALNUM+ ':' ;
fragment ABBR : UPPER UPPER+ ;
fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ;
fragment REVISION : '?revision=' DIGIT+ ;
/* ***** Macros ***** */
MacroSt : '<<' -> mode(MACRO) ;
DirectiveEnable : '<<+' -> mode(MACRO) ;
DirectiveDisable : '<<-' -> mode(MACRO) ;
/* ***** Quotes ***** */
BlockquoteSt : '[<blockquote>]' ;
BlockquoteEnd : '[</blockquote>]' ;
/* ***** Miscellaneous ***** */
Any : ALNUM+ | . ;
WS : (' '|'\t')+ ;
// Skip empty links like [[]] and {{}}. These are commonly used to break up WikiWords.
EmptyLink : ('[[' WS? ']]' | '{{' WS? '}}' |'[[' WS? '|' WS? ']]' | '{{' WS? '|' WS? '}}') -> skip ;
fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ;
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') ;
// 'START' matches something which is start-of-line-like. Currently that's upon
// entering a list item or table cell
fragment START : {start}? | {intr && priorTokId == TdStart}? WS* | LINE ;
fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*;
/* ***** Contextual stuff ***** */
mode LINK;
LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
Sep : ' '* '|'+ ' '* -> mode(LINK_END);
InLink : (~('|'|'\r'|'\n'|']'|'}') | (']' ~']' | '}' ~'}'))+ {doLinkEnd();} ;
mode LINK_END;
InLinkEnd : (~('\r'|'\n'|']'|'}') | (']' ~']' | '}' ~'}'))+ {doLinkEnd();} ;
LiEnd2 : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
ImEnd2 : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
mode ANCHOR;
InAnchor : ~('#'|']')+ ;
AnEnd : ']]' -> mode(DEFAULT_MODE);
mode MACRO;
MacroName : ~(':'|'>')+ ;
MacroEndNoArgs : '>>' -> mode(DEFAULT_MODE) ;
MacroSep : ':' -> mode(MACRO_ARGS) ;
mode MACRO_ARGS;
MacroArgs : . -> more ;
MacroEnd : '>>' -> mode(DEFAULT_MODE) ;
// ***** NoWiki
mode NOWIKI_INLINE;
fragment INLINE : ~('\r'|'\n') ;
fragment BLOCK : . ;
fragment TOBLOCK : ('\r'|'\n') ;
NoWikiInline : INLINE -> more ;
NoWikiToBlock : TOBLOCK -> mode(NOWIKI_BLOCK), more ;
EndNoWikiInline : '}}}' ~'}' {seek(-1);} -> mode(DEFAULT_MODE) ;
mode NOWIKI_BLOCK;
NoWikiAny : BLOCK -> more ;
EndNoWikiBlock : (~' ' '}}}' | ' }}}' '\r'? '\n' {seek(-1);}) -> mode(DEFAULT_MODE) ;
// ***** C++
mode CPP_INLINE;
CppInline : INLINE -> more ;
CppToBlock : TOBLOCK -> mode(CPP_BLOCK), more ;
EndCppInline : '[</c++>]' -> mode(DEFAULT_MODE) ;
mode CPP_BLOCK;
CppAny : BLOCK -> more ;
EndCppBlock : ~' ' '[</c++>]' -> mode(DEFAULT_MODE) ;
// ***** HTML
mode HTML_INLINE;
HtmlInline : INLINE -> more ;
HtmlToBlock : TOBLOCK -> mode(HTML_BLOCK), more ;
EndHtmlInline : '[</html>]'-> mode(DEFAULT_MODE) ;
mode HTML_BLOCK;
HtmlAny : BLOCK -> more ;
EndHtmlBlock : ~' ' '[</html>]' -> mode(DEFAULT_MODE) ;
// ***** Java
mode JAVA_INLINE;
JavaInline : INLINE -> more ;
JavaToBlock : TOBLOCK -> mode(JAVA_BLOCK), more ;
EndJavaInline : '[</java>]'-> mode(DEFAULT_MODE) ;
mode JAVA_BLOCK;
JavaAny : BLOCK -> more ;
EndJavaBlock : ~' ' '[</java>]' -> mode(DEFAULT_MODE) ;
// ***** XHTML
mode XHTML_INLINE;
XhtmlInline : INLINE -> more ;
XhtmlToBlock : TOBLOCK -> mode(XHTML_BLOCK), more ;
EndXhtmlInline : '[</xhtml>]' -> mode(DEFAULT_MODE) ;
mode XHTML_BLOCK;
XhtmlAny : BLOCK -> more ;
EndXhtmlBlock : ~' ' '[</xhtml>]' -> mode(DEFAULT_MODE) ;
// ***** XML
mode XML_INLINE;
XmlInline : INLINE -> more ;
XmlToBlock : TOBLOCK -> mode(XML_BLOCK), more ;
EndXmlInline : '[</xml>]' -> mode(DEFAULT_MODE) ;
mode XML_BLOCK;
XmlAny : BLOCK -> more ;
EndXmlBlock : ~' ' '[</xml>]' -> mode(DEFAULT_MODE) ;
// Helper token types, not directly matched, but seta s the type of other tokens.
mode HELPERS;
BSt : ;
ISt : ;
SSt : ;
BEnd : ;
IEnd : ;
SEnd : ;
|
Allow '.' and '-' to occur in the middle of interwiki link targets
|
Allow '.' and '-' to occur in the middle of interwiki link targets
|
ANTLR
|
apache-2.0
|
CoreFiling/reviki,ashirley/reviki,strr/reviki,strr/reviki,strr/reviki,CoreFiling/reviki,ashirley/reviki,ashirley/reviki,strr/reviki,CoreFiling/reviki,ashirley/reviki,CoreFiling/reviki,ashirley/reviki,strr/reviki,CoreFiling/reviki
|
f1bef0bdd931b2d1aa09d0e63d82aefd5049dae6
|
omni-cx2x/src/cx2x/translator/language/parser/Claw.g4
|
omni-cx2x/src/cx2x/translator/language/parser/Claw.g4
|
/*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
/**
* ANTLR 4 Grammar file for the CLAW directive language.
*
* @author clementval
*/
grammar Claw;
@header
{
import cx2x.translator.common.ClawConstant;
import cx2x.translator.language.base.ClawDirective;
import cx2x.translator.language.base.ClawLanguage;
import cx2x.translator.language.common.*;
import cx2x.translator.common.Utility;
}
/*----------------------------------------------------------------------------
* PARSER RULES
*----------------------------------------------------------------------------*/
/*
* Entry point for the analyzis of a CLAW directive.
* Return a CLawLanguage object with all needed information.
*/
analyze returns [ClawLanguage l]
@init{
$l = new ClawLanguage();
}
:
CLAW directive[$l] EOF
| CLAW VERBATIM // this directive accept anything after the verbatim
{ $l.setDirective(ClawDirective.VERBATIM); }
| CLAW ACC // this directive accept anything after the acc
{ $l.setDirective(ClawDirective.PRIMITIVE); }
| CLAW OMP // this directive accept anything after the omp
{ $l.setDirective(ClawDirective.PRIMITIVE); }
;
directive[ClawLanguage l]
@init{
List<ClawMapping> m = new ArrayList<>();
List<String> o = new ArrayList<>();
List<String> s = new ArrayList<>();
List<Integer> i = new ArrayList<>();
}
:
// loop-fusion directive
LOOPFUSION group_clause_optional[$l] collapse_optional[$l] EOF
{ $l.setDirective(ClawDirective.LOOP_FUSION); }
// loop-interchange directive
| LOOPINTERCHANGE indexes_option[$l] parallel_optional[$l] acc_optional[$l] EOF
{ $l.setDirective(ClawDirective.LOOP_INTERCHANGE); }
// loop-extract directive
| LOOPEXTRACT range_option mapping_option_list[m] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF
{
$l.setDirective(ClawDirective.LOOP_EXTRACT);
$l.setRange($range_option.r);
$l.setMappings(m);
}
// remove directive
| REMOVE EOF
{ $l.setDirective(ClawDirective.REMOVE); }
| END REMOVE EOF
{
$l.setDirective(ClawDirective.REMOVE);
$l.setEndPragma();
}
// Kcache directive
| KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF
{
$l.setDirective(ClawDirective.KCACHE);
$l.setOffsets(i);
}
| KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF
{
$l.setDirective(ClawDirective.KCACHE);
$l.setOffsets(i);
$l.setInitClause();
}
// Array notation transformation directive
| ARRAY_TRANS induction_optional[$l] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF
{ $l.setDirective(ClawDirective.ARRAY_TRANSFORM); }
| END ARRAY_TRANS
{
$l.setDirective(ClawDirective.ARRAY_TRANSFORM);
$l.setEndPragma();
}
// loop-hoist directive
| LOOPHOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF
{
$l.setHoistInductionVars(o);
$l.setDirective(ClawDirective.LOOP_HOIST);
}
| END LOOPHOIST EOF
{
$l.setDirective(ClawDirective.LOOP_HOIST);
$l.setEndPragma();
}
// on the fly directive
| ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')'
{
$l.setDirective(ClawDirective.ARRAY_TO_CALL);
$l.setFctParams(o);
$l.setFctName($fct_name.text);
$l.setArrayName($array_name.text);
}
// parallelize directive
| define_option[$l]* PARALLELIZE data_over_clause[$l]*
{
$l.setDirective(ClawDirective.PARALLELIZE);
}
| PARALLELIZE FORWARD
{
$l.setDirective(ClawDirective.PARALLELIZE);
$l.setForwardClause();
}
| END PARALLELIZE
{
$l.setDirective(ClawDirective.PARALLELIZE);
$l.setEndPragma();
}
// ignore directive
| IGNORE
{
$l.setDirective(ClawDirective.IGNORE);
}
| END IGNORE
{
$l.setDirective(ClawDirective.IGNORE);
$l.setEndPragma();
}
;
// Comma-separated identifiers list
ids_list[List<String> ids]
:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids]
;
// Comma-separated identifiers or colon symbol list
ids_or_colon_list[List<String> ids]
:
i=IDENTIFIER { $ids.add($i.text); }
| ':' { $ids.add(":"); }
| i=IDENTIFIER { $ids.add($i.text); } ',' ids_or_colon_list[$ids]
| ':' { $ids.add(":"); } ',' ids_or_colon_list[$ids]
;
// data over clause used in parallelize directive
data_over_clause[ClawLanguage l]
@init{
List<String> overLst = new ArrayList<>();
List<String> dataLst = new ArrayList<>();
}
:
DATA '(' ids_list[dataLst] ')' OVER '(' ids_or_colon_list[overLst] ')'
{
$l.setOverDataClause(dataLst);
$l.setOverClause(overLst);
}
;
// group clause
group_clause_optional[ClawLanguage l]:
GROUP '(' group_name=IDENTIFIER ')'
{ $l.setGroupClause($group_name.text); }
| /* empty */
;
// collapse clause
collapse_optional[ClawLanguage l]:
COLLAPSE '(' n=NUMBER ')'
{ $l.setCollapseClause($n.text); }
| /* empty */
;
// fusion clause
fusion_optional[ClawLanguage l]:
FUSION group_clause_optional[$l] { $l.setFusionClause(); }
| /* empty */
;
// parallel clause
parallel_optional[ClawLanguage l]:
PARALLEL { $l.setParallelClause(); }
| /* empty */
;
// acc clause
acc_optional[ClawLanguage l]
@init{
List<String> tempAcc = new ArrayList<>();
}
:
ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); }
| /* empty */
;
// interchange clause
interchange_optional[ClawLanguage l]:
INTERCHANGE indexes_option[$l]
{
$l.setInterchangeClause();
}
| /* empty */
;
// induction clause
induction_optional[ClawLanguage l]
@init{
List<String> temp = new ArrayList<>();
}
:
INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); }
| /* empty */
;
// data clause
data_clause[ClawLanguage l]
@init {
List<String> temp = new ArrayList<>();
}
:
DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); }
;
// private clause
private_optional[ClawLanguage l]:
PRIVATE { $l.setPrivateClause(); }
| /* empty */
;
// reshape clause
reshape_optional[ClawLanguage l]
@init{
List<ClawReshapeInfo> r = new ArrayList();
}
:
RESHAPE '(' reshape_list[r] ')'
{ $l.setReshapeClauseValues(r); }
| /* empty */
;
// reshape clause
reshape_element returns [ClawReshapeInfo i]
@init{
List<Integer> temp = new ArrayList();
}
:
array_name=IDENTIFIER '(' target_dim=NUMBER ')'
{ $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); }
| array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')'
{ $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); }
;
reshape_list[List<ClawReshapeInfo> r]:
info=reshape_element { $r.add($info.i); } ',' reshape_list[$r]
| info=reshape_element { $r.add($info.i); }
;
identifiers[List<String> ids]:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids]
;
identifiers_list[List<String> ids]:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids]
;
integers[List<Integer> ints]:
;
integers_list[List<Integer> ints]:
i=NUMBER { $ints.add(Integer.parseInt($i.text)); }
| i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints]
;
indexes_option[ClawLanguage l]
@init{
List<String> indexes = new ArrayList();
}
:
'(' ids_list[indexes] ')' { $l.setIndexes(indexes); }
| /* empty */
;
offset_list_optional[List<Integer> offsets]:
OFFSET '(' offset_list[$offsets] ')'
| /* empty */
;
offset_list[List<Integer> offsets]:
offset[$offsets]
| offset[$offsets] ',' offset_list[$offsets]
;
offset[List<Integer> offsets]:
n=NUMBER { $offsets.add(Integer.parseInt($n.text)); }
| '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); }
| '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); }
;
range_option returns [ClawRange r]
@init{
$r = new ClawRange();
}
:
RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')'
{
$r.setInductionVar($induction.text);
$r.setLowerBound($lower.text);
$r.setUpperBound($upper.text);
$r.setStep(ClawConstant.DEFAULT_STEP_VALUE);
}
| RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')'
{
$r.setInductionVar($induction.text);
$r.setLowerBound($lower.text);
$r.setUpperBound($upper.text);
$r.setStep($step.text);
}
;
range_id returns [String text]:
n=NUMBER { $text = $n.text; }
| i=IDENTIFIER { $text = $i.text; }
;
mapping_var returns [ClawMappingVar mappingVar]:
lhs=IDENTIFIER '/' rhs=IDENTIFIER
{
$mappingVar = new ClawMappingVar($lhs.text, $rhs.text);
}
| i=IDENTIFIER
{
$mappingVar = new ClawMappingVar($i.text, $i.text);
}
;
mapping_var_list[List<ClawMappingVar> vars]:
mv=mapping_var { $vars.add($mv.mappingVar); }
| mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars]
;
mapping_option returns [ClawMapping mapping]
@init{
$mapping = new ClawMapping();
List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>();
List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>();
$mapping.setMappedVariables(listMapped);
$mapping.setMappingVariables(listMapping);
}
:
MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')'
;
mapping_option_list[List<ClawMapping> mappings]:
m=mapping_option { $mappings.add($m.mapping); }
| m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings]
;
define_option[ClawLanguage l]:
DEFINE DIMENSION id=IDENTIFIER '(' lower=range_id ':' upper=range_id ')'
{
ClawDimension cd = new ClawDimension($id.text, $lower.text, $upper.text);
$l.addDimension(cd);
}
;
/*----------------------------------------------------------------------------
* LEXER RULES
*----------------------------------------------------------------------------*/
// Start point
CLAW : 'claw';
// CLAW Directives
ARRAY_TRANS : 'array-transform';
ARRAY_TO_CALL : 'call';
DEFINE : 'define';
END : 'end';
KCACHE : 'kcache';
LOOPEXTRACT : 'loop-extract';
LOOPFUSION : 'loop-fusion';
LOOPHOIST : 'loop-hoist';
LOOPINTERCHANGE : 'loop-interchange';
PARALLELIZE : 'parallelize';
REMOVE : 'remove';
IGNORE : 'ignore';
VERBATIM : 'verbatim';
// CLAW Clauses
COLLAPSE : 'collapse';
DATA : 'data';
DIMENSION : 'dimension';
FORWARD : 'forward';
FUSION : 'fusion';
GROUP : 'group';
INDUCTION : 'induction';
INIT : 'init';
INTERCHANGE : 'interchange';
MAP : 'map';
OFFSET : 'offset';
OVER : 'over';
PARALLEL : 'parallel';
PRIVATE : 'private';
RANGE : 'range';
RESHAPE : 'reshape';
// Directive primitive clause
ACC : 'acc';
OMP : 'omp';
// Special elements
IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ;
NUMBER : (DIGIT)+ ;
fragment DIGIT : [0-9] ;
// Skip whitspaces
WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
|
/*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
/**
* ANTLR 4 Grammar file for the CLAW directive language.
*
* @author clementval
*/
grammar Claw;
@header
{
import cx2x.translator.common.ClawConstant;
import cx2x.translator.language.base.ClawDirective;
import cx2x.translator.language.base.ClawLanguage;
import cx2x.translator.language.common.*;
import cx2x.translator.common.Utility;
}
/*----------------------------------------------------------------------------
* PARSER RULES
*----------------------------------------------------------------------------*/
/*
* Entry point for the analyzis of a CLAW directive.
* Return a CLawLanguage object with all needed information.
*/
analyze returns [ClawLanguage l]
@init{
$l = new ClawLanguage();
}
:
CLAW directive[$l] EOF
| CLAW VERBATIM // this directive accept anything after the verbatim
{ $l.setDirective(ClawDirective.VERBATIM); }
| CLAW ACC // this directive accept anything after the acc
{ $l.setDirective(ClawDirective.PRIMITIVE); }
| CLAW OMP // this directive accept anything after the omp
{ $l.setDirective(ClawDirective.PRIMITIVE); }
;
directive[ClawLanguage l]
@init{
List<ClawMapping> m = new ArrayList<>();
List<String> o = new ArrayList<>();
List<String> s = new ArrayList<>();
List<Integer> i = new ArrayList<>();
}
:
// loop-fusion directive
LOOPFUSION group_clause_optional[$l] collapse_clause_optional[$l] EOF
{ $l.setDirective(ClawDirective.LOOP_FUSION); }
// loop-interchange directive
| LOOPINTERCHANGE indexes_option[$l] parallel_clause_optional[$l] acc_optional[$l] EOF
{ $l.setDirective(ClawDirective.LOOP_INTERCHANGE); }
// loop-extract directive
| LOOPEXTRACT range_option mapping_option_list[m] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF
{
$l.setDirective(ClawDirective.LOOP_EXTRACT);
$l.setRange($range_option.r);
$l.setMappings(m);
}
// remove directive
| REMOVE EOF
{ $l.setDirective(ClawDirective.REMOVE); }
| END REMOVE EOF
{
$l.setDirective(ClawDirective.REMOVE);
$l.setEndPragma();
}
// Kcache directive
| KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF
{
$l.setDirective(ClawDirective.KCACHE);
$l.setOffsets(i);
}
| KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF
{
$l.setDirective(ClawDirective.KCACHE);
$l.setOffsets(i);
$l.setInitClause();
}
// Array notation transformation directive
| ARRAY_TRANS induction_optional[$l] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF
{ $l.setDirective(ClawDirective.ARRAY_TRANSFORM); }
| END ARRAY_TRANS
{
$l.setDirective(ClawDirective.ARRAY_TRANSFORM);
$l.setEndPragma();
}
// loop-hoist directive
| LOOPHOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF
{
$l.setHoistInductionVars(o);
$l.setDirective(ClawDirective.LOOP_HOIST);
}
| END LOOPHOIST EOF
{
$l.setDirective(ClawDirective.LOOP_HOIST);
$l.setEndPragma();
}
// on the fly directive
| ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')'
{
$l.setDirective(ClawDirective.ARRAY_TO_CALL);
$l.setFctParams(o);
$l.setFctName($fct_name.text);
$l.setArrayName($array_name.text);
}
// parallelize directive
| define_option[$l]* PARALLELIZE data_over_clause[$l]*
{
$l.setDirective(ClawDirective.PARALLELIZE);
}
| PARALLELIZE FORWARD
{
$l.setDirective(ClawDirective.PARALLELIZE);
$l.setForwardClause();
}
| END PARALLELIZE
{
$l.setDirective(ClawDirective.PARALLELIZE);
$l.setEndPragma();
}
// ignore directive
| IGNORE
{
$l.setDirective(ClawDirective.IGNORE);
}
| END IGNORE
{
$l.setDirective(ClawDirective.IGNORE);
$l.setEndPragma();
}
;
// Comma-separated identifiers list
ids_list[List<String> ids]
:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids]
;
// Comma-separated identifiers or colon symbol list
ids_or_colon_list[List<String> ids]
:
i=IDENTIFIER { $ids.add($i.text); }
| ':' { $ids.add(":"); }
| i=IDENTIFIER { $ids.add($i.text); } ',' ids_or_colon_list[$ids]
| ':' { $ids.add(":"); } ',' ids_or_colon_list[$ids]
;
// data over clause used in parallelize directive
data_over_clause[ClawLanguage l]
@init{
List<String> overLst = new ArrayList<>();
List<String> dataLst = new ArrayList<>();
}
:
DATA '(' ids_list[dataLst] ')' OVER '(' ids_or_colon_list[overLst] ')'
{
$l.setOverDataClause(dataLst);
$l.setOverClause(overLst);
}
;
// group clause
group_clause_optional[ClawLanguage l]:
GROUP '(' group_name=IDENTIFIER ')'
{ $l.setGroupClause($group_name.text); }
| /* empty */
;
// collapse clause
collapse_clause_optional[ClawLanguage l]:
COLLAPSE '(' n=NUMBER ')'
{ $l.setCollapseClause($n.text); }
| /* empty */
;
// fusion clause
fusion_clause_optional[ClawLanguage l]:
FUSION group_clause_optional[$l] { $l.setFusionClause(); }
| /* empty */
;
// parallel clause
parallel_clause_optional[ClawLanguage l]:
PARALLEL { $l.setParallelClause(); }
| /* empty */
;
// acc clause
acc_optional[ClawLanguage l]
@init{
List<String> tempAcc = new ArrayList<>();
}
:
ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); }
| /* empty */
;
// interchange clause
interchange_optional[ClawLanguage l]:
INTERCHANGE indexes_option[$l]
{
$l.setInterchangeClause();
}
| /* empty */
;
// induction clause
induction_optional[ClawLanguage l]
@init{
List<String> temp = new ArrayList<>();
}
:
INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); }
| /* empty */
;
// data clause
data_clause[ClawLanguage l]
@init {
List<String> temp = new ArrayList<>();
}
:
DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); }
;
// private clause
private_optional[ClawLanguage l]:
PRIVATE { $l.setPrivateClause(); }
| /* empty */
;
// reshape clause
reshape_optional[ClawLanguage l]
@init{
List<ClawReshapeInfo> r = new ArrayList();
}
:
RESHAPE '(' reshape_list[r] ')'
{ $l.setReshapeClauseValues(r); }
| /* empty */
;
// reshape clause
reshape_element returns [ClawReshapeInfo i]
@init{
List<Integer> temp = new ArrayList();
}
:
array_name=IDENTIFIER '(' target_dim=NUMBER ')'
{ $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); }
| array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')'
{ $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); }
;
reshape_list[List<ClawReshapeInfo> r]:
info=reshape_element { $r.add($info.i); } ',' reshape_list[$r]
| info=reshape_element { $r.add($info.i); }
;
identifiers[List<String> ids]:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids]
;
identifiers_list[List<String> ids]:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids]
;
integers[List<Integer> ints]:
;
integers_list[List<Integer> ints]:
i=NUMBER { $ints.add(Integer.parseInt($i.text)); }
| i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints]
;
indexes_option[ClawLanguage l]
@init{
List<String> indexes = new ArrayList();
}
:
'(' ids_list[indexes] ')' { $l.setIndexes(indexes); }
| /* empty */
;
offset_list_optional[List<Integer> offsets]:
OFFSET '(' offset_list[$offsets] ')'
| /* empty */
;
offset_list[List<Integer> offsets]:
offset[$offsets]
| offset[$offsets] ',' offset_list[$offsets]
;
offset[List<Integer> offsets]:
n=NUMBER { $offsets.add(Integer.parseInt($n.text)); }
| '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); }
| '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); }
;
range_option returns [ClawRange r]
@init{
$r = new ClawRange();
}
:
RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')'
{
$r.setInductionVar($induction.text);
$r.setLowerBound($lower.text);
$r.setUpperBound($upper.text);
$r.setStep(ClawConstant.DEFAULT_STEP_VALUE);
}
| RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')'
{
$r.setInductionVar($induction.text);
$r.setLowerBound($lower.text);
$r.setUpperBound($upper.text);
$r.setStep($step.text);
}
;
range_id returns [String text]:
n=NUMBER { $text = $n.text; }
| i=IDENTIFIER { $text = $i.text; }
;
mapping_var returns [ClawMappingVar mappingVar]:
lhs=IDENTIFIER '/' rhs=IDENTIFIER
{
$mappingVar = new ClawMappingVar($lhs.text, $rhs.text);
}
| i=IDENTIFIER
{
$mappingVar = new ClawMappingVar($i.text, $i.text);
}
;
mapping_var_list[List<ClawMappingVar> vars]:
mv=mapping_var { $vars.add($mv.mappingVar); }
| mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars]
;
mapping_option returns [ClawMapping mapping]
@init{
$mapping = new ClawMapping();
List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>();
List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>();
$mapping.setMappedVariables(listMapped);
$mapping.setMappingVariables(listMapping);
}
:
MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')'
;
mapping_option_list[List<ClawMapping> mappings]:
m=mapping_option { $mappings.add($m.mapping); }
| m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings]
;
define_option[ClawLanguage l]:
DEFINE DIMENSION id=IDENTIFIER '(' lower=range_id ':' upper=range_id ')'
{
ClawDimension cd = new ClawDimension($id.text, $lower.text, $upper.text);
$l.addDimension(cd);
}
;
/*----------------------------------------------------------------------------
* LEXER RULES
*----------------------------------------------------------------------------*/
// Start point
CLAW : 'claw';
// CLAW Directives
ARRAY_TRANS : 'array-transform';
ARRAY_TO_CALL : 'call';
DEFINE : 'define';
END : 'end';
KCACHE : 'kcache';
LOOPEXTRACT : 'loop-extract';
LOOPFUSION : 'loop-fusion';
LOOPHOIST : 'loop-hoist';
LOOPINTERCHANGE : 'loop-interchange';
PARALLELIZE : 'parallelize';
REMOVE : 'remove';
IGNORE : 'ignore';
VERBATIM : 'verbatim';
// CLAW Clauses
COLLAPSE : 'collapse';
DATA : 'data';
DIMENSION : 'dimension';
FORWARD : 'forward';
FUSION : 'fusion';
GROUP : 'group';
INDUCTION : 'induction';
INIT : 'init';
INTERCHANGE : 'interchange';
MAP : 'map';
OFFSET : 'offset';
OVER : 'over';
PARALLEL : 'parallel';
PRIVATE : 'private';
RANGE : 'range';
RESHAPE : 'reshape';
// Directive primitive clause
ACC : 'acc';
OMP : 'omp';
// Special elements
IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ;
NUMBER : (DIGIT)+ ;
fragment DIGIT : [0-9] ;
// Skip whitspaces
WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
|
Refactor some parser rule to have same naming convention
|
Refactor some parser rule to have same naming convention
|
ANTLR
|
bsd-2-clause
|
clementval/claw-compiler,clementval/claw-compiler
|
128458d6aeb67dce09ba08a7f2594f9b71ed4e17
|
src/grammars/org/antlr/intellij/plugin/parser/ANTLRv4Parser.g4
|
src/grammars/org/antlr/intellij/plugin/parser/ANTLRv4Parser.g4
|
/*
* [The "BSD license"]
* Copyright (c) 2013 Terence Parr
* Copyright (c) 2013 Sam Harwell
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** A grammar for ANTLR v4 written in ANTLR v4 */
parser grammar ANTLRv4Parser;
options { tokenVocab=ANTLRv4Lexer; superClass=org.antlr.intellij.plugin.adaptors.AdaptorParserBase; }
@header { package org.antlr.intellij.plugin.parser; }
// The main entry point for parsing a v4 grammar.
grammarSpec
: DOC_COMMENT?
grammarType id SEMI
prequelConstruct*
rules
modeSpec*
EOF
;
grammarType
: ( LEXER GRAMMAR
| PARSER GRAMMAR
| GRAMMAR
)
;
// This is the list of all constructs that can be declared before
// the set of rules that compose the grammar, and is invoked 0..n
// times by the grammarPrequel rule.
prequelConstruct
: optionsSpec
| delegateGrammars
| tokensSpec
| action
;
// A list of options that affect analysis and/or code generation
optionsSpec
: OPTIONS (option SEMI)* RBRACE
;
option
: id ASSIGN optionValue
;
optionValue
: id
| STRING_LITERAL
| INT
;
delegateGrammars
: IMPORT delegateGrammar (COMMA delegateGrammar)* SEMI
;
delegateGrammar
: id ASSIGN id
| id
;
tokensSpec
: TOKENS id (COMMA id)* COMMA? RBRACE
;
/** Match stuff like @parser::members {int i;} */
action
: AT (actionScopeName COLONCOLON)? id ACTION
;
/** Sometimes the scope names will collide with keywords; allow them as
* ids for action scopes.
*/
actionScopeName
: id
| LEXER
| PARSER
;
modeSpec
: MODE id SEMI ruleSpec+
;
rules
: ruleSpec*
;
ruleSpec
: parserRuleSpec
| lexerRule
;
parserRuleSpec
: DOC_COMMENT?
ruleModifiers? RULE_REF ARG_ACTION?
ruleReturns? throwsSpec? localsSpec?
rulePrequel*
COLON
ruleBlock
SEMI
exceptionGroup
;
exceptionGroup
: exceptionHandler* finallyClause?
;
exceptionHandler
: CATCH ARG_ACTION ACTION
;
finallyClause
: FINALLY ACTION
;
rulePrequel
: optionsSpec
| ruleAction
;
ruleReturns
: RETURNS ARG_ACTION
;
throwsSpec
: THROWS id (COMMA id)*
;
localsSpec
: LOCALS ARG_ACTION
;
/** Match stuff like @init {int i;} */
ruleAction
: AT id ACTION
;
ruleModifiers
: ruleModifier+
;
// An individual access modifier for a rule. The 'fragment' modifier
// is an internal indication for lexer rules that they do not match
// from the input but are like subroutines for other lexer rules to
// reuse for certain lexical patterns. The other modifiers are passed
// to the code generation templates and may be ignored by the template
// if they are of no use in that language.
ruleModifier
: PUBLIC
| PRIVATE
| PROTECTED
| FRAGMENT
;
ruleBlock
: ruleAltList
;
ruleAltList
: labeledAlt (OR labeledAlt)*
;
labeledAlt
: alternative (POUND id)?
;
lexerRule
: DOC_COMMENT? FRAGMENT?
TOKEN_REF COLON lexerRuleBlock SEMI
;
lexerRuleBlock
: lexerAltList
;
lexerAltList
: lexerAlt (OR lexerAlt)*
;
lexerAlt
: lexerElements? lexerCommands?
;
lexerElements
: lexerElement+
;
lexerElement
: labeledLexerElement ebnfSuffix?
| lexerAtom ebnfSuffix?
| lexerBlock ebnfSuffix?
| ACTION QUESTION? // actions only allowed at end of outer alt actually,
// but preds can be anywhere
;
labeledLexerElement
: id (ASSIGN|PLUS_ASSIGN)
( lexerAtom
| block
)
;
lexerBlock
: LPAREN lexerAltList RPAREN
;
// E.g., channel(HIDDEN), skip, more, mode(INSIDE), push(INSIDE), pop
lexerCommands
: RARROW lexerCommand (COMMA lexerCommand)*
;
lexerCommand
: lexerCommandName LPAREN lexerCommandExpr RPAREN
| lexerCommandName
;
lexerCommandName
: id
| MODE
;
lexerCommandExpr
: id
| INT
;
altList
: alternative (OR alternative)*
;
alternative
: elements
| // empty alt
;
elements
: element+
;
element
: labeledElement
( ebnfSuffix
|
)
| atom
( ebnfSuffix
|
)
| ebnf
| ACTION QUESTION? // SEMPRED is ACTION followed by QUESTION
;
labeledElement
: id (ASSIGN|PLUS_ASSIGN)
( atom
| block
)
;
ebnf: block blockSuffix?
;
blockSuffix
: ebnfSuffix // Standard EBNF
;
ebnfSuffix
: QUESTION QUESTION?
| STAR QUESTION?
| PLUS QUESTION?
;
lexerAtom
: range
| terminal
| RULE_REF
| notSet
| LEXER_CHAR_SET
| DOT elementOptions?
;
atom
: range // Range x..y - only valid in lexers
| terminal
| ruleref
| notSet
| DOT elementOptions?
;
notSet
: NOT setElement
| NOT blockSet
;
blockSet
: LPAREN setElement (OR setElement)* RPAREN
;
setElement
: TOKEN_REF
| STRING_LITERAL
| range
| LEXER_CHAR_SET
;
block
: LPAREN
( optionsSpec? ruleAction* COLON )?
altList
RPAREN
;
ruleref
: RULE_REF ARG_ACTION?
;
range
: STRING_LITERAL RANGE STRING_LITERAL
;
terminal
: TOKEN_REF elementOptions?
| STRING_LITERAL elementOptions?
;
// Terminals may be adorned with certain options when
// reference in the grammar: TOK<,,,>
elementOptions
: LT elementOption (COMMA elementOption)* GT
;
elementOption
: // This format indicates the default node option
id
| // This format indicates option assignment
id ASSIGN (id | STRING_LITERAL)
;
id : RULE_REF
| TOKEN_REF
;
|
/*
* [The "BSD license"]
* Copyright (c) 2013 Terence Parr
* Copyright (c) 2013 Sam Harwell
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** A grammar for ANTLR v4 written in ANTLR v4.
Build with
$ antlr4 -no-listener *.g4
*/
parser grammar ANTLRv4Parser;
options { tokenVocab=ANTLRv4Lexer; superClass=org.antlr.intellij.plugin.adaptors.AdaptorParserBase; }
@header { package org.antlr.intellij.plugin.parser; }
// The main entry point for parsing a v4 grammar.
grammarSpec
: DOC_COMMENT?
grammarType id SEMI
prequelConstruct*
rules
modeSpec*
EOF
;
grammarType
: ( LEXER GRAMMAR
| PARSER GRAMMAR
| GRAMMAR
)
;
// This is the list of all constructs that can be declared before
// the set of rules that compose the grammar, and is invoked 0..n
// times by the grammarPrequel rule.
prequelConstruct
: optionsSpec
| delegateGrammars
| tokensSpec
| action
;
// A list of options that affect analysis and/or code generation
optionsSpec
: OPTIONS (option SEMI)* RBRACE
;
option
: id ASSIGN optionValue
;
optionValue
: id
| STRING_LITERAL
| INT
;
delegateGrammars
: IMPORT delegateGrammar (COMMA delegateGrammar)* SEMI
;
delegateGrammar
: id ASSIGN id
| id
;
tokensSpec
: TOKENS id (COMMA id)* COMMA? RBRACE
;
/** Match stuff like @parser::members {int i;} */
action
: AT (actionScopeName COLONCOLON)? id ACTION
;
/** Sometimes the scope names will collide with keywords; allow them as
* ids for action scopes.
*/
actionScopeName
: id
| LEXER
| PARSER
;
modeSpec
: MODE id SEMI ruleSpec+
;
rules
: ruleSpec*
;
ruleSpec
: parserRuleSpec
| lexerRule
;
parserRuleSpec
: DOC_COMMENT?
ruleModifiers? RULE_REF ARG_ACTION?
ruleReturns? throwsSpec? localsSpec?
rulePrequel*
COLON
ruleBlock
SEMI
exceptionGroup
;
exceptionGroup
: exceptionHandler* finallyClause?
;
exceptionHandler
: CATCH ARG_ACTION ACTION
;
finallyClause
: FINALLY ACTION
;
rulePrequel
: optionsSpec
| ruleAction
;
ruleReturns
: RETURNS ARG_ACTION
;
throwsSpec
: THROWS id (COMMA id)*
;
localsSpec
: LOCALS ARG_ACTION
;
/** Match stuff like @init {int i;} */
ruleAction
: AT id ACTION
;
ruleModifiers
: ruleModifier+
;
// An individual access modifier for a rule. The 'fragment' modifier
// is an internal indication for lexer rules that they do not match
// from the input but are like subroutines for other lexer rules to
// reuse for certain lexical patterns. The other modifiers are passed
// to the code generation templates and may be ignored by the template
// if they are of no use in that language.
ruleModifier
: PUBLIC
| PRIVATE
| PROTECTED
| FRAGMENT
;
ruleBlock
: ruleAltList
;
ruleAltList
: labeledAlt (OR labeledAlt)*
;
labeledAlt
: alternative (POUND id)?
;
lexerRule
: DOC_COMMENT? FRAGMENT?
TOKEN_REF COLON lexerRuleBlock SEMI
;
lexerRuleBlock
: lexerAltList
;
lexerAltList
: lexerAlt (OR lexerAlt)*
;
lexerAlt
: lexerElements? lexerCommands?
;
lexerElements
: lexerElement+
;
lexerElement
: labeledLexerElement ebnfSuffix?
| lexerAtom ebnfSuffix?
| lexerBlock ebnfSuffix?
| ACTION QUESTION? // actions only allowed at end of outer alt actually,
// but preds can be anywhere
;
labeledLexerElement
: id (ASSIGN|PLUS_ASSIGN)
( lexerAtom
| block
)
;
lexerBlock
: LPAREN lexerAltList RPAREN
;
// E.g., channel(HIDDEN), skip, more, mode(INSIDE), push(INSIDE), pop
lexerCommands
: RARROW lexerCommand (COMMA lexerCommand)*
;
lexerCommand
: lexerCommandName LPAREN lexerCommandExpr RPAREN
| lexerCommandName
;
lexerCommandName
: id
| MODE
;
lexerCommandExpr
: id
| INT
;
altList
: alternative (OR alternative)*
;
alternative
: elements
| // empty alt
;
elements
: element+
;
element
: labeledElement
( ebnfSuffix
|
)
| atom
( ebnfSuffix
|
)
| ebnf
| ACTION QUESTION? // SEMPRED is ACTION followed by QUESTION
;
labeledElement
: id (ASSIGN|PLUS_ASSIGN)
( atom
| block
)
;
ebnf: block blockSuffix?
;
blockSuffix
: ebnfSuffix // Standard EBNF
;
ebnfSuffix
: QUESTION QUESTION?
| STAR QUESTION?
| PLUS QUESTION?
;
lexerAtom
: range
| terminal
| RULE_REF
| notSet
| LEXER_CHAR_SET
| DOT elementOptions?
;
atom
: range // Range x..y - only valid in lexers
| terminal
| ruleref
| notSet
| DOT elementOptions?
;
notSet
: NOT setElement
| NOT blockSet
;
blockSet
: LPAREN setElement (OR setElement)* RPAREN
;
setElement
: TOKEN_REF
| STRING_LITERAL
| range
| LEXER_CHAR_SET
;
block
: LPAREN
( optionsSpec? ruleAction* COLON )?
altList
RPAREN
;
ruleref
: RULE_REF ARG_ACTION?
;
range
: STRING_LITERAL RANGE STRING_LITERAL
;
terminal
: TOKEN_REF elementOptions?
| STRING_LITERAL elementOptions?
;
// Terminals may be adorned with certain options when
// reference in the grammar: TOK<,,,>
elementOptions
: LT elementOption (COMMA elementOption)* GT
;
elementOption
: // This format indicates the default node option
id
| // This format indicates option assignment
id ASSIGN (id | STRING_LITERAL)
;
id : RULE_REF
| TOKEN_REF
;
|
add comment
|
add comment
|
ANTLR
|
bsd-3-clause
|
parrt/intellij-plugin-v4,antlr/intellij-plugin-v4,consulo/consulo-antlr4,rojaster/intellij-plugin-v4,rojaster/intellij-plugin-v4,bjansen/intellij-plugin-v4,bjansen/intellij-plugin-v4,Maccimo/intellij-plugin-v4,parrt/intellij-plugin-v4,antlr/intellij-plugin-v4,Maccimo/intellij-plugin-v4,sharwell/intellij-plugin-v4
|
8c448d8980ed48a5b491caaa30e066126430dbad
|
kquery/KQuery.g4
|
kquery/KQuery.g4
|
/*
[The "BSD licence"]
Copyright (c) 2013 Sam Harwell
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Grammar for KLEE KQuery parsing.
// Ported to Antlr4 by Sumit Lahiri.
grammar KQuery;
kqueryExpression
: ktranslationUnit* EOF
;
ktranslationUnit
: arrayDeclaration
| queryCommand
;
queryCommand
: LeftParen Query evalExprList queryExpr RightParen
;
queryExpr
: expression
| expression evalExprList
| expression evalExprList evalArrayList
;
evalExprList
: LeftBracket expression* RightBracket
;
evalArrayList
: LeftBracket Identifier* RightBracket
;
arrayDeclaration
: Array arrName LeftBracket arrayElemsStub RightBracket
Colon domain Arrow rangeLimit Equal arrayInitializer
;
arrayElemsStub
: Constant
;
arrayInitializer
: Symbolic
| LeftBracket numberList RightBracket
;
expression
: Identifier
| Identifier Colon expression
| LeftParen WidthType number RightParen
| LeftParen arithmeticExpr WidthType expression expression RightParen
| LeftParen NOT LeftBracket WidthType RightBracket expression RightParen
| LeftParen bitwiseExpr WidthType expression expression RightParen
| LeftParen SHL WidthType expression expression RightParen
| LeftParen LSHR WidthType expression expression RightParen
| LeftParen ASHR WidthType expression expression RightParen
| LeftParen comparisonExpr WidthType expression expression RightParen
| LeftParen comparisonExpr expression expression RightParen
| LeftParen CONCAT WidthType expression expression RightParen
| LeftParen CONCAT expression expression RightParen
| LeftParen EXTRACT WidthType number expression RightParen
| LeftParen ZEXT WidthType expression RightParen
| LeftParen SEXT WidthType expression RightParen
| LeftParen READ WidthType expression version RightParen
| LeftParen READ WidthType expression RightParen
| LeftParen SELECT WidthType expression expression expression RightParen
| LeftParen NEGETION WidthType expression RightParen
| LeftParen NEGETION expression RightParen
| LeftParen READLSB WidthType expression version RightParen
| LeftParen READMSB WidthType expression version RightParen
| LeftParen READLSB WidthType expression RightParen
| LeftParen READMSB WidthType expression RightParen
| version
| number
;
version
: Identifier
| Identifier Colon expression
| LeftBracket updateList RightBracket ATR version
| LeftBracket RightBracket ATR version
;
updateList
: expression Equal expression COMMA updateList
| expression Equal expression
;
bitwiseExpr
: BITWISEAND
| BITWISEOR
| BITWISEXOR
| SHL
| LSHR
| ASHR
;
comparisonExpr
: EQ
| NEQ
| ULT
| UGT
| ULE
| UGE
| SLT
| SLE
| SGT
| SGE
;
arithmeticExpr
: ADD
| SUB
| MUL
| UDIV
| UREM
| SDIV
| SREM
;
domain : WidthType ;
rangeLimit : WidthType ;
arrName : Identifier ;
numberList
: number
| number numberList
;
number
: TrueMatch
| FalseMatch
| SignedConstant
| Constant
;
SignedConstant
: (PLUS | MINUS)Constant
;
Constant
: DIGIT+
| BinConstant
| OctConstant
| HexConstant
;
BinConstant
: BinId BIN_DIGIT+
;
OctConstant
: OctId OCTAL_DIGIT+
;
HexConstant
: HexId HEX_DIGIT+
;
FloatingPointType
: FP DIGIT ((.).*?)?
;
IntegerType
: INT DIGIT+
;
WidthType
: WIDTH DIGIT+
;
BinId : '0b';
OctId : '0o';
WIDTH : 'w';
HexId : '0x';
TrueMatch : 'true';
FalseMatch : 'false';
Query : 'query';
Array : 'array';
Symbolic : 'symbolic';
Colon : ':';
Arrow : '->';
Equal : '=';
COMMA : ',';
NOT : 'Not';
SHL : 'Shl';
LSHR : 'LShr';
ASHR : 'AShr';
CONCAT : 'Concat';
EXTRACT: 'Extract';
ZEXT: 'ZExt';
SEXT: 'SExt';
READ: 'Read';
SELECT: 'Select';
NEGETION: 'Neg';
READLSB: 'ReadLSB';
READMSB: 'ReadMSB';
PLUS : '+';
MINUS : '-';
INT : 'i';
ATR : '@';
FP : 'fp';
BITWISEAND : 'And';
BITWISEOR : 'Or';
BITWISEXOR : 'Xor';
EQ : 'Eq';
NEQ : 'Ne' ;
ULT : 'Ult' ;
ULE : 'Ule' ;
UGT : 'Ugt' ;
UGE : 'Uge' ;
SLT : 'Slt' ;
SLE : 'Sle' ;
SGT : 'Sgt' ;
SGE : 'Sge' ;
ADD : 'Add' ;
SUB : 'Sub' ;
MUL : 'Mul' ;
UDIV : 'UDiv';
UREM : 'URem';
SDIV : 'SDiv';
SREM : 'SRem';
fragment
DIGIT
: ('0'..'9')
;
BIN_DIGIT
: ('0' | '1' | '_')
;
OCTAL_DIGIT
: ('0'..'7' | '_')
;
HEX_DIGIT
: ('0'..'9'|'a'..'f'|'A'..'F'|'_')
;
Identifier
: ('a'..'z' | 'A'..'Z' | '_')('a'..'z' | 'A'..'Z' | '_' | '0'..'9' | '.' )*
;
Whitespace
: [ \t]+ -> skip
;
Newline
: ( '\r' '\n'?
| '\n'
)
-> skip
;
BlockComment
: '/*' .*? '*/' -> skip
;
LineComment
: '#' ~[\r\n]* -> skip
;
LeftParen : '(';
RightParen : ')';
LeftBracket : '[';
RightBracket : ']';
LeftBrace : '{';
RightBrace : '}';
|
/*
[The "BSD licence"]
Copyright (c) 2013 Sumit Lahiri
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Grammar for KLEE KQuery parsing. (A bit more verbose with richer parsing)
// Ported to Antlr4 by Sumit Lahiri.
grammar KQuery;
kqueryExpression
: ktranslationUnit* EOF
;
ktranslationUnit
: arrayDeclaration
| queryCommand
;
queryCommand
: LeftParen Query evalExprList queryExpr RightParen
;
queryExpr
: expression
| expression evalExprList
| expression evalExprList evalArrayList
;
evalExprList
: LeftBracket expression* RightBracket
;
evalArrayList
: LeftBracket Identifier* RightBracket
;
arrayDeclaration
: Array arrName LeftBracket numArrayElements RightBracket
Colon domain Arrow rangeLimit Equal arrayInitializer
;
numArrayElements
: Constant
;
arrayInitializer
: Symbolic
| LeftBracket numberList RightBracket
;
expression
: varName
| namedConstant Colon fullyQualifiedExpression
| LeftParen widthOrSizeExpr number RightParen
| LeftParen arithmeticExpr widthOrSizeExpr leftExpr rightExpr RightParen
| LeftParen notExpr LeftBracket widthOrSizeExpr RightBracket expression RightParen
| LeftParen bitwiseExpr widthOrSizeExpr leftExpr rightExpr RightParen
| LeftParen comparisonExpr widthOrSizeExpr leftExpr rightExpr RightParen
| LeftParen comparisonExpr leftExpr rightExpr RightParen
| LeftParen concatExpr widthOrSizeExpr leftExpr rightExpr RightParen
| LeftParen concatExpr leftExpr rightExpr RightParen
| LeftParen arrExtractExpr widthOrSizeExpr number expression RightParen
| LeftParen bitExtractExpr widthOrSizeExpr expression RightParen
| LeftParen genericBitRead widthOrSizeExpr expression version RightParen
| LeftParen selectExpr widthOrSizeExpr leftExpr rightExpr expression RightParen
| LeftParen exprNegation widthOrSizeExpr expression RightParen
| LeftParen exprNegation expression RightParen
| LeftParen genericBitRead widthOrSizeExpr expression RightParen
| version
| number
;
genericBitRead
: READ
| READLSB
| READMSB
;
bitExtractExpr
: ZEXT
| SEXT
;
version
: varName
| namedConstant Colon fullyQualifiedExpression
| LeftBracket updateList RightBracket ATR version
| LeftBracket RightBracket ATR version
;
fullyQualifiedExpression
: expression
;
notExpr
: NOT
;
concatExpr
: CONCAT
;
exprNegation
: NEGETION
;
selectExpr
: SELECT
;
arrExtractExpr
: EXTRACT
;
varName
: Identifier
;
leftExpr
: expression
;
rightExpr
: expression
;
namedConstant
: Identifier
;
updateList
: expression Equal expression COMMA updateList
| expression Equal expression
;
bitwiseExpr
: BITWISEAND
| BITWISEOR
| BITWISEXOR
| SHL
| LSHR
| ASHR
;
comparisonExpr
: EQ
| NEQ
| ULT
| UGT
| ULE
| UGE
| SLT
| SLE
| SGT
| SGE
;
arithmeticExpr
: ADD
| SUB
| MUL
| UDIV
| UREM
| SDIV
| SREM
;
domain : widthOrSizeExpr ;
rangeLimit : widthOrSizeExpr ;
arrName : Identifier ;
numberList
: number
| number numberList
;
number
: boolnum
| signedConstant
| constant
;
constant: Constant;
boolnum: Boolean;
signedConstant: SignedConstant;
Boolean
: TrueMatch
| FalseMatch
;
SignedConstant
: (PLUS | MINUS)Constant
;
Constant
: DIGIT+
| BinConstant
| OctConstant
| HexConstant
;
BinConstant
: BinId BIN_DIGIT+
;
OctConstant
: OctId OCTAL_DIGIT+
;
HexConstant
: HexId HEX_DIGIT+
;
FloatingPointType
: FP DIGIT ((.).*?)?
;
IntegerType
: INT DIGIT+
;
widthOrSizeExpr
: WidthType
;
WidthType
: WIDTH DIGIT+
;
BinId : '0b';
OctId : '0o';
WIDTH : 'w';
HexId : '0x';
TrueMatch : 'true';
FalseMatch : 'false';
Query : 'query';
Array : 'array';
Symbolic : 'symbolic';
Colon : ':';
Arrow : '->';
Equal : '=';
COMMA : ',';
NOT : 'Not';
SHL : 'Shl';
LSHR : 'LShr';
ASHR : 'AShr';
CONCAT : 'Concat';
EXTRACT: 'Extract';
ZEXT: 'ZExt';
SEXT: 'SExt';
READ: 'Read';
SELECT: 'Select';
NEGETION: 'Neg';
READLSB: 'ReadLSB';
READMSB: 'ReadMSB';
PLUS : '+';
MINUS : '-';
INT : 'i';
ATR : '@';
FP : 'fp';
BITWISEAND : 'And';
BITWISEOR : 'Or';
BITWISEXOR : 'Xor';
EQ : 'Eq';
NEQ : 'Ne' ;
ULT : 'Ult' ;
ULE : 'Ule' ;
UGT : 'Ugt' ;
UGE : 'Uge' ;
SLT : 'Slt' ;
SLE : 'Sle' ;
SGT : 'Sgt' ;
SGE : 'Sge' ;
ADD : 'Add' ;
SUB : 'Sub' ;
MUL : 'Mul' ;
UDIV : 'UDiv';
UREM : 'URem';
SDIV : 'SDiv';
SREM : 'SRem';
fragment
DIGIT
: ('0'..'9')
;
fragment
BIN_DIGIT
: ('0' | '1' | '_')
;
fragment
OCTAL_DIGIT
: ('0'..'7' | '_')
;
fragment
HEX_DIGIT
: ('0'..'9'|'a'..'f'|'A'..'F'|'_')
;
Identifier
: ('a'..'z' | 'A'..'Z' | '_')('a'..'z' | 'A'..'Z' | '_' | '0'..'9' | '.' )*
;
Whitespace
: [ \t]+ -> skip
;
Newline
: ( '\r' '\n'?
| '\n'
)
-> skip
;
BlockComment
: '/*' .*? '*/' -> skip
;
LineComment
: '#' ~[\r\n]* -> skip
;
LeftParen : '(';
RightParen : ')';
LeftBracket : '[';
RightBracket : ']';
LeftBrace : '{';
RightBrace : '}';
|
Update KQuery.g4
|
Update KQuery.g4
|
ANTLR
|
mit
|
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
|
4b2e3499d68396d386721034df9d2c70810152ee
|
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
|
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
|
lexer grammar CreoleTokens;
options { superClass=ContextSensitiveLexer; }
@members {
// We keep track of whether we're in bold or not with this state. It's not
// ideal, but as the start/end formatting tokens are all the same, this is
// probably the best we can do (short of going crazy with lexer modes).
Formatting bold;
Formatting italic;
Formatting strike;
public java.util.List<Formatting> setupFormatting() {
bold = new Formatting("**", BSt, BEnd);
italic = new Formatting("//", ISt, IEnd);
strike = new Formatting("--", SSt, SEnd);
return com.google.common.collect.ImmutableList.of(bold, italic, strike);
}
public boolean inHeader = false;
public boolean start = false;
public int listLevel = 0;
boolean intr = false;
// Start matching a list item: this updates the list level (allowing deeper
// list tokens to be matched), and breaks out of any formatting we may have
// going on - which may trigger parser error-correction.
public void doList(int level) {
listLevel = level;
seek(-1);
resetFormatting();
String next1 = get(0);
String next2 = get(1);
start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#"));
}
// When we think we've matched a URL, seek back through it until we have
// something more reasonable looking.
public void doUrl() {
String url = getText();
String last = url.substring(url.length()-1);
String next = next(1);
String badEnds = inHeader ? "[\\.,)\"';:\\\\=-]" : "[\\.,)\"';:\\\\-]";
while((last + next).equals("//") || last.matches(badEnds)) {
seek(-1);
url = url.substring(0, url.length() - 1);
last = url.substring(url.length()-1);
next = next(1);
// Break out if we no longer have a URL
if(url.endsWith(":/") || url.endsWith("mailto:")) {
setType(Any);
break;
}
}
setText(url);
}
// Reset all special lexer state.
public void breakOut() {
resetFormatting();
listLevel = 0;
inHeader = false;
intr = false;
}
// Determine which tokens can, at this stage, break out of any inline
// formatting.
public java.util.List<String> thisKillsTheFormatting() {
java.util.List<String> ends = new java.util.ArrayList<String>();
if(inHeader || intr) {
ends.add("\n");
ends.add("\r\n");
}
else {
ends.add("\n\n");
ends.add("\r\n\r\n");
}
if(intr) {
ends.add("|");
}
if(listLevel > 0) {
// \L (when at the start) matches the start of a line.
ends.add("\\L*");
ends.add("\\L#");
}
return ends;
}
// Handle a link target or title ending with a ']' or '}'.
public void doLinkEnd() {
String txt = getText().trim();
int len = txt.length();
if(len > 2) {
String lastButTwo = txt.substring(len - 3, len - 2);
if(lastButTwo.equals("]") || lastButTwo.equals("}")) {
txt = txt.substring(0, len - 2);
seek(-2);
}
}
setText(txt);
}
}
/* ***** Headings ***** */
HSt : LINE ('=' | '==' | '===' | '====' | '=====' | '======') ~'=' {inHeader=true; seek(-1);} ;
HEnd : WS? '='* WS? (LineBreak | ParBreak) {inHeader}? {breakOut();} ;
/* ***** Lists ***** */
// Lists are messy, as in the parser. One notable trait is that sublists can
// start with any combination of *s and #s, which is perhaps too flexible, but
// it works (and was easy to specify). It means we can do things like this:
// * Level 1 Unordered
// *# Sublist which is ordered
// *#* Sublist which is unordered
// #** Item of same unordered sublist
// ##* Item of same unordered sublist
U1 : START U {doList(1);} ;
U2 : START L U {listLevel >= 1}? {doList(2);} ;
U3 : START L L U {listLevel >= 2}? {doList(3);} ;
U4 : START L L L U {listLevel >= 3}? {doList(4);} ;
U5 : START L L L L U {listLevel >= 4}? {doList(5);} ;
U6 : START L L L L L U {listLevel >= 5}? {doList(6);} ;
U7 : START L L L L L L U {listLevel >= 6}? {doList(7);} ;
U8 : START L L L L L L L U {listLevel >= 7}? {doList(8);} ;
U9 : START L L L L L L L L U {listLevel >= 8}? {doList(9);} ;
U10 : START L L L L L L L L L U {listLevel >= 9}? {doList(10);} ;
O1 : START O {doList(1);} ;
O2 : START L O {listLevel >= 1}? {doList(2);} ;
O3 : START L L O {listLevel >= 2}? {doList(3);} ;
O4 : START L L L O {listLevel >= 3}? {doList(4);} ;
O5 : START L L L L O {listLevel >= 4}? {doList(5);} ;
O6 : START L L L L L O {listLevel >= 5}? {doList(6);} ;
O7 : START L L L L L L O {listLevel >= 6}? {doList(7);} ;
O8 : START L L L L L L L O {listLevel >= 7}? {doList(8);} ;
O9 : START L L L L L L L L O {listLevel >= 8}? {doList(9);} ;
O10 : START L L L L L L L L L O {listLevel >= 9}? {doList(10);} ;
fragment U : '*' ~('*'|'\r'|'\n') ;
fragment O : '#' ~('#'|'\r'|'\n') ;
fragment L : '*' | '#' ;
/* ***** 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 ***** */
Bold : '**' {toggleFormatting(bold, Any);} ;
Italic : '//' {prior() == null || (prior() != ':' || !Character.isLetterOrDigit(priorprior()))}? {toggleFormatting(italic, Any);} ;
Strike : '--' {toggleFormatting(strike, Any);} ;
NoWiki : '{{{' -> mode(NOWIKI_INLINE) ;
StartCpp : '[<c++>]' -> mode(CPP_INLINE) ;
StartHtml : '[<html>]' -> mode(HTML_INLINE) ;
StartJava : '[<java>]' -> mode(JAVA_INLINE) ;
StartXhtml : '[<xhtml>]' -> mode(XHTML_INLINE) ;
StartXml : '[<xml>]' -> mode(XML_INLINE) ;
/* ***** Links ***** */
LiSt : '[[' -> mode(LINK) ;
ImSt : '{{' -> mode(LINK) ;
AnSt : '[[#' -> mode(ANCHOR) ;
/* ***** Breaks ***** */
InlineBrk : '\\\\' ;
ParBreak : LineBreak WS? LineBreak+ {breakOut();} ;
LineBreak : '\r'? '\n' ;
/* ***** Links ***** */
RawUrl : PROTOCOL (~(' '|'\t'|'\r'|'\n'|'|'|'['|']'|'"'|'/')+ '/'?)+ {doUrl();} ;
fragment PROTOCOL : ('http' 's'? | 'file' | 'ftp') '://' | 'file:/' | 'mailto:' ;
Attachment : UPPER CAMEL '.' ALNUM+ ;
WikiWords : (UPPER (ABBR | CAMEL) | INTERWIKI ALNUM+) NOTALNUM {prior() == null || prior() != '.' && prior() != ':' && !Character.isLetterOrDigit(prior()) && !(last() == '.' && Character.isLetter(next()))}? {seek(-1);} ;
fragment INTERWIKI : ALPHA ALNUM+ ':' ;
fragment ABBR : UPPER UPPER+ ;
fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ;
/* ***** Macros ***** */
MacroSt : '<<' -> mode(MACRO) ;
/* ***** Quotes ***** */
BlockquoteSt : '[<blockquote>]' ;
BlockquoteEnd : '[</blockquote>]' ;
/* ***** Miscellaneous ***** */
Any : ALNUM+ | . ;
WS : (' '|'\t')+ ;
// Skip empty links like [[]] and {{}}. These are commonly used to break up WikiWords.
EmptyLink : ('[[' WS? ']]' | '{{' WS? '}}' |'[[' WS? '|' WS? ']]' | '{{' WS? '|' WS? '}}') -> skip ;
fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ;
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') ;
// 'START' matches something which is start-of-line-like. Currently that's only
// handled by entering a new list level, but it could in principle be more
// general, replacing the use of 'LINE' entirely.
fragment START : {start}? | LINE ;
fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*;
/* ***** Contextual stuff ***** */
mode LINK;
LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
Sep : ' '* '|'+ ' '* -> mode(LINK_END);
InLink : (~('|'|'\r'|'\n'|']'|'}') | (']' ~']' | '}' ~'}'))+ {doLinkEnd();} ;
mode LINK_END;
InLinkEnd : (~('\r'|'\n'|']'|'}') | (']' ~']' | '}' ~'}'))+ {doLinkEnd();} ;
LiEnd2 : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
ImEnd2 : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
mode ANCHOR;
InAnchor : ~('#'|']')+ ;
AnEnd : ']]' -> mode(DEFAULT_MODE);
mode MACRO;
MacroName : ~(':'|'>')+ ;
MacroEndNoArgs : '>>' -> mode(DEFAULT_MODE) ;
MacroSep : ':' -> mode(MACRO_ARGS) ;
mode MACRO_ARGS;
MacroArgs : . -> more ;
MacroEnd : '>>' -> mode(DEFAULT_MODE) ;
// ***** NoWiki
mode NOWIKI_INLINE;
fragment INLINE : ~('\r'|'\n') ;
fragment BLOCK : . ;
fragment TOBLOCK : ('\r'|'\n') ;
NoWikiInline : INLINE -> more ;
NoWikiToBlock : TOBLOCK -> mode(NOWIKI_BLOCK), more ;
EndNoWikiInline : '}}}' ~'}' {seek(-1);} -> mode(DEFAULT_MODE) ;
mode NOWIKI_BLOCK;
NoWikiAny : BLOCK -> more ;
EndNoWikiBlock : (~' ' '}}}' | ' }}}' '\r'? '\n' {seek(-1);}) -> mode(DEFAULT_MODE) ;
// ***** C++
mode CPP_INLINE;
CppInline : INLINE -> more ;
CppToBlock : TOBLOCK -> mode(CPP_BLOCK), more ;
EndCppInline : '[</c++>]' -> mode(DEFAULT_MODE) ;
mode CPP_BLOCK;
CppAny : BLOCK -> more ;
EndCppBlock : ~' ' '[</c++>]' -> mode(DEFAULT_MODE) ;
// ***** HTML
mode HTML_INLINE;
HtmlInline : INLINE -> more ;
HtmlToBlock : TOBLOCK -> mode(HTML_BLOCK), more ;
EndHtmlInline : '[</html>]'-> mode(DEFAULT_MODE) ;
mode HTML_BLOCK;
HtmlAny : BLOCK -> more ;
EndHtmlBlock : ~' ' '[</html>]' -> mode(DEFAULT_MODE) ;
// ***** Java
mode JAVA_INLINE;
JavaInline : INLINE -> more ;
JavaToBlock : TOBLOCK -> mode(JAVA_BLOCK), more ;
EndJavaInline : '[</java>]'-> mode(DEFAULT_MODE) ;
mode JAVA_BLOCK;
JavaAny : BLOCK -> more ;
EndJavaBlock : ~' ' '[</java>]' -> mode(DEFAULT_MODE) ;
// ***** XHTML
mode XHTML_INLINE;
XhtmlInline : INLINE -> more ;
XhtmlToBlock : TOBLOCK -> mode(XHTML_BLOCK), more ;
EndXhtmlInline : '[</xhtml>]' -> mode(DEFAULT_MODE) ;
mode XHTML_BLOCK;
XhtmlAny : BLOCK -> more ;
EndXhtmlBlock : ~' ' '[</xhtml>]' -> mode(DEFAULT_MODE) ;
// ***** XML
mode XML_INLINE;
XmlInline : INLINE -> more ;
XmlToBlock : TOBLOCK -> mode(XML_BLOCK), more ;
EndXmlInline : '[</xml>]' -> mode(DEFAULT_MODE) ;
mode XML_BLOCK;
XmlAny : BLOCK -> more ;
EndXmlBlock : ~' ' '[</xml>]' -> mode(DEFAULT_MODE) ;
// Helper token types, not directly matched, but seta s the type of other tokens.
mode HELPERS;
BSt : ;
ISt : ;
SSt : ;
BEnd : ;
IEnd : ;
SEnd : ;
|
lexer grammar CreoleTokens;
options { superClass=ContextSensitiveLexer; }
@members {
// We keep track of whether we're in bold or not with this state. It's not
// ideal, but as the start/end formatting tokens are all the same, this is
// probably the best we can do (short of going crazy with lexer modes).
Formatting bold;
Formatting italic;
Formatting strike;
public java.util.List<Formatting> setupFormatting() {
bold = new Formatting("**", BSt, BEnd);
italic = new Formatting("//", ISt, IEnd);
strike = new Formatting("--", SSt, SEnd);
return com.google.common.collect.ImmutableList.of(bold, italic, strike);
}
public boolean inHeader = false;
public boolean start = false;
public int listLevel = 0;
boolean intr = false;
// Start matching a list item: this updates the list level (allowing deeper
// list tokens to be matched), and breaks out of any formatting we may have
// going on - which may trigger parser error-correction.
public void doList(int level) {
listLevel = level;
seek(-1);
resetFormatting();
String next1 = get(0);
String next2 = get(1);
start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#"));
}
// When we think we've matched a URL, seek back through it until we have
// something more reasonable looking.
public void doUrl() {
String url = getText();
String last = url.substring(url.length()-1);
String next = next(1);
String badEnds = inHeader ? "[\\.,)\"';:\\\\=-]" : "[\\.,)\"';:\\\\-]";
while((last + next).equals("//") || last.matches(badEnds)) {
seek(-1);
url = url.substring(0, url.length() - 1);
last = url.substring(url.length()-1);
next = next(1);
// Break out if we no longer have a URL
if(url.endsWith(":/") || url.endsWith("mailto:")) {
setType(Any);
break;
}
}
setText(url);
}
// Reset all special lexer state.
public void breakOut() {
resetFormatting();
listLevel = 0;
inHeader = false;
intr = false;
}
// Determine which tokens can, at this stage, break out of any inline
// formatting.
public java.util.List<String> thisKillsTheFormatting() {
java.util.List<String> ends = new java.util.ArrayList<String>();
if(inHeader || intr) {
ends.add("\n");
ends.add("\r\n");
}
else {
ends.add("\n\n");
ends.add("\r\n\r\n");
}
if(intr) {
ends.add("|");
}
if(listLevel > 0) {
// \L (when at the start) matches the start of a line.
ends.add("\\L*");
ends.add("\\L#");
}
return ends;
}
// Handle a link target or title ending with a ']' or '}'.
public void doLinkEnd() {
String txt = getText().trim();
int len = txt.length();
if(len > 2) {
String lastButTwo = txt.substring(len - 3, len - 2);
if(lastButTwo.equals("]") || lastButTwo.equals("}")) {
txt = txt.substring(0, len - 2);
seek(-2);
}
}
setText(txt);
}
}
/* ***** Headings ***** */
HSt : LINE ('=' | '==' | '===' | '====' | '=====' | '======') ~'=' {inHeader=true; seek(-1);} ;
HEnd : WS? '='* WS? (LineBreak | ParBreak) {inHeader}? {breakOut();} ;
/* ***** Lists ***** */
// Lists are messy, as in the parser. One notable trait is that sublists can
// start with any combination of *s and #s, which is perhaps too flexible, but
// it works (and was easy to specify). It means we can do things like this:
// * Level 1 Unordered
// *# Sublist which is ordered
// *#* Sublist which is unordered
// #** Item of same unordered sublist
// ##* Item of same unordered sublist
U1 : START U {doList(1);} ;
U2 : START L U {listLevel >= 1}? {doList(2);} ;
U3 : START L L U {listLevel >= 2}? {doList(3);} ;
U4 : START L L L U {listLevel >= 3}? {doList(4);} ;
U5 : START L L L L U {listLevel >= 4}? {doList(5);} ;
U6 : START L L L L L U {listLevel >= 5}? {doList(6);} ;
U7 : START L L L L L L U {listLevel >= 6}? {doList(7);} ;
U8 : START L L L L L L L U {listLevel >= 7}? {doList(8);} ;
U9 : START L L L L L L L L U {listLevel >= 8}? {doList(9);} ;
U10 : START L L L L L L L L L U {listLevel >= 9}? {doList(10);} ;
O1 : START O {doList(1);} ;
O2 : START L O {listLevel >= 1}? {doList(2);} ;
O3 : START L L O {listLevel >= 2}? {doList(3);} ;
O4 : START L L L O {listLevel >= 3}? {doList(4);} ;
O5 : START L L L L O {listLevel >= 4}? {doList(5);} ;
O6 : START L L L L L O {listLevel >= 5}? {doList(6);} ;
O7 : START L L L L L L O {listLevel >= 6}? {doList(7);} ;
O8 : START L L L L L L L O {listLevel >= 7}? {doList(8);} ;
O9 : START L L L L L L L L O {listLevel >= 8}? {doList(9);} ;
O10 : START L L L L L L L L L O {listLevel >= 9}? {doList(10);} ;
fragment U : '*' ~('*'|'\r'|'\n') ;
fragment O : '#' ~('#'|'\r'|'\n') ;
fragment L : '*' | '#' ;
/* ***** 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 ***** */
Bold : '**' {toggleFormatting(bold, Any);} ;
Italic : '//' {prior() == null || (prior() != ':' || !Character.isLetterOrDigit(priorprior()))}? {toggleFormatting(italic, Any);} ;
Strike : '--' {toggleFormatting(strike, Any);} ;
NoWiki : '{{{' -> mode(NOWIKI_INLINE) ;
StartCpp : '[<c++>]' -> mode(CPP_INLINE) ;
StartHtml : '[<html>]' -> mode(HTML_INLINE) ;
StartJava : '[<java>]' -> mode(JAVA_INLINE) ;
StartXhtml : '[<xhtml>]' -> mode(XHTML_INLINE) ;
StartXml : '[<xml>]' -> mode(XML_INLINE) ;
/* ***** Links ***** */
LiSt : '[[' -> mode(LINK) ;
ImSt : '{{' -> mode(LINK) ;
AnSt : '[[#' -> mode(ANCHOR) ;
/* ***** Breaks ***** */
InlineBrk : '\\\\' ;
ParBreak : LineBreak WS? LineBreak+ {breakOut();} ;
LineBreak : '\r'? '\n' ;
/* ***** Links ***** */
RawUrl : PROTOCOL (~(' '|'\t'|'\r'|'\n'|'|'|'['|']'|'"'|'/')+ '/'?)+ {doUrl();} ;
fragment PROTOCOL : ('http' 's'? | 'file' | 'ftp') '://' | 'file:/' | 'mailto:' ;
Attachment : UPPER CAMEL '.' ALNUM+ ;
WikiWords : (UPPER (ABBR | CAMEL) REVISION? | INTERWIKI ALNUM+) NOTALNUM {prior() == null || prior() != '.' && prior() != ':' && !Character.isLetterOrDigit(prior()) && !(last() == '.' && Character.isLetter(next()))}? {seek(-1);} ;
fragment INTERWIKI : ALPHA ALNUM+ ':' ;
fragment ABBR : UPPER UPPER+ ;
fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ;
fragment REVISION : '?revision=' DIGIT+ ;
/* ***** Macros ***** */
MacroSt : '<<' -> mode(MACRO) ;
/* ***** Quotes ***** */
BlockquoteSt : '[<blockquote>]' ;
BlockquoteEnd : '[</blockquote>]' ;
/* ***** Miscellaneous ***** */
Any : ALNUM+ | . ;
WS : (' '|'\t')+ ;
// Skip empty links like [[]] and {{}}. These are commonly used to break up WikiWords.
EmptyLink : ('[[' WS? ']]' | '{{' WS? '}}' |'[[' WS? '|' WS? ']]' | '{{' WS? '|' WS? '}}') -> skip ;
fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ;
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') ;
// 'START' matches something which is start-of-line-like. Currently that's only
// handled by entering a new list level, but it could in principle be more
// general, replacing the use of 'LINE' entirely.
fragment START : {start}? | LINE ;
fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*;
/* ***** Contextual stuff ***** */
mode LINK;
LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
Sep : ' '* '|'+ ' '* -> mode(LINK_END);
InLink : (~('|'|'\r'|'\n'|']'|'}') | (']' ~']' | '}' ~'}'))+ {doLinkEnd();} ;
mode LINK_END;
InLinkEnd : (~('\r'|'\n'|']'|'}') | (']' ~']' | '}' ~'}'))+ {doLinkEnd();} ;
LiEnd2 : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
ImEnd2 : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ;
mode ANCHOR;
InAnchor : ~('#'|']')+ ;
AnEnd : ']]' -> mode(DEFAULT_MODE);
mode MACRO;
MacroName : ~(':'|'>')+ ;
MacroEndNoArgs : '>>' -> mode(DEFAULT_MODE) ;
MacroSep : ':' -> mode(MACRO_ARGS) ;
mode MACRO_ARGS;
MacroArgs : . -> more ;
MacroEnd : '>>' -> mode(DEFAULT_MODE) ;
// ***** NoWiki
mode NOWIKI_INLINE;
fragment INLINE : ~('\r'|'\n') ;
fragment BLOCK : . ;
fragment TOBLOCK : ('\r'|'\n') ;
NoWikiInline : INLINE -> more ;
NoWikiToBlock : TOBLOCK -> mode(NOWIKI_BLOCK), more ;
EndNoWikiInline : '}}}' ~'}' {seek(-1);} -> mode(DEFAULT_MODE) ;
mode NOWIKI_BLOCK;
NoWikiAny : BLOCK -> more ;
EndNoWikiBlock : (~' ' '}}}' | ' }}}' '\r'? '\n' {seek(-1);}) -> mode(DEFAULT_MODE) ;
// ***** C++
mode CPP_INLINE;
CppInline : INLINE -> more ;
CppToBlock : TOBLOCK -> mode(CPP_BLOCK), more ;
EndCppInline : '[</c++>]' -> mode(DEFAULT_MODE) ;
mode CPP_BLOCK;
CppAny : BLOCK -> more ;
EndCppBlock : ~' ' '[</c++>]' -> mode(DEFAULT_MODE) ;
// ***** HTML
mode HTML_INLINE;
HtmlInline : INLINE -> more ;
HtmlToBlock : TOBLOCK -> mode(HTML_BLOCK), more ;
EndHtmlInline : '[</html>]'-> mode(DEFAULT_MODE) ;
mode HTML_BLOCK;
HtmlAny : BLOCK -> more ;
EndHtmlBlock : ~' ' '[</html>]' -> mode(DEFAULT_MODE) ;
// ***** Java
mode JAVA_INLINE;
JavaInline : INLINE -> more ;
JavaToBlock : TOBLOCK -> mode(JAVA_BLOCK), more ;
EndJavaInline : '[</java>]'-> mode(DEFAULT_MODE) ;
mode JAVA_BLOCK;
JavaAny : BLOCK -> more ;
EndJavaBlock : ~' ' '[</java>]' -> mode(DEFAULT_MODE) ;
// ***** XHTML
mode XHTML_INLINE;
XhtmlInline : INLINE -> more ;
XhtmlToBlock : TOBLOCK -> mode(XHTML_BLOCK), more ;
EndXhtmlInline : '[</xhtml>]' -> mode(DEFAULT_MODE) ;
mode XHTML_BLOCK;
XhtmlAny : BLOCK -> more ;
EndXhtmlBlock : ~' ' '[</xhtml>]' -> mode(DEFAULT_MODE) ;
// ***** XML
mode XML_INLINE;
XmlInline : INLINE -> more ;
XmlToBlock : TOBLOCK -> mode(XML_BLOCK), more ;
EndXmlInline : '[</xml>]' -> mode(DEFAULT_MODE) ;
mode XML_BLOCK;
XmlAny : BLOCK -> more ;
EndXmlBlock : ~' ' '[</xml>]' -> mode(DEFAULT_MODE) ;
// Helper token types, not directly matched, but seta s the type of other tokens.
mode HELPERS;
BSt : ;
ISt : ;
SSt : ;
BEnd : ;
IEnd : ;
SEnd : ;
|
Allow the WikiWords token to include a revision
|
Allow the WikiWords token to include a revision
|
ANTLR
|
apache-2.0
|
CoreFiling/reviki,CoreFiling/reviki,strr/reviki,ashirley/reviki,strr/reviki,ashirley/reviki,CoreFiling/reviki,ashirley/reviki,CoreFiling/reviki,ashirley/reviki,ashirley/reviki,strr/reviki,strr/reviki,CoreFiling/reviki,strr/reviki
|
2a8c5d9cc123e8858e74932c073d6d7703591fed
|
omni-cx2x/src/cx2x/translator/language/parser/Claw.g4
|
omni-cx2x/src/cx2x/translator/language/parser/Claw.g4
|
/*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
/**
* ANTLR 4 Grammar file for the CLAW directive language.
*
* @author clementval
*/
grammar Claw;
@header
{
import cx2x.translator.common.ClawConstant;
import cx2x.translator.language.base.*;
import cx2x.translator.language.common.*;
import cx2x.translator.common.Utility;
}
/*----------------------------------------------------------------------------
* PARSER RULES
*----------------------------------------------------------------------------*/
/*
* Entry point for the analyzis of a CLAW directive.
* Return a CLawLanguage object with all needed information.
*/
analyze returns [ClawLanguage l]
@init{
$l = new ClawLanguage();
}
:
CLAW directive[$l] EOF
| CLAW VERBATIM // this directive accept anything after the verbatim
{ $l.setDirective(ClawDirective.VERBATIM); }
| CLAW ACC // this directive accept anything after the acc
{ $l.setDirective(ClawDirective.PRIMITIVE); }
| CLAW OMP // this directive accept anything after the omp
{ $l.setDirective(ClawDirective.PRIMITIVE); }
;
directive[ClawLanguage l]
@init{
List<ClawMapping> m = new ArrayList<>();
List<String> o = new ArrayList<>();
List<String> s = new ArrayList<>();
List<Integer> i = new ArrayList<>();
}
:
// loop-fusion directive
LOOP_FUSION group_clause_optional[$l] collapse_clause_optional[$l] EOF
{ $l.setDirective(ClawDirective.LOOP_FUSION); }
// loop-interchange directive
| LOOP_INTERCHANGE indexes_option[$l] parallel_clause_optional[$l] acc_optional[$l] EOF
{ $l.setDirective(ClawDirective.LOOP_INTERCHANGE); }
// loop-extract directive
| LOOP_EXTRACT range_option mapping_option_list[m] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF
{
$l.setDirective(ClawDirective.LOOP_EXTRACT);
$l.setRange($range_option.r);
$l.setMappings(m);
}
// remove directive
| REMOVE EOF
{ $l.setDirective(ClawDirective.REMOVE); }
| END REMOVE EOF
{
$l.setDirective(ClawDirective.REMOVE);
$l.setEndPragma();
}
// Kcache directive
| KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF
{
$l.setDirective(ClawDirective.KCACHE);
$l.setOffsets(i);
}
| KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF
{
$l.setDirective(ClawDirective.KCACHE);
$l.setOffsets(i);
$l.setInitClause();
}
// Array notation transformation directive
| ARRAY_TRANS induction_optional[$l] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF
{ $l.setDirective(ClawDirective.ARRAY_TRANSFORM); }
| END ARRAY_TRANS
{
$l.setDirective(ClawDirective.ARRAY_TRANSFORM);
$l.setEndPragma();
}
// loop-hoist directive
| LOOP_HOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF
{
$l.setHoistInductionVars(o);
$l.setDirective(ClawDirective.LOOP_HOIST);
}
| END LOOP_HOIST EOF
{
$l.setDirective(ClawDirective.LOOP_HOIST);
$l.setEndPragma();
}
// on the fly directive
| ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')'
{
$l.setDirective(ClawDirective.ARRAY_TO_CALL);
$l.setFctParams(o);
$l.setFctName($fct_name.text);
$l.setArrayName($array_name.text);
}
// parallelize directive
| define_option[$l]* PARALLELIZE data_over_clause[$l]* parallelize_clauses[$l]
{
$l.setDirective(ClawDirective.PARALLELIZE);
}
| PARALLELIZE FORWARD parallelize_clauses[$l]
{
$l.setDirective(ClawDirective.PARALLELIZE);
$l.setForwardClause();
}
| END PARALLELIZE
{
$l.setDirective(ClawDirective.PARALLELIZE);
$l.setEndPragma();
}
// ignore directive
| IGNORE
{
$l.setDirective(ClawDirective.IGNORE);
}
| END IGNORE
{
$l.setDirective(ClawDirective.IGNORE);
$l.setEndPragma();
}
;
// Comma-separated identifiers list
ids_list[List<String> ids]
:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids]
;
// Comma-separated identifiers or colon symbol list
ids_or_colon_list[List<String> ids]
:
i=IDENTIFIER { $ids.add($i.text); }
| ':' { $ids.add(":"); }
| i=IDENTIFIER { $ids.add($i.text); } ',' ids_or_colon_list[$ids]
| ':' { $ids.add(":"); } ',' ids_or_colon_list[$ids]
;
// data over clause used in parallelize directive
data_over_clause[ClawLanguage l]
@init{
List<String> overLst = new ArrayList<>();
List<String> dataLst = new ArrayList<>();
}
:
DATA '(' ids_list[dataLst] ')' OVER '(' ids_or_colon_list[overLst] ')'
{
$l.setOverDataClause(dataLst);
$l.setOverClause(overLst);
}
;
// group clause
group_clause_optional[ClawLanguage l]:
GROUP '(' group_name=IDENTIFIER ')'
{ $l.setGroupClause($group_name.text); }
| /* empty */
;
// collapse clause
collapse_clause_optional[ClawLanguage l]:
COLLAPSE '(' n=NUMBER ')'
{ $l.setCollapseClause($n.text); }
| /* empty */
;
// fusion clause
fusion_clause_optional[ClawLanguage l]:
FUSION group_clause_optional[$l] { $l.setFusionClause(); }
| /* empty */
;
// parallel clause
parallel_clause_optional[ClawLanguage l]:
PARALLEL { $l.setParallelClause(); }
| /* empty */
;
// acc clause
acc_optional[ClawLanguage l]
@init{
List<String> tempAcc = new ArrayList<>();
}
:
ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); }
| /* empty */
;
// interchange clause
interchange_optional[ClawLanguage l]:
INTERCHANGE indexes_option[$l]
{
$l.setInterchangeClause();
}
| /* empty */
;
// induction clause
induction_optional[ClawLanguage l]
@init{
List<String> temp = new ArrayList<>();
}
:
INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); }
| /* empty */
;
// data clause
data_clause[ClawLanguage l]
@init {
List<String> temp = new ArrayList<>();
}
:
DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); }
;
// private clause
private_optional[ClawLanguage l]:
PRIVATE { $l.setPrivateClause(); }
| /* empty */
;
// reshape clause
reshape_optional[ClawLanguage l]
@init{
List<ClawReshapeInfo> r = new ArrayList();
}
:
RESHAPE '(' reshape_list[r] ')'
{ $l.setReshapeClauseValues(r); }
| /* empty */
;
// reshape clause
reshape_element returns [ClawReshapeInfo i]
@init{
List<Integer> temp = new ArrayList();
}
:
array_name=IDENTIFIER '(' target_dim=NUMBER ')'
{ $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); }
| array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')'
{ $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); }
;
reshape_list[List<ClawReshapeInfo> r]:
info=reshape_element { $r.add($info.i); } ',' reshape_list[$r]
| info=reshape_element { $r.add($info.i); }
;
identifiers[List<String> ids]:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids]
;
identifiers_list[List<String> ids]:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids]
;
integers[List<Integer> ints]:
;
integers_list[List<Integer> ints]:
i=NUMBER { $ints.add(Integer.parseInt($i.text)); }
| i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints]
;
indexes_option[ClawLanguage l]
@init{
List<String> indexes = new ArrayList();
}
:
'(' ids_list[indexes] ')' { $l.setIndexes(indexes); }
| /* empty */
;
offset_list_optional[List<Integer> offsets]:
OFFSET '(' offset_list[$offsets] ')'
| /* empty */
;
offset_list[List<Integer> offsets]:
offset[$offsets]
| offset[$offsets] ',' offset_list[$offsets]
;
offset[List<Integer> offsets]:
n=NUMBER { $offsets.add(Integer.parseInt($n.text)); }
| '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); }
| '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); }
;
range_option returns [ClawRange r]
@init{
$r = new ClawRange();
}
:
RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')'
{
$r.setInductionVar($induction.text);
$r.setLowerBound($lower.text);
$r.setUpperBound($upper.text);
$r.setStep(ClawConstant.DEFAULT_STEP_VALUE);
}
| RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')'
{
$r.setInductionVar($induction.text);
$r.setLowerBound($lower.text);
$r.setUpperBound($upper.text);
$r.setStep($step.text);
}
;
range_id returns [String text]:
n=NUMBER { $text = $n.text; }
| i=IDENTIFIER { $text = $i.text; }
;
mapping_var returns [ClawMappingVar mappingVar]:
lhs=IDENTIFIER '/' rhs=IDENTIFIER
{
$mappingVar = new ClawMappingVar($lhs.text, $rhs.text);
}
| i=IDENTIFIER
{
$mappingVar = new ClawMappingVar($i.text, $i.text);
}
;
mapping_var_list[List<ClawMappingVar> vars]:
mv=mapping_var { $vars.add($mv.mappingVar); }
| mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars]
;
mapping_option returns [ClawMapping mapping]
@init{
$mapping = new ClawMapping();
List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>();
List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>();
$mapping.setMappedVariables(listMapped);
$mapping.setMappingVariables(listMapping);
}
:
MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')'
;
mapping_option_list[List<ClawMapping> mappings]:
m=mapping_option { $mappings.add($m.mapping); }
| m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings]
;
define_option[ClawLanguage l]:
DEFINE DIMENSION id=IDENTIFIER '(' lower=range_id ':' upper=range_id ')'
{
ClawDimension cd = new ClawDimension($id.text, $lower.text, $upper.text);
$l.addDimension(cd);
}
;
// Allow to switch order
parallelize_clauses[ClawLanguage l]:
copy_clause_optional[$l] update_clause_optional[$l]
| update_clause_optional[$l] copy_clause_optional[$l]
;
copy_clause_optional[ClawLanguage l]:
/* empty */
| COPY
{ $l.setCopyClauseValue(ClawDMD.BOTH); }
| COPY '(' IN ')'
{ $l.setCopyClauseValue(ClawDMD.IN); }
| COPY '(' OUT ')'
{ $l.setCopyClauseValue(ClawDMD.OUT); }
;
update_clause_optional[ClawLanguage l]:
/* empty */
| UPDATE
{ $l.setUpdateClauseValue(ClawDMD.BOTH); }
| UPDATE '(' IN ')'
{ $l.setUpdateClauseValue(ClawDMD.IN); }
| UPDATE '(' OUT ')'
{ $l.setUpdateClauseValue(ClawDMD.OUT); }
;
/*----------------------------------------------------------------------------
* LEXER RULES
*----------------------------------------------------------------------------*/
// Start point
CLAW : 'claw';
// CLAW Directives
ARRAY_TRANS : 'array-transform';
ARRAY_TO_CALL : 'call';
DEFINE : 'define';
END : 'end';
KCACHE : 'kcache';
LOOP_EXTRACT : 'loop-extract';
LOOP_FUSION : 'loop-fusion';
LOOP_HOIST : 'loop-hoist';
LOOP_INTERCHANGE : 'loop-interchange';
PARALLELIZE : 'parallelize';
REMOVE : 'remove';
IGNORE : 'ignore';
VERBATIM : 'verbatim';
// CLAW Clauses
COLLAPSE : 'collapse';
COPY : 'copy';
DATA : 'data';
DIMENSION : 'dimension';
FORWARD : 'forward';
FUSION : 'fusion';
GROUP : 'group';
INDUCTION : 'induction';
INIT : 'init';
INTERCHANGE : 'interchange';
MAP : 'map';
OFFSET : 'offset';
OVER : 'over';
PARALLEL : 'parallel';
PRIVATE : 'private';
RANGE : 'range';
RESHAPE : 'reshape';
UPDATE : 'update';
// data copy/update clause keywords
IN : 'in';
OUT : 'out';
// Directive primitive clause
ACC : 'acc';
OMP : 'omp';
// Special elements
IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ;
NUMBER : (DIGIT)+ ;
fragment DIGIT : [0-9] ;
// Skip whitspaces
WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
|
/*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
/**
* ANTLR 4 Grammar file for the CLAW directive language.
*
* @author clementval
*/
grammar Claw;
@header
{
import cx2x.translator.common.ClawConstant;
import cx2x.translator.language.base.*;
import cx2x.translator.language.common.*;
import cx2x.translator.language.helper.target.Target;
import cx2x.translator.common.Utility;
}
/*----------------------------------------------------------------------------
* PARSER RULES
*----------------------------------------------------------------------------*/
/*
* Entry point for the analyzis of a CLAW directive.
* Return a CLawLanguage object with all needed information.
*/
analyze returns [ClawLanguage l]
@init{
$l = new ClawLanguage();
}
:
CLAW directive[$l] EOF
| CLAW VERBATIM // this directive accept anything after the verbatim
{ $l.setDirective(ClawDirective.VERBATIM); }
| CLAW ACC // this directive accept anything after the acc
{ $l.setDirective(ClawDirective.PRIMITIVE); }
| CLAW OMP // this directive accept anything after the omp
{ $l.setDirective(ClawDirective.PRIMITIVE); }
;
directive[ClawLanguage l]
@init{
List<ClawMapping> m = new ArrayList<>();
List<String> o = new ArrayList<>();
List<String> s = new ArrayList<>();
List<Integer> i = new ArrayList<>();
}
:
// loop-fusion directive
LOOP_FUSION loop_fusion_clauses[$l] EOF
{ $l.setDirective(ClawDirective.LOOP_FUSION); }
// loop-interchange directive
| LOOP_INTERCHANGE indexes_option[$l] parallel_clause_optional[$l] acc_optional[$l] EOF
{ $l.setDirective(ClawDirective.LOOP_INTERCHANGE); }
// loop-extract directive
| LOOP_EXTRACT range_option mapping_option_list[m] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF
{
$l.setDirective(ClawDirective.LOOP_EXTRACT);
$l.setRange($range_option.r);
$l.setMappings(m);
}
// remove directive
| REMOVE EOF
{ $l.setDirective(ClawDirective.REMOVE); }
| END REMOVE EOF
{
$l.setDirective(ClawDirective.REMOVE);
$l.setEndPragma();
}
// Kcache directive
| KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF
{
$l.setDirective(ClawDirective.KCACHE);
$l.setOffsets(i);
}
| KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF
{
$l.setDirective(ClawDirective.KCACHE);
$l.setOffsets(i);
$l.setInitClause();
}
// Array notation transformation directive
| ARRAY_TRANS induction_optional[$l] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF
{ $l.setDirective(ClawDirective.ARRAY_TRANSFORM); }
| END ARRAY_TRANS
{
$l.setDirective(ClawDirective.ARRAY_TRANSFORM);
$l.setEndPragma();
}
// loop-hoist directive
| LOOP_HOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF
{
$l.setHoistInductionVars(o);
$l.setDirective(ClawDirective.LOOP_HOIST);
}
| END LOOP_HOIST EOF
{
$l.setDirective(ClawDirective.LOOP_HOIST);
$l.setEndPragma();
}
// on the fly directive
| ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')'
{
$l.setDirective(ClawDirective.ARRAY_TO_CALL);
$l.setFctParams(o);
$l.setFctName($fct_name.text);
$l.setArrayName($array_name.text);
}
// parallelize directive
| define_option[$l]* PARALLELIZE data_over_clause[$l]* parallelize_clauses[$l]
{
$l.setDirective(ClawDirective.PARALLELIZE);
}
| PARALLELIZE FORWARD parallelize_clauses[$l]
{
$l.setDirective(ClawDirective.PARALLELIZE);
$l.setForwardClause();
}
| END PARALLELIZE
{
$l.setDirective(ClawDirective.PARALLELIZE);
$l.setEndPragma();
}
// ignore directive
| IGNORE
{
$l.setDirective(ClawDirective.IGNORE);
}
| END IGNORE
{
$l.setDirective(ClawDirective.IGNORE);
$l.setEndPragma();
}
;
// Comma-separated identifiers list
ids_list[List<String> ids]
:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids]
;
// Comma-separated identifiers or colon symbol list
ids_or_colon_list[List<String> ids]
:
i=IDENTIFIER { $ids.add($i.text); }
| ':' { $ids.add(":"); }
| i=IDENTIFIER { $ids.add($i.text); } ',' ids_or_colon_list[$ids]
| ':' { $ids.add(":"); } ',' ids_or_colon_list[$ids]
;
// data over clause used in parallelize directive
data_over_clause[ClawLanguage l]
@init{
List<String> overLst = new ArrayList<>();
List<String> dataLst = new ArrayList<>();
}
:
DATA '(' ids_list[dataLst] ')' OVER '(' ids_or_colon_list[overLst] ')'
{
$l.setOverDataClause(dataLst);
$l.setOverClause(overLst);
}
;
// group clause
group_clause[ClawLanguage l]:
GROUP '(' group_name=IDENTIFIER ')'
{ $l.setGroupClause($group_name.text); }
;
// collapse clause
collapse_clause[ClawLanguage l]:
COLLAPSE '(' n=NUMBER ')'
{ $l.setCollapseClause($n.text); }
;
// fusion clause
fusion_clause_optional[ClawLanguage l]:
FUSION group_clause[$l] { $l.setFusionClause(); }
| FUSION { $l.setFusionClause(); }
| /* empty */
;
// parallel clause
parallel_clause_optional[ClawLanguage l]:
PARALLEL { $l.setParallelClause(); }
| /* empty */
;
// acc clause
acc_optional[ClawLanguage l]
@init{
List<String> tempAcc = new ArrayList<>();
}
:
ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); }
| /* empty */
;
// interchange clause
interchange_optional[ClawLanguage l]:
INTERCHANGE indexes_option[$l]
{
$l.setInterchangeClause();
}
| /* empty */
;
// induction clause
induction_optional[ClawLanguage l]
@init{
List<String> temp = new ArrayList<>();
}
:
INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); }
| /* empty */
;
// data clause
data_clause[ClawLanguage l]
@init {
List<String> temp = new ArrayList<>();
}
:
DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); }
;
// private clause
private_optional[ClawLanguage l]:
PRIVATE { $l.setPrivateClause(); }
| /* empty */
;
// reshape clause
reshape_optional[ClawLanguage l]
@init{
List<ClawReshapeInfo> r = new ArrayList();
}
:
RESHAPE '(' reshape_list[r] ')'
{ $l.setReshapeClauseValues(r); }
| /* empty */
;
// reshape clause
reshape_element returns [ClawReshapeInfo i]
@init{
List<Integer> temp = new ArrayList();
}
:
array_name=IDENTIFIER '(' target_dim=NUMBER ')'
{ $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); }
| array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')'
{ $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); }
;
reshape_list[List<ClawReshapeInfo> r]:
info=reshape_element { $r.add($info.i); } ',' reshape_list[$r]
| info=reshape_element { $r.add($info.i); }
;
identifiers[List<String> ids]:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids]
;
identifiers_list[List<String> ids]:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids]
;
integers[List<Integer> ints]:
;
integers_list[List<Integer> ints]:
i=NUMBER { $ints.add(Integer.parseInt($i.text)); }
| i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints]
;
indexes_option[ClawLanguage l]
@init{
List<String> indexes = new ArrayList();
}
:
'(' ids_list[indexes] ')' { $l.setIndexes(indexes); }
| /* empty */
;
offset_list_optional[List<Integer> offsets]:
OFFSET '(' offset_list[$offsets] ')'
| /* empty */
;
offset_list[List<Integer> offsets]:
offset[$offsets]
| offset[$offsets] ',' offset_list[$offsets]
;
offset[List<Integer> offsets]:
n=NUMBER { $offsets.add(Integer.parseInt($n.text)); }
| '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); }
| '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); }
;
range_option returns [ClawRange r]
@init{
$r = new ClawRange();
}
:
RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')'
{
$r.setInductionVar($induction.text);
$r.setLowerBound($lower.text);
$r.setUpperBound($upper.text);
$r.setStep(ClawConstant.DEFAULT_STEP_VALUE);
}
| RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')'
{
$r.setInductionVar($induction.text);
$r.setLowerBound($lower.text);
$r.setUpperBound($upper.text);
$r.setStep($step.text);
}
;
range_id returns [String text]:
n=NUMBER { $text = $n.text; }
| i=IDENTIFIER { $text = $i.text; }
;
mapping_var returns [ClawMappingVar mappingVar]:
lhs=IDENTIFIER '/' rhs=IDENTIFIER
{
$mappingVar = new ClawMappingVar($lhs.text, $rhs.text);
}
| i=IDENTIFIER
{
$mappingVar = new ClawMappingVar($i.text, $i.text);
}
;
mapping_var_list[List<ClawMappingVar> vars]:
mv=mapping_var { $vars.add($mv.mappingVar); }
| mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars]
;
mapping_option returns [ClawMapping mapping]
@init{
$mapping = new ClawMapping();
List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>();
List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>();
$mapping.setMappedVariables(listMapped);
$mapping.setMappingVariables(listMapping);
}
:
MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')'
;
mapping_option_list[List<ClawMapping> mappings]:
m=mapping_option { $mappings.add($m.mapping); }
| m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings]
;
define_option[ClawLanguage l]:
DEFINE DIMENSION id=IDENTIFIER '(' lower=range_id ':' upper=range_id ')'
{
ClawDimension cd = new ClawDimension($id.text, $lower.text, $upper.text);
$l.addDimension(cd);
}
;
// Allow to switch order
parallelize_clauses[ClawLanguage l]:
copy_clause_optional[$l] update_clause_optional[$l]
| update_clause_optional[$l] copy_clause_optional[$l]
;
copy_clause_optional[ClawLanguage l]:
/* empty */
| COPY
{ $l.setCopyClauseValue(ClawDMD.BOTH); }
| COPY '(' IN ')'
{ $l.setCopyClauseValue(ClawDMD.IN); }
| COPY '(' OUT ')'
{ $l.setCopyClauseValue(ClawDMD.OUT); }
;
update_clause_optional[ClawLanguage l]:
/* empty */
| UPDATE
{ $l.setUpdateClauseValue(ClawDMD.BOTH); }
| UPDATE '(' IN ')'
{ $l.setUpdateClauseValue(ClawDMD.IN); }
| UPDATE '(' OUT ')'
{ $l.setUpdateClauseValue(ClawDMD.OUT); }
;
target_clause[ClawLanguage l]
@init{
List<Target> targets = new ArrayList<>();
}
:
TARGET '(' target_list[targets] ')'
{ $l.setTargetClauseValue(targets); }
;
target_list[List<Target> targets]:
target { if(!$targets.contains($target.t)) { $targets.add($target.t); } }
| target { if(!$targets.contains($target.t)) { $targets.add($target.t); } } ',' target_list[$targets]
;
target returns [Target t]:
CPU { $t = Target.CPU; }
| GPU { $t = Target.GPU; }
| MIC { $t = Target.MIC; }
;
loop_fusion_clauses[ClawLanguage l]:
(
{ !$l.hasGroupClause() }? group_clause[$l]
| { !$l.hasCollapseClause() }? collapse_clause[$l]
| { !$l.hasTargetClause() }? target_clause[$l]
)*
;
/*----------------------------------------------------------------------------
* LEXER RULES
*----------------------------------------------------------------------------*/
// Start point
CLAW : 'claw';
// CLAW Directives
ARRAY_TRANS : 'array-transform';
ARRAY_TO_CALL : 'call';
DEFINE : 'define';
END : 'end';
KCACHE : 'kcache';
LOOP_EXTRACT : 'loop-extract';
LOOP_FUSION : 'loop-fusion';
LOOP_HOIST : 'loop-hoist';
LOOP_INTERCHANGE : 'loop-interchange';
PARALLELIZE : 'parallelize';
REMOVE : 'remove';
IGNORE : 'ignore';
VERBATIM : 'verbatim';
// CLAW Clauses
COLLAPSE : 'collapse';
COPY : 'copy';
DATA : 'data';
DIMENSION : 'dimension';
FORWARD : 'forward';
FUSION : 'fusion';
GROUP : 'group';
INDUCTION : 'induction';
INIT : 'init';
INTERCHANGE : 'interchange';
MAP : 'map';
OFFSET : 'offset';
OVER : 'over';
PARALLEL : 'parallel';
PRIVATE : 'private';
RANGE : 'range';
RESHAPE : 'reshape';
TARGET : 'target';
UPDATE : 'update';
// data copy/update clause keywords
IN : 'in';
OUT : 'out';
// Directive primitive clause
ACC : 'acc';
OMP : 'omp';
// Target for the target clause
CPU : 'cpu';
GPU : 'gpu';
MIC : 'mic';
// Special elements
IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ;
NUMBER : (DIGIT)+ ;
fragment DIGIT : [0-9] ;
// Skip whitspaces
WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
|
Introduce target clause parser rule + apply it to loop fusion
|
Introduce target clause parser rule + apply it to loop fusion
#84
|
ANTLR
|
bsd-2-clause
|
clementval/claw-compiler,clementval/claw-compiler
|
ee69928feab2aff9c18f92e7523d398d67d5825a
|
src/main/resources/syntax/LPMLN.g4
|
src/main/resources/syntax/LPMLN.g4
|
/**
* LPMLN 词法语法定义
* 王彬
* 2016-08-30
**/
grammar LPMLN;
/**
* 词法定义
**/
//缺省否定关键字
NAF_NOT : 'not ';
//字符串
STRING : '"' ('\\"'|~('"'))* '"';
//规则终结符
FULLSTOP : '.';
//正整数
POSITIVE_INT : [1-9][0-9]*;
//小数(点表示法)
DECIMAL : MINUS? (POSITIVE_INT* | ZERO ) FULLSTOP [0-9] ZERO* [1-9]*;
//0
ZERO : '0';
//常量
CONSTANT : [a-z][a-zA-Z0-9_']*;
//变量
VAR : [A-Z][a-zA-Z0-9_']*;
//指数运算
EXPONENITIATION : '**';
//位运算
BITWISE_AND : '&';
BITWISE_OR : '?';
BITWISE_EXCLUSIVE_OR : '^';
BITWISE_COMPLEMENT : '~';
//加号
PLUS : '+';
//减号、经典否定关键字
MINUS : '-';
//乘号、 星号
STAR : '*';
//除号、斜线
SLASH : '/';
//左圆括号
LPAREN : '(';
//右圆括号
RPAREN : ')';
//左方括号
LSBRACK : '[';
//右方括号
RSBRACK : ']';
//左花括号
LCBRACK : '{';
//右花括号
RCBRACK : '}';
//范围运算
RANGE : '..';
//逗号
COMMA : ',';
//认知析取符
DISJUNCTION : '|';
//条件限制符
CONDITION : ':';
//推导符号
ASSIGN : ':-';
//弱约束推导符号
WEAK_ASSIGN : ':~';
//分号
SEMICOLON : ';';
//关系运算符
LESS_THAN : '<';
LEQ : '<=';
GREATER_THAN : '>';
GEQ : '>=';
EQUAL : '=';
DOUBLE_EQUAL : '==';
NEQ : '!=';
AGGREGATE_OP : '#count' | '#sum' | '#max' | '#min';
//
META_OP : '#show ';
//单行注释
LINE_COMMENT : ('%' ~('\r' | '\n')* '\r'? '\n') -> skip;
//空白字符或换行符
WS : ( ' ' | '\t' | '\n' | '\r')+ -> skip ;
//布尔常量
BOOL_CONSTANTS : '#true' | '#false';
/**
* 语法规则定义
**/
//负整数
negative_int : MINUS POSITIVE_INT ;
//整数
integer : POSITIVE_INT | negative_int | ZERO;
//自然数
natural_number : POSITIVE_INT | ZERO;
//四则运算符
arithmetic_op : PLUS | MINUS | STAR | SLASH;
//二元位运算
bitwise_op : BITWISE_AND | BITWISE_OR | BITWISE_EXCLUSIVE_OR;
//二元运算符
binary_op : arithmetic_op | bitwise_op | EXPONENITIATION;
//一元运算符
unary_op : BITWISE_COMPLEMENT;
//数字
bit_number : unary_op? natural_number;
//关系运算符(comparison predicates)
relation_op : LESS_THAN | LEQ | GREATER_THAN | GEQ | EQUAL | DOUBLE_EQUAL | NEQ;
//简单四则运算算术表达式,不加括号
simple_arithmetic_expr :
integer |
(MINUS)? VAR |
(integer | (MINUS)? VAR) (binary_op (bit_number | VAR))* ;
//四则运算算术表达式,加括号
simple_arithmetic_expr2 :
simple_arithmetic_expr |
(LPAREN simple_arithmetic_expr2 RPAREN) |
simple_arithmetic_expr2 arithmetic_op simple_arithmetic_expr2;
//四则运算表达式
arithmethic_expr:
simple_arithmetic_expr2 |
MINUS LPAREN simple_arithmetic_expr2 RPAREN;
//函数
function : CONSTANT LPAREN term (COMMA term)* RPAREN;
//简单项,缺_,#sup,#inf
simpleterm : integer | CONSTANT | STRING | VAR;
//元组
tuple : LPAREN ( | term ( | COMMA | (COMMA term)* )) RPAREN;
//项
//term : VAR | CONSTANT | integer | arithmethic_expr | function | STRING;
term : simpleterm | function | tuple;
//原子
atom :
CONSTANT |
CONSTANT LPAREN term (COMMA term)* RPAREN;
//范围整数枚举原子
range_atom : CONSTANT LPAREN integer RANGE integer RPAREN;
//文字
literal : atom | MINUS atom | NAF_NOT literal;
//缺省文字
//default_literal : NAF_NOT literal;
//扩展文字,包含查询原子
//extended_literal : literal | default_literal;
//项元组
term_tuple : term (COMMA term)*;
//文字元组
literal_tuple : literal (COMMA literal)*;
//聚合元素
aggregate_elements : (term_tuple CONDITION)? literal_tuple (SEMICOLON (term_tuple CONDITION)? literal_tuple)*;
//带条件的聚合元素
aggregate_elements_condition : (term_tuple CONDITION)? literal_tuple CONDITION literal_tuple (SEMICOLON (term_tuple CONDITION)? literal_tuple CONDITION literal_tuple)*;
//体部聚合原子
body_aggregate : (term relation_op?)? AGGREGATE_OP? LCBRACK aggregate_elements RCBRACK (relation_op? term)?;
//aggregate_atom : AGGREGATE_OP LCBRACK (literal | VAR) CONDITION literal RCBRACK ;
//头部聚合原子
head_aggregate : (term relation_op?)? AGGREGATE_OP? LCBRACK aggregate_elements_condition RCBRACK (relation_op? term)?;
//聚合运算表达式
//aggregate_expr: (VAR | aggregate_atom | integer) relation_op aggregate_atom |
// aggregate_atom relation_op (VAR | integer) |
// VAR EQUAL aggregate_atom;
//关系运算表达式
relation_expr :
(MINUS)? VAR relation_op (MINUS)? VAR |
VAR relation_op STRING |
((MINUS)? VAR | arithmethic_expr) relation_op ((MINUS)? VAR | arithmethic_expr);
//规则头部
head : head_literal (DISJUNCTION head_literal)*;
//头部文字
head_literal : literal | head_aggregate | NAF_NOT head_literal;
//规则体部
body : body_literal (COMMA body_literal)*;
//体部文字
body_literal : literal | relation_expr | body_aggregate | NAF_NOT body_literal;
//事实
fact : (head | range_atom) FULLSTOP;
//约束
constraint : ASSIGN body FULLSTOP;
//基本规则
full_rule : head ASSIGN body FULLSTOP;
//ASP 规则 (hard rule)
hard_rule : fact | constraint | full_rule;
//弱规则 (soft rule)
soft_rule : (DECIMAL | integer ) CONDITION hard_rule;
//
meta_rule : META_OP (MINUS)? CONSTANT SLASH natural_number FULLSTOP;
//ASP4QA程序
lpmln_rule : (hard_rule | soft_rule | meta_rule)*;
|
/**
* LPMLN 词法语法定义
* 王彬
* 2016-08-30
**/
grammar LPMLN;
/**
* 词法定义
**/
//缺省否定关键字
NAF_NOT : 'not ';
//字符串
STRING : '"' ('\\"'|~('"'))* '"';
//规则终结符
FULLSTOP : '.';
//正整数
POSITIVE_INT : [1-9][0-9]*;
//小数(点表示法)
DECIMAL : MINUS? (POSITIVE_INT* | ZERO ) FULLSTOP [0-9] ZERO* [1-9]*;
//0
ZERO : '0';
//常量
CONSTANT : [a-z][a-zA-Z0-9_']*;
//变量
VAR : [A-Z][a-zA-Z0-9_']*;
//指数运算
EXPONENITIATION : '**';
//位运算
BITWISE_AND : '&';
BITWISE_OR : '?';
BITWISE_EXCLUSIVE_OR : '^';
BITWISE_COMPLEMENT : '~';
//加号
PLUS : '+';
//减号、经典否定关键字
MINUS : '-';
//乘号、 星号
STAR : '*';
//除号、斜线
SLASH : '/';
//左圆括号
LPAREN : '(';
//右圆括号
RPAREN : ')';
//左方括号
LSBRACK : '[';
//右方括号
RSBRACK : ']';
//左花括号
LCBRACK : '{';
//右花括号
RCBRACK : '}';
//范围运算
RANGE : '..';
//逗号
COMMA : ',';
//认知析取符
DISJUNCTION : '|';
//条件限制符
CONDITION : ':';
//推导符号
ASSIGN : ':-';
//弱约束推导符号
WEAK_ASSIGN : ':~';
//分号
SEMICOLON : ';';
//关系运算符
LESS_THAN : '<';
LEQ : '<=';
GREATER_THAN : '>';
GEQ : '>=';
EQUAL : '=';
DOUBLE_EQUAL : '==';
NEQ : '!=';
AGGREGATE_OP : '#count' | '#sum' | '#max' | '#min';
//
META_OP : '#show ';
//单行注释
LINE_COMMENT : ('%' ~('\r' | '\n')* '\r'? '\n') -> skip;
//空白字符或换行符
WS : ( ' ' | '\t' | '\n' | '\r')+ -> skip ;
//布尔常量
BOOL_CONSTANTS : '#true' | '#false';
/**
* 语法规则定义
**/
//负整数
negative_int : MINUS POSITIVE_INT ;
//整数
integer : POSITIVE_INT | negative_int | ZERO;
//自然数
natural_number : POSITIVE_INT | ZERO;
//四则运算符
arithmetic_op : PLUS | MINUS | STAR | SLASH;
//二元位运算
bitwise_op : BITWISE_AND | BITWISE_OR | BITWISE_EXCLUSIVE_OR;
//二元运算符
binary_op : arithmetic_op | bitwise_op | EXPONENITIATION;
//一元运算符
unary_op : BITWISE_COMPLEMENT;
//数字
bit_number : unary_op? natural_number;
//关系运算符(comparison predicates)
relation_op : LESS_THAN | LEQ | GREATER_THAN | GEQ | EQUAL | DOUBLE_EQUAL | NEQ;
//简单四则运算算术表达式,不加括号
simple_arithmetic_expr :
integer |
(MINUS)? VAR |
(integer | (MINUS)? VAR) (binary_op (bit_number | VAR))* ;
//四则运算算术表达式,加括号
simple_arithmetic_expr2 :
simple_arithmetic_expr |
(LPAREN simple_arithmetic_expr2 RPAREN) |
simple_arithmetic_expr2 arithmetic_op simple_arithmetic_expr2;
//四则运算表达式
arithmethic_expr:
simple_arithmetic_expr2 |
MINUS LPAREN simple_arithmetic_expr2 RPAREN;
//函数
function : CONSTANT LPAREN term (COMMA term)* RPAREN;
//简单项,缺_,#sup,#inf
simpleterm : integer | CONSTANT | STRING | VAR;
//元组
tuple : LPAREN ( | term ( | COMMA | (COMMA term)* )) RPAREN;
//项
//term : VAR | CONSTANT | integer | arithmethic_expr | function | STRING;
term : simpleterm | function | tuple | arithmethic_expr;
//原子
atom :
CONSTANT |
CONSTANT LPAREN term (COMMA term)* RPAREN;
//范围整数枚举原子
range_atom : CONSTANT LPAREN integer RANGE integer RPAREN;
//文字
literal : atom | MINUS atom | NAF_NOT literal;
//缺省文字
//default_literal : NAF_NOT literal;
//扩展文字,包含查询原子
//extended_literal : literal | default_literal;
//项元组
term_tuple : term (COMMA term)*;
//文字元组
literal_tuple : literal (COMMA literal)*;
//聚合元素
aggregate_elements : (term_tuple CONDITION)? literal_tuple (SEMICOLON (term_tuple CONDITION)? literal_tuple)*;
//带条件的聚合元素
aggregate_elements_condition : (term_tuple CONDITION)? literal_tuple CONDITION literal_tuple (SEMICOLON (term_tuple CONDITION)? literal_tuple CONDITION literal_tuple)*;
//体部聚合原子
body_aggregate : (term relation_op?)? AGGREGATE_OP? LCBRACK aggregate_elements RCBRACK (relation_op? term)?;
//aggregate_atom : AGGREGATE_OP LCBRACK (literal | VAR) CONDITION literal RCBRACK ;
//头部聚合原子
head_aggregate : (term relation_op?)? AGGREGATE_OP? LCBRACK aggregate_elements_condition RCBRACK (relation_op? term)?;
//聚合运算表达式
//aggregate_expr: (VAR | aggregate_atom | integer) relation_op aggregate_atom |
// aggregate_atom relation_op (VAR | integer) |
// VAR EQUAL aggregate_atom;
//关系运算表达式
relation_expr : ((MINUS)? term) relation_op ((MINUS)? term);
//规则头部
head : head_literal (DISJUNCTION head_literal)*;
//头部文字
head_literal : literal | head_aggregate | NAF_NOT head_literal;
//规则体部
body : body_literal (COMMA body_literal)*;
//体部文字
body_literal : literal | relation_expr | body_aggregate | NAF_NOT body_literal;
//事实
fact : (head | range_atom) FULLSTOP;
//约束
constraint : ASSIGN body FULLSTOP;
//基本规则
full_rule : head ASSIGN body FULLSTOP;
//ASP 规则 (hard rule)
hard_rule : fact | constraint | full_rule;
//弱规则 (soft rule)
soft_rule : (DECIMAL | integer ) CONDITION hard_rule;
//
meta_rule : META_OP (MINUS)? CONSTANT SLASH natural_number FULLSTOP;
//ASP4QA程序
lpmln_rule : (hard_rule | soft_rule | meta_rule)*;
|
修改项,统一关系表达式
|
修改项,统一关系表达式
Signed-off-by: 许鸿翔 <[email protected]>
|
ANTLR
|
agpl-3.0
|
wangbiu/lpmlnmodels
|
d4b076a755cbd9567fa02e0ff576e1021dbf6cd5
|
antlr/antlr4/Python3/ANTLRv4Lexer.g4
|
antlr/antlr4/Python3/ANTLRv4Lexer.g4
|
/*
* [The "BSD license"]
* Copyright (c) 2012-2015 Terence Parr
* Copyright (c) 2012-2015 Sam Harwell
* Copyright (c) 2015 Gerald Rosenberg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* A grammar for ANTLR v4 implemented using v4 syntax
*
* Modified 2015.06.16 gbr
* -- update for compatibility with Antlr v4.5
*/
lexer grammar ANTLRv4LexerPythonTarget;
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* ;
|
/*
* [The "BSD license"]
* Copyright (c) 2012-2015 Terence Parr
* Copyright (c) 2012-2015 Sam Harwell
* Copyright (c) 2015 Gerald Rosenberg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* A grammar for ANTLR v4 implemented using v4 syntax
*
* Modified 2015.06.16 gbr
* -- update for compatibility with Antlr v4.5
*/
// ======================================================
// Lexer specification
// ======================================================
lexer grammar ANTLRv4LexerPythonTarget;
options { superClass = LexerAdaptor; }
import LexBasic;
// Standard set of fragments
tokens { TOKEN_REF , RULE_REF , LEXER_CHAR_SET }
channels { OFF_CHANNEL , COMMENT }
// -------------------------
// Comments
DOC_COMMENT
: DocComment -> channel (COMMENT)
;
BLOCK_COMMENT
: BlockComment -> channel (COMMENT)
;
LINE_COMMENT
: LineComment -> channel (COMMENT)
;
// -------------------------
// Integer
INT
: DecimalNumeral
;
// -------------------------
// Literal string
//
// ANTLR makes no distinction between a single character literal and a
// multi-character string. All literals are single quote delimited and
// may contain unicode escape sequences of the form \uxxxx, where x
// is a valid hexadecimal number (per Unicode standard).
STRING_LITERAL
: SQuoteLiteral
;
UNTERMINATED_STRING_LITERAL
: USQuoteLiteral
;
// -------------------------
// Arguments
//
// Certain argument lists, such as those specifying call parameters
// to a rule invocation, or input parameters to a rule specification
// are contained within square brackets.
BEGIN_ARGUMENT
: LBrack
{ self.handleBeginArgument() }
;
// -------------------------
// Target Language Actions
BEGIN_ACTION
: LBrace -> pushMode (TargetLanguageAction)
;
// -------------------------
// Keywords
//
// 'options', 'tokens', and 'channels' are considered keywords
// but only when followed by '{', and considered as a single token.
// Otherwise, the symbols are tokenized as RULE_REF and allowed as
// an identifier in a labeledElement.
OPTIONS : 'options' WSNLCHARS* '{' ;
TOKENS : 'tokens' WSNLCHARS* '{' ;
CHANNELS : 'channels' WSNLCHARS* '{' ;
fragment WSNLCHARS : ' ' | '\t' | '\f' | '\n' | '\r' ;
IMPORT
: 'import'
;
FRAGMENT
: 'fragment'
;
LEXER
: 'lexer'
;
PARSER
: 'parser'
;
GRAMMAR
: 'grammar'
;
PROTECTED
: 'protected'
;
PUBLIC
: 'public'
;
PRIVATE
: 'private'
;
RETURNS
: 'returns'
;
LOCALS
: 'locals'
;
THROWS
: 'throws'
;
CATCH
: 'catch'
;
FINALLY
: 'finally'
;
MODE
: 'mode'
;
// -------------------------
// Punctuation
COLON
: Colon
;
COLONCOLON
: DColon
;
COMMA
: Comma
;
SEMI
: Semi
;
LPAREN
: LParen
;
RPAREN
: RParen
;
LBRACE
: LBrace
;
RBRACE
: RBrace
;
RARROW
: RArrow
;
LT
: Lt
;
GT
: Gt
;
ASSIGN
: Equal
;
QUESTION
: Question
;
STAR
: Star
;
PLUS_ASSIGN
: PlusAssign
;
PLUS
: Plus
;
OR
: Pipe
;
DOLLAR
: Dollar
;
RANGE
: Range
;
DOT
: Dot
;
AT
: At
;
POUND
: Pound
;
NOT
: Tilde
;
// -------------------------
// Identifiers - allows unicode rule/token names
ID
: Id
;
// -------------------------
// Whitespace
WS
: Ws+ -> channel (OFF_CHANNEL)
;
// -------------------------
// Illegal Characters
//
// This is an illegal character trap which is always the last rule in the
// lexer specification. It matches a single character of any value and being
// the last rule in the file will match when no other rule knows what to do
// about the character. It is reported as an error but is not passed on to the
// parser. This means that the parser to deal with the gramamr file anyway
// but we will not try to analyse or code generate from a file with lexical
// errors.
// Comment this rule out to allow the error to be propagated to the parser
ERRCHAR
: . -> channel (HIDDEN)
;
// ======================================================
// Lexer modes
// -------------------------
// Arguments
mode Argument;
// E.g., [int x, List<String> a[]]
NESTED_ARGUMENT
: LBrack -> type (ARGUMENT_CONTENT) , pushMode (Argument)
;
ARGUMENT_ESCAPE
: EscAny -> type (ARGUMENT_CONTENT)
;
ARGUMENT_STRING_LITERAL
: DQuoteLiteral -> type (ARGUMENT_CONTENT)
;
ARGUMENT_CHAR_LITERAL
: SQuoteLiteral -> type (ARGUMENT_CONTENT)
;
END_ARGUMENT
: RBrack
{ self.handleEndArgument() }
;
// added this to return non-EOF token type here. EOF does something weird
UNTERMINATED_ARGUMENT
: EOF -> popMode
;
ARGUMENT_CONTENT
: .
;
// -------------------------
// Target Language Actions
//
// Many language targets use {} as block delimiters and so we
// must recursively match {} delimited blocks to balance the
// braces. Additionally, we must make some assumptions about
// literal string representation in the target language. We assume
// that they are delimited by ' or " and so consume these
// in their own alts so as not to inadvertantly match {}.
mode TargetLanguageAction;
NESTED_ACTION
: LBrace -> type (ACTION_CONTENT) , pushMode (TargetLanguageAction)
;
ACTION_ESCAPE
: EscAny -> type (ACTION_CONTENT)
;
ACTION_STRING_LITERAL
: DQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_CHAR_LITERAL
: SQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_DOC_COMMENT
: DocComment -> type (ACTION_CONTENT)
;
ACTION_BLOCK_COMMENT
: BlockComment -> type (ACTION_CONTENT)
;
ACTION_LINE_COMMENT
: LineComment -> type (ACTION_CONTENT)
;
END_ACTION
: RBrace
{ self.handleEndAction() }
;
UNTERMINATED_ACTION
: EOF -> popMode
;
ACTION_CONTENT
: .
;
// -------------------------
mode LexerCharSet;
LEXER_CHAR_SET_BODY
: (~ [\]\\] | EscAny)+ -> more
;
LEXER_CHAR_SET
: RBrack -> popMode
;
UNTERMINATED_CHAR_SET
: EOF -> popMode
;
// ------------------------------------------------------------------------------
// Grammar specific Keywords, Punctuation, etc.
fragment Id
: NameStartChar NameChar*
;
|
Update Python3 target for antlr/antlr4/ grammar.
|
Update Python3 target for antlr/antlr4/ 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
|
b8af2a4884d97ac5a1198b52949c34a58e3c826b
|
terraform/terraform.g4
|
terraform/terraform.g4
|
/*
BSD License
Copyright (c) 2020, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar terraform;
file
: (local | module | output | provider | variable | data | resource | terraform)+
;
terraform
: 'terraform' blockbody
;
resource
: 'resource' resourcetype name blockbody
;
data
: 'data' resourcetype name blockbody
;
provider
: 'provider' resourcetype blockbody
;
output
: 'output' name blockbody
;
local
: 'locals' blockbody
;
module
: 'module' name blockbody
;
variable
: 'variable' name blockbody
;
block
: blocktype label* blockbody
;
blocktype
: IDENTIFIER
;
resourcetype
: STRING
;
name
: STRING
;
label
: STRING
;
blockbody
: LCURL (argument | block)* RCURL
;
argument
: identifier '=' expression
;
identifier
: IDENTIFIER
;
expression
: RESOURCEREFERENCE
| section
| expression OPERATOR expression
| LPAREN expression RPAREN
| expression '?' expression ':' expression
| map
;
RESOURCEREFERENCE
: [a-zA-Z] [a-zA-Z0-9_-]* RESOURCEINDEX? '.' ([a-zA-Z0-9_.-] RESOURCEINDEX?)+
;
RESOURCEINDEX
: '[' [0-9]+ ']'
;
section
: list
| map
| val
;
val
: NULL
| SIGNED_NUMBER
| string
| BOOL
| IDENTIFIER index?
| DESCRIPTION
| filedecl
| functioncall
| EOF_
;
functioncall
: functionname LPAREN functionarguments RPAREN
;
functionname
: IDENTIFIER
;
functionarguments
: //no arguments
| expression (',' expression)*
;
index
: '[' expression ']'
;
filedecl
: 'file' '(' expression ')'
;
list
: '[' expression (',' expression)* ','? ']'
;
map
: LCURL argument* (',' argument)* LCURL
;
string
: STRING
| MULTILINESTRING
;
fragment DIGIT
: [0-9]
;
SIGNED_NUMBER
: '+' NUMBER
| '-' NUMBER
| NUMBER
;
OPERATOR
: '*'
| '/'
| '%'
| '+'
| '-'
| '>'
| '>='
| '<'
| '<='
| '=='
| '!='
| '&&'
| '||'
;
LCURL
: '{'
;
RCURL
: '}'
;
LPAREN
: '('
;
RPAREN
: ')'
;
EOF_
: '<<EOF' .*? 'EOF'
;
NULL
: 'nul'
;
NUMBER
: DIGIT+ ('.' DIGIT+)?
;
BOOL
: 'true'
| 'false'
;
DESCRIPTION
: '<<DESCRIPTION' .*? 'DESCRIPTION'
;
MULTILINESTRING
: '<<-EOF' .*? 'EOF'
;
STRING
: '"' (~ [\r\n"] | '""')* '"'
;
IDENTIFIER
: [a-zA-Z] ([a-zA-Z0-9_-])*
;
COMMENT
: ('#' | '//') ~ [\r\n]* -> channel(HIDDEN)
;
BLOCKCOMMENT
: '/*' .*? '*/' -> channel(HIDDEN)
;
WS
: [ \r\n\t]+ -> skip
;
|
/*
BSD License
Copyright (c) 2020, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar terraform;
file
: (local | module | output | provider | variable | data | resource | terraform)+
;
terraform
: 'terraform' blockbody
;
resource
: 'resource' resourcetype name blockbody
;
data
: 'data' resourcetype name blockbody
;
provider
: 'provider' resourcetype blockbody
;
output
: 'output' name blockbody
;
local
: 'locals' blockbody
;
module
: 'module' name blockbody
;
variable
: 'variable' name blockbody
;
block
: blocktype label* blockbody
;
blocktype
: IDENTIFIER
;
resourcetype
: STRING
;
name
: STRING
;
label
: STRING
;
blockbody
: LCURL (argument | block)* RCURL
;
argument
: identifier '=' expression
;
identifier
: IDENTIFIER
;
expression
: RESOURCEREFERENCE
| section
| expression OPERATOR expression
| LPAREN expression RPAREN
| expression '?' expression ':' expression
;
RESOURCEREFERENCE
: [a-zA-Z] [a-zA-Z0-9_-]* RESOURCEINDEX? '.' ([a-zA-Z0-9_.-] RESOURCEINDEX?)+
;
RESOURCEINDEX
: '[' [0-9]+ ']'
;
section
: list
| map
| val
;
val
: NULL
| SIGNED_NUMBER
| string
| BOOL
| IDENTIFIER index?
| DESCRIPTION
| filedecl
| functioncall
| EOF_
;
functioncall
: functionname LPAREN functionarguments RPAREN
;
functionname
: IDENTIFIER
;
functionarguments
: //no arguments
| expression (',' expression)*
;
index
: '[' expression ']'
;
filedecl
: 'file' '(' expression ')'
;
list
: '[' expression (',' expression)* ','? ']'
;
map
: LCURL (argument ','?)* RCURL
;
string
: STRING
| MULTILINESTRING
;
fragment DIGIT
: [0-9]
;
SIGNED_NUMBER
: '+' NUMBER
| '-' NUMBER
| NUMBER
;
OPERATOR
: '*'
| '/'
| '%'
| '+'
| '-'
| '>'
| '>='
| '<'
| '<='
| '=='
| '!='
| '&&'
| '||'
;
LCURL
: '{'
;
RCURL
: '}'
;
LPAREN
: '('
;
RPAREN
: ')'
;
EOF_
: '<<EOF' .*? 'EOF'
;
NULL
: 'nul'
;
NUMBER
: DIGIT+ ('.' DIGIT+)?
;
BOOL
: 'true'
| 'false'
;
DESCRIPTION
: '<<DESCRIPTION' .*? 'DESCRIPTION'
;
MULTILINESTRING
: '<<-EOF' .*? 'EOF'
;
STRING
: '"' (~ [\r\n"] | '""')* '"'
;
IDENTIFIER
: [a-zA-Z] ([a-zA-Z0-9_-])*
;
COMMENT
: ('#' | '//') ~ [\r\n]* -> channel(HIDDEN)
;
BLOCKCOMMENT
: '/*' .*? '*/' -> channel(HIDDEN)
;
WS
: [ \r\n\t]+ -> skip
;
|
Add ',' to separate map entries
|
Add ',' to separate map entries
|
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
|
2b82932f980f90789b099fb2445b52e7aa44bb51
|
src/main/antlr/at/ac/tuwien/kr/alpha/antlr/ASPCore2.g4
|
src/main/antlr/at/ac/tuwien/kr/alpha/antlr/ASPCore2.g4
|
grammar ASPCore2;
import ASPLexer;
/* The ASP-Core-2 grammar in ANTLR v4 based on
* https://www.mat.unical.it/aspcomp2013/files/ASP-CORE-2.01c.pdf
* (sections 4 and 5, pages 10-12).
* It is extended a bit to parse widespread syntax used by gringo/clasp,
* see productions "gringo_range" and "gringo_sharp".
*/
program : statements? query?;
statements : statement+;
query : classical_literal QUERY_MARK;
statement : head DOT # statement_fact
| CONS body DOT # statement_constraint
| head CONS body DOT # statement_rule
| WCONS body? DOT SQUARE_OPEN weight_at_level SQUARE_CLOSE # statement_weightConstraint
| gringo_sharp # statement_gringoSharp; // syntax extension
head : disjunction | choice;
body : ( naf_literal | NAF? aggregate ) (COMMA body)?;
disjunction : classical_literal (OR disjunction)?;
choice : (term binop)? CURLY_OPEN choice_elements? CURLY_CLOSE (binop term)?;
choice_elements : choice_element (SEMICOLON choice_elements)?;
choice_element : classical_literal (COLON naf_literals?)?;
aggregate : (term binop)? aggregate_function CURLY_OPEN aggregate_elements CURLY_CLOSE (binop term)?;
aggregate_elements : aggregate_element (SEMICOLON aggregate_elements)?;
aggregate_element : basic_terms? (COLON naf_literals?)?;
aggregate_function : AGGREGATE_COUNT | AGGREGATE_MAX | AGGREGATE_MIN | AGGREGATE_SUM;
weight_at_level : term (AT term)? (COMMA terms)?;
naf_literals : naf_literal (COMMA naf_literals)?;
naf_literal : NAF? (external_atom | classical_literal | builtin_atom);
classical_literal : MINUS? ID (PAREN_OPEN terms PAREN_CLOSE)?;
builtin_atom : term binop term;
binop : EQUAL | UNEQUAL | LESS | GREATER | LESS_OR_EQ | GREATER_OR_EQ;
terms : term (COMMA terms)?;
term : ID # term_const
| ID (PAREN_OPEN terms? PAREN_CLOSE) # term_func
| NUMBER # term_number
| STRING # term_string
| VARIABLE # term_variable
| ANONYMOUS_VARIABLE # term_anonymousVariable
| PAREN_OPEN term PAREN_CLOSE # term_parenthesisedTerm
| MINUS term # term_minusTerm
| term arithop term # term_binopTerm
| interval # term_interval; // syntax extension
arithop : PLUS | MINUS | TIMES | DIV;
interval : lower = (NUMBER | VARIABLE) DOT DOT upper = (NUMBER | VARIABLE); // NOT Core2 syntax, but widespread
external_atom : MINUS? AMPERSAND ID (SQUARE_OPEN output = terms SQUARE_CLOSE)? (PAREN_OPEN input = terms PAREN_CLOSE)?;
gringo_sharp : SHARP ~(DOT)* DOT; // NOT Core2 syntax, but widespread, matching not perfect due to possible earlier dots
basic_terms : basic_term (COMMA basic_terms)? ;
basic_term : ground_term | variable_term;
ground_term : /*SYMBOLIC_CONSTANT*/ ID | STRING | MINUS? NUMBER;
variable_term : VARIABLE | ANONYMOUS_VARIABLE;
answer_set : CURLY_OPEN classical_literal* (COMMA classical_literal)* CURLY_CLOSE;
answer_sets: answer_set*;
|
grammar ASPCore2;
import ASPLexer;
/* The ASP-Core-2 grammar in ANTLR v4 based on
* https://www.mat.unical.it/aspcomp2013/files/ASP-CORE-2.01c.pdf
* (sections 4 and 5, pages 10-12).
* It is extended a bit to parse widespread syntax (e.g. used by gringo/clasp).
*/
program : statements? query?;
statements : statement+;
query : classical_literal QUERY_MARK;
statement : head DOT # statement_fact
| CONS body DOT # statement_constraint
| head CONS body DOT # statement_rule
| WCONS body? DOT SQUARE_OPEN weight_at_level SQUARE_CLOSE # statement_weightConstraint
| gringo_sharp # statement_gringoSharp; // syntax extension
head : disjunction | choice;
body : ( naf_literal | NAF? aggregate ) (COMMA body)?;
disjunction : classical_literal (OR disjunction)?;
choice : (term binop)? CURLY_OPEN choice_elements? CURLY_CLOSE (binop term)?;
choice_elements : choice_element (SEMICOLON choice_elements)?;
choice_element : classical_literal (COLON naf_literals?)?;
aggregate : (term binop)? aggregate_function CURLY_OPEN aggregate_elements CURLY_CLOSE (binop term)?;
aggregate_elements : aggregate_element (SEMICOLON aggregate_elements)?;
aggregate_element : basic_terms? (COLON naf_literals?)?;
aggregate_function : AGGREGATE_COUNT | AGGREGATE_MAX | AGGREGATE_MIN | AGGREGATE_SUM;
weight_at_level : term (AT term)? (COMMA terms)?;
naf_literals : naf_literal (COMMA naf_literals)?;
naf_literal : NAF? (external_atom | classical_literal | builtin_atom);
classical_literal : MINUS? ID (PAREN_OPEN terms PAREN_CLOSE)?;
builtin_atom : term binop term;
binop : EQUAL | UNEQUAL | LESS | GREATER | LESS_OR_EQ | GREATER_OR_EQ;
terms : term (COMMA terms)?;
term : ID # term_const
| ID (PAREN_OPEN terms? PAREN_CLOSE) # term_func
| NUMBER # term_number
| STRING # term_string
| VARIABLE # term_variable
| ANONYMOUS_VARIABLE # term_anonymousVariable
| PAREN_OPEN term PAREN_CLOSE # term_parenthesisedTerm
| MINUS term # term_minusTerm
| term arithop term # term_binopTerm
| interval # term_interval; // syntax extension
arithop : PLUS | MINUS | TIMES | DIV;
interval : lower = (NUMBER | VARIABLE) DOT DOT upper = (NUMBER | VARIABLE); // NOT Core2 syntax, but widespread
external_atom : MINUS? AMPERSAND ID (SQUARE_OPEN output = terms SQUARE_CLOSE)? (PAREN_OPEN input = terms PAREN_CLOSE)?; // NOT Core2 syntax.
gringo_sharp : SHARP ~(DOT)* DOT; // NOT Core2 syntax, but widespread, matching not perfect due to possible earlier dots
basic_terms : basic_term (COMMA basic_terms)? ;
basic_term : ground_term | variable_term;
ground_term : /*SYMBOLIC_CONSTANT*/ ID | STRING | MINUS? NUMBER;
variable_term : VARIABLE | ANONYMOUS_VARIABLE;
answer_set : CURLY_OPEN classical_literal? (COMMA classical_literal)* CURLY_CLOSE;
answer_sets: answer_set*;
|
Revert "Revert "Enforcing commas in answer-set parsing. Minor comment adaption.""
|
Revert "Revert "Enforcing commas in answer-set parsing. Minor comment adaption.""
This reverts commit 173bdee9144afca0133a36b270a4210e4216ec36.
|
ANTLR
|
bsd-2-clause
|
AntoniusW/Alpha,alpha-asp/Alpha,alpha-asp/Alpha
|
fb32fa04370e7e50919f1b7ec5f8614e9ba1db09
|
src/main/antlr/YokohamaUnitParser.g4
|
src/main/antlr/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? clauses condition? STOP ;
clauses: clause (AND THAT? clause)* ;
clause: proposition (OR proposition)* ;
proposition: subject predicate ;
subject: quotedExpr | invokeExpr ;
predicate: isPredicate
| isNotPredicate
| throwsPredicate
| matchesPredicate
| doesNotMatchPredicate
;
isPredicate: IS matcher ;
isNotPredicate: IS NOT matcher ;
throwsPredicate: THROWS matcher ;
matchesPredicate: MATCHES pattern ;
doesNotMatchPredicate: DOES NOT MATCH pattern ;
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 ;
pattern: regexp ;
regexp: (RE_TICK | REGEX_TICK | REGEXP_TICK) Regexp BACK_TICK ;
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: singleBinding | choiceBinding | tableBinding ;
singleBinding: Identifier (EQ | IS) expr ;
choiceBinding: Identifier (EQ | IS) ANY_OF expr (COMMA expr)* (OR expr)? ;
tableBinding: Identifier (COMMA Identifier)* (EQ | IS) ANY_DEFINED_BY tableRef ;
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: letSingleBinding | letChoiceBinding | letTableBinding ;
letSingleBinding: Identifier (EQ | BE) expr ;
letChoiceBinding: Identifier (EQ | BE) ANY_OF expr (COMMA expr)* (OR expr)? ;
letTableBinding: Identifier (COMMA Identifier)* (EQ | BE) ANY_DEFINED_BY tableRef ;
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
| asExpr
;
quotedExpr: BACK_TICK Expr BACK_TICK ;
stubExpr: A_STUB_OF_BACK_TICK classType BACK_TICK ( SUCH THAT stubBehavior (AND stubBehavior)* )? ;
stubBehavior: stubReturns | stubThrows ;
stubReturns: METHOD_BACK_TICK methodPattern BACK_TICK RETURNS expr ;
stubThrows: METHOD_BACK_TICK methodPattern BACK_TICK THROWS 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
| resourceExpr
;
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 ;
asExpr: sourceExpr AS_BACK_TICK classType BACK_TICK ;
sourceExpr: stringExpr | anchorExpr ;
resourceExpr: RESOURCE stringExpr (AS_BACK_TICK classType BACK_TICK)? ;
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? clauses condition? STOP ;
clauses: clause (AND THAT? clause)* ;
clause: proposition (OR proposition)* ;
proposition: subject predicate ;
subject: quotedExpr | invokeExpr ;
predicate: isPredicate
| isNotPredicate
| throwsPredicate
| matchesPredicate
| doesNotMatchPredicate
;
isPredicate: IS matcher ;
isNotPredicate: IS NOT matcher ;
throwsPredicate: THROWS matcher ;
matchesPredicate: MATCHES pattern ;
doesNotMatchPredicate: DOES NOT MATCH pattern ;
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 ;
pattern: regexp ;
regexp: (RE_TICK | REGEX_TICK | REGEXP_TICK) Regexp BACK_TICK ;
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: singleBinding | choiceBinding | tableBinding ;
singleBinding: Identifier (EQ | IS) expr ;
choiceBinding: Identifier (EQ | IS) ANY_OF expr (COMMA expr)* (OR expr)? ;
tableBinding: Identifier (COMMA Identifier)* (EQ | IS) ANY_DEFINED_BY tableRef ;
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: letSingleBinding | letChoiceBinding | letTableBinding ;
letSingleBinding: Identifier (EQ | BE) expr ;
letChoiceBinding: Identifier (EQ | BE) ANY_OF expr (COMMA expr)* (OR expr)? ;
letTableBinding: Identifier (COMMA Identifier)* (EQ | BE) ANY_DEFINED_BY tableRef ;
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
| asExpr
;
quotedExpr: BACK_TICK Expr BACK_TICK ;
stubExpr: A_STUB_OF_BACK_TICK classType BACK_TICK ( SUCH THAT stubBehavior (AND stubBehavior)* )? ;
stubBehavior: stubReturns | stubThrows ;
stubReturns: METHOD_BACK_TICK methodPattern BACK_TICK RETURNS expr ;
stubThrows: METHOD_BACK_TICK methodPattern BACK_TICK THROWS 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
| resourceExpr
;
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 ;
asExpr: sourceExpr AS_BACK_TICK classType BACK_TICK ;
sourceExpr: stringExpr | anchorExpr ;
resourceExpr: RESOURCE DOUBLE_QUOTE Str DOUBLE_QUOTE (AS_BACK_TICK classType BACK_TICK)? ;
codeBlock: heading BACK_TICKS attributes CodeLine* BACK_TICKS ;
attributes: CodeLine ;
heading: HASHES Line ;
|
Embed `string` into resourceExpr instead of referring stringExpr
|
Embed `string` into resourceExpr instead of referring stringExpr
|
ANTLR
|
mit
|
tkob/yokohamaunit,tkob/yokohamaunit
|
2932258e2c6140e195d7a4cc4814c52656bbff6d
|
src/main/antlr4/YokohamaUnitLexer.g4
|
src/main/antlr4/YokohamaUnitLexer.g4
|
lexer grammar YokohamaUnitLexer;
HASH1: '#' ;
HASH2: '##' ;
HASH3: '###' ;
HASH4: '####' ;
HASH5: '#####' ;
HASH6: '######' ;
TEST: 'Test:' -> mode(TEST_LEADING);
TABLECAPTION: '[' -> skip, mode(TABLE_NAME);
SETUP: 'Setup' -> mode(PHASE_LEADING);
EXERCISE: 'Exercise' -> mode(PHASE_LEADING);
VERIFY: 'Verify' -> mode(PHASE_LEADING);
TEARDOWN: 'Teardown' -> mode(PHASE_LEADING);
BAR: '|' -> mode(IN_TABLE_HEADER) ;
STARLBRACKET: '*[' -> skip, mode(ABBREVIATION);
ASSERT: 'Assert' -> mode(IN_THE_MIDDLE_OF_LINE) ;
THAT: 'that' -> mode(IN_THE_MIDDLE_OF_LINE) ;
STOP: '.' -> mode(IN_THE_MIDDLE_OF_LINE) ;
AND: 'and' -> mode(IN_THE_MIDDLE_OF_LINE) ;
IS: 'is' -> mode(IN_THE_MIDDLE_OF_LINE) ;
NOT: 'not' -> mode(IN_THE_MIDDLE_OF_LINE) ;
THROWS: 'throws' -> mode(IN_THE_MIDDLE_OF_LINE) ;
FOR: 'for' -> mode(IN_THE_MIDDLE_OF_LINE) ;
ALL: 'all' -> mode(IN_THE_MIDDLE_OF_LINE) ;
COMMA: ',' -> mode(IN_THE_MIDDLE_OF_LINE) ;
RULES: 'rules' -> mode(IN_THE_MIDDLE_OF_LINE) ;
IN: 'in' -> mode(IN_THE_MIDDLE_OF_LINE) ;
UTABLE: 'Table' -> mode(AFTER_TABLE) ;
CSV: 'CSV' -> mode(AFTER_CSV) ;
TSV: 'TSV' -> mode(AFTER_CSV) ;
EXCEL: 'Excel' -> mode(AFTER_EXCEL) ;
WHERE: 'where' -> mode(IN_THE_MIDDLE_OF_LINE) ;
EQ: '=' -> mode(IN_THE_MIDDLE_OF_LINE) ;
LET: 'Let' -> mode(IN_THE_MIDDLE_OF_LINE) ;
BE: 'be' -> mode(IN_THE_MIDDLE_OF_LINE) ;
DO: 'Do' -> mode(IN_THE_MIDDLE_OF_LINE) ;
A_STUB_OF: 'a' [ \t\r\n]+ 'stub' [ \t\r\n]+ 'of' -> mode(EXPECT_CLASS) ;
SUCH: 'such' -> mode(IN_THE_MIDDLE_OF_LINE) ;
METHOD: 'method' -> mode(AFTER_METHOD) ;
RETURNS: 'returns' -> mode(IN_THE_MIDDLE_OF_LINE) ;
AN_INSTANCE_OF: 'an' [ \t\r\n]+ 'instance' [ \t\r\n] 'of' -> mode(EXPECT_CLASS) ;
AN_INSTANCE: 'an' [ \t\r\n]+ 'instance' -> mode(AFTER_AN_INSTANCE) ;
AN_INVOCATION_OF: 'an' [ \t\r\n]+ 'invocation' [ \t\r\n] 'of' -> mode(AFTER_METHOD) ;
NULL: 'null' -> mode(IN_THE_MIDDLE_OF_LINE) ;
NOTHING: 'nothing' -> mode(IN_THE_MIDDLE_OF_LINE) ;
Identifier: IdentStart IdentPart* -> mode(IN_THE_MIDDLE_OF_LINE) ;
Integer: IntegerLiteral -> mode(IN_THE_MIDDLE_OF_LINE) ;
FloatingPoint: FloatingPointLiteral -> mode(IN_THE_MIDDLE_OF_LINE) ;
MINUS: '-' -> mode(IN_THE_MIDDLE_OF_LINE) ;
OPENBACKTICK: '`' -> skip, mode(IN_BACKTICK) ;
OPENDOUBLEQUOTE: '"' -> skip, mode(IN_DOUBLEQUOTE) ;
NEW_LINE : ('\r'? '\n')+ -> skip ;
WS : [ \t]+ -> skip ;
mode IN_THE_MIDDLE_OF_LINE;
ASSERT2: 'Assert' -> type(ASSERT) ;
THAT2: 'that' -> type(THAT) ;
STOP2: '.' -> type(STOP) ;
AND2: 'and' -> type(AND) ;
IS2: 'is' -> type(IS) ;
NOT2: 'not' -> type(NOT) ;
THROWS2: 'throws' -> type(THROWS) ;
FOR2: 'for' -> type(FOR) ;
ALL2: 'all' -> type(ALL) ;
RULES2: 'rules' -> type(RULES) ;
COMMA2: ',' -> type(COMMA);
IN2: 'in' -> type(IN) ;
UTABLE2: 'Table' -> type(UTABLE), mode(AFTER_TABLE) ;
CSV2: 'CSV' -> type(CSV), mode(AFTER_CSV) ;
TSV2: 'TSV' -> type(TSV), mode(AFTER_CSV) ;
EXCEL2: 'Excel' -> type(EXCEL), mode(AFTER_EXCEL) ;
WHERE2: 'where' -> type(WHERE) ;
EQ2: '=' -> type(EQ) ;
LET2: 'Let' -> type(LET) ;
BE2: 'be' -> type(BE) ;
DO2: 'Do' -> type(DO) ;
A_STUB_OF2: 'a' [ \t\r\n]+ 'stub' [ \t\r\n]+ 'of' -> type(A_STUB_OF), mode(EXPECT_CLASS) ;
SUCH2: 'such' -> type(SUCH) ;
METHOD2: 'method' -> type(METHOD), mode(AFTER_METHOD) ;
RETURNS2: 'returns' -> type(RETURNS) ;
AN_INSTANCE_OF2: 'an' [ \t\r\n]+ 'instance' [ \t\r\n] 'of' -> type(AN_INSTANCE_OF), mode(EXPECT_CLASS) ;
AN_INSTANCE2: 'an' [ \t\r\n]+ 'instance' -> type(AN_INSTANCE), mode(AFTER_AN_INSTANCE) ;
AN_INVOCATION_OF2: 'an' [ \t\r\n]+ 'invocation' [ \t\r\n] 'of' -> type(AN_INVOCATION_OF), mode(AFTER_METHOD) ;
NULL2: 'null' -> type(NULL) ;
NOTHING2: 'nothing' -> type(NOTHING) ;
Identifier2 : IdentStart IdentPart* -> type(Identifier);
Integer2: IntegerLiteral -> type(Integer);
FloatingPoint2: FloatingPointLiteral -> type(FloatingPoint);
MINUS2: '-' -> type(MINUS) ;
OPENBACKTICK2: '`' -> skip, mode(IN_BACKTICK) ;
OPENDOUBLEQUOTE2: '"' -> skip, mode(IN_DOUBLEQUOTE) ;
NEW_LINE2 : ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
WS2 : [ \t]+ -> skip ;
mode TEST_LEADING;
WS3: [ \t]+ -> skip, mode(TEST_NAME);
mode TEST_NAME;
TestName: ~[\r\n]+ ;
NEW_LINE_TESTNAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
mode TABLE_NAME;
TableName: ~[\]\r\n]+ ;
EXIT_TABLENAME: ']' [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
mode PHASE_LEADING;
COLON: ':' [ \t]* -> skip, mode(PHASE_DESCRIPTION) ;
WS5: [ \t]* '\r'? '\n' -> skip, mode(DEFAULT_MODE) ;
mode PHASE_DESCRIPTION;
PhaseDescription: ~[\r\n]+ ;
NEW_LINE_PHASE: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
mode IN_DOUBLEQUOTE;
Quoted: ~["]+ ;
CLOSEDOUBLEQUOTE: '"' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode IN_BACKTICK;
Expr: ~[`]+ /*-> type(Expr)*/ ;
CLOSEBACKTICK: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode IN_TABLE_HEADER;
IDENTHEADER: IdentStart IdentPart* -> type(Identifier) ;
BARH: '|' -> type(BAR) ;
NEWLINE: '\r'? '\n' -> mode(IN_TABLE_ONSET) ;
SPACETAB: [ \t]+ -> skip ;
mode IN_TABLE_CELL;
ExprCell: ~[|\r\n]+ -> type(Expr) ;
BARCELL: '|' -> type(BAR) ;
NEWLINECELL: '\r'? '\n' -> type(NEWLINE), mode(IN_TABLE_ONSET) ;
SPACETABCELL: [ \t]+ -> skip ;
mode IN_TABLE_ONSET;
HBAR: [|\-=\:\.\+ \t]+ '\r'? '\n' ;
BARONSET: '|' -> type(BAR), mode(IN_TABLE_CELL) ;
TABLECAPTION2: '[' -> skip, mode(TABLE_NAME);
SPACETAB2: [ \t]+ -> skip ;
NEWLINEONSET: '\r'?'\n' -> skip, mode(DEFAULT_MODE) ;
mode AFTER_METHOD;
OPENBACKTICK3: '`' -> skip, mode(METHOD_PATTERN) ;
SPACETABNEWLINE: [ \t\r\n]+ -> skip ;
mode METHOD_PATTERN;
BOOLEAN: 'boolean' ;
BYTE: 'byte' ;
SHORT: 'short' ;
INT: 'int' ;
LONG: 'long' ;
CHAR: 'char' ;
FLOAT: 'float' ;
DOUBLE: 'double' ;
COMMA3: ',' -> type(COMMA);
THREEDOTS: '...' ;
DOT: '.' ;
LPAREN: '(' ;
RPAREN: ')' ;
LBRACKET: '[' ;
RBRACKET: ']' ;
Identifier3 : IdentStart IdentPart* -> type(Identifier);
SPACETABNEWLINE2: [ \t\r\n]+ -> skip ;
CLOSEBACKTICK2: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode EXPECT_CLASS;
OPENBACKTICK4: '`' -> skip, mode(CLASS) ;
SPACETABNEWLINE3: [ \t\r\n]+ -> skip ;
mode CLASS;
DOT2: '.' -> type(DOT) ;
Identifier4 : IdentStart IdentPart* -> type(Identifier) ;
SPACETABNEWLINE4: [ \t\r\n]+ -> skip ;
CLOSEBACKTICK3: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode AFTER_AN_INSTANCE;
OF: 'of' ;
Identifier5 : IdentStart IdentPart* -> type(Identifier) ;
OPENBACKTICK5: '`' -> skip, mode(CLASS) ;
SPACETABNEWLINE5: [ \t\r\n]+ -> skip ;
mode AFTER_TABLE;
LBRACKET2: '[' -> skip, mode(IN_TABLE_NAME) ;
SPACETABNEWLINE6: [ \t\r\n]+ -> skip ;
mode AFTER_CSV;
OPENSINGLEQUOTE2: '\'' -> skip, mode(IN_FILE_NAME) ;
SPACETABNEWLINE7: [ \t\r\n]+ -> skip ;
mode AFTER_EXCEL;
OPENSINGLEQUOTE3: '\'' -> skip, mode(IN_BOOK_NAME) ;
SPACETABNEWLINE8: [ \t\r\n]+ -> skip ;
mode IN_TABLE_NAME;
SingleQuoteName: ~[\]\r\n]* ;
RBRACKET2: ']' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode IN_FILE_NAME;
SingleQuoteName2: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ;
CLOSESINGLEQUOTE2: '\'' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode IN_BOOK_NAME;
SingleQuoteName3: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ;
CLOSESINGLEQUOTE3: '\'' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode ABBREVIATION;
ShortName: ~[\]\r\n]* ;
RBRACKETCOLON: ']:' [ \t\r\n]* -> skip, mode(LONG_NAME) ;
mode LONG_NAME;
LongName: ~[\r\n]* ;
EXIT_LONG_NAME: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
fragment
IdentStart: ~[\uD800-\uDBFF]
{Character.isJavaIdentifierStart(_input.LA(-1))}?
| [\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
fragment
IdentPart: ~[\uD800-\uDBFF]
{Character.isJavaIdentifierPart(_input.LA(-1))}?
| [\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
fragment
IntegerLiteral: DecimalIntegerLiteral
| HexIntegerLiteral
| OctalIntegerLiteral
| BinaryIntegerLiteral
;
fragment
DecimalIntegerLiteral: DecimalNumeral IntegerTypeSuffix? ;
fragment
HexIntegerLiteral: HexNumeral IntegerTypeSuffix? ;
fragment
OctalIntegerLiteral: OctalNumeral IntegerTypeSuffix? ;
fragment
BinaryIntegerLiteral: BinaryNumeral IntegerTypeSuffix? ;
fragment
IntegerTypeSuffix: [lL] ;
fragment
DecimalNumeral: '0' | [1-9] ([_0-9]* [0-9])? ;
fragment
HexNumeral: '0' [xX] HexDigits ;
fragment
HexDigits: [0-9a-fA-F] ([_0-9a-fA-F]* [0-9a-fA-F])? ;
fragment
OctalNumeral: '0' [_0-7]* [0-7] ;
fragment
BinaryNumeral: '0' [bB] [01] ([_01]* [01])? ;
fragment
FloatingPointLiteral: DecimalFloatingPointLiteral
| HexadecimalFloatingPointLiteral
;
fragment
DecimalFloatingPointLiteral: Digits '.' Digits ExponentPart? FloatTypeSuffix?
| Digits '.' ExponentPart FloatTypeSuffix?
| Digits '.' ExponentPart? FloatTypeSuffix
/* the above rules differ from the Java spec:
fp literals which end with dot are not allowd */
| '.' Digits ExponentPart? FloatTypeSuffix?
| Digits ExponentPart FloatTypeSuffix?
| Digits ExponentPart? FloatTypeSuffix
;
fragment
Digits: [0-9] ([_0-9]* [0-9])? ;
fragment
ExponentPart: [eE] SignedInteger ;
fragment
SignedInteger: ('+' | '-')? Digits ;
fragment
FloatTypeSuffix: [fFdD] ;
fragment
HexadecimalFloatingPointLiteral: HexSignificand BinaryExponent FloatTypeSuffix? ;
fragment
HexSignificand: HexNumeral '.'?
| '0' [xX] HexDigits? . HexDigits
;
fragment
BinaryExponent: [pP] SignedInteger ;
|
lexer grammar YokohamaUnitLexer;
HASH1: '#' ;
HASH2: '##' ;
HASH3: '###' ;
HASH4: '####' ;
HASH5: '#####' ;
HASH6: '######' ;
TEST: 'Test:' -> mode(TEST_LEADING);
TABLECAPTION: '[' -> skip, mode(TABLE_NAME);
SETUP: 'Setup' -> mode(PHASE_LEADING);
EXERCISE: 'Exercise' -> mode(PHASE_LEADING);
VERIFY: 'Verify' -> mode(PHASE_LEADING);
TEARDOWN: 'Teardown' -> mode(PHASE_LEADING);
BAR: '|' -> mode(IN_TABLE_HEADER) ;
STARLBRACKET: '*[' -> skip, mode(ABBREVIATION);
ASSERT: 'Assert' -> mode(IN_THE_MIDDLE_OF_LINE) ;
THAT: 'that' -> mode(IN_THE_MIDDLE_OF_LINE) ;
STOP: '.' -> mode(IN_THE_MIDDLE_OF_LINE) ;
AND: 'and' -> mode(IN_THE_MIDDLE_OF_LINE) ;
IS: 'is' -> mode(IN_THE_MIDDLE_OF_LINE) ;
NOT: 'not' -> mode(IN_THE_MIDDLE_OF_LINE) ;
THROWS: 'throws' -> mode(IN_THE_MIDDLE_OF_LINE) ;
FOR: 'for' -> mode(IN_THE_MIDDLE_OF_LINE) ;
ALL: 'all' -> mode(IN_THE_MIDDLE_OF_LINE) ;
COMMA: ',' -> mode(IN_THE_MIDDLE_OF_LINE) ;
RULES: 'rules' -> mode(IN_THE_MIDDLE_OF_LINE) ;
IN: 'in' -> mode(IN_THE_MIDDLE_OF_LINE) ;
UTABLE: 'Table' -> mode(AFTER_TABLE) ;
CSV: 'CSV' -> mode(AFTER_CSV) ;
TSV: 'TSV' -> mode(AFTER_CSV) ;
EXCEL: 'Excel' -> mode(AFTER_EXCEL) ;
WHERE: 'where' -> mode(IN_THE_MIDDLE_OF_LINE) ;
EQ: '=' -> mode(IN_THE_MIDDLE_OF_LINE) ;
LET: 'Let' -> mode(IN_THE_MIDDLE_OF_LINE) ;
BE: 'be' -> mode(IN_THE_MIDDLE_OF_LINE) ;
DO: 'Do' -> mode(IN_THE_MIDDLE_OF_LINE) ;
A_STUB_OF: 'a' [ \t\r\n]+ 'stub' [ \t\r\n]+ 'of' -> mode(EXPECT_CLASS) ;
SUCH: 'such' -> mode(IN_THE_MIDDLE_OF_LINE) ;
METHOD: 'method' -> mode(AFTER_METHOD) ;
RETURNS: 'returns' -> mode(IN_THE_MIDDLE_OF_LINE) ;
AN_INSTANCE_OF: 'an' [ \t\r\n]+ 'instance' [ \t\r\n] 'of' -> mode(EXPECT_CLASS) ;
AN_INSTANCE: 'an' [ \t\r\n]+ 'instance' -> mode(AFTER_AN_INSTANCE) ;
AN_INVOCATION_OF: 'an' [ \t\r\n]+ 'invocation' [ \t\r\n] 'of' -> mode(AFTER_METHOD) ;
NULL: 'null' -> mode(IN_THE_MIDDLE_OF_LINE) ;
NOTHING: 'nothing' -> mode(IN_THE_MIDDLE_OF_LINE) ;
TRUE: 'true' -> mode(IN_THE_MIDDLE_OF_LINE) ;
FALSE: 'false' -> mode(IN_THE_MIDDLE_OF_LINE) ;
Identifier: IdentStart IdentPart* -> mode(IN_THE_MIDDLE_OF_LINE) ;
Integer: IntegerLiteral -> mode(IN_THE_MIDDLE_OF_LINE) ;
FloatingPoint: FloatingPointLiteral -> mode(IN_THE_MIDDLE_OF_LINE) ;
MINUS: '-' -> mode(IN_THE_MIDDLE_OF_LINE) ;
OPENBACKTICK: '`' -> skip, mode(IN_BACKTICK) ;
OPENDOUBLEQUOTE: '"' -> skip, mode(IN_DOUBLEQUOTE) ;
NEW_LINE : ('\r'? '\n')+ -> skip ;
WS : [ \t]+ -> skip ;
mode IN_THE_MIDDLE_OF_LINE;
ASSERT2: 'Assert' -> type(ASSERT) ;
THAT2: 'that' -> type(THAT) ;
STOP2: '.' -> type(STOP) ;
AND2: 'and' -> type(AND) ;
IS2: 'is' -> type(IS) ;
NOT2: 'not' -> type(NOT) ;
THROWS2: 'throws' -> type(THROWS) ;
FOR2: 'for' -> type(FOR) ;
ALL2: 'all' -> type(ALL) ;
RULES2: 'rules' -> type(RULES) ;
COMMA2: ',' -> type(COMMA);
IN2: 'in' -> type(IN) ;
UTABLE2: 'Table' -> type(UTABLE), mode(AFTER_TABLE) ;
CSV2: 'CSV' -> type(CSV), mode(AFTER_CSV) ;
TSV2: 'TSV' -> type(TSV), mode(AFTER_CSV) ;
EXCEL2: 'Excel' -> type(EXCEL), mode(AFTER_EXCEL) ;
WHERE2: 'where' -> type(WHERE) ;
EQ2: '=' -> type(EQ) ;
LET2: 'Let' -> type(LET) ;
BE2: 'be' -> type(BE) ;
DO2: 'Do' -> type(DO) ;
A_STUB_OF2: 'a' [ \t\r\n]+ 'stub' [ \t\r\n]+ 'of' -> type(A_STUB_OF), mode(EXPECT_CLASS) ;
SUCH2: 'such' -> type(SUCH) ;
METHOD2: 'method' -> type(METHOD), mode(AFTER_METHOD) ;
RETURNS2: 'returns' -> type(RETURNS) ;
AN_INSTANCE_OF2: 'an' [ \t\r\n]+ 'instance' [ \t\r\n] 'of' -> type(AN_INSTANCE_OF), mode(EXPECT_CLASS) ;
AN_INSTANCE2: 'an' [ \t\r\n]+ 'instance' -> type(AN_INSTANCE), mode(AFTER_AN_INSTANCE) ;
AN_INVOCATION_OF2: 'an' [ \t\r\n]+ 'invocation' [ \t\r\n] 'of' -> type(AN_INVOCATION_OF), mode(AFTER_METHOD) ;
NULL2: 'null' -> type(NULL) ;
NOTHING2: 'nothing' -> type(NOTHING) ;
TRUE2: 'true' -> type(TRUE) ;
FALSE2: 'false' -> type(FALSE) ;
Identifier2 : IdentStart IdentPart* -> type(Identifier);
Integer2: IntegerLiteral -> type(Integer);
FloatingPoint2: FloatingPointLiteral -> type(FloatingPoint);
MINUS2: '-' -> type(MINUS) ;
OPENBACKTICK2: '`' -> skip, mode(IN_BACKTICK) ;
OPENDOUBLEQUOTE2: '"' -> skip, mode(IN_DOUBLEQUOTE) ;
NEW_LINE2 : ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
WS2 : [ \t]+ -> skip ;
mode TEST_LEADING;
WS3: [ \t]+ -> skip, mode(TEST_NAME);
mode TEST_NAME;
TestName: ~[\r\n]+ ;
NEW_LINE_TESTNAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
mode TABLE_NAME;
TableName: ~[\]\r\n]+ ;
EXIT_TABLENAME: ']' [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
mode PHASE_LEADING;
COLON: ':' [ \t]* -> skip, mode(PHASE_DESCRIPTION) ;
WS5: [ \t]* '\r'? '\n' -> skip, mode(DEFAULT_MODE) ;
mode PHASE_DESCRIPTION;
PhaseDescription: ~[\r\n]+ ;
NEW_LINE_PHASE: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
mode IN_DOUBLEQUOTE;
Quoted: ~["]+ ;
CLOSEDOUBLEQUOTE: '"' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode IN_BACKTICK;
Expr: ~[`]+ /*-> type(Expr)*/ ;
CLOSEBACKTICK: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode IN_TABLE_HEADER;
IDENTHEADER: IdentStart IdentPart* -> type(Identifier) ;
BARH: '|' -> type(BAR) ;
NEWLINE: '\r'? '\n' -> mode(IN_TABLE_ONSET) ;
SPACETAB: [ \t]+ -> skip ;
mode IN_TABLE_CELL;
ExprCell: ~[|\r\n]+ -> type(Expr) ;
BARCELL: '|' -> type(BAR) ;
NEWLINECELL: '\r'? '\n' -> type(NEWLINE), mode(IN_TABLE_ONSET) ;
SPACETABCELL: [ \t]+ -> skip ;
mode IN_TABLE_ONSET;
HBAR: [|\-=\:\.\+ \t]+ '\r'? '\n' ;
BARONSET: '|' -> type(BAR), mode(IN_TABLE_CELL) ;
TABLECAPTION2: '[' -> skip, mode(TABLE_NAME);
SPACETAB2: [ \t]+ -> skip ;
NEWLINEONSET: '\r'?'\n' -> skip, mode(DEFAULT_MODE) ;
mode AFTER_METHOD;
OPENBACKTICK3: '`' -> skip, mode(METHOD_PATTERN) ;
SPACETABNEWLINE: [ \t\r\n]+ -> skip ;
mode METHOD_PATTERN;
BOOLEAN: 'boolean' ;
BYTE: 'byte' ;
SHORT: 'short' ;
INT: 'int' ;
LONG: 'long' ;
CHAR: 'char' ;
FLOAT: 'float' ;
DOUBLE: 'double' ;
COMMA3: ',' -> type(COMMA);
THREEDOTS: '...' ;
DOT: '.' ;
LPAREN: '(' ;
RPAREN: ')' ;
LBRACKET: '[' ;
RBRACKET: ']' ;
Identifier3 : IdentStart IdentPart* -> type(Identifier);
SPACETABNEWLINE2: [ \t\r\n]+ -> skip ;
CLOSEBACKTICK2: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode EXPECT_CLASS;
OPENBACKTICK4: '`' -> skip, mode(CLASS) ;
SPACETABNEWLINE3: [ \t\r\n]+ -> skip ;
mode CLASS;
DOT2: '.' -> type(DOT) ;
Identifier4 : IdentStart IdentPart* -> type(Identifier) ;
SPACETABNEWLINE4: [ \t\r\n]+ -> skip ;
CLOSEBACKTICK3: '`' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode AFTER_AN_INSTANCE;
OF: 'of' ;
Identifier5 : IdentStart IdentPart* -> type(Identifier) ;
OPENBACKTICK5: '`' -> skip, mode(CLASS) ;
SPACETABNEWLINE5: [ \t\r\n]+ -> skip ;
mode AFTER_TABLE;
LBRACKET2: '[' -> skip, mode(IN_TABLE_NAME) ;
SPACETABNEWLINE6: [ \t\r\n]+ -> skip ;
mode AFTER_CSV;
OPENSINGLEQUOTE2: '\'' -> skip, mode(IN_FILE_NAME) ;
SPACETABNEWLINE7: [ \t\r\n]+ -> skip ;
mode AFTER_EXCEL;
OPENSINGLEQUOTE3: '\'' -> skip, mode(IN_BOOK_NAME) ;
SPACETABNEWLINE8: [ \t\r\n]+ -> skip ;
mode IN_TABLE_NAME;
SingleQuoteName: ~[\]\r\n]* ;
RBRACKET2: ']' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode IN_FILE_NAME;
SingleQuoteName2: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ;
CLOSESINGLEQUOTE2: '\'' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode IN_BOOK_NAME;
SingleQuoteName3: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ;
CLOSESINGLEQUOTE3: '\'' -> skip, mode(IN_THE_MIDDLE_OF_LINE) ;
mode ABBREVIATION;
ShortName: ~[\]\r\n]* ;
RBRACKETCOLON: ']:' [ \t\r\n]* -> skip, mode(LONG_NAME) ;
mode LONG_NAME;
LongName: ~[\r\n]* ;
EXIT_LONG_NAME: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ;
fragment
IdentStart: ~[\uD800-\uDBFF]
{Character.isJavaIdentifierStart(_input.LA(-1))}?
| [\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
fragment
IdentPart: ~[\uD800-\uDBFF]
{Character.isJavaIdentifierPart(_input.LA(-1))}?
| [\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
fragment
IntegerLiteral: DecimalIntegerLiteral
| HexIntegerLiteral
| OctalIntegerLiteral
| BinaryIntegerLiteral
;
fragment
DecimalIntegerLiteral: DecimalNumeral IntegerTypeSuffix? ;
fragment
HexIntegerLiteral: HexNumeral IntegerTypeSuffix? ;
fragment
OctalIntegerLiteral: OctalNumeral IntegerTypeSuffix? ;
fragment
BinaryIntegerLiteral: BinaryNumeral IntegerTypeSuffix? ;
fragment
IntegerTypeSuffix: [lL] ;
fragment
DecimalNumeral: '0' | [1-9] ([_0-9]* [0-9])? ;
fragment
HexNumeral: '0' [xX] HexDigits ;
fragment
HexDigits: [0-9a-fA-F] ([_0-9a-fA-F]* [0-9a-fA-F])? ;
fragment
OctalNumeral: '0' [_0-7]* [0-7] ;
fragment
BinaryNumeral: '0' [bB] [01] ([_01]* [01])? ;
fragment
FloatingPointLiteral: DecimalFloatingPointLiteral
| HexadecimalFloatingPointLiteral
;
fragment
DecimalFloatingPointLiteral: Digits '.' Digits ExponentPart? FloatTypeSuffix?
| Digits '.' ExponentPart FloatTypeSuffix?
| Digits '.' ExponentPart? FloatTypeSuffix
/* the above rules differ from the Java spec:
fp literals which end with dot are not allowd */
| '.' Digits ExponentPart? FloatTypeSuffix?
| Digits ExponentPart FloatTypeSuffix?
| Digits ExponentPart? FloatTypeSuffix
;
fragment
Digits: [0-9] ([_0-9]* [0-9])? ;
fragment
ExponentPart: [eE] SignedInteger ;
fragment
SignedInteger: ('+' | '-')? Digits ;
fragment
FloatTypeSuffix: [fFdD] ;
fragment
HexadecimalFloatingPointLiteral: HexSignificand BinaryExponent FloatTypeSuffix? ;
fragment
HexSignificand: HexNumeral '.'?
| '0' [xX] HexDigits? . HexDigits
;
fragment
BinaryExponent: [pP] SignedInteger ;
|
Add boolean literals to the lexer
|
Add boolean literals to the lexer
|
ANTLR
|
mit
|
tkob/yokohamaunit,tkob/yokohamaunit
|
057ed71e12fb68b5ae211b4e6e6e7c12ee62ee04
|
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;
grantSystemPrivileges
: systemObjects TO (granteeClause | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)?
;
systemObjects
: systemObject(COMMA systemObject)*
;
systemObject
: ALL PRIVILEGES
| roleName
| systemPrivilege
;
systemPrivilege
: ID *?
;
granteeClause
: grantee (COMMA grantee)
;
grantee
: userName
| roleName
| PUBLIC
;
granteeIdentifiedBy
: userName (COMMA userName)* IDENTIFIED BY STRING (COMMA STRING)*
;
grantObjectPrivileges
: objectPrivilege (COMMA objectPrivilege)*
;
grantObjectPrivilege
: (objectPrivilege | ALL PRIVILEGES?)( LEFT_PAREN columnName (COMMA columnName)* RIGHT_PAREN)?
;
objectPrivilege
: ID *?
;
grantRolesToPrograms
: roleName (COMMA roleName)* TO programUnit ( COMMA programUnit )*
;
programUnit
: (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID
;
|
grammar OracleDCLStatement;
import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol;
grant
: GRANT
(
(grantSystemPrivileges | grantObjectPrivileges) (CONTAINER EQ_OR_ASSIGN (CURRENT | ALL))?
| grantRolesToPrograms
)
;
grantSystemPrivileges
: systemObjects TO (granteeClause | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)?
;
systemObjects
: systemObject(COMMA systemObject)*
;
systemObject
: ALL PRIVILEGES
| roleName
| systemPrivilege
;
systemPrivilege
: ID *?
;
granteeClause
: grantee (COMMA grantee)
;
grantee
: userName
| roleName
| PUBLIC
;
granteeIdentifiedBy
: userName (COMMA userName)* IDENTIFIED BY STRING (COMMA STRING)*
;
grantObjectPrivileges
: objectPrivilege (COMMA objectPrivilege)*
;
grantObjectPrivilege
: (objectPrivilege | ALL PRIVILEGES?)( LEFT_PAREN columnName (COMMA columnName)* RIGHT_PAREN)?
;
objectPrivilege
: ID *?
;
grantRolesToPrograms
: roleName (COMMA roleName)* TO programUnit ( COMMA programUnit )*
;
programUnit
: (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID
;
|
add grant
|
add grant
|
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
|
5a4d65dae7b44fb111ef829cee58e5d2a705c356
|
src/antlr/clj/alphabet.g4
|
src/antlr/clj/alphabet.g4
|
lexer grammar alphabet;
fragment LETTER
: [a-zA-Z]
| // 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
DIGIT
: '0'
| NonZeroDigit
;
fragment
NonZeroDigit
: [1-9]
;
SLASH : '/' ;
LPAREN : '(' ;
RPAREN : ')' ;
LBRACK : '[' ;
RBRACK : ']' ;
LBRACE : '{' ;
RBRACE : '}' ;
// DELIM : '(' | ')' | '[' | ']' | '{' | '}' ;
|
lexer grammar alphabet;
fragment LETTER
: [a-zA-Z]
| // 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)))}?
;
// use of fragments below forces lexer to pass token rather than char
// literal, e.g. LPAREN instead of '(' . This makes token lists easier
// to handle, since ' is special in Clojure.
fragment SLASH_FRAG : '/' ;
SLASH : SLASH_FRAG ;
fragment LPAREN_FRAG : '(' ;
LPAREN : LPAREN_FRAG ;
fragment RPAREN_FRAG : ')' ;
RPAREN : RPAREN_FRAG ;
fragment LBRACK_FRAG : '[' ;
LBRACK : LBRACK_FRAG ;
fragment RBRACK_FRAG : ']' ;
RBRACK : RBRACK_FRAG ;
fragment LBRACE_FRAG : '{' ;
LBRACE : LBRACE_FRAG ;
fragment RBRACE_FRAG : '}' ;
RBRACE : RBRACE_FRAG ;
// DELIM : '(' | ')' | '[' | ']' | '{' | '}' ;
fragment
DIGIT
: '0'
| NonZeroDigit
;
fragment
NonZeroDigit
: [1-9]
;
|
use fragment to force emission of tokens not chars
|
use fragment to force emission of tokens not chars
|
ANTLR
|
epl-1.0
|
mobileink/lab.clj.antlr,mobileink/lab.antlr
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.