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
|
---|---|---|---|---|---|---|---|---|---|
736f81413da3017c1c53f25334a324f513629235
|
sharding-core/src/main/antlr4/imports/PostgreAlterTable.g4
|
sharding-core/src/main/antlr4/imports/PostgreAlterTable.g4
|
grammar PostgreAlterTable;
import PostgreKeyword, DataType, Keyword, PostgreBase, BaseRule, Symbol;
alterTable
: alterTableNameWithAsterisk (alterTableActions| renameColumn | renameConstraint)
| alterTableNameExists renameTable
;
alterTableNameWithAsterisk
: ALTER TABLE (IF EXISTS)? ONLY? tableName ASTERISK?
;
alterTableOp
: ALTER TABLE
;
alterTableActions
: alterTableAction (COMMA alterTableAction)*
;
alterTableAction
: addColumn
| dropColumn
| modifyColumn
| alterTableAddConstraint
| ALTER CONSTRAINT constraintName constraintOptionalParam
| VALIDATE CONSTRAINT constraintName
| DROP CONSTRAINT (IF EXISTS)? constraintName (RESTRICT | CASCADE)?
| INHERIT tableName
| NO INHERIT tableName
| REPLICA IDENTITY (DEFAULT | USING INDEX indexName | FULL | NOTHING)
;
tableConstraintUsingIndex
: (CONSTRAINT constraintName)?
(UNIQUE | primaryKey) USING INDEX indexName
constraintOptionalParam
;
constraintOptionalParam
: (NOT? DEFERRABLE)? (INITIALLY (DEFERRED |IMMEDIATE))?
;
addColumn
: ADD COLUMN? (IF NOT EXISTS )? columnDefinition
;
dropColumn
: DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)?
;
modifyColumn
: alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)?
;
alterColumn
: ALTER COLUMN? columnName
;
alterTableAddConstraint
: ADD tableConstraint (NOT VALID)?
| ADD tableConstraintUsingIndex
;
renameColumn
: RENAME COLUMN? columnName TO columnName
;
renameConstraint
: RENAME CONSTRAINT constraintName TO constraintName
;
alterTableNameExists
: alterTableOp (IF EXISTS)? tableName
;
renameTable
: RENAME TO tableName
;
|
grammar PostgreAlterTable;
import PostgreKeyword, DataType, Keyword, PostgreBase, BaseRule, Symbol;
alterTable
: alterTableNameWithAsterisk (alterTableActions | renameColumn | renameConstraint)
| alterTableNameExists renameTable
;
alterTableNameWithAsterisk
: ALTER TABLE (IF EXISTS)? ONLY? tableName ASTERISK?
;
alterTableOp
: ALTER TABLE
;
alterTableActions
: alterTableAction (COMMA alterTableAction)*
;
alterTableAction
: addColumn
| dropColumn
| modifyColumn
| alterTableAddConstraint
| ALTER CONSTRAINT constraintName constraintOptionalParam
| VALIDATE CONSTRAINT constraintName
| DROP CONSTRAINT (IF EXISTS)? constraintName (RESTRICT | CASCADE)?
| (DISABLE |ENABLE) TRIGGER (triggerName | ALL | USER )?
| ENABLE (REPLICA | ALWAYS) TRIGGER triggerName
| (DISABLE | ENABLE) RULE rewriteRuleName
| ENABLE (REPLICA | ALWAYS) RULE rewriteRuleName
| (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY
| CLUSTER ON indexName
| SET WITHOUT CLUSTER
| SET (WITH | WITHOUT) OIDS
| SET TABLESPACE tablespaceName
| SET (LOGGED | UNLOGGED)
| SET LEFT_PAREN storageParameterWithValue (COMMA storageParameterWithValue)* RIGHT_PAREN
| RESET LEFT_PAREN storageParameter (COMMA storageParameter)* RIGHT_PAREN
| INHERIT tableName
| NO INHERIT tableName
| OF typeName
| NOT OF
| OWNER TO (ownerName | CURRENT_USER | SESSION_USER)
| REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING)
;
tableConstraintUsingIndex
: (CONSTRAINT constraintName)?
(UNIQUE | primaryKey) USING INDEX indexName
constraintOptionalParam
;
constraintOptionalParam
: (NOT? DEFERRABLE)? (INITIALLY (DEFERRED |IMMEDIATE))?
;
addColumn
: ADD COLUMN? (IF NOT EXISTS )? columnDefinition
;
dropColumn
: DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)?
;
modifyColumn
: alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)?
| alterColumn SET DEFAULT expr
| alterColumn DROP DEFAULT
| alterColumn (SET | DROP) NOT NULL
| alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LEFT_PAREN sequenceOptions RIGHT_PAREN)?
| alterColumn alterColumnSetOption alterColumnSetOption*
| alterColumn DROP IDENTITY (IF EXISTS)?
| alterColumn SET STATISTICS NUMBER
| alterColumn SET LEFT_PAREN attributeOptions RIGHT_PAREN
| alterColumn RESET LEFT_PAREN attributeOptions RIGHT_PAREN
| alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN)
;
alterColumn
: ALTER COLUMN? columnName
;
alterColumnSetOption
: SET GENERATED (ALWAYS | BY DEFAULT)
| SET sequenceOption
| RESTART (WITH? NUMBER)?
;
attributeOptions
: attributeOption (COMMA attributeOption)*
;
attributeOption
: ID EQ_OR_ASSIGN simpleExpr
;
alterTableAddConstraint
: ADD tableConstraint (NOT VALID)?
| ADD tableConstraintUsingIndex
;
renameColumn
: RENAME COLUMN? columnName TO columnName
;
renameConstraint
: RENAME CONSTRAINT constraintName TO constraintName
;
storageParameterWithValue
: storageParameter EQ_OR_ASSIGN simpleExpr
;
storageParameter
: ID
;
alterTableNameExists
: alterTableOp (IF EXISTS)? tableName
;
renameTable
: RENAME TO tableName
;
|
improve postgre alter table
|
improve postgre alter table
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
|
73ebb7e85f46c28843e4aceaa8dee5a97aa0162a
|
sharding-core/src/main/antlr4/imports/MySQLTCLStatement.g4
|
sharding-core/src/main/antlr4/imports/MySQLTCLStatement.g4
|
grammar MySQLTCLStatement;
import MySQLKeyword, Keyword, DQLBase, BaseRule, DataType, Symbol;
setTransaction
: SET (GLOBAL | SESSION) TRANSACTION setTransactionCharacteristic (COMMA setTransactionCharacteristic)*
;
setTransactionCharacteristic
: ISOLATION LEVEL level| accessMode
;
level
: REPEATABLE READ | READ (COMMITTED | UNCOMMITTED) | SERIALIZABLE
;
accessMode
: READ (WRITE | ONLY)
;
commit
: COMMIT WORK? (AND NO? CHAIN)? (NO? RELEASE)?
;
beginWork
: BEGIN WORK? | startTransaction
;
startTransaction
: START TRANSACTION startTransactionCharacteristic (COMMA startTransactionCharacteristic)*
;
startTransactionCharacteristic
: WITH CONSISTENT SNAPSHOT | READ (WRITE | ONLY)
;
rollback
: ROLLBACK WORK?
(
(AND NO? CHAIN)? (NO? RELEASE)?
| TO SAVEPOINT? ID
)
;
savepoint
: SAVEPOINT ID
;
setVariable
: SET assignment (COMMA assignment)*
;
assignment
: variable EQ_ expr
;
|
grammar MySQLTCLStatement;
import MySQLKeyword, Keyword, DQLBase, BaseRule, DataType, Symbol;
setTransaction
: SET (GLOBAL | SESSION) TRANSACTION setTransactionCharacteristic (COMMA setTransactionCharacteristic)*
;
setTransactionCharacteristic
: ISOLATION LEVEL level| accessMode
;
level
: REPEATABLE READ | READ (COMMITTED | UNCOMMITTED) | SERIALIZABLE
;
accessMode
: READ (WRITE | ONLY)
;
commit
: COMMIT WORK? (AND NO? CHAIN)? (NO? RELEASE)?
;
beginWork
: BEGIN WORK? | startTransaction
;
startTransaction
: START TRANSACTION (startTransactionCharacteristic (COMMA startTransactionCharacteristic)*)?
;
startTransactionCharacteristic
: WITH CONSISTENT SNAPSHOT | READ (WRITE | ONLY)
;
rollback
: ROLLBACK WORK?
(
(AND NO? CHAIN)? (NO? RELEASE)?
| TO SAVEPOINT? ID
)
;
savepoint
: SAVEPOINT ID
;
setVariable
: SET setVariableAssignment (COMMA setVariableAssignment)*
;
setVariableAssignment
: (AT_ AT_)? (GLOBAL | PERSIST | PERSIST_ONLY | SESSION)? DOT? variableKey EQ_ variableValue
;
variableKey
: ID
;
variableValue
: expr
;
|
rename mysql rule assignment to setVariableAssignment and add variableKey variableValue rule
|
rename mysql rule assignment to setVariableAssignment and add variableKey variableValue rule
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
|
bb70d74fd357295109120785439f7fa645844f12
|
antlr/src/main/resources/org/minijs/parser/antlr/JavaScript.g4
|
antlr/src/main/resources/org/minijs/parser/antlr/JavaScript.g4
|
grammar JavaScript;
@header {
}
program
: statement+
;
variableDeclarators
: 'var'? variableDeclarator (COMMA variableDeclarator)*
;
variableDeclarator
: IDENTIFIER ('=' variableInitializer)?
;
variableInitializer
: expression
;
statement
: SEMI
| 'break'
| 'continue'
| expression
| variableDeclarators
| '{' statement* '}'
| 'if' parenthesizedExpression statement
'for' '(' forControl ')' statement
| 'while' parenthesizedExpression statement
| 'do' statement 'while' parenthesizedExpression
| 'return' expression
;
forControl
: forInit? ';' expression? ';' forUpdate?
;
forInit
: variableDeclarators
;
forUpdate
: expressionList
;
parenthesizedExpression
: LPAREN expression RPAREN
;
expression
: expression '.' IDENTIFIER #propertyExpression
| expression '[' expression ']' #indexorExpression
| 'new' IDENTIFIER '(' expressionList? ')' #newExpression
| expression '(' expressionList? ')' #functionCallExpression
| primaryExpression #primaryExpression2
| expression (INC | DEC) #postIncDecExpression
| unaryExpression #unaryExpression2
| expression ('*' | '/' | '%') expression #mulExpression
| expression ('+' | '-') expression #plusExpression
| expression ('<' | '<=' | '>' | '>=' |
'in' | 'instanceof') expression #relationalExpression
| expression ('==' | '!=' | '===' | '!==') expression #loginEqualityExpression
| expression '&&' expression #loginAndExpression
| expression '||' expression #logicOrExpression
| expression '?' expression ':' expression #conditionalExpression
;
unaryExpression
: (INC | DEC | '!' | '~' | '+' | '-' | 'delete') expression
;
expressionList
: expression (',' expression)*
;
primaryExpression
: IDENTIFIER
| literal
| parenthesizedExpression
| arrayLiteral
;
arrayLiteral
: '[' expressionList? ']'
;
literal
: NUMBER
| BOOLEAN_LITERAL
| NULL_LITERAL
| UNDEFINED_LITERAL
| STRING_LITERAL
;
BOOLEAN_LITERAL
: 'true'
| 'false'
;
STRING_LITERAL
: '"' ( ESC_SEQ | ~('\\'|'"') )* '"'
| '\'' ( ESC_SEQ | ~('\\'|'\'') )* '\''
;
UNDEFINED_LITERAL
: 'undefined'
;
NULL_LITERAL
: 'null'
;
IDENTIFIER
: [a-zA-Z$_] [a-zA-Z0-9$_]*
;
NUMBER
: SIGN? INT+ ('.' INT+)? EXPONENT?
;
// Keywords
VAR: 'var';
IF: 'if';
WHILE: 'while';
DO: 'do';
FOR: 'for';
CONTINUE: 'continue';
BREAK: 'break';
RETURN: 'return';
FUNCTION: 'function';
NEW: 'new';
DELETE: 'delete';
IN: 'in';
INSTANCEOF: 'instanceof';
// Separators
LPAREN : '(';
RPAREN : ')';
LBRACE : '{';
RBRACE : '}';
LBRACK : '[';
RBRACK : ']';
SEMI : ';';
COMMA : ',';
DOT : '.';
QUESTION : '?';
COLON : ':';
// Operators
PLUS: '+';
MINUS: '-';
MUL: '*';
DIV: '/';
MOD: '%';
ASSIGN: '=';
AND: '&&';
OR: '||';
GT: '>';
LT: '<';
GE: '>=';
LE: '<=';
EQ: '==';
NEQ: '!=';
NOT: '!';
INC: '++';
DEC: '--';
EXACT_EQ: '===';
EXACT_NEQ: '!==';
BITWISE_NOT: '~';
fragment
SIGN
: [+-]
;
fragment
INT
: [0-9]+
;
fragment
EXPONENT
: ('e'|'E') ('+'|'-')? [0-9]+
;
fragment
ESC_SEQ
: '\\' ('\"'|'\\'|'/'|'b'|'f'|'n'|'r'|'t')
| UNICODE_ESC
;
fragment
UNICODE_ESC
: '\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
;
fragment
HEX_DIGIT
: [0-9a-fA-F]
;
//
// Whitespace and comments
//
WS
: [ \t\r\n]+ -> skip
;
COMMENT
: '/*' .*? '*/' -> skip
;
LINE_COMMENT
: '//' ~[\r\n]* -> skip
;
|
grammar JavaScript;
@header {
}
program
: statement+
;
variableDeclarators
: 'var'? variableDeclarator (COMMA variableDeclarator)*
;
variableDeclarator
: IDENTIFIER ('=' variableInitializer)?
;
variableInitializer
: expression
;
statement
: SEMI
| 'break'
| 'continue'
| expression
| variableDeclarators
| '{' statement* '}'
| 'if' parenthesizedExpression statement
'for' '(' forControl ')' statement
| 'while' parenthesizedExpression statement
| 'do' statement 'while' parenthesizedExpression
| 'return' expression
;
forControl
: forInit? ';' expression? ';' forUpdate?
;
forInit
: variableDeclarators
;
forUpdate
: expressionList
;
parenthesizedExpression
: LPAREN expression RPAREN
;
expression
: expression '.' IDENTIFIER #propertyExpression
| expression '[' expression ']' #indexorExpression
| 'new' IDENTIFIER '(' expressionList? ')' #newExpression
| expression '(' expressionList? ')' #functionCallExpression
| primaryExpression #primaryExpression2
| expression (INC | DEC) #postUpdateExpression
| unaryExpression #unaryExpression2
| expression ('*' | '/' | '%') expression #mulExpression
| expression ('+' | '-') expression #plusExpression
| expression ('<' | '<=' | '>' | '>=' |
'in' | 'instanceof') expression #relationalExpression
| expression ('==' | '!=' | '===' | '!==') expression #loginEqualityExpression
| expression '&&' expression #loginAndExpression
| expression '||' expression #logicOrExpression
| expression '?' expression ':' expression #conditionalExpression
;
unaryExpression
: (INC | DEC | '!' | '~' | '+' | '-' | 'delete') expression
;
expressionList
: expression (',' expression)*
;
primaryExpression
: IDENTIFIER
| literal
| parenthesizedExpression
| arrayLiteral
;
arrayLiteral
: '[' expressionList? ']'
;
literal
: NUMBER
| BOOLEAN_LITERAL
| NULL_LITERAL
| UNDEFINED_LITERAL
| STRING_LITERAL
;
BOOLEAN_LITERAL
: 'true'
| 'false'
;
STRING_LITERAL
: '"' ( ESC_SEQ | ~('\\'|'"') )* '"'
| '\'' ( ESC_SEQ | ~('\\'|'\'') )* '\''
;
UNDEFINED_LITERAL
: 'undefined'
;
NULL_LITERAL
: 'null'
;
IDENTIFIER
: [a-zA-Z$_] [a-zA-Z0-9$_]*
;
NUMBER
: SIGN? INT+ ('.' INT+)? EXPONENT?
;
// Keywords
VAR: 'var';
IF: 'if';
WHILE: 'while';
DO: 'do';
FOR: 'for';
CONTINUE: 'continue';
BREAK: 'break';
RETURN: 'return';
FUNCTION: 'function';
NEW: 'new';
DELETE: 'delete';
IN: 'in';
INSTANCEOF: 'instanceof';
// Separators
LPAREN : '(';
RPAREN : ')';
LBRACE : '{';
RBRACE : '}';
LBRACK : '[';
RBRACK : ']';
SEMI : ';';
COMMA : ',';
DOT : '.';
QUESTION : '?';
COLON : ':';
// Operators
PLUS: '+';
MINUS: '-';
MUL: '*';
DIV: '/';
MOD: '%';
ASSIGN: '=';
AND: '&&';
OR: '||';
GT: '>';
LT: '<';
GE: '>=';
LE: '<=';
EQ: '==';
NEQ: '!=';
NOT: '!';
INC: '++';
DEC: '--';
EXACT_EQ: '===';
EXACT_NEQ: '!==';
BITWISE_NOT: '~';
fragment
SIGN
: [+-]
;
fragment
INT
: [0-9]+
;
fragment
EXPONENT
: ('e'|'E') ('+'|'-')? [0-9]+
;
fragment
ESC_SEQ
: '\\' ('\"'|'\\'|'/'|'b'|'f'|'n'|'r'|'t')
| UNICODE_ESC
;
fragment
UNICODE_ESC
: '\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
;
fragment
HEX_DIGIT
: [0-9a-fA-F]
;
//
// Whitespace and comments
//
WS
: [ \t\r\n]+ -> skip
;
COMMENT
: '/*' .*? '*/' -> skip
;
LINE_COMMENT
: '//' ~[\r\n]* -> skip
;
|
Rename postIncDecExpression to postUpdateExpression
|
Rename postIncDecExpression to postUpdateExpression
|
ANTLR
|
apache-2.0
|
frankdu/minijs
|
0016f3a0cc0a91a0a55aa4cdf4585abcabecb87b
|
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 */
grammar GrammarParser;
// The main entry point for parsing a v4 grammar.
grammarSpec
: DOC_COMMENT?
grammarType id ';'
prequelConstruct*
ruleSpec*
modeSpec*
EOF
;
grammarType
: 'lexer' 'grammar'
| 'parser' 'grammar'
| 'grammar'
;
prequelConstruct
: optionsDef
| // A list of grammars to which this grammar will delegate certain
// parts of the parsing sequence - a set of imported grammars
imports
| // The declaration of any token types we need that are not already
// specified by a preceeding grammar
tokenDefs
| action // e.g., @header or @lexer::header
;
// A list of options that affect analysis and/or code generation
optionsDef
: 'options' '{' (option ';')* '}'
;
option
: id '=' optionValue
;
optionValue
: id
| STRING_LITERAL
| INT
;
// A list of grammars to which this grammar will delegate certain
// parts of the parsing sequence - a set of imported grammars
imports
: 'import' grammarName (',' grammarName)* ';'
;
// A possibly named grammar file that should be imported to this gramamr
// and delgated to for the rules it specifies
grammarName
: id '=' id
| id
;
/** The declaration of any token types we need that are not already
* specified by a preceeding grammar, such as when a parser declares
* imaginary tokens with which to construct the AST, or a rewriting
* tree parser adds further imaginary tokens to ones defined in a prior
* {tree} parser.
*/
tokenDefs
: 'tokens' id (',' id)* ','? '}'
;
actionBlock
: BEGIN_ACTION
( actionBlock
| actionExpression
| actionScopeExpression
| ACTION_WS
| ACTION_NEWLINE
| ACTION_COMMENT
| ACTION_LITERAL
| ACTION_TEXT
| ACTION_LT
| ACTION_GT
| ACTION_LPAREN
| ACTION_RPAREN
| ACTION_LBRACK
| ACTION_RBRACK
| ACTION_EQUALS
| ACTION_','
| ACTION_ESCAPE
| ACTION_WORD
| ACTION_REFERENCE
| ACTION_COLON
| ACTION_COLON2
| ACTION_MINUS
| ACTION_DOT
)*
END_ACTION
;
actionExpression
: ref=ACTION_REFERENCE ignored* op=ACTION_DOT ignored* member=ACTION_WORD
;
actionScopeExpression
: ref=ACTION_REFERENCE ignored* (ACTION_LBRACK ignored* (neg=ACTION_MINUS ignored*)? index=ACTION_WORD ignored* ACTION_RBRACK ignored*)? op=ACTION_COLON2 ignored* member=ACTION_WORD
;
argActionBlock
: BEGIN_ARG_ACTION
( ARG_ACTION_ELEMENT
| ARG_ACTION_TEXT
| ARG_ACTION_LT
| ARG_ACTION_GT
| ARG_ACTION_LPAREN
| ARG_ACTION_RPAREN
| ARG_ACTION_EQUALS
| ARG_ACTION_','
| ARG_ACTION_ESCAPE
| ARG_ACTION_WORD
| ARG_ACTION_WS
| ARG_ACTION_NEWLINE
)*
END_ARG_ACTION
;
argActionParameters
: BEGIN_ARG_ACTION
ignored* (parameters+=argActionParameter ignored* (ARG_ACTION_',' ignored* parameters+=argActionParameter ignored*)*)?
END_ARG_ACTION
;
argActionParameter
: type=argActionParameterType? ignored* name=ARG_ACTION_WORD
;
argActionParameterType
: argActionParameterTypePart (ignored* argActionParameterTypePart)*
;
argActionParameterTypePart
: ARG_ACTION_WORD
| ARG_ACTION_LT argActionParameterType? ARG_ACTION_GT
| ARG_ACTION_LPAREN argActionParameterType? ARG_ACTION_RPAREN
;
ignored
: ACTION_WS
| ACTION_NEWLINE
| ACTION_COMMENT
| ARG_ACTION_WS
| ARG_ACTION_NEWLINE
;
// A declaration of a language target specifc section,
// such as @header, @includes and so on. We do not verify these
// sections, they are just passed on to the language target.
/** Match stuff like @parser::members {int i;} */
action
: AT (actionScopeName COLONCOLON)? id actionBlock
;
/** Sometimes the scope names will collide with keywords; allow them as
* ids for action scopes.
*/
actionScopeName
: id
| LEXER
| PARSER
;
modeSpec
: MODE id ';' ruleSpec+
;
rules
: ruleSpec*
;
ruleSpec
: parserRuleSpec
| lexerRule
;
// The specification of an EBNF rule in ANTLR style, with all the
// rule level parameters, declarations, actions, rewrite specs and so
// on.
//
// Note that here we allow any number of rule declaration sections (such
// as scope, returns, etc) in any order and we let the upcoming semantic
// verification of the AST determine if things are repeated or if a
// particular functional element is not valid in the context of the
// grammar type, such as using returns in lexer rules and so on.
parserRuleSpec
: // A rule may start with an optional documentation comment
DOC_COMMENT?
// Following the documentation, we can declare a rule to be
// public, private and so on. This is only valid for some
// language targets of course but the target will ignore these
// modifiers if they make no sense in that language.
ruleModifiers?
// Next comes the rule name. Here we do not distinguish between
// parser or lexer rules, the semantic verification phase will
// reject any rules that make no sense, such as lexer rules in
// a pure parser or tree parser.
name=RULE_REF
// Immediately following the rulename, there may be a specification
// of input parameters for the rule. We do not do anything with the
// parameters here except gather them for future phases such as
// semantic verifcation, type assignment etc. We require that
// the input parameters are the next syntactically significant element
// following the rule id.
argActionParameters?
ruleReturns?
throwsSpec?
localsSpec?
// Now, before the rule specification itself, which is introduced
// with a COLON, we may have zero or more configuration sections.
// As usual we just accept anything that is syntactically valid for
// one form of the rule or another and let the semantic verification
// phase throw out anything that is invalid.
// At the rule level, a programmer may specify a number of sections, such
// as scope declarations, rule return elements, @ sections (which may be
// language target specific) and so on. We allow any number of these in any
// order here and as usual rely onthe semantic verification phase to reject
// anything invalid using its addinotal context information. Here we are
// context free and just accept anything that is a syntactically correct
// construct.
//
rulePrequels
COLON
// The rule is, at the top level, just a list of alts, with
// finer grained structure defined within the alts.
ruleBlock
';'
exceptionGroup
;
// Many language targets support exceptions and the rule will
// generally be able to throw the language target equivalent
// of a recognition exception. The grammar programmar can
// specify a list of exceptions to catch or a generic catch all
// and the target language code generation template is
// responsible for generating code that makes sense.
exceptionGroup
: exceptionHandler* finallyClause?
;
// Specifies a handler for a particular type of exception
// thrown by a rule
exceptionHandler
: CATCH argActionBlock actionBlock
;
finallyClause
: FINALLY actionBlock
;
rulePrequels
: rulePrequel*
;
// An individual rule level configuration as referenced by the ruleActions
// rule above.
//
rulePrequel
: optionsDef
| ruleAction
;
// A rule can return elements that it constructs as it executes.
// The return values are specified in a 'returns' prequel element,
// which contains ',' separated declarations, where the declaration
// is target language specific. Here we see the returns declaration
// as a single lexical action element, to be processed later.
//
ruleReturns
: RETURNS argActionParameters
;
// --------------
// Exception spec
//
// Some target languages, such as Java and C# support exceptions
// and they are specified as a prequel element for each rule that
// wishes to throw its own exception type. Note that the name of the
// exception is just a single word, so the header section of the grammar
// must specify the correct import statements (or language equivalent).
// Target languages that do not support exceptions just safely ignore
// them.
//
throwsSpec
: THROWS id (',' id)*
;
localsSpec
: LOCALS argActionParameters
;
// @ Sections are generally target language specific things
// such as local variable declarations, code to run before the
// rule starts and so on. Fir instance most targets support the
// @init {} section where declarations and code can be placed
// to run before the rule is entered. The C target also has
// an @declarations {} section, where local variables are declared
// in order that the generated code is C89 copmliant.
//
/** Match stuff like @init {int i;} */
ruleAction
: AT id actionBlock
;
// A set of access modifiers that may be applied to rule declarations
// and which may or may not mean something to the target language.
// Note that the parser allows any number of these in any order and the
// semantic pass will throw out invalid combinations.
//
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
;
// A set of alts, rewritten as a BLOCK for generic processing
// in tree walkers. Used by the rule 'rule' so that the list of
// alts for a rule appears as a BLOCK containing the alts and
// can be processed by the generic BLOCK rule. Note that we
// use a separate rule so that the BLOCK node has start and stop
// boundaries set correctly by rule post processing of rewrites.
ruleBlock
: ruleAltList
;
ruleAltList
: labeledAlt (OR labeledAlt)*
;
labeledAlt
: alternative (POUND id)?
;
lexerRule
: DOC_COMMENT? FRAGMENT?
name=TOKEN_REF COLON lexerRuleBlock ';'
;
lexerRuleBlock
: lexerAltList
;
lexerAltList
: lexerAlt (OR lexerAlt)*
;
lexerAlt
: lexerElements? lexerCommands?
;
lexerElements
: lexerElement+
;
lexerElement
: labeledLexerElement ebnfSuffix?
| lexerAtom ebnfSuffix?
| lexerBlock ebnfSuffix?
| actionBlock QUESTION? // actions only allowed at end of outer alt actually,
// but preds can be anywhere
;
labeledLexerElement
: id ass=('='|PLUS_'=')
( lexerAtom
| block
)
;
lexerBlock
: LPAREN lexerAltList RPAREN
;
// channel=HIDDEN, skip, more, mode(INSIDE), push(INSIDE), pop
lexerCommands
: RARROW lexerCommand (',' lexerCommand)*
;
lexerCommand
: lexerCommandName LPAREN lexerCommandExpr RPAREN
| lexerCommandName
;
lexerCommandName
: id
| MODE
;
lexerCommandExpr
: id
| INT
;
altList
: alternative (OR alternative)*
;
// An individual alt with an optional rewrite clause for the
// elements of the alt.
alternative
: elements
| // empty alt
;
elements
: element+
;
element
: labeledElement
( ebnfSuffix
|
)
| atom
( ebnfSuffix
|
)
| ebnf
| actionBlock QUESTION? // SEMPRED is actionBlock followed by QUESTION
;
labeledElement
: label=id ass=('='|PLUS_'=')
( atom
| block
)
;
// A block of gramamr structure optionally followed by standard EBNF
// notation, or ANTLR specific notation. I.E. ? + ^ and so on
ebnf
: block
// And now we see if we have any of the optional suffixs and rewrite
// the AST for this rule accordingly
( blockSuffix
|
)
;
// The standard EBNF suffixes with additional components that make
// sense only to ANTLR, in the context of a grammar block.
blockSuffix
: ebnfSuffix // Standard EBNF
;
ebnfSuffix
: QUESTION
| STAR
| PLUS
;
lexerAtom
: range
| terminal
| RULE_REF
| notSet
| LEXER_CHAR_SET
| // Wildcard '.' means any character in a lexer, any
// token in parser and any node or subtree in a tree parser
// Because the terminal rule is allowed to be the node
// specification for the start of a tree rule, we must
// later check that wildcard was not used for that.
DOT elementOptions?
;
atom
: // Qualified reference delegate.rule. This must be
// lexically contiguous (no spaces either side of the DOT)
// otherwise it is two references with a wildcard in between
// and not a qualified reference.
range // Range x..y - only valid in lexers
| terminal
| ruleref
| notSet
| // Wildcard '.' means any character in a lexer, any
// token in parser and any node or subtree in a tree parser
// Because the terminal rule is allowed to be the node
// specification for the start of a tree rule, we must
// later check that wildcard was not used for that.
DOT elementOptions?
;
// --------------------
// Inverted element set
//
// A set of characters (in a lexer) or terminal tokens, if a parser,
// that are then used to create the inverse set of them.
notSet
: NOT setElement
| NOT blockSet
;
blockSet
: LPAREN setElement (OR setElement)* RPAREN
;
setElement
: TOKEN_REF
| STRING_LITERAL
| range
| LEXER_CHAR_SET
;
// -------------
// Grammar Block
//
// Anywhere where an element is valid, the grammar may start a new block
// of alts by surrounding that block with ( ). A new block may also have a set
// of options, which apply only to that block.
//
block
: LPAREN
( optionsDef? ruleAction* COLON )?
altList
RPAREN
;
// ----------------
// Parser rule ref
//
// Reference to a parser rule with optional arguments and optional
// directive to become the root node or ignore the tree produced
//
ruleref
: RULE_REF argActionBlock?
;
// ---------------
// Character Range
//
// Specifies a range of characters. Valid for lexer rules only, but
// we do not check that here, the tree walkers shoudl do that.
// Note also that the parser also allows through more than just
// character literals so that we can produce a much nicer semantic
// error about any abuse of the .. operator.
//
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 (',' elementOption)* GT
;
// WHen used with elements we can specify what the tree node type can
// be and also assign settings of various options (which we do not check here)
elementOption
: // This format indicates the default node option
id
| // This format indicates option assignment
id '=' (id | STRING_LITERAL)
;
// The name of the grammar, and indeed some other grammar elements may
// come through to the parser looking like a rule reference or a token
// reference, hence this rule is used to pick up whichever it is and rewrite
// it as a generic ID token.
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 */
grammar ANTLRv4Parser;
// 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
| STAR
| PLUS
;
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
;
|
clean up grammar
|
clean up grammar
|
ANTLR
|
bsd-3-clause
|
bjansen/intellij-plugin-v4,Maccimo/intellij-plugin-v4,sharwell/intellij-plugin-v4,parrt/intellij-plugin-v4,Maccimo/intellij-plugin-v4,rojaster/intellij-plugin-v4,parrt/intellij-plugin-v4,rojaster/intellij-plugin-v4,antlr/intellij-plugin-v4,consulo/consulo-antlr4,bjansen/intellij-plugin-v4,antlr/intellij-plugin-v4
|
dd3d13875d37c13ccc4fa106f7ece49a7df79058
|
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)?
;
|
grammar SQLServerDCLStatement;
import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol;
grant
: grantGeneral | grantDW
;
grantGeneral
: GRANT (ALL PRIVILEGES? | permissionOnColumns ( COMMA permissionOnColumns)*)
(ON (ID COLON COLON)? ID)? TO ids
(WITH GRANT OPTION)? (AS ID)?
;
permissionOnColumns
: permission columnList?
;
permission
: ID *?
;
grantDW
: GRANT permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
TO ids (WITH GRANT OPTION)?
;
classType
: LOGIN | DATABASE | OBJECT | ROLE | SCHEMA | USER
;
revoke
: revokeGeneral | revokeDW
;
revokeGeneral
: REVOKE (GRANT OPTION FOR)?
((ALL PRIVILEGES?)? | permissionOnColumns)
(ON (ID COLON COLON)? ID)?
(TO | FROM) ids (CASCADE)? (AS ID)?
;
revokeDW
: REVOKE permissionWithClass (FROM | TO)? ids CASCADE?
;
permissionWithClass
: permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
;
denyGeneral
: DENY permissionWithClass TO ids CASCADE? (AS ID)?
;
|
add denyGeneral
|
add denyGeneral
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
|
8c06da892491b522e556949515846338fd2996d0
|
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
|
sharding-core/src/main/antlr4/imports/SQLServerDCLStatement.g4
|
grammar SQLServerDCLStatement;
import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol;
grant
: grantGeneral | grantDW
;
grantGeneral
: GRANT generalPrisOn TO ids (WITH GRANT OPTION)? (AS ID)?
;
generalPrisOn
: (ALL PRIVILEGES? | permissionOnColumns (COMMA permissionOnColumns)*) (ON (ID COLON COLON)? ID)?
;
permissionOnColumns
: permission columnList?
;
permission
: ID *?
;
grantDW
: GRANT permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
TO ids (WITH GRANT OPTION)?
;
classType
: LOGIN | DATABASE | OBJECT | ROLE | SCHEMA | USER
;
revoke
: revokeGeneral | revokeDW
;
revokeGeneral
: REVOKE (GRANT OPTION FOR)? ((ALL PRIVILEGES?)? | permissionOnColumns)
(ON (ID COLON COLON)? ID)? (TO | FROM) ids (CASCADE)? (AS ID)?
;
revokeDW
: REVOKE permissionWithClass (FROM | TO)? ids CASCADE?
;
permissionWithClass
: permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
;
deny
: DENY generalPrisOn TO ids CASCADE? (AS ID)?
;
createUser
: CREATE USER
(
userName (createUserBody1 | createUserBody4)
| createUserBody2
| createUserBody3
)?
;
createUserBody1
: ((FOR | FROM) LOGIN ID)? (WITH optionsLists)?
;
createUserBody2
: windowsPrincipal (WITH optionsLists)?
| userName WITH PASSWORD EQ_ STRING (COMMA optionsList)*
| ID FROM EXTERNAL PROVIDER
;
windowsPrincipal
: ID BACKSLASH ID
;
createUserBody3
: windowsPrincipal ((FOR | FROM) LOGIN ID)?
| userName (FOR | FROM) LOGIN ID
;
createUserBody4
: WITHOUT LOGIN (WITH optionsLists)?
| (FOR | FROM) (CERTIFICATE ID | ASYMMETRIC KEY ID)
;
optionsLists
: optionsList (COMMA optionsList)*
;
optionsList
: ID EQ_ ID?
;
alterUser
: ALTER USER userName optionsLists
;
dropUser
: DROP USER (IF EXISTS)? userName
;
createLogin
: CREATE LOGIN (windowsPrincipal | ID) (WITH loginOptionList | FROM sources)
;
loginOptionList
: PASSWORD EQ_ STRING HASHED? MUST_CHANGE? (COMMA optionsList)*
;
sources
: WINDOWS (WITH optionsLists)? | CERTIFICATE ID | ASYMMETRIC KEY ID
;
alterLogin
: ALTER LOGIN ID (ENABLE | DISABLE | WITH loginOption (COMMA loginOption)* | credentialOption)
;
loginOption
: PASSWORD EQ_ STRING HASHED? (OLD_PASSWORD EQ_ STRING | passwordOption (passwordOption )?)?
| DEFAULT_DATABASE EQ_ databaseName
| optionsList
| NO CREDENTIAL
;
passwordOption
: MUST_CHANGE | UNLOCK
;
credentialOption
: ADD CREDENTIAL ID
| DROP CREDENTIAL
;
dropLogin
: DROP LOGIN ID
;
createRole
: CREATE ROLE roleName (AUTHORIZATION ID)
;
alterRole
: ALTER ROLE roleName ((ADD | DROP) MEMBER ID | WITH NAME EQ_ ID )
;
dropRole
: DROP ROLE roleName
;
|
grammar SQLServerDCLStatement;
import SQLServerKeyword, DataType, Keyword, SQLServerBase, BaseRule, Symbol;
grant
: grantGeneral | grantDW
;
grantGeneral
: GRANT generalPrisOn TO ids (WITH GRANT OPTION)? (AS ID)?
;
generalPrisOn
: (ALL PRIVILEGES? | permissionOnColumns (COMMA permissionOnColumns)*) (ON (ID COLON COLON)? ID)?
;
permissionOnColumns
: permission columnList?
;
permission
: ID +?
;
grantDW
: GRANT permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
TO ids (WITH GRANT OPTION)?
;
classType
: LOGIN | DATABASE | OBJECT | ROLE | SCHEMA | USER
;
revoke
: revokeGeneral | revokeDW
;
revokeGeneral
: REVOKE (GRANT OPTION FOR)? ((ALL PRIVILEGES?)? | permissionOnColumns)
(ON (ID COLON COLON)? ID)? (TO | FROM) ids (CASCADE)? (AS ID)?
;
revokeDW
: REVOKE permissionWithClass (FROM | TO)? ids CASCADE?
;
permissionWithClass
: permission (COMMA permission)* (ON (classType COLON COLON)? ID)?
;
deny
: DENY generalPrisOn TO ids CASCADE? (AS ID)?
;
createUser
: CREATE USER
(
userName (createUserBody1 | createUserBody4)
| createUserBody2
| createUserBody3
)?
;
createUserBody1
: ((FOR | FROM) LOGIN ID)? (WITH optionsLists)?
;
createUserBody2
: windowsPrincipal (WITH optionsLists)?
| userName WITH PASSWORD EQ_ STRING (COMMA optionsList)*
| ID FROM EXTERNAL PROVIDER
;
windowsPrincipal
: ID BACKSLASH ID
;
createUserBody3
: windowsPrincipal ((FOR | FROM) LOGIN ID)?
| userName (FOR | FROM) LOGIN ID
;
createUserBody4
: WITHOUT LOGIN (WITH optionsLists)?
| (FOR | FROM) (CERTIFICATE ID | ASYMMETRIC KEY ID)
;
optionsLists
: optionsList (COMMA optionsList)*
;
optionsList
: ID EQ_ ID?
;
alterUser
: ALTER USER userName optionsLists
;
dropUser
: DROP USER (IF EXISTS)? userName
;
createLogin
: CREATE LOGIN (windowsPrincipal | ID) (WITH loginOptionList | FROM sources)
;
loginOptionList
: PASSWORD EQ_ STRING HASHED? MUST_CHANGE? (COMMA optionsList)*
;
sources
: WINDOWS (WITH optionsLists)? | CERTIFICATE ID | ASYMMETRIC KEY ID
;
alterLogin
: ALTER LOGIN ID (ENABLE | DISABLE | WITH loginOption (COMMA loginOption)* | credentialOption)
;
loginOption
: PASSWORD EQ_ STRING HASHED? (OLD_PASSWORD EQ_ STRING | passwordOption (passwordOption )?)?
| DEFAULT_DATABASE EQ_ databaseName
| optionsList
| NO CREDENTIAL
;
passwordOption
: MUST_CHANGE | UNLOCK
;
credentialOption
: ADD CREDENTIAL ID
| DROP CREDENTIAL
;
dropLogin
: DROP LOGIN ID
;
createRole
: CREATE ROLE roleName (AUTHORIZATION ID)
;
alterRole
: ALTER ROLE roleName ((ADD | DROP) MEMBER ID | WITH NAME EQ_ ID )
;
dropRole
: DROP ROLE roleName
;
|
update permission
|
update permission
|
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
|
b10d5b32c542d1a1b30194d1b21a0232bad4d608
|
src/main/antlr4/com/sri/ai/grinder/parser/antlr/AntlrGrinder.g4
|
src/main/antlr4/com/sri/ai/grinder/parser/antlr/AntlrGrinder.g4
|
grammar AntlrGrinder;
expression : expr ;
expr :
// parenthesis, e.g.:(1+2)
'(' expr ')' #parenthesesAroundExpression
// an expression symbol, e.g.:<X + Y>
| '<' expr '>' #expressionSymbol
// function application, e.g.: f(X)
| functor=expr '(' ( args+=expr (',' args+=expr)* )? ')' # functionApplication
// tuple, e.g.: (A, B, C)
| '(' expr ',' expr (',' expr)* ')' #tuple
// counting formula, e.g.: | X in 1..10 : X < 5 |
| '|' ( indexes+=expr (',' indexes+=expr)* )? ':' body=expr '|' #countingFormula
// cardinality, e.g.: | X |
| '|' expr '|' #cardinality
// intensional uniset, e.g.: { (on X) f(X) | X != a }
| '{' ('(' scope=ON ( scopeargs+=expr (',' scopeargs+=expr)* )? ')')? head=expr (':' condition=expr)? '}' #intensionalUniset
// intensional multiset, e.g.: {{ (on X) f(X) | X != a }}
| '{{' ('(' scope=ON ( scopeargs+=expr (',' scopeargs+=expr)* )? ')')? head=expr (':' condition=expr)? '}}' #intensionalMultiset
// extensional uniset, e.g.: { A, B, C, C, D }
| '{' ( expr (',' expr)* )? '}' #extensionalUniset
// extensional multiset, e.g.: {{ A, B, C, C, D }}
| '{{' ( expr (',' expr)* )? '}}' #extensionalMultiset
// bracketed expression, for parfactors and random variables, e.g. [if p(X) then 1 else 2]
| '[' expr ']' #bracketedExpression
// not, e.g.: not A and B -> (not(A)) and B
| NOT expr #not
// negative, e.g.: 2 * -1 -> 2 * (-1)
| '-' expr #negative // We set the unary minus to higher precedence
// NOTE: P)arentheses, E)xponents, ( M)ultiplication, D)ivision and special case of Integer Interval '..' ), ( A)ddition, S)ubtraction )
// see: http://en.wikipedia.org/wiki/Order_of_operations
// exponentiation, e.g. 2^3^4 -> 2^(3^4)
|<assoc=right> base=expr '^' exponent=expr #Exponentiation
// multiplication or division or an Integer Interval, e.g.: 2*3/2 -> 2*(3/2)
| leftop=expr op=('*' | '/' | '..') rightop=expr #multiplicationOrDivisionOrIntegerInterval
// addition or subtraction, e.g.: 1-2+3 -> (1-2)+3
| leftop=expr op=('+' | '-') rightop=expr #additionOrSubtraction
// real interval
| leftBracket=('[' | ']') lower=expr SEMICOLON upper=expr rightBracket=(']' | '[') #realInterval
// set intersection, e.g.: {a, b, c} intersection {b}
| leftop=expr INTERSECTION rightop=expr #intersection
// set union, {a, b, c} union {b, d}
| leftop=expr UNION rightop=expr #union
// cartesian product
| firstarg=expr (X additionalargs+=expr)+ #cartesianProduct
// function type
| domaintypes+=expr (X domaintypes+=expr)* FUNCTION_TYPE rangetype=expr #functionType
// set membership, x in {x, y, z}
| leftop=expr IN rightop=expr #in
// comparison operators, e.g.: X = Y, 2 < 3
| leftop=expr op=('<' | '<=' | '=' | '!=' | '>=' | '>') rightop=expr #comparison
// conjunction, e.g.: A or B and C -> A or (B and C)
| leftconj=expr AND rightconj=expr #and
// disjunction, e.g.: A => B or C -> A => (B or C)
| leftdisj=expr OR rightdisj=expr #or
// implication, e.g.: A = B => C = D
|<assoc=right> antecedent=expr IMPLICATION consequent=expr #implication
// biconditional, e.g.: A = B <=> C = D
|<assoc=right> leftop=expr BICONDITIONAL rightop=expr #biconditional
// conditional, e.g.: if X = Y then 1 else 2
| IF condition=expr THEN thenbranch=expr ELSE elsebranch=expr #ifThenElse
// lambda, e.g.: lambda f(X) : 2 + f(X)
| LAMBDA ( parameters+=expr (',' parameters+=expr)* )? ':' body=expr #lamda
// universal quantification, e.g.: for all X : X != a
| FOR ALL index=expr ':' body=expr #forAll
// existential quantification, e.g.: there exists X : X = a
| THERE EXISTS index=expr ':' body=expr #thereExists
| expr_symbol #symbol
;
expr_symbol
: expr_non_numeric_symbol
| expr_constant_number
;
expr_non_numeric_symbol
: expr_constant_name
// NOTE: even though the expr_constant_name pattern should match these tokens
// ANTLR excludes the set of tokens that are used from matching
// this pattern (see chapter5 of reference manual). Therefore, we
// need to explicitly list all of the keywords and operators that we
// want also to be interpreted as Symbols.
| FUNCTION_TYPE
| IMPLICATION | BICONDITIONAL // Logic Operators
| EXPONENTIATION | DIVIDE | TIMES | PLUS | SUBTRACT // Arithmetic
| LESS_THAN_EQUAL | EQUAL | NOT_EQUAL | GREATER_THAN_EQUAL // Comparison, Note: We intentionally exclude '<' and '>' as these can affect parsing of an expression symbol
| COLON | VERT_BAR | UNDERSCORE | PERIOD // Misc
;
expr_constant_name
: CONSTANT_STR
| QUOTED_CONSTANT_STR
// NOTE: even though the expr_constant_name pattern should match these tokens
// ANTLR excludes the set of tokens that are used from matching
// this pattern (see chapter5 of reference manual). Therefore, we
// need to explicitly list all of the keywords and operators that we
// want also to be interpreted as Symbols.
| NOT | AND | OR | FOR | ALL | THERE | EXISTS // Keywords
| LAMBDA | IF | THEN | ELSE
| INTERSECTION | UNION
| ON | IN
| X | TUPLE_TYPE
;
expr_constant_number
: INTEGER
| RATIONAL
;
/*
The lexer tokenizes the input string that the parser is asked to
parse. The tokens are all typed. Whitespace
symbols will be excluded from the resulting token stream.
Adding new grammar rules
------------------------
Add any terminal symbols in the new grammar rules to the list below.
Note: Ensure you update the corresponding list in AntlrGrinderTerminalSymbols.java
with any changes made.
*/
// Keywords
NOT : 'not' ;
AND : 'and' ;
OR : 'or' ;
FOR : 'for' ;
ALL : 'all' ;
THERE : 'there' ;
EXISTS : 'exists' ;
LAMBDA : 'lambda' ;
IF : 'if' ;
THEN : 'then' ;
ELSE : 'else' ;
INTERSECTION : 'intersection' ;
UNION : 'union' ;
ON : 'on' ;
IN : 'in' ;
// Special Functions
X : 'x' ; // Used for Cartesian Product
TUPLE_TYPE : '(...)';
FUNCTION_TYPE : '->' ;
// Logic Operators
IMPLICATION : '=>' ;
BICONDITIONAL : '<=>' ;
// Arithmetic
EXPONENTIATION : '^' ;
DIVIDE : '/' ;
TIMES : '*' ;
INTEGER_INTERVAL : '..' ;
PLUS : '+' ;
SUBTRACT : '-' ;
// Comparison
LESS_THAN : '<' ;
LESS_THAN_EQUAL : '<=' ;
EQUAL : '=' ;
NOT_EQUAL : '!=' ;
GREATER_THAN_EQUAL : '>=' ;
GREATER_THAN : '>' ;
// Brackets
OPEN_PAREN : '(' ;
CLOSE_PAREN : ')' ;
OPEN_SQUARE : '[' ;
CLOSE_SQUARE : ']' ;
OPEN_CURLY : '{' ;
CLOSE_CURLY : '}' ;
OPEN_DOUBLE_CURLY : '{{' ;
CLOSE_DOUBLE_CURLY : '}}' ;
// Misc
SEMICOLON : ';' ;
COLON : ':' ;
VERT_BAR : '|' ;
COMMA : ',' ;
UNDERSCORE : '_' ;
PERIOD : '.' ;
INTEGER
: ('0'..'9')+
;
RATIONAL
: ('0' | '1'..'9' '0'..'9'*)
| ('0'..'9')+ '.' ('0'..'9')+ EXPONENT? FLOAT_TYPE_SUFFIX?
| '.' ('0'..'9')+ EXPONENT? FLOAT_TYPE_SUFFIX?
| ('0'..'9')+ EXPONENT FLOAT_TYPE_SUFFIX?
| ('0'..'9')+ FLOAT_TYPE_SUFFIX
| ('0x' | '0X') (HEX_DIGIT )*
('.' (HEX_DIGIT)*)?
( 'p' | 'P' )
( '+' | '-' )?
( '0' .. '9' )+
FLOAT_TYPE_SUFFIX?
;
CONSTANT_STR
: ([a-zA-Z] | [0-9] | '_') ([a-zA-Z] | [0-9] | '_')* ('\'')*
;
QUOTED_CONSTANT_STR
: '"' (ESCAPE_SEQUENCE | ~('\\' | '"' ) )* '"'
| '\'' (ESCAPE_SEQUENCE | ~('\\' | '\'') )* '\''
;
fragment
EXPONENT : ('e'|'E') ('+'|'-')? ('0'..'9')+
;
fragment
FLOAT_TYPE_SUFFIX : ('f'|'F'|'d'|'D')
;
fragment
ESCAPE_SEQUENCE
: '\\' ('b'|'t'|'n'|'f'|'r'|'"'|'\''|'\\')
| UNICODE_ESCAPE
| OCTAL_ESCAPE
;
fragment
UNICODE_ESCAPE
: '\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
;
fragment
OCTAL_ESCAPE
: '\\' ('0'..'3') ('0'..'7') ('0'..'7')
| '\\' ('0'..'7') ('0'..'7')
| '\\' ('0'..'7')
;
fragment
HEX_DIGIT : ('0'..'9'|'a'..'f'|'A'..'F')
;
COMMENT
: '/*' .*? '*/' -> channel(HIDDEN) // match anything between /* and */
;
LINE_COMMENT
: '//' ~[\r\n]* '\r'? ('\n' | EOF) -> channel(HIDDEN)
;
WS : [ \t\r\n]+ -> skip
; // Define whitespace rule, toss it out
|
grammar AntlrGrinder;
expression : expr ;
expr :
// parenthesis, e.g.:(1+2)
'(' expr ')' #parenthesesAroundExpression
// an expression symbol, e.g.:<X + Y>
| '<' expr '>' #expressionSymbol
// function application, e.g.: f(X)
| functor=expr '(' ( args+=expr (',' args+=expr)* )? ')' # functionApplication
// tuple, e.g.: (A, B, C)
| '(' expr ',' expr (',' expr)* ')' #tuple
// counting formula, e.g.: | X in 1..10 : X < 5 |
| '|' ( indexes+=expr (',' indexes+=expr)* )? ':' body=expr '|' #countingFormula
// cardinality, e.g.: | X |
| '|' expr '|' #cardinality
// intensional uniset, e.g.: { (on X) f(X) | X != a }
| '{' ('(' scope=ON ( scopeargs+=expr (',' scopeargs+=expr)* )? ')')? head=expr (':' condition=expr)? '}' #intensionalUniset
// intensional multiset, e.g.: {{ (on X) f(X) | X != a }}
| '{{' ('(' scope=ON ( scopeargs+=expr (',' scopeargs+=expr)* )? ')')? head=expr (':' condition=expr)? '}}' #intensionalMultiset
// extensional uniset, e.g.: { A, B, C, C, D }
| '{' ( expr (',' expr)* )? '}' #extensionalUniset
// extensional multiset, e.g.: {{ A, B, C, C, D }}
| '{{' ( expr (',' expr)* )? '}}' #extensionalMultiset
// bracketed expression, for parfactors and random variables, e.g. [if p(X) then 1 else 2]
| '[' expr ']' #bracketedExpression
// not, e.g.: not A and B -> (not(A)) and B
| NOT expr #not
// negative, e.g.: 2 * -1 -> 2 * (-1)
| '-' expr #negative // We set the unary minus to higher precedence
// NOTE: P)arentheses, E)xponents, ( M)ultiplication, D)ivision and special case of Integer Interval '..' ), ( A)ddition, S)ubtraction )
// see: http://en.wikipedia.org/wiki/Order_of_operations
// exponentiation, e.g. 2^3^4 -> 2^(3^4)
|<assoc=right> base=expr '^' exponent=expr #Exponentiation
// multiplication or division or an Integer Interval, e.g.: 2*3/2 -> 2*(3/2)
| leftop=expr op=('*' | '/' | '..') rightop=expr #multiplicationOrDivisionOrIntegerInterval
// addition or subtraction, e.g.: 1-2+3 -> (1-2)+3
| leftop=expr op=('+' | '-') rightop=expr #additionOrSubtraction
// real interval
| leftBracket=('[' | ']') lower=expr SEMICOLON upper=expr rightBracket=(']' | '[') #realInterval
// set intersection, e.g.: {a, b, c} intersection {b}
| leftop=expr INTERSECTION rightop=expr #intersection
// set union, {a, b, c} union {b, d}
| leftop=expr UNION rightop=expr #union
// cartesian product
| firstarg=expr (X additionalargs+=expr)+ #cartesianProduct
// function type
| domaintypes+=expr (X domaintypes+=expr)* FUNCTION_TYPE rangetype=expr #functionType
// set membership, x in {x, y, z}
| leftop=expr IN rightop=expr #in
// comparison operators, e.g.: X = Y, 2 < 3
| leftop=expr op=('<' | '<=' | '=' | '!=' | '>=' | '>') rightop=expr #comparison
// conjunction, e.g.: A or B and C -> A or (B and C)
| leftconj=expr AND rightconj=expr #and
// disjunction, e.g.: A => B or C -> A => (B or C)
| leftdisj=expr OR rightdisj=expr #or
// implication, e.g.: A = B => C = D
|<assoc=right> antecedent=expr IMPLICATION consequent=expr #implication
// biconditional, e.g.: A = B <=> C = D
|<assoc=right> leftop=expr BICONDITIONAL rightop=expr #biconditional
// conditional, e.g.: if X = Y then 1 else 2
| IF condition=expr THEN thenbranch=expr ELSE elsebranch=expr #ifThenElse
// lambda, e.g.: lambda f(X) : 2 + f(X)
| LAMBDA ( parameters+=expr (',' parameters+=expr)* )? ':' body=expr #lamda
// universal quantification, e.g.: for all X : X != a
| FOR ALL index=expr ':' body=expr #forAll
// existential quantification, e.g.: there exists X : X = a
| THERE EXISTS index=expr ':' body=expr #thereExists
| expr_symbol #symbol
;
expr_symbol
: expr_non_numeric_symbol
| expr_constant_number
;
expr_non_numeric_symbol
: expr_constant_name
// NOTE: even though the expr_constant_name pattern should match these tokens
// ANTLR excludes the set of tokens that are used from matching
// this pattern (see chapter5 of reference manual). Therefore, we
// need to explicitly list all of the keywords and operators that we
// want also to be interpreted as Symbols.
| FUNCTION_TYPE
| IMPLICATION | BICONDITIONAL // Logic Operators
| EXPONENTIATION | DIVIDE | TIMES | PLUS | SUBTRACT // Arithmetic
| LESS_THAN_EQUAL | EQUAL | NOT_EQUAL | GREATER_THAN_EQUAL // Comparison, Note: We intentionally exclude '<' and '>' as these can affect parsing of an expression symbol
| COLON | VERT_BAR | UNDERSCORE | PERIOD // Misc
;
expr_constant_name
: CONSTANT_STR
| QUOTED_CONSTANT_STR
// NOTE: even though the expr_constant_name pattern should match these tokens
// ANTLR excludes the set of tokens that are used from matching
// this pattern (see chapter5 of reference manual). Therefore, we
// need to explicitly list all of the keywords and operators that we
// want also to be interpreted as Symbols.
| NOT | AND | OR | FOR | ALL | THERE | EXISTS // Keywords
| LAMBDA | IF | THEN | ELSE
| INTERSECTION | UNION
| ON | IN
| X | TUPLE_TYPE
;
expr_constant_number
: INTEGER
| RATIONAL
;
/*
The lexer tokenizes the input string that the parser is asked to
parse. The tokens are all typed. Whitespace
symbols will be excluded from the resulting token stream.
Adding new grammar rules
------------------------
Add any terminal symbols in the new grammar rules to the list below.
Note: Ensure you update the corresponding list in AntlrGrinderTerminalSymbols.java
with any changes made.
*/
// Keywords
NOT : 'not' ;
AND : 'and' ;
OR : 'or' ;
FOR : 'for' ;
ALL : 'all' ;
THERE : 'there' ;
EXISTS : 'exists' ;
LAMBDA : 'lambda' ;
IF : 'if' ;
THEN : 'then' ;
ELSE : 'else' ;
INTERSECTION : 'intersection' ;
UNION : 'union' ;
ON : 'on' ;
IN : 'in' ;
// Special Functions
X : 'x' ; // Used for Cartesian Product
TUPLE_TYPE : 'tuple_type' ;
FUNCTION_TYPE : '->' ;
// Logic Operators
IMPLICATION : '=>' ;
BICONDITIONAL : '<=>' ;
// Arithmetic
EXPONENTIATION : '^' ;
DIVIDE : '/' ;
TIMES : '*' ;
INTEGER_INTERVAL : '..' ;
PLUS : '+' ;
SUBTRACT : '-' ;
// Comparison
LESS_THAN : '<' ;
LESS_THAN_EQUAL : '<=' ;
EQUAL : '=' ;
NOT_EQUAL : '!=' ;
GREATER_THAN_EQUAL : '>=' ;
GREATER_THAN : '>' ;
// Brackets
OPEN_PAREN : '(' ;
CLOSE_PAREN : ')' ;
OPEN_SQUARE : '[' ;
CLOSE_SQUARE : ']' ;
OPEN_CURLY : '{' ;
CLOSE_CURLY : '}' ;
OPEN_DOUBLE_CURLY : '{{' ;
CLOSE_DOUBLE_CURLY : '}}' ;
// Misc
SEMICOLON : ';' ;
COLON : ':' ;
VERT_BAR : '|' ;
COMMA : ',' ;
UNDERSCORE : '_' ;
PERIOD : '.' ;
INTEGER
: ('0'..'9')+
;
RATIONAL
: ('0' | '1'..'9' '0'..'9'*)
| ('0'..'9')+ '.' ('0'..'9')+ EXPONENT? FLOAT_TYPE_SUFFIX?
| '.' ('0'..'9')+ EXPONENT? FLOAT_TYPE_SUFFIX?
| ('0'..'9')+ EXPONENT FLOAT_TYPE_SUFFIX?
| ('0'..'9')+ FLOAT_TYPE_SUFFIX
| ('0x' | '0X') (HEX_DIGIT )*
('.' (HEX_DIGIT)*)?
( 'p' | 'P' )
( '+' | '-' )?
( '0' .. '9' )+
FLOAT_TYPE_SUFFIX?
;
CONSTANT_STR
: ([a-zA-Z] | [0-9] | '_') ([a-zA-Z] | [0-9] | '_')* ('\'')*
;
QUOTED_CONSTANT_STR
: '"' (ESCAPE_SEQUENCE | ~('\\' | '"' ) )* '"'
| '\'' (ESCAPE_SEQUENCE | ~('\\' | '\'') )* '\''
;
fragment
EXPONENT : ('e'|'E') ('+'|'-')? ('0'..'9')+
;
fragment
FLOAT_TYPE_SUFFIX : ('f'|'F'|'d'|'D')
;
fragment
ESCAPE_SEQUENCE
: '\\' ('b'|'t'|'n'|'f'|'r'|'"'|'\''|'\\')
| UNICODE_ESCAPE
| OCTAL_ESCAPE
;
fragment
UNICODE_ESCAPE
: '\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
;
fragment
OCTAL_ESCAPE
: '\\' ('0'..'3') ('0'..'7') ('0'..'7')
| '\\' ('0'..'7') ('0'..'7')
| '\\' ('0'..'7')
;
fragment
HEX_DIGIT : ('0'..'9'|'a'..'f'|'A'..'F')
;
COMMENT
: '/*' .*? '*/' -> channel(HIDDEN) // match anything between /* and */
;
LINE_COMMENT
: '//' ~[\r\n]* '\r'? ('\n' | EOF) -> channel(HIDDEN)
;
WS : [ \t\r\n]+ -> skip
; // Define whitespace rule, toss it out
|
Fix token error in expresso parser grammar file.
|
Fix token error in expresso parser grammar file.
|
ANTLR
|
bsd-3-clause
|
aic-sri-international/aic-expresso,aic-sri-international/aic-expresso
|
05b5b2e4240c718d7a957883cf32eeb031427faf
|
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
|
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
|
grammar OracleDCLStatement;
import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol;
/**
* each statement has a url,
* each base url : https://docs.oracle.com/database/121/SQLRF/.
* no begin statement in oracle
*/
//statements_9014.htm#SQLRF01603
grant
: GRANT
(
(grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))?
| grantRolesToPrograms
)
;
grantSystemPrivileges
: systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)?
;
systemObjects
: systemObject(COMMA systemObject)*
;
systemObject
: ALL PRIVILEGES
| roleName
| ID *?
;
grantees
: grantee (COMMA grantee)*
;
grantee
: userName
| roleName
| PUBLIC
;
granteeIdentifiedBy
: userNames IDENTIFIED BY STRING (COMMA STRING)*
;
grantObjectPrivilegeClause
: grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause
TO grantees (WITH HIERARCHY OPTION)?(WITH GRANT OPTION)?
;
grantObjectPrivilege
: objectPrivilege columnList?
;
objectPrivilege
: ID *?
| ALL PRIVILEGES?
;
onObjectClause
: ON
(
schemaName? ID
| USER userName ( COMMA userName)*
| (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID
)
;
grantRolesToPrograms
: roleNames TO programUnits
;
programUnits
: programUnit (COMMA programUnit)*
;
programUnit
: (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID
;
revoke
: REVOKE
(
(revokeSystemPrivileges | revokeObjectPrivileges) (CONTAINER EQ_ (CURRENT | ALL))?
| revokeRolesFromPrograms
)
;
revokeSystemPrivileges
: systemObjects FROM
;
revokeObjectPrivileges
: objectPrivilege (COMMA objectPrivilege)* onObjectClause
FROM grantees
(CASCADE CONSTRAINTS | FORCE)?
;
revokeRolesFromPrograms
: (roleNames | ALL) FROM programUnits
;
sizeClause
: NUMBER ID?
;
|
grammar OracleDCLStatement;
import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol;
/**
* each statement has a url,
* each base url : https://docs.oracle.com/database/121/SQLRF/.
* no begin statement in oracle
*/
//statements_9014.htm#SQLRF01603
grant
: GRANT
(
(grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))?
| grantRolesToPrograms
)
;
grantSystemPrivileges
: systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)?
;
systemObjects
: systemObject(COMMA systemObject)*
;
systemObject
: ALL PRIVILEGES
| roleName
| ID *?
;
grantees
: grantee (COMMA grantee)*
;
grantee
: userName
| roleName
| PUBLIC
;
granteeIdentifiedBy
: userNames IDENTIFIED BY STRING (COMMA STRING)*
;
grantObjectPrivilegeClause
: grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause
TO grantees (WITH HIERARCHY OPTION)?(WITH GRANT OPTION)?
;
grantObjectPrivilege
: objectPrivilege columnList?
;
objectPrivilege
: ID *?
| ALL PRIVILEGES?
;
onObjectClause
: ON
(
schemaName? ID
| USER userName ( COMMA userName)*
| (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID
)
;
grantRolesToPrograms
: roleNames TO programUnits
;
programUnits
: programUnit (COMMA programUnit)*
;
programUnit
: (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID
;
revoke
: REVOKE
(
(revokeSystemPrivileges | revokeObjectPrivileges) (CONTAINER EQ_ (CURRENT | ALL))?
| revokeRolesFromPrograms
)
;
revokeSystemPrivileges
: systemObjects FROM
;
revokeObjectPrivileges
: objectPrivilege (COMMA objectPrivilege)* onObjectClause
FROM grantees
(CASCADE CONSTRAINTS | FORCE)?
;
revokeRolesFromPrograms
: (roleNames | ALL) FROM programUnits
;
createUser
: CREATE USER userName IDENTIFIED
(BY STRING | (EXTERNALLY | GLOBALLY) ( AS STRING)?)
(
DEFAULT TABLESPACE ID
| TEMPORARY TABLESPACE ID
| (QUOTA (sizeClause | UNLIMITED) ON ID)
| PROFILE ID
| PASSWORD EXPIRE
| ACCOUNT (LOCK | UNLOCK)
| ENABLE EDITIONS
| CONTAINER EQ_ (CURRENT | ALL)
)*
;
sizeClause
: NUMBER ID?
;
|
add createUser
|
add createUser
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
4d142a1fa92c85ca522ff290eb71964cff1650d8
|
java-vtl-parser/src/main/resources/kohl/hadrien/antlr4/VTL.g4
|
java-vtl-parser/src/main/resources/kohl/hadrien/antlr4/VTL.g4
|
parser grammar VTL;
options{
language = Java;
tokenVocab = VTLLexer;
}
start
:
statement* EOF
;
/* Assignment */
statement
: variableRef ':=' expr;
/* Conditional */
expr :
exprOr
| IF exprOr THEN exprOr (ELSEIF exprOr THEN exprOr)* (ELSE exprOr)*
;
exprOr
: exprAnd ( OR exprAnd | XOR exprAnd )*
;
/* Logical AND */
exprAnd
:
exprEq (AND exprEq)*
;
/* Equality, inequality */
exprEq
:
exprExists ( ( '=' | '<>' | '<='| '>=' ) exprExists )*
;
/* Matching */
exprExists
:
exprComp (
('exists_in' exprComp) |
('exists_in_all' exprComp) |
('not_exists_in' exprComp) |
('not_exists_in_all' exprComp )
)*
;
/* Comparison, range */
exprComp
:
exprAdd (
IN setExpr |
NOT IN setExpr |
( '>' | '<' ) exprAdd |
BETWEEN exprAdd AND exprAdd |
'not' 'between' exprAdd 'and' exprAdd )*
;
/* Addition, subtraction */
exprAdd
:
exprMultiply (
'++' exprMultiply |
'--' exprMultiply |
'+' exprMultiply |
'-' exprMultiply
)*
;
/* Multiplication, division */
exprMultiply
:
exprFactor
(
(
('**' exprFactor)
|
('//' exprFactor)
|
('*' exprFactor)
|
('/' exprFactor)
|
('%' exprFactor)
)
)*
;
/* Unary plus, unary minus, not */
exprFactor
:
(exprMember)
| ('+' exprMember)
| ('-' exprMember)
| 'not' exprMember
;
/* Membership and clauses */
exprMember
:
exprAtom ('[' datasetClause ']')?('#' componentID)?
;
/* Functions */
exprAtom
: 'round' '(' expr ',' INTEGER_CONSTANT ')'
| 'min' '(' expr ')'
| 'max' '(' expr ')'
| 'abs' '(' expr ')'
| 'exp' '(' expr ')'
| 'ln' '(' expr ')'
| 'log' '(' expr ',' logBase ')'
| 'trunc' '(' expr ',' INTEGER_CONSTANT ')'
| 'power' '(' expr ',' powerExponent ')'
| 'nroot' '(' expr ',' INTEGER_CONSTANT ')'
| 'length' '(' expr ')'
| 'trim' '(' expr ')'
| 'upper' '(' expr ')'
| 'lower' '(' expr ')'
| 'substr' '(' expr ',' scalarExpr (',' scalarExpr)? ')'
| 'indexof' '(' expr ',' STRING_CONSTANT ')'
| 'missing' '(' expr ')'
| 'match_characters' '(' expr ',' STRING_CONSTANT (',' 'all')? ')'
| 'match_values' '(' expr ',' setExpr (',' 'all')? ')'
| 'charlength' '(' expr ')'
| 'type' '(' expr ')' '=' STRING_CONSTANT
| 'intersect' '(' expr ',' expr ')'
| 'union' '(' expr ',' expr ')'
| 'symdiff' '(' expr ',' expr ')'
| 'setdiff' '(' expr ',' expr ')'
| 'isnull' '(' expr ')'
| 'nvl' '(' expr ',' constant ')'
| 'mod' '(' expr ',' expr ')'
| validationExpr
| getExpr
| variableRef
| putExpr
| evalExpr
| mergeExpr
| hierarchyExpr
;
/* Parentheses */
variableRef
: '(' exprOr ')' | varID | constant;
/* get */
getExpr
:
'get' '(' persistentDatasetID (',' persistentDatasetID)* (',' keepClause)? (',' filterClause)? (',' aggregategetClause)? ')'
;
persistentDatasetID
:
STRING_CONSTANT
;
putExpr
:
'put' '(' expr ',' persistentDatasetID ')'
;
evalExpr
:
'eval' '(' STRING_CONSTANT (',' variableRef)* ',' persistentDatasetID ')'
;
validationExpr
:
'check' '(' exprOr (',' 'imbalance' '(' exprOr ')')? (',' 'erlevel' '(' exprOr ')')? (',' 'errorcode' '(' constant ')')? (',' 'threshold' '(' constant ')')? (',' 'all')? ')'
;
mergeExpr
:
'merge' '(' expr 'as'? STRING_CONSTANT (',' expr 'as'? STRING_CONSTANT)+ ',' 'on' '(' expr ')' ',' 'return' '(' (expr 'as'? STRING_CONSTANT) (',' expr 'as'? STRING_CONSTANT)+ ')' ')'
;
hierarchyExpr
:
'hierarchy' '(' expr ',' IDENTIFIER ','
(
STRING_CONSTANT
| (mappingExpr (',' mappingExpr)* 'as' STRING_CONSTANT)
)
',' BOOLEAN_CONSTANT (',' aggrParam)? ')'
;
mappingExpr
:
'(' constant ',' INTEGER_CONSTANT ','
(
'+'
| '-'
)
')' 'to' constant
;
aggrParam
:
'sum'
| 'prod'
;
aggregategetClause
:
'aggregate' '(' aggrFunction '(' scalarExpr ')' (',' aggrFunction '(' scalarExpr ')')* ')'
;
aggregateClause
:
aggrFunctionClause (',' aggrFunctionClause)*
;
aggrFunctionClause
:
aggrFunction '(' scalarExpr ')'
| percentileFunction
;
datasetIDGroup
:
varID (',' varID)*
;
caseElseClause
:
(
(',' ELSE exprAdd)
)
;
caseCaseClause
:
(
(exprOr ',' exprOr (',' exprOr ',' exprOr)*)
)
;
getFiltersClause
:
(
getFilterClause (',' getFilterClause)*
)
;
getFilterClause
:
(
('filter'? bScalarExpr)
)
;
datasetClause
:
('rename' renameClause)
| aggrFilterClause
| (calcClause)
| (attrCalcClause)
| (keepClause)
| (dropClause)
| (compareClause)
;
aggrFilterClause
:
|
(
filterClause (',' keepClause ',' 'aggregate' aggregateClause)?
)
|
(
(
keepClause
| dropClause
)
',' 'aggregate' aggregateClause
)
;
filterClause
:
(
('filter'? bScalarExpr)
)
;
ascdescClause
: 'asc'
| 'desc'
;
renameClause
:
(
varID 'as' varID ('role' varRole)? (',' varID 'as' varID ('role' varRole)?)*
)
;
aggrFunction
:
'sum'
| 'avg'
| 'min'
| 'max'
| 'std'
| 'count'
| 'count_distinct'
| 'median'
;
percentileFunction
:
('percentile' '(' scalarExpr ',' constant ')')
;
calcClause
:
(
('calc') calcClauseItem (',' calcClauseItem)*
)
;
attrCalcClause
:
'attrcalc' scalarExpr 'as' STRING_CONSTANT ('viral')? (',' IDENTIFIER 'as' STRING_CONSTANT ('viral')?)*
;
calcClauseItem
:
(
calcExpr 'as' STRING_CONSTANT ('role' varRole ('viral')?)?
)
;
calcExpr
:
(aggrFunction '(' scalarExpr ')')
| scalarExpr
;
dropClause
:
'drop' '(' dropClauseItem (',' dropClauseItem)* ')'
;
dropClauseItem
:
(varID)
;
keepClause
:
'keep' '(' keepClauseItem (',' keepClauseItem)* ')'
;
keepClauseItem
:
(varID)
;
compareClause
: compOpScalarClause constant
;
inBetweenClause
:
(
('in' setExpr)
)
|
(
('between' constant 'and' constant)
)
|
(
('not' 'in' setExpr)
)
|
(
('not' 'between' constant 'and' constant)
)
;
dimClause
:
| compareClause
| inBetweenClause
;
varRole
:
('IDENTIFIER')
| ('MEASURE')
| ('ATTRIBUTE')
;
bScalarExpr
:
(sExprOr)
(
(
('or' sExprOr)
)
|
(
('xor' sExprOr)
)
)*
;
sExprOr
:
(sExprAnd)
(
('and' sExprAnd)
)*
;
sExprAnd
:
(
('not' sExprPredicate)
)
| sExprPredicate
;
sExprPredicate
:
(scalarExpr)
(
(
(compOpScalar scalarExpr)
)
|
(
('in' setExpr)
)
|
(
('between' scalarExpr 'and' scalarExpr)
)
|
(
('not' 'in' setExpr)
)
|
(
('not' 'between' scalarExpr 'and' scalarExpr)
)
)?
;
scalarExpr
:
(sExprAdd)
(
(
('+' sExprAdd)
)
|
(
('-' sExprAdd)
)
)*
;
sExprAdd
:
(sExprFactor)
(
(
('/' sExprFactor)
)
|
(
('*' sExprFactor)
)
|
(
('%' sExprFactor)
)
)*
;
sExprFactor
:
(
(sExprAtom)
|
(
('+' sExprAtom)
)
|
(
('-' sExprAtom)
)
)
;
sExprAtom
:
varID
| constant
| '(' bScalarExpr ')'
| ('length' '(' scalarExpr ')')
| ('concat' '(' scalarExpr (',' scalarExpr)+ ')')
| ('trim' '(' scalarExpr ')')
| ('upper' '(' scalarExpr ')')
| ('lower' '(' scalarExpr ')')
| ('substr' '(' b1=scalarExpr ',' b2=scalarExpr ',' b3=scalarExpr ')')
| ('round' '(' scalarExpr ',' INTEGER_CONSTANT ')')
| ('trunc' '(' scalarExpr ')')
| ('ln' '(' scalarExpr ')')
| ('exp' '(' scalarExpr ')')
| ('mod' '(' scalarExpr ',' INTEGER_CONSTANT ')')
| ('abs' '(' scalarExpr ')')
| ('power' '(' scalarExpr ',' powerExponent ')')
| ('SYSTIMESTAMP')
;
componentID
:
IDENTIFIER
;
compOpScalarClause
: '='
| '<'
| '>'
| '<='
| '>='
| '<>'
;
logBase
:
INTEGER_CONSTANT
;
powerExponent
:
(
(exponent)
|
(
('+' exponent)
)
|
(
('-' exponent)
)
)
;
exponent
: INTEGER_CONSTANT | FLOAT_CONSTANT
;
setExpr
: '(' constant (',' constant)* ')'
| 'union' '(' setExpr (',' setExpr)+ ')'
| 'symdiff' '(' setExpr ',' setExpr ')'
| 'intersect' '(' setExpr ',' setExpr ')'
;
varID
:
IDENTIFIER
;
compOp
: ('=')
| ('<')
| ('>')
| ('<=')
| ('>=')
| ('<>')
;
compOpScalar
: ('=')
| ('<')
| ('>')
| ('<=')
| ('>=')
| ('<>')
;
constant
: INTEGER_CONSTANT
| FLOAT_CONSTANT
| BOOLEAN_CONSTANT
| STRING_CONSTANT
| NULL_CONSTANT
;
isCompl
:
('Y')
| ('N')
;
lhperc
:
(
PLUS
| MINUS
)?
FLOAT_CONSTANT
| ('INF')
|
(
PLUS
| MINUS
)?
INTEGER_CONSTANT
;
|
grammar VTL;
options{
language = Java;
}
import Conditional;
start : statement+ EOF;
/* Assignment */
statement : variableRef ':=' expression;
/* Atom */
exprAtom : variableRef;
expression : getExpression
| putExpression
| exprAtom
;
getExpression : 'get(todo)';
putExpression : 'put(todo)';
variableRef : varID
| constant
;
constant : INTEGER_CONSTANT | FLOAT_CONSTANT | BOOLEAN_CONSTANT | STRING_CONSTANT | NULL_CONSTANT;
varID : IDENTIFIER;
IDENTIFIER:LETTER(LETTER|'_'|'0'..'9')*;
INTEGER_CONSTANT:'0'..'9'+;
FLOAT_CONSTANT : ('0'..'9')+ '.' ('0'..'9')* FLOATEXP?
| ('0'..'9')+ FLOATEXP
;
STRING_CONSTANT :'"' (~'"')* '"';
NULL_CONSTANT:'null';
fragment
FLOATEXP : ('e'|'E')(PLUS|MINUS)?('0'..'9')+;
PLUS : '+';
MINUS : '-';
fragment
LETTER : 'A'..'Z' | 'a'..'z';
WS : [ \r\t\u000C] -> skip ;
|
Add basic assignment in the main grammar file
|
Add basic assignment in the main grammar file
|
ANTLR
|
apache-2.0
|
hadrienk/java-vtl,statisticsnorway/java-vtl,hadrienk/java-vtl,hadrienk/java-vtl,statisticsnorway/java-vtl,statisticsnorway/java-vtl,statisticsnorway/java-vtl
|
aa3ae7b5a1f712c5f8b04261537ef8cd5478f9ef
|
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;
VALUE
: 'value'
;
BEAN
: 'bean'
;
TYPE
: 'type'
;
CONSTRUCTOR
: 'constructor'
;
MUTABLE_BUILDER
: 'builder'
;
IMMUTABLE_BUILDER
: 'immutable builder'
;
OPTIONAL
: 'optional'
;
OPEN_BLOCK
: '{'
;
CLOSE_BLOCK
: '}'
;
OPEN_TYPE_PARAMETERS
: '<'
;
CLOSE_TYPE_PARAMETERS
: '>'
;
PACKAGE
: 'package'
;
PACKAGE_SEPARATOR
: '.'
;
DEFAULT
: 'default' -> pushMode(LITERAL)
;
OPTIONS
: 'options'
;
EXTENDS
: ':'
;
IMPORT
: 'imports'
;
PROPERTIES
: 'properties'
;
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)))}?
;
INLINE_WS
: [ ]+ -> channel(HIDDEN)
;
LINE_BREAK
: ('\n' | '\r\n') -> channel(HIDDEN)
;
LINE_COMMENT
: '//' ~[\r\n]* -> skip
;
Identifier
: Letter LetterOrDigit*
;
mode LITERAL;
INLINE_WS_2
: [ ]+ -> skip
;
ANYTHING
: ~[ \t\r\n\u000C]+ -> 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;
VALUE
: 'value'
;
BEAN
: 'bean'
;
TYPE
: 'type'
;
CONSTRUCTOR
: 'constructor'
;
MUTABLE_BUILDER
: 'builder'
;
IMMUTABLE_BUILDER
: 'immutable builder'
;
OPTIONAL
: 'optional'
;
OPEN_TYPE_PARAMETERS
: '<'
;
CLOSE_TYPE_PARAMETERS
: '>'
;
PACKAGE
: 'package'
;
PACKAGE_SEPARATOR
: '.'
;
DEFAULT
: 'default' -> pushMode(LITERAL)
;
OPTIONS
: 'options'
;
EXTENDS
: ':'
;
IMPORT
: 'imports'
;
PROPERTIES
: 'properties'
;
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)))}?
;
INLINE_WS
: [ ]+ -> channel(HIDDEN)
;
LINE_BREAK
: ('\n' | '\r\n') -> channel(HIDDEN)
;
LINE_COMMENT
: '//' ~[\r\n]* -> skip
;
Identifier
: Letter LetterOrDigit*
;
mode LITERAL;
INLINE_WS_2
: [ ]+ -> skip
;
ANYTHING
: ~[ \t\r\n\u000C]+ -> popMode
;
|
Remove block opening and closing brackets.
|
Remove block opening and closing brackets.
|
ANTLR
|
bsd-3-clause
|
mattunderscorechampion/specky,mattunderscorechampion/specky,mattunderscorechampion/specky
|
d969f4ae5a5cb7ee9de3dd4f3cc33382469ef784
|
protostuff-parser/src/main/antlr4/io/protostuff/compiler/parser/ProtoLexer.g4
|
protostuff-parser/src/main/antlr4/io/protostuff/compiler/parser/ProtoLexer.g4
|
lexer grammar ProtoLexer;
PACKAGE
: 'package'
;
SYNTAX
: 'syntax'
;
IMPORT
: 'import'
;
PUBLIC
: 'public'
;
OPTION
: 'option'
;
MESSAGE
: 'message'
;
GROUP
: 'group'
;
OPTIONAL
: 'optional'
;
REQUIRED
: 'required'
;
REPEATED
: 'repeated'
;
ONEOF
: 'oneof'
;
EXTEND
: 'extend'
;
EXTENSIONS
: 'extensions'
;
TO
: 'to'
;
MAX
: 'max'
;
RESERVED
: 'reserved'
;
ENUM
: 'enum'
;
SERVICE
: 'service'
;
RPC
: 'rpc'
;
RETURNS
: 'returns'
;
STREAM
: 'stream'
;
MAP
: 'map'
;
BOOLEAN_VALUE
: 'true'
| 'false'
;
DOUBLE
: 'double'
;
FLOAT
: 'float'
;
INT32
: 'int32'
;
INT64
: 'int64'
;
UINT32
: 'uint32'
;
UINT64
: 'uint64'
;
SINT32
: 'sint32'
;
SINT64
: 'sint64'
;
FIXED32
: 'fixed32'
;
FIXED64
: 'fixed64'
;
SFIXED32
: 'sfixed32'
;
SFIXED64
: 'sfixed64'
;
BOOL
: 'bool'
;
STRING
: 'string'
;
BYTES
: 'bytes'
;
COMMENT
: '/*' .*? '*/' -> channel(HIDDEN)
;
LINE_COMMENT
: '//' ~('\r' | '\n')* -> channel(HIDDEN)
;
PLUGIN_DEV_MARKER
// Non-protobuf.
// Added for convenience of IntelliJ IDEA plugin development
: ('<caret>'
| '<error ' .*? '>'
| '</error>'
| '<fold ' .*? '>'
| '</fold>') -> channel(HIDDEN)
;
NL
: '\r'? '\n' -> channel(HIDDEN)
;
WS
: [ \t]+ -> channel(HIDDEN)
;
LCURLY
: '{'
;
RCURLY
: '}'
;
LPAREN
: '('
;
RPAREN
: ')'
;
LSQUARE
: '['
;
RSQUARE
: ']'
;
LT
: '<'
;
GT
: '>'
;
COMMA
: ','
;
DOT
: '.'
;
COLON
: ':'
;
SEMICOLON
: ';'
;
ASSIGN
: '='
;
IDENT
: (ALPHA | UNDERSCORE) (ALPHA | DIGIT | UNDERSCORE)*
;
STRING_VALUE
: DOUBLE_QUOTE_STRING
| SINGLE_QUOTE_STRING
;
INTEGER_VALUE
: DEC_VALUE
| HEX_VALUE
| OCT_VALUE
;
FLOAT_VALUE
: EXPONENT
| FLOAT_LIT
| MINUS? INF
| NAN
;
fragment DOUBLE_QUOTE_STRING
: '"' ( ESC_SEQ | ~('\\' | '"' | '\r' | '\n') )* '"'
;
fragment SINGLE_QUOTE_STRING
: '\'' ( ESC_SEQ | ~('\\' | '\'' | '\r' | '\n') )* '\''
;
fragment EXPONENT
: (FLOAT_LIT|DEC_VALUE) EXP DEC_VALUE
;
fragment FLOAT_LIT
: MINUS? DIGIT+ '.' DIGIT* // "0.", "0.123"
| MINUS? '.' DIGIT+ // ".123"
;
fragment INF
: 'inf'
;
fragment NAN
: 'nan'
;
fragment EXP
: 'e'
| 'E'
;
fragment DEC_VALUE
: '0' | MINUS? '1'..'9' '0'..'9'*
;
fragment HEX_VALUE
: MINUS? '0' [xX] HEX_DIGIT+
;
fragment OCT_VALUE
: MINUS? '0' OCT_DIGIT+
;
fragment MINUS
: '-'
;
fragment ALPHA
: [a-zA-Z]
;
fragment DIGIT
: [0-9]
;
fragment HEX_DIGIT
: [0-9a-fA-F]
;
fragment OCT_DIGIT
: [0-7]
;
fragment UNDERSCORE
: '_'
;
fragment ESC_SEQ
: '\\' ('a'|'v'|'b'|'t'|'n'|'f'|'r'|'?'|'"'|'\''|'\\')
| '\\' ('x'|'X') HEX_DIGIT HEX_DIGIT
| UNICODE_ESC
| OCTAL_ESC
;
fragment OCTAL_ESC
: '\\' [0-3] OCT_DIGIT OCT_DIGIT
| '\\' OCT_DIGIT OCT_DIGIT
| '\\' OCT_DIGIT
;
fragment UNICODE_ESC
: '\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
;
/** "catch all" rule for any char not matche in a token rule of your
* grammar. Lexers in Intellij must return all tokens good and bad.
* There must be a token to cover all characters, which makes sense, for
* an IDE. The parser however should not see these bad tokens because
* it just confuses the issue. Hence, the hidden channel.
*/
ERRCHAR
: . -> channel(HIDDEN)
;
|
lexer grammar ProtoLexer;
PACKAGE
: 'package'
;
SYNTAX
: 'syntax'
;
IMPORT
: 'import'
;
PUBLIC
: 'public'
;
OPTION
: 'option'
;
MESSAGE
: 'message'
;
GROUP
: 'group'
;
OPTIONAL
: 'optional'
;
REQUIRED
: 'required'
;
REPEATED
: 'repeated'
;
ONEOF
: 'oneof'
;
EXTEND
: 'extend'
;
EXTENSIONS
: 'extensions'
;
TO
: 'to'
;
MAX
: 'max'
;
RESERVED
: 'reserved'
;
ENUM
: 'enum'
;
SERVICE
: 'service'
;
RPC
: 'rpc'
;
RETURNS
: 'returns'
;
STREAM
: 'stream'
;
MAP
: 'map'
;
BOOLEAN_VALUE
: 'true'
| 'false'
;
DOUBLE
: 'double'
;
FLOAT
: 'float'
;
INT32
: 'int32'
;
INT64
: 'int64'
;
UINT32
: 'uint32'
;
UINT64
: 'uint64'
;
SINT32
: 'sint32'
;
SINT64
: 'sint64'
;
FIXED32
: 'fixed32'
;
FIXED64
: 'fixed64'
;
SFIXED32
: 'sfixed32'
;
SFIXED64
: 'sfixed64'
;
BOOL
: 'bool'
;
STRING
: 'string'
;
BYTES
: 'bytes'
;
COMMENT
: '/*' .*? '*/' -> channel(HIDDEN)
;
LINE_COMMENT
: '//' ~('\r' | '\n')* -> channel(HIDDEN)
;
PLUGIN_DEV_MARKER
// Non-protobuf.
// Added for convenience of IntelliJ IDEA plugin development
: ('<caret>'
| '<error ' .*? '>'
| '</error>'
| '<fold ' .*? '>'
| '</fold>'
| '<TYPO ' .*? '>'
| '</TYPO>'
) -> channel(HIDDEN)
;
NL
: '\r'? '\n' -> channel(HIDDEN)
;
WS
: [ \t]+ -> channel(HIDDEN)
;
LCURLY
: '{'
;
RCURLY
: '}'
;
LPAREN
: '('
;
RPAREN
: ')'
;
LSQUARE
: '['
;
RSQUARE
: ']'
;
LT
: '<'
;
GT
: '>'
;
COMMA
: ','
;
DOT
: '.'
;
COLON
: ':'
;
SEMICOLON
: ';'
;
ASSIGN
: '='
;
IDENT
: (ALPHA | UNDERSCORE) (ALPHA | DIGIT | UNDERSCORE)*
;
STRING_VALUE
: DOUBLE_QUOTE_STRING
| SINGLE_QUOTE_STRING
;
INTEGER_VALUE
: DEC_VALUE
| HEX_VALUE
| OCT_VALUE
;
FLOAT_VALUE
: EXPONENT
| FLOAT_LIT
| MINUS? INF
| NAN
;
fragment DOUBLE_QUOTE_STRING
: '"' ( ESC_SEQ | ~('\\' | '"' | '\r' | '\n') )* '"'
;
fragment SINGLE_QUOTE_STRING
: '\'' ( ESC_SEQ | ~('\\' | '\'' | '\r' | '\n') )* '\''
;
fragment EXPONENT
: (FLOAT_LIT|DEC_VALUE) EXP DEC_VALUE
;
fragment FLOAT_LIT
: MINUS? DIGIT+ '.' DIGIT* // "0.", "0.123"
| MINUS? '.' DIGIT+ // ".123"
;
fragment INF
: 'inf'
;
fragment NAN
: 'nan'
;
fragment EXP
: 'e'
| 'E'
;
fragment DEC_VALUE
: '0' | MINUS? '1'..'9' '0'..'9'*
;
fragment HEX_VALUE
: MINUS? '0' [xX] HEX_DIGIT+
;
fragment OCT_VALUE
: MINUS? '0' OCT_DIGIT+
;
fragment MINUS
: '-'
;
fragment ALPHA
: [a-zA-Z]
;
fragment DIGIT
: [0-9]
;
fragment HEX_DIGIT
: [0-9a-fA-F]
;
fragment OCT_DIGIT
: [0-7]
;
fragment UNDERSCORE
: '_'
;
fragment ESC_SEQ
: '\\' ('a'|'v'|'b'|'t'|'n'|'f'|'r'|'?'|'"'|'\''|'\\')
| '\\' ('x'|'X') HEX_DIGIT HEX_DIGIT
| UNICODE_ESC
| OCTAL_ESC
;
fragment OCTAL_ESC
: '\\' [0-3] OCT_DIGIT OCT_DIGIT
| '\\' OCT_DIGIT OCT_DIGIT
| '\\' OCT_DIGIT
;
fragment UNICODE_ESC
: '\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
;
/** "catch all" rule for any char not matche in a token rule of your
* grammar. Lexers in Intellij must return all tokens good and bad.
* There must be a token to cover all characters, which makes sense, for
* an IDE. The parser however should not see these bad tokens because
* it just confuses the issue. Hence, the hidden channel.
*/
ERRCHAR
: . -> channel(HIDDEN)
;
|
Add special token types for IntelliJ Plugin spellchecker test
|
Add special token types for IntelliJ Plugin spellchecker test
|
ANTLR
|
apache-2.0
|
kshchepanovskyi/proto-compiler,kshchepanovskyi/protostuff-compiler,protostuff/protostuff-compiler,protostuff/protostuff-compiler,protostuff/protostuff-compiler,kshchepanovskyi/protostuff-compiler,kshchepanovskyi/proto-compiler,kshchepanovskyi/protostuff-compiler,kshchepanovskyi/proto-compiler
|
ab5e1625e440285c1f4a262234be5dc1486e7a82
|
grammars/JSON.g4
|
grammars/JSON.g4
|
grammar JSON;
json
: object
| array
;
object
: '{' pair (',' pair)* '}'
| '{' '}'
;
pair
: STRING ':' value
;
array
: '[' value (',' value)* ']'
| '[' ']'
;
value
: STRING
| NUMBER
| object
| array
| 'true'
| 'false'
| 'null'
;
STRING
: '"' (ESC | ~["\\])* '"'
;
fragment ESC
: '\\' (["\\/bfnrt] | UNICODE)
;
fragment UNICODE
: 'u' HEX HEX HEX HEX
;
fragment HEX
: [0-9a-fA-F]
;
NUMBER
: '-'? INT '.' [0-9] + EXP? | '-'? INT EXP | '-'? INT
;
fragment INT
: '0' | [1-9] [0-9]*
;
// no leading zeros
fragment EXP
: [Ee] [+-]? INT
;
// \- since - means "range" inside [...]
WS
: [ \t\n\r] + -> skip
;
|
grammar JSON;
json
: object
| array
;
object
: '{' pair (',' pair)* '}'
| '{' '}'
;
pair
: '"' STRING '":' value
;
array
: '[' value (',' value)* ']'
| '[' ']'
;
value
: '"' STRING '"'
| NUMBER
| object
| array
| 'true'
| 'false'
| 'null'
;
STRING
: (ESC | ~["\\])*
;
fragment ESC
: '\\' (["\\/bfnrt] | UNICODE)
;
fragment UNICODE
: 'u' HEX HEX HEX HEX
;
fragment HEX
: [0-9a-fA-F]
;
NUMBER
: '-'? INT '.' [0-9] + EXP? | '-'? INT EXP | '-'? INT
;
fragment INT
: '0' | [1-9] [0-9]*
;
// no leading zeros
fragment EXP
: [Ee] [+-]? INT
;
// \- since - means "range" inside [...]
WS
: [ \t\n\r] + -> skip
;
|
Fix JSON grammar so quotes are not included in value
|
Fix JSON grammar so quotes are not included in value
|
ANTLR
|
apache-2.0
|
premun/ingrid
|
71fb6f4f004cf36f99ab540b6120f32b77b81655
|
Code/src/main/antlr4/nl/utwente/group10/haskell/typeparser/Type.g4
|
Code/src/main/antlr4/nl/utwente/group10/haskell/typeparser/Type.g4
|
grammar Type;
CT : [A-Z][a-z]+ ;
VT : [a-z]+ ;
WS : [ \t\r\n]+ -> skip ;
type : functionType | compoundType; // function type
functionType : compoundType ('->' type)+ ;
compoundType : concreteType | tupleType | listType | parenType ;
tupleType : '(' type (',' type)+ ')' ; // tuple type, k>=2
listType : '[' type ']' ; // list type
parenType : '(' type ')' ; // parenthesised constructor
concreteType : constantType | variableType ;
constantType : CT ;
variableType : VT ;
|
grammar Type;
CT : [A-Z][a-z]+ ;
VT : [a-z]+ ;
WS : [ \t\r\n]+ -> skip ;
type : functionType | compoundType ; // function type
functionType : compoundType '->' type ;
compoundType : constantType | variableType | tupleType | listType | parenType ;
tupleType : '(' type (',' type)+ ')' ; // tuple type, k>=2
listType : '[' type ']' ; // list type
parenType : '(' type ')' ; // type with parentheses
constantType : CT ;
variableType : VT ;
|
Change antler grammar to support new type API
|
Change antler grammar to support new type API
|
ANTLR
|
mit
|
andrewdavidmackenzie/viskell,viskell/viskell,wandernauta/viskell
|
d5b2416561f19b06bf8b7bf67f482e35e8d2c9ab
|
src/main/antlr4/xyz/morecraft/dev/lang/morelang/MoreLangGrammar.g4
|
src/main/antlr4/xyz/morecraft/dev/lang/morelang/MoreLangGrammar.g4
|
grammar MoreLangGrammar;
@header {
import xyz.morecraft.dev.lang.morelang.object.Program;
import xyz.morecraft.dev.lang.morelang.object.Statement;
}
program:
programHeader? programBody;
programBody :
(SEMICOLON | functionDefinition)+;
body :
(SEMICOLON | statement)+;
bodyBlock :
BRACKET_BRACE_OP body BRACKET_BRACE_CLOSE;
programHeader :
(ctrlImport)+;
ctrlImport:
CTRL_IMPORT ctrlImportName SEMICOLON;
ctrlImportName:
ID (CTRL_DOT ID)*;
statement :
((assignmentStatement | functionInvocationStatement) SEMICOLON) | variableDefinitionStatement | ifStatement | whileLoopStatement;
ifStatement :
CTRL_IF BRACKET_PAREN_OP expression BRACKET_PAREN_CLOSE bodyBlock (CTRL_ELSE (bodyBlock | ifStatement))?;
whileLoopStatement :
CTRL_WHILE BRACKET_PAREN_OP expression BRACKET_PAREN_CLOSE bodyBlock;
variableDefinitionStatement :
typedIdentifier TAB_SUFFIX? (EQUAL expression)? SEMICOLON;
value :
VAL_STRING | VAL_INT | VAL_FLOAT;
returnStatement :
CTRL_RETURN expression?;
expression :
assignmentStatement | atomicExpression | arithmeticExpression;
arithmeticExpression :
(simpleExpression (operator simpleExpression)+);
simpleExpression :
atomicExpression | (BRACKET_PAREN_OP expression BRACKET_PAREN_CLOSE);
atomicExpression:
value | variable | functionInvocationStatement;
assignmentStatement :
variable (BRACKET_SQUARE_OP VAL_INT BRACKET_SQUARE_CLOSE)? EQUAL expression;
functionDefinition :
functionDefinitionHeader BRACKET_BRACE_OP body returnStatement SEMICOLON BRACKET_BRACE_CLOSE;
functionInvocationStatement:
identifier BRACKET_PAREN_OP functionInvocationArguments BRACKET_PAREN_CLOSE;
functionDefinitionHeader :
typedIdentifier BRACKET_PAREN_OP functionDefinitionHeaderArguments BRACKET_PAREN_CLOSE;
functionDefinitionHeaderArguments:
((typedIdentifier) (COMMA (typedIdentifier))*)?;
functionInvocationArguments :
((value | variable) (COMMA (value | variable) )*)?;
typedIdentifier:
type identifier;
variable:
identifier (BRACKET_SQUARE_OP expression BRACKET_SQUARE_CLOSE)?;
identifier:
ID;
type:
((INT | FLOAT | STRING) TAB_SUFFIX?) | VOID;
operator :
OP_PLUS | OP_MINUS | OP_DIVIDE | OP_MULTIPLY | OP_COMPARE | OP_COMPARE_NEG | OP_AND | OP_OR;
// control sequences
CTRL_IMPORT : 'import';
CTRL_RETURN : 'return';
CTRL_IF : 'if';
CTRL_ELSE : 'else';
CTRL_WHILE : 'while';
CTRL_DOT : '.';
// types
INT : 'int';
FLOAT : 'float';
STRING : 'string';
VOID : 'void';
TAB_SUFFIX : '[]';
// operations
OP_PLUS : '+';
OP_MINUS : '-';
OP_DIVIDE : '/';
OP_MULTIPLY : '*';
OP_COMPARE : '==';
OP_COMPARE_NEG : '!=';
OP_AND : '&&';
OP_OR : '||';
// values
VAL_STRING : ['].*?['];
VAL_INT : [0-9];
VAL_FLOAT : [0-9]* '.' [0-9]+;
//special
EQUAL : '=';
COMMA : ',';
SEMICOLON : ';';
BRACKET_PAREN_OP : '(';
BRACKET_PAREN_CLOSE : ')';
BRACKET_BRACE_OP : '{';
BRACKET_BRACE_CLOSE : '}';
BRACKET_SQUARE_OP : '[';
BRACKET_SQUARE_CLOSE : ']';
ID : [a-zA-Z][a-zA-Z0-9]*;
WS : (' '|'\r'|'\n') -> skip;
COMMENT : ( '//' ~[\r\n]* '\r'? '\n' | '/*' .*? '*/' ) -> skip;
|
grammar MoreLangGrammar;
@header {
import xyz.morecraft.dev.lang.morelang.object.Program;
import xyz.morecraft.dev.lang.morelang.object.Statement;
}
program:
programHeader? programBody;
programBody :
(SEMICOLON | functionDefinition)+;
body :
(SEMICOLON | statement)+;
bodyBlock :
BRACKET_BRACE_OP body BRACKET_BRACE_CLOSE;
programHeader :
(ctrlImport)+;
ctrlImport:
CTRL_IMPORT ctrlImportName SEMICOLON;
ctrlImportName:
ID (CTRL_DOT ID)*;
statement :
((assignmentStatement | functionInvocationStatement) SEMICOLON) | variableDefinitionStatement | ifStatement | whileLoopStatement;
ifStatement :
CTRL_IF BRACKET_PAREN_OP expression BRACKET_PAREN_CLOSE bodyBlock (CTRL_ELSE (bodyBlock | ifStatement))?;
whileLoopStatement :
CTRL_WHILE BRACKET_PAREN_OP expression BRACKET_PAREN_CLOSE bodyBlock;
variableDefinitionStatement :
typedIdentifier TAB_SUFFIX? (EQUAL expression)? SEMICOLON;
assignmentStatement :
variable (BRACKET_SQUARE_OP VAL_INT BRACKET_SQUARE_CLOSE)? EQUAL expression;
value :
VAL_STRING | VAL_INT | VAL_FLOAT;
returnStatement :
CTRL_RETURN expression?;
expression :
expression operator expression
| '(' expression ')'
| atomicExpression
| assignmentStatement;
atomicExpression:
value | variable | functionInvocationStatement;
functionDefinition :
functionDefinitionHeader BRACKET_BRACE_OP body returnStatement SEMICOLON BRACKET_BRACE_CLOSE;
functionInvocationStatement:
identifier BRACKET_PAREN_OP functionInvocationArguments BRACKET_PAREN_CLOSE;
functionDefinitionHeader :
typedIdentifier BRACKET_PAREN_OP functionDefinitionHeaderArguments BRACKET_PAREN_CLOSE;
functionDefinitionHeaderArguments:
((typedIdentifier) (COMMA (typedIdentifier))*)?;
functionInvocationArguments :
((value | variable) (COMMA (value | variable) )*)?;
typedIdentifier:
type identifier;
variable:
identifier (BRACKET_SQUARE_OP expression BRACKET_SQUARE_CLOSE)?;
identifier:
ID;
type:
((INT | FLOAT | STRING) TAB_SUFFIX?) | VOID;
operator :
OP_PLUS | OP_MINUS | OP_DIVIDE | OP_MULTIPLY | OP_COMPARE | OP_COMPARE_NEG | OP_AND | OP_OR;
// control sequences
CTRL_IMPORT : 'import';
CTRL_RETURN : 'return';
CTRL_IF : 'if';
CTRL_ELSE : 'else';
CTRL_WHILE : 'while';
CTRL_DOT : '.';
// types
INT : 'int';
FLOAT : 'float';
STRING : 'string';
VOID : 'void';
TAB_SUFFIX : '[]';
// operations
OP_PLUS : '+';
OP_MINUS : '-';
OP_DIVIDE : '/';
OP_MULTIPLY : '*';
OP_COMPARE : '==';
OP_COMPARE_NEG : '!=';
OP_AND : '&&';
OP_OR : '||';
// values
VAL_STRING : ['].*?['];
VAL_INT : [0-9];
VAL_FLOAT : [0-9]* '.' [0-9]+;
//special
EQUAL : '=';
COMMA : ',';
SEMICOLON : ';';
BRACKET_PAREN_OP : '(';
BRACKET_PAREN_CLOSE : ')';
BRACKET_BRACE_OP : '{';
BRACKET_BRACE_CLOSE : '}';
BRACKET_SQUARE_OP : '[';
BRACKET_SQUARE_CLOSE : ']';
ID : [a-zA-Z][a-zA-Z0-9]*;
WS : (' '|'\r'|'\n') -> skip;
COMMENT : ( '//' ~[\r\n]* '\r'? '\n' | '/*' .*? '*/' ) -> skip;
|
Switch expression parsing strategy to tree-like
|
Switch expression parsing strategy to tree-like
|
ANTLR
|
mit
|
EmhyrVarEmreis/MoreLang,EmhyrVarEmreis/MoreLang
|
b64338343836c428e6f0be8adcab5696e3308e29
|
org.eclipse.titan.designer/src/org/eclipse/titan/designer/parsers/ttcn3parser/Ttcn3Lexer.g4
|
org.eclipse.titan.designer/src/org/eclipse/titan/designer/parsers/ttcn3parser/Ttcn3Lexer.g4
|
lexer grammar Ttcn3Lexer;
import Ttcn3BaseLexer;
/*
******************************************************************************
* Copyright (c) 2000-2016 Ericsson Telecom AB
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************
*/
/*
* author Arpad Lovassy
*/
//Overriding tokens inherited from TTCN3BaseLexer4
/*------------------------------------------- Keywords -------------------------------------------*/
ACTION: 'action'; ACTIVATE: 'activate'; ADDRESS: 'address';
ALIVE: 'alive'; ALL: 'all'; ALT: 'alt';
ALTSTEP: 'altstep'; AND: 'and'; AND4B: 'and4b';
ANY: 'any'; ANYTYPE: 'anytype'; ANY2UNISTR: 'any2unistr';
APPLY: 'apply';
BITSTRING: 'bitstring'; BOOLEAN: 'boolean'; BREAK: 'break';
CALL: 'call'; CASE: 'case'; CATCH: 'catch';
CHARKEYWORD: 'char'; CHARSTRING: 'charstring'; CHECK: 'check';
CHECKSTATE: 'checkstate'; CLEAR: 'clear'; COMPLEMENTKEYWORD: 'complement';
COMPONENT: 'component'; CONNECT: 'connect'; CONST: 'const';
CONTINUE: 'continue'; CONTROL: 'control'; CREATE: 'create';
DEACTIVATE: 'deactivate'; DEFAULT: 'default'; DECMATCH: 'decmatch';
DECVALUE: 'decvalue'; DECVALUE_UNICHAR: 'decvalue_unichar';
DEREFERS: 'derefers'; DISCONNECT: 'disconnect'; DISPLAY: 'display';
DO: 'do'; DONE: 'done';
ELSE: 'else'; ENCODE: 'encode'; ENCVALUE: 'encvalue';
ENCVALUE_UNICHAR: 'encvalue_unichar'; ENUMERATED: 'enumerated';
ERROR: 'error'; EXCEPT: 'except'; EXCEPTION: 'exception';
EXECUTE: 'execute'; EXTENDS: 'extends';
EXTENSION: 'extension'; EXTERNAL: 'external';
FAIL: 'fail'; FALSE: 'false'; FLOAT: 'float';
FOR: 'for'; FRIEND: 'friend'; FROM: 'from';
FUNCTION: 'function';
GETCALL: 'getcall'; GETREPLY: 'getreply'; GETVERDICT: 'getverdict';
GOTO: 'goto'; GROUP: 'group';
HALT: 'halt'; HEXSTRING: 'hexstring'; HOSTID: 'hostid';
IF: 'if'; IFPRESENT: 'ifpresent'; IMPORT: 'import';
IN: 'in'; INCONC: 'inconc'; INFINITY: 'infinity';
INOUT: 'inout'; INTEGER: 'integer'; INTERLEAVE: 'interleave';
ISTEMPLATEKIND: 'istemplatekind';
KILL: 'kill'; KILLED: 'killed';
LABEL: 'label'; LANGUAGE: 'language'; LENGTH: 'length';
LOG: 'log';
MAP: 'map'; MATCH: 'match'; MESSAGE: 'message';
MIXED: 'mixed'; MOD: 'mod'; MODIFIES: 'modifies';
MODULE: 'module'; MODULEPAR: 'modulepar'; MTC: 'mtc';
NOBLOCK: 'noblock'; NONE: 'none';
NOT: 'not'; NOT4B: 'not4b'; NOWAIT: 'nowait';
NOT_A_NUMBER: 'not_a_number'; NULL1: 'null'; NULL2: 'NULL';
OBJECTIDENTIFIERKEYWORD: 'objid'; OCTETSTRING: 'octetstring'; OF: 'of';
OMIT: 'omit'; ON: 'on'; OPTIONAL: 'optional';
OR: 'or'; OR4B: 'or4b'; OUT: 'out';
OVERRIDEKEYWORD: 'override';
PARAM: 'param'; PASS: 'pass'; PATTERNKEYWORD: 'pattern';
PERMUTATION: 'permutation'; PORT: 'port'; PUBLIC: 'public';
PRESENT: 'present'; PRIVATE: 'private'; PROCEDURE: 'procedure';
RAISE: 'raise'; READ: 'read'; RECEIVE: 'receive';
RECORD: 'record'; RECURSIVE: 'recursive'; REFERS: 'refers';
REM: 'rem'; REPEAT: 'repeat'; REPLY: 'reply';
RETURN: 'return'; RUNNING: 'running'; RUNS: 'runs';
SELECT: 'select'; SELF: 'self'; SEND: 'send';
SENDER: 'sender'; SET: 'set'; SETVERDICT: 'setverdict';
SIGNATURE: 'signature'; START: 'start';
STOP: 'stop'; SUBSET: 'subset'; SUPERSET: 'superset';
SYSTEM: 'system';
TEMPLATE: 'template'; TESTCASE: 'testcase'; TIMEOUT: 'timeout';
TIMER: 'timer'; TO: 'to'; TRIGGER: 'trigger';
TRUE: 'true'; TYPE: 'type';
UNION: 'union'; UNIVERSAL: 'universal'; UNMAP: 'unmap';
VALUE: 'value'; VALUEOF: 'valueof'; VAR: 'var';
VARIANT: 'variant'; VERDICTTYPE: 'verdicttype';
WHILE: 'while'; WITH: 'with';
XOR: 'xor'; XOR4B: 'xor4b';
/*------------------------------ Predefined function identifiers --------------------------------*/
BIT2HEX: 'bit2hex'; BIT2INT: 'bit2int'; BIT2OCT: 'bit2oct'; BIT2STR: 'bit2str';
CHAR2INT: 'char2int'; CHAR2OCT: 'char2oct';
DECOMP: 'decomp';
ENUM2INT: 'enum2int';
FLOAT2INT: 'float2int'; FLOAT2STR: 'float2str';
HEX2BIT: 'hex2bit'; HEX2INT: 'hex2int'; HEX2OCT: 'hex2oct'; HEX2STR: 'hex2str';
INT2BIT: 'int2bit'; INT2CHAR: 'int2char'; INT2ENUM: 'int2enum'; INT2FLOAT: 'int2float';
INT2HEX: 'int2hex'; INT2OCT: 'int2oct'; INT2STR: 'int2str'; INT2UNICHAR: 'int2unichar';
ISVALUE: 'isvalue'; ISCHOSEN: 'ischosen'; ISPRESENT: 'ispresent'; ISBOUND: 'isbound';
LENGTHOF: 'lengthof'; LOG2STR: 'log2str';
OCT2BIT: 'oct2bit'; OCT2CHAR: 'oct2char'; OCT2HEX: 'oct2hex';
OCT2INT: 'oct2int'; OCT2STR: 'oct2str';
REGEXP: 'regexp'; REPLACE: 'replace'; RND: 'rnd';
SIZEOF: 'sizeof';
STR2BIT: 'str2bit'; STR2FLOAT: 'str2float'; STR2HEX: 'str2hex';
STR2INT: 'str2int'; STR2OCT: 'str2oct';
SUBSTR: 'substr';
TESTCASENAME: 'testcasename';
UNICHAR2INT: 'unichar2int'; UNICHAR2CHAR: 'unichar2char';
TTCN2STRING: 'ttcn2string'; STRING2TTCN: 'string2ttcn';
GET_STRINGENCODING: 'get_stringencoding'; OCT2UNICHAR: 'oct2unichar'; REMOVE_BOM: 'remove_bom';
UNICHAR2OCT: 'unichar2oct'; ENCODE_BASE64: 'encode_base64'; DECODE_BASE64: 'decode_base64';
|
lexer grammar Ttcn3Lexer;
import Ttcn3BaseLexer;
/*
******************************************************************************
* Copyright (c) 2000-2016 Ericsson Telecom AB
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************
*/
/*
* author Arpad Lovassy
*/
//Overriding tokens inherited from TTCN3BaseLexer.g4
/*------------------------------------------- Keywords -------------------------------------------*/
ACTION: 'action'; ACTIVATE: 'activate'; ADDRESS: 'address';
ALIVE: 'alive'; ALL: 'all'; ALT: 'alt';
ALTSTEP: 'altstep'; AND: 'and'; AND4B: 'and4b';
ANY: 'any'; ANYTYPE: 'anytype'; ANY2UNISTR: 'any2unistr';
APPLY: 'apply';
BITSTRING: 'bitstring'; BOOLEAN: 'boolean'; BREAK: 'break';
CALL: 'call'; CASE: 'case'; CATCH: 'catch';
CHARKEYWORD: 'char'; CHARSTRING: 'charstring'; CHECK: 'check';
CHECKSTATE: 'checkstate'; CLEAR: 'clear'; COMPLEMENTKEYWORD: 'complement';
COMPONENT: 'component'; CONNECT: 'connect'; CONST: 'const';
CONTINUE: 'continue'; CONTROL: 'control'; CREATE: 'create';
DEACTIVATE: 'deactivate'; DEFAULT: 'default'; DECMATCH: 'decmatch';
DECVALUE: 'decvalue'; DECVALUE_UNICHAR: 'decvalue_unichar';
DEREFERS: 'derefers'; DISCONNECT: 'disconnect'; DISPLAY: 'display';
DO: 'do'; DONE: 'done';
ELSE: 'else'; ENCODE: 'encode'; ENCVALUE: 'encvalue';
ENCVALUE_UNICHAR: 'encvalue_unichar'; ENUMERATED: 'enumerated';
ERROR: 'error'; EXCEPT: 'except'; EXCEPTION: 'exception';
EXECUTE: 'execute'; EXTENDS: 'extends';
EXTENSION: 'extension'; EXTERNAL: 'external';
FAIL: 'fail'; FALSE: 'false'; FLOAT: 'float';
FOR: 'for'; FRIEND: 'friend'; FROM: 'from';
FUNCTION: 'function';
GETCALL: 'getcall'; GETREPLY: 'getreply'; GETVERDICT: 'getverdict';
GOTO: 'goto'; GROUP: 'group';
HALT: 'halt'; HEXSTRING: 'hexstring'; HOSTID: 'hostid';
IF: 'if'; IFPRESENT: 'ifpresent'; IMPORT: 'import';
IN: 'in'; INCONC: 'inconc'; INFINITY: 'infinity';
INOUT: 'inout'; INTEGER: 'integer'; INTERLEAVE: 'interleave';
ISTEMPLATEKIND: 'istemplatekind';
KILL: 'kill'; KILLED: 'killed';
LABEL: 'label'; LANGUAGE: 'language'; LENGTH: 'length';
LOG: 'log';
MAP: 'map'; MATCH: 'match'; MESSAGE: 'message';
MIXED: 'mixed'; MOD: 'mod'; MODIFIES: 'modifies';
MODULE: 'module'; MODULEPAR: 'modulepar'; MTC: 'mtc';
NOBLOCK: 'noblock'; NONE: 'none';
NOT: 'not'; NOT4B: 'not4b'; NOWAIT: 'nowait';
NOT_A_NUMBER: 'not_a_number'; NULL1: 'null'; NULL2: 'NULL';
OBJECTIDENTIFIERKEYWORD: 'objid'; OCTETSTRING: 'octetstring'; OF: 'of';
OMIT: 'omit'; ON: 'on'; OPTIONAL: 'optional';
OR: 'or'; OR4B: 'or4b'; OUT: 'out';
OVERRIDEKEYWORD: 'override';
PARAM: 'param'; PASS: 'pass'; PATTERNKEYWORD: 'pattern';
PERMUTATION: 'permutation'; PORT: 'port'; PUBLIC: 'public';
PRESENT: 'present'; PRIVATE: 'private'; PROCEDURE: 'procedure';
RAISE: 'raise'; READ: 'read'; RECEIVE: 'receive';
RECORD: 'record'; RECURSIVE: 'recursive'; REFERS: 'refers';
REM: 'rem'; REPEAT: 'repeat'; REPLY: 'reply';
RETURN: 'return'; RUNNING: 'running'; RUNS: 'runs';
SELECT: 'select'; SELF: 'self'; SEND: 'send';
SENDER: 'sender'; SET: 'set'; SETVERDICT: 'setverdict';
SIGNATURE: 'signature'; START: 'start';
STOP: 'stop'; SUBSET: 'subset'; SUPERSET: 'superset';
SYSTEM: 'system';
TEMPLATE: 'template'; TESTCASE: 'testcase'; TIMEOUT: 'timeout';
TIMER: 'timer'; TO: 'to'; TRIGGER: 'trigger';
TRUE: 'true'; TYPE: 'type';
UNION: 'union'; UNIVERSAL: 'universal'; UNMAP: 'unmap';
VALUE: 'value'; VALUEOF: 'valueof'; VAR: 'var';
VARIANT: 'variant'; VERDICTTYPE: 'verdicttype';
WHILE: 'while'; WITH: 'with';
XOR: 'xor'; XOR4B: 'xor4b';
/*------------------------------ Predefined function identifiers --------------------------------*/
BIT2HEX: 'bit2hex'; BIT2INT: 'bit2int'; BIT2OCT: 'bit2oct'; BIT2STR: 'bit2str';
CHAR2INT: 'char2int'; CHAR2OCT: 'char2oct';
DECOMP: 'decomp';
ENUM2INT: 'enum2int';
FLOAT2INT: 'float2int'; FLOAT2STR: 'float2str';
HEX2BIT: 'hex2bit'; HEX2INT: 'hex2int'; HEX2OCT: 'hex2oct'; HEX2STR: 'hex2str';
INT2BIT: 'int2bit'; INT2CHAR: 'int2char'; INT2ENUM: 'int2enum'; INT2FLOAT: 'int2float';
INT2HEX: 'int2hex'; INT2OCT: 'int2oct'; INT2STR: 'int2str'; INT2UNICHAR: 'int2unichar';
ISVALUE: 'isvalue'; ISCHOSEN: 'ischosen'; ISPRESENT: 'ispresent'; ISBOUND: 'isbound';
LENGTHOF: 'lengthof'; LOG2STR: 'log2str';
OCT2BIT: 'oct2bit'; OCT2CHAR: 'oct2char'; OCT2HEX: 'oct2hex';
OCT2INT: 'oct2int'; OCT2STR: 'oct2str';
REGEXP: 'regexp'; REPLACE: 'replace'; RND: 'rnd';
SIZEOF: 'sizeof';
STR2BIT: 'str2bit'; STR2FLOAT: 'str2float'; STR2HEX: 'str2hex';
STR2INT: 'str2int'; STR2OCT: 'str2oct';
SUBSTR: 'substr';
TESTCASENAME: 'testcasename';
UNICHAR2INT: 'unichar2int'; UNICHAR2CHAR: 'unichar2char';
TTCN2STRING: 'ttcn2string'; STRING2TTCN: 'string2ttcn';
GET_STRINGENCODING: 'get_stringencoding'; OCT2UNICHAR: 'oct2unichar'; REMOVE_BOM: 'remove_bom';
UNICHAR2OCT: 'unichar2oct'; ENCODE_BASE64: 'encode_base64'; DECODE_BASE64: 'decode_base64';
|
comment fixed
|
comment fixed
Signed-off-by: earplov <[email protected]>
|
ANTLR
|
epl-1.0
|
eroslevi/titan.EclipsePlug-ins,eroslevi/titan.EclipsePlug-ins,eroslevi/titan.EclipsePlug-ins,eroslevi/titan.EclipsePlug-ins,eroslevi/titan.EclipsePlug-ins
|
5925caba36db7131e6a990086025e8cd72415e64
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE temporaryClause_ TABLE existClause_ tableName (createDefinitionClause_ | createLikeClause_)
;
createIndex
: CREATE (UNIQUE | FULLTEXT | SPATIAL)? INDEX indexName indexType_? ON tableName
;
alterTable
: ALTER TABLE tableName alterSpecifications_?
;
dropTable
: DROP TEMPORARY? TABLE (IF EXISTS)? tableName (COMMA_ tableName)*
;
dropIndex
: DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName
;
truncateTable
: TRUNCATE TABLE? tableName
;
temporaryClause_
: TEMPORARY?
;
existClause_
: (IF NOT EXISTS)?
;
createDefinitionClause_
: LP_ createDefinitions_ RP_
;
createLikeClause_
: LP_? LIKE tableName RP_?
;
createDefinitions_
: createDefinition_ (COMMA_ createDefinition_)*
;
createDefinition_
: columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_
;
columnDefinition
: columnName dataType (inlineDataType_* | generatedDataType_*)
;
indexDefinition_
: (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
constraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_)
;
checkConstraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)?
;
inlineDataType_
: commonDataTypeOption_
| NOT? NULL
| AUTO_INCREMENT
| DEFAULT (literals | expr)
| COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT)
| STORAGE (DISK | MEMORY | DEFAULT)
;
generatedDataType_
: commonDataTypeOption_
| (GENERATED ALWAYS)? AS expr
| (VIRTUAL | STORED)
;
commonDataTypeOption_
: primaryKey | UNIQUE KEY? | collateClause_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_
;
referenceDefinition_
: REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)*
;
referenceOption_
: RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT
;
indexType_
: USING (BTREE | HASH)
;
keyParts_
: LP_ keyPart_ (COMMA_ keyPart_)* RP_
;
keyPart_
: (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)?
;
indexOption_
: KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE
;
primaryKeyOption_
: primaryKey indexType_? columnNames indexOption_*
;
primaryKey
: PRIMARY? KEY
;
uniqueOption_
: UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
foreignKeyOption_
: FOREIGN KEY indexName? columnNames referenceDefinition_
;
alterSpecifications_
: alterSpecification_ (COMMA_ alterSpecification_)*
;
alterSpecification_
: tableOptions_
| addColumnSpecification
| addIndexSpecification
| addConstraintSpecification
| ADD checkConstraintDefinition_
| DROP CHECK ignoredIdentifier_
| ALTER CHECK ignoredIdentifier_ NOT? ENFORCED
| ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY)
| ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT)
| ALTER INDEX indexName (VISIBLE | INVISIBLE)
| changeColumnSpecification
| DEFAULT? characterSet_ collateClause_?
| CONVERT TO characterSet_ collateClause_?
| (DISABLE | ENABLE) KEYS
| (DISCARD | IMPORT_) TABLESPACE
| dropColumnSpecification
| dropIndexSpecification
| dropPrimaryKeySpecification
| DROP FOREIGN KEY ignoredIdentifier_
| FORCE
| LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE)
| modifyColumnSpecification
// TODO hongjun investigate ORDER BY col_name [, col_name] ...
| ORDER BY columnName (COMMA_ columnName)*
| renameColumnSpecification
| renameIndexSpecification
| renameTableSpecification_
| (WITHOUT | WITH) VALIDATION
| ADD PARTITION LP_ partitionDefinition_ RP_
| DROP PARTITION ignoredIdentifiers_
| DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| TRUNCATE PARTITION (ignoredIdentifiers_ | ALL)
| COALESCE PARTITION NUMBER_
| REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_
| EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)?
| ANALYZE PARTITION (ignoredIdentifiers_ | ALL)
| CHECK PARTITION (ignoredIdentifiers_ | ALL)
| OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL)
| REBUILD PARTITION (ignoredIdentifiers_ | ALL)
| REPAIR PARTITION (ignoredIdentifiers_ | ALL)
| REMOVE PARTITIONING
| UPGRADE PARTITIONING
;
tableOptions_
: tableOption_ (COMMA_? tableOption_)*
;
tableOption_
: AUTO_INCREMENT EQ_? NUMBER_
| AVG_ROW_LENGTH EQ_? NUMBER_
| DEFAULT? (characterSet_ | collateClause_)
| CHECKSUM EQ_? NUMBER_
| COMMENT EQ_? STRING_
| COMPRESSION EQ_? STRING_
| CONNECTION EQ_? STRING_
| (DATA | INDEX) DIRECTORY EQ_? STRING_
| DELAY_KEY_WRITE EQ_? NUMBER_
| ENCRYPTION EQ_? STRING_
| ENGINE EQ_? ignoredIdentifier_
| INSERT_METHOD EQ_? (NO | FIRST | LAST)
| KEY_BLOCK_SIZE EQ_? NUMBER_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| PACK_KEYS EQ_? (NUMBER_ | DEFAULT)
| PASSWORD EQ_? STRING_
| ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT)
| STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_)
| STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_)
| STATS_SAMPLE_PAGES EQ_? NUMBER_
| TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))?
| UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_
;
addColumnSpecification
: ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_)
;
firstOrAfterColumn
: FIRST | AFTER columnName
;
addIndexSpecification
: ADD indexDefinition_
;
addConstraintSpecification
: ADD constraintDefinition_
;
changeColumnSpecification
: CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn?
;
dropColumnSpecification
: DROP COLUMN? columnName
;
dropIndexSpecification
: DROP (INDEX | KEY) indexName
;
dropPrimaryKeySpecification
: DROP primaryKey
;
modifyColumnSpecification
: MODIFY COLUMN? columnDefinition firstOrAfterColumn?
;
// TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
// TODO hongjun: should support renameIndexSpecification on mysql
renameIndexSpecification
: RENAME (INDEX | KEY) indexName TO indexName
;
// TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table
renameTableSpecification_
: RENAME (TO | AS)? newTableName
;
newTableName
: identifier_
;
partitionDefinitions_
: LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_
;
partitionDefinition_
: PARTITION identifier_
(VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))?
partitionDefinitionOption_*
(LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)?
;
partitionLessThanValue_
: LP_ (expr | partitionValueList_) RP_ | MAXVALUE
;
partitionValueList_
: literals (COMMA_ literals)*
;
partitionDefinitionOption_
: STORAGE? ENGINE EQ_? identifier_
| COMMENT EQ_? STRING_
| DATA DIRECTORY EQ_? STRING_
| INDEX DIRECTORY EQ_? STRING_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| TABLESPACE EQ_? identifier_
;
subpartitionDefinition_
: SUBPARTITION identifier_ partitionDefinitionOption_*
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE temporaryClause_ TABLE existClause_ tableName (createDefinitionClause_ | createLikeClause_)
;
createIndex
: CREATE (UNIQUE | FULLTEXT | SPATIAL)? INDEX indexName indexType_? ON tableName
;
alterTable
: ALTER TABLE tableName alterSpecifications_?
;
dropTable
: DROP TEMPORARY? TABLE (IF EXISTS)? tableName (COMMA_ tableName)*
;
dropIndex
: DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName
;
truncateTable
: TRUNCATE TABLE? tableName
;
temporaryClause_
: TEMPORARY?
;
existClause_
: (IF NOT EXISTS)?
;
createDefinitionClause_
: LP_ createDefinitions_ RP_
;
createLikeClause_
: LP_? LIKE tableName RP_?
;
createDefinitions_
: createDefinition_ (COMMA_ createDefinition_)*
;
createDefinition_
: columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_
;
columnDefinition
: columnName dataType (inlineDataType_* | generatedDataType_*)
;
indexDefinition_
: (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
constraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_)
;
checkConstraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)?
;
inlineDataType_
: commonDataTypeOption_
| AUTO_INCREMENT
| DEFAULT (literals | expr)
| COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT)
| STORAGE (DISK | MEMORY | DEFAULT)
;
generatedDataType_
: commonDataTypeOption_
| (GENERATED ALWAYS)? AS expr
| (VIRTUAL | STORED)
;
commonDataTypeOption_
: primaryKey | UNIQUE KEY? | NOT? NULL | collateName_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_
;
referenceDefinition_
: REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)*
;
referenceOption_
: RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT
;
indexType_
: USING (BTREE | HASH)
;
keyParts_
: LP_ keyPart_ (COMMA_ keyPart_)* RP_
;
keyPart_
: (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)?
;
indexOption_
: KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE
;
primaryKeyOption_
: primaryKey indexType_? columnNames indexOption_*
;
primaryKey
: PRIMARY? KEY
;
uniqueOption_
: UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
foreignKeyOption_
: FOREIGN KEY indexName? columnNames referenceDefinition_
;
alterSpecifications_
: alterSpecification_ (COMMA_ alterSpecification_)*
;
alterSpecification_
: tableOptions_
| addColumnSpecification
| addIndexSpecification
| addConstraintSpecification
| ADD checkConstraintDefinition_
| DROP CHECK ignoredIdentifier_
| ALTER CHECK ignoredIdentifier_ NOT? ENFORCED
| ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY)
| ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT)
| ALTER INDEX indexName (VISIBLE | INVISIBLE)
| changeColumnSpecification
| DEFAULT? characterSet_ collateClause_?
| CONVERT TO characterSet_ collateClause_?
| (DISABLE | ENABLE) KEYS
| (DISCARD | IMPORT_) TABLESPACE
| dropColumnSpecification
| dropIndexSpecification
| dropPrimaryKeySpecification
| DROP FOREIGN KEY ignoredIdentifier_
| FORCE
| LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE)
| modifyColumnSpecification
// TODO hongjun investigate ORDER BY col_name [, col_name] ...
| ORDER BY columnName (COMMA_ columnName)*
| renameColumnSpecification
| renameIndexSpecification
| renameTableSpecification_
| (WITHOUT | WITH) VALIDATION
| ADD PARTITION LP_ partitionDefinition_ RP_
| DROP PARTITION ignoredIdentifiers_
| DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| TRUNCATE PARTITION (ignoredIdentifiers_ | ALL)
| COALESCE PARTITION NUMBER_
| REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_
| EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)?
| ANALYZE PARTITION (ignoredIdentifiers_ | ALL)
| CHECK PARTITION (ignoredIdentifiers_ | ALL)
| OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL)
| REBUILD PARTITION (ignoredIdentifiers_ | ALL)
| REPAIR PARTITION (ignoredIdentifiers_ | ALL)
| REMOVE PARTITIONING
| UPGRADE PARTITIONING
;
tableOptions_
: tableOption_ (COMMA_? tableOption_)*
;
tableOption_
: AUTO_INCREMENT EQ_? NUMBER_
| AVG_ROW_LENGTH EQ_? NUMBER_
| DEFAULT? (characterSet_ | collateClause_)
| CHECKSUM EQ_? NUMBER_
| COMMENT EQ_? STRING_
| COMPRESSION EQ_? STRING_
| CONNECTION EQ_? STRING_
| (DATA | INDEX) DIRECTORY EQ_? STRING_
| DELAY_KEY_WRITE EQ_? NUMBER_
| ENCRYPTION EQ_? STRING_
| ENGINE EQ_? ignoredIdentifier_
| INSERT_METHOD EQ_? (NO | FIRST | LAST)
| KEY_BLOCK_SIZE EQ_? NUMBER_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| PACK_KEYS EQ_? (NUMBER_ | DEFAULT)
| PASSWORD EQ_? STRING_
| ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT)
| STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_)
| STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_)
| STATS_SAMPLE_PAGES EQ_? NUMBER_
| TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))?
| UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_
;
addColumnSpecification
: ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_)
;
firstOrAfterColumn
: FIRST | AFTER columnName
;
addIndexSpecification
: ADD indexDefinition_
;
addConstraintSpecification
: ADD constraintDefinition_
;
changeColumnSpecification
: CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn?
;
dropColumnSpecification
: DROP COLUMN? columnName
;
dropIndexSpecification
: DROP (INDEX | KEY) indexName
;
dropPrimaryKeySpecification
: DROP primaryKey
;
modifyColumnSpecification
: MODIFY COLUMN? columnDefinition firstOrAfterColumn?
;
// TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
// TODO hongjun: should support renameIndexSpecification on mysql
renameIndexSpecification
: RENAME (INDEX | KEY) indexName TO indexName
;
// TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table
renameTableSpecification_
: RENAME (TO | AS)? newTableName
;
newTableName
: identifier_
;
partitionDefinitions_
: LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_
;
partitionDefinition_
: PARTITION identifier_
(VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))?
partitionDefinitionOption_*
(LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)?
;
partitionLessThanValue_
: LP_ (expr | partitionValueList_) RP_ | MAXVALUE
;
partitionValueList_
: literals (COMMA_ literals)*
;
partitionDefinitionOption_
: STORAGE? ENGINE EQ_? identifier_
| COMMENT EQ_? STRING_
| DATA DIRECTORY EQ_? STRING_
| INDEX DIRECTORY EQ_? STRING_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| TABLESPACE EQ_? identifier_
;
subpartitionDefinition_
: SUBPARTITION identifier_ partitionDefinitionOption_*
;
|
use collateName_
|
use collateName_
|
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
|
d6523ef6c2ed9d0c47a11437f2498b3774e283eb
|
projects/batfish/src/main/antlr4/org/batfish/grammar/juniper/JuniperLexer.g4
|
projects/batfish/src/main/antlr4/org/batfish/grammar/juniper/JuniperLexer.g4
|
lexer grammar JuniperLexer;
options {
superClass = 'org.batfish.grammar.juniper.parsing.JuniperBaseLexer';
}
@members {
boolean enableIPV6_ADDRESS = true;
boolean enableIP_ADDRESS = true;
boolean enableDEC = true;
@Override
public String printStateVariables() {
StringBuilder sb = new StringBuilder();
sb.append("enableIPV6_ADDRESS: " + enableIPV6_ADDRESS + "\n");
sb.append("enableIP_ADDRESS: " + enableIP_ADDRESS + "\n");
sb.append("enableDEC: " + enableDEC + "\n");
return sb.toString();
}
}
REPLACE
:
'replace:'
;
CLOSE_BRACE
:
'}'
;
CLOSE_BRACKET
:
']'
;
CLOSE_PAREN
:
')'
;
// The start of a flat line
START_FLAT_LINE
:
F_WhitespaceChar* ('activate'|'deactivate'|'delete'|'insert'|'set')
{lastTokenType() == -1 || lastTokenType() == NEWLINE}? -> pushMode(M_FLAT_LINE)
;
INACTIVE
:
'inactive:'
;
// Handle Juniper-style and RANCID-header-style line comments
COMMENT_LINE
:
F_WhitespaceChar* [!#]
{lastTokenType() == -1 || lastTokenType() == NEWLINE}?
F_NonNewlineChar* (F_NewlineChar+ | EOF)
-> skip // so not counted as last token
;
MULTILINE_COMMENT
:
'/*' .*? '*/' -> skip // so not counted as last token
;
OPEN_BRACE
:
'{'
;
OPEN_BRACKET
:
'['
;
OPEN_PAREN
:
'('
;
SEMICOLON
:
';' F_SECRET_DATA?
;
WORD
:
F_QuotedString
| F_ParenString
| F_WordChar+
;
NEWLINE: F_NewlineChar+ -> channel(HIDDEN);
WS
:
F_WhitespaceChar+ -> skip // so not counted as last token
;
mode M_FLAT_LINE;
M_FLAT_LINE_WORD
:
(
F_QuotedString
| F_ParenString
| F_WordChar+
) -> type(WORD)
;
M_FLAT_LINE_NEWLINE
:
F_NewlineChar -> type(NEWLINE), popMode
;
M_FLAT_LINE_WS
:
F_WhitespaceChar+ -> skip
;
fragment
F_NewlineChar
:
[\r\n]
;
fragment
F_NonNewlineChar
:
~[\r\n]
;
fragment
F_ParenString
:
'(' ~')'* ')'
;
fragment
F_QuotedString
:
'"' ~'"'* '"'
;
// This may appear after a semicolon when there is a secret key in the file
// Search for examples online.
fragment
F_SECRET_DATA
:
' '* '## SECRET-DATA'
;
fragment
F_WhitespaceChar
:
[ \t\u000C]
;
fragment
F_WordChar
:
~[ \t\u000C\r\n;{}[\]"#()]
;
|
lexer grammar JuniperLexer;
options {
superClass = 'org.batfish.grammar.juniper.parsing.JuniperBaseLexer';
}
REPLACE
:
'replace:'
;
CLOSE_BRACE
:
'}'
;
CLOSE_BRACKET
:
']'
;
CLOSE_PAREN
:
')'
;
// The start of a flat line
START_FLAT_LINE
:
F_WhitespaceChar* ('activate'|'deactivate'|'delete'|'insert'|'set')
{lastTokenType() == -1 || lastTokenType() == NEWLINE}? -> pushMode(M_FLAT_LINE)
;
INACTIVE
:
'inactive:'
;
// Handle Juniper-style and RANCID-header-style line comments
COMMENT_LINE
:
F_WhitespaceChar* [!#]
{lastTokenType() == -1 || lastTokenType() == NEWLINE}?
F_NonNewlineChar* (F_NewlineChar+ | EOF)
-> skip // so not counted as last token
;
MULTILINE_COMMENT
:
'/*' .*? '*/' -> skip // so not counted as last token
;
OPEN_BRACE
:
'{'
;
OPEN_BRACKET
:
'['
;
OPEN_PAREN
:
'('
;
SEMICOLON
:
';' F_SECRET_DATA?
;
WORD
:
F_QuotedString
| F_ParenString
| F_WordChar+
;
NEWLINE: F_NewlineChar+ -> channel(HIDDEN);
WS
:
F_WhitespaceChar+ -> skip // so not counted as last token
;
mode M_FLAT_LINE;
M_FLAT_LINE_WORD
:
(
F_QuotedString
| F_ParenString
| F_WordChar+
) -> type(WORD)
;
M_FLAT_LINE_NEWLINE
:
F_NewlineChar -> type(NEWLINE), popMode
;
M_FLAT_LINE_WS
:
F_WhitespaceChar+ -> skip
;
fragment
F_NewlineChar
:
[\r\n]
;
fragment
F_NonNewlineChar
:
~[\r\n]
;
fragment
F_ParenString
:
'(' ~')'* ')'
;
fragment
F_QuotedString
:
'"' ~'"'* '"'
;
// This may appear after a semicolon when there is a secret key in the file
// Search for examples online.
fragment
F_SECRET_DATA
:
' '* '## SECRET-DATA'
;
fragment
F_WhitespaceChar
:
[ \t\u000C]
;
fragment
F_WordChar
:
~[ \t\u000C\r\n;{}[\]"#()]
;
|
remove unused state from flattening lexer (#7954)
|
JuniperLexer: remove unused state from flattening lexer (#7954)
|
ANTLR
|
apache-2.0
|
arifogel/batfish,dhalperi/batfish,dhalperi/batfish,intentionet/batfish,intentionet/batfish,intentionet/batfish,batfish/batfish,intentionet/batfish,batfish/batfish,arifogel/batfish,batfish/batfish,arifogel/batfish,dhalperi/batfish,intentionet/batfish
|
98328881af6f5b800bd26da0b1c81b736f0d6044
|
shardingsphere-sql-parser/shardingsphere-sql-parser-mysql/src/main/antlr4/imports/mysql/BaseRule.g4
|
shardingsphere-sql-parser/shardingsphere-sql-parser-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
;
characterSetName_
: IDENTIFIER_
;
collationName_
: IDENTIFIER_
;
identifier
: IDENTIFIER_ | unreservedWord
;
unreservedWord
: ACCOUNT | ACTION | AFTER | ALGORITHM | ALWAYS | ANY | AUTO_INCREMENT
| AVG_ROW_LENGTH | BEGIN | BTREE | CHAIN | CHARSET | CHECKSUM | CIPHER
| CLIENT | COALESCE | COLUMNS | COLUMN_FORMAT | COMMENT | COMMIT | COMMITTED
| COMPACT | COMPRESSED | COMPRESSION | CONNECTION | CONSISTENT | CURRENT | DATA
| DATE | DELAY_KEY_WRITE | DISABLE | DISCARD | DISK | DUPLICATE | ENABLE
| ENCRYPTION | ENFORCED | END | ENGINE | ESCAPE | EVENT | EXCHANGE
| EXECUTE | FILE | FIRST | FIXED | FOLLOWING | GLOBAL | HASH
| IMPORT_ | INSERT_METHOD | INVISIBLE | KEY_BLOCK_SIZE | LAST | LESS
| LEVEL | MAX_ROWS | MEMORY | MIN_ROWS | MODIFY | NO | NONE | OFFSET
| PACK_KEYS | PARSER | PARTIAL | PARTITIONING | PASSWORD | PERSIST | PERSIST_ONLY
| PRECEDING | PRIVILEGES | PROCESS | PROXY | QUICK | REBUILD | REDUNDANT
| RELOAD | REMOVE | REORGANIZE | REPAIR | REVERSE | ROLLBACK | ROLLUP
| ROW_FORMAT | SAVEPOINT | SESSION | SHUTDOWN | SIMPLE | SLAVE | SOUNDS
| SQL_BIG_RESULT | SQL_BUFFER_RESULT | SQL_CACHE | SQL_NO_CACHE | START | STATS_AUTO_RECALC | STATS_PERSISTENT
| STATS_SAMPLE_PAGES | STORAGE | SUBPARTITION | SUPER | TABLES | TABLESPACE | TEMPORARY
| THAN | TIME | TIMESTAMP | TRANSACTION | TRUNCATE | UNBOUNDED | UNKNOWN
| UPGRADE | VALIDATION | VALUE | VIEW | VISIBLE | WEIGHT_STRING | WITHOUT
| MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH
| QUARTER | YEAR | AGAINST | LANGUAGE | MODE | QUERY | EXPANSION
| BOOLEAN | MAX | MIN | SUM | COUNT | AVG | BIT_AND
| BIT_OR | BIT_XOR | GROUP_CONCAT | JSON_ARRAYAGG | JSON_OBJECTAGG | STD | STDDEV
| STDDEV_POP | STDDEV_SAMP | VAR_POP | VAR_SAMP | VARIANCE | EXTENDED | STATUS
| FIELDS | INDEXES | USER | ROLE | OJ | AUTOCOMMIT | OFF | ROTATE | INSTANCE | MASTER | BINLOG |ERROR
| SCHEDULE | COMPLETION | DO | DEFINER | START | EVERY | HOST | SOCKET | OWNER | PORT | RETURNS | CONTAINS
| SECURITY | INVOKER | UNDEFINED | MERGE | TEMPTABLE | CASCADED | LOCAL | SERVER | WRAPPER | OPTIONS | DATAFILE
| FILE_BLOCK_SIZE | EXTENT_SIZE | INITIAL_SIZE | AUTOEXTEND_SIZE | MAX_SIZE | NODEGROUP
| WAIT | LOGFILE | UNDOFILE | UNDO_BUFFER_SIZE | REDO_BUFFER_SIZE | DEFINITION | ORGANIZATION
| DESCRIPTION | REFERENCE | FOLLOWS | PRECEDES | NAME |CLOSE | OPEN | NEXT | HANDLER | PREV
| IMPORT | CONCURRENT | XML | POSITION | SHARE | DUMPFILE | CLONE | AGGREGATE | INSTALL | UNINSTALL
| RESOURCE | FLUSH | RESET | RESTART | HOSTS | RELAY | EXPORT | USER_RESOURCES | SLOW | GENERAL | CACHE
| SUBJECT | ISSUER | OLD | RANDOM | RETAIN | MAX_USER_CONNECTIONS | MAX_CONNECTIONS_PER_HOUR | MAX_UPDATES_PER_HOUR
| MAX_QUERIES_PER_HOUR | REUSE | OPTIONAL | HISTORY | NEVER | EXPIRE | TYPE | CONTEXT | CODE | CHANNEL | SOURCE
;
variable
: (AT_? AT_)? (GLOBAL | PERSIST | PERSIST_ONLY | SESSION)? DOT_? identifier
;
schemaName
: identifier
;
tableName
: (owner DOT_)? name
;
columnName
: (owner DOT_)? name
;
indexName
: identifier
;
userName
: STRING_ AT_ STRING_
| 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
;
tableNames
: LP_? tableName (COMMA_ tableName)* RP_?
;
columnNames
: LP_? columnName (COMMA_ columnName)* RP_?
;
groupName
: IDENTIFIER_
;
shardLibraryName
: STRING_
;
componentName
: STRING_
;
pluginName
: IDENTIFIER_
;
hostName
: STRING_
;
port
: NUMBER_
;
cloneInstance
: userName AT_ hostName COLON_ port
;
cloneDir
: IDENTIFIER_
;
channelName
: IDENTIFIER_
;
logName
: identifier
;
roleName
: (STRING_ | IDENTIFIER_) AT_ (STRING_ IDENTIFIER_) | IDENTIFIER_
;
engineName
: IDENTIFIER_
;
triggerName
: IDENTIFIER_
;
triggerTime
: BEFORE | AFTER
;
userOrRole
: userName | roleName
;
partitionName
: IDENTIFIER_
;
triggerEvent
: INSERT | UPDATE | DELETE
;
triggerOrder
: (FOLLOWS | PRECEDES) triggerName
;
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 | valuesFunction_
;
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_
;
valuesFunction_
: VALUES LP_ columnName 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 | UNIX_TIMESTAMP | LOCALTIME | LOCALTIMESTAMP | NOW | REPLACE | INTERVAL | SUBSTRING | MOD
| DATABASE | LEFT | RIGHT | LOWER | UPPER | DATE | DATEDIFF | DATE_FORMAT | DAY | DAYNAME | DAYOFMONTH | DAYOFWEEK | DAYOFYEAR
| GEOMCOLLECTION | GEOMETRYCOLLECTION | LINESTRING | MULTILINESTRING | MULTIPOINT | MULTIPOLYGON | POINT | POLYGON | STR_TO_DATE
| ST_AREA | ST_ASBINARY | ST_ASGEOJSON | ST_ASTEXT | ST_ASWKB | ST_ASWKT | ST_BUFFER | ST_BUFFER_STRATEGY | ST_CENTROID | ST_CONTAINS
| ST_CONVEXHULL | ST_CROSSES | ST_DIFFERENCE | ST_DIMENSION | ST_DISJOINT | ST_DISTANCE | ST_DISTANCE_SPHERE | ST_ENDPOINT | ST_ENVELOPE
| ST_EQUALS | ST_EXTERIORRING | ST_GEOHASH | ST_GEOMCOLLFROMTEXT | ST_GEOMCOLLFROMTXT | ST_GEOMCOLLFROMWKB | ST_GEOMETRYCOLLECTIONFROMTEXT
| ST_GEOMETRYCOLLECTIONFROMWKB | ST_GEOMETRYFROMTEXT | ST_GEOMETRYFROMWKB | ST_GEOMETRYN | ST_GEOMETRYTYPE | ST_GEOMFROMGEOJSON
| ST_GEOMFROMTEXT | ST_GEOMFROMWKB | ST_INTERIORRINGN | ST_INTERSECTION | ST_INTERSECTS | ST_ISCLOSED | ST_ISEMPTY | ST_ISSIMPLE
| ST_ISVALID | ST_LATFROMGEOHASH | ST_LATITUDE | ST_LENGTH | ST_LINEFROMTEXT | ST_LINEFROMWKB | ST_LINESTRINGFROMTEXT | ST_LINESTRINGFROMWKB
| ST_LONGFROMGEOHASH | ST_LONGITUDE | ST_MAKEENVELOPE | ST_MLINEFROMTEXT | ST_MLINEFROMWKB | ST_MULTILINESTRINGFROMTEXT | ST_MULTILINESTRINGFROMWKB
| ST_MPOINTFROMTEXT | ST_MPOINTFROMWKB | ST_MULTIPOINTFROMTEXT | ST_MULTIPOINTFROMWKB | ST_MPOLYFROMTEXT | ST_MPOLYFROMWKB | ST_MULTIPOLYGONFROMTEXT
| ST_MULTIPOLYGONFROMWKB | ST_NUMGEOMETRIES | ST_NUMINTERIORRING | ST_NUMINTERIORRINGS | ST_NUMPOINTS | ST_OVERLAPS | ST_POINTFROMGEOHASH
| ST_POINTFROMTEXT | ST_POINTFROMWKB | ST_POINTN | ST_POLYFROMTEXT | ST_POLYFROMWKB | ST_POLYGONFROMTEXT | ST_POLYGONFROMWKB | ST_SIMPLIFY
| ST_SRID | ST_STARTPOINT | ST_SWAPXY | ST_SYMDIFFERENCE | ST_TOUCHES | ST_TRANSFORM | ST_UNION | ST_VALIDATE | ST_WITHIN | ST_X | ST_Y
| TIME | TIMEDIFF | TIMESTAMP | TIMESTAMPADD | TIMESTAMPDIFF | TIME_FORMAT | TIME_TO_SEC | AES_DECRYPT | AES_ENCRYPT | FROM_BASE64 | TO_BASE64
| ADDDATE | ADDTIME | DATE | DATE_ADD | DATE_SUB |
;
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
;
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
;
characterSetName_
: IDENTIFIER_
;
collationName_
: IDENTIFIER_
;
identifier
: IDENTIFIER_ | unreservedWord
;
unreservedWord
: ACCOUNT | ACTION | AFTER | ALGORITHM | ALWAYS | ANY | AUTO_INCREMENT
| AVG_ROW_LENGTH | BEGIN | BTREE | CHAIN | CHARSET | CHECKSUM | CIPHER
| CLIENT | COALESCE | COLUMNS | COLUMN_FORMAT | COMMENT | COMMIT | COMMITTED
| COMPACT | COMPRESSED | COMPRESSION | CONNECTION | CONSISTENT | CURRENT | DATA
| DATE | DELAY_KEY_WRITE | DISABLE | DISCARD | DISK | DUPLICATE | ENABLE
| ENCRYPTION | ENFORCED | END | ENGINE | ESCAPE | EVENT | EXCHANGE
| EXECUTE | FILE | FIRST | FIXED | FOLLOWING | GLOBAL | HASH
| IMPORT_ | INSERT_METHOD | INVISIBLE | KEY_BLOCK_SIZE | LAST | LESS
| LEVEL | MAX_ROWS | MEMORY | MIN_ROWS | MODIFY | NO | NONE | OFFSET
| PACK_KEYS | PARSER | PARTIAL | PARTITIONING | PASSWORD | PERSIST | PERSIST_ONLY
| PRECEDING | PRIVILEGES | PROCESS | PROXY | QUICK | REBUILD | REDUNDANT
| RELOAD | REMOVE | REORGANIZE | REPAIR | REVERSE | ROLLBACK | ROLLUP
| ROW_FORMAT | SAVEPOINT | SESSION | SHUTDOWN | SIMPLE | SLAVE | SOUNDS
| SQL_BIG_RESULT | SQL_BUFFER_RESULT | SQL_CACHE | SQL_NO_CACHE | START | STATS_AUTO_RECALC | STATS_PERSISTENT
| STATS_SAMPLE_PAGES | STORAGE | SUBPARTITION | SUPER | TABLES | TABLESPACE | TEMPORARY
| THAN | TIME | TIMESTAMP | TRANSACTION | TRUNCATE | UNBOUNDED | UNKNOWN
| UPGRADE | VALIDATION | VALUE | VIEW | VISIBLE | WEIGHT_STRING | WITHOUT
| MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH
| QUARTER | YEAR | AGAINST | LANGUAGE | MODE | QUERY | EXPANSION
| BOOLEAN | MAX | MIN | SUM | COUNT | AVG | BIT_AND
| BIT_OR | BIT_XOR | GROUP_CONCAT | JSON_ARRAYAGG | JSON_OBJECTAGG | STD | STDDEV
| STDDEV_POP | STDDEV_SAMP | VAR_POP | VAR_SAMP | VARIANCE | EXTENDED | STATUS
| FIELDS | INDEXES | USER | ROLE | OJ | AUTOCOMMIT | OFF | ROTATE | INSTANCE | MASTER | BINLOG |ERROR
| SCHEDULE | COMPLETION | DO | DEFINER | START | EVERY | HOST | SOCKET | OWNER | PORT | RETURNS | CONTAINS
| SECURITY | INVOKER | UNDEFINED | MERGE | TEMPTABLE | CASCADED | LOCAL | SERVER | WRAPPER | OPTIONS | DATAFILE
| FILE_BLOCK_SIZE | EXTENT_SIZE | INITIAL_SIZE | AUTOEXTEND_SIZE | MAX_SIZE | NODEGROUP
| WAIT | LOGFILE | UNDOFILE | UNDO_BUFFER_SIZE | REDO_BUFFER_SIZE | DEFINITION | ORGANIZATION
| DESCRIPTION | REFERENCE | FOLLOWS | PRECEDES | NAME |CLOSE | OPEN | NEXT | HANDLER | PREV
| IMPORT | CONCURRENT | XML | POSITION | SHARE | DUMPFILE | CLONE | AGGREGATE | INSTALL | UNINSTALL | COMPONENT
| RESOURCE | FLUSH | RESET | RESTART | HOSTS | RELAY | EXPORT | USER_RESOURCES | SLOW | GENERAL | CACHE
| SUBJECT | ISSUER | OLD | RANDOM | RETAIN | MAX_USER_CONNECTIONS | MAX_CONNECTIONS_PER_HOUR | MAX_UPDATES_PER_HOUR
| MAX_QUERIES_PER_HOUR | REUSE | OPTIONAL | HISTORY | NEVER | EXPIRE | TYPE | CONTEXT | CODE | CHANNEL | SOURCE
;
variable
: (AT_? AT_)? (GLOBAL | PERSIST | PERSIST_ONLY | SESSION)? DOT_? identifier
;
schemaName
: identifier
;
tableName
: (owner DOT_)? name
;
columnName
: (owner DOT_)? name
;
indexName
: identifier
;
userName
: STRING_ AT_ STRING_
| 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
;
tableNames
: LP_? tableName (COMMA_ tableName)* RP_?
;
columnNames
: LP_? columnName (COMMA_ columnName)* RP_?
;
groupName
: IDENTIFIER_
;
shardLibraryName
: STRING_
;
componentName
: STRING_
;
pluginName
: IDENTIFIER_
;
hostName
: STRING_
;
port
: NUMBER_
;
cloneInstance
: userName AT_ hostName COLON_ port
;
cloneDir
: IDENTIFIER_
;
channelName
: IDENTIFIER_
;
logName
: identifier
;
roleName
: (STRING_ | IDENTIFIER_) AT_ (STRING_ IDENTIFIER_) | IDENTIFIER_
;
engineName
: IDENTIFIER_
;
triggerName
: IDENTIFIER_
;
triggerTime
: BEFORE | AFTER
;
userOrRole
: userName | roleName
;
partitionName
: IDENTIFIER_
;
triggerEvent
: INSERT | UPDATE | DELETE
;
triggerOrder
: (FOLLOWS | PRECEDES) triggerName
;
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 | valuesFunction_
;
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_
;
valuesFunction_
: VALUES LP_ columnName 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 | UNIX_TIMESTAMP | LOCALTIME | LOCALTIMESTAMP | NOW | REPLACE | INTERVAL | SUBSTRING | MOD
| DATABASE | LEFT | RIGHT | LOWER | UPPER | DATE | DATEDIFF | DATE_FORMAT | DAY | DAYNAME | DAYOFMONTH | DAYOFWEEK | DAYOFYEAR
| GEOMCOLLECTION | GEOMETRYCOLLECTION | LINESTRING | MULTILINESTRING | MULTIPOINT | MULTIPOLYGON | POINT | POLYGON | STR_TO_DATE
| ST_AREA | ST_ASBINARY | ST_ASGEOJSON | ST_ASTEXT | ST_ASWKB | ST_ASWKT | ST_BUFFER | ST_BUFFER_STRATEGY | ST_CENTROID | ST_CONTAINS
| ST_CONVEXHULL | ST_CROSSES | ST_DIFFERENCE | ST_DIMENSION | ST_DISJOINT | ST_DISTANCE | ST_DISTANCE_SPHERE | ST_ENDPOINT | ST_ENVELOPE
| ST_EQUALS | ST_EXTERIORRING | ST_GEOHASH | ST_GEOMCOLLFROMTEXT | ST_GEOMCOLLFROMTXT | ST_GEOMCOLLFROMWKB | ST_GEOMETRYCOLLECTIONFROMTEXT
| ST_GEOMETRYCOLLECTIONFROMWKB | ST_GEOMETRYFROMTEXT | ST_GEOMETRYFROMWKB | ST_GEOMETRYN | ST_GEOMETRYTYPE | ST_GEOMFROMGEOJSON
| ST_GEOMFROMTEXT | ST_GEOMFROMWKB | ST_INTERIORRINGN | ST_INTERSECTION | ST_INTERSECTS | ST_ISCLOSED | ST_ISEMPTY | ST_ISSIMPLE
| ST_ISVALID | ST_LATFROMGEOHASH | ST_LATITUDE | ST_LENGTH | ST_LINEFROMTEXT | ST_LINEFROMWKB | ST_LINESTRINGFROMTEXT | ST_LINESTRINGFROMWKB
| ST_LONGFROMGEOHASH | ST_LONGITUDE | ST_MAKEENVELOPE | ST_MLINEFROMTEXT | ST_MLINEFROMWKB | ST_MULTILINESTRINGFROMTEXT | ST_MULTILINESTRINGFROMWKB
| ST_MPOINTFROMTEXT | ST_MPOINTFROMWKB | ST_MULTIPOINTFROMTEXT | ST_MULTIPOINTFROMWKB | ST_MPOLYFROMTEXT | ST_MPOLYFROMWKB | ST_MULTIPOLYGONFROMTEXT
| ST_MULTIPOLYGONFROMWKB | ST_NUMGEOMETRIES | ST_NUMINTERIORRING | ST_NUMINTERIORRINGS | ST_NUMPOINTS | ST_OVERLAPS | ST_POINTFROMGEOHASH
| ST_POINTFROMTEXT | ST_POINTFROMWKB | ST_POINTN | ST_POLYFROMTEXT | ST_POLYFROMWKB | ST_POLYGONFROMTEXT | ST_POLYGONFROMWKB | ST_SIMPLIFY
| ST_SRID | ST_STARTPOINT | ST_SWAPXY | ST_SYMDIFFERENCE | ST_TOUCHES | ST_TRANSFORM | ST_UNION | ST_VALIDATE | ST_WITHIN | ST_X | ST_Y
| TIME | TIMEDIFF | TIMESTAMP | TIMESTAMPADD | TIMESTAMPDIFF | TIME_FORMAT | TIME_TO_SEC | AES_DECRYPT | AES_ENCRYPT | FROM_BASE64 | TO_BASE64
| ADDDATE | ADDTIME | DATE | DATE_ADD | DATE_SUB |
;
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
;
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 'component' to unreservedWord for #4371 (#4490)
|
add 'component' to unreservedWord for #4371 (#4490)
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
b2285149bf0c739cd80f3b31d0398b9f701cb05f
|
tinymud/tinymud.g4
|
tinymud/tinymud.g4
|
/*
BSD License
Copyright (c) 2018, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar tinymud;
prog
: line + EOL*
;
line
: (command | action) EOL
;
command
: bootcommand
| chowncommand
| createcommand
| describecommand
| digcommand
| dumpcommand
| failcommand
| findcommand
| forcecommand
| linkcommand
| lockcommand
| namecommand
| newpassswordcommand
| ofailcommand
| opencommand
| osuccesscommand
| passwordcommand
| pcreatecommand
| setcommand
| shutdowncommand
| statscommand
| successcommand
| teleportcommand
| toadcommand
| unlinkcommand
| unlockcommand
| wallcommand
;
bootcommand
: '@boot' player
;
chowncommand
: '@chown' object '=' player
;
createcommand
: '@create' name ('=' cost)?
;
describecommand
: ('@describe' | '@desc') object ('=' description)?
;
digcommand
: '@dig' name
;
dumpcommand
: '@dump'
;
failcommand
: '@fail' name ('=' description)?
;
findcommand
: '@find' name?
;
forcecommand
: '@force' player '=' command
;
linkcommand
: '@link' object '=' (number | dir | room)
;
lockcommand
: '@lock' object '=' key
;
namecommand
: '@name' object '=' name password?
;
newpassswordcommand
: '@newpassword' player ('=' password)?
;
ofailcommand
: '@ofail' object ('=' message)?
;
opencommand
: '@open' dir (';' dir)* ('=' number)?
;
osuccesscommand
: ('@osuccess' | '@osucc') object ('=' message)?
;
passwordcommand
: '@password' password '=' password
;
pcreatecommand
: '@pcreate' name
;
setcommand
: '@set' object '=' '!'? flag
;
shutdowncommand
: '@shutdown'
;
statscommand
: '@stats' player
;
successcommand
: ('@success' | '@succ') object ('=' message)?
;
teleportcommand
: '@teleport' (object '=')? room
;
toadcommand
: '@toad' player
;
unlinkcommand
: '@unlink' dir
;
unlockcommand
: '@unlock' object
;
wallcommand
: '@wall' message
;
action
: dropaction
| examineaction
| getaction
| giveaction
| gotoaction
| gripeaction
| helpaction
| inventoryaction
| killaction
| lookaction
| newsaction
| pageaction
| quitaction
| robaction
| sayaction
| scoreaction
| whisperaction
| whoaction
;
dropaction
: ('drop' | 'throw') object
;
examineaction
: 'examine' object
;
getaction
: ('get' | 'take') object
;
giveaction
: 'give' player '=' pennies
;
gotoaction
: ('go' | 'goto' | 'move') direction
;
gripeaction
: 'gripe' message
;
helpaction
: 'help'
;
inventoryaction
: 'inventory'
| 'inv'
;
killaction
: 'kill' player ('=' cost)
;
lookaction
: ('look' | 'read') object
;
newsaction
: 'news'
;
pageaction
: 'page' player ('=' message)
;
quitaction
: 'quit'
;
robaction
: 'rob' player
;
sayaction
: 'say' message
;
scoreaction
: 'score'
;
whisperaction
: 'whisper' player '=' message
;
whoaction
: 'who' player?
;
object
: STRING
;
player
: STRING
;
name
: STRING
;
description
: STRING
;
cost
: NUMBER
;
key
: STRING
;
password
: STRING
;
message
: STRING
;
dir
: STRING
;
number
: NUMBER
;
room
: STRING
;
flag
: NUMBER
;
pennies
: NUMBER
;
direction
: STRING
;
STRING
: [a-zA-Z] [a-zA-Z0-9_. %,']*
;
NUMBER
: [0-9] +
;
EOL
: [r\n]
;
WS
: [ \t] -> skip
;
|
/*
BSD License
Copyright (c) 2018, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar tinymud;
prog
: line + EOL*
;
line
: (command | action) EOL
;
command
: bootcommand
| chowncommand
| createcommand
| describecommand
| digcommand
| dumpcommand
| failcommand
| findcommand
| forcecommand
| linkcommand
| lockcommand
| namecommand
| newpassswordcommand
| ofailcommand
| opencommand
| osuccesscommand
| passwordcommand
| pcreatecommand
| setcommand
| shutdowncommand
| statscommand
| successcommand
| teleportcommand
| toadcommand
| unlinkcommand
| unlockcommand
| wallcommand
;
bootcommand
: '@boot' player
;
chowncommand
: '@chown' object '=' player
;
createcommand
: '@create' name ('=' cost)?
;
describecommand
: ('@describe' | '@desc') object ('=' description)?
;
digcommand
: '@dig' name
;
dumpcommand
: '@dump'
;
failcommand
: '@fail' name ('=' description)?
;
findcommand
: '@find' name?
;
forcecommand
: '@force' player '=' command
;
linkcommand
: '@link' object '=' (number | dir | room)
;
lockcommand
: '@lock' object '=' key
;
namecommand
: '@name' object '=' name password?
;
newpassswordcommand
: '@newpassword' player ('=' password)?
;
ofailcommand
: '@ofail' object ('=' message)?
;
opencommand
: '@open' dir (';' dir)* ('=' number)?
;
osuccesscommand
: ('@osuccess' | '@osucc') object ('=' message)?
;
passwordcommand
: '@password' password '=' password
;
pcreatecommand
: '@pcreate' name
;
setcommand
: '@set' object '=' '!'? flag
;
shutdowncommand
: '@shutdown'
;
statscommand
: '@stats' player
;
successcommand
: ('@success' | '@succ') object ('=' message)?
;
teleportcommand
: '@teleport' (object '=')? room
;
toadcommand
: '@toad' player
;
unlinkcommand
: '@unlink' dir
;
unlockcommand
: '@unlock' object
;
wallcommand
: '@wall' message
;
action
: dropaction
| examineaction
| getaction
| giveaction
| gotoaction
| gripeaction
| helpaction
| inventoryaction
| killaction
| lookaction
| newsaction
| pageaction
| quitaction
| robaction
| sayaction
| scoreaction
| whisperaction
| whoaction
;
dropaction
: ('drop' | 'throw') object
;
examineaction
: 'examine' object
;
getaction
: ('get' | 'take') object
;
giveaction
: 'give' player '=' pennies
;
gotoaction
: ('go' | 'goto' | 'move') direction
;
gripeaction
: 'gripe' message
;
helpaction
: 'help'
;
inventoryaction
: 'inventory'
| 'inv'
;
killaction
: 'kill' player ('=' cost)
;
lookaction
: ('look' | 'read') object
;
newsaction
: 'news'
;
pageaction
: 'page' player ('=' message)
;
quitaction
: 'quit'
;
robaction
: 'rob' player
;
sayaction
: 'say' message
;
scoreaction
: 'score'
;
whisperaction
: 'whisper' player '=' message
;
whoaction
: 'who' player?
;
object
: STRING
;
player
: STRING
;
name
: STRING
;
description
: STRING
;
cost
: NUMBER
;
key
: STRING
;
password
: STRING
;
message
: STRING
;
dir
: STRING
;
number
: NUMBER
;
room
: STRING
;
flag
: NUMBER
;
pennies
: NUMBER
;
direction
: STRING
;
STRING
: [a-zA-Z] [a-zA-Z0-9_. %,']*
;
NUMBER
: [0-9] +
;
EOL
: '\r'? '\n'
;
WS
: [ \t] -> skip
;
|
Change tinymud grammar: '\r' in EOL token optional
|
Change tinymud grammar: '\r' in EOL token optional
|
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
|
a759d45d8186336f52203159d08a4e2a40b5acd3
|
turin-parser/src/main/antlr4/me/tomassetti/parser/antlr/TurinLexer.g4
|
turin-parser/src/main/antlr4/me/tomassetti/parser/antlr/TurinLexer.g4
|
lexer grammar TurinLexer;
@header {
}
@lexer::members {
public static final int WHITESPACE = 1;
public static final int COMMENTS = 2;
private boolean useHiddenChannel = false;
public void setUseHiddenChannel(boolean value) {
this.useHiddenChannel = value;
}
public int whitespaceChannel() {
if (useHiddenChannel) {
return HIDDEN;
} else {
return WHITESPACE;
}
}
public int commentsChannel() {
if (useHiddenChannel) {
return HIDDEN;
} else {
return COMMENTS;
}
}
}
// It is suggested to define the token types reused in different mode.
// See mode in-interpolation below
tokens { NAME_PLACEHOLDER, PLACEHOLDER, VALUE_ID, TYPE_ID, INT, LPAREN, RPAREN, COMMA, RELOP, AND_KW, OR_KW, NOT_KW }
NAMESPACE_KW : 'namespace';
PROGRAM_KW : 'program';
PROPERTY_KW : 'property';
DEFAULT_KW : 'default';
TYPE_KW : 'type';
VAL_KW : 'val';
HAS_KW : 'has';
ABSTRACT_KW : 'abstract';
SHARED_KW : 'shared';
IMPORT_KW : 'import';
AS_KW : 'as';
VOID_KW : 'void';
RETURN_KW : 'return';
FALSE_KW : 'false';
TRUE_KW : 'true';
IF_KW : 'if';
ELIF_KW : 'elif';
ELSE_KW : 'else';
THROW_KW : 'throw';
TRY_KW : 'try';
CATCH_KW : 'catch';
// For definitions reused in mode in-interpolation we define and refer to fragments
AND_KW : F_AND;
OR_KW : F_OR;
NOT_KW : F_NOT;
LPAREN : '(';
RPAREN : ')';
LBRACKET : '{';
RBRACKET : '}';
LSQUARE : '[';
RSQUARE : ']';
COMMA : ',';
POINT : '.';
COLON : ':';
// We use just one token type to reduce the number of states (and not crash Antlr...)
// https://github.com/antlr/antlr4/issues/840
EQUAL : '==' -> type(RELOP);
DIFFERENT : '!=' -> type(RELOP);
LESSEQ : '<=' -> type(RELOP);
LESS : '<' -> type(RELOP);
MOREEQ : '>=' -> type(RELOP);
MORE : '>' -> type(RELOP);
// ASSIGNMENT has to comes after EQUAL
ASSIGNMENT : '=';
// Mathematical operators cannot be merged in one token type because
// they have different precedences
ASTERISK : '*';
SLASH : '/';
PLUS : '+';
MINUS : '-';
PIPE : '|';
NAME_PLACEHOLDER : F_NAME_PLACEHOLDER;
PLACEHOLDER : F_PLACEHOLDER;
PRIMITIVE_TYPE : F_PRIMITIVE_TYPE;
BASIC_TYPE : F_BASIC_TYPE;
VALUE_ID : F_VALUE_ID;
// Only for types
TYPE_ID : F_TYPE_ID;
INT : F_INT;
STRING_START : '"' -> pushMode(IN_STRING);
WS : (' ' | '\t')+ -> channel(WHITESPACE);
NL : '\r'? '\n';
COMMENT : '/*' .*? '*/' -> channel(COMMENTS);
LINE_COMMENT : '//' ~[\r\n]* -> channel(COMMENTS);
ANNOTATION_ID : F_ANNOTATION_ID;
UNEXPECTED_CHAR : . ;
mode IN_STRING;
STRING_STOP : '"' -> popMode;
STRING_CONTENT : (~["\\#]|ESCAPE_SEQUENCE|SHARP)+;
INTERPOLATION_START : '#{' -> pushMode(IN_INTERPOLATION);
mode IN_INTERPOLATION;
INTERPOLATION_END : '}' -> popMode;
I_PRIMITIVE_TYPE : F_PRIMITIVE_TYPE -> type(PRIMITIVE_TYPE);
I_BASIC_TYPE : F_BASIC_TYPE -> type(BASIC_TYPE);
I_FALSE_KW : 'false' -> type(FALSE_KW);
I_TRUE_KW : 'true' -> type(TRUE_KW);
I_AND_KW : F_AND -> type(AND_KW);
I_OR_KW : F_OR -> type(OR_KW);
I_NOT_KW : F_NOT -> type(NOT_KW);
I_IF_KW : 'if' -> type(IF_KW);
I_ELSE_KW : 'else' -> type(ELSE_KW);
I_NAME_PLACEHOLDER : F_NAME_PLACEHOLDER -> type(NAME_PLACEHOLDER);
I_PLACEHOLDER : F_PLACEHOLDER -> type(PLACEHOLDER);
I_VALUE_ID : F_VALUE_ID -> type(VALUE_ID);
I_TYPE_ID : F_TYPE_ID -> type(TYPE_ID);
I_INT : F_INT -> type(INT);
I_COMMA : ',' -> type(COMMA);
I_LPAREN : '(' -> type(LPAREN);
I_RPAREN : ')' -> type(RPAREN);
I_LSQUARE : '[' -> type(LSQUARE);
I_RSQUARE : ']' -> type(RSQUARE);
I_ASTERISK : '*' -> type(ASTERISK);
I_SLASH : '/' -> type(SLASH);
I_PLUS : '+' -> type(PLUS);
I_MINUS : '-' -> type(MINUS);
I_POINT : '.' -> type(POINT);
I_EQUAL : '==' -> type(RELOP);
I_DIFFERENT : '!=' -> type(RELOP);
I_LESSEQ : '<=' -> type(RELOP);
I_LESS : '<' -> type(RELOP);
I_MOREEQ : '>=' -> type(RELOP);
I_MORE : '>' -> type(RELOP);
I_STRING_START : '"' -> type(STRING_START), pushMode(IN_STRING);
I_WS : (' ' | '\t')+ -> type(WS), channel(WHITESPACE);
I_UNEXPECTED_CHAR : . -> type(UNEXPECTED_CHAR);
fragment F_NAME_PLACEHOLDER : '_name';
fragment F_PLACEHOLDER : '_';
fragment F_AND : 'and';
fragment F_OR : 'or';
fragment F_NOT : 'not';
fragment F_VALUE_ID : ('_')*'a'..'z' ('A'..'Z' | 'a'..'z' | '0'..'9' | '_')*;
// Only for types
fragment F_TYPE_ID : ('_')*'A'..'Z' ('A'..'Z' | 'a'..'z' | '0'..'9' | '_')*;
fragment F_ANNOTATION_ID : '@'('_')*('A'..'Z' | 'a'..'z' | '0'..'9' | '_')*;
fragment F_INT : ('-')?('0'|(('1'..'9')('0'..'9')*));
fragment F_PRIMITIVE_TYPE : 'byte'|'int'|'long'|'boolean'|'char'|'float'|'double'|'short';
fragment F_BASIC_TYPE : 'uint'|'ulong'|'ufloat'|'udouble'|'ushort'|'ubyte';
fragment ESCAPE_SEQUENCE : '\\r'|'\\n'|'\\t'|'\\"'|'\\\\';
fragment SHARP : '#'{ _input.LA(1)!='{' }?;
|
lexer grammar TurinLexer;
@header {
}
@lexer::members {
public static final int WHITESPACE = 1;
public static final int COMMENTS = 2;
private boolean useHiddenChannel = false;
public void setUseHiddenChannel(boolean value) {
this.useHiddenChannel = value;
}
public int whitespaceChannel() {
if (useHiddenChannel) {
return HIDDEN;
} else {
return WHITESPACE;
}
}
public int commentsChannel() {
if (useHiddenChannel) {
return HIDDEN;
} else {
return COMMENTS;
}
}
}
// It is suggested to define the token types reused in different mode.
// See mode in-interpolation below
tokens { NAME_PLACEHOLDER, PLACEHOLDER, VALUE_ID, TYPE_ID, INT, LPAREN, RPAREN, COMMA, RELOP, AND_KW, OR_KW, NOT_KW }
NAMESPACE_KW : 'namespace';
PROGRAM_KW : 'program';
PROPERTY_KW : 'property';
DEFAULT_KW : 'default';
TYPE_KW : 'type';
VAL_KW : 'val';
HAS_KW : 'has';
ABSTRACT_KW : 'abstract';
SHARED_KW : 'shared';
IMPORT_KW : 'import';
AS_KW : 'as';
VOID_KW : 'void';
RETURN_KW : 'return';
FALSE_KW : 'false';
TRUE_KW : 'true';
IF_KW : 'if';
ELIF_KW : 'elif';
ELSE_KW : 'else';
THROW_KW : 'throw';
TRY_KW : 'try';
CATCH_KW : 'catch';
// For definitions reused in mode in-interpolation we define and refer to fragments
AND_KW : F_AND;
OR_KW : F_OR;
NOT_KW : F_NOT;
LPAREN : '(';
RPAREN : ')';
LBRACKET : '{';
RBRACKET : '}';
LSQUARE : '[';
RSQUARE : ']';
COMMA : ',';
POINT : '.';
COLON : ':';
// We use just one token type to reduce the number of states (and not crash Antlr...)
// https://github.com/antlr/antlr4/issues/840
EQUAL : '==' -> type(RELOP);
DIFFERENT : '!=' -> type(RELOP);
LESSEQ : '<=' -> type(RELOP);
LESS : '<' -> type(RELOP);
MOREEQ : '>=' -> type(RELOP);
MORE : '>' -> type(RELOP);
// ASSIGNMENT has to comes after EQUAL
ASSIGNMENT : '=';
// Mathematical operators cannot be merged in one token type because
// they have different precedences
ASTERISK : '*';
SLASH : '/';
PLUS : '+';
MINUS : '-';
PIPE : '|';
NAME_PLACEHOLDER : F_NAME_PLACEHOLDER;
PLACEHOLDER : F_PLACEHOLDER;
PRIMITIVE_TYPE : F_PRIMITIVE_TYPE;
BASIC_TYPE : F_BASIC_TYPE;
VALUE_ID : F_VALUE_ID | F_ESCAPED_VALUE_ID;
// Only for types
TYPE_ID : F_TYPE_ID | F_ESCAPED_TYPE_ID;
INT : F_INT;
STRING_START : '"' -> pushMode(IN_STRING);
WS : (' ' | '\t')+ -> channel(WHITESPACE);
NL : '\r'? '\n';
COMMENT : '/*' .*? '*/' -> channel(COMMENTS);
LINE_COMMENT : '//' ~[\r\n]* -> channel(COMMENTS);
ANNOTATION_ID : F_ANNOTATION_ID;
UNEXPECTED_CHAR : . ;
mode IN_STRING;
STRING_STOP : '"' -> popMode;
STRING_CONTENT : (~["\\#]|ESCAPE_SEQUENCE|SHARP)+;
INTERPOLATION_START : '#{' -> pushMode(IN_INTERPOLATION);
mode IN_INTERPOLATION;
INTERPOLATION_END : '}' -> popMode;
I_PRIMITIVE_TYPE : F_PRIMITIVE_TYPE -> type(PRIMITIVE_TYPE);
I_BASIC_TYPE : F_BASIC_TYPE -> type(BASIC_TYPE);
I_FALSE_KW : 'false' -> type(FALSE_KW);
I_TRUE_KW : 'true' -> type(TRUE_KW);
I_AND_KW : F_AND -> type(AND_KW);
I_OR_KW : F_OR -> type(OR_KW);
I_NOT_KW : F_NOT -> type(NOT_KW);
I_IF_KW : 'if' -> type(IF_KW);
I_ELSE_KW : 'else' -> type(ELSE_KW);
I_NAME_PLACEHOLDER : F_NAME_PLACEHOLDER -> type(NAME_PLACEHOLDER);
I_PLACEHOLDER : F_PLACEHOLDER -> type(PLACEHOLDER);
I_VALUE_ID : (F_VALUE_ID | F_ESCAPED_VALUE_ID) -> type(VALUE_ID);
I_TYPE_ID : (F_TYPE_ID | F_ESCAPED_TYPE_ID) -> type(TYPE_ID);
I_INT : F_INT -> type(INT);
I_COMMA : ',' -> type(COMMA);
I_LPAREN : '(' -> type(LPAREN);
I_RPAREN : ')' -> type(RPAREN);
I_LSQUARE : '[' -> type(LSQUARE);
I_RSQUARE : ']' -> type(RSQUARE);
I_ASTERISK : '*' -> type(ASTERISK);
I_SLASH : '/' -> type(SLASH);
I_PLUS : '+' -> type(PLUS);
I_MINUS : '-' -> type(MINUS);
I_POINT : '.' -> type(POINT);
I_EQUAL : '==' -> type(RELOP);
I_DIFFERENT : '!=' -> type(RELOP);
I_LESSEQ : '<=' -> type(RELOP);
I_LESS : '<' -> type(RELOP);
I_MOREEQ : '>=' -> type(RELOP);
I_MORE : '>' -> type(RELOP);
I_STRING_START : '"' -> type(STRING_START), pushMode(IN_STRING);
I_WS : (' ' | '\t')+ -> type(WS), channel(WHITESPACE);
I_UNEXPECTED_CHAR : . -> type(UNEXPECTED_CHAR);
fragment F_NAME_PLACEHOLDER : '_name';
fragment F_PLACEHOLDER : '_';
fragment F_AND : 'and';
fragment F_OR : 'or';
fragment F_NOT : 'not';
fragment F_VALUE_ID : ('_')*'a'..'z' ('A'..'Z' | 'a'..'z' | '0'..'9' | '_')*;
fragment F_ESCAPED_VALUE_ID : 'v#'('_')*('A'..'Z' | 'a'..'z') ('A'..'Z' | 'a'..'z' | '0'..'9' | '_')*;
// Only for types
fragment F_TYPE_ID : ('_')*'A'..'Z' ('A'..'Z' | 'a'..'z' | '0'..'9' | '_')*;
fragment F_ESCAPED_TYPE_ID : 'T#'('_')*('A'..'Z' | 'a'..'z') ('A'..'Z' | 'a'..'z' | '0'..'9' | '_')*;
fragment F_ANNOTATION_ID : '@'('_')*('A'..'Z' | 'a'..'z' | '0'..'9' | '_')*;
fragment F_INT : ('-')?('0'|(('1'..'9')('0'..'9')*));
fragment F_PRIMITIVE_TYPE : 'byte'|'int'|'long'|'boolean'|'char'|'float'|'double'|'short';
fragment F_BASIC_TYPE : 'uint'|'ulong'|'ufloat'|'udouble'|'ushort'|'ubyte';
fragment ESCAPE_SEQUENCE : '\\r'|'\\n'|'\\t'|'\\"'|'\\\\';
fragment SHARP : '#'{ _input.LA(1)!='{' }?;
|
define literals to escape value or type IDs with wrong case
|
define literals to escape value or type IDs with wrong case
|
ANTLR
|
apache-2.0
|
ftomassetti/turin-programming-language,ftomassetti/turin-programming-language
|
9014d9217e7d193e1586061bb54514cede67da7b
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/BaseRule.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/BaseRule.g4
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar BaseRule;
import Symbol, Keyword, Literals;
parameterMarker
: QUESTION_
;
literals
: stringLiterals
| numberLiterals
| dateTimeLiterals
| hexadecimalLiterals
| bitValueLiterals
| booleanLiterals
| nullValueLiterals
;
stringLiterals
: characterSetName_? STRING_ collateName_?
;
numberLiterals
: NUMBER_
;
dateTimeLiterals
: (DATE | TIME | TIMESTAMP) STRING_
| LBE_ identifier_ STRING_ RBE_
;
hexadecimalLiterals
: characterSetName_? HEX_DIGIT_ collateName_?
;
bitValueLiterals
: characterSetName_? BIT_NUM_ collateName_?
;
booleanLiterals
: TRUE | FALSE
;
nullValueLiterals
: NULL
;
characterSetName_
: IDENTIFIER_
;
collateName_
: IDENTIFIER_
;
identifier_
: IDENTIFIER_ | unreservedWord_
;
variable_
: (AT_ AT_)? (GLOBAL | PERSIST | PERSIST_ONLY | SESSION)? DOT_? identifier_
;
unreservedWord_
: ACCOUNT | ACTION | AFTER | ALGORITHM | ALWAYS | ANY | AUTO_INCREMENT
| AVG_ROW_LENGTH | BEGIN | BTREE | CHAIN | CHARSET | CHECKSUM | CIPHER
| CLIENT | COALESCE | COLUMNS | COLUMN_FORMAT | COMMENT | COMMIT | COMMITTED
| COMPACT | COMPRESSED | COMPRESSION | CONNECTION | CONSISTENT | CURRENT | DATA
| DATE | DELAY_KEY_WRITE | DISABLE | DISCARD | DISK | DUPLICATE | ENABLE
| ENCRYPTION | ENFORCED | END | ENGINE | ESCAPE | EVENT | EXCHANGE
| EXECUTE | FILE | FIRST | FIXED | FOLLOWING | GLOBAL | HASH
| IMPORT_ | INSERT_METHOD | INVISIBLE | KEY_BLOCK_SIZE | LAST | LESS
| LEVEL | MAX_ROWS | MEMORY | MIN_ROWS | MODIFY | NO | NONE | OFFSET
| PACK_KEYS | PARSER | PARTIAL | PARTITIONING | PASSWORD | PERSIST | PERSIST_ONLY
| PRECEDING | PRIVILEGES | PROCESS | PROXY | QUICK | REBUILD | REDUNDANT
| RELOAD | REMOVE | REORGANIZE | REPAIR | REVERSE | ROLLBACK | ROLLUP
| ROW_FORMAT | SAVEPOINT | SESSION | SHUTDOWN | SIMPLE | SLAVE | SOUNDS
| SQL_BIG_RESULT | SQL_BUFFER_RESULT | SQL_CACHE | SQL_NO_CACHE | START | STATS_AUTO_RECALC | STATS_PERSISTENT
| STATS_SAMPLE_PAGES | STORAGE | SUBPARTITION | SUPER | TABLES | TABLESPACE | TEMPORARY
| THAN | TIME | TIMESTAMP | TRANSACTION | TRUNCATE | UNBOUNDED | UNKNOWN
| UPGRADE | VALIDATION | VALUE | VIEW | VISIBLE | WEIGHT_STRING | WITHOUT
| MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH
| QUARTER | YEAR | AGAINST | LANGUAGE | MODE | QUERY | EXPANSION
| BOOLEAN | MAX | MIN | SUM | COUNT | AVG | BIT_AND
| BIT_OR | BIT_XOR | GROUP_CONCAT | JSON_ARRAYAGG | JSON_OBJECTAGG | STD | STDDEV
| STDDEV_POP | STDDEV_SAMP | VAR_POP | VAR_SAMP | VARIANCE
;
tableName
: (identifier_ DOT_)? identifier_
;
columnName
: (identifier_ DOT_)? identifier_
;
columnNames
: LP_ columnName (COMMA_ columnName)* RP_
;
indexName
: identifier_
;
expr
: expr logicalOperator expr
| expr XOR expr
| notOperator_ expr
| LP_ expr RP_
| booleanPrimary_
;
logicalOperator
: OR | OR_ | AND | AND_
;
notOperator_
: NOT | NOT_
;
booleanPrimary_
: booleanPrimary_ IS NOT? (TRUE | FALSE | UNKNOWN | NULL)
| booleanPrimary_ SAFE_EQ_ predicate
| booleanPrimary_ comparisonOperator predicate
| booleanPrimary_ comparisonOperator (ALL | ANY) subquery
| predicate
;
comparisonOperator
: EQ_ | GTE_ | GT_ | LTE_ | LT_ | NEQ_
;
predicate
: bitExpr NOT? IN subquery
| bitExpr NOT? IN LP_ expr (COMMA_ expr)* RP_
| bitExpr NOT? BETWEEN bitExpr AND predicate
| bitExpr SOUNDS LIKE bitExpr
| bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)?
| bitExpr NOT? (REGEXP | RLIKE) bitExpr
| bitExpr
;
bitExpr
: bitExpr VERTICAL_BAR_ bitExpr
| bitExpr AMPERSAND_ bitExpr
| bitExpr SIGNED_LEFT_SHIFT_ bitExpr
| bitExpr SIGNED_RIGHT_SHIFT_ bitExpr
| bitExpr PLUS_ bitExpr
| bitExpr MINUS_ bitExpr
| bitExpr ASTERISK_ bitExpr
| bitExpr SLASH_ bitExpr
| bitExpr DIV bitExpr
| bitExpr MOD bitExpr
| bitExpr MOD_ bitExpr
| bitExpr CARET_ bitExpr
| bitExpr PLUS_ intervalExpression_
| bitExpr MINUS_ intervalExpression_
| simpleExpr
;
simpleExpr
: functionCall
| parameterMarker
| literals
| columnName
| simpleExpr COLLATE (STRING_ | identifier_)
| variable_
| simpleExpr OR_ simpleExpr
| (PLUS_ | MINUS_ | TILDE_ | NOT_ | BINARY) simpleExpr
| ROW? LP_ expr (COMMA_ expr)* RP_
| EXISTS? subquery
| LBE_ identifier_ expr RBE_
| matchExpression_
| caseExpression_
| intervalExpression_
;
functionCall
: aggregationFunction | specialFunction_ | regularFunction_
;
aggregationFunction
: aggregationFunctionName_ LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? RP_ overClause_?
;
aggregationFunctionName_
: MAX | MIN | SUM | COUNT | AVG | BIT_AND | BIT_OR
| BIT_XOR | JSON_ARRAYAGG | JSON_OBJECTAGG | STD | STDDEV | STDDEV_POP | STDDEV_SAMP
| VAR_POP | VAR_SAMP | VARIANCE
;
distinct
: DISTINCT
;
overClause_
: OVER (LP_ windowSpecification_ RP_ | identifier_)
;
windowSpecification_
: identifier_? partitionClause_? orderByClause? frameClause_?
;
partitionClause_
: PARTITION BY expr (COMMA_ expr)*
;
frameClause_
: (ROWS | RANGE) (frameStart_ | frameBetween_)
;
frameStart_
: CURRENT ROW | UNBOUNDED PRECEDING | UNBOUNDED FOLLOWING | expr PRECEDING | expr FOLLOWING
;
frameEnd_
: frameStart_
;
frameBetween_
: BETWEEN frameStart_ AND frameEnd_
;
specialFunction_
: groupConcatFunction_ | windowFunction_ | castFunction_ | convertFunction_ | positionFunction_ | substringFunction_ | extractFunction_
| charFunction_ | trimFunction_ | weightStringFunction_
;
groupConcatFunction_
: GROUP_CONCAT LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? (orderByClause (SEPARATOR expr)?)? RP_
;
windowFunction_
: identifier_ LP_ expr (COMMA_ expr)* RP_ overClause_
;
castFunction_
: CAST LP_ expr AS dataType RP_
;
convertFunction_
: CONVERT LP_ expr COMMA_ dataType RP_
| CONVERT LP_ expr USING identifier_ RP_
;
positionFunction_
: POSITION LP_ expr IN expr RP_
;
substringFunction_
: (SUBSTRING | SUBSTR) LP_ expr FROM NUMBER_ (FOR NUMBER_)? RP_
;
extractFunction_
: EXTRACT LP_ identifier_ FROM expr RP_
;
charFunction_
: CHAR LP_ expr (COMMA_ expr)* (USING ignoredIdentifier_)? RP_
;
trimFunction_
: TRIM LP_ (LEADING | BOTH | TRAILING) STRING_ FROM STRING_ RP_
;
weightStringFunction_
: WEIGHT_STRING LP_ expr (AS dataType)? levelClause_? RP_
;
levelClause_
: LEVEL (levelInWeightListElement_ (COMMA_ levelInWeightListElement_)* | NUMBER_ MINUS_ NUMBER_)
;
levelInWeightListElement_
: NUMBER_ (ASC | DESC)? REVERSE?
;
regularFunction_
: regularFunctionName_ LP_ (expr (COMMA_ expr)* | ASTERISK_)? RP_
;
regularFunctionName_
: identifier_ | IF | CURRENT_TIMESTAMP | LOCALTIME | LOCALTIMESTAMP | NOW | REPLACE
;
matchExpression_
: MATCH columnNames AGAINST (expr matchSearchModifier_?)
;
matchSearchModifier_
: IN NATURAL LANGUAGE MODE | IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION | IN BOOLEAN MODE | WITH QUERY EXPANSION
;
caseExpression_
: CASE simpleExpr? caseWhen_+ caseElse_? END
;
caseWhen_
: WHEN expr THEN expr
;
caseElse_
: ELSE expr
;
intervalExpression_
: INTERVAL expr intervalUnit_
;
intervalUnit_
: MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH
| QUARTER | YEAR | SECOND_MICROSECOND | MINUTE_MICROSECOND | MINUTE_SECOND | HOUR_MICROSECOND | HOUR_SECOND
| HOUR_MINUTE | DAY_MICROSECOND | DAY_SECOND | DAY_MINUTE | DAY_HOUR | YEAR_MONTH
;
subquery
: 'Default does not match anything'
;
orderByClause
: ORDER BY orderByItem (COMMA_ orderByItem)*
;
orderByItem
: (columnName | numberLiterals | expr) (ASC | DESC)?
;
dataType
: dataTypeName_ dataTypeLength? characterSet_? collateClause_? UNSIGNED? ZEROFILL? | dataTypeName_ LP_ STRING_ (COMMA_ STRING_)* RP_ characterSet_? collateClause_?
;
dataTypeName_
: identifier_ identifier_?
;
dataTypeLength
: LP_ NUMBER_ (COMMA_ NUMBER_)? RP_
;
characterSet_
: (CHARACTER | CHAR) SET EQ_? ignoredIdentifier_ | CHARSET EQ_? ignoredIdentifier_
;
collateClause_
: COLLATE EQ_? (STRING_ | ignoredIdentifier_)
;
ignoredIdentifier_
: identifier_ (DOT_ identifier_)?
;
ignoredIdentifiers_
: ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar BaseRule;
import Symbol, Keyword, Literals;
parameterMarker
: QUESTION_
;
literals
: stringLiterals
| numberLiterals
| dateTimeLiterals
| hexadecimalLiterals
| bitValueLiterals
| booleanLiterals
| nullValueLiterals
;
stringLiterals
: characterSetName_? STRING_ collateName_?
;
numberLiterals
: NUMBER_
;
dateTimeLiterals
: (DATE | TIME | TIMESTAMP) STRING_
| LBE_ identifier_ STRING_ RBE_
;
hexadecimalLiterals
: characterSetName_? HEX_DIGIT_ collateName_?
;
bitValueLiterals
: characterSetName_? BIT_NUM_ collateName_?
;
booleanLiterals
: TRUE | FALSE
;
nullValueLiterals
: NULL
;
characterSetName_
: IDENTIFIER_
;
collateName_
: COLLATE IDENTIFIER_
;
identifier_
: IDENTIFIER_ | unreservedWord_
;
variable_
: (AT_ AT_)? (GLOBAL | PERSIST | PERSIST_ONLY | SESSION)? DOT_? identifier_
;
unreservedWord_
: ACCOUNT | ACTION | AFTER | ALGORITHM | ALWAYS | ANY | AUTO_INCREMENT
| AVG_ROW_LENGTH | BEGIN | BTREE | CHAIN | CHARSET | CHECKSUM | CIPHER
| CLIENT | COALESCE | COLUMNS | COLUMN_FORMAT | COMMENT | COMMIT | COMMITTED
| COMPACT | COMPRESSED | COMPRESSION | CONNECTION | CONSISTENT | CURRENT | DATA
| DATE | DELAY_KEY_WRITE | DISABLE | DISCARD | DISK | DUPLICATE | ENABLE
| ENCRYPTION | ENFORCED | END | ENGINE | ESCAPE | EVENT | EXCHANGE
| EXECUTE | FILE | FIRST | FIXED | FOLLOWING | GLOBAL | HASH
| IMPORT_ | INSERT_METHOD | INVISIBLE | KEY_BLOCK_SIZE | LAST | LESS
| LEVEL | MAX_ROWS | MEMORY | MIN_ROWS | MODIFY | NO | NONE | OFFSET
| PACK_KEYS | PARSER | PARTIAL | PARTITIONING | PASSWORD | PERSIST | PERSIST_ONLY
| PRECEDING | PRIVILEGES | PROCESS | PROXY | QUICK | REBUILD | REDUNDANT
| RELOAD | REMOVE | REORGANIZE | REPAIR | REVERSE | ROLLBACK | ROLLUP
| ROW_FORMAT | SAVEPOINT | SESSION | SHUTDOWN | SIMPLE | SLAVE | SOUNDS
| SQL_BIG_RESULT | SQL_BUFFER_RESULT | SQL_CACHE | SQL_NO_CACHE | START | STATS_AUTO_RECALC | STATS_PERSISTENT
| STATS_SAMPLE_PAGES | STORAGE | SUBPARTITION | SUPER | TABLES | TABLESPACE | TEMPORARY
| THAN | TIME | TIMESTAMP | TRANSACTION | TRUNCATE | UNBOUNDED | UNKNOWN
| UPGRADE | VALIDATION | VALUE | VIEW | VISIBLE | WEIGHT_STRING | WITHOUT
| MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH
| QUARTER | YEAR | AGAINST | LANGUAGE | MODE | QUERY | EXPANSION
| BOOLEAN | MAX | MIN | SUM | COUNT | AVG | BIT_AND
| BIT_OR | BIT_XOR | GROUP_CONCAT | JSON_ARRAYAGG | JSON_OBJECTAGG | STD | STDDEV
| STDDEV_POP | STDDEV_SAMP | VAR_POP | VAR_SAMP | VARIANCE
;
tableName
: (identifier_ DOT_)? identifier_
;
columnName
: (identifier_ DOT_)? identifier_
;
columnNames
: LP_ columnName (COMMA_ columnName)* RP_
;
indexName
: identifier_
;
expr
: expr logicalOperator expr
| expr XOR expr
| notOperator_ expr
| LP_ expr RP_
| booleanPrimary_
;
logicalOperator
: OR | OR_ | AND | AND_
;
notOperator_
: NOT | NOT_
;
booleanPrimary_
: booleanPrimary_ IS NOT? (TRUE | FALSE | UNKNOWN | NULL)
| booleanPrimary_ SAFE_EQ_ predicate
| booleanPrimary_ comparisonOperator predicate
| booleanPrimary_ comparisonOperator (ALL | ANY) subquery
| predicate
;
comparisonOperator
: EQ_ | GTE_ | GT_ | LTE_ | LT_ | NEQ_
;
predicate
: bitExpr NOT? IN subquery
| bitExpr NOT? IN LP_ expr (COMMA_ expr)* RP_
| bitExpr NOT? BETWEEN bitExpr AND predicate
| bitExpr SOUNDS LIKE bitExpr
| bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)?
| bitExpr NOT? (REGEXP | RLIKE) bitExpr
| bitExpr
;
bitExpr
: bitExpr VERTICAL_BAR_ bitExpr
| bitExpr AMPERSAND_ bitExpr
| bitExpr SIGNED_LEFT_SHIFT_ bitExpr
| bitExpr SIGNED_RIGHT_SHIFT_ bitExpr
| bitExpr PLUS_ bitExpr
| bitExpr MINUS_ bitExpr
| bitExpr ASTERISK_ bitExpr
| bitExpr SLASH_ bitExpr
| bitExpr DIV bitExpr
| bitExpr MOD bitExpr
| bitExpr MOD_ bitExpr
| bitExpr CARET_ bitExpr
| bitExpr PLUS_ intervalExpression_
| bitExpr MINUS_ intervalExpression_
| simpleExpr
;
simpleExpr
: functionCall
| parameterMarker
| literals
| columnName
| simpleExpr COLLATE (STRING_ | identifier_)
| variable_
| simpleExpr OR_ simpleExpr
| (PLUS_ | MINUS_ | TILDE_ | NOT_ | BINARY) simpleExpr
| ROW? LP_ expr (COMMA_ expr)* RP_
| EXISTS? subquery
| LBE_ identifier_ expr RBE_
| matchExpression_
| caseExpression_
| intervalExpression_
;
functionCall
: aggregationFunction | specialFunction_ | regularFunction_
;
aggregationFunction
: aggregationFunctionName_ LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? RP_ overClause_?
;
aggregationFunctionName_
: MAX | MIN | SUM | COUNT | AVG | BIT_AND | BIT_OR
| BIT_XOR | JSON_ARRAYAGG | JSON_OBJECTAGG | STD | STDDEV | STDDEV_POP | STDDEV_SAMP
| VAR_POP | VAR_SAMP | VARIANCE
;
distinct
: DISTINCT
;
overClause_
: OVER (LP_ windowSpecification_ RP_ | identifier_)
;
windowSpecification_
: identifier_? partitionClause_? orderByClause? frameClause_?
;
partitionClause_
: PARTITION BY expr (COMMA_ expr)*
;
frameClause_
: (ROWS | RANGE) (frameStart_ | frameBetween_)
;
frameStart_
: CURRENT ROW | UNBOUNDED PRECEDING | UNBOUNDED FOLLOWING | expr PRECEDING | expr FOLLOWING
;
frameEnd_
: frameStart_
;
frameBetween_
: BETWEEN frameStart_ AND frameEnd_
;
specialFunction_
: groupConcatFunction_ | windowFunction_ | castFunction_ | convertFunction_ | positionFunction_ | substringFunction_ | extractFunction_
| charFunction_ | trimFunction_ | weightStringFunction_
;
groupConcatFunction_
: GROUP_CONCAT LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? (orderByClause (SEPARATOR expr)?)? RP_
;
windowFunction_
: identifier_ LP_ expr (COMMA_ expr)* RP_ overClause_
;
castFunction_
: CAST LP_ expr AS dataType RP_
;
convertFunction_
: CONVERT LP_ expr COMMA_ dataType RP_
| CONVERT LP_ expr USING identifier_ RP_
;
positionFunction_
: POSITION LP_ expr IN expr RP_
;
substringFunction_
: (SUBSTRING | SUBSTR) LP_ expr FROM NUMBER_ (FOR NUMBER_)? RP_
;
extractFunction_
: EXTRACT LP_ identifier_ FROM expr RP_
;
charFunction_
: CHAR LP_ expr (COMMA_ expr)* (USING ignoredIdentifier_)? RP_
;
trimFunction_
: TRIM LP_ (LEADING | BOTH | TRAILING) STRING_ FROM STRING_ RP_
;
weightStringFunction_
: WEIGHT_STRING LP_ expr (AS dataType)? levelClause_? RP_
;
levelClause_
: LEVEL (levelInWeightListElement_ (COMMA_ levelInWeightListElement_)* | NUMBER_ MINUS_ NUMBER_)
;
levelInWeightListElement_
: NUMBER_ (ASC | DESC)? REVERSE?
;
regularFunction_
: regularFunctionName_ LP_ (expr (COMMA_ expr)* | ASTERISK_)? RP_
;
regularFunctionName_
: identifier_ | IF | CURRENT_TIMESTAMP | LOCALTIME | LOCALTIMESTAMP | NOW | REPLACE
;
matchExpression_
: MATCH columnNames AGAINST (expr matchSearchModifier_?)
;
matchSearchModifier_
: IN NATURAL LANGUAGE MODE | IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION | IN BOOLEAN MODE | WITH QUERY EXPANSION
;
caseExpression_
: CASE simpleExpr? caseWhen_+ caseElse_? END
;
caseWhen_
: WHEN expr THEN expr
;
caseElse_
: ELSE expr
;
intervalExpression_
: INTERVAL expr intervalUnit_
;
intervalUnit_
: MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH
| QUARTER | YEAR | SECOND_MICROSECOND | MINUTE_MICROSECOND | MINUTE_SECOND | HOUR_MICROSECOND | HOUR_SECOND
| HOUR_MINUTE | DAY_MICROSECOND | DAY_SECOND | DAY_MINUTE | DAY_HOUR | YEAR_MONTH
;
subquery
: 'Default does not match anything'
;
orderByClause
: ORDER BY orderByItem (COMMA_ orderByItem)*
;
orderByItem
: (columnName | numberLiterals | expr) (ASC | DESC)?
;
dataType
: dataTypeName_ dataTypeLength? characterSet_? collateClause_? UNSIGNED? ZEROFILL? | dataTypeName_ LP_ STRING_ (COMMA_ STRING_)* RP_ characterSet_? collateClause_?
;
dataTypeName_
: identifier_ identifier_?
;
dataTypeLength
: LP_ NUMBER_ (COMMA_ NUMBER_)? RP_
;
characterSet_
: (CHARACTER | CHAR) SET EQ_? ignoredIdentifier_ | CHARSET EQ_? ignoredIdentifier_
;
collateClause_
: COLLATE EQ_? (STRING_ | ignoredIdentifier_)
;
ignoredIdentifier_
: identifier_ (DOT_ identifier_)?
;
ignoredIdentifiers_
: ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*
;
|
modify collateName_
|
modify collateName_
|
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
|
c3f7bf8873bc0776feff8bc744f986f0afbf6797
|
omni-cx2x/src/cx2x/translator/language/Claw.g4
|
omni-cx2x/src/cx2x/translator/language/Claw.g4
|
/*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
/**
* ANTLR 4 Grammar file for the CLAW directive language.
*
* @author clementval
*/
grammar Claw;
@header
{
import java.util.List;
import java.util.ArrayList;
}
/*----------------------------------------------------------------------------
* PARSER RULES
*----------------------------------------------------------------------------*/
/*
* Entry point for the analyzis of a CLAW directive.
* Return a CLawLanguage object with all needed information.
*/
analyze returns [ClawLanguage language]
@init{
$language = new ClawLanguage();
}
:
CLAW directive[$language]
;
index_list returns [List<String> indexes]
@init{
$indexes = new ArrayList();
}
:
i=IDENTIFIER { $indexes.add($i.text); }
| i=IDENTIFIER { $indexes.add($i.text); } COMMA index_list
;
directive[ClawLanguage language]:
LFUSION { $language.setDirective(ClawDirective.LOOP_FUSION); } group_option
| LINTERCHANGE { $language.setDirective(ClawDirective.LOOP_INTERCHANGE); } '(' index_list ')'
| LEXTRACT { $language.setDirective(ClawDirective.LOOP_EXTRACT); } range_option
| REMOVE { $language.setDirective(ClawDirective.REMOVE); }
| END REMOVE { $language.setDirective(ClawDirective.END_REMOVE); }
;
group_option:
GROUP '(' IDENTIFIER ')'
| /* empty */
;
range_option:
RANGE '(' IDENTIFIER '=' ')'
;
mapping_option:
MAP '(' COLON ')'
;
map_list:
mapping_option
| mapping_option map_list
;
/*----------------------------------------------------------------------------
* LEXER RULES
*----------------------------------------------------------------------------*/
// Start point
CLAW : 'claw';
// Directives
LFUSION : 'loop-fusion';
LINTERCHANGE : 'loop-interchange';
LEXTRACT : 'loop-extract';
REMOVE : 'remove';
END : 'end';
// Options
GROUP : 'group';
RANGE : 'range';
MAP : 'map';
// Special elements
IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9]* ;
COMMA : ',' ;
COLON : ':';
NUMBER : (DIGIT)+ ;
fragment DIGIT : '0'..'9' ;
// Skip whitspaces
WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
|
/*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
/**
* ANTLR 4 Grammar file for the CLAW directive language.
*
* @author clementval
*/
grammar Claw;
@header
{
import java.util.List;
import java.util.ArrayList;
}
/*----------------------------------------------------------------------------
* PARSER RULES
*----------------------------------------------------------------------------*/
/*
* Entry point for the analyzis of a CLAW directive.
* Return a CLawLanguage object with all needed information.
*/
analyze returns [ClawLanguage language]
@init{
$language = new ClawLanguage();
}
:
CLAW directive[$language]
;
ids_list returns [List<String> ids]
@init{
$ids = new ArrayList();
}
:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } COMMA ids_list
;
directive[ClawLanguage language]:
LFUSION { $language.setDirective(ClawDirective.LOOP_FUSION); } group_option
| LINTERCHANGE { $language.setDirective(ClawDirective.LOOP_INTERCHANGE); } '(' ids_list ')'
| LEXTRACT { $language.setDirective(ClawDirective.LOOP_EXTRACT); } range_option
| REMOVE { $language.setDirective(ClawDirective.REMOVE); }
| END REMOVE { $language.setDirective(ClawDirective.END_REMOVE); }
;
group_option:
GROUP '(' IDENTIFIER ')'
| /* empty */
;
range_option:
RANGE '(' IDENTIFIER '=' ')'
;
mapping_option:
MAP '(' ids_list COLON ids_list ')'
;
map_list:
mapping_option
| mapping_option map_list
;
/*----------------------------------------------------------------------------
* LEXER RULES
*----------------------------------------------------------------------------*/
// Start point
CLAW : 'claw';
// Directives
LFUSION : 'loop-fusion';
LINTERCHANGE : 'loop-interchange';
LEXTRACT : 'loop-extract';
REMOVE : 'remove';
END : 'end';
// Options
GROUP : 'group';
RANGE : 'range';
MAP : 'map';
// Special elements
IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9]* ;
COMMA : ',' ;
COLON : ':';
NUMBER : (DIGIT)+ ;
fragment DIGIT : '0'..'9' ;
// Skip whitspaces
WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
|
Add ids_list to mapping option parser rule
|
Add ids_list to mapping option parser rule
|
ANTLR
|
bsd-2-clause
|
clementval/claw-compiler,clementval/claw-compiler
|
527f2f3dc878448b6477c1bb35e0a135c09e1849
|
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
|
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
|
grammar OracleDCLStatement;
import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol;
/**
* each statement has a url,
* each base url : https://docs.oracle.com/database/121/SQLRF/.
* no begin statement in oracle
*/
//statements_9014.htm#SQLRF01603
grant
: GRANT
(
(grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))?
| grantRolesToPrograms
)
;
grantSystemPrivileges
: systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)?
;
systemObjects
: systemObject(COMMA systemObject)*
;
systemObject
: ALL PRIVILEGES
| roleName
| ID *?
;
systemPrivilege
:
;
grantees
: grantee (COMMA grantee)*
;
grantee
: userName
| roleName
| PUBLIC
;
granteeIdentifiedBy
: userName (COMMA userName)* IDENTIFIED BY STRING (COMMA STRING)*
;
grantObjectPrivilegeClause
: grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause
TO grantees (WITH HIERARCHY OPTION)?(WITH GRANT OPTION)?
;
grantObjectPrivilege
: objectPrivilege ( LP_ columnName (COMMA columnName)* RP_)?
;
objectPrivilege
: ID *?
| ALL PRIVILEGES?
;
onObjectClause
: ON
(
schemaName? ID
| USER userName ( COMMA userName)*
| (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID
)
;
grantRolesToPrograms
: roleName (COMMA roleName)* TO programUnit ( COMMA programUnit )*
;
programUnit
: (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID
;
|
grammar OracleDCLStatement;
import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol;
/**
* each statement has a url,
* each base url : https://docs.oracle.com/database/121/SQLRF/.
* no begin statement in oracle
*/
//statements_9014.htm#SQLRF01603
grant
: GRANT
(
(grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))?
| grantRolesToPrograms
)
;
grantSystemPrivileges
: systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)?
;
systemObjects
: systemObject(COMMA systemObject)*
;
systemObject
: ALL PRIVILEGES
| roleName
| ID *?
;
grantees
: grantee (COMMA grantee)*
;
grantee
: userName
| roleName
| PUBLIC
;
granteeIdentifiedBy
: userName (COMMA userName)* IDENTIFIED BY STRING (COMMA STRING)*
;
grantObjectPrivilegeClause
: grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause
TO grantees (WITH HIERARCHY OPTION)?(WITH GRANT OPTION)?
;
grantObjectPrivilege
: objectPrivilege ( LP_ columnName (COMMA columnName)* RP_)?
;
objectPrivilege
: ID *?
| ALL PRIVILEGES?
;
onObjectClause
: ON
(
schemaName? ID
| USER userName ( COMMA userName)*
| (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID
)
;
grantRolesToPrograms
: roleName (COMMA roleName)* TO programUnit ( COMMA programUnit )*
;
programUnit
: (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID
;
|
remove systemPrivilege
|
remove systemPrivilege
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
92be65e3fac0607b5c2c0ed6f5e3c922d170b15d
|
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 createSpecification_ TABLE tableName createDefinitionClause_
;
createIndex
: CREATE (UNIQUE | BITMAP)? INDEX indexName ON (tableIndexClause_ | bitmapJoinIndexClause_)
;
alterTable
: ALTER TABLE tableName (alterTableProperties | columnClauses | constraintClauses | alterExternalTable)?
;
// TODO hongjun throw exeption when alter index on oracle
alterIndex
: ALTER INDEX indexName (RENAME TO indexName)?
;
dropTable
: DROP TABLE tableName
;
dropIndex
: DROP INDEX indexName
;
truncateTable
: TRUNCATE TABLE tableName
;
createSpecification_
: (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*
;
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
;
tableIndexClause_
: tableName alias? LP_ indexExpr_ (COMMA_ indexExpr_)* RP_
;
indexExpr_
: (columnName | expr) (ASC | DESC)?
;
bitmapJoinIndexClause_
: tableName LP_ columnSortClause_ (COMMA_ columnSortClause_)* RP_ FROM tableName alias? (COMMA_ tableName alias?)* WHERE expr
;
columnSortClause_
: tableName alias? columnName (ASC | DESC)?
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE 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? LP_ indexExpr_ (COMMA_ indexExpr_)* RP_
;
indexExpr_
: (columnName | expr) (ASC | DESC)?
;
bitmapJoinIndexClause_
: tableName LP_ columnSortClause_ (COMMA_ columnSortClause_)* RP_ FROM tableName alias? (COMMA_ tableName alias?)* WHERE expr
;
columnSortClause_
: tableName alias? columnName (ASC | DESC)?
;
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 createIndexSpecification_
|
add createIndexSpecification_
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
|
919ac257445878bd1dce3570ea5ed59132ee864c
|
projects/batfish/src/org/batfish/grammar/topology/BatfishTopologyLexer.g4
|
projects/batfish/src/org/batfish/grammar/topology/BatfishTopologyLexer.g4
|
lexer grammar BatfishTopologyLexer;
options {
superClass = 'org.batfish.grammar.BatfishLexer';
}
@header {
package org.batfish.grammar.topology;
}
HEADER
:
'BATFISH_TOPOLOGY'
;
COLON
:
':'
;
COMMA
:
','
;
HASH
:
'#' -> pushMode(M_COMMENT), channel(HIDDEN)
;
NEWLINE
:
F_NewlineChar+
;
VARIABLE
:
F_VarChar+
;
WS
:
F_WhitespaceChar+ -> channel(HIDDEN)
;
fragment
F_NewlineChar
:
[\n\r]
;
fragment
F_NonNewlineChar
:
~[\n\r]
;
fragment
F_VarChar
:
~[\n\r:, \t\u000C]
;
fragment
F_WhitespaceChar
:
[ \t\u000C]
;
mode M_COMMENT;
M_COMMENT_COMMENT
:
F_NonNewlineChar+ -> channel(HIDDEN)
;
M_COMMENT_NEWLINE
:
F_NewlineChar+ -> type(NEWLINE), popMode
;
|
lexer grammar BatfishTopologyLexer;
options {
superClass = 'org.batfish.grammar.BatfishLexer';
}
@header {
package org.batfish.grammar.topology;
}
HEADER
:
'BATFISH_TOPOLOGY'
;
COLON
:
':'
;
COMMA
:
','
;
DOUBLE_QUOTE
:
'"' -> pushMode ( M_DoubleQuote ) , channel ( HIDDEN )
;
HASH
:
'#' -> pushMode ( M_COMMENT ) , channel ( HIDDEN )
;
NEWLINE
:
F_NewlineChar+
;
SINGLE_QUOTE
:
'\'' -> pushMode ( M_SingleQuote ) , channel ( HIDDEN )
;
VARIABLE
:
F_VarChar+
;
WS
:
F_WhitespaceChar+ -> channel ( HIDDEN )
;
fragment
F_NewlineChar
:
[\n\r]
;
fragment
F_NonNewlineChar
:
~[\n\r]
;
fragment
F_VarChar
:
~[\n\r:, \t\u000C]
;
fragment
F_WhitespaceChar
:
[ \t\u000C]
;
mode M_COMMENT;
M_COMMENT_COMMENT
:
F_NonNewlineChar+ -> channel ( HIDDEN )
;
M_COMMENT_NEWLINE
:
F_NewlineChar+ -> type ( NEWLINE ) , popMode
;
mode M_DoubleQuote;
M_DoubleQuote_VARIABLE
:
~'"'+ -> type ( VARIABLE )
;
M_DoubleQuote_DOUBLE_QUOTE
:
'"' -> channel ( HIDDEN ) , popMode
;
mode M_SingleQuote;
M_SingleQuote_VARIABLE
:
~'\''+ -> type ( VARIABLE )
;
M_SingleQuote_SINGLE_QUOTE
:
'\'' -> channel ( HIDDEN ) , popMode
;
|
allow single and double-quotes in batfish topology format
|
allow single and double-quotes in batfish topology format
|
ANTLR
|
apache-2.0
|
arifogel/batfish,batfish/batfish,intentionet/batfish,intentionet/batfish,intentionet/batfish,arifogel/batfish,dhalperi/batfish,batfish/batfish,batfish/batfish,intentionet/batfish,dhalperi/batfish,arifogel/batfish,dhalperi/batfish,intentionet/batfish
|
5f9cbe3d02deb669330026c3068cd4e8ff4bc2c6
|
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 (GLOBAL TEMPORARY)? TABLE tableName relationalTable
;
createIndex
: CREATE (UNIQUE | BITMAP)? INDEX indexName ON (tableIndexClause_ | bitmapJoinIndexClause_)
;
alterTable
: ALTER TABLE tableName (alterTableProperties | columnClauses | constraintClauses | alterExternalTable)?
;
// TODO hongjun throw exeption when alter index on oracle
alterIndex
: ALTER INDEX indexName (RENAME TO indexName)?
;
dropTable
: DROP TABLE tableName
;
dropIndex
: DROP INDEX indexName
;
truncateTable
: TRUNCATE TABLE tableName
;
tablespaceClauseWithParen
: LP_ tablespaceClause RP_
;
tablespaceClause
: TABLESPACE ignoredIdentifier_
;
domainIndexClause
: indexTypeName
;
relationalTable
: (LP_ relationalProperties RP_)? (ON COMMIT (DELETE | PRESERVE) ROWS)? tableProperties
;
relationalProperties
: relationalProperty (COMMA_ relationalProperty)*
;
relationalProperty
: columnDefinition | virtualColumnDefinition | outOfLineConstraint | outOfLineRefConstraint
;
tableProperties
: columnProperties? (AS unionSelect)?
;
unionSelect
: matchNone
;
alterTableProperties
: renameTableSpecification_ | REKEY encryptionSpec
;
renameTableSpecification_
: RENAME TO newTableName
;
newTableName
: IDENTIFIER_
;
columnClauses
: opColumnClause+ | renameColumnSpecification
;
opColumnClause
: addColumnSpecification | modifyColumnSpecification | dropColumnClause
;
addColumnSpecification
: ADD columnOrVirtualDefinitions columnProperties?
;
columnOrVirtualDefinitions
: LP_ columnOrVirtualDefinition (COMMA_ columnOrVirtualDefinition)* RP_ | columnOrVirtualDefinition
;
columnOrVirtualDefinition
: columnDefinition | virtualColumnDefinition
;
modifyColumnSpecification
: MODIFY (LP_? modifyColProperties (COMMA_ modifyColProperties)* RP_? | modifyColSubstitutable)
;
modifyColProperties
: columnName dataType? (DEFAULT expr)? (ENCRYPT encryptionSpec | DECRYPT)? inlineConstraint*
;
modifyColSubstitutable
: COLUMN columnName NOT? SUBSTITUTABLE AT ALL LEVELS FORCE?
;
dropColumnClause
: SET UNUSED columnOrColumnList cascadeOrInvalidate* | dropColumnSpecification
;
dropColumnSpecification
: DROP columnOrColumnList cascadeOrInvalidate* checkpointNumber?
;
columnOrColumnList
: COLUMN columnName | LP_ columnName (COMMA_ columnName)* RP_
;
cascadeOrInvalidate
: CASCADE CONSTRAINTS | INVALIDATE
;
checkpointNumber
: CHECKPOINT NUMBER_
;
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
constraintClauses
: addConstraintSpecification | modifyConstraintClause | renameConstraintClause | dropConstraintClause+
;
addConstraintSpecification
: ADD (outOfLineConstraint+ | outOfLineRefConstraint)
;
modifyConstraintClause
: MODIFY constraintOption constraintState+ CASCADE?
;
constraintWithName
: CONSTRAINT ignoredIdentifier_
;
constraintOption
: constraintWithName | constraintPrimaryOrUnique
;
constraintPrimaryOrUnique
: primaryKey | UNIQUE columnNames
;
renameConstraintClause
: RENAME constraintWithName TO ignoredIdentifier_
;
dropConstraintClause
: DROP
(
constraintPrimaryOrUnique CASCADE? ((KEEP | DROP) INDEX)? | (CONSTRAINT ignoredIdentifier_ CASCADE?)
)
;
alterExternalTable
: (addColumnSpecification | modifyColumnSpecification | dropColumnSpecification)+
;
columnDefinition
: columnName dataType SORT? (DEFAULT (ON NULL)? expr | identityClause)? (ENCRYPT encryptionSpec)? (inlineConstraint+ | inlineRefConstraint)?
;
identityClause
: GENERATED (ALWAYS | BY DEFAULT (ON NULL)?) AS IDENTITY LP_? (identityOptions+)? RP_?
;
identityOptions
: START WITH (NUMBER_ | LIMIT VALUE)
| INCREMENT BY NUMBER_
| MAXVALUE NUMBER_
| NOMAXVALUE
| MINVALUE NUMBER_
| NOMINVALUE
| CYCLE
| NOCYCLE
| CACHE NUMBER_
| NOCACHE
| ORDER
| NOORDER
;
virtualColumnDefinition
: columnName dataType? (GENERATED ALWAYS)? AS LP_ expr RP_ VIRTUAL? inlineConstraint*
;
inlineConstraint
: (CONSTRAINT ignoredIdentifier_)? (NOT? NULL | UNIQUE | primaryKey | referencesClause | CHECK LP_ expr RP_) constraintState*
;
referencesClause
: REFERENCES tableName columnNames? (ON DELETE (CASCADE | SET NULL))?
;
constraintState
: notDeferrable
| initiallyClause
| RELY
| NORELY
| usingIndexClause
| ENABLE
| DISABLE
| VALIDATE
| NOVALIDATE
| exceptionsClause
;
notDeferrable
: NOT? DEFERRABLE
;
initiallyClause
: INITIALLY (IMMEDIATE | DEFERRED)
;
exceptionsClause
: EXCEPTIONS INTO
;
usingIndexClause
: USING INDEX (indexName | LP_ createIndex RP_)?
;
inlineRefConstraint
: SCOPE IS tableName | WITH ROWID | (CONSTRAINT ignoredIdentifier_)? referencesClause constraintState*
;
outOfLineConstraint
: (CONSTRAINT ignoredIdentifier_)?
(
UNIQUE columnNames
| primaryKey columnNames
| FOREIGN KEY columnNames referencesClause
| CHECK LP_ expr RP_
)
constraintState*
;
outOfLineRefConstraint
: SCOPE FOR LP_ lobItem RP_ IS tableName
| REF LP_ lobItem RP_ WITH ROWID
| (CONSTRAINT ignoredIdentifier_)? FOREIGN KEY lobItemList referencesClause constraintState*
;
encryptionSpec
: (USING STRING_)? (IDENTIFIED BY STRING_)? STRING_? (NO? SALT)?
;
objectProperties
: objectProperty (COMMA_ objectProperty)*
;
objectProperty
: (columnName | attributeName) (DEFAULT expr)? (inlineConstraint* | inlineRefConstraint?) | outOfLineConstraint | outOfLineRefConstraint
;
columnProperties
: columnProperty+
;
columnProperty
: objectTypeColProperties
;
objectTypeColProperties
: COLUMN columnName substitutableColumnClause
;
substitutableColumnClause
: ELEMENT? IS OF TYPE? LP_ ONLY? dataTypeName_ RP_ | NOT? SUBSTITUTABLE AT ALL LEVELS
;
tableIndexClause_
: tableName alias? LP_ indexExpr_ (COMMA_ indexExpr_)* RP_
;
indexExpr_
: (columnName | expr) (ASC | DESC)?
;
bitmapJoinIndexClause_
: tableName LP_ columnSortClause_ (COMMA_ columnSortClause_)* RP_ FROM tableName alias? (COMMA_ tableName alias?)* WHERE expr
;
columnSortClause_
: tableName alias? columnName (ASC | DESC)?
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE temporaryClause_ TABLE tableName relationalTable
;
createIndex
: CREATE (UNIQUE | BITMAP)? INDEX indexName ON (tableIndexClause_ | bitmapJoinIndexClause_)
;
alterTable
: ALTER TABLE tableName (alterTableProperties | columnClauses | constraintClauses | alterExternalTable)?
;
// TODO hongjun throw exeption when alter index on oracle
alterIndex
: ALTER INDEX indexName (RENAME TO indexName)?
;
dropTable
: DROP TABLE tableName
;
dropIndex
: DROP INDEX indexName
;
truncateTable
: TRUNCATE TABLE tableName
;
temporaryClause_
: (GLOBAL TEMPORARY)?
;
tablespaceClauseWithParen
: LP_ tablespaceClause RP_
;
tablespaceClause
: TABLESPACE ignoredIdentifier_
;
domainIndexClause
: indexTypeName
;
relationalTable
: (LP_ relationalProperties RP_)? (ON COMMIT (DELETE | PRESERVE) ROWS)?
;
relationalProperties
: relationalProperty (COMMA_ relationalProperty)*
;
relationalProperty
: columnDefinition | virtualColumnDefinition | outOfLineConstraint | outOfLineRefConstraint
;
tableProperties
: columnProperties? (AS unionSelect)?
;
unionSelect
: matchNone
;
alterTableProperties
: renameTableSpecification_ | REKEY encryptionSpec
;
renameTableSpecification_
: RENAME TO newTableName
;
newTableName
: IDENTIFIER_
;
columnClauses
: opColumnClause+ | renameColumnSpecification
;
opColumnClause
: addColumnSpecification | modifyColumnSpecification | dropColumnClause
;
addColumnSpecification
: ADD columnOrVirtualDefinitions columnProperties?
;
columnOrVirtualDefinitions
: LP_ columnOrVirtualDefinition (COMMA_ columnOrVirtualDefinition)* RP_ | columnOrVirtualDefinition
;
columnOrVirtualDefinition
: columnDefinition | virtualColumnDefinition
;
modifyColumnSpecification
: MODIFY (LP_? modifyColProperties (COMMA_ modifyColProperties)* RP_? | modifyColSubstitutable)
;
modifyColProperties
: columnName dataType? (DEFAULT expr)? (ENCRYPT encryptionSpec | DECRYPT)? inlineConstraint*
;
modifyColSubstitutable
: COLUMN columnName NOT? SUBSTITUTABLE AT ALL LEVELS FORCE?
;
dropColumnClause
: SET UNUSED columnOrColumnList cascadeOrInvalidate* | dropColumnSpecification
;
dropColumnSpecification
: DROP columnOrColumnList cascadeOrInvalidate* checkpointNumber?
;
columnOrColumnList
: COLUMN columnName | LP_ columnName (COMMA_ columnName)* RP_
;
cascadeOrInvalidate
: CASCADE CONSTRAINTS | INVALIDATE
;
checkpointNumber
: CHECKPOINT NUMBER_
;
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
constraintClauses
: addConstraintSpecification | modifyConstraintClause | renameConstraintClause | dropConstraintClause+
;
addConstraintSpecification
: ADD (outOfLineConstraint+ | outOfLineRefConstraint)
;
modifyConstraintClause
: MODIFY constraintOption constraintState+ CASCADE?
;
constraintWithName
: CONSTRAINT ignoredIdentifier_
;
constraintOption
: constraintWithName | constraintPrimaryOrUnique
;
constraintPrimaryOrUnique
: primaryKey | UNIQUE columnNames
;
renameConstraintClause
: RENAME constraintWithName TO ignoredIdentifier_
;
dropConstraintClause
: DROP
(
constraintPrimaryOrUnique CASCADE? ((KEEP | DROP) INDEX)? | (CONSTRAINT ignoredIdentifier_ CASCADE?)
)
;
alterExternalTable
: (addColumnSpecification | modifyColumnSpecification | dropColumnSpecification)+
;
columnDefinition
: columnName dataType SORT? (VISIBLE | INVISIBLE)? (DEFAULT (ON NULL)? expr | identityClause)? (ENCRYPT encryptionSpec)? (inlineConstraint+ | inlineRefConstraint)?
;
identityClause
: GENERATED (ALWAYS | BY DEFAULT (ON NULL)?) AS IDENTITY LP_? (identityOptions+)? RP_?
;
identityOptions
: START WITH (NUMBER_ | LIMIT VALUE)
| INCREMENT BY NUMBER_
| MAXVALUE NUMBER_
| NOMAXVALUE
| MINVALUE NUMBER_
| NOMINVALUE
| CYCLE
| NOCYCLE
| CACHE NUMBER_
| NOCACHE
| ORDER
| NOORDER
;
virtualColumnDefinition
: columnName dataType? (GENERATED ALWAYS)? AS LP_ expr RP_ VIRTUAL? inlineConstraint*
;
inlineConstraint
: (CONSTRAINT ignoredIdentifier_)? (NOT? NULL | UNIQUE | primaryKey | referencesClause | CHECK LP_ expr RP_) constraintState*
;
referencesClause
: REFERENCES tableName columnNames? (ON DELETE (CASCADE | SET NULL))?
;
constraintState
: notDeferrable
| initiallyClause
| RELY
| NORELY
| usingIndexClause
| ENABLE
| DISABLE
| VALIDATE
| NOVALIDATE
| exceptionsClause
;
notDeferrable
: NOT? DEFERRABLE
;
initiallyClause
: INITIALLY (IMMEDIATE | DEFERRED)
;
exceptionsClause
: EXCEPTIONS INTO
;
usingIndexClause
: USING INDEX (indexName | LP_ createIndex RP_)?
;
inlineRefConstraint
: SCOPE IS tableName | WITH ROWID | (CONSTRAINT ignoredIdentifier_)? referencesClause constraintState*
;
outOfLineConstraint
: (CONSTRAINT ignoredIdentifier_)?
(
UNIQUE columnNames
| primaryKey columnNames
| FOREIGN KEY columnNames referencesClause
| CHECK LP_ expr RP_
)
constraintState*
;
outOfLineRefConstraint
: SCOPE FOR LP_ lobItem RP_ IS tableName
| REF LP_ lobItem RP_ WITH ROWID
| (CONSTRAINT ignoredIdentifier_)? FOREIGN KEY lobItemList referencesClause constraintState*
;
encryptionSpec
: (USING STRING_)? (IDENTIFIED BY STRING_)? STRING_? (NO? SALT)?
;
objectProperties
: objectProperty (COMMA_ objectProperty)*
;
objectProperty
: (columnName | attributeName) (DEFAULT expr)? (inlineConstraint* | inlineRefConstraint?) | outOfLineConstraint | outOfLineRefConstraint
;
columnProperties
: columnProperty+
;
columnProperty
: objectTypeColProperties
;
objectTypeColProperties
: COLUMN columnName substitutableColumnClause
;
substitutableColumnClause
: ELEMENT? IS OF TYPE? LP_ ONLY? dataTypeName_ RP_ | NOT? SUBSTITUTABLE AT ALL LEVELS
;
tableIndexClause_
: tableName alias? LP_ indexExpr_ (COMMA_ indexExpr_)* RP_
;
indexExpr_
: (columnName | expr) (ASC | DESC)?
;
bitmapJoinIndexClause_
: tableName LP_ columnSortClause_ (COMMA_ columnSortClause_)* RP_ FROM tableName alias? (COMMA_ tableName alias?)* WHERE expr
;
columnSortClause_
: tableName alias? columnName (ASC | DESC)?
;
|
add temporaryClause_
|
add temporaryClause_
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
|
11d343dc9dfe2f8a2160033cb9d7afff2566a315
|
sharding-core/sharding-core-parse/sharding-core-parse-oracle/src/main/antlr4/imports/oracle/Keyword.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-oracle/src/main/antlr4/imports/oracle/Keyword.g4
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
lexer grammar Keyword;
import Alphabet;
WS
: [ \t\r\n] + ->skip
;
ALL
: A L L
;
AND
: A N D
;
ANY
: A N Y
;
ASC
: A S C
;
BETWEEN
: B E T W E E N
;
BINARY
: B I N A R Y
;
BY
: B Y
;
DATE
: D A T E
;
DESC
: D E S C
;
DISTINCT
: D I S T I N C T
;
ESCAPE
: E S C A P E
;
EXISTS
: E X I S T S
;
FALSE
: F A L S E
;
FROM
: F R O M
;
GROUP
: G R O U P
;
HAVING
: H A V I N G
;
IN
: I N
;
IS
: I S
;
KEY
: K E Y
;
LIKE
: L I K E
;
LIMIT
: L I M I T
;
MOD
: M O D
;
NOT
: N O T
;
NULL
: N U L L
;
OR
: O R
;
ORDER
: O R D E R
;
PRIMARY
: P R I M A R Y
;
REGEXP
: R E G E X P
;
ROW
: R O W
;
SET
: S E T
;
SOUNDS
: S O U N D S
;
TIME
: T I M E
;
TIMESTAMP
: T I M E S T A M P
;
TRUE
: T R U E
;
UNION
: U N I O N
;
UNKNOWN
: U N K N O W N
;
WHERE
: W H E R E
;
WITH
: W I T H
;
XOR
: X O R
;
ADD
: A D D
;
ALTER
: A L T E R
;
ALWAYS
: A L W A Y S
;
AS
: A S
;
CASCADE
: C A S C A D E
;
CHECK
: C H E C K
;
COLUMN
: C O L U M N
;
COMMIT
: C O M M I T
;
CONSTRAINT
: C O N S T R A I N T
;
CREATE
: C R E A T E
;
DAY
: D A Y
;
DEFAULT
: D E F A U L T
;
DELETE
: D E L E T E
;
DISABLE
: D I S A B L E
;
DROP
: D R O P
;
ENABLE
: E N A B L E
;
FOR
: F O R
;
FOREIGN
: F O R E I G N
;
FUNCTION
: F U N C T I O N
;
GENERATED
: G E N E R A T E D
;
GRANT
: G R A N T
;
INDEX
: I N D E X
;
NO
: N O
;
ON
: O N
;
PRIVILEGES
: P R I V I L E G E S
;
READ
: R E A D
;
REFERENCES
: R E F E R E N C E S
;
REVOKE
: R E V O K E
;
ROLE
: R O L E
;
ROLLBACK
: R O L L B A C K
;
ROWS
: R O W S
;
START
: S T A R T
;
TABLE
: T A B L E
;
TO
: T O
;
TRANSACTION
: T R A N S A C T I O N
;
TRUNCATE
: T R U N C A T E
;
UNIQUE
: U N I Q U E
;
USER
: U S E R
;
YEAR
: Y E A R
;
SELECT
: S E L E C T
;
INSERT
: I N S E R T
;
UPDATE
: U P D A T E
;
WRITE
: W R I T E
;
EXECUTE
: E X E C U T E
;
USE
: U S E
;
DEBUG
: D E B U G
;
UNDER
: U N D E R
;
FLASHBACK
: F L A S H B A C K
;
ARCHIVE
: A R C H I V E
;
REFRESH
: R E F R E S H
;
QUERY
: Q U E R Y
;
REWRITE
: R E W R I T E
;
KEEP
: K E E P
;
SEQUENCE
: S E Q U E N C E
;
INHERIT
: I N H E R I T
;
TRANSLATE
: T R A N S L A T E
;
SQL
: S Q L
;
MERGE
: M E R G E
;
VIEW
: V I E W
;
AT
: A T
;
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
;
CONNECT
: C O N N E C T
;
CONSTRAINTS
: C O N S T R A I N T S
;
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
;
DIRECTORY
: D I R E C T O R Y
;
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
;
FORCE
: F O R C E
;
GLOBAL
: G L O B A L
;
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
;
INTO
: I N T O
;
INVALIDATE
: I N V A L I D A T E
;
JAVA
: J A V A
;
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
;
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
;
OF
: O F
;
ONLY
: O N L Y
;
PRESERVE
: P R E S E R V E
;
PRIOR
: P R I O R
;
PROFILE
: P R O F I L E
;
REF
: R E F
;
REKEY
: R E K E Y
;
RELY
: R E L Y
;
RENAME
: R E N A M E
;
REPLACE
: R E P L A C E
;
RESOURCE
: R E S O U R C E
;
ROWID
: R O W I D
;
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
;
SORT
: S O R T
;
SOURCE
: S O U R C E
;
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
;
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
;
WHEN
: W H E N
;
ZONE
: Z O N E
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
lexer grammar Keyword;
import Alphabet;
WS
: [ \t\r\n] + ->skip
;
ALL
: A L L
;
AND
: A N D
;
ANY
: A N Y
;
ASC
: A S C
;
BETWEEN
: B E T W E E N
;
BINARY
: B I N A R Y
;
BY
: B Y
;
DATE
: D A T E
;
DESC
: D E S C
;
DISTINCT
: D I S T I N C T
;
ESCAPE
: E S C A P E
;
EXISTS
: E X I S T S
;
FALSE
: F A L S E
;
FROM
: F R O M
;
GROUP
: G R O U P
;
HAVING
: H A V I N G
;
IN
: I N
;
IS
: I S
;
KEY
: K E Y
;
LIKE
: L I K E
;
LIMIT
: L I M I T
;
MOD
: M O D
;
NOT
: N O T
;
NULL
: N U L L
;
OR
: O R
;
ORDER
: O R D E R
;
PRIMARY
: P R I M A R Y
;
REGEXP
: R E G E X P
;
ROW
: R O W
;
SET
: S E T
;
SOUNDS
: S O U N D S
;
TIME
: T I M E
;
TIMESTAMP
: T I M E S T A M P
;
TRUE
: T R U E
;
UNION
: U N I O N
;
UNKNOWN
: U N K N O W N
;
WHERE
: W H E R E
;
WITH
: W I T H
;
XOR
: X O R
;
ADD
: A D D
;
ALTER
: A L T E R
;
ALWAYS
: A L W A Y S
;
AS
: A S
;
CASCADE
: C A S C A D E
;
CHECK
: C H E C K
;
COLUMN
: C O L U M N
;
COMMIT
: C O M M I T
;
CONSTRAINT
: C O N S T R A I N T
;
CREATE
: C R E A T E
;
DAY
: D A Y
;
DEFAULT
: D E F A U L T
;
DELETE
: D E L E T E
;
DISABLE
: D I S A B L E
;
DROP
: D R O P
;
ENABLE
: E N A B L E
;
FOR
: F O R
;
FOREIGN
: F O R E I G N
;
FUNCTION
: F U N C T I O N
;
GENERATED
: G E N E R A T E D
;
GRANT
: G R A N T
;
INDEX
: I N D E X
;
NO
: N O
;
ON
: O N
;
PRIVILEGES
: P R I V I L E G E S
;
READ
: R E A D
;
REFERENCES
: R E F E R E N C E S
;
REVOKE
: R E V O K E
;
ROLE
: R O L E
;
ROLLBACK
: R O L L B A C K
;
ROWS
: R O W S
;
START
: S T A R T
;
TABLE
: T A B L E
;
TO
: T O
;
TRANSACTION
: T R A N S A C T I O N
;
TRUNCATE
: T R U N C A T E
;
UNIQUE
: U N I Q U E
;
USER
: U S E R
;
VISIBLE
: V I S I B L E
;
INVISIBLE
: I N V I S I B L E
;
YEAR
: Y E A R
;
SELECT
: S E L E C T
;
INSERT
: I N S E R T
;
UPDATE
: U P D A T E
;
WRITE
: W R I T E
;
EXECUTE
: E X E C U T E
;
USE
: U S E
;
DEBUG
: D E B U G
;
UNDER
: U N D E R
;
FLASHBACK
: F L A S H B A C K
;
ARCHIVE
: A R C H I V E
;
REFRESH
: R E F R E S H
;
QUERY
: Q U E R Y
;
REWRITE
: R E W R I T E
;
KEEP
: K E E P
;
SEQUENCE
: S E Q U E N C E
;
INHERIT
: I N H E R I T
;
TRANSLATE
: T R A N S L A T E
;
SQL
: S Q L
;
MERGE
: M E R G E
;
VIEW
: V I E W
;
AT
: A T
;
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
;
CONNECT
: C O N N E C T
;
CONSTRAINTS
: C O N S T R A I N T S
;
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
;
DIRECTORY
: D I R E C T O R Y
;
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
;
FORCE
: F O R C E
;
GLOBAL
: G L O B A L
;
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
;
INTO
: I N T O
;
INVALIDATE
: I N V A L I D A T E
;
JAVA
: J A V A
;
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
;
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
;
OF
: O F
;
ONLY
: O N L Y
;
PRESERVE
: P R E S E R V E
;
PRIOR
: P R I O R
;
PROFILE
: P R O F I L E
;
REF
: R E F
;
REKEY
: R E K E Y
;
RELY
: R E L Y
;
RENAME
: R E N A M E
;
REPLACE
: R E P L A C E
;
RESOURCE
: R E S O U R C E
;
ROWID
: R O W I D
;
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
;
SORT
: S O R T
;
SOURCE
: S O U R C E
;
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
;
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
;
WHEN
: W H E N
;
ZONE
: Z O N E
;
|
add VISIBLE
|
add VISIBLE
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
|
c0fb2f200d70b708227b7b01d12e6571ea3d57e8
|
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: createTableHeader createDefinitions inheritClause?
;
createIndex
: CREATE UNIQUE? INDEX CONCURRENTLY? ((IF NOT EXISTS)? indexName)? ON tableName
;
alterTable
: alterTableNameWithAsterisk (alterTableActions | renameColumnSpecification | renameConstraint) | alterTableNameExists renameTableSpecification_
;
alterIndex
: alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace
;
dropTable
: DROP TABLE (IF EXISTS)? tableName (COMMA_ tableName)*
;
dropIndex
: DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)*
;
truncateTable
: TRUNCATE TABLE? ONLY? tableNameParts
;
alterIndexName
: ALTER INDEX (IF EXISTS)? indexName
;
renameIndexSpecification
: RENAME TO indexName
;
alterIndexDependsOnExtension
: ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_
;
alterIndexSetTableSpace
: ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)?
;
tableNameParts
: tableNamePart (COMMA_ tableNamePart)*
;
tableNamePart
: tableName ASTERISK_?
;
createTableHeader
: CREATE ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? TABLE (IF NOT EXISTS)? tableName
;
createDefinitions
: LP_ (createDefinition (COMMA_ createDefinition)*)? RP_
;
createDefinition
: columnDefinition | tableConstraint | LIKE tableName likeOption*
;
likeOption
: (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL)
;
inheritClause
: INHERITS LP_ tableName (COMMA_ tableName)* RP_
;
alterTableNameWithAsterisk
: ALTER TABLE (IF EXISTS)? ONLY? tableName ASTERISK_?
;
alterTableActions
: alterTableAction (COMMA_ alterTableAction)*
;
alterTableAction
: addColumnSpecification
| dropColumnSpecification
| modifyColumnSpecification
| addConstraintSpecification
| ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam
| VALIDATE CONSTRAINT ignoredIdentifier_
| DROP CONSTRAINT (IF EXISTS)? ignoredIdentifier_ (RESTRICT | CASCADE)?
| (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)?
| ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_
| (DISABLE | ENABLE) RULE ignoredIdentifier_
| ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_
| (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY
| CLUSTER ON indexName
| SET WITHOUT CLUSTER
| SET (WITH | WITHOUT) OIDS
| SET TABLESPACE ignoredIdentifier_
| SET (LOGGED | UNLOGGED)
| SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_
| RESET LP_ storageParameter (COMMA_ storageParameter)* RP_
| INHERIT tableName
| NO INHERIT tableName
| OF dataTypeName_
| NOT OF
| OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER)
| REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING)
;
tableConstraintUsingIndex
: (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam
;
addColumnSpecification
: ADD COLUMN? (IF NOT EXISTS)? columnDefinition
;
dropColumnSpecification
: DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)?
;
modifyColumnSpecification
: alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)?
| alterColumn SET DEFAULT expr
| alterColumn DROP DEFAULT
| alterColumn (SET | DROP) NOT NULL
| alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)?
| alterColumn alterColumnSetOption alterColumnSetOption*
| alterColumn DROP IDENTITY (IF EXISTS)?
| alterColumn SET STATISTICS NUMBER_
| alterColumn SET LP_ attributeOptions RP_
| alterColumn RESET LP_ attributeOptions RP_
| alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN)
;
alterColumn
: ALTER COLUMN? columnName
;
alterColumnSetOption
: SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)?
;
attributeOptions
: attributeOption (COMMA_ attributeOption)*
;
attributeOption
: IDENTIFIER_ EQ_ simpleExpr
;
addConstraintSpecification
: ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex)
;
renameColumnSpecification
: RENAME COLUMN? columnName TO columnName
;
renameConstraint
: RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_
;
storageParameterWithValue
: storageParameter EQ_ simpleExpr
;
storageParameter
: IDENTIFIER_
;
alterTableNameExists
: ALTER TABLE (IF EXISTS)? tableName
;
renameTableSpecification_
: RENAME TO newTableName
;
newTableName
: IDENTIFIER_
;
usingIndexType
: USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN)
;
tableConstraint
: constraintClause? tableConstraintOption constraintOptionalParam
;
tableConstraintOption
: checkOption
| UNIQUE columnNames indexParameters
| primaryKey columnNames indexParameters
| FOREIGN KEY columnNames REFERENCES tableName columnNames (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? foreignKeyOnAction*
;
excludeElement
: (columnName | expr) ignoredIdentifier_? (ASC | DESC)? (NULLS (FIRST | LAST))?
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: createTableHeader createDefinitions inheritClause?
;
createIndex
: CREATE UNIQUE? INDEX CONCURRENTLY? ((IF NOT EXISTS)? indexName)? ON tableName
;
alterTable
: alterTableNameWithAsterisk (alterTableActions | renameColumnSpecification | renameConstraint) | alterTableNameExists renameTableSpecification_
;
alterIndex
: alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace
;
dropTable
: DROP TABLE (IF EXISTS)? tableName (COMMA_ tableName)*
;
dropIndex
: DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)*
;
truncateTable
: TRUNCATE TABLE? ONLY? tableNameParts
;
alterIndexName
: ALTER INDEX (IF EXISTS)? indexName
;
renameIndexSpecification
: RENAME TO indexName
;
alterIndexDependsOnExtension
: ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_
;
alterIndexSetTableSpace
: ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)?
;
tableNameParts
: tableNamePart (COMMA_ tableNamePart)*
;
tableNamePart
: tableName ASTERISK_?
;
createTableHeader
: CREATE ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? TABLE (IF NOT EXISTS)? tableName
;
createDefinitions
: LP_ (createDefinition (COMMA_ createDefinition)*)? RP_
;
createDefinition
: columnDefinition | tableConstraint | LIKE tableName likeOption*
;
likeOption
: (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL)
;
inheritClause
: INHERITS LP_ tableName (COMMA_ tableName)* RP_
;
alterTableNameWithAsterisk
: ALTER TABLE (IF EXISTS)? ONLY? tableName ASTERISK_?
;
alterTableActions
: alterTableAction (COMMA_ alterTableAction)*
;
alterTableAction
: addColumnSpecification
| dropColumnSpecification
| modifyColumnSpecification
| addConstraintSpecification
| ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam
| VALIDATE CONSTRAINT ignoredIdentifier_
| DROP CONSTRAINT (IF EXISTS)? ignoredIdentifier_ (RESTRICT | CASCADE)?
| (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)?
| ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_
| (DISABLE | ENABLE) RULE ignoredIdentifier_
| ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_
| (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY
| CLUSTER ON indexName
| SET WITHOUT CLUSTER
| SET (WITH | WITHOUT) OIDS
| SET TABLESPACE ignoredIdentifier_
| SET (LOGGED | UNLOGGED)
| SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_
| RESET LP_ storageParameter (COMMA_ storageParameter)* RP_
| INHERIT tableName
| NO INHERIT tableName
| OF dataTypeName_
| NOT OF
| OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER)
| REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING)
;
tableConstraintUsingIndex
: (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam
;
addColumnSpecification
: ADD COLUMN? (IF NOT EXISTS)? columnDefinition
;
dropColumnSpecification
: DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)?
;
modifyColumnSpecification
: alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)?
| alterColumn SET DEFAULT expr
| alterColumn DROP DEFAULT
| alterColumn (SET | DROP) NOT NULL
| alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)?
| alterColumn alterColumnSetOption alterColumnSetOption*
| alterColumn DROP IDENTITY (IF EXISTS)?
| alterColumn SET STATISTICS NUMBER_
| alterColumn SET LP_ attributeOptions RP_
| alterColumn RESET LP_ attributeOptions RP_
| alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN)
;
alterColumn
: ALTER COLUMN? columnName
;
alterColumnSetOption
: SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)?
;
attributeOptions
: attributeOption (COMMA_ attributeOption)*
;
attributeOption
: IDENTIFIER_ EQ_ simpleExpr
;
addConstraintSpecification
: ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex)
;
renameColumnSpecification
: RENAME COLUMN? columnName TO columnName
;
renameConstraint
: RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_
;
storageParameterWithValue
: storageParameter EQ_ simpleExpr
;
storageParameter
: IDENTIFIER_
;
alterTableNameExists
: ALTER TABLE (IF EXISTS)? tableName
;
renameTableSpecification_
: RENAME TO newTableName
;
newTableName
: IDENTIFIER_
;
usingIndexType
: USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN)
;
tableConstraint
: constraintClause? tableConstraintOption constraintOptionalParam
;
tableConstraintOption
: checkOption
| UNIQUE columnNames indexParameters
| primaryKey columnNames indexParameters
| EXCLUDE (USING ignoredIdentifier_)?
| FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)*
;
excludeElement
: (columnName | expr) ignoredIdentifier_? (ASC | DESC)? (NULLS (FIRST | LAST))?
;
|
modify rule for creating table
|
modify rule for creating table
|
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
|
4475b63613f46443695bbda2603c54366c006cd3
|
sharding-jdbc-ddl-parser/src/main/antlr4/imports/SQLServerKeyword.g4
|
sharding-jdbc-ddl-parser/src/main/antlr4/imports/SQLServerKeyword.g4
|
lexer grammar SQLServerKeyword;
import Symbol;
ADD: A D D;
ALL: A L L;
ALTER: A L T E R;
AND: A N D;
ANY: A N Y;
AS: A S;
ASC: A S C;
AUTHORIZATION: A U T H O R I Z A T I O N;
BACKUP: B A C K U P;
BEGIN: B E G I N;
BETWEEN: B E T W E E N;
BREAK: B R E A K;
BROWSE: B R O W S E;
BULK: B U L K;
BY: B Y;
CASCADE: C A S C A D E;
CASE: C A S E;
CHECK: C H E C K;
CHECKPOINT: C H E C K P O I N T;
CLOSE: C L O S E;
CLUSTERED: C L U S T E R E D;
COALESCE: C O A L E S C E;
COLLATE: C O L L A T E;
COLUMN: C O L U M N;
COMMIT: C O M M I T;
COMPUTE: C O M P U T E;
CONSTRAINT: C O N S T R A I N T;
CONTAINS: C O N T A I N S;
CONTAINSTABLE: C O N T A I N S T A B L E;
CONTINUE: C O N T I N U E;
CONVERT: C O N V E R T;
CREATE: C R E A T E;
CROSS: C R O S S;
CURRENT: C U R R E N T;
CURRENT_DATE: C U R R E N T UL_ D A T E;
CURRENT_TIME: C U R R E N T UL_ T I M E;
CURRENT_TIMESTAMP: C U R R E N T UL_ T I M E S T A M P;
CURRENT_USER: C U R R E N T UL_ U S E R;
CURSOR: C U R S O R;
DATABASE: D A T A B A S E;
DBCC: D B C C;
DEALLOCATE: D E A L L O C A T E;
DECLARE: D E C L A R E;
DEFAULT: D E F A U L T;
DELETE: D E L E T E;
DENY: D E N Y;
DESC: D E S C;
DISK: D I S K;
DISTINCT: D I S T I N C T;
DISTRIBUTED: D I S T R I B U T E D;
DOUBLE: D O U B L E;
DROP: D R O P;
DUMP: D U M P;
ELSE: E L S E;
END: E N D;
ERRLVL: E R R L V L;
ESCAPE: E S C A P E;
EXCEPT: E X C E P T;
EXEC: E X E C;
EXECUTE: E X E C U T E;
EXISTS: E X I S T S;
EXIT: E X I T;
EXTERNAL: E X T E R N A L;
FETCH: F E T C H;
FILE: F I L E;
FILLFACTOR: F I L L F A C T O R;
FOR: F O R;
FOREIGN: F O R E I G N;
FREETEXT: F R E E T E X T;
FREETEXTTABLE: F R E E T E X T T A B L E;
FROM: F R O M;
FULL: F U L L;
FUNCTION: F U N C T I O N;
GOTO: G O T O;
GRANT: G R A N T;
GROUP: G R O U P;
HAVING: H A V I N G;
HOLDLOCK: H O L D L O C K;
IDENTITY: I D E N T I T Y;
IDENTITYCOL: I D E N T I T Y C O L;
IDENTITY_INSERT: I D E N T I T Y UL_ I N S E R T;
IF: I F;
IN: I N;
INDEX: I N D E X;
INNER: I N N E R;
INSERT: I N S E R T;
INTERSECT: I N T E R S E C T;
INTO: I N T O;
IS: I S;
JOIN: J O I N;
KEY: K E Y;
KILL: K I L L;
LEFT: L E F T;
LIKE: L I K E;
LINENO: L I N E N O;
LOAD: L O A D;
MERGE: M E R G E;
NATIONAL: N A T I O N A L;
NOCHECK: N O C H E C K;
NONCLUSTERED: N O N C L U S T E R E D;
NOT: N O T;
NULL: N U L L;
NULLIF: N U L L I F;
OF: O F;
OFF: O F F;
OFFSETS: O F F S E T S;
ON: O N;
OPEN: O P E N;
OPENDATASOURCE: O P E N D A T A S O U R C E;
OPENQUERY: O P E N Q U E R Y;
OPENROWSET: O P E N R O W S E T;
OPENXML: O P E N X M L;
OPTION: O P T I O N;
OR: O R;
ORDER: O R D E R;
OUTER: O U T E R;
OVER: O V E R;
PERCENT: P E R C E N T;
PIVOT: P I V O T;
PLAN: P L A N;
PRECISION: P R E C I S I O N;
PRIMARY: P R I M A R Y;
PRINT: P R I N T;
PROCEDURE: P R O C E D U R E;
PUBLIC: P U B L I C;
RAISERROR: R A I S E R R O R;
READ: R E A D;
READTEXT: R E A D T E X T;
RECONFIGURE: R E C O N F I G U R E;
REFERENCES: R E F E R E N C E S;
REPLICATION: R E P L I C A T I O N;
RESTORE: R E S T O R E;
RESTRICT: R E S T R I C T;
RETURN: R E T U R N;
REVERT: R E V E R T;
REVOKE: R E V O K E;
RIGHT: R I G H T;
ROLLBACK: R O L L B A C K;
ROWCOUNT: R O W C O U N T;
ROWGUIDCOL: R O W G U I D C O L;
RULE: R U L E;
SAVE: S A V E;
SCHEMA: S C H E M A;
SECURITYAUDIT: S E C U R I T Y A U D I T;
SELECT: S E L E C T;
SEMANTICKEYPHRASETABLE: S E M A N T I C K E Y P H R A S E T A B L E;
SEMANTICSIMILARITYDETAILSTABLE: S E M A N T I C S I M I L A R I T Y D E T A I L S T A B L E;
SEMANTICSIMILARITYTABLE: S E M A N T I C S I M I L A R I T Y T A B L E;
SESSION_USER: S E S S I O N UL_ U S E R;
SET: S E T;
SETUSER: S E T U S E R;
SHUTDOWN: S H U T D O W N;
SOME: S O M E;
STATISTICS: S T A T I S T I C S;
SYSTEM_USER: S Y S T E M UL_ U S E R;
TABLE: T A B L E;
TABLESAMPLE: T A B L E S A M P L E;
TEXTSIZE: T E X T S I Z E;
THEN: T H E N;
TO: T O;
TOP: T O P;
TRAN: T R A N;
TRANSACTION: T R A N S A C T I O N;
TRIGGER: T R I G G E R;
TRUNCATE: T R U N C A T E;
TRY_CONVERT: T R Y UL_ C O N V E R T;
TSEQUAL: T S E Q U A L;
UNION: U N I O N;
UNIQUE: U N I Q U E;
UNPIVOT: U N P I V O T;
UPDATE: U P D A T E;
UPDATETEXT: U P D A T E T E X T;
USE: U S E;
USER: U S E R;
VALUES: V A L U E S;
VARYING: V A R Y I N G;
VIEW: V I E W;
WAITFOR: W A I T F O R;
WHEN: W H E N;
WHERE: W H E R E;
WHILE: W H I L E;
WITH: W I T H;
WITHIN: W I T H I N;
WRITETEXT: W R I T E T E X T;
FILETABLE:F I L E T A B L E;
ACTION: A C T I O N;
AEAD_AES_: A E A D UL_ A E S UL_;
ALGORITHM: A L G O R I T H M;
ALLOW_PAGE_LOCKS: A L L O W UL_ P A G E UL_ L O C K S;
ALLOW_ROW_LOCKS: A L L O W UL_ R O W UL_ L O C K S;
ALL_SPARSE_COLUMNS: A L L UL_ S P A R S E UL_ C O L U M N S;
ALWAYS: A L W A Y S;
BUCKET_COUNT: B U C K E T UL_ C O U N T;
CBC_HMAC_SHA_: C B C UL_ H M A C UL_ S H A UL_;
COLUMNSTORE: C O L U M N S T O R E;
COLUMNSTORE_ARCHIVE: C O L U M N S T O R E UL_ A R C H I V E;
COLUMN_ENCRYPTION_KEY: C O L U M N UL_ E N C R Y P T I O N UL_ K E Y;
COLUMN_SET: C O L U M N UL_ S E T;
COMPRESSION_DELAY: C O M P R E S S I O N UL_ D E L A Y;
CONTENT: C O N T E N T;
DATA_COMPRESSION: D A T A UL_ C O M P R E S S I O N;
DATA_CONSISTENCY_CHECK: D A T A UL_ C O N S I S T E N C Y UL_ C H E C K;
DETERMINISTIC: D E T E R M I N I S T I C;
DOCUMENT: D O C U M E N T;
DURABILITY: D U R A B I L I T Y;
ENCRYPTED: E N C R Y P T E D;
ENCRYPTION_TYPE: E N C R Y P T I O N UL_ T Y P E;
FILESTREAM: F I L E S T R E A M;
FILESTREAM_ON: F I L E S T R E A M UL_ O N;
FILETABLE_COLLATE_FILENAME: F I L E T A B L E UL_ C O L L A T E UL_ F I L E N A M E;
FILETABLE_DIRECTORY: F I L E T A B L E UL_ D I R E C T O R Y;
FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME: F I L E T A B L E UL_ F U L L P A T H UL_ U N I Q U E UL_ C O N S T R A I N T UL_ N A M E;
FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME: F I L E T A B L E UL_ P R I M A R Y UL_ K E Y UL_ C O N S T R A I N T UL_ N A M E;
FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME: F I L E T A B L E UL_ S T R E A M I D UL_ U N I Q U E UL_ C O N S T R A I N T UL_ N A M E;
FILTER_PREDICATE: F I L T E R UL_ P R E D I C A T E;
GENERATED: G E N E R A T E D;
HASH: H A S H;
HIDDEN_: H I D D E N;
HISTORY_TABLE: H I S T O R Y UL_ T A B L E;
IGNORE_DUP_KEY: I G N O R E UL_ D U P UL_ K E Y;
INBOUND: I N B O U N D;
MASKED: M A S K E D;
MEMORY_OPTIMIZED: M E M O R Y UL_ O P T I M I Z E D;
MIGRATION_STATE: M I G R A T I O N UL_ S T A T E;
NO: N O;
NONE: N O N E;
OUTBOUND: O U T B O U N D;
PAD_INDEX: P A D UL_ I N D E X;
PAGE: P A G E;
PARTITIONS: P A R T I T I O N S;
PAUSED: P A U S E D;
PERIOD: P E R I O D;
PERSISTED: P E R S I S T E D;
RANDOMIZED: R A N D O M I Z E D;
REMOTE_DATA_ARCHIVE: R E M O T E UL_ D A T A UL_ A R C H I V E;
ROW: R O W;
SCHEMA_AND_DATA: S C H E M A UL_ A N D UL_ D A T A;
SCHEMA_ONLY: S C H E M A UL_ O N L Y;
SPARSE: S P A R S E;
START: S T A R T;
STATISTICS_INCREMENTAL: S T A T I S T I C S UL_ I N C R E M E N T A L;
STATISTICS_NORECOMPUTE: S T A T I S T I C S UL_ N O R E C O M P U T E;
SYSTEM_TIME: S Y S T E M UL_ T I M E;
SYSTEM_VERSIONING: S Y S T E M UL_ V E R S I O N I N G;
TEXTIMAGE_ON: T E X T I M A G E UL_ O N;
XML: X M L;
MINUTES: M I N U T E S;
DATABASE_DEAULT: D A T A B A S E UL_ D E A U L T;
FOLLOWING: F O L L O W I N G;
PARTITION: P A R T I T I O N;
PRECEDING: P R E C E D I N G;
RANGE: R A N G E;
ROWS: R O W S;
UNBOUNDED: U N B O U N D E D;
ZONE: Z O N E;
CAST: C A S T;
MAX: M A X;
|
lexer grammar SQLServerKeyword;
import Symbol;
ADD: A D D;
ALL: A L L;
ALTER: A L T E R;
AND: A N D;
ANY: A N Y;
AS: A S;
ASC: A S C;
AUTHORIZATION: A U T H O R I Z A T I O N;
BACKUP: B A C K U P;
BEGIN: B E G I N;
BETWEEN: B E T W E E N;
BREAK: B R E A K;
BROWSE: B R O W S E;
BULK: B U L K;
BY: B Y;
CASCADE: C A S C A D E;
CASE: C A S E;
CHECK: C H E C K;
CHECKPOINT: C H E C K P O I N T;
CLOSE: C L O S E;
CLUSTERED: C L U S T E R E D;
COALESCE: C O A L E S C E;
COLLATE: C O L L A T E;
COLUMN: C O L U M N;
COMMIT: C O M M I T;
COMPUTE: C O M P U T E;
CONSTRAINT: C O N S T R A I N T;
CONTAINS: C O N T A I N S;
CONTAINSTABLE: C O N T A I N S T A B L E;
CONTINUE: C O N T I N U E;
CONVERT: C O N V E R T;
CREATE: C R E A T E;
CROSS: C R O S S;
CURRENT: C U R R E N T;
CURRENT_DATE: C U R R E N T UL_ D A T E;
CURRENT_TIME: C U R R E N T UL_ T I M E;
CURRENT_TIMESTAMP: C U R R E N T UL_ T I M E S T A M P;
CURRENT_USER: C U R R E N T UL_ U S E R;
CURSOR: C U R S O R;
DATABASE: D A T A B A S E;
DBCC: D B C C;
DEALLOCATE: D E A L L O C A T E;
DECLARE: D E C L A R E;
DEFAULT: D E F A U L T;
DELETE: D E L E T E;
DENY: D E N Y;
DESC: D E S C;
DISK: D I S K;
DISTINCT: D I S T I N C T;
DISTRIBUTED: D I S T R I B U T E D;
DOUBLE: D O U B L E;
DROP: D R O P;
DUMP: D U M P;
ELSE: E L S E;
END: E N D;
ERRLVL: E R R L V L;
ESCAPE: E S C A P E;
EXCEPT: E X C E P T;
EXEC: E X E C;
EXECUTE: E X E C U T E;
EXISTS: E X I S T S;
EXIT: E X I T;
EXTERNAL: E X T E R N A L;
FETCH: F E T C H;
FILE: F I L E;
FILLFACTOR: F I L L F A C T O R;
FOR: F O R;
FOREIGN: F O R E I G N;
FREETEXT: F R E E T E X T;
FREETEXTTABLE: F R E E T E X T T A B L E;
FROM: F R O M;
FULL: F U L L;
FUNCTION: F U N C T I O N;
GOTO: G O T O;
GRANT: G R A N T;
GROUP: G R O U P;
HAVING: H A V I N G;
HOLDLOCK: H O L D L O C K;
IDENTITY: I D E N T I T Y;
IDENTITYCOL: I D E N T I T Y C O L;
IDENTITY_INSERT: I D E N T I T Y UL_ I N S E R T;
IF: I F;
IN: I N;
INDEX: I N D E X;
INNER: I N N E R;
INSERT: I N S E R T;
INTERSECT: I N T E R S E C T;
INTO: I N T O;
IS: I S;
JOIN: J O I N;
KEY: K E Y;
KILL: K I L L;
LEFT: L E F T;
LIKE: L I K E;
LINENO: L I N E N O;
LOAD: L O A D;
MERGE: M E R G E;
NATIONAL: N A T I O N A L;
NOCHECK: N O C H E C K;
NONCLUSTERED: N O N C L U S T E R E D;
NOT: N O T;
NULL: N U L L;
NULLIF: N U L L I F;
OF: O F;
OFF: O F F;
OFFSETS: O F F S E T S;
ON: O N;
OPEN: O P E N;
OPENDATASOURCE: O P E N D A T A S O U R C E;
OPENQUERY: O P E N Q U E R Y;
OPENROWSET: O P E N R O W S E T;
OPENXML: O P E N X M L;
OPTION: O P T I O N;
OR: O R;
ORDER: O R D E R;
OUTER: O U T E R;
OVER: O V E R;
PERCENT: P E R C E N T;
PIVOT: P I V O T;
PLAN: P L A N;
PRECISION: P R E C I S I O N;
PRIMARY: P R I M A R Y;
PRINT: P R I N T;
PROCEDURE: P R O C E D U R E;
PUBLIC: P U B L I C;
RAISERROR: R A I S E R R O R;
READ: R E A D;
READTEXT: R E A D T E X T;
RECONFIGURE: R E C O N F I G U R E;
REFERENCES: R E F E R E N C E S;
REPLICATION: R E P L I C A T I O N;
RESTORE: R E S T O R E;
RESTRICT: R E S T R I C T;
RETURN: R E T U R N;
REVERT: R E V E R T;
REVOKE: R E V O K E;
RIGHT: R I G H T;
ROLLBACK: R O L L B A C K;
ROWCOUNT: R O W C O U N T;
ROWGUIDCOL: R O W G U I D C O L;
RULE: R U L E;
SAVE: S A V E;
SCHEMA: S C H E M A;
SECURITYAUDIT: S E C U R I T Y A U D I T;
SELECT: S E L E C T;
SEMANTICKEYPHRASETABLE: S E M A N T I C K E Y P H R A S E T A B L E;
SEMANTICSIMILARITYDETAILSTABLE: S E M A N T I C S I M I L A R I T Y D E T A I L S T A B L E;
SEMANTICSIMILARITYTABLE: S E M A N T I C S I M I L A R I T Y T A B L E;
SESSION_USER: S E S S I O N UL_ U S E R;
SET: S E T;
SETUSER: S E T U S E R;
SHUTDOWN: S H U T D O W N;
SOME: S O M E;
STATISTICS: S T A T I S T I C S;
SYSTEM_USER: S Y S T E M UL_ U S E R;
TABLE: T A B L E;
TABLESAMPLE: T A B L E S A M P L E;
TEXTSIZE: T E X T S I Z E;
THEN: T H E N;
TO: T O;
TOP: T O P;
TRAN: T R A N;
TRANSACTION: T R A N S A C T I O N;
TRIGGER: T R I G G E R;
TRUNCATE: T R U N C A T E;
TRY_CONVERT: T R Y UL_ C O N V E R T;
TSEQUAL: T S E Q U A L;
UNION: U N I O N;
UNIQUE: U N I Q U E;
UNPIVOT: U N P I V O T;
UPDATE: U P D A T E;
UPDATETEXT: U P D A T E T E X T;
USE: U S E;
USER: U S E R;
VALUES: V A L U E S;
VARYING: V A R Y I N G;
VIEW: V I E W;
WAITFOR: W A I T F O R;
WHEN: W H E N;
WHERE: W H E R E;
WHILE: W H I L E;
WITH: W I T H;
WITHIN: W I T H I N;
WRITETEXT: W R I T E T E X T;
FILETABLE:F I L E T A B L E;
ACTION: A C T I O N;
AEAD_AES_: A E A D UL_ A E S UL_;
ALGORITHM: A L G O R I T H M;
ALLOW_PAGE_LOCKS: A L L O W UL_ P A G E UL_ L O C K S;
ALLOW_ROW_LOCKS: A L L O W UL_ R O W UL_ L O C K S;
ALL_SPARSE_COLUMNS: A L L UL_ S P A R S E UL_ C O L U M N S;
ALWAYS: A L W A Y S;
BUCKET_COUNT: B U C K E T UL_ C O U N T;
CBC_HMAC_SHA_: C B C UL_ H M A C UL_ S H A UL_;
COLUMNSTORE: C O L U M N S T O R E;
COLUMNSTORE_ARCHIVE: C O L U M N S T O R E UL_ A R C H I V E;
COLUMN_ENCRYPTION_KEY: C O L U M N UL_ E N C R Y P T I O N UL_ K E Y;
COLUMN_SET: C O L U M N UL_ S E T;
COMPRESSION_DELAY: C O M P R E S S I O N UL_ D E L A Y;
CONTENT: C O N T E N T;
DATA_COMPRESSION: D A T A UL_ C O M P R E S S I O N;
DATA_CONSISTENCY_CHECK: D A T A UL_ C O N S I S T E N C Y UL_ C H E C K;
DETERMINISTIC: D E T E R M I N I S T I C;
DOCUMENT: D O C U M E N T;
DURABILITY: D U R A B I L I T Y;
ENCRYPTED: E N C R Y P T E D;
ENCRYPTION_TYPE: E N C R Y P T I O N UL_ T Y P E;
FILESTREAM: F I L E S T R E A M;
FILESTREAM_ON: F I L E S T R E A M UL_ O N;
FILETABLE_COLLATE_FILENAME: F I L E T A B L E UL_ C O L L A T E UL_ F I L E N A M E;
FILETABLE_DIRECTORY: F I L E T A B L E UL_ D I R E C T O R Y;
FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME: F I L E T A B L E UL_ F U L L P A T H UL_ U N I Q U E UL_ C O N S T R A I N T UL_ N A M E;
FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME: F I L E T A B L E UL_ P R I M A R Y UL_ K E Y UL_ C O N S T R A I N T UL_ N A M E;
FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME: F I L E T A B L E UL_ S T R E A M I D UL_ U N I Q U E UL_ C O N S T R A I N T UL_ N A M E;
FILTER_PREDICATE: F I L T E R UL_ P R E D I C A T E;
GENERATED: G E N E R A T E D;
HASH: H A S H;
HIDDEN_: H I D D E N;
HISTORY_TABLE: H I S T O R Y UL_ T A B L E;
IGNORE_DUP_KEY: I G N O R E UL_ D U P UL_ K E Y;
INBOUND: I N B O U N D;
MASKED: M A S K E D;
MEMORY_OPTIMIZED: M E M O R Y UL_ O P T I M I Z E D;
MIGRATION_STATE: M I G R A T I O N UL_ S T A T E;
NO: N O;
NONE: N O N E;
OUTBOUND: O U T B O U N D;
PAD_INDEX: P A D UL_ I N D E X;
PAGE: P A G E;
PARTITIONS: P A R T I T I O N S;
PAUSED: P A U S E D;
PERIOD: P E R I O D;
PERSISTED: P E R S I S T E D;
RANDOMIZED: R A N D O M I Z E D;
REMOTE_DATA_ARCHIVE: R E M O T E UL_ D A T A UL_ A R C H I V E;
ROW: R O W;
SCHEMA_AND_DATA: S C H E M A UL_ A N D UL_ D A T A;
SCHEMA_ONLY: S C H E M A UL_ O N L Y;
SPARSE: S P A R S E;
START: S T A R T;
STATISTICS_INCREMENTAL: S T A T I S T I C S UL_ I N C R E M E N T A L;
STATISTICS_NORECOMPUTE: S T A T I S T I C S UL_ N O R E C O M P U T E;
SYSTEM_TIME: S Y S T E M UL_ T I M E;
SYSTEM_VERSIONING: S Y S T E M UL_ V E R S I O N I N G;
TEXTIMAGE_ON: T E X T I M A G E UL_ O N;
XML: X M L;
MINUTES: M I N U T E S;
DATABASE_DEAULT: D A T A B A S E UL_ D E A U L T;
FOLLOWING: F O L L O W I N G;
PARTITION: P A R T I T I O N;
PRECEDING: P R E C E D I N G;
RANGE: R A N G E;
ROWS: R O W S;
UNBOUNDED: U N B O U N D E D;
ZONE: Z O N E;
CAST: C A S T;
MAX: M A X;
ABORT_AFTER_WAIT: A B O R T UL_ A F T E R UL_ W A I T;
AUTO: A U T O;
BLOCKERS: B L O C K E R S;
CHANGE_TRACKING: C H A N G E UL_ T R A C K I N G;
DAY: D A Y;
DAYS: D A Y S;
DISABLE: D I S A B L E;
ENABLE: E N A B L E;
HISTORY_RETENTION_PERIOD: H I S T O R Y UL_ R E T E N T I O N UL_ P E R I O D;
INFINITE: I N F I N I T E;
LOCK_ESCALATION: L O C K UL_ E S C A L A T I O N;
MAXDOP: M A X D O P;
MAX_DURATION: M A X UL_ D U R A T I O N;
MONTH: M O N T H;
MONTHS: M O N T H S;
MOVE: M O V E;
OFF_WITHOUT_DATA_RECOVERY: O F F UL_ W I T H O U T UL_ D A T A UL_ R E C O V E R Y;
ONLINE: O N L I N E;
REBUILD: R E B U I L D;
SELF: S E L F;
SORT_IN_TEMPDB: S O R T UL_ I N UL_ T E M P D B;
SPACE: S P A C E;
SWITCH: S W I T C H;
TRACK_COLUMNS_UPDATED: T R A C K UL_ C O L U M N S UL_ U P D A T E D;
WAIT_AT_LOW_PRIORITY: W A I T UL_ A T UL_ L O W UL_ P R I O R I T Y;
WEEK: W E E K;
WEEKS: W E E K S;
YEAR: Y E A R;
YEARS: Y E A R S;
FILETABLE_NAMESPACE: F I L E T A B L E UL_ N A M E S P A C E;
|
add sql server keyword
|
add sql server keyword
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
|
72c0bd2e7b976e2b5371ef7f46db81e525612c3a
|
sharding-jdbc-ddl-parser/src/main/antlr4/io/shardingsphere/parser/antlr/sqlserver/SQLServerDDL.g4
|
sharding-jdbc-ddl-parser/src/main/antlr4/io/shardingsphere/parser/antlr/sqlserver/SQLServerDDL.g4
|
grammar SQLServerDDL;
import SQLServerKeyword, DataType, Keyword, BaseRule,DDLBase,MySQLDQL,DQLBase,Symbol;
createTable:
createTableOpWithName
(
createMemoryTable
|createDiskTable
)
;
createTableOpWithName:
CREATE TABLE tableName
;
createDiskTable:
(AS FILETABLE)?
LEFT_PAREN
createTableDefinition (COMMA createTableDefinition)*
periodClause?
RIGHT_PAREN
(ON ( schemeName LEFT_PAREN columnName RIGHT_PAREN
| fileGroup
| STRING ) )?
(TEXTIMAGE_ON (fileGroup | STRING) )?
((FILESTREAM_ON (schemeName)
| fileGroup
| STRING) )?
(WITH LEFT_PAREN tableOption (COMMA tableOption)* RIGHT_PAREN)?
;
periodClause:
COMMA PERIOD FOR SYSTEM_TIME LEFT_PAREN systemStartTimeColumnName
COMMA systemEndTimeColumnName RIGHT_PAREN
;
systemStartTimeColumnName:
ID
;
systemEndTimeColumnName:
ID
;
schemeName:
ID
;
fileGroup:
ID
;
groupName:
ID
;
constraintName:
ID
;
keyName:
ID
;
typeName:
ID
;
xmlSchemaCollection:
ID
;
columnSetName:
ID
;
directoryName:
ID
;
createTableDefinition:
columnDefinition
| computedColumnDefinition
| columnSetDefinition
| tableConstraint
| tableIndex
;
columnDefinition:
columnName dataType
columnDefinitionOption*
(columnConstraint (COMMA columnConstraint)*)?
columnIndex?
;
columnDefinitionOption:
FILESTREAM
|(COLLATE collationName )
|SPARSE
|( MASKED WITH LEFT_PAREN FUNCTION EQ_OR_ASSIGN STRING RIGHT_PAREN )
|((CONSTRAINT constraintName)? DEFAULT expr)
|(IDENTITY (LEFT_PAREN NUMBER COMMA NUMBER RIGHT_PAREN )? )
|(NOT FOR REPLICATION)
|(GENERATED ALWAYS AS ROW (START | END) HIDDEN_? )
|(NOT? NULL)
|ROWGUIDCOL
|( ENCRYPTED WITH
LEFT_PAREN
COLUMN_ENCRYPTION_KEY EQ_OR_ASSIGN keyName COMMA
ENCRYPTION_TYPE EQ_OR_ASSIGN ( DETERMINISTIC | RANDOMIZED ) COMMA
ALGORITHM EQ_OR_ASSIGN STRING
RIGHT_PAREN
)
|(columnConstraint (COMMA columnConstraint)*)
|columnIndex
;
dataType:
typeName
(
LEFT_PAREN
(
(NUMBER ( COMMA NUMBER )?)
| MAX
|((CONTENT | DOCUMENT)? xmlSchemaCollection)
)
RIGHT_PAREN
)?
;
columnConstraint :
(CONSTRAINT constraintName )?
( primaryKeyConstraint
| columnForeignKeyConstraint
| checkConstraint
)
;
primaryKeyConstraint:
(PRIMARY KEY | UNIQUE) (CLUSTERED | NONCLUSTERED)?
primaryKeyWithClause?
primaryKeyOnClause?
;
primaryKeyWithClause:
WITH
((FILLFACTOR EQ_OR_ASSIGN NUMBER)
| (LEFT_PAREN indexOption (COMMA indexOption)* RIGHT_PAREN)
)
;
primaryKeyOnClause:
ON (
(schemeName LEFT_PAREN columnName RIGHT_PAREN)
| fileGroup
| STRING
)
;
columnForeignKeyConstraint:
(FOREIGN KEY)?
REFERENCES tableName LEFT_PAREN columnName RIGHT_PAREN
foreignKeyOnAction
;
tableForeignKeyConstraint:
(FOREIGN KEY)? columnList
REFERENCES tableName columnList
foreignKeyOnAction
;
foreignKeyOnAction:
( ON DELETE foreignKeyOn )?
( ON UPDATE foreignKeyOn )?
( NOT FOR REPLICATION )?
;
foreignKeyOn:
NO ACTION
| CASCADE
| SET NULL
| SET DEFAULT
;
checkConstraint:
CHECK(NOT FOR REPLICATION)? LEFT_PAREN expr RIGHT_PAREN
;
columnIndex:
INDEX indexName ( CLUSTERED | NONCLUSTERED )?
( WITH LEFT_PAREN indexOption (COMMA indexOption)* RIGHT_PAREN )?
( ON (
(schemeName LEFT_PAREN columnName RIGHT_PAREN)
| fileGroup
| DEFAULT
)
)?
( FILESTREAM_ON ( fileGroup | schemeName | STRING ) )?
;
computedColumnDefinition :
columnName AS expr
(PERSISTED( NOT NULL )?)?
columnConstraint?
;
columnSetDefinition :
columnSetName ID COLUMN_SET FOR ALL_SPARSE_COLUMNS
;
tableConstraint:
(CONSTRAINT constraintName )?
(
tablePrimaryConstraint
| tableForeignKeyConstraint
| checkConstraint
)
;
tablePrimaryConstraint:
primaryKeyUnique
( CLUSTERED | NONCLUSTERED )?
columnNameWithSortsWithParen
primaryKeyWithClause?
primaryKeyOnClause?
;
primaryKeyUnique:
(PRIMARY KEY)
| UNIQUE
;
columnNameWithSortsWithParen:
LEFT_PAREN columnNameWithSort (COMMA columnNameWithSort)* RIGHT_PAREN
;
columnNameWithSort:
columnName ( ASC | DESC )?
;
tableIndex:
(
(
INDEX indexName
(
((CLUSTERED | NONCLUSTERED )? columnNameWithSortsWithParen)
| (CLUSTERED COLUMNSTORE)
| (( NONCLUSTERED )? COLUMNSTORE columnList)
)
)
(WHERE expr)?
(WITH LEFT_PAREN indexOption ( COMMA indexOption)* RIGHT_PAREN)?
( ON
(
(schemeName LEFT_PAREN columnName RIGHT_PAREN)
| groupName
| DEFAULT
)
)?
( FILESTREAM_ON ( groupName | schemeName | STRING ) )?
)
;
tableOption:
(DATA_COMPRESSION EQ_OR_ASSIGN ( NONE | ROW | PAGE ) (ON PARTITIONS LEFT_PAREN partitionExpressions RIGHT_PAREN )?)
|( FILETABLE_DIRECTORY EQ_OR_ASSIGN directoryName )
|( FILETABLE_COLLATE_FILENAME EQ_OR_ASSIGN ( collationName | DATABASE_DEAULT ) )
|( FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME EQ_OR_ASSIGN constraintName )
|( FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME EQ_OR_ASSIGN constraintName )
|( FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME EQ_OR_ASSIGN constraintName )
|( SYSTEM_VERSIONING EQ_OR_ASSIGN ON ( LEFT_PAREN HISTORY_TABLE EQ_OR_ASSIGN tableName
(COMMA DATA_CONSISTENCY_CHECK EQ_OR_ASSIGN ( ON | OFF ) )? RIGHT_PAREN)? )
|(
REMOTE_DATA_ARCHIVE EQ_OR_ASSIGN
(
(ON (LEFT_PAREN tableStretchOptions (COMMA tableStretchOptions)* RIGHT_PAREN )?)
| (OFF LEFT_PAREN MIGRATION_STATE EQ_OR_ASSIGN PAUSED RIGHT_PAREN)
)
)
|tableOptOption
;
tableStretchOptions:
( FILTER_PREDICATE EQ_OR_ASSIGN ( NULL | functionCall ) COMMA )?
MIGRATION_STATE EQ_OR_ASSIGN ( OUTBOUND | INBOUND | PAUSED )
;
indexOption :
(PAD_INDEX EQ_OR_ASSIGN ( ON | OFF ) )
| (FILLFACTOR EQ_OR_ASSIGN NUMBER)
| (IGNORE_DUP_KEY EQ_OR_ASSIGN ( ON | OFF ))
| (STATISTICS_NORECOMPUTE EQ_OR_ASSIGN ( ON | OFF ))
| (STATISTICS_INCREMENTAL EQ_OR_ASSIGN ( ON | OFF ))
| (ALLOW_ROW_LOCKS EQ_OR_ASSIGN ( ON | OFF))
| (ALLOW_PAGE_LOCKS EQ_OR_ASSIGN( ON | OFF))
| (COMPRESSION_DELAY EQ_OR_ASSIGN NUMBER MINUTES?)
| (DATA_COMPRESSION EQ_OR_ASSIGN ( NONE | ROW | PAGE | COLUMNSTORE | COLUMNSTORE_ARCHIVE )
( ON PARTITIONS LEFT_PAREN partitionExpressions RIGHT_PAREN )?)
;
partitionExpressions:
partitionExpression (COMMA partitionExpression)*
;
partitionExpression:
NUMBER
|partitionRange
;
partitionRange:
NUMBER TO NUMBER
;
createMemoryTable:
LEFT_PAREN
columnOption (COMMA columnOption)*
periodClause?
RIGHT_PAREN
(WITH LEFT_PAREN tableOptOption ( COMMA tableOptOption)* RIGHT_PAREN)?
;
columnOption:
columnOptDefinition
| (tableOptConstraint (COMMA tableOptConstraint)*)?
| tableIndex?
;
columnOptDefinition :
columnName dataType
columnOptDefinitionOpt*
;
columnOptDefinitionOpt:
(COLLATE collationName )
| (GENERATED ALWAYS AS ROW (START | END) HIDDEN_? )
| (NOT? NULL)
| ((CONSTRAINT constraintName )? DEFAULT expr )
| ( IDENTITY ( LEFT_PAREN NUMBER COMMA NUMBER RIGHT_PAREN ) )
| columnOptConstraint
| columnOptIndex
;
columnOptConstraint :
(CONSTRAINT constraintName )?
(
primaryKeyOptConstaint
| foreignKeyOptConstaint
| (CHECK LEFT_PAREN expr RIGHT_PAREN)
)
;
primaryKeyOptConstaint:
primaryKeyUnique
(
(NONCLUSTERED columnNameWithSortsWithParen)
| (NONCLUSTERED HASH WITH LEFT_PAREN BUCKET_COUNT EQ_OR_ASSIGN NUMBER RIGHT_PAREN)
)
;
foreignKeyOptConstaint:
(FOREIGN KEY )? REFERENCES tableName ( LEFT_PAREN columnName RIGHT_PAREN )?
;
tableOptConstraint:
( CONSTRAINT constraintName )?
(
(primaryKeyUnique
(
(NONCLUSTERED columnNameWithSortsWithParen)
| (NONCLUSTERED HASH columnList WITH LEFT_PAREN BUCKET_COUNT EQ_OR_ASSIGN NUMBER RIGHT_PAREN)
))
| (FOREIGN KEY columnList REFERENCES tableName columnList? )
| (CHECK LEFT_PAREN expr RIGHT_PAREN )
)
;
columnOptIndex:
INDEX indexName
(NONCLUSTERED? (HASH WITH LEFT_PAREN BUCKET_COUNT EQ_OR_ASSIGN NUMBER RIGHT_PAREN)? )
;
tableOptIndex :
INDEX indexName
(
( NONCLUSTERED ? HASH columnList WITH LEFT_PAREN BUCKET_COUNT EQ_OR_ASSIGN NUMBER RIGHT_PAREN )
| ( NONCLUSTERED ? columnNameWithSortsWithParen ( ON groupName | DEFAULT )? )
| (CLUSTERED COLUMNSTORE (WITH LEFT_PAREN COMPRESSION_DELAY EQ_OR_ASSIGN (NUMBER MINUTES?) RIGHT_PAREN)? ( ON groupName | DEFAULT )?)
)
;
tableOptOption :
(MEMORY_OPTIMIZED EQ_OR_ASSIGN ON)
| (DURABILITY EQ_OR_ASSIGN (SCHEMA_ONLY | SCHEMA_AND_DATA))
| (SYSTEM_VERSIONING EQ_OR_ASSIGN ON ( LEFT_PAREN HISTORY_TABLE EQ_OR_ASSIGN tableName
(COMMA DATA_CONSISTENCY_CHECK EQ_OR_ASSIGN ( ON | OFF ) )? RIGHT_PAREN )?)
;
privateExprOfDb:
windowedFunction
|atTimeZoneExpr
|castExpr
|convertExpr
;
atTimeZoneExpr:
ID (WITH TIME ZONE)? STRING
;
castExpr:
CAST LEFT_PAREN expr AS dataType (LEFT_PAREN NUMBER RIGHT_PAREN )? RIGHT_PAREN
;
convertExpr:
CONVERT ( dataType (LEFT_PAREN NUMBER RIGHT_PAREN )? COMMA expr (COMMA NUMBER)?)
;
windowedFunction:
functionCall overClause
;
overClause:
OVER
LEFT_PAREN
partitionByClause?
orderByClause?
rowRangeClause?
RIGHT_PAREN
;
partitionByClause:
PARTITION BY expr (COMMA expr)*
;
orderByClause:
ORDER BY orderByExpr (COMMA orderByExpr)*
;
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
;
|
grammar SQLServerDDL;
import SQLServerKeyword, DataType, Keyword, BaseRule,DDLBase,MySQLDQL,DQLBase,Symbol;
createTable:
createTableOpWithName
(
createMemoryTable
|createDiskTable
)
;
createTableOpWithName:
CREATE TABLE tableName
;
createDiskTable:
(AS FILETABLE)?
LEFT_PAREN
createTableDefinition (COMMA createTableDefinition)*
periodClause?
RIGHT_PAREN
(ON ( schemaName LEFT_PAREN columnName RIGHT_PAREN
| fileGroup
| STRING ) )?
(TEXTIMAGE_ON (fileGroup | STRING) )?
((FILESTREAM_ON (schemaName)
| fileGroup
| STRING) )?
(WITH LEFT_PAREN tableOption (COMMA tableOption)* RIGHT_PAREN)?
;
periodClause:
PERIOD FOR SYSTEM_TIME LEFT_PAREN columnName
COMMA columnName RIGHT_PAREN
;
createTableDefinition:
columnDefinition
| computedColumnDefinition
| columnSetDefinition
| tableConstraint
| tableIndex
;
columnDefinition:
columnName dataType
columnDefinitionOption*
(columnConstraint (COMMA columnConstraint)*)?
columnIndex?
;
columnDefinitionOption:
FILESTREAM
|(COLLATE collationName )
|SPARSE
|( MASKED WITH LEFT_PAREN FUNCTION EQ_OR_ASSIGN STRING RIGHT_PAREN )
|((CONSTRAINT constraintName)? DEFAULT expr)
|(IDENTITY (LEFT_PAREN NUMBER COMMA NUMBER RIGHT_PAREN )? )
|(NOT FOR REPLICATION)
|(GENERATED ALWAYS AS ROW (START | END) HIDDEN_? )
|(NOT? NULL)
|ROWGUIDCOL
|( ENCRYPTED WITH
LEFT_PAREN
COLUMN_ENCRYPTION_KEY EQ_OR_ASSIGN keyName COMMA
ENCRYPTION_TYPE EQ_OR_ASSIGN ( DETERMINISTIC | RANDOMIZED ) COMMA
ALGORITHM EQ_OR_ASSIGN STRING
RIGHT_PAREN
)
|(columnConstraint (COMMA columnConstraint)*)
|columnIndex
;
dataType:
typeName
(
LEFT_PAREN
(
(NUMBER ( COMMA NUMBER )?)
| MAX
|((CONTENT | DOCUMENT)? xmlSchemaCollection)
)
RIGHT_PAREN
)?
;
columnConstraint :
(CONSTRAINT constraintName )?
( primaryKeyConstraint
| columnForeignKeyConstraint
| checkConstraint
)
;
primaryKeyConstraint:
(PRIMARY KEY | UNIQUE) (CLUSTERED | NONCLUSTERED)?
primaryKeyWithClause?
primaryKeyOnClause?
;
primaryKeyWithClause:
WITH
((FILLFACTOR EQ_OR_ASSIGN NUMBER)
| (LEFT_PAREN indexOption (COMMA indexOption)* RIGHT_PAREN)
)
;
primaryKeyOnClause:
ON (
(schemaName LEFT_PAREN columnName RIGHT_PAREN)
| fileGroup
| STRING
)
;
columnForeignKeyConstraint:
(FOREIGN KEY)?
REFERENCES tableName LEFT_PAREN columnName RIGHT_PAREN
foreignKeyOnAction
;
tableForeignKeyConstraint:
(FOREIGN KEY)? columnList
REFERENCES tableName columnList
foreignKeyOnAction
;
foreignKeyOnAction:
( ON DELETE foreignKeyOn )?
( ON UPDATE foreignKeyOn )?
( NOT FOR REPLICATION )?
;
foreignKeyOn:
NO ACTION
| CASCADE
| SET NULL
| SET DEFAULT
;
checkConstraint:
CHECK(NOT FOR REPLICATION)? LEFT_PAREN expr RIGHT_PAREN
;
columnIndex:
INDEX indexName ( CLUSTERED | NONCLUSTERED )?
( WITH LEFT_PAREN indexOption (COMMA indexOption)* RIGHT_PAREN )?
( ON (
(schemaName LEFT_PAREN columnName RIGHT_PAREN)
| fileGroup
| DEFAULT
)
)?
( FILESTREAM_ON ( fileGroup | schemaName | STRING ) )?
;
computedColumnDefinition :
columnName AS expr
(PERSISTED( NOT NULL )?)?
columnConstraint?
;
columnSetDefinition :
columnSetName ID COLUMN_SET FOR ALL_SPARSE_COLUMNS
;
tableConstraint:
(CONSTRAINT constraintName )?
(
tablePrimaryConstraint
| tableForeignKeyConstraint
| checkConstraint
)
;
tablePrimaryConstraint:
primaryKeyUnique
( CLUSTERED | NONCLUSTERED )?
columnNameWithSortsWithParen
primaryKeyWithClause?
primaryKeyOnClause?
;
primaryKeyUnique:
(PRIMARY KEY)
| UNIQUE
;
columnNameWithSortsWithParen:
LEFT_PAREN columnNameWithSort (COMMA columnNameWithSort)* RIGHT_PAREN
;
columnNameWithSort:
columnName ( ASC | DESC )?
;
tableIndex:
(
(
INDEX indexName
(
((CLUSTERED | NONCLUSTERED )? columnNameWithSortsWithParen)
| (CLUSTERED COLUMNSTORE)
| (( NONCLUSTERED )? COLUMNSTORE columnList)
)
)
(WHERE expr)?
(WITH LEFT_PAREN indexOption ( COMMA indexOption)* RIGHT_PAREN)?
( ON
(
(schemaName LEFT_PAREN columnName RIGHT_PAREN)
| groupName
| DEFAULT
)
)?
( FILESTREAM_ON ( groupName | schemaName | STRING ) )?
)
;
tableOption:
(DATA_COMPRESSION EQ_OR_ASSIGN ( NONE | ROW | PAGE ) (ON PARTITIONS LEFT_PAREN partitionExpressions RIGHT_PAREN )?)
|( FILETABLE_DIRECTORY EQ_OR_ASSIGN directoryName )
|( FILETABLE_COLLATE_FILENAME EQ_OR_ASSIGN ( collationName | DATABASE_DEAULT ) )
|( FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME EQ_OR_ASSIGN constraintName )
|( FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME EQ_OR_ASSIGN constraintName )
|( FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME EQ_OR_ASSIGN constraintName )
|( SYSTEM_VERSIONING EQ_OR_ASSIGN ON ( LEFT_PAREN HISTORY_TABLE EQ_OR_ASSIGN tableName
(COMMA DATA_CONSISTENCY_CHECK EQ_OR_ASSIGN ( ON | OFF ) )? RIGHT_PAREN)? )
|(
REMOTE_DATA_ARCHIVE EQ_OR_ASSIGN
(
(ON (LEFT_PAREN tableStretchOptions (COMMA tableStretchOptions)* RIGHT_PAREN )?)
| (OFF LEFT_PAREN MIGRATION_STATE EQ_OR_ASSIGN PAUSED RIGHT_PAREN)
)
)
|tableOptOption
;
tableStretchOptions:
( FILTER_PREDICATE EQ_OR_ASSIGN ( NULL | functionCall ) COMMA )?
MIGRATION_STATE EQ_OR_ASSIGN ( OUTBOUND | INBOUND | PAUSED )
;
indexOption :
(PAD_INDEX EQ_OR_ASSIGN ( ON | OFF ) )
| (FILLFACTOR EQ_OR_ASSIGN NUMBER)
| (IGNORE_DUP_KEY EQ_OR_ASSIGN ( ON | OFF ))
| (STATISTICS_NORECOMPUTE EQ_OR_ASSIGN ( ON | OFF ))
| (STATISTICS_INCREMENTAL EQ_OR_ASSIGN ( ON | OFF ))
| (ALLOW_ROW_LOCKS EQ_OR_ASSIGN ( ON | OFF))
| (ALLOW_PAGE_LOCKS EQ_OR_ASSIGN( ON | OFF))
| (COMPRESSION_DELAY EQ_OR_ASSIGN NUMBER MINUTES?)
| (DATA_COMPRESSION EQ_OR_ASSIGN ( NONE | ROW | PAGE | COLUMNSTORE | COLUMNSTORE_ARCHIVE )
( ON PARTITIONS LEFT_PAREN partitionExpressions RIGHT_PAREN )?)
;
partitionExpressions:
partitionExpression (COMMA partitionExpression)*
;
partitionExpression:
NUMBER
|partitionRange
;
partitionRange:
NUMBER TO NUMBER
;
createMemoryTable:
LEFT_PAREN
columnOption (COMMA columnOption)*
(COMMA periodClause)?
RIGHT_PAREN
(WITH LEFT_PAREN tableOptOption ( COMMA tableOptOption)* RIGHT_PAREN)?
;
columnOption:
columnOptDefinition
| (tableOptConstraint (COMMA tableOptConstraint)*)?
| tableIndex?
;
columnOptDefinition :
columnName dataType
columnOptDefinitionOpt*
;
columnOptDefinitionOpt:
(COLLATE collationName )
| (GENERATED ALWAYS AS ROW (START | END) HIDDEN_? )
| (NOT? NULL)
| ((CONSTRAINT constraintName )? DEFAULT expr )
| ( IDENTITY ( LEFT_PAREN NUMBER COMMA NUMBER RIGHT_PAREN ) )
| columnOptConstraint
| columnOptIndex
;
columnOptConstraint :
(CONSTRAINT constraintName )?
(
primaryKeyOptConstaint
| foreignKeyOptConstaint
| (CHECK LEFT_PAREN expr RIGHT_PAREN)
)
;
primaryKeyOptConstaint:
primaryKeyUnique
(
(NONCLUSTERED columnNameWithSortsWithParen)
| (NONCLUSTERED HASH WITH LEFT_PAREN BUCKET_COUNT EQ_OR_ASSIGN NUMBER RIGHT_PAREN)
)
;
foreignKeyOptConstaint:
(FOREIGN KEY )? REFERENCES tableName ( LEFT_PAREN columnName RIGHT_PAREN )?
;
tableOptConstraint:
( CONSTRAINT constraintName )?
(
(primaryKeyUnique
(
(NONCLUSTERED columnNameWithSortsWithParen)
| (NONCLUSTERED HASH columnList WITH LEFT_PAREN BUCKET_COUNT EQ_OR_ASSIGN NUMBER RIGHT_PAREN)
))
| (FOREIGN KEY columnList REFERENCES tableName columnList? )
| (CHECK LEFT_PAREN expr RIGHT_PAREN )
)
;
columnOptIndex:
INDEX indexName
(NONCLUSTERED? (HASH WITH LEFT_PAREN BUCKET_COUNT EQ_OR_ASSIGN NUMBER RIGHT_PAREN)? )
;
tableOptIndex :
INDEX indexName
(
( NONCLUSTERED ? HASH columnList WITH LEFT_PAREN BUCKET_COUNT EQ_OR_ASSIGN NUMBER RIGHT_PAREN )
| ( NONCLUSTERED ? columnNameWithSortsWithParen ( ON groupName | DEFAULT )? )
| (CLUSTERED COLUMNSTORE (WITH LEFT_PAREN COMPRESSION_DELAY EQ_OR_ASSIGN (NUMBER MINUTES?) RIGHT_PAREN)? ( ON groupName | DEFAULT )?)
)
;
tableOptOption :
(MEMORY_OPTIMIZED EQ_OR_ASSIGN ON)
| (DURABILITY EQ_OR_ASSIGN (SCHEMA_ONLY | SCHEMA_AND_DATA))
| (SYSTEM_VERSIONING EQ_OR_ASSIGN ON ( LEFT_PAREN HISTORY_TABLE EQ_OR_ASSIGN tableName
(COMMA DATA_CONSISTENCY_CHECK EQ_OR_ASSIGN ( ON | OFF ) )? RIGHT_PAREN )?)
;
privateExprOfDb:
windowedFunction
|atTimeZoneExpr
|castExpr
|convertExpr
;
atTimeZoneExpr:
ID (WITH TIME ZONE)? STRING
;
castExpr:
CAST LEFT_PAREN expr AS dataType (LEFT_PAREN NUMBER RIGHT_PAREN )? RIGHT_PAREN
;
convertExpr:
CONVERT ( dataType (LEFT_PAREN NUMBER RIGHT_PAREN )? COMMA expr (COMMA NUMBER)?)
;
windowedFunction:
functionCall overClause
;
overClause:
OVER
LEFT_PAREN
partitionByClause?
orderByClause?
rowRangeClause?
RIGHT_PAREN
;
partitionByClause:
PARTITION BY expr (COMMA expr)*
;
orderByClause:
ORDER BY orderByExpr (COMMA orderByExpr)*
;
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
;
alterTable:
alterTableOp
(alterColumn
|addColumn
|alterDrop
|alterCheckConstraint
|alterTrigger
|alterTracking
|alterSwitch
|alterSet
|alterRebuild
|fileTableOption
|stretchConfiguration)
;
alterTableOp:
ALTER TABLE tableName
;
alterColumn:
ALTER COLUMN columnName
(
dataType
(
(COLLATE collationName)
|( NULL | NOT NULL )
|( SPARSE )
)*
| ((ADD | DROP) ( ROWGUIDCOL | PERSISTED | NOT FOR REPLICATION | SPARSE | HIDDEN_))
| ((ADD | DROP) MASKED (WITH LEFT_PAREN FUNCTION EQ_OR_ASSIGN STRING RIGHT_PAREN )?)
)
(WITH LEFT_PAREN ONLINE EQ_OR_ASSIGN ON | OFF RIGHT_PAREN)?
;
alterIndex:
ALTER INDEX indexName
typeName REBUILD
(NONCLUSTERED? WITH LEFT_PAREN BUCKET_COUNT EQ_OR_ASSIGN NUMBER RIGHT_PAREN)?
;
addColumn:
(WITH (CHECK | NOCHECK))?
ADD
(
(alterColumnAddOption (COMMA alterColumnAddOption)*)
|(
(columnNameGeneratedClause COMMA periodClause)
|(periodClause COMMA columnNameGeneratedClause)
)
)
;
alterColumnAddOption:
columnDefinition
| computedColumnDefinition
| tableConstraint
| columnSetDefinition
| columnIndex
;
columnNameGeneratedClause:
columnNameGenerated
DEFAULT simpleExpr (WITH VALUES)? COMMA
columnNameGenerated
;
columnNameGenerated:
columnName typeName GENERATED ALWAYS AS ROW START
HIDDEN_? (NOT NULL)? (CONSTRAINT constraintName)?
;
alterDrop:
DROP
(
alterTableDropConstraint
|alterTableDropColumn
|(PERIOD FOR SYSTEM_TIME)
)
;
alterTableDropConstraint:
CONSTRAINT? (IF EXISTS)?
dropConstraintName (COMMA dropConstraintName)
;
dropConstraintName:
constraintName dropConstraintWithClause?
;
dropConstraintWithClause:
WITH LEFT_PAREN dropConstraintOption ( COMMA dropConstraintOption)* RIGHT_PAREN
;
alterTableDropColumn:
COLUMN (IF EXISTS)?
columnName (COMMA columnName)*
;
dropConstraintOption:
(
(MAXDOP EQ_OR_ASSIGN NUMBER )
| (ONLINE EQ_OR_ASSIGN ( ON | OFF ))
| (MOVE TO
( schemaName LEFT_PAREN columnName RIGHT_PAREN | fileGroup | STRING ) )
)
;
alterTableOption:
SET LEFT_PAREN LOCK_ESCALATION EQ_OR_ASSIGN (AUTO | TABLE | DISABLE) RIGHT_PAREN
;
alterCheckConstraint:
WITH? (CHECK | NOCHECK) CONSTRAINT
(ALL | (constraintName (COMMA constraintName)*))
;
alterTrigger:
(ENABLE| DISABLE) TRIGGER
(ALL | (triggerName ( COMMA triggerName)*))
;
alterTracking:
(ENABLE | DISABLE) CHANGE_TRACKING
(WITH LEFT_PAREN TRACK_COLUMNS_UPDATED EQ_OR_ASSIGN (ON | OFF) RIGHT_PAREN )?
;
alterSwitch:
SWITCH ( PARTITION expr )?
TO tableName
( PARTITION expr)?
( WITH LEFT_PAREN lowPriorityLockWait RIGHT_PAREN )?
;
alterSet:
SET
LEFT_PAREN
( FILESTREAM_ON EQ_OR_ASSIGN
( schemaName | fileGroup | STRING ) )
| (SYSTEM_VERSIONING EQ_OR_ASSIGN
(
OFF
|alterSetOnClause
)
)
RIGHT_PAREN
;
alterSetOnClause:
ON
(LEFT_PAREN
HISTORY_TABLE EQ_OR_ASSIGN tableName
(COMMA DATA_CONSISTENCY_CHECK EQ_OR_ASSIGN ( ON | OFF ) )?
(COMMA HISTORY_RETENTION_PERIOD EQ_OR_ASSIGN
(
INFINITE | NUMBER (DAY | DAYS | WEEK | WEEKS | MONTH | MONTHS | YEAR | YEARS )
)
)?
RIGHT_PAREN
)?
;
alterRebuild:
REBUILD
(
((PARTITION EQ_OR_ASSIGN ALL)? ( WITH LEFT_PAREN rebuildOption ( COMMA rebuildOption)* RIGHT_PAREN ))
| ( PARTITION EQ_OR_ASSIGN numberRange (WITH LEFT_PAREN singlePartitionRebuildOption (COMMA singlePartitionRebuildOption)* RIGHT_PAREN )?)
)
;
fileTableOption :
((ENABLE | DISABLE) FILETABLE_NAMESPACE)
|(SET LEFT_PAREN FILETABLE_DIRECTORY EQ_OR_ASSIGN directoryName RIGHT_PAREN )
;
stretchConfiguration :
SET
LEFT_PAREN
REMOTE_DATA_ARCHIVE
(
(EQ_OR_ASSIGN ON LEFT_PAREN tableStretchOptions RIGHT_PAREN)
| (EQ_OR_ASSIGN OFF_WITHOUT_DATA_RECOVERY LEFT_PAREN MIGRATION_STATE EQ_OR_ASSIGN PAUSED RIGHT_PAREN)
| (LEFT_PAREN tableStretchOptions (COMMA )? RIGHT_PAREN)
)
RIGHT_PAREN
;
singlePartitionRebuildOption :
(SORT_IN_TEMPDB EQ_OR_ASSIGN ( ON | OFF ))
| (MAXDOP EQ_OR_ASSIGN NUMBER)
| (DATA_COMPRESSION EQ_OR_ASSIGN ( NONE | ROW | PAGE | COLUMNSTORE | COLUMNSTORE_ARCHIVE))
| (ONLINE EQ_OR_ASSIGN ( ON (LEFT_PAREN lowPriorityLockWait RIGHT_PAREN )?| OFF))
;
lowPriorityLockWait:
WAIT_AT_LOW_PRIORITY LEFT_PAREN MAX_DURATION EQ_OR_ASSIGN NUMBER ( MINUTES )? COMMA
ABORT_AFTER_WAIT EQ_OR_ASSIGN ( NONE | SELF | BLOCKERS ) RIGHT_PAREN
;
rebuildOption:
DATA_COMPRESSION EQ_OR_ASSIGN (COLUMNSTORE | COLUMNSTORE_ARCHIVE )
(ON PARTITIONS LEFT_PAREN numberRange (COMMA numberRange)* RIGHT_PAREN)
;
numberRange:
NUMBER (TO NUMBER)?
;
|
add sqlserver alter table
|
add sqlserver alter table
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
|
9fc370b67187a06602ff5f95951f5f4466db629f
|
parser/src/main/antlr/AdlVocabulary.g4
|
parser/src/main/antlr/AdlVocabulary.g4
|
//
// description: Antlr4 lexer grammar for keywords of Archetype Definition Language (ADL2)
// author: Thomas Beale <[email protected]>
// support: openEHR Specifications PR tracker <https://openehr.atlassian.net/projects/SPECPR/issues>
// copyright: Copyright (c) 2015 openEHR Foundation
// license: Apache 2.0 License <http://www.apache.org/licenses/LICENSE-2.0.html>
//
lexer grammar AdlVocabulary;
MATCHES_REGEXP : SYM_MATCHES WS? '{' WS? REGEXP WS? '}' ;
fragment REGEXP : '/' SLASH_REGEXP_CHAR* '/' | '^' REGEXP_CHAR* '^';
fragment REGEXP_CHAR : ~('\\'|[^\n\r]) | REGEXP_ESCAPE_SEQ | UTF8CHAR ;
fragment REGEXP_ESCAPE_SEQ : '\\' [?abfnrtv\\^] ;
fragment SLASH_REGEXP_CHAR : ~[/\n\r] ;
// ~('\\'|[/\n\r]) | SLASH_REGEXP_ESCAPE_SEQ | UTF8CHAR ;
fragment SLASH_REGEXP_ESCAPE_SEQ : '\\' [?abfnrtv\/\\] ;
// TODO: should these be matched in the lexer, or should we just match any identifier and do things in parser rules?
ROOT_ID_CODE : 'id1' ('.1')* ;
ID_CODE : 'id' CODE_STR ;
AT_CODE : 'at' CODE_STR ;
AC_CODE : 'ac' CODE_STR ;
fragment CODE_STR : ('0' | [1-9][0-9]*) ( '.' ('0' | [1-9][0-9]* ))* ;
// ADL keywords
SYM_ARCHETYPE : [Aa][Rr][Cc][Hh][Ee][Tt][Yy][Pp][Ee] ;
SYM_TEMPLATE_OVERLAY : [Tt][Ee][Mm][Pp][Ll][Aa][Tt][Ee]'_'[Oo][Vv][Ee][Rr][Ll][Aa][Yy] ;
SYM_TEMPLATE : [Tt][Ee][Mm][Pp][Ll][Aa][Tt][Ee] ;
SYM_OPERATIONAL_TEMPLATE : [Oo][Pp][Ee][Rr][Aa][Tt][Ii][Oo][Nn][Aa][Ll]'_'[Tt][Ee][Mm][Pp][Ll][Aa][Tt][Ee] ;
SYM_SPECIALIZE : '\n'[Ss][Pp][Ee][Cc][Ii][Aa][Ll][Ii][SsZz][Ee] ;
SYM_LANGUAGE : '\n'[Ll][Aa][Nn][Gg][Uu][Aa][Gg][Ee] ;
SYM_DESCRIPTION : '\n'[Dd][Ee][Ss][Cc][Rr][Ii][Pp][Tt][Ii][Oo][Nn] ;
SYM_DEFINITION : '\n'[Dd][Ee][Ff][Ii][Nn][Ii][Tt][Ii][Oo][Nn] ;
SYM_RULES : '\n'[Rr][Uu][Ll][Ee][Ss] ;
SYM_TERMINOLOGY : '\n'[Tt][Ee][Rr][Mm][Ii][Nn][Oo][Ll][Oo][Gg][Yy] ;
SYM_ANNOTATIONS : '\n'[Aa][Nn][Nn][Oo][Tt][Aa][Tt][Ii][Oo][Nn][Ss] ;
SYM_COMPONENT_TERMINOLOGIES : '\n'[Cc][Oo][Mm][Pp][Oo][Nn][Ee][Nn][Tt]'_'[Tt][Ee][Rr][Mm][Ii][Nn][Oo][Ll][Oo][Gg][Ii][Ee][Ss] ;
// meta-data keywords
SYM_ADL_VERSION : [Aa][Dd][Ll]'_'[Vv][Ee][Rr][Ss][Ii][Oo][Nn] ;
SYM_RM_RELEASE : [Rr][Mm]'_'[Rr][Ee][Ll][Ee][Aa][Ss][Ee] ;
SYM_IS_CONTROLLED : [Cc][Oo][Nn][Nn][Tt][Rr][Oo][Ll][Ll][Ee][Dd] ;
SYM_IS_GENERATED : [Gg][Ee][Nn][Ee][Rr][Aa][Tt][Ee][Dd] ;
SYM_UID : [Uu][Ii][Dd] ;
SYM_BUILD_UID : [Bb][Uu][Ii][Ll][Dd]'_'[Uu][Ii][Dd] ;
// CADL keywords
SYM_EXISTENCE : [Ee][Xx][Ii][Ss][Tt][Ee][Nn][Cc][Ee] ;
SYM_OCCURRENCES : [Oo][Cc][Cc][Uu][Rr][Rr][Ee][Nn][Cc][Ee][Ss] ;
SYM_CARDINALITY : [Cc][Aa][Rr][Dd][Ii][Nn][Aa][Ll][Ii][Tt][Yy] ;
SYM_ORDERED : [Oo][Rr][Dd][Ee][Rr][Ee][Dd] ;
SYM_UNORDERED : [Uu][Nn][Oo][Rr][Dd][Ee][Rr][Ee][Dd] ;
SYM_UNIQUE : [Uu][Nn][Ii][Qq][Uu][Ee] ;
SYM_USE_NODE : [Uu][Ss][Ee][_][Nn][Oo][Dd][Ee] ;
SYM_USE_ARCHETYPE : [Uu][Ss][Ee][_][Aa][Rr][Cc][Hh][Ee][Tt][Yy][Pp][Ee] ;
SYM_ALLOW_ARCHETYPE : [Aa][Ll][Ll][Oo][Ww][_][Aa][Rr][Cc][Hh][Ee][Tt][Yy][Pp][Ee] ;
SYM_INCLUDE : [Ii][Nn][Cc][Ll][Uu][Dd][Ee] ;
SYM_EXCLUDE : [Ee][Xx][Cc][Ll][Uu][Dd][Ee] ;
SYM_AFTER : [Aa][Ff][Tt][Ee][Rr] ;
SYM_BEFORE : [Bb][Ee][Ff][Oo][Rr][Ee] ;
SYM_CLOSED : [Cc][Ll][Oo][Ss][Ee][Dd] ;
SYM_THEN : [Tt][Hh][Ee][Nn] ;
SYM_AND : [Aa][Nn][Dd] ;
SYM_OR : [Oo][Rr] ;
SYM_XOR : [Xx][Oo][Rr] ;
SYM_NOT : [Nn][Oo][Tt] ;
SYM_IMPLIES : [Ii][Mm][Pp][Ll][Ii][Ee][Ss] ;
SYM_FOR_ALL : [Ff][Oo][Rr][_][Aa][Ll][Ll] ;
SYM_EXISTS : [Ee][Xx][Ii][Ss][Tt][Ss] ;
SYM_MATCHES : ([Mm][Aa][Tt][Cc][Hh][Ee][Ss] | [Ii][Ss]'_'[Ii][Nn] | '\u2208');
// ---------- whitespace & comments ----------
WS : [ \t\r]+ -> skip ;
LINE : '\n' -> skip ; // increment line count
HLINE : '--------------------*' ; // special comment line used as a horizontal separator
CMT_LINE : '--'.*?'\n' -> skip ; // (increment line count)
// ---------- ISO8601 Date/Time values ----------
ISO8601_DATE : YEAR '-' MONTH ( '-' DAY )? ;
ISO8601_TIME : HOUR ':' MINUTE ( ':' SECOND ( ',' INTEGER )?)? ( TIMEZONE )? ;
ISO8601_DATE_TIME : YEAR '-' MONTH '-' DAY 'T' HOUR (':' MINUTE (':' SECOND ( ',' DIGIT+ )?)?)? ( TIMEZONE )? ;
fragment TIMEZONE : 'Z' | ('+'|'-') HOUR_MIN ; // hour offset, e.g. `+0930`, or else literal `Z` indicating +0000.
fragment YEAR : [1-9][0-9]* ;
fragment MONTH : ( [0][0-9] | [1][0-2] ) ; // month in year
fragment DAY : ( [012][0-9] | [3][0-2] ) ; // day in month
fragment HOUR : ( [01]?[0-9] | [2][0-3] ) ; // hour in 24 hour clock
fragment MINUTE : [0-5][0-9] ; // minutes
fragment HOUR_MIN : ( [01]?[0-9] | [2][0-3] ) [0-5][0-9] ; // hour / minutes quad digit pattern
fragment SECOND : [0-5][0-9] ; // seconds
// ISO8601 DURATION PnYnMnWnDTnnHnnMnn.nnnS
// here we allow a deviation from the standard to allow weeks to be // mixed in with the rest since this commonly occurs in medicine
// TODO: the following will incorrectly match just 'P'
ISO8601_DURATION : 'P'(DIGIT+[yY])?(DIGIT+[mM])?(DIGIT+[wW])?(DIGIT+[dD])?('T'(DIGIT+[hH])?(DIGIT+[mM])?(DIGIT+('.'DIGIT+)?[sS])?)? ;
// ---------------------- Identifiers ---------------------
ARCHETYPE_HRID : ARCHETYPE_HRID_ROOT '.v' VERSION_ID ;
ARCHETYPE_REF : ARCHETYPE_HRID_ROOT '.v' INTEGER ( '.' DIGIT+ )* ;
ARCHETYPE_HRID_ROOT : (NAMESPACE '::')? IDENTIFIER '-' IDENTIFIER '-' IDENTIFIER '.' IDENTIFIER ;
NAMESPACE : LABEL ('.' LABEL)+ ;
fragment LABEL : ALPHA_CHAR ( NAME_CHAR* ALPHANUM_CHAR )? ;
fragment IDENTIFIER : ALPHA_CHAR WORD_CHAR* ;
VERSION_ID : DIGIT+ DOT_SEGMENT DOT_SEGMENT (('-rc' | '-alpha') DOT_SEGMENT? )? ;
fragment DOT_SEGMENT : '.' DIGIT+ ;
GUID : HEX_DIGIT+ '-' HEX_DIGIT+ '-' HEX_DIGIT+ '-' HEX_DIGIT+ '-' HEX_DIGIT+ ;
ALPHA_UC_ID : ALPHA_UCHAR WORD_CHAR* ; // used for type ids
ALPHA_LC_ID : ALPHA_LCHAR WORD_CHAR* ; // used for attribute / method ids
// --------------------- primitive types -------------------
TERM_CODE_REF : '[' NAME_CHAR+ ( '(' NAME_CHAR+ ')' )? '::' NAME_CHAR+ ']' ; // e.g. [ICD10AM(1998)::F23]; [ISO_639-1::en]
URI : [a-z]+ ':' ( '//' | '/' )? ~[ \t\n]+? ; // just a simple recogniser, the full thing isn't required
INTEGER : DIGIT+ E_SUFFIX? ;
REAL : DIGIT+ '.' DIGIT+ E_SUFFIX? ;
fragment E_SUFFIX : [eE][+-]? DIGIT+ ;
STRING : '"' STRING_CHAR*? '"' ;
fragment STRING_CHAR : ~('\\'|["\r\n]) | ESCAPE_SEQ | UTF8CHAR ;
CHARACTER : '\'' CHAR '\'' ;
fragment CHAR : ~('\\'|['\r\n]) | ESCAPE_SEQ | UTF8CHAR ;
fragment ESCAPE_SEQ: '\\' ['"?abfnrtv\\] ;
SYM_TRUE : [Tt][Rr][Uu][Ee] ;
SYM_FALSE : [Ff][Aa][Ll][Ss][Ee] ;
// ------------------- character fragments ------------------
fragment NAME_CHAR : WORD_CHAR | '-' ;
fragment WORD_CHAR : ALPHANUM_CHAR | '_' ;
fragment ALPHANUM_CHAR : ALPHA_CHAR | DIGIT ;
fragment ALPHA_CHAR : [a-zA-Z] ;
fragment ALPHA_UCHAR : [A-Z] ;
fragment ALPHA_LCHAR : [a-z] ;
fragment UTF8CHAR : '\\u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ;
fragment DIGIT : [0-9] ;
fragment HEX_DIGIT : [0-9a-fA-F] ;
BRACKETS : [()<>=;\[\]{}];
ARITHMETIC_OPERATORS : [-+*/%^];
SYM_LIST_CONTINUE: '...' ;
SYM_INTERVAL_SEP: '..' ;
/*mode MATCHES;
SYM_LPAREN: '{';
SYM_START: '*' -> mode(DEFAULT_MODE);
SYM_OTHER: . -> mode(DEFAULT_MODE);
REGEXP : ('/' SLASH_REGEXP_CHAR* '/' | '^' REGEXP_CHAR* '^') -> mode(DEFAULT_MODE);
fragment REGEXP_CHAR : ~["\\^\n\r] | REGEXP_ESCAPE_SEQ | UTF8CHAR ;
fragment REGEXP_ESCAPE_SEQ : '\\' ['"?abfnrtv\\^] ;
*/
|
//
// description: Antlr4 lexer grammar for keywords of Archetype Definition Language (ADL2)
// author: Thomas Beale <[email protected]>
// support: openEHR Specifications PR tracker <https://openehr.atlassian.net/projects/SPECPR/issues>
// copyright: Copyright (c) 2015 openEHR Foundation
// license: Apache 2.0 License <http://www.apache.org/licenses/LICENSE-2.0.html>
//
lexer grammar AdlVocabulary;
MATCHES_REGEXP : SYM_MATCHES WS? '{' WS? REGEXP WS? '}' ;
fragment REGEXP : '/' SLASH_REGEXP_CHAR* '/' | '^' REGEXP_CHAR* '^';
fragment REGEXP_CHAR : ~('\\'|[^\n\r]) | REGEXP_ESCAPE_SEQ | UTF8CHAR ;
fragment REGEXP_ESCAPE_SEQ : '\\' [?abfnrtv\\^] ;
fragment SLASH_REGEXP_CHAR : ~[/\n\r] ;
// ~('\\'|[/\n\r]) | SLASH_REGEXP_ESCAPE_SEQ | UTF8CHAR ;
fragment SLASH_REGEXP_ESCAPE_SEQ : '\\' [?abfnrtv\/\\] ;
// TODO: should these be matched in the lexer, or should we just match any identifier and do things in parser rules?
ROOT_ID_CODE : 'id1' ('.1')* ;
ID_CODE : 'id' CODE_STR ;
AT_CODE : 'at' CODE_STR ;
AC_CODE : 'ac' CODE_STR ;
fragment CODE_STR : ('0' | [1-9][0-9]*) ( '.' ('0' | [1-9][0-9]* ))* ;
// ADL keywords
SYM_ARCHETYPE : [Aa][Rr][Cc][Hh][Ee][Tt][Yy][Pp][Ee] ;
SYM_TEMPLATE_OVERLAY : [Tt][Ee][Mm][Pp][Ll][Aa][Tt][Ee]'_'[Oo][Vv][Ee][Rr][Ll][Aa][Yy] ;
SYM_TEMPLATE : [Tt][Ee][Mm][Pp][Ll][Aa][Tt][Ee] ;
SYM_OPERATIONAL_TEMPLATE : [Oo][Pp][Ee][Rr][Aa][Tt][Ii][Oo][Nn][Aa][Ll]'_'[Tt][Ee][Mm][Pp][Ll][Aa][Tt][Ee] ;
SYM_SPECIALIZE : '\n'[Ss][Pp][Ee][Cc][Ii][Aa][Ll][Ii][SsZz][Ee] ;
SYM_LANGUAGE : '\n'[Ll][Aa][Nn][Gg][Uu][Aa][Gg][Ee] ;
SYM_DESCRIPTION : '\n'[Dd][Ee][Ss][Cc][Rr][Ii][Pp][Tt][Ii][Oo][Nn] ;
SYM_DEFINITION : '\n'[Dd][Ee][Ff][Ii][Nn][Ii][Tt][Ii][Oo][Nn] ;
SYM_RULES : '\n'[Rr][Uu][Ll][Ee][Ss] ;
SYM_TERMINOLOGY : '\n'[Tt][Ee][Rr][Mm][Ii][Nn][Oo][Ll][Oo][Gg][Yy] ;
SYM_ANNOTATIONS : '\n'[Aa][Nn][Nn][Oo][Tt][Aa][Tt][Ii][Oo][Nn][Ss] ;
SYM_COMPONENT_TERMINOLOGIES : '\n'[Cc][Oo][Mm][Pp][Oo][Nn][Ee][Nn][Tt]'_'[Tt][Ee][Rr][Mm][Ii][Nn][Oo][Ll][Oo][Gg][Ii][Ee][Ss] ;
// meta-data keywords
SYM_ADL_VERSION : [Aa][Dd][Ll]'_'[Vv][Ee][Rr][Ss][Ii][Oo][Nn] ;
SYM_RM_RELEASE : [Rr][Mm]'_'[Rr][Ee][Ll][Ee][Aa][Ss][Ee] ;
SYM_IS_CONTROLLED : [Cc][Oo][Nn][Nn][Tt][Rr][Oo][Ll][Ll][Ee][Dd] ;
SYM_IS_GENERATED : [Gg][Ee][Nn][Ee][Rr][Aa][Tt][Ee][Dd] ;
SYM_UID : [Uu][Ii][Dd] ;
SYM_BUILD_UID : [Bb][Uu][Ii][Ll][Dd]'_'[Uu][Ii][Dd] ;
// CADL keywords
SYM_EXISTENCE : [Ee][Xx][Ii][Ss][Tt][Ee][Nn][Cc][Ee] ;
SYM_OCCURRENCES : [Oo][Cc][Cc][Uu][Rr][Rr][Ee][Nn][Cc][Ee][Ss] ;
SYM_CARDINALITY : [Cc][Aa][Rr][Dd][Ii][Nn][Aa][Ll][Ii][Tt][Yy] ;
SYM_ORDERED : [Oo][Rr][Dd][Ee][Rr][Ee][Dd] ;
SYM_UNORDERED : [Uu][Nn][Oo][Rr][Dd][Ee][Rr][Ee][Dd] ;
SYM_UNIQUE : [Uu][Nn][Ii][Qq][Uu][Ee] ;
SYM_USE_NODE : [Uu][Ss][Ee][_][Nn][Oo][Dd][Ee] ;
SYM_USE_ARCHETYPE : [Uu][Ss][Ee][_][Aa][Rr][Cc][Hh][Ee][Tt][Yy][Pp][Ee] ;
SYM_ALLOW_ARCHETYPE : [Aa][Ll][Ll][Oo][Ww][_][Aa][Rr][Cc][Hh][Ee][Tt][Yy][Pp][Ee] ;
SYM_INCLUDE : [Ii][Nn][Cc][Ll][Uu][Dd][Ee] ;
SYM_EXCLUDE : [Ee][Xx][Cc][Ll][Uu][Dd][Ee] ;
SYM_AFTER : [Aa][Ff][Tt][Ee][Rr] ;
SYM_BEFORE : [Bb][Ee][Ff][Oo][Rr][Ee] ;
SYM_CLOSED : [Cc][Ll][Oo][Ss][Ee][Dd] ;
SYM_THEN : [Tt][Hh][Ee][Nn] ;
SYM_AND : [Aa][Nn][Dd] ;
SYM_OR : [Oo][Rr] ;
SYM_XOR : [Xx][Oo][Rr] ;
SYM_NOT : [Nn][Oo][Tt] ;
SYM_IMPLIES : [Ii][Mm][Pp][Ll][Ii][Ee][Ss] ;
SYM_FOR_ALL : [Ff][Oo][Rr][_][Aa][Ll][Ll] ;
SYM_EXISTS : [Ee][Xx][Ii][Ss][Tt][Ss] ;
SYM_MATCHES : ([Mm][Aa][Tt][Cc][Hh][Ee][Ss] | [Ii][Ss]'_'[Ii][Nn] | '\u2208');
SYM_TRUE : [Tt][Rr][Uu][Ee] ;
SYM_FALSE : [Ff][Aa][Ll][Ss][Ee] ;
// ---------- whitespace & comments ----------
WS : [ \t\r]+ -> skip ;
LINE : '\n' -> skip ; // increment line count
HLINE : '--------------------*' ; // special comment line used as a horizontal separator
CMT_LINE : '--'.*?'\n' -> skip ; // (increment line count)
// ---------- ISO8601 Date/Time values ----------
ISO8601_DATE : YEAR '-' MONTH ( '-' DAY )? ;
ISO8601_TIME : HOUR ':' MINUTE ( ':' SECOND ( ',' INTEGER )?)? ( TIMEZONE )? ;
ISO8601_DATE_TIME : YEAR '-' MONTH '-' DAY 'T' HOUR (':' MINUTE (':' SECOND ( ',' DIGIT+ )?)?)? ( TIMEZONE )? ;
fragment TIMEZONE : 'Z' | ('+'|'-') HOUR_MIN ; // hour offset, e.g. `+0930`, or else literal `Z` indicating +0000.
fragment YEAR : [1-9][0-9]* ;
fragment MONTH : ( [0][0-9] | [1][0-2] ) ; // month in year
fragment DAY : ( [012][0-9] | [3][0-2] ) ; // day in month
fragment HOUR : ( [01]?[0-9] | [2][0-3] ) ; // hour in 24 hour clock
fragment MINUTE : [0-5][0-9] ; // minutes
fragment HOUR_MIN : ( [01]?[0-9] | [2][0-3] ) [0-5][0-9] ; // hour / minutes quad digit pattern
fragment SECOND : [0-5][0-9] ; // seconds
// ISO8601 DURATION PnYnMnWnDTnnHnnMnn.nnnS
// here we allow a deviation from the standard to allow weeks to be // mixed in with the rest since this commonly occurs in medicine
// TODO: the following will incorrectly match just 'P'
ISO8601_DURATION : 'P'(DIGIT+[yY])?(DIGIT+[mM])?(DIGIT+[wW])?(DIGIT+[dD])?('T'(DIGIT+[hH])?(DIGIT+[mM])?(DIGIT+('.'DIGIT+)?[sS])?)? ;
// ---------------------- Identifiers ---------------------
ARCHETYPE_HRID : ARCHETYPE_HRID_ROOT '.v' VERSION_ID ;
ARCHETYPE_REF : ARCHETYPE_HRID_ROOT '.v' INTEGER ( '.' DIGIT+ )* ;
ARCHETYPE_HRID_ROOT : (NAMESPACE '::')? IDENTIFIER '-' IDENTIFIER '-' IDENTIFIER '.' IDENTIFIER ;
fragment NAMESPACE : LABEL ('.' LABEL)+ ;
fragment LABEL : ALPHA_CHAR ( NAME_CHAR* ALPHANUM_CHAR )? ;
fragment IDENTIFIER : ALPHA_CHAR WORD_CHAR* ;
VERSION_ID : DIGIT+ DOT_SEGMENT DOT_SEGMENT (('-rc' | '-alpha') DOT_SEGMENT? )? ;
fragment DOT_SEGMENT : '.' DIGIT+ ;
GUID : HEX_DIGIT+ '-' HEX_DIGIT+ '-' HEX_DIGIT+ '-' HEX_DIGIT+ '-' HEX_DIGIT+ ;
ALPHA_UC_ID : ALPHA_UCHAR WORD_CHAR* ; // used for type ids
ALPHA_LC_ID : ALPHA_LCHAR WORD_CHAR* ; // used for attribute / method ids
// --------------------- primitive types -------------------
TERM_CODE_REF : '[' NAME_CHAR+ ( '(' NAME_CHAR+ ')' )? '::' NAME_CHAR+ ']' ; // e.g. [ICD10AM(1998)::F23]; [ISO_639-1::en]
URI : [a-z]+ ':' ( '//' | '/' )? (~[ \t\n>]+)? ; // just a simple recogniser, the full thing isn't required
INTEGER : DIGIT+ E_SUFFIX? ;
REAL : DIGIT+ '.' DIGIT+ E_SUFFIX? ;
fragment E_SUFFIX : [eE][+-]? DIGIT+ ;
STRING : '"' STRING_CHAR*? '"' ;
fragment STRING_CHAR : ~[\\"] | ESCAPE_SEQ | UTF8CHAR ;
CHARACTER : '\'' CHAR '\'' ;
fragment CHAR : ~[\\'\r\n] | ESCAPE_SEQ | UTF8CHAR ;
fragment ESCAPE_SEQ: '\\' ['"?abfnrtv\\] ;
// ------------------- character fragments ------------------
fragment NAME_CHAR : WORD_CHAR | '-' ;
fragment WORD_CHAR : ALPHANUM_CHAR | '_' ;
fragment ALPHANUM_CHAR : ALPHA_CHAR | DIGIT ;
fragment ALPHA_CHAR : [a-zA-Z] ;
fragment ALPHA_UCHAR : [A-Z] ;
fragment ALPHA_LCHAR : [a-z] ;
fragment UTF8CHAR : '\\u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ;
fragment DIGIT : [0-9] ;
fragment HEX_DIGIT : [0-9a-fA-F] ;
BRACKETS : [()<>\[\]{}];
ARITHMETIC_OPERATORS : [-+*/%^=];
MISC : [;];
SYM_LIST_CONTINUE: '...' ;
SYM_INTERVAL_SEP: '..' ;
DATE_CONSTRAINT_PATTERN : YEAR_PATTERN '-' MONTH_PATTERN '-' DAY_PATTERN ;
TIME_CONSTRAINT_PATTERN : HOUR_PATTERN ':' MINUTE_PATTERN ':' SECOND_PATTERN ;
DATE_TIME_CONSTRAINT_PATTERN : DATE_CONSTRAINT_PATTERN 'T' TIME_CONSTRAINT_PATTERN ;
DURATION_CONSTRAINT_PATTERN : 'P' [yY]?[mM]?[Ww]?[dD]? ('T' [hH]?[mM]?[sS]?)? ;
// date time pattern
fragment YEAR_PATTERN: ('yyy' 'y'?) | ('YYY' 'Y'?);
fragment MONTH_PATTERN: 'mm' | 'MM' | '??' | 'XX';
fragment DAY_PATTERN: 'dd' | 'DD' | '??' | 'XX';
fragment HOUR_PATTERN: 'hh' | 'HH' | '??' | 'XX';
fragment MINUTE_PATTERN: 'mm' | 'MM' | '??' | 'XX';
fragment SECOND_PATTERN: 'ss' | 'SS' | '??' | 'XX';
|
Fix grammar
|
Fix grammar
|
ANTLR
|
apache-2.0
|
nedap/archie
|
74c8466ea800339d046fa18c943dcc3f5f723ea7
|
antlr4/ANTLRv4Lexer.g4
|
antlr4/ANTLRv4Lexer.g4
|
/*
* [The "BSD license"]
* Copyright (c) 2012-2015 Terence Parr
* Copyright (c) 2012-2015 Sam Harwell
* Copyright (c) 2015 Gerald Rosenberg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* A grammar for ANTLR v4 implemented using v4 syntax
*
* Modified 2015.06.16 gbr
* -- update for compatibility with Antlr v4.5
*/
lexer grammar ANTLRv4Lexer;
options
{ superClass = LexerAdaptor; }
import LexBasic;
// Standard set of fragments
tokens
{ TOKEN_REF , RULE_REF , LEXER_CHAR_SET }
channels
{ OFF_CHANNEL }
// ======================================================
// 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{ handleBeginArgument(); };
// -------------------------
// Actions
BEGIN_ACTION
: LBrace -> pushMode (Action)
;
// -------------------------
// Keywords
//
// Keywords may not be used as labels for rules or in any other context where
// they would be ambiguous with the keyword vs some other identifier. OPTIONS,
// TOKENS, & CHANNELS blocks are handled idiomatically in dedicated lexical modes.
OPTIONS
: 'options' -> pushMode (Options)
;
TOKENS
: 'tokens' -> pushMode (Tokens)
;
CHANNELS
: 'channels' -> pushMode (Channels)
;
IMPORT
: 'import'
;
FRAGMENT
: 'fragment'
;
LEXER
: 'lexer'
;
PARSER
: 'parser'
;
GRAMMAR
: 'grammar'
;
PROTECTED
: 'protected'
;
PUBLIC
: 'public'
;
PRIVATE
: 'private'
;
RETURNS
: 'returns'
;
LOCALS
: 'locals'
;
THROWS
: 'throws'
;
CATCH
: 'catch'
;
FINALLY
: 'finally'
;
MODE
: 'mode'
;
// -------------------------
// Punctuation
COLON
: Colon
;
COLONCOLON
: DColon
;
COMMA
: Comma
;
SEMI
: Semi
;
LPAREN
: LParen
;
RPAREN
: RParen
;
LBRACE
: LBrace
;
RBRACE
: RBrace
;
RARROW
: RArrow
;
LT
: Lt
;
GT
: Gt
;
ASSIGN
: Equal
;
QUESTION
: Question
;
STAR
: Star
;
PLUS_ASSIGN
: PlusAssign
;
PLUS
: Plus
;
OR
: Pipe
;
DOLLAR
: Dollar
;
RANGE
: Range
;
DOT
: Dot
;
AT
: At
;
POUND
: Pound
;
NOT
: Tilde
;
// -------------------------
// Identifiers - allows unicode rule/token names
ID
: Id
;
// -------------------------
// Whitespace
WS
: Ws + -> channel (OFF_CHANNEL)
;
// -------------------------
// Illegal Characters
//
// This is an illegal character trap which is always the last rule in the
// lexer specification. It matches a single character of any value and being
// the last rule in the file will match when no other rule knows what to do
// about the character. It is reported as an error but is not passed on to the
// parser. This means that the parser to deal with the gramamr file anyway
// but we will not try to analyse or code generate from a file with lexical
// errors.
//
// Comment this rule out to allow the error to be propagated to the parser
ERRCHAR
: . -> channel (HIDDEN)
;
// ======================================================
// Lexer modes
// -------------------------
// Arguments
mode Argument;
// E.g., [int x, List<String> a[]]
NESTED_ARGUMENT
: LBrack -> type (ARGUMENT_CONTENT) , pushMode (Argument)
;
ARGUMENT_ESCAPE
: EscAny -> type (ARGUMENT_CONTENT)
;
ARGUMENT_STRING_LITERAL
: DQuoteLiteral -> type (ARGUMENT_CONTENT)
;
ARGUMENT_CHAR_LITERAL
: SQuoteLiteral -> type (ARGUMENT_CONTENT)
;
END_ARGUMENT
: RBrack{ handleEndArgument(); };
// added this to return non-EOF token type here. EOF does something weird
UNTERMINATED_ARGUMENT
: EOF -> popMode
;
ARGUMENT_CONTENT
: .
;
// -------------------------
// Actions
//
// Many language targets use {} as block delimiters and so we
// must recursively match {} delimited blocks to balance the
// braces. Additionally, we must make some assumptions about
// literal string representation in the target language. We assume
// that they are delimited by ' or " and so consume these
// in their own alts so as not to inadvertantly match {}.
mode Action;
NESTED_ACTION
: LBrace -> type (ACTION_CONTENT) , pushMode (Action)
;
ACTION_ESCAPE
: EscAny -> type (ACTION_CONTENT)
;
ACTION_STRING_LITERAL
: DQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_CHAR_LITERAL
: SQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_DOC_COMMENT
: DocComment -> type (ACTION_CONTENT)
;
ACTION_BLOCK_COMMENT
: BlockComment -> type (ACTION_CONTENT)
;
ACTION_LINE_COMMENT
: LineComment -> type (ACTION_CONTENT)
;
END_ACTION
: RBrace{ handleEndAction(); };
UNTERMINATED_ACTION
: EOF -> popMode
;
ACTION_CONTENT
: .
;
// -------------------------
mode Options;
OPT_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (OFF_CHANNEL)
;
OPT_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (OFF_CHANNEL)
;
OPT_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (OFF_CHANNEL)
;
OPT_LBRACE
: LBrace -> type (LBRACE)
;
OPT_RBRACE
: RBrace -> type (RBRACE) , popMode
;
OPT_ID
: Id -> type (ID)
;
OPT_DOT
: Dot -> type (DOT)
;
OPT_ASSIGN
: Equal -> type (ASSIGN)
;
OPT_STRING_LITERAL
: SQuoteLiteral -> type (STRING_LITERAL)
;
OPT_INT
: Int -> type (INT)
;
OPT_STAR
: Star -> type (STAR)
;
OPT_SEMI
: Semi -> type (SEMI)
;
OPT_WS
: Ws + -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode Tokens;
TOK_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (OFF_CHANNEL)
;
TOK_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (OFF_CHANNEL)
;
TOK_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (OFF_CHANNEL)
;
TOK_LBRACE
: LBrace -> type (LBRACE)
;
TOK_RBRACE
: RBrace -> type (RBRACE) , popMode
;
TOK_ID
: Id -> type (ID)
;
TOK_DOT
: Dot -> type (DOT)
;
TOK_COMMA
: Comma -> type (COMMA)
;
TOK_WS
: Ws + -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode Channels;
// currently same as Tokens mode; distinguished by keyword
CHN_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (OFF_CHANNEL)
;
CHN_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (OFF_CHANNEL)
;
CHN_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (OFF_CHANNEL)
;
CHN_LBRACE
: LBrace -> type (LBRACE)
;
CHN_RBRACE
: RBrace -> type (RBRACE) , popMode
;
CHN_ID
: Id -> type (ID)
;
CHN_DOT
: Dot -> type (DOT)
;
CHN_COMMA
: Comma -> type (COMMA)
;
CHN_WS
: Ws + -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode LexerCharSet;
LEXER_CHAR_SET_BODY
: (~ [\]\\] | EscAny) + -> more
;
LEXER_CHAR_SET
: RBrack -> popMode
;
UNTERMINATED_CHAR_SET
: EOF -> popMode
;
// ------------------------------------------------------------------------------
// Grammar specific Keywords, Punctuation, etc.
fragment Id
: NameStartChar NameChar*
;
|
/*
* [The "BSD license"]
* Copyright (c) 2012-2015 Terence Parr
* Copyright (c) 2012-2015 Sam Harwell
* Copyright (c) 2015 Gerald Rosenberg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* A grammar for ANTLR v4 implemented using v4 syntax
*
* Modified 2015.06.16 gbr
* -- update for compatibility with Antlr v4.5
*/
lexer grammar ANTLRv4Lexer;
options
{ superClass = LexerAdaptor; }
import LexBasic;
// Standard set of fragments
tokens
{ TOKEN_REF , RULE_REF , LEXER_CHAR_SET }
channels
{ OFF_CHANNEL }
// ======================================================
// 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{ handleBeginArgument(); };
// -------------------------
// Actions
BEGIN_ACTION
: LBrace -> pushMode (Action)
;
// -------------------------
// Keywords
//
// Keywords may not be used as labels for rules or in any other context where
// they would be ambiguous with the keyword vs some other identifier. OPTIONS,
// TOKENS, & CHANNELS blocks are handled idiomatically in dedicated lexical modes.
OPTIONS
: 'options' -> pushMode (Options)
;
TOKENS
: 'tokens' -> pushMode (Tokens)
;
CHANNELS
: 'channels' -> pushMode (Channels)
;
IMPORT
: 'import'
;
FRAGMENT
: 'fragment'
;
LEXER
: 'lexer'
;
PARSER
: 'parser'
;
GRAMMAR
: 'grammar'
;
PROTECTED
: 'protected'
;
PUBLIC
: 'public'
;
PRIVATE
: 'private'
;
RETURNS
: 'returns'
;
LOCALS
: 'locals'
;
THROWS
: 'throws'
;
CATCH
: 'catch'
;
FINALLY
: 'finally'
;
MODE
: 'mode'
;
// -------------------------
// Punctuation
COLON
: Colon
;
COLONCOLON
: DColon
;
COMMA
: Comma
;
SEMI
: Semi
;
LPAREN
: LParen
;
RPAREN
: RParen
;
LBRACE
: LBrace
;
RBRACE
: RBrace
;
RARROW
: RArrow
;
LT
: Lt
;
GT
: Gt
;
ASSIGN
: Equal
;
QUESTION
: Question
;
STAR
: Star
;
PLUS_ASSIGN
: PlusAssign
;
PLUS
: Plus
;
OR
: Pipe
;
DOLLAR
: Dollar
;
RANGE
: Range
;
DOT
: Dot
;
AT
: At
;
POUND
: Pound
;
NOT
: Tilde
;
// -------------------------
// Identifiers - allows unicode rule/token names
ID
: Id
;
// -------------------------
// Whitespace
WS
: Ws + -> channel (OFF_CHANNEL)
;
// -------------------------
// Illegal Characters
//
// This is an illegal character trap which is always the last rule in the
// lexer specification. It matches a single character of any value and being
// the last rule in the file will match when no other rule knows what to do
// about the character. It is reported as an error but is not passed on to the
// parser. This means that the parser to deal with the gramamr file anyway
// but we will not try to analyse or code generate from a file with lexical
// errors.
//
// Comment this rule out to allow the error to be propagated to the parser
ERRCHAR
: . -> channel (HIDDEN)
;
// ======================================================
// Lexer modes
// -------------------------
// Arguments
mode Argument;
// E.g., [int x, List<String> a[]]
NESTED_ARGUMENT
: LBrack -> type (ARGUMENT_CONTENT) , pushMode (Argument)
;
ARGUMENT_ESCAPE
: EscAny -> type (ARGUMENT_CONTENT)
;
ARGUMENT_STRING_LITERAL
: DQuoteLiteral -> type (ARGUMENT_CONTENT)
;
ARGUMENT_CHAR_LITERAL
: SQuoteLiteral -> type (ARGUMENT_CONTENT)
;
END_ARGUMENT
: RBrack{ handleEndArgument(); };
// added this to return non-EOF token type here. EOF does something weird
UNTERMINATED_ARGUMENT
: EOF -> popMode
;
ARGUMENT_CONTENT
: .
;
// -------------------------
// Actions
//
// Many language targets use {} as block delimiters and so we
// must recursively match {} delimited blocks to balance the
// braces. Additionally, we must make some assumptions about
// literal string representation in the target language. We assume
// that they are delimited by ' or " and so consume these
// in their own alts so as not to inadvertantly match {}.
mode Action;
NESTED_ACTION
: LBrace -> type (ACTION_CONTENT) , pushMode (Action)
;
ACTION_ESCAPE
: EscAny -> type (ACTION_CONTENT)
;
ACTION_STRING_LITERAL
: DQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_CHAR_LITERAL
: SQuoteLiteral -> type (ACTION_CONTENT)
;
ACTION_DOC_COMMENT
: DocComment -> type (ACTION_CONTENT)
;
ACTION_BLOCK_COMMENT
: BlockComment -> type (ACTION_CONTENT)
;
ACTION_LINE_COMMENT
: LineComment -> type (ACTION_CONTENT)
;
END_ACTION
: RBrace{ handleEndAction(); };
UNTERMINATED_ACTION
: EOF -> popMode
;
ACTION_CONTENT
: .
;
// -------------------------
mode Options;
OPT_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (OFF_CHANNEL)
;
OPT_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (OFF_CHANNEL)
;
OPT_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (OFF_CHANNEL)
;
OPT_LBRACE
: LBrace -> type (LBRACE)
;
OPT_RBRACE
: RBrace -> type (RBRACE) , popMode
;
OPT_ID
: Id -> type (ID)
;
OPT_DOT
: Dot -> type (DOT)
;
OPT_ASSIGN
: Equal -> type (ASSIGN)
;
OPT_STRING_LITERAL
: SQuoteLiteral -> type (STRING_LITERAL)
;
OPT_INT
: DecimalNumeral -> type (INT)
;
OPT_STAR
: Star -> type (STAR)
;
OPT_SEMI
: Semi -> type (SEMI)
;
OPT_WS
: Ws + -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode Tokens;
TOK_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (OFF_CHANNEL)
;
TOK_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (OFF_CHANNEL)
;
TOK_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (OFF_CHANNEL)
;
TOK_LBRACE
: LBrace -> type (LBRACE)
;
TOK_RBRACE
: RBrace -> type (RBRACE) , popMode
;
TOK_ID
: Id -> type (ID)
;
TOK_DOT
: Dot -> type (DOT)
;
TOK_COMMA
: Comma -> type (COMMA)
;
TOK_WS
: Ws + -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode Channels;
// currently same as Tokens mode; distinguished by keyword
CHN_DOC_COMMENT
: DocComment -> type (DOC_COMMENT) , channel (OFF_CHANNEL)
;
CHN_BLOCK_COMMENT
: BlockComment -> type (BLOCK_COMMENT) , channel (OFF_CHANNEL)
;
CHN_LINE_COMMENT
: LineComment -> type (LINE_COMMENT) , channel (OFF_CHANNEL)
;
CHN_LBRACE
: LBrace -> type (LBRACE)
;
CHN_RBRACE
: RBrace -> type (RBRACE) , popMode
;
CHN_ID
: Id -> type (ID)
;
CHN_DOT
: Dot -> type (DOT)
;
CHN_COMMA
: Comma -> type (COMMA)
;
CHN_WS
: Ws + -> type (WS) , channel (OFF_CHANNEL)
;
// -------------------------
mode LexerCharSet;
LEXER_CHAR_SET_BODY
: (~ [\]\\] | EscAny) + -> more
;
LEXER_CHAR_SET
: RBrack -> popMode
;
UNTERMINATED_CHAR_SET
: EOF -> popMode
;
// ------------------------------------------------------------------------------
// Grammar specific Keywords, Punctuation, etc.
fragment Id
: NameStartChar NameChar*
;
|
Fix int options parsing in ANTLRv4Lexer.g4
|
Fix int options parsing in ANTLRv4Lexer.g4
|
ANTLR
|
mit
|
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
|
e54013b12926486331bac48ef715bb7fbf66aa2e
|
sharding-core/src/main/antlr4/imports/MySQLKeyword.g4
|
sharding-core/src/main/antlr4/imports/MySQLKeyword.g4
|
lexer grammar MySQLKeyword;
import Symbol;
ACCOUNT
: A C C O U N T
;
ACTION
: A C T I O N
;
ADMIN
: A D M I N
;
AFTER
: A F T E R
;
ALGORITHM
: A L G O R I T H M
;
ANALYZE
: A N A L Y Z E
;
AUDIT_ADMIN
: A U D I T UL_ A D M I N
;
AUTO_INCREMENT
: A U T O UL_ I N C R E M E N T
;
AVG_ROW_LENGTH
: A V G UL_ R O W UL_ L E N G T H
;
BEGIN
: B E G I N
;
BINLOG_ADMIN
: B I N L O G UL_ A D M I N
;
BTREE
: B T R E E
;
CASE
: C A S E
;
CHAIN
: C H A I N
;
CHANGE
: C H A N G E
;
CHAR
: C H A R
;
CHARACTER
: C H A R A C T E R
;
CHARSET
: C H A R S E T
;
CHECKSUM
: C H E C K S U M
;
CIPHER
: C I P H E R
;
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
;
EXCEPT
: E X C E P 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
;
EXPIRE
: E X P I R 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
;
HISTORY
: H I S T O R Y
;
IDENTIFIED
: I D E N T I F I E D
;
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
;
INTERVAL
: I N T E R V A L
;
INTO
: I N T O
;
ISSUER
: I S S U E R
;
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_CONNECTIONS_PER_HOUR
: M A X UL_ C O N N E C T I O N S UL_ P E R UL_ H O U R
;
MAX_QUERIES_PER_HOUR
: M A X UL_ Q U E R I E S UL_ P E R UL_ H O U R
;
MAX_ROWS
: M A X UL_ R O W S
;
MAX_UPDATES_PER_HOUR
: M A X UL_ U P D A T E S UL_ P E R UL_ H O U R
;
MAX_USER_CONNECTIONS
: M A X UL_ U S E R UL_ C O N N E C T I O N 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
;
NEVER
: N E V E R
;
NONE
: N O N E
;
NOW
: N O W
;
OFFLINE
: O F F L I N E
;
OLD
: O L D
;
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
;
OPTIONAL
: O P T I O N A L
;
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
;
REQUIRE
: R E Q U I R E
;
RESTRICT
: R E S T R I C T
;
RETAIN
: R E T A I N
;
REUSE
: R E U S E
;
REVOKE
: R E V O K E
;
RIGHT
: R I G H T
;
ROLE
: R O L E
;
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
;
SSL
: S S L
;
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
;
SUBJECT
: S U B J E C T
;
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
;
UNLOCK
: U N L O C K
;
UNSIGNED
: U N S I G N E D
;
UPDATE
: U P D A T E
;
UPGRADE
: U P G R A D E
;
USAGE
: U S A G E
;
USE
: U S E
;
USER
: U S E R
;
USING
: U S I N G
;
VALIDATION
: V A L I D A T I O N
;
VALUE
: V A L U E
;
VALUES
: V A L U E S
;
VERSION_TOKEN_ADMIN
: V E R S I O N UL_ T O K E N UL_ A D M I N
;
VIEW
: V I E W
;
VIRTUAL
: V I R T U A L
;
WHEN
: W H E N
;
WITHOUT
: W I T H O U T
;
WRITE
: W R I T E
;
ZEROFILL
: Z E R O F I L L
;
|
lexer grammar MySQLKeyword;
import Symbol;
ACCOUNT
: A C C O U N T
;
ACTION
: A C T I O N
;
ADMIN
: A D M I N
;
AFTER
: A F T E R
;
ALGORITHM
: A L G O R I T H M
;
ANALYZE
: A N A L Y Z E
;
AUDIT_ADMIN
: A U D I T UL_ A D M I N
;
AUTO_INCREMENT
: A U T O UL_ I N C R E M E N T
;
AVG_ROW_LENGTH
: A V G UL_ R O W UL_ L E N G T H
;
BEGIN
: B E G I N
;
BINLOG_ADMIN
: B I N L O G UL_ A D M I N
;
BTREE
: B T R E E
;
CASE
: C A S E
;
CHAIN
: C H A I N
;
CHANGE
: C H A N G E
;
CHAR
: C H A R
;
CHARACTER
: C H A R A C T E R
;
CHARSET
: C H A R S E T
;
CHECKSUM
: C H E C K S U M
;
CIPHER
: C I P H E R
;
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
;
EXCEPT
: E X C E P 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
;
EXPIRE
: E X P I R 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
;
HISTORY
: H I S T O R Y
;
IDENTIFIED
: I D E N T I F I E D
;
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
;
INTERVAL
: I N T E R V A L
;
INTO
: I N T O
;
ISSUER
: I S S U E R
;
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_CONNECTIONS_PER_HOUR
: M A X UL_ C O N N E C T I O N S UL_ P E R UL_ H O U R
;
MAX_QUERIES_PER_HOUR
: M A X UL_ Q U E R I E S UL_ P E R UL_ H O U R
;
MAX_ROWS
: M A X UL_ R O W S
;
MAX_UPDATES_PER_HOUR
: M A X UL_ U P D A T E S UL_ P E R UL_ H O U R
;
MAX_USER_CONNECTIONS
: M A X UL_ U S E R UL_ C O N N E C T I O N 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
;
NEVER
: N E V E R
;
NONE
: N O N E
;
NOW
: N O W
;
OFFLINE
: O F F L I N E
;
OLD
: O L D
;
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
;
OPTIONAL
: O P T I O N A L
;
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
;
REQUIRE
: R E Q U I R E
;
RESTRICT
: R E S T R I C T
;
RETAIN
: R E T A I N
;
REUSE
: R E U S E
;
REVOKE
: R E V O K E
;
RIGHT
: R I G H T
;
ROLE
: R O L E
;
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
;
SSL
: S S L
;
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
;
SUBJECT
: S U B J E C T
;
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
;
UNLOCK
: U N L O C K
;
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
;
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 keyword
|
add keyword
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
|
963b4c87bbb1d595518139873fb6b6f9e9956511
|
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
;
execute
: createIndex
| alterIndex
| dropIndex
| createTable
| alterTable
| dropTable
| truncateTable
| setTransaction
| commit
| rollback
| savepoint
;
|
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
;
|
add programUnit
|
add programUnit
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
e63e4049996297ffde6578078dcace9843c1b041
|
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 fileTableClause_ createDefinitionClause_
;
createIndex
: CREATE createIndexSpecification_ INDEX indexName ON tableName columnNames
;
alterTable
: alterTableOp
(
alterColumn
| addColumnSpecification
| alterDrop
| alterCheckConstraint
| alterTrigger
| alterSwitch
| alterSet
| alterTableTableOption
| REBUILD
)
;
alterIndex
: ALTER INDEX (indexName | ALL) ON tableName
;
dropTable
: DROP TABLE (IF EXISTS)? tableName (COMMA_ tableName)*
;
dropIndex
: DROP INDEX (IF EXISTS)? indexName ON tableName
;
truncateTable
: TRUNCATE TABLE tableName
;
fileTableClause_
: (AS FILETABLE)?
;
createDefinitionClause_
: createTableDefinitions_ partitionScheme_ fileGroup_
;
createTableDefinitions_
: LP_ createTableDefinition_ (COMMA_ createTableDefinition_)* (COMMA_ periodClause)? RP_
;
createTableDefinition_
: columnDefinition | computedColumnDefinition | columnSetDefinition | tableConstraint | tableIndex
;
columnDefinition
: columnName dataType columnDefinitionOption* columnConstraints columnIndex?
;
columnDefinitionOption
: FILESTREAM
| COLLATE collationName
| SPARSE
| MASKED WITH LP_ FUNCTION EQ_ STRING_ RP_
| (CONSTRAINT ignoredIdentifier_)? DEFAULT expr
| IDENTITY (LP_ NUMBER_ COMMA_ NUMBER_ RP_)?
| NOT FOR REPLICATION
| GENERATED ALWAYS AS ROW (START | END) HIDDEN_?
| NOT? NULL
| ROWGUIDCOL
| ENCRYPTED WITH LP_ COLUMN_ENCRYPTION_KEY EQ_ ignoredIdentifier_ COMMA_ ENCRYPTION_TYPE EQ_ (DETERMINISTIC | RANDOMIZED) COMMA_ ALGORITHM EQ_ STRING_ RP_
| columnConstraint (COMMA_ columnConstraint)*
| columnIndex
;
columnConstraint
: (CONSTRAINT ignoredIdentifier_)? (primaryKeyConstraint | columnForeignKeyConstraint | checkConstraint)
;
primaryKeyConstraint
: (primaryKey | UNIQUE) (diskTablePrimaryKeyConstraintOption | memoryTablePrimaryKeyConstraintOption)
;
diskTablePrimaryKeyConstraintOption
: (CLUSTERED | NONCLUSTERED)? primaryKeyWithClause? primaryKeyOnClause?
;
primaryKeyWithClause
: WITH (FILLFACTOR EQ_ NUMBER_ | LP_ indexOption (COMMA_ indexOption)* RP_)
;
primaryKeyOnClause
: onSchemaColumn | onFileGroup | onString
;
onSchemaColumn
: ON schemaName LP_ columnName RP_
;
onFileGroup
: ON ignoredIdentifier_
;
onString
: ON STRING_
;
memoryTablePrimaryKeyConstraintOption
: CLUSTERED withBucket?
;
withBucket
: WITH LP_ BUCKET_COUNT EQ_ NUMBER_ RP_
;
columnForeignKeyConstraint
: (FOREIGN KEY)? REFERENCES tableName LP_ columnName RP_ foreignKeyOnAction*
;
foreignKeyOnAction
: ON (DELETE | UPDATE) foreignKeyOn | NOT FOR REPLICATION
;
foreignKeyOn
: NO ACTION | CASCADE | SET (NULL | DEFAULT)
;
checkConstraint
: CHECK(NOT FOR REPLICATION)? LP_ expr RP_
;
columnIndex
: INDEX indexName (CLUSTERED | NONCLUSTERED)? (WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause? (FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))?
;
indexOnClause
: onSchemaColumn | onFileGroup | onDefault
;
onDefault
: ON DEFAULT
;
columnConstraints
: (columnConstraint(COMMA_ columnConstraint)*)?
;
computedColumnDefinition
: columnName AS expr (PERSISTED(NOT NULL)?)? columnConstraint?
;
columnSetDefinition
: ignoredIdentifier_ IDENTIFIER_ COLUMN_SET FOR ALL_SPARSE_COLUMNS
;
tableConstraint
: (CONSTRAINT ignoredIdentifier_)? (tablePrimaryConstraint | tableForeignKeyConstraint | checkConstraint)
;
tablePrimaryConstraint
: primaryKeyUnique (diskTablePrimaryConstraintOption | memoryTablePrimaryConstraintOption)
;
primaryKeyUnique
: primaryKey | UNIQUE
;
diskTablePrimaryConstraintOption
: (CLUSTERED | NONCLUSTERED)? columnNames primaryKeyWithClause? primaryKeyOnClause?
;
memoryTablePrimaryConstraintOption
: NONCLUSTERED (columnNames | hashWithBucket)
;
hashWithBucket
: HASH columnNames withBucket
;
tableForeignKeyConstraint
: (FOREIGN KEY)? columnNames REFERENCES tableName columnNames foreignKeyOnAction*
;
tableIndex
: INDEX indexName
((CLUSTERED | NONCLUSTERED)? columnNames
| CLUSTERED COLUMNSTORE
| NONCLUSTERED? (COLUMNSTORE columnNames | hashWithBucket)
| CLUSTERED COLUMNSTORE (WITH LP_ COMPRESSION_DELAY EQ_ (NUMBER_ MINUTES?) RP_)?)
(WHERE expr)?
(WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause?
(FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))?
;
createIndexSpecification_
: UNIQUE? (CLUSTERED | NONCLUSTERED)?
;
tableOption
: DATA_COMPRESSION EQ_ (NONE | ROW | PAGE) (ON PARTITIONS LP_ partitionExpressions RP_)?
| FILETABLE_DIRECTORY EQ_ ignoredIdentifier_
| FILETABLE_COLLATE_FILENAME EQ_ (collationName | DATABASE_DEAULT)
| FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME EQ_ ignoredIdentifier_
| FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME EQ_ ignoredIdentifier_
| FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME EQ_ ignoredIdentifier_
| SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?
| REMOTE_DATA_ARCHIVE EQ_ (ON (LP_ tableStretchOptions (COMMA_ tableStretchOptions)* RP_)? | OFF LP_ MIGRATION_STATE EQ_ PAUSED RP_)
| tableOptOption
| distributionOption
| dataWareHouseTableOption
;
tableOptOption
: (MEMORY_OPTIMIZED EQ_ ON) | (DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA)) | (SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?)
;
distributionOption
: DISTRIBUTION EQ_ (HASH LP_ columnName RP_ | ROUND_ROBIN | REPLICATE)
;
dataWareHouseTableOption
: CLUSTERED COLUMNSTORE INDEX | HEAP | dataWareHousePartitionOption
;
dataWareHousePartitionOption
: (PARTITION LP_ columnName RANGE (LEFT | RIGHT)? FOR VALUES LP_ simpleExpr (COMMA_ simpleExpr)* RP_ RP_)
;
tableStretchOptions
: (FILTER_PREDICATE EQ_ (NULL | functionCall) COMMA_)? MIGRATION_STATE EQ_ (OUTBOUND | INBOUND | PAUSED)
;
partitionScheme_
: (ON (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_))?
;
fileGroup_
: (TEXTIMAGE_ON (ignoredIdentifier_ | STRING_))? ((FILESTREAM_ON (schemaName) | ignoredIdentifier_ STRING_))? (WITH LP_ tableOption (COMMA_ tableOption)* RP_)?
;
periodClause
: PERIOD FOR SYSTEM_TIME LP_ columnName COMMA_ columnName RP_
;
alterTableOp
: ALTER TABLE tableName
;
alterColumn
: modifyColumnSpecification
;
modifyColumnSpecification
: alterColumnOp dataType (COLLATE collationName)? (NULL | NOT NULL)? SPARSE?
;
alterColumnOp
: ALTER COLUMN columnName
;
addColumnSpecification
: (WITH (CHECK | NOCHECK))? ADD (alterColumnAddOption (COMMA_ alterColumnAddOption)* | (columnNameGeneratedClause COMMA_ periodClause| periodClause COMMA_ columnNameGeneratedClause))
;
alterColumnAddOption
: columnDefinition
| computedColumnDefinition
| columnSetDefinition
| tableConstraint
| alterTableTableIndex
| constraintForColumn
;
constraintForColumn
: (CONSTRAINT ignoredIdentifier_)? DEFAULT simpleExpr FOR columnName
;
columnNameWithSortsWithParen
: LP_ columnNameWithSort (COMMA_ columnNameWithSort)* RP_
;
columnNameWithSort
: columnName (ASC | DESC)?
;
columnNameGeneratedClause
: columnNameGenerated DEFAULT simpleExpr (WITH VALUES)? COMMA_ columnNameGenerated
;
columnNameGenerated
: columnName dataTypeName_ GENERATED ALWAYS AS ROW (START | END)? HIDDEN_? (NOT NULL)? (CONSTRAINT ignoredIdentifier_)?
;
alterDrop
: DROP
(
alterTableDropConstraint
| dropColumnSpecification
| dropIndexSpecification
| PERIOD FOR SYSTEM_TIME
)
;
alterTableDropConstraint
: CONSTRAINT? (IF EXISTS)? dropConstraintName (COMMA_ dropConstraintName)*
;
dropConstraintName
: ignoredIdentifier_ dropConstraintWithClause?
;
dropConstraintWithClause
: WITH LP_ dropConstraintOption (COMMA_ dropConstraintOption)* RP_
;
dropConstraintOption
: (MAXDOP EQ_ NUMBER_ | ONLINE EQ_ (ON | OFF) | MOVE TO (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_))
;
dropColumnSpecification
: COLUMN (IF EXISTS)? columnName (COMMA_ columnName)*
;
dropIndexSpecification
: INDEX (IF EXISTS)? indexName (COMMA_ indexName)*
;
alterCheckConstraint
: WITH? (CHECK | NOCHECK) CONSTRAINT (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*))
;
alterTrigger
: (ENABLE| DISABLE) TRIGGER (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*))
;
alterSwitch
: SWITCH (PARTITION expr)? TO tableName (PARTITION expr)? (WITH LP_ lowPriorityLockWait RP_)?
;
alterSet
: SET LP_ (setFileStreamClause | setSystemVersionClause) RP_
;
setFileStreamClause
: FILESTREAM_ON EQ_ (schemaName | ignoredIdentifier_ | STRING_)
;
setSystemVersionClause
: SYSTEM_VERSIONING EQ_ (OFF | alterSetOnClause)
;
alterSetOnClause
: ON
(
LP_ (HISTORY_TABLE EQ_ tableName)?
(COMMA_? DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))?
(COMMA_? HISTORY_RETENTION_PERIOD EQ_ (INFINITE | (NUMBER_ (DAY | DAYS | WEEK | WEEKS | MONTH | MONTHS | YEAR | YEARS))))?
RP_
)?
;
alterTableTableIndex
: indexWithName (indexNonClusterClause | indexClusterClause)
;
indexWithName
: INDEX indexName
;
indexNonClusterClause
: NONCLUSTERED (hashWithBucket | (columnNameWithSortsWithParen alterTableIndexOnClause?))
;
alterTableIndexOnClause
: ON ignoredIdentifier_ | DEFAULT
;
indexClusterClause
: CLUSTERED COLUMNSTORE (WITH COMPRESSION_DELAY EQ_ NUMBER_ MINUTES?)? indexOnClause?
;
alterTableTableOption
: SET LP_ LOCK_ESCALATION EQ_ (AUTO | TABLE | DISABLE) RP_
| MEMORY_OPTIMIZED EQ_ ON
| DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA)
| SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?
;
|
add createIndexSpecification_
|
add createIndexSpecification_
|
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
|
6b994bac97af045873b1d4c7265b723aaa00b954
|
grammars/Wry.g4
|
grammars/Wry.g4
|
/*
* Wry.g4
*
* ANTLR4 grammar for wry.
*
* Author: Mike Weaver
* Created: 2017-03-15
*
*/
// Another thought I had: we can compose an object with a function, without calling the function, and save that.
// Doing so creates a sort of "bundle" with the function and a built-in $obj. But what about allowing the same thing
// with a pre-composed, or bundled, $arg? So maybe we allow this:
// saved = my_obj -> my_func < my_arg >
// Then that can be saved and called later. It can also be composed later, so we might see something like this:
// oth_obj -> saved( oth_args... )
// And in this case, the $obj will be equivalent to `oth_obj -> my_obj` and the $arg will be equivalent to oth_args replayed
// on top of (i.e. overwriting) my_arg.
// The thing to note here is that the object provided at the call will be composed "behind" the original (searched last),
// but the args will be combined with original, replacing any that have the same key. Another way to think about this is $args will not be
// composed into a hierarchy. There is only 1 $args and if it composed multiple times, it will be the result of overwriting each time. And during function execution, the $arg scope will be marked as "read-only" so attempts to modify it will blow up.
// Another thing I want to provide for is composing and defining at the same time. This allows for a form of inheritance.
// So instead of this:
// copy = base_obj
// a = copy -> [] // or however we designate an empty array? maybe with a comma?
// with a
// ...
// // update: based on my answer below dated 2017-04-18, we could write the example like this:
// a = ~~base_obj -> []
// with a
// ...
// All of the above can be accomplished with:
// a <- base_obj
// ...
// Something to note: normally composing would create a reference to the original objects, but in this case we probably don't want a reference,
// we want a copy. So what mechanism do we have to allow the alternative? In other words, how do we get a copy of `base_obj`, if that is what we want, in the following:
// a = base_obj -> []
// instead of a reference, which would be the normal result?
// [2017-04-18] I know the answer: we use expansion:
// a = ~~base_obj -> []
// That will make a composition of a _copy_ of `base_obj`above an empty object and the result will be stored in `a`.
// So maybe the one remaining question is how do we assign a reference of an object? or store a reference to an object:
// a = ( parent=<ref to some object>, name="fred" )
// The C-like syntax (also PHP) would be to use `&` as a prefix in front of the object name.
// [Updated on 2017-04-17] When composing, we can assign a "badge" to an object so that we can do name lookup directly on that object,
// rather than up the normal hierarchy chain.
// Use the pound sign (octothorp) to badge an object during composition:
// base_obj#base -> oth_obj#child -> some_func()
// Later use the ampersand to access the badged object directly (for example inside a function with an $obj in scope):
// @base.parent_func()
// Or, if we are saving the composition:
// comp = base_obj#base -> oth_obj#child
// [email protected]_func() //(1)
// comp.some_func() //(2)
// Version 1 will grab the function `some_func` defined on the original base_obj array, ignoring it if it exists on `oth_obj`; whereas version 2
// will undergo a normal name resolution search starting with `oth_obj`.
// Also need to sort out how strong and weak references will work. They only make sense in assignments
// (so a new name is pointing at a reference to an existing name) or maybe return statements from functions.
// This includes assignments that are happening inside an array construction. Let's go see how PHP handles this.
grammar Wry;
tokens { INDENT, DEDENT }
@lexer::members {
private boolean pendingDent = true; // Starting out `true` means we'll capture any whitespace at the beginning of the script.
private int indentCount = 0;
private java.util.LinkedList<Token> tokenQueue = new java.util.LinkedList<>();
private java.util.Stack<Integer> indentStack = new java.util.Stack<>();
private Token initialIndentToken = null;
private int getSavedIndent() { return indentStack.isEmpty() ? 0 : indentStack.peek(); }
private CommonToken createToken(int type, String text, Token next) {
CommonToken token = new CommonToken(type, text);
if (null != initialIndentToken) {
token.setStartIndex(initialIndentToken.getStartIndex());
token.setLine(initialIndentToken.getLine());
token.setCharPositionInLine(initialIndentToken.getCharPositionInLine());
token.setStopIndex(next.getStartIndex()-1);
}
return token;
}
@Override
public Token nextToken() {
// Return tokens from the queue if it is not empty.
if (!tokenQueue.isEmpty()) { return tokenQueue.poll(); }
// Grab the next token and if nothing special is needed, simply return it.
Token next = super.nextToken();
//NOTE: This would be the appropriate spot to count whitespace or deal with NEWLINES, but it is already handled with custom actions down in the lexer rules.
if (pendingDent && null == initialIndentToken && NEWLINE != next.getType()) { initialIndentToken = next; }
if (null == next || HIDDEN == next.getChannel() || NEWLINE == next.getType()) { return next; }
// Handle EOF; in particular, handle an abrupt EOF that comes without an immediately preceding NEWLINE.
if (next.getType() == EOF) {
indentCount = 0;
// EOF outside of `pendingDent` state means we did not have a final NEWLINE before the end of file.
if (!pendingDent) {
initialIndentToken = next;
tokenQueue.offer(createToken(NEWLINE, "NEWLINE", next));
}
}
// Before exiting `pendingDent` state we need to queue up proper INDENTS and DEDENTS.
while (indentCount != getSavedIndent()) {
if (indentCount > getSavedIndent()) {
indentStack.push(indentCount);
tokenQueue.offer(createToken(WryParser.INDENT, "INDENT" + indentCount, next));
} else {
indentStack.pop();
tokenQueue.offer(createToken(WryParser.DEDENT, "DEDENT"+getSavedIndent(), next));
}
}
pendingDent = false;
tokenQueue.offer(next);
return tokenQueue.poll();
}
}
script
: ( NEWLINE | statement )* EOF
;
/*
* statement
*/
statement
: inlineStatementList NEWLINE
| compoundStatement
;
inlineStatementList
: smallStatement ( ';' smallStatement )* ';'? ;
/*
* smallStatement
*/
smallStatement
: flowStatement
| topExpr
| assignStatement
;
assignStatement
: nameRef '=' topExpr
// we need the expr ':' expr alternate here, but that leftside expression can be a limited set (not, for example expr'='expr)
;
flowStatement
: 'break' inlineStatementList? Label?
| 'continue' inlineStatementList? Label?
| 'return' topExpr
| 'throw' topExpr
// | 'assert' topExpr
// | 'yield' topExpr
;
/*
* compound statement
*/
compoundStatement
: ifStatement
| doStatement
| forStatement
| tryStatement
| withStatement
| assignBlock
;
ifStatement
: 'if' topExpr doableBlock ( 'else' 'if' topExpr doableBlock )* ( 'else' doableBlock )?
;
doStatement
: 'do' ( Label )? block ( 'then' block )?
| 'do' 'if' topExpr ( Label )? block ( 'then' block )?
;
forStatement
: 'for' topExpr ( Label )? block ( 'then' block )?
| 'for' topExpr 'if' topExpr ( Label )? block ( 'then' block )?
;
tryStatement
: 'try' doableBlock ( 'catch' 'if' topExpr doableBlock )* ( 'catch' doableBlock )?
;
withStatement
: 'with' nameRef block
;
assignBlock
: nameRef blockStatements
| topExpr ':' blockStatements
;
block
: inlineStatementList NEWLINE
| blockStatements
;
blockStatements
: NEWLINE INDENT statement+ DEDENT
;
doableBlock
: block
| doStatement
| forStatement
;
topExpr
: expr ( ',' expr)* ','?
| '(' topExpr ')'
;
expr
: expr '->' expr #composeExpr
| expr '(' expr? ')' #executeExpr
| expr '<' expr '>' #argExpr
| sign=( PLUS | MINUS ) expr #unarySignExpr
| NOT expr #notExpr
| expr op=( MULT | DIV | MOD ) expr #multExpr
| expr op=( PLUS | MINUS ) expr #addExpr
| expr op=( LTEQ | GTEQ | LT | GT ) expr #relationExpr
| expr AND expr #andExpr
| expr OR expr #orExpr
| nameRef '=' expr #nameAssignExpr
| expr ':' expr #assignExpr
| '(' expr ')' #groupExpr
| atom #atomExpr
;
NOT : '!' ;
MULT : '*' | '×' ;
DIV : '/' | '÷' ;
MOD : '%' ;
PLUS : '+' ;
MINUS : '-' ;
LTEQ : '<=' | '≤' ;
GTEQ : '≥' | '>=' ;
LT : '<' ;
GT : '>' ;
AND : '&&' | '∧' ;
OR : '||' | '∨' ;
functionExpression
: '{' inlineStatementList '}'
;
// funcBlock
// : inlineStatementList
// | blockStatements
// ;
atom
: nameExpression
| functionExpression
| literal
| TildeName
| DubTildeName
;
TildeName : '~' Name ;
DubTildeName : '~~' Name ;
/*
* names
*/
nameRef
: Name trailer*
;
trailer
: '[' expr ']'
| '.' PlainName
;
PlainName : NameHead NameChar* ;
nameExpression
: nameRef
| '&' nameRef
| '&&' nameRef
;
Name
: PlainName
| SpecialName
;
fragment NameHead : [_a-zA-Z] ;
fragment NameChar : [0-9] | NameHead ;
SpecialName : '$' PlainName ;
Label : '#' NameChar+ ;
/*
* What does it mean to type `&a.fred` as opposed to `a.&fred`? I don't think we want to put the & in the middle of the dot operator. So it seems more natural to come first.
* So does that make it a token? Or is it an operator?
* It can't be just in front of a name, it needs to be in front of a reference.
* Will this ever be used other than in assignment? YES: it could be in a return statement or in an array assignment used as an argument to a function.
* So it seems like it is part of object reference, not really an operator
*/
/*
* literals
*/
literal
: numericLiteral
| StringLiteral
| booleanLiteral
| nullLiteral
;
booleanLiteral : 'true' | 'false' ;
nullLiteral : 'null' ;
numericLiteral
: integerLiteral
| FloatingPointLiteral
;
/*
* integer literal
*/
integerLiteral
: BinaryLiteral
| OctalLiteral
| DecimalLiteral
| DozenalLiteral
| HexadecimalLiteral
;
BinaryLiteral : '0b' BinDigit ( BinDigit | '_' )* ;
fragment BinDigit : [01] ;
OctalLiteral : '0o' OctDigit ( OctDigit | '_' )* ;
fragment OctDigit : [0-7] ;
DecimalLiteral : DecDigit ( DecDigit | '_' )* ;
fragment DecDigit : [0-9] ;
DozenalLiteral : '0d' DozDigit ( DozDigit | '_' )* ;
fragment DozDigit : [0-9xeXE] ;
HexadecimalLiteral : '0x' HexDigit HexChars? ;
fragment HexDigit : [0-9a-fA-F] ;
fragment HexChars : ( HexDigit | '_' )+ ;
/*
* floating point literal
*/
FloatingPointLiteral
: DecimalLiteral ( '.' DecimalLiteral )? DecimalExponent?
| HexadecimalLiteral ( '.' HexDigit HexChars? )? HexadecimalExponent?
;
fragment DecimalExponent : [eE] (PLUS|MINUS)? DecimalLiteral ;
fragment HexadecimalExponent : [pP] (PLUS|MINUS)? DecimalLiteral ;
/*
* string literal
*/
StringLiteral
: '"' ( StringEscapeChar | ~[\r\n\\"] )*? '"'
| '\'' ( StringEscapeChar | ~[\r\n\\'] )*? '\''
;
fragment
StringEscapeChar
: '\\' [0\\tnr"']
| '\\x' HexDigit HexDigit
| '\\u' '{' HexDigit HexDigit HexDigit HexDigit '}'
| '\\u' '{' HexDigit HexDigit HexDigit HexDigit HexDigit HexDigit HexDigit HexDigit '}'
;
/*
* comments and whitespace
*/
BlockComment : '/*' ( BlockComment | . )*? '*/' -> channel(HIDDEN) ; // allow nesting comments
LineComment : '//' ~[\r\n]* -> channel(HIDDEN) ;
NEWLINE : ( '\r'? '\n' | '\r' ) { if (pendingDent) { setChannel(HIDDEN); } pendingDent = true; indentCount = 0; initialIndentToken = null; } ;
WS : [ \t]+ { setChannel(HIDDEN); if (pendingDent) { indentCount += getText().length(); } } ; //TODO: Swift includes \u000B, \u000C, and \u0000
|
/*
* Wry.g4
*
* ANTLR4 grammar for wry.
*
* Author: Mike Weaver
* Created: 2017-03-15
*
*/
// Another thought I had: we can compose an object with a function, without calling the function, and save that.
// Doing so creates a sort of "bundle" with the function and a built-in $obj. But what about allowing the same thing
// with a pre-composed, or bundled, $arg? So maybe we allow this:
// saved = my_obj -> my_func < my_arg >
// Then that can be saved and called later. It can also be composed later, so we might see something like this:
// oth_obj -> saved( oth_args... )
// And in this case, the $obj will be equivalent to `oth_obj -> my_obj` and the $arg will be equivalent to oth_args replayed
// on top of (i.e. overwriting) my_arg.
// The thing to note here is that the object provided at the call will be composed "behind" the original (searched last),
// but the args will be combined with original, replacing any that have the same key. Another way to think about this is $args will not be
// composed into a hierarchy. There is only 1 $args and if it composed multiple times, it will be the result of overwriting each time. And during function execution, the $arg scope will be marked as "read-only" so attempts to modify it will blow up.
// Another thing I want to provide for is composing and defining at the same time. This allows for a form of inheritance.
// So instead of this:
// copy = base_obj
// a = copy -> [] // or however we designate an empty array? maybe with a comma?
// with a
// ...
// // update: based on my answer below dated 2017-04-18, we could write the example like this:
// a = ~~base_obj -> []
// with a
// ...
// All of the above can be accomplished with:
// a <- base_obj
// ...
// Something to note: normally composing would create a reference to the original objects, but in this case we probably don't want a reference,
// we want a copy. So what mechanism do we have to allow the alternative? In other words, how do we get a copy of `base_obj`, if that is what we want, in the following:
// a = base_obj -> []
// instead of a reference, which would be the normal result?
// [2017-04-18] I know the answer: we use expansion:
// a = ~~base_obj -> []
// That will make a composition of a _copy_ of `base_obj`above an empty object and the result will be stored in `a`.
// So maybe the one remaining question is how do we assign a reference of an object? or store a reference to an object:
// a = ( parent=<ref to some object>, name="fred" )
// The C-like syntax (also PHP) would be to use `&` as a prefix in front of the object name.
// [Updated on 2017-04-17] When composing, we can assign a "badge" to an object so that we can do name lookup directly on that object,
// rather than up the normal hierarchy chain.
// Use the pound sign (octothorp) to badge an object during composition:
// base_obj#base -> oth_obj#child -> some_func()
// Later use the ampersand to access the badged object directly (for example inside a function with an $obj in scope):
// @base.parent_func()
// Or, if we are saving the composition:
// comp = base_obj#base -> oth_obj#child
// [email protected]_func() //(1)
// comp.some_func() //(2)
// Version 1 will grab the function `some_func` defined on the original base_obj array, ignoring it if it exists on `oth_obj`; whereas version 2
// will undergo a normal name resolution search starting with `oth_obj`.
// Also need to sort out how strong and weak references will work. They only make sense in assignments
// (so a new name is pointing at a reference to an existing name) or maybe return statements from functions.
// This includes assignments that are happening inside an array construction. Let's go see how PHP handles this.
grammar Wry;
tokens { INDENT, DEDENT }
@lexer::members {
private boolean pendingDent = true; // Starting out `true` means we'll capture any whitespace at the beginning of the script.
private int indentCount = 0;
private java.util.LinkedList<Token> tokenQueue = new java.util.LinkedList<>();
private java.util.Stack<Integer> indentStack = new java.util.Stack<>();
private Token initialIndentToken = null;
private int getSavedIndent() { return indentStack.isEmpty() ? 0 : indentStack.peek(); }
private CommonToken createToken(int type, String text, Token next) {
CommonToken token = new CommonToken(type, text);
if (null != initialIndentToken) {
token.setStartIndex(initialIndentToken.getStartIndex());
token.setLine(initialIndentToken.getLine());
token.setCharPositionInLine(initialIndentToken.getCharPositionInLine());
token.setStopIndex(next.getStartIndex()-1);
}
return token;
}
@Override
public Token nextToken() {
// Return tokens from the queue if it is not empty.
if (!tokenQueue.isEmpty()) { return tokenQueue.poll(); }
// Grab the next token and if nothing special is needed, simply return it.
Token next = super.nextToken();
//NOTE: This would be the appropriate spot to count whitespace or deal with NEWLINES, but it is already handled with custom actions down in the lexer rules.
if (pendingDent && null == initialIndentToken && NEWLINE != next.getType()) { initialIndentToken = next; }
if (null == next || HIDDEN == next.getChannel() || NEWLINE == next.getType()) { return next; }
// Handle EOF; in particular, handle an abrupt EOF that comes without an immediately preceding NEWLINE.
if (next.getType() == EOF) {
indentCount = 0;
// EOF outside of `pendingDent` state means we did not have a final NEWLINE before the end of file.
if (!pendingDent) {
initialIndentToken = next;
tokenQueue.offer(createToken(NEWLINE, "NEWLINE", next));
}
}
// Before exiting `pendingDent` state we need to queue up proper INDENTS and DEDENTS.
while (indentCount != getSavedIndent()) {
if (indentCount > getSavedIndent()) {
indentStack.push(indentCount);
tokenQueue.offer(createToken(WryParser.INDENT, "INDENT" + indentCount, next));
} else {
indentStack.pop();
tokenQueue.offer(createToken(WryParser.DEDENT, "DEDENT"+getSavedIndent(), next));
}
}
pendingDent = false;
tokenQueue.offer(next);
return tokenQueue.poll();
}
}
script
: ( NEWLINE | statement )* EOF
;
/*
* statement
*/
statement
: inlineStatementList NEWLINE
| compoundStatement
;
inlineStatementList
: smallStatement ( ';' smallStatement )* ';'? ;
/*
* smallStatement
*/
smallStatement
: flowStatement
| exprList
;
flowStatement
: 'break' inlineStatementList? Label?
| 'continue' inlineStatementList? Label?
| 'return' exprList
| 'throw' exprList
// | 'assert' exprList
// | 'yield' exprList
;
/*
* compound statement
*/
compoundStatement
: ifStatement
| doStatement
| forStatement
| tryStatement
| withStatement
| assignBlock
;
ifStatement
: 'if' exprList doableBlock ( 'else' 'if' exprList doableBlock )* ( 'else' doableBlock )?
;
doStatement
: 'do' ( Label )? block ( 'then' block )?
| 'do' 'if' exprList ( Label )? block ( 'then' block )?
;
forStatement
: 'for' exprList ( Label )? block ( 'then' block )?
| 'for' exprList 'if' exprList ( Label )? block ( 'then' block )?
;
tryStatement
: 'try' doableBlock ( 'catch' 'if' exprList doableBlock )* ( 'catch' doableBlock )?
;
withStatement
: 'with' nameRef block
;
assignBlock
: nameRef blockStatements
| exprList ':' blockStatements
;
block
: inlineStatementList NEWLINE
| blockStatements
;
blockStatements
: NEWLINE INDENT statement+ DEDENT
;
doableBlock
: block
| doStatement
| forStatement
;
exprList
: expr ( ',' expr)* ','?
;
expr
: '(' exprList ')' #groupExpr
| expr '->' expr #composeExpr
| expr '(' expr? ')' #executeExpr
| expr '<' expr '>' #argExpr
| sign=( PLUS | MINUS ) expr #unarySignExpr
| NOT expr #notExpr
| expr op=( MULT | DIV | MOD ) expr #multExpr
| expr op=( PLUS | MINUS ) expr #addExpr
| expr op=( LTEQ | GTEQ | LT | GT ) expr #relationExpr
| expr AND expr #andExpr
| expr OR expr #orExpr
| nameRef '=' expr #assignExpr
|<assoc=right> expr ':' expr #assocExpr
| atom #atomExpr
;
NOT : '!' ;
MULT : '*' | '×' ;
DIV : '/' | '÷' ;
MOD : '%' ;
PLUS : '+' ;
MINUS : '-' ;
LTEQ : '<=' | '≤' ;
GTEQ : '≥' | '>=' ;
LT : '<' ;
GT : '>' ;
AND : '&&' | '∧' ;
OR : '||' | '∨' ;
functionExpression
: '{' inlineStatementList '}'
;
// funcBlock
// : inlineStatementList
// | blockStatements
// ;
atom
: nameExpression
| functionExpression
| literal
| TildeName
| DubTildeName
;
TildeName : '~' Name ;
DubTildeName : '~~' Name ;
/*
* names
*/
nameExpression
: nameRef
| '&' nameRef
| '&&' nameRef
;
nameRef
: Name trailer*
;
trailer
: '[' expr ']'
| '.' PlainName
;
Name
: PlainName
| SpecialName
;
PlainName : NameHead NameChar* ;
fragment NameHead : [_a-zA-Z] ;
fragment NameChar : [0-9] | NameHead ;
SpecialName : '$' PlainName ;
Label : '#' NameChar+ ;
/*
* What does it mean to type `&a.fred` as opposed to `a.&fred`? I don't think we want to put the & in the middle of the dot operator. So it seems more natural to come first.
* So does that make it a token? Or is it an operator?
* It can't be just in front of a name, it needs to be in front of a reference.
* Will this ever be used other than in assignment? YES: it could be in a return statement or in an array assignment used as an argument to a function.
* So it seems like it is part of object reference, not really an operator
*/
/*
* literals
*/
literal
: numericLiteral
| StringLiteral
| booleanLiteral
| nullLiteral
;
booleanLiteral : 'true' | 'false' ;
nullLiteral : 'null' ;
numericLiteral
: integerLiteral
| FloatingPointLiteral
;
/*
* integer literal
*/
integerLiteral
: BinaryLiteral
| OctalLiteral
| DecimalLiteral
| DozenalLiteral
| HexadecimalLiteral
;
BinaryLiteral : '0b' BinDigit ( BinDigit | '_' )* ;
fragment BinDigit : [01] ;
OctalLiteral : '0o' OctDigit ( OctDigit | '_' )* ;
fragment OctDigit : [0-7] ;
DecimalLiteral : DecDigit ( DecDigit | '_' )* ;
fragment DecDigit : [0-9] ;
DozenalLiteral : '0d' DozDigit ( DozDigit | '_' )* ;
fragment DozDigit : [0-9xeXE] ;
HexadecimalLiteral : '0x' HexDigit HexChars? ;
fragment HexDigit : [0-9a-fA-F] ;
fragment HexChars : ( HexDigit | '_' )+ ;
/*
* floating point literal
*/
FloatingPointLiteral
: DecimalLiteral ( '.' DecimalLiteral )? DecimalExponent?
| HexadecimalLiteral ( '.' HexDigit HexChars? )? HexadecimalExponent?
;
fragment DecimalExponent : [eE] (PLUS|MINUS)? DecimalLiteral ;
fragment HexadecimalExponent : [pP] (PLUS|MINUS)? DecimalLiteral ;
/*
* string literal
*/
StringLiteral
: '"' ( StringEscapeChar | ~[\r\n\\"] )*? '"'
| '\'' ( StringEscapeChar | ~[\r\n\\'] )*? '\''
;
fragment
StringEscapeChar
: '\\' [0\\tnr"']
| '\\x' HexDigit HexDigit
| '\\u' '{' HexDigit HexDigit HexDigit HexDigit '}'
| '\\u' '{' HexDigit HexDigit HexDigit HexDigit HexDigit HexDigit HexDigit HexDigit '}'
;
/*
* comments and whitespace
*/
BlockComment : '/*' ( BlockComment | . )*? '*/' -> channel(HIDDEN) ; // allow nesting comments
LineComment : '//' ~[\r\n]* -> channel(HIDDEN) ;
NEWLINE : ( '\r'? '\n' | '\r' ) { if (pendingDent) { setChannel(HIDDEN); } pendingDent = true; indentCount = 0; initialIndentToken = null; } ;
WS : [ \t]+ { setChannel(HIDDEN); if (pendingDent) { indentCount += getText().length(); } } ; //TODO: Swift includes \u000B, \u000C, and \u0000
|
drop assignment statement and let them be expressions
|
drop assignment statement and let them be expressions
It's tricky to distinguish between assignments as statements and
expressions. I think I'll let them always be expressions, and our
listener will sort it out.
|
ANTLR
|
mit
|
wevrem/wry
|
d2c455c1a2b478445279319c72b65d85324fee63
|
Twee2Z/Analyzer/LEX.g4
|
Twee2Z/Analyzer/LEX.g4
|
lexer grammar LEX;
/*
* Lexer Rules
*/
// special symbols
INT : DIGIT+;
MACRO_START : MACRO_BRACKET_OPEN -> pushMode(MMode);
LINK_START : '[[' -> pushMode(LMode);
FUNC_START : FUNC_NAME -> pushMode(FMode);
VAR_NAME : DOLLAR (LETTER|LOW_LINE) (LETTER|DIGIT|LOW_LINE)*;
ITALIC_BEGIN : '//' -> pushMode(ItalicMode);
UNDERLINE_BEGIN : '__' -> pushMode(UnderlineMode);
STRIKEOUT_BEGIN : '==' -> pushMode(StrikeoutMode);
SUPERSCRIPT_BEGIN : '^^' -> pushMode(SuperscriptMode);
SUBSCRIPT_BEGIN : '~~' -> pushMode(SubscriptMode);
MONOSPACE_BEGIN : '{{{' -> pushMode(MonospaceMode);
COMMENT_BEGIN : '/%' -> pushMode(CommentMode);
STRING : STRING_START STRING_BODY STRING_END;
WORD : ~('0'..'9'|'\r'|'\n'|'['|']'|' '|'"'); //<-PIPE hinzugefuegt wegen Link, ist noch zu beheben
// ('''' | '//' | '__' | '==' | '^^' | '~~' | '{{{' | '/%' | '@@')
SPACE : ' ';
NEW_LINE : ('\r' | '\n' | '\r\n');
PASS : ':'(':'+);
// normal symbols
fragment LETTER: [a-zA-Z];
fragment DIGIT : [0-9];
fragment DOUBLE_DOT : ':';
fragment EXCLAMATION_MARK :'!';
fragment POINT : '.';
fragment COMMA : ',';
fragment SEMICOLON : ';';
fragment LOW_LINE : '_';
fragment QUOTE : '"';
fragment DOLLAR : '$';
// TAG-MODE
TAGS : SQ_BRACKET_OPEN SPACE* TAG_WORDS (SPACE+ TAG_WORDS)* SPACE* SQ_BRACKET_CLOSE;
fragment TAG_WORDS : (INT|WORD)+;
fragment TAG_BRACKET_CLOSE : ']';
fragment TAG_BRACKET_OPEN : '[';
// STRING-MODE
STRING_START : QUOTE -> pushMode(SMode);
mode SMode;
STRING_BODY : .*?;
STRING_END : QUOTE -> popMode;
// FUNCTION-MODE
mode FMode;
FUNC_NAME : 'random' | 'either' | 'visited' | 'visitedTag' | 'turns' | 'confirm' | 'prompt';
FUNC_PARAM : ((STRING) (COMMA SPACE* (STRING))*)?;
FUNC_BRACKET_OPEN : '(';
FUNC_BRACKET_CLOSE : ')' -> popMode;
// MAKRO-MODE
mode MMode;
FOR : 'for' 'in' SPACE*;
ENDFOR : 'endfor' SPACE*;
IF : 'if' SPACE*;
ELSE_IF : 'else if' SPACE*;
ELSE : 'else' SPACE*;
ENDIF : 'endif' SPACE*;
NOBR : 'nobr' SPACE*;
ENDNOBR : 'endnobr' SPACE*;
SILENTLY : 'silently' SPACE*;
ENDSILENTLY : 'endsilently' SPACE*;
ACTIONS : 'actions' SPACE*;
CHOICE : 'choice' SPACE* ;
RADIO : 'radio' SPACE* ;
DISPLAY : 'display' (NEW_LINE|SPACE)*;
SET : 'set' (NEW_LINE|SPACE)*;
PRINT : 'print' (NEW_LINE|SPACE)*;
MACRO_BRACKET_OPEN : '<<';
MACRO_END : '>>' -> popMode;
// ESPRESSION-MODE
EXPRESSION_FORM : (EXPRESSION_START EXPRESSION_CONTENT);
EXPRESSION_START : (VAR_NAME | STRING | LETTER+ | (NOT|ADD|SUB)? INT) -> pushMode(EMode);
mode EMode;
EXPRESSION_CONTENT : ((((NOT|ADD|SUB) EXPRESSION_CONTENT) | (SPACE* (LOG_OP|MOD|ADD|MUL|DIV|SUB) SPACE* EXPRESSION_END) | (FUNC_BRACKET_OPEN EXPRESSION_CONTENT FUNC_BRACKET_CLOSE)));
MUL : '*';
DIV : '/';
ADD : '+';
SUB : '-';
LOG_OP : 'is' | 'eq'|'neq'| 'and'| 'or'| '<'| 'lt'| '<='| 'lte'| '>'| 'gt'| '>='| 'gte';
MOD : '%';
EQ_SIGN: '=';
NOT : 'not';
LT : '<';
GT : '<';
EXPRESSION_END : (COMMA | FUNC_BRACKET_CLOSE) -> popMode;// (SQ_BRACKET_CLOSE|FUNC_BRACKET_CLOSE|LT) -> popMode;
// LINK-MODE
mode LMode;
FUNC_LINK : ('previous()' | 'start()' | 'passage()');
PIPE : '|';
SQ_BRACKET_CLOSE : ']';
SQ_BRACKET_OPEN : '[';
WORDS : EXPRESSION_START|WORD+; //<- nach unten weil sonst keine funk erkannt werden
LINK_END : ']]' -> popMode; //KEIN POPMODE VERWENDEN!
/*mode BoldMode;
BOLD_END : '''' -> popMode;
*/
// FORMAT-MODE
mode ItalicMode;
ITALIC_TEXT_SWITCH : ('='|'_'|'^'|'~'|'{'|'/%') -> pushMode(DEFAULT_MODE);
ITALIC_TEXT : .*?;
ITALIC_END : '//' -> popMode;
mode UnderlineMode;
UNDERLINE_TEXT_SWITCH : ('='|'//'|'^'|'~'|'{'|'/%') -> pushMode(DEFAULT_MODE);
UNDERLINE_TEXT : .*?;
UNDERLINE_END : '__' -> popMode;
mode StrikeoutMode;
STRIKEOUT_TEXT_SWITCH : ('//'|'_'|'^'|'~'|'{'|'/%') -> pushMode(DEFAULT_MODE);
STRIKEOUT_TEXT : .*?;
STRIKEOUT_END : '==' -> popMode;
mode SuperscriptMode;
SUPERSCRIPT_TEXT_SWITCH : ('='|'_'|'//'|'~'|'{'|'/%') -> pushMode(DEFAULT_MODE);
SUPERSCRIPT_TEXT : .*?;
SUPERSCRIPT_END : '^^' -> popMode;
mode SubscriptMode;
SUBSCRIPT_TEXT_SWITCH : ('='|'_'|'^'|'//'|'{'|'/%') -> pushMode(DEFAULT_MODE);
SUBSCRIPT_TEXT : .*?;
SUBSCRIPT_END : '~~' -> popMode;
mode MonospaceMode;
MONOSPACE_TEXT_SWITCH : ('='|'_'|'^'|'~'|'//'|'/%') -> pushMode(DEFAULT_MODE);
MONOSPACE_TEXT : ~[}];
MONOSPACE_END : '}}}' -> popMode;
mode CommentMode;
COMMENT_TEXT_SWITCH : ('='|'_'|'^'|'~'|'{'|'//') -> pushMode(DEFAULT_MODE);
COMMENT_TEXT : .*?;
COMMENT_END : '%/' -> popMode;
|
lexer grammar LEX;
/*
* Lexer Rules
*/
// special symbols
INT : DIGIT+;
MACRO_START : MACRO_BRACKET_OPEN -> pushMode(MMode);
LINK_START : '[[' -> pushMode(LMode);
FUNC_START : FUNC_NAME -> pushMode(FMode);
VAR_NAME : DOLLAR (LETTER|LOW_LINE) (LETTER|DIGIT|LOW_LINE)*;
ITALIC_BEGIN : '//' -> pushMode(ItalicMode);
UNDERLINE_BEGIN : '__' -> pushMode(UnderlineMode);
STRIKEOUT_BEGIN : '==' -> pushMode(StrikeoutMode);
SUPERSCRIPT_BEGIN : '^^' -> pushMode(SuperscriptMode);
SUBSCRIPT_BEGIN : '~~' -> pushMode(SubscriptMode);
MONOSPACE_BEGIN : '{{{' -> pushMode(MonospaceMode);
COMMENT_BEGIN : '/%' -> pushMode(CommentMode);
STRING : STRING_START STRING_BODY STRING_END;
WORD : ~('0'..'9'|'\r'|'\n'|'['|']'|' '|'"'); //<-PIPE hinzugefuegt wegen Link, ist noch zu beheben
// ('''' | '//' | '__' | '==' | '^^' | '~~' | '{{{' | '/%' | '@@')
SPACE : ' ';
NEW_LINE : ('\r' | '\n' | '\r\n');
PASS : ':'(':'+);
// normal symbols
fragment LETTER: [a-zA-Z];
fragment DIGIT : [0-9];
fragment DOUBLE_DOT : ':';
fragment EXCLAMATION_MARK :'!';
fragment POINT : '.';
fragment COMMA : ',';
fragment SEMICOLON : ';';
fragment LOW_LINE : '_';
fragment QUOTE : '"';
fragment DOLLAR : '$';
// TAG-MODE
TAGS : SQ_BRACKET_OPEN SPACE* TAG_WORDS (SPACE+ TAG_WORDS)* SPACE* SQ_BRACKET_CLOSE;
fragment TAG_WORDS : (INT|WORD)+;
fragment TAG_BRACKET_CLOSE : ']';
fragment TAG_BRACKET_OPEN : '[';
// STRING-MODE
STRING_START : QUOTE -> pushMode(SMode);
mode SMode;
STRING_BODY : .*?;
STRING_END : QUOTE -> popMode;
// FUNCTION-MODE
mode FMode;
FUNC_NAME : 'random' | 'either' | 'visited' | 'visitedTag' | 'turns' | 'confirm' | 'prompt';
FUNC_PARAM : ((STRING) (COMMA SPACE* (STRING))*)?;
FUNC_BRACKET_OPEN : '(';
FUNC_BRACKET_CLOSE : ')' -> popMode;
// MAKRO-MODE
mode MMode;
FOR : 'for' 'in' SPACE*;
ENDFOR : 'endfor' SPACE*;
IF : 'if' SPACE*;
ELSE_IF : 'else if' SPACE*;
ELSE : 'else' SPACE*;
ENDIF : 'endif' SPACE*;
NOBR : 'nobr' SPACE*;
ENDNOBR : 'endnobr' SPACE*;
SILENTLY : 'silently' SPACE*;
ENDSILENTLY : 'endsilently' SPACE*;
ACTIONS : 'actions' SPACE*;
CHOICE : 'choice' SPACE* ;
RADIO : 'radio' SPACE* ;
DISPLAY : 'display' (NEW_LINE|SPACE)*;
SET : 'set' (NEW_LINE|SPACE)*;
PRINT : 'print' (NEW_LINE|SPACE)*;
MACRO_BRACKET_OPEN : '<<';
MACRO_END : '>>' -> popMode;
// ESPRESSION-MODE
EXPRESSION_FORM : (EXPRESSION_START EXPRESSION_CONTENT);
EXPRESSION_START : (VAR_NAME | STRING | LETTER+ | (NOT|ADD|SUB)? INT) -> pushMode(EMode);
mode EMode;
EXPRESSION_CONTENT : ((((NOT|ADD|SUB) EXPRESSION_CONTENT) | (SPACE* (LOG_OP|MOD|ADD|MUL|DIV|SUB) SPACE* EXPRESSION_END) | (FUNC_BRACKET_OPEN EXPRESSION_CONTENT FUNC_BRACKET_CLOSE)));
MUL : '*';
DIV : '/';
ADD : '+';
SUB : '-';
LOG_OP : 'is' | 'eq'|'neq'| 'and'| 'or'| '<'| 'lt'| '<='| 'lte'| '>'| 'gt'| '>='| 'gte';
MOD : '%';
EQ_SIGN: '=';
NOT : 'not';
LT : '<';
GT : '<';
EXPRESSION_END : (COMMA | FUNC_BRACKET_CLOSE) -> popMode;// (SQ_BRACKET_CLOSE|FUNC_BRACKET_CLOSE|LT) -> popMode;
// LINK-MODE
mode LMode;
FUNC_LINK : ('previous()' | 'start()' | 'passage()');
PIPE : '|';
SQ_BRACKET_CLOSE : ']';
SQ_BRACKET_OPEN : '[';
WORDS : EXPRESSION_START|WORD+; //<- nach unten weil sonst keine funk erkannt werden
LINK_END : ']]' -> popMode; //KEIN POPMODE VERWENDEN!
/*mode BoldMode;
BOLD_END : '''' -> popMode;
*/
// FORMAT-MODE
mode ItalicMode;
ITALIC_TEXT_SWITCH : ('='|'_'|'^'|'~'|'{'|'/%') -> pushMode(DEFAULT_MODE);
ITALIC_TEXT : ~[/];
ITALIC_END : '//' -> popMode;
mode UnderlineMode;
UNDERLINE_TEXT_SWITCH : ('='|'//'|'^'|'~'|'{'|'/%') -> pushMode(DEFAULT_MODE);
UNDERLINE_TEXT : ~[_];
UNDERLINE_END : '__' -> popMode;
mode StrikeoutMode;
STRIKEOUT_TEXT_SWITCH : ('//'|'_'|'^'|'~'|'{'|'/%') -> pushMode(DEFAULT_MODE);
STRIKEOUT_TEXT : ~[=];
STRIKEOUT_END : '==' -> popMode;
mode SuperscriptMode;
SUPERSCRIPT_TEXT_SWITCH : ('='|'_'|'//'|'~'|'{'|'/%') -> pushMode(DEFAULT_MODE);
SUPERSCRIPT_TEXT : ~[^];
SUPERSCRIPT_END : '^^' -> popMode;
mode SubscriptMode;
SUBSCRIPT_TEXT_SWITCH : ('='|'_'|'^'|'//'|'{'|'/%') -> pushMode(DEFAULT_MODE);
SUBSCRIPT_TEXT : ~[~];
SUBSCRIPT_END : '~~' -> popMode;
mode MonospaceMode;
MONOSPACE_TEXT_SWITCH : ('='|'_'|'^'|'~'|'//'|'/%') -> pushMode(DEFAULT_MODE);
MONOSPACE_TEXT : ~[}];
MONOSPACE_END : '}}}' -> popMode;
mode CommentMode;
COMMENT_TEXT_SWITCH : ('='|'_'|'^'|'~'|'{'|'//') -> pushMode(DEFAULT_MODE);
COMMENT_TEXT : ~[%/];
COMMENT_END : '%/' -> popMode;
|
Update Formats
|
Update Formats
|
ANTLR
|
mit
|
humsp/uebersetzerbauSWP
|
77fdc652015856a0cc1461a91685d4f196f97140
|
java-vtl-parser/src/main/antlr4/no/ssb/vtl/parser/VTL.g4
|
java-vtl-parser/src/main/antlr4/no/ssb/vtl/parser/VTL.g4
|
/*-
* #%L
* Java VTL
* %%
* Copyright (C) 2016 Hadrien Kohl
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
grammar VTL;
start : assignment+ EOF;
/* Assignment */
assignment : identifier ASSIGNMENT datasetExpression
| identifier ASSIGNMENT block
;
block : '{' assignment+ '}' ;
/* Expressions */
datasetExpression : <assoc=right>datasetExpression clauseExpression #withClause
| relationalExpression #withRelational
| function #withFunction
| exprAtom #withAtom
;
function: getFunction #withGet
| putFunction #withPut
| checkFunction #withCheck
;
getFunction : 'get' '(' datasetId ')';
putFunction : 'put(todo)';
datasetId : STRING_CONSTANT ;
/* Atom */
exprAtom : variableRef;
checkFunction : 'check' '(' checkParam ')';
checkParam : datasetExpression (',' checkRows)? (',' checkColumns)? ( 'errorcode' '(' errorCode ')' )? ( 'errorlevel' '=' '(' errorLevel ')' )?;
checkRows : ( 'not_valid' | 'valid' | 'all' ) ;
checkColumns : ( 'measures' | 'condition' ) ;
errorCode : STRING_CONSTANT ;
errorLevel : INTEGER_CONSTANT ;
datasetRef: variableRef ;
componentRef : ( datasetRef '.')? variableRef ;
variableRef : identifier;
identifier : IDENTIFIER ;
constant : INTEGER_CONSTANT | FLOAT_CONSTANT | BOOLEAN_CONSTANT | STRING_CONSTANT | NULL_CONSTANT;
clauseExpression : '[' clause ']' ;
clause : 'rename' renameParam (',' renameParam)* #renameClause
| filter #filterClause
| keep #keepClause
| calc #calcClause
| attrcalc #attrcalcClause
| aggregate #aggregateClause
;
// [ rename component as string,
// component as string role = IDENTIFIER,
// component as string role = MEASURE,
// component as string role = ATTRIBUTE
// ]
renameParam : from=componentRef 'as' to=identifier ( 'role' role )? ;
role : ( 'IDENTIFIER' | 'MEASURE' | 'ATTRIBUTE' ) ;
filter : 'filter' booleanExpression ;
keep : 'keep' booleanExpression ( ',' booleanExpression )* ;
calc : 'calc' ;
attrcalc : 'attrcalc' ;
aggregate : 'aggregate' ;
//varID : 'varId';
//WS : [ \t\n\t] -> skip ;
booleanExpression //Evaluation order of the operators
: '(' booleanExpression ')' # BooleanPrecedence // I
| ISNULL_FUNC '(' booleanParam ')' # BooleanIsNullFunction // II All functional operators
| booleanParam op=(ISNULL|ISNOTNULL) # BooleanPostfix // ??
| left=booleanParam op=( LE | LT | GE | GT ) right=booleanParam # BooleanEquality // VII
| op=NOT booleanExpression # BooleanNot // IV
| left=booleanParam op=( EQ | NE ) right=booleanParam # BooleanEquality // IX
| booleanExpression op=AND booleanExpression # BooleanAlgebra // X
| booleanExpression op=(OR|XOR) booleanExpression # BooleanAlgebra // XI
| BOOLEAN_CONSTANT # BooleanConstant
;
booleanParam
: componentRef
| constant
;
ASSIGNMENT : ':=' ;
EQ : '=' ;
NE : '<>' ;
LE : '<=' ;
LT : '<' ;
GE : '>=' ;
GT : '>' ;
AND : 'and' ;
OR : 'or' ;
XOR : 'xor' ;
NOT : 'not' ;
ISNULL : 'is null' ;
ISNOTNULL : 'is not null' ;
ISNULL_FUNC : 'isnull' ;
//WS : [ \r\t\u000C] -> skip ;
relationalExpression : unionExpression | joinExpression ;
unionExpression : 'union' '(' datasetExpression (',' datasetExpression )* ')' ;
joinExpression : '[' joinDefinition ']' '{' joinBody '}';
joinDefinition : type=( INNER | OUTER | CROSS )? datasetRef (',' datasetRef )* ( 'on' componentRef (',' componentRef )* )? ;
joinBody : joinClause (',' joinClause)* ;
// TODO: Implement role and implicit
joinClause : role? identifier ASSIGNMENT joinCalcExpression # joinCalcClause
| joinDropExpression # joinDropClause
| joinKeepExpression # joinKeepClause
| joinRenameExpression # joinRenameClause
| joinFilterExpression # joinFilterClause
| joinFoldExpression # joinFoldClause
| joinUnfoldExpression # joinUnfoldClause
;
// TODO: The spec writes examples with parentheses, but it seems unecessary to me.
// TODO: The spec is unclear regarding types of the elements, we support only strings ATM.
joinFoldExpression : 'fold' componentRef (',' componentRef)* 'to' dimension=identifier ',' measure=identifier ;
joinUnfoldExpression : 'unfold' dimension=componentRef ',' measure=componentRef 'to' STRING_CONSTANT (',' STRING_CONSTANT)* ;
conditionalExpression
: nvlExpression
;
nvlExpression : 'nvl' '(' componentRef ',' nvlRepValue=constant ')';
dateFunction
: dateFromStringFunction
;
dateFromStringFunction : 'date_from_string' '(' componentRef ',' format=STRING_CONSTANT ')';
// Left recursive
joinCalcExpression : leftOperand=joinCalcExpression sign=( '*' | '/' ) rightOperand=joinCalcExpression #joinCalcProduct
| leftOperand=joinCalcExpression sign=( '+' | '-' ) rightOperand=joinCalcExpression #joinCalcSummation
| '(' joinCalcExpression ')' #joinCalcPrecedence
| conditionalExpression #joinCalcCondition
| dateFunction #joinCalcDate
| componentRef #joinCalcReference
| constant #joinCalcAtom
| booleanExpression #joinCalcBoolean
;
// Drop clause
joinDropExpression : 'drop' componentRef (',' componentRef)* ;
// Keep clause
joinKeepExpression : 'keep' componentRef (',' componentRef)* ;
// TODO: Use in keep, drop and calc.
// TODO: Make this the membership operator.
// TODO: Revise this when the final version of the specification precisely define if the rename needs ' or not.
// Rename clause
joinRenameExpression : 'rename' joinRenameParameter (',' joinRenameParameter)* ;
joinRenameParameter : from=componentRef 'to' to=identifier ;
// Filter clause
joinFilterExpression : 'filter' booleanExpression ;
//role : ( 'IDENTIFIER' | 'MEASURE' | 'ATTRIBUTE' ) ;
INNER : 'inner' ;
OUTER : 'outer' ;
CROSS : 'cross' ;
INTEGER_CONSTANT : DIGIT+;
BOOLEAN_CONSTANT : 'true' | 'false' ;
STRING_CONSTANT :'"' (~'"')* '"';
FLOAT_CONSTANT : (DIGIT)+ '.' (DIGIT)* FLOATEXP?
| (DIGIT)+ FLOATEXP
;
NULL_CONSTANT : 'null';
IDENTIFIER : REG_IDENTIFIER | ESCAPED_IDENTIFIER ;
//regular identifiers start with a (lowercase or uppercase) English alphabet letter, followed by zero or more letters, decimal digits, or underscores
REG_IDENTIFIER: LETTER(LETTER|'_'|DIGIT)* ; //TODO: Case insensitive??
//VTL 1.1 allows us to escape the limitations imposed on regular identifiers by enclosing them in single quotes (apostrophes).
fragment ESCAPED_IDENTIFIER: QUOTE (~['\r\n] | '\'\'')+ QUOTE;
fragment QUOTE : '\'';
PLUS : '+';
MINUS : '-';
fragment DIGIT : '0'..'9' ;
fragment FLOATEXP : ('e'|'E')(PLUS|MINUS)?('0'..'9')+;
fragment LETTER : 'A'..'Z' | 'a'..'z';
WS : [ \n\r\t\u000C] -> skip ;
COMMENT : '/*' .*? '*/' -> skip;
|
/*-
* #%L
* Java VTL
* %%
* Copyright (C) 2016 Hadrien Kohl
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
grammar VTL;
start : assignment+ EOF;
/* Assignment */
assignment : identifier ASSIGNMENT datasetExpression
| identifier ASSIGNMENT block
;
block : '{' assignment+ '}' ;
/* Expressions */
datasetExpression : <assoc=right>datasetExpression clauseExpression #withClause
| relationalExpression #withRelational
| function #withFunction
| exprAtom #withAtom
;
function : getFunction #withGet
| putFunction #withPut
| checkFunction #withCheck
| aggregationFunction #withAggregation
;
aggregationFunction: sumFunction;
getFunction : 'get' '(' datasetId ')';
putFunction : 'put(todo)';
sumFunction: 'sum' '(' datasetRef ')' ('group by'|'along') componentRef (',' componentRef)*;
datasetId : STRING_CONSTANT ;
/* Atom */
exprAtom : variableRef;
checkFunction : 'check' '(' checkParam ')';
checkParam : datasetExpression (',' checkRows)? (',' checkColumns)? ( 'errorcode' '(' errorCode ')' )? ( 'errorlevel' '=' '(' errorLevel ')' )?;
checkRows : ( 'not_valid' | 'valid' | 'all' ) ;
checkColumns : ( 'measures' | 'condition' ) ;
errorCode : STRING_CONSTANT ;
errorLevel : INTEGER_CONSTANT ;
datasetRef: variableRef ;
componentRef : ( datasetRef '.')? variableRef ;
variableRef : identifier;
identifier : IDENTIFIER ;
constant : INTEGER_CONSTANT | FLOAT_CONSTANT | BOOLEAN_CONSTANT | STRING_CONSTANT | NULL_CONSTANT;
clauseExpression : '[' clause ']' ;
clause : 'rename' renameParam (',' renameParam)* #renameClause
| filter #filterClause
| keep #keepClause
| calc #calcClause
| attrcalc #attrcalcClause
| aggregate #aggregateClause
;
// [ rename component as string,
// component as string role = IDENTIFIER,
// component as string role = MEASURE,
// component as string role = ATTRIBUTE
// ]
renameParam : from=componentRef 'as' to=identifier ( 'role' role )? ;
role : ( 'IDENTIFIER' | 'MEASURE' | 'ATTRIBUTE' ) ;
filter : 'filter' booleanExpression ;
keep : 'keep' booleanExpression ( ',' booleanExpression )* ;
calc : 'calc' ;
attrcalc : 'attrcalc' ;
aggregate : 'aggregate' ;
//varID : 'varId';
//WS : [ \t\n\t] -> skip ;
booleanExpression //Evaluation order of the operators
: '(' booleanExpression ')' # BooleanPrecedence // I
| ISNULL_FUNC '(' booleanParam ')' # BooleanIsNullFunction // II All functional operators
| booleanParam op=(ISNULL|ISNOTNULL) # BooleanPostfix // ??
| left=booleanParam op=( LE | LT | GE | GT ) right=booleanParam # BooleanEquality // VII
| op=NOT booleanExpression # BooleanNot // IV
| left=booleanParam op=( EQ | NE ) right=booleanParam # BooleanEquality // IX
| booleanExpression op=AND booleanExpression # BooleanAlgebra // X
| booleanExpression op=(OR|XOR) booleanExpression # BooleanAlgebra // XI
| BOOLEAN_CONSTANT # BooleanConstant
;
booleanParam
: componentRef
| constant
;
ASSIGNMENT : ':=' ;
EQ : '=' ;
NE : '<>' ;
LE : '<=' ;
LT : '<' ;
GE : '>=' ;
GT : '>' ;
AND : 'and' ;
OR : 'or' ;
XOR : 'xor' ;
NOT : 'not' ;
ISNULL : 'is null' ;
ISNOTNULL : 'is not null' ;
ISNULL_FUNC : 'isnull' ;
//WS : [ \r\t\u000C] -> skip ;
relationalExpression : unionExpression | joinExpression ;
unionExpression : 'union' '(' datasetExpression (',' datasetExpression )* ')' ;
joinExpression : '[' joinDefinition ']' '{' joinBody '}';
joinDefinition : type=( INNER | OUTER | CROSS )? datasetRef (',' datasetRef )* ( 'on' componentRef (',' componentRef )* )? ;
joinBody : joinClause (',' joinClause)* ;
// TODO: Implement role and implicit
joinClause : role? identifier ASSIGNMENT joinCalcExpression # joinCalcClause
| joinDropExpression # joinDropClause
| joinKeepExpression # joinKeepClause
| joinRenameExpression # joinRenameClause
| joinFilterExpression # joinFilterClause
| joinFoldExpression # joinFoldClause
| joinUnfoldExpression # joinUnfoldClause
;
// TODO: The spec writes examples with parentheses, but it seems unecessary to me.
// TODO: The spec is unclear regarding types of the elements, we support only strings ATM.
joinFoldExpression : 'fold' componentRef (',' componentRef)* 'to' dimension=identifier ',' measure=identifier ;
joinUnfoldExpression : 'unfold' dimension=componentRef ',' measure=componentRef 'to' STRING_CONSTANT (',' STRING_CONSTANT)* ;
conditionalExpression
: nvlExpression
;
nvlExpression : 'nvl' '(' componentRef ',' nvlRepValue=constant ')';
dateFunction
: dateFromStringFunction
;
dateFromStringFunction : 'date_from_string' '(' componentRef ',' format=STRING_CONSTANT ')';
// Left recursive
joinCalcExpression : leftOperand=joinCalcExpression sign=( '*' | '/' ) rightOperand=joinCalcExpression #joinCalcProduct
| leftOperand=joinCalcExpression sign=( '+' | '-' ) rightOperand=joinCalcExpression #joinCalcSummation
| '(' joinCalcExpression ')' #joinCalcPrecedence
| conditionalExpression #joinCalcCondition
| dateFunction #joinCalcDate
| componentRef #joinCalcReference
| constant #joinCalcAtom
| booleanExpression #joinCalcBoolean
;
// Drop clause
joinDropExpression : 'drop' componentRef (',' componentRef)* ;
// Keep clause
joinKeepExpression : 'keep' componentRef (',' componentRef)* ;
// TODO: Use in keep, drop and calc.
// TODO: Make this the membership operator.
// TODO: Revise this when the final version of the specification precisely define if the rename needs ' or not.
// Rename clause
joinRenameExpression : 'rename' joinRenameParameter (',' joinRenameParameter)* ;
joinRenameParameter : from=componentRef 'to' to=identifier ;
// Filter clause
joinFilterExpression : 'filter' booleanExpression ;
//role : ( 'IDENTIFIER' | 'MEASURE' | 'ATTRIBUTE' ) ;
INNER : 'inner' ;
OUTER : 'outer' ;
CROSS : 'cross' ;
INTEGER_CONSTANT : DIGIT+;
BOOLEAN_CONSTANT : 'true' | 'false' ;
STRING_CONSTANT :'"' (~'"')* '"';
FLOAT_CONSTANT : (DIGIT)+ '.' (DIGIT)* FLOATEXP?
| (DIGIT)+ FLOATEXP
;
NULL_CONSTANT : 'null';
IDENTIFIER : REG_IDENTIFIER | ESCAPED_IDENTIFIER ;
//regular identifiers start with a (lowercase or uppercase) English alphabet letter, followed by zero or more letters, decimal digits, or underscores
REG_IDENTIFIER: LETTER(LETTER|'_'|DIGIT)* ; //TODO: Case insensitive??
//VTL 1.1 allows us to escape the limitations imposed on regular identifiers by enclosing them in single quotes (apostrophes).
fragment ESCAPED_IDENTIFIER: QUOTE (~['\r\n] | '\'\'')+ QUOTE;
fragment QUOTE : '\'';
PLUS : '+';
MINUS : '-';
fragment DIGIT : '0'..'9' ;
fragment FLOATEXP : ('e'|'E')(PLUS|MINUS)?('0'..'9')+;
fragment LETTER : 'A'..'Z' | 'a'..'z';
WS : [ \n\r\t\u000C] -> skip ;
COMMENT : '/*' .*? '*/' -> skip;
|
Add grammar for sum function
|
Add grammar for sum function
|
ANTLR
|
apache-2.0
|
statisticsnorway/java-vtl,hadrienk/java-vtl,hadrienk/java-vtl,hadrienk/java-vtl,statisticsnorway/java-vtl,statisticsnorway/java-vtl,statisticsnorway/java-vtl
|
c43dd02bd046996e81d5f27fe5871d1328236a94
|
promql/PromQLParser.g4
|
promql/PromQLParser.g4
|
/*
[The "BSD licence"]
Copyright (c) 2013 Terence Parr
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
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 PromQLParser;
options { tokenVocab = PromQLLexer; }
expression: vectorOperation EOF;
// Binary operations are ordered by precedence
// Unary operations have the same precedence as multiplications
vectorOperation
: vector powOp vectorOperation // pow is right-associative
| unaryOp vectorOperation
| vectorOperation multOp vectorOperation
| vectorOperation addOp vectorOperation
| vectorOperation compareOp vectorOperation
| vectorOperation andUnlessOp vectorOperation
| vectorOperation orOp vectorOperation
| vector
;
// Operators
unaryOp: (ADD | SUB);
powOp: POW grouping?;
multOp: (MULT | DIV | MOD) grouping?;
addOp: (ADD | SUB) grouping?;
compareOp: (DEQ | NE | GT | LT | GE | LE) BOOL? grouping?;
andUnlessOp: (AND | UNLESS) grouping?;
orOp: OR grouping?;
vector
: function
| aggregation
| instantSelector
| matrixSelector
| offset
| literal
| parens
;
parens: LEFT_PAREN vectorOperation RIGHT_PAREN;
// Selectors
instantSelector
: METRIC_NAME LEFT_BRACE labelMatcher (COMMA labelMatcher)* RIGHT_BRACE
| METRIC_NAME LEFT_BRACE RIGHT_BRACE
| METRIC_NAME
| LEFT_BRACE labelMatcher (COMMA labelMatcher)* RIGHT_BRACE
;
labelMatcher: labelName labelMatcherOperator STRING;
labelMatcherOperator: EQ | NE | RE | NRE;
matrixSelector: instantSelector TIME_RANGE;
offset
: instantSelector OFFSET DURATION
| matrixSelector OFFSET DURATION
;
// Functions
function: FUNCTION LEFT_PAREN parameter (COMMA parameter)* RIGHT_PAREN;
parameter: literal | vector;
parameterList
: LEFT_PAREN parameter (COMMA parameter)* RIGHT_PAREN
| LEFT_PAREN RIGHT_PAREN
;
// Aggregations
aggregation
: AGGREGATION_OPERATOR parameterList
| AGGREGATION_OPERATOR (by | without) parameterList
| AGGREGATION_OPERATOR parameterList ( by | without)
;
by: BY labelNameList;
without: WITHOUT labelNameList;
// Vector one-to-one/one-to-many joins
grouping: (on | ignoring) (groupLeft | groupRight)?;
on: ON labelNameList;
ignoring: IGNORING labelNameList;
groupLeft: GROUP_LEFT labelNameList;
groupRight: GROUP_RIGHT labelNameList;
// Label names
labelName: keyword | METRIC_NAME | LABEL_NAME;
labelNameList
: LEFT_PAREN labelName (COMMA labelName)* RIGHT_PAREN
| LEFT_PAREN RIGHT_PAREN
;
keyword
: AND
| OR
| UNLESS
| BY
| WITHOUT
| ON
| IGNORING
| GROUP_LEFT
| GROUP_RIGHT
| OFFSET
| BOOL
| AGGREGATION_OPERATOR
| FUNCTION
;
literal: NUMBER | STRING;
|
/*
[The "BSD licence"]
Copyright (c) 2013 Terence Parr
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
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 PromQLParser;
options { tokenVocab = PromQLLexer; }
expression: vectorOperation EOF;
// Binary operations are ordered by precedence
// Unary operations have the same precedence as multiplications
vectorOperation
: <assoc=right> vectorOperation powOp vectorOperation
| unaryOp vectorOperation
| vectorOperation multOp vectorOperation
| vectorOperation addOp vectorOperation
| vectorOperation compareOp vectorOperation
| vectorOperation andUnlessOp vectorOperation
| vectorOperation orOp vectorOperation
| vector
;
// Operators
unaryOp: (ADD | SUB);
powOp: POW grouping?;
multOp: (MULT | DIV | MOD) grouping?;
addOp: (ADD | SUB) grouping?;
compareOp: (DEQ | NE | GT | LT | GE | LE) BOOL? grouping?;
andUnlessOp: (AND | UNLESS) grouping?;
orOp: OR grouping?;
vector
: function
| aggregation
| instantSelector
| matrixSelector
| offset
| literal
| parens
;
parens: LEFT_PAREN vectorOperation RIGHT_PAREN;
// Selectors
instantSelector
: METRIC_NAME (LEFT_BRACE labelMatcherList? RIGHT_BRACE)?
| LEFT_BRACE labelMatcherList RIGHT_BRACE
;
labelMatcher: labelName labelMatcherOperator STRING;
labelMatcherOperator: EQ | NE | RE | NRE;
labelMatcherList: labelMatcher (COMMA labelMatcher)*;
matrixSelector: instantSelector TIME_RANGE;
offset
: instantSelector OFFSET DURATION
| matrixSelector OFFSET DURATION
;
// Functions
function: FUNCTION LEFT_PAREN parameter (COMMA parameter)* RIGHT_PAREN;
parameter: literal | vector;
parameterList: LEFT_PAREN (parameter (COMMA parameter)*)? RIGHT_PAREN;
// Aggregations
aggregation
: AGGREGATION_OPERATOR parameterList
| AGGREGATION_OPERATOR (by | without) parameterList
| AGGREGATION_OPERATOR parameterList ( by | without)
;
by: BY labelNameList;
without: WITHOUT labelNameList;
// Vector one-to-one/one-to-many joins
grouping: (on | ignoring) (groupLeft | groupRight)?;
on: ON labelNameList;
ignoring: IGNORING labelNameList;
groupLeft: GROUP_LEFT labelNameList;
groupRight: GROUP_RIGHT labelNameList;
// Label names
labelName: keyword | METRIC_NAME | LABEL_NAME;
labelNameList: LEFT_PAREN (labelName (COMMA labelName)*)? RIGHT_PAREN;
keyword
: AND
| OR
| UNLESS
| BY
| WITHOUT
| ON
| IGNORING
| GROUP_LEFT
| GROUP_RIGHT
| OFFSET
| BOOL
| AGGREGATION_OPERATOR
| FUNCTION
;
literal: NUMBER | STRING;
|
address review comments
|
address review comments
|
ANTLR
|
mit
|
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
|
5fcfc2592b794421c84f3f5a682df293ed8383cd
|
protobuf3/Protobuf3.g4
|
protobuf3/Protobuf3.g4
|
// SPDX-License-Identifier: Apache-2.0
/**
* A Protocol Buffers 3 grammar
*
* Original source: https://developers.google.com/protocol-buffers/docs/reference/proto3-spec
* Original source is published under Apache License 2.0.
*
* Changes from the source above:
* - rewrite to antlr
* - extract some group to rule.
*
* @author anatawa12
*/
grammar Protobuf3;
proto
: syntax
(
importStatement
| packageStatement
| optionStatement
| topLevelDef
| emptyStatement_
)* EOF
;
// Syntax
syntax
: SYNTAX EQ (PROTO3_LIT_SINGLE | PROTO3_LIT_DOBULE) SEMI
;
// Import Statement
importStatement
: IMPORT ( WEAK | PUBLIC )? strLit SEMI
;
// Package
packageStatement
: PACKAGE fullIdent SEMI
;
// Option
optionStatement
: OPTION optionName EQ constant SEMI
;
optionName
: fullIdent
| LP fullIdent RP ( DOT fullIdent )?
;
// Normal Field
field
: ( REPEATED )? type_ fieldName EQ fieldNumber ( LB fieldOptions RB )? SEMI
;
fieldOptions
: fieldOption ( COMMA fieldOption )*
;
fieldOption
: optionName EQ constant
;
fieldNumber
: intLit
;
// Oneof and oneof field
oneof
: ONEOF oneofName LC ( optionStatement | oneofField | emptyStatement_ )* RC
;
oneofField
: type_ fieldName EQ fieldNumber ( LB fieldOptions RB )? SEMI
;
// Map field
mapField
: MAP LT keyType COMMA type_ GT mapName
EQ fieldNumber ( LB fieldOptions RB )? SEMI
;
keyType
: INT32
| INT64
| UINT32
| UINT64
| SINT32
| SINT64
| FIXED32
| FIXED64
| SFIXED32
| SFIXED64
| BOOL
| STRING
;
// field types
type_
: DOUBLE
| FLOAT
| INT32
| INT64
| UINT32
| UINT64
| SINT32
| SINT64
| FIXED32
| FIXED64
| SFIXED32
| SFIXED64
| BOOL
| STRING
| BYTES
| messageType
| enumType
;
// Reserved
reserved
: RESERVED ( ranges | reservedFieldNames ) SEMI
;
ranges
: range_ ( COMMA range_ )*
;
range_
: intLit ( TO ( intLit | MAX ) )?
;
reservedFieldNames
: strLit ( COMMA strLit )*
;
// Top Level definitions
topLevelDef
: messageDef
| enumDef
| serviceDef
;
// enum
enumDef
: ENUM enumName enumBody
;
enumBody
: LC enumElement* RC
;
enumElement
: optionStatement
| enumField
| emptyStatement_
;
enumField
: ident EQ ( MINUS )? intLit enumValueOptions?SEMI
;
enumValueOptions
: LB enumValueOption ( COMMA enumValueOption )* RB
;
enumValueOption
: optionName EQ constant
;
// message
messageDef
: MESSAGE messageName messageBody
;
messageBody
: LC messageElement* RC
;
messageElement
: field
| enumDef
| messageDef
| optionStatement
| oneof
| mapField
| reserved
| emptyStatement_
;
// service
serviceDef
: SERVICE serviceName LC serviceElement* RC
;
serviceElement
: optionStatement
| rpc
| emptyStatement_
;
rpc
: RPC rpcName LP ( STREAM )? messageType RP
RETURNS LP ( STREAM )? messageType RP
(LC ( optionStatement | emptyStatement_ )* RC | SEMI)
;
// lexical
constant
: fullIdent
| (MINUS | PLUS )? intLit
| ( MINUS | PLUS )? floatLit
| strLit
| boolLit
| blockLit
;
// not specified in specification but used in tests
blockLit
: LC ( ident COLON constant )* RC
;
emptyStatement_: SEMI;
// Lexical elements
ident: IDENTIFIER | keywords;
fullIdent: ident ( DOT ident )*;
messageName: ident;
enumName: ident;
fieldName: ident;
oneofName: ident;
mapName: ident;
serviceName: ident;
rpcName: ident;
messageType: ( DOT )? ( ident DOT )* messageName;
enumType: ( DOT )? ( ident DOT )* enumName;
intLit: INT_LIT;
strLit: STR_LIT | PROTO3_LIT_SINGLE | PROTO3_LIT_DOBULE;
boolLit: BOOL_LIT;
floatLit: FLOAT_LIT;
// keywords
SYNTAX: 'syntax';
IMPORT: 'import';
WEAK: 'weak';
PUBLIC: 'public';
PACKAGE: 'package';
OPTION: 'option';
REPEATED: 'repeated';
ONEOF: 'oneof';
MAP: 'map';
INT32: 'int32';
INT64: 'int64';
UINT32: 'uint32';
UINT64: 'uint64';
SINT32: 'sint32';
SINT64: 'sint64';
FIXED32: 'fixed32';
FIXED64: 'fixed64';
SFIXED32: 'sfixed32';
SFIXED64: 'sfixed64';
BOOL: 'bool';
STRING: 'string';
DOUBLE: 'double';
FLOAT: 'float';
BYTES: 'bytes';
RESERVED: 'reserved';
TO: 'to';
MAX: 'max';
ENUM: 'enum';
MESSAGE: 'message';
SERVICE: 'service';
RPC: 'rpc';
STREAM: 'stream';
RETURNS: 'returns';
PROTO3_LIT_SINGLE: '"proto3"';
PROTO3_LIT_DOBULE: '\'proto3\'';
// symbols
SEMI: ';';
EQ: '=';
LP: '(';
RP: ')';
LB: '[';
RB: ']';
LC: '{';
RC: '}';
LT: '<';
GT: '>';
DOT: '.';
COMMA: ',';
COLON: ':';
PLUS: '+';
MINUS: '-';
STR_LIT: ( '\'' ( CHAR_VALUE )*? '\'' ) | ( '"' ( CHAR_VALUE )*? '"' );
fragment CHAR_VALUE: HEX_ESCAPE | OCT_ESCAPE | CHAR_ESCAPE | ~[\u0000\n\\];
fragment HEX_ESCAPE: '\\' ( 'x' | 'X' ) HEX_DIGIT HEX_DIGIT;
fragment OCT_ESCAPE: '\\' OCTAL_DIGIT OCTAL_DIGIT OCTAL_DIGIT;
fragment CHAR_ESCAPE: '\\' ( 'a' | 'b' | 'f' | 'n' | 'r' | 't' | 'v' | '\\' | '\'' | '"' );
BOOL_LIT: 'true' | 'false';
FLOAT_LIT : ( DECIMALS DOT DECIMALS? EXPONENT? | DECIMALS EXPONENT | DOT DECIMALS EXPONENT? ) | 'inf' | 'nan';
fragment EXPONENT : ( 'e' | 'E' ) (PLUS | MINUS)? DECIMALS;
fragment DECIMALS : DECIMAL_DIGIT+;
INT_LIT : DECIMAL_LIT | OCTAL_LIT | HEX_LIT;
fragment DECIMAL_LIT : ( [1-9] ) DECIMAL_DIGIT*;
fragment OCTAL_LIT : '0' OCTAL_DIGIT*;
fragment HEX_LIT : '0' ( 'x' | 'X' ) HEX_DIGIT+ ;
IDENTIFIER: LETTER ( LETTER | DECIMAL_DIGIT )*;
fragment LETTER: [A-Za-z_];
fragment DECIMAL_DIGIT: [0-9];
fragment OCTAL_DIGIT: [0-7];
fragment HEX_DIGIT: [0-9A-Fa-f];
// comments
WS : [ \t\r\n\u000C]+ -> skip;
LINE_COMMENT: '//' ~[\r\n]* -> skip;
COMMENT: '/*' .*? '*/' -> skip;
keywords
: SYNTAX
| IMPORT
| WEAK
| PUBLIC
| PACKAGE
| OPTION
| REPEATED
| ONEOF
| MAP
| INT32
| INT64
| UINT32
| UINT64
| SINT32
| SINT64
| FIXED32
| FIXED64
| SFIXED32
| SFIXED64
| BOOL
| STRING
| DOUBLE
| FLOAT
| BYTES
| RESERVED
| TO
| MAX
| ENUM
| MESSAGE
| SERVICE
| RPC
| STREAM
| RETURNS
| BOOL_LIT
;
|
// SPDX-License-Identifier: Apache-2.0
/**
* A Protocol Buffers 3 grammar
*
* Original source: https://developers.google.com/protocol-buffers/docs/reference/proto3-spec
* Original source is published under Apache License 2.0.
*
* Changes from the source above:
* - rewrite to antlr
* - extract some group to rule.
*
* @author anatawa12
*/
grammar Protobuf3;
proto
: syntax
(
importStatement
| packageStatement
| optionStatement
| topLevelDef
| emptyStatement_
)* EOF
;
// Syntax
syntax
: SYNTAX EQ (PROTO3_LIT_SINGLE | PROTO3_LIT_DOBULE) SEMI
;
// Import Statement
importStatement
: IMPORT ( WEAK | PUBLIC )? strLit SEMI
;
// Package
packageStatement
: PACKAGE fullIdent SEMI
;
// Option
optionStatement
: OPTION optionName EQ constant SEMI
;
optionName
: fullIdent
| LP fullIdent RP ( DOT fullIdent )?
;
// Normal Field
field
: ( REPEATED )? type_ fieldName EQ fieldNumber ( LB fieldOptions RB )? SEMI
;
fieldOptions
: fieldOption ( COMMA fieldOption )*
;
fieldOption
: optionName EQ constant
;
fieldNumber
: intLit
;
// Oneof and oneof field
oneof
: ONEOF oneofName LC ( optionStatement | oneofField | emptyStatement_ )* RC
;
oneofField
: type_ fieldName EQ fieldNumber ( LB fieldOptions RB )? SEMI
;
// Map field
mapField
: MAP LT keyType COMMA type_ GT mapName
EQ fieldNumber ( LB fieldOptions RB )? SEMI
;
keyType
: INT32
| INT64
| UINT32
| UINT64
| SINT32
| SINT64
| FIXED32
| FIXED64
| SFIXED32
| SFIXED64
| BOOL
| STRING
;
// field types
type_
: DOUBLE
| FLOAT
| INT32
| INT64
| UINT32
| UINT64
| SINT32
| SINT64
| FIXED32
| FIXED64
| SFIXED32
| SFIXED64
| BOOL
| STRING
| BYTES
| messageType
| enumType
;
// Reserved
reserved
: RESERVED ( ranges | reservedFieldNames ) SEMI
;
ranges
: range_ ( COMMA range_ )*
;
range_
: intLit ( TO ( intLit | MAX ) )?
;
reservedFieldNames
: strLit ( COMMA strLit )*
;
// Top Level definitions
topLevelDef
: messageDef
| enumDef
| extendDef
| serviceDef
;
// enum
enumDef
: ENUM enumName enumBody
;
enumBody
: LC enumElement* RC
;
enumElement
: optionStatement
| enumField
| emptyStatement_
;
enumField
: ident EQ ( MINUS )? intLit enumValueOptions?SEMI
;
enumValueOptions
: LB enumValueOption ( COMMA enumValueOption )* RB
;
enumValueOption
: optionName EQ constant
;
// message
messageDef
: MESSAGE messageName messageBody
;
messageBody
: LC messageElement* RC
;
messageElement
: field
| enumDef
| messageDef
| extendDef
| optionStatement
| oneof
| mapField
| reserved
| emptyStatement_
;
// Extend definition
//
// NB: not defined in the spec but supported by protoc and covered by protobuf3 tests
// see e.g. php/tests/proto/test_import_descriptor_proto.proto
// of https://github.com/protocolbuffers/protobuf
// it also was discussed here: https://github.com/protocolbuffers/protobuf/issues/4610
extendDef
: EXTEND messageType LC ( field
| emptyStatement_
)* RC
;
// service
serviceDef
: SERVICE serviceName LC serviceElement* RC
;
serviceElement
: optionStatement
| rpc
| emptyStatement_
;
rpc
: RPC rpcName LP ( STREAM )? messageType RP
RETURNS LP ( STREAM )? messageType RP
(LC ( optionStatement | emptyStatement_ )* RC | SEMI)
;
// lexical
constant
: fullIdent
| (MINUS | PLUS )? intLit
| ( MINUS | PLUS )? floatLit
| strLit
| boolLit
| blockLit
;
// not specified in specification but used in tests
blockLit
: LC ( ident COLON constant )* RC
;
emptyStatement_: SEMI;
// Lexical elements
ident: IDENTIFIER | keywords;
fullIdent: ident ( DOT ident )*;
messageName: ident;
enumName: ident;
fieldName: ident;
oneofName: ident;
mapName: ident;
serviceName: ident;
rpcName: ident;
messageType: ( DOT )? ( ident DOT )* messageName;
enumType: ( DOT )? ( ident DOT )* enumName;
intLit: INT_LIT;
strLit: STR_LIT | PROTO3_LIT_SINGLE | PROTO3_LIT_DOBULE;
boolLit: BOOL_LIT;
floatLit: FLOAT_LIT;
// keywords
SYNTAX: 'syntax';
IMPORT: 'import';
WEAK: 'weak';
PUBLIC: 'public';
PACKAGE: 'package';
OPTION: 'option';
REPEATED: 'repeated';
ONEOF: 'oneof';
MAP: 'map';
INT32: 'int32';
INT64: 'int64';
UINT32: 'uint32';
UINT64: 'uint64';
SINT32: 'sint32';
SINT64: 'sint64';
FIXED32: 'fixed32';
FIXED64: 'fixed64';
SFIXED32: 'sfixed32';
SFIXED64: 'sfixed64';
BOOL: 'bool';
STRING: 'string';
DOUBLE: 'double';
FLOAT: 'float';
BYTES: 'bytes';
RESERVED: 'reserved';
TO: 'to';
MAX: 'max';
ENUM: 'enum';
MESSAGE: 'message';
SERVICE: 'service';
EXTEND: 'extend';
RPC: 'rpc';
STREAM: 'stream';
RETURNS: 'returns';
PROTO3_LIT_SINGLE: '"proto3"';
PROTO3_LIT_DOBULE: '\'proto3\'';
// symbols
SEMI: ';';
EQ: '=';
LP: '(';
RP: ')';
LB: '[';
RB: ']';
LC: '{';
RC: '}';
LT: '<';
GT: '>';
DOT: '.';
COMMA: ',';
COLON: ':';
PLUS: '+';
MINUS: '-';
STR_LIT: ( '\'' ( CHAR_VALUE )*? '\'' ) | ( '"' ( CHAR_VALUE )*? '"' );
fragment CHAR_VALUE: HEX_ESCAPE | OCT_ESCAPE | CHAR_ESCAPE | ~[\u0000\n\\];
fragment HEX_ESCAPE: '\\' ( 'x' | 'X' ) HEX_DIGIT HEX_DIGIT;
fragment OCT_ESCAPE: '\\' OCTAL_DIGIT OCTAL_DIGIT OCTAL_DIGIT;
fragment CHAR_ESCAPE: '\\' ( 'a' | 'b' | 'f' | 'n' | 'r' | 't' | 'v' | '\\' | '\'' | '"' );
BOOL_LIT: 'true' | 'false';
FLOAT_LIT : ( DECIMALS DOT DECIMALS? EXPONENT? | DECIMALS EXPONENT | DOT DECIMALS EXPONENT? ) | 'inf' | 'nan';
fragment EXPONENT : ( 'e' | 'E' ) (PLUS | MINUS)? DECIMALS;
fragment DECIMALS : DECIMAL_DIGIT+;
INT_LIT : DECIMAL_LIT | OCTAL_LIT | HEX_LIT;
fragment DECIMAL_LIT : ( [1-9] ) DECIMAL_DIGIT*;
fragment OCTAL_LIT : '0' OCTAL_DIGIT*;
fragment HEX_LIT : '0' ( 'x' | 'X' ) HEX_DIGIT+ ;
IDENTIFIER: LETTER ( LETTER | DECIMAL_DIGIT )*;
fragment LETTER: [A-Za-z_];
fragment DECIMAL_DIGIT: [0-9];
fragment OCTAL_DIGIT: [0-7];
fragment HEX_DIGIT: [0-9A-Fa-f];
// comments
WS : [ \t\r\n\u000C]+ -> skip;
LINE_COMMENT: '//' ~[\r\n]* -> channel(HIDDEN);
COMMENT: '/*' .*? '*/' -> channel(HIDDEN);
keywords
: SYNTAX
| IMPORT
| WEAK
| PUBLIC
| PACKAGE
| OPTION
| REPEATED
| ONEOF
| MAP
| INT32
| INT64
| UINT32
| UINT64
| SINT32
| SINT64
| FIXED32
| FIXED64
| SFIXED32
| SFIXED64
| BOOL
| STRING
| DOUBLE
| FLOAT
| BYTES
| RESERVED
| TO
| MAX
| ENUM
| MESSAGE
| SERVICE
| EXTEND
| RPC
| STREAM
| RETURNS
| BOOL_LIT
;
|
Add extend option
|
Add extend option
|
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
|
8bda4721952a2fa672dcc54cb61569be4d26f9b2
|
src/main/antlr/Parser.g4
|
src/main/antlr/Parser.g4
|
grammar Parser;
@header {
package net.zero918nobita.Xemime;
}
prog: (expr '\n')*;
expr: WS? 'let' WS SYMBOL WS? '=' WS? expr WS?
| WS? expr1 WS? ';'
| WS? expr1 WS?
;
expr1: expr1 WS? '[' WS? expr1 WS? ']'
| expr2
;
expr2: expr2 WS? '(' ( WS? expr1 WS? ( ',' WS? expr1)* )? WS? ')'
| expr3
;
expr3: '!' WS? expr1
| '+' WS? expr1
| '-' WS? expr1
| '++' WS? expr1
| '--' WS? expr1
| expr4
;
expr4: expr4 WS? '^' WS? expr1
| expr6
;
expr6: expr6 WS? '*' WS? expr1
| expr6 WS? '/' WS? expr1
| expr6 WS? '%' WS? expr1
| expr7
;
expr7: expr7 WS? '+' WS? expr1
| expr7 WS? '-' WS? expr2
| expr8
;
expr8: expr8 WS? '<' WS? expr1
| expr8 WS? '<=' WS? expr1
| expr8 WS? '>' WS? expr1
| expr8 WS? '>=' WS? expr1
| expr9
;
expr9: expr9 WS? '==' WS? expr1
| expr9 WS? '!=' WS? expr1
| expr10;
expr10: expr10 WS? '&&' WS? expr1
| expr11
;
expr11: expr11 WS? '||' WS? expr1
| expr12
;
expr12: '(' WS? expr1 WS? ')'
| SYMBOL WS? '=' WS? expr1
| SYMBOL WS? '++'
| SYMBOL WS? '--'
| SYMBOL
| INT
;
WS: ' '*;
INT: [0-9]+ ;
SYMBOL: [A-Za-z][A-Za-z0-9]*;
|
grammar Parser;
@header {
package net.zero918nobita.Xemime;
}
prog: (expr? '\n')*;
expr: WS? 'if' WS expr WS '{' WS? expr WS? (expr WS? '\n' WS?)* '}' WS? ('else' WS? '{' WS? expr WS? (expr WS? '\n' WS?)* '}')?
| WS? 'let' WS SYMBOL WS? '=' WS? expr WS?
| WS? expr1 WS? ';'
| WS? expr1 WS?
;
expr1: expr1 WS? '[' WS? expr1 WS? ']'
| expr2
;
expr2: expr2 WS? '(' ( WS? expr1 WS? ( ',' WS? expr1)* )? WS? ')'
| expr3
;
expr3: '!' WS? expr1
| '+' WS? expr1
| '-' WS? expr1
| '++' WS? expr1
| '--' WS? expr1
| expr4
;
expr4: expr4 WS? '^' WS? expr1
| expr6
;
expr6: expr6 WS? '*' WS? expr1
| expr6 WS? '/' WS? expr1
| expr6 WS? '%' WS? expr1
| expr7
;
expr7: expr7 WS? '+' WS? expr1
| expr7 WS? '-' WS? expr2
| expr8
;
expr8: expr8 WS? '<' WS? expr1
| expr8 WS? '<=' WS? expr1
| expr8 WS? '>' WS? expr1
| expr8 WS? '>=' WS? expr1
| expr9
;
expr9: expr9 WS? '==' WS? expr1
| expr9 WS? '!=' WS? expr1
| expr10;
expr10: expr10 WS? '&&' WS? expr1
| expr11
;
expr11: expr11 WS? '||' WS? expr1
| expr12
;
expr12: '(' WS? expr1 WS? ')'
| SYMBOL WS? '=' WS? expr1
| SYMBOL WS? '++'
| SYMBOL WS? '--'
| SYMBOL
| INT
;
WS: ' '*;
INT: [0-9]+ ;
SYMBOL: [A-Za-z][A-Za-z0-9]*;
|
Update Parser.g4
|
Update Parser.g4
|
ANTLR
|
mit
|
xemime-lang/xemime,xemime-lang/xemime
|
1a5f8341fa210609e3638c5c272891f9fc3334b9
|
src/COOL.g4
|
src/COOL.g4
|
grammar COOL;
program
: classDefine ';' program #class
| EOF #eof
;
classDefine: CLASS TYPEID (INHERITS TYPEID)? '{' (feature ';')* '}';
feature
: OBJECTID '(' (formal (',' formal)*)* ')' ':' TYPEID '{' expression '}' #method
| OBJECTID ':' TYPEID (ASSIGNMENT expression)? /* class member variable */ #classVariable
;
formal: OBJECTID ':' TYPEID; /* method argument */
expression
: OBJECTID ASSIGNMENT expression #assignment
| expression ('@' TYPEID)? '.' OBJECTID '(' (expression (',' expression)*)* ')' /* call super class method */ #superClassMethod
| OBJECTID '(' (expression (',' expression)*)* ')' /* call function that refered by variable */ #functionCall
| IF expression THEN expression ELSE expression FI #if
| WHILE expression LOOP expression POOL #whild
| '{' (expression ';')+ '}' #multipleExpression
| LET OBJECTID ':' TYPEID (ASSIGNMENT expression)? (',' OBJECTID ':' TYPEID (ASSIGNMENT expression)?)* IN expression /* let num : Int <- num_cells() in */ #letIn
| CASE expression OF (OBJECTID ':' TYPEID CASE_ARROW expression ';')+ ESAC #case
| NEW TYPEID #newType
| ISVOID expression #isvoid
| expression ADD expression #add
| expression MINUS expression #minus
| expression MULTIPLY expression #multiply
| expression DIVISION expression #division
| INTEGER_COMPLEMENT expression #integerComplement
| expression LESS_THAN expression #lessThan
| expression LESS_EQUAL expression #lessEqual
| expression EQUAL expression #equal
| NOT expression #boolNot
| '(' expression ')' #parentheses
| OBJECTID #id
| INT #int
| STRING #string
| TRUE #true
| FALSE #false
;
// skip spaces, tabs, newlines, note that \v is not suppoted in antlr
WHITESPACE: [ \t\r\n\f]+ -> skip;
// comments
OPEN_COMMENT: '(*';
CLOSE_COMMENT: '*)';
COMMENT: OPEN_COMMENT (COMMENT|.)*? CLOSE_COMMENT -> channel(HIDDEN);
ONE_LINE_COMMENT: '--' .*? '\n' -> channel(HIDDEN);
// key words
CLASS: ('C'|'c')('L'|'l')('A'|'a')('S'|'s')('S'|'s');
ELSE: ('E'|'e')('L'|'l')('S'|'s')('E'|'e');
FALSE: 'f'('A'|'a')('L'|'l')('S'|'s')('E'|'e');
FI: ('F'|'f')('I'|'i');
IF: ('I'|'i')('F'|'f');
IN: ('I'|'i')('N'|'n');
INHERITS: ('I'|'i')('N'|'n')('H'|'h')('E'|'e')('R'|'r')('I'|'i')('T'|'t')('S'|'s');
ISVOID: ('I'|'i')('S'|'s')('V'|'v')('O'|'o')('I'|'i')('D'|'d');
LET: ('L'|'l')('E'|'e')('T'|'t');
LOOP: ('L'|'l')('O'|'o')('O'|'o')('P'|'p');
POOL: ('P'|'p')('O'|'o')('O'|'o')('L'|'l');
THEN: ('T'|'t')('H'|'h')('E'|'e')('N'|'n');
WHILE: ('W'|'w')('H'|'h')('I'|'i')('L'|'l')('E'|'e');
CASE: ('C'|'c')('A'|'a')('S'|'s')('E'|'e');
ESAC: ('E'|'e')('S'|'s')('A'|'a')('C'|'c');
NEW: ('N'|'n')('E'|'e')('W'|'w');
OF: ('O'|'o')('F'|'f');
NOT: ('N'|'n')('O'|'o')('T'|'t');
TRUE: 't'('R'|'r')('U'|'u')('E'|'e');
// premitives
STRING: '"' (ESC | ~ ["\\])* '"'; // non-greedy matching one line string
INT: [0-9]+;
TYPEID: [A-Z][_0-9A-Za-z]*;
OBJECTID: [a-z][_0-9A-Za-z]*;
ASSIGNMENT: '<-';
CASE_ARROW: '=>';
ADD: '+';
MINUS: '-';
MULTIPLY: '*';
DIVISION: '/';
LESS_THAN: '<';
LESS_EQUAL: '<=';
EQUAL: '=';
INTEGER_COMPLEMENT: '~';
fragment ESC: '\\' (["\\/bfnrt] | UNICODE);
fragment UNICODE: 'u' HEX HEX HEX HEX;
fragment HEX: [0-9a-fA-F];
|
/*
To generate JS file, install gulp first, then run:
gulp build-compiler
generated js files will be placed in ./antlrGenerated
*/
grammar COOL;
program
: classDefine ';' program #class
| EOF #eof
;
classDefine: CLASS TYPEID (INHERITS TYPEID)? '{' (feature ';')* '}';
feature
: OBJECTID '(' (formal (',' formal)*)* ')' ':' TYPEID '{' expression '}' #method
| OBJECTID ':' TYPEID (ASSIGNMENT expression)? /* class member variable */ #classVariable
;
formal: OBJECTID ':' TYPEID; /* method argument */
expression
: OBJECTID ASSIGNMENT expression #assignment
| expression ('@' TYPEID)? '.' OBJECTID '(' (expression (',' expression)*)* ')' /* call super class method */ #superClassMethod
| OBJECTID '(' (expression (',' expression)*)* ')' /* call function that refered by variable */ #functionCall
| IF expression THEN expression ELSE expression FI #if
| WHILE expression LOOP expression POOL #whild
| '{' (expression ';')+ '}' #multipleExpression
| LET OBJECTID ':' TYPEID (ASSIGNMENT expression)? (',' OBJECTID ':' TYPEID (ASSIGNMENT expression)?)* IN expression /* let num : Int <- num_cells() in */ #letIn
| CASE expression OF (OBJECTID ':' TYPEID CASE_ARROW expression ';')+ ESAC #case
| NEW TYPEID #newType
| ISVOID expression #isvoid
| expression ADD expression #add
| expression MINUS expression #minus
| expression MULTIPLY expression #multiply
| expression DIVISION expression #division
| INTEGER_COMPLEMENT expression #integerComplement
| expression LESS_THAN expression #lessThan
| expression LESS_EQUAL expression #lessEqual
| expression EQUAL expression #equal
| NOT expression #boolNot
| '(' expression ')' #parentheses
| OBJECTID #id
| INT #int
| STRING #string
| TRUE #true
| FALSE #false
;
// skip spaces, tabs, newlines, note that \v is not suppoted in antlr
WHITESPACE: [ \t\r\n\f]+ -> skip;
// comments
OPEN_COMMENT: '(*';
CLOSE_COMMENT: '*)';
COMMENT: OPEN_COMMENT (COMMENT|.)*? CLOSE_COMMENT -> channel(HIDDEN);
ONE_LINE_COMMENT: '--' .*? '\n' -> channel(HIDDEN);
// key words
CLASS: ('C'|'c')('L'|'l')('A'|'a')('S'|'s')('S'|'s');
ELSE: ('E'|'e')('L'|'l')('S'|'s')('E'|'e');
FALSE: 'f'('A'|'a')('L'|'l')('S'|'s')('E'|'e');
FI: ('F'|'f')('I'|'i');
IF: ('I'|'i')('F'|'f');
IN: ('I'|'i')('N'|'n');
INHERITS: ('I'|'i')('N'|'n')('H'|'h')('E'|'e')('R'|'r')('I'|'i')('T'|'t')('S'|'s');
ISVOID: ('I'|'i')('S'|'s')('V'|'v')('O'|'o')('I'|'i')('D'|'d');
LET: ('L'|'l')('E'|'e')('T'|'t');
LOOP: ('L'|'l')('O'|'o')('O'|'o')('P'|'p');
POOL: ('P'|'p')('O'|'o')('O'|'o')('L'|'l');
THEN: ('T'|'t')('H'|'h')('E'|'e')('N'|'n');
WHILE: ('W'|'w')('H'|'h')('I'|'i')('L'|'l')('E'|'e');
CASE: ('C'|'c')('A'|'a')('S'|'s')('E'|'e');
ESAC: ('E'|'e')('S'|'s')('A'|'a')('C'|'c');
NEW: ('N'|'n')('E'|'e')('W'|'w');
OF: ('O'|'o')('F'|'f');
NOT: ('N'|'n')('O'|'o')('T'|'t');
TRUE: 't'('R'|'r')('U'|'u')('E'|'e');
// premitives
STRING: '"' (ESC | ~ ["\\])* '"'; // non-greedy matching one line string
INT: [0-9]+;
TYPEID: [A-Z][_0-9A-Za-z]*;
OBJECTID: [a-z][_0-9A-Za-z]*;
ASSIGNMENT: '<-';
CASE_ARROW: '=>';
ADD: '+';
MINUS: '-';
MULTIPLY: '*';
DIVISION: '/';
LESS_THAN: '<';
LESS_EQUAL: '<=';
EQUAL: '=';
INTEGER_COMPLEMENT: '~';
fragment ESC: '\\' (["\\/bfnrt] | UNICODE);
fragment UNICODE: 'u' HEX HEX HEX HEX;
fragment HEX: [0-9a-fA-F];
|
comment usage
|
doc: comment usage
|
ANTLR
|
mit
|
linonetwo/COOL-to-JavaScript,linonetwo/COOL-to-JavaScript
|
3109b29378d6235e325b65f9b2ef86595f9fda02
|
terraform/terraform.g4
|
terraform/terraform.g4
|
/*
BSD License
Copyright (c) 2020, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar terraform;
file
: (local | module | output | provider | variable | data | resource)+
;
resource
: 'resource' resourcetype name blockbody
;
data
: 'data' resourcetype name blockbody
;
provider
: 'provider' resourcetype blockbody
;
output
: 'output' name blockbody
;
local
: 'locals' blockbody
;
module
: 'module' name blockbody
;
variable
: 'variable' name blockbody
;
block
: blocktype label* blockbody
;
blocktype
: IDENTIFIER
;
resourcetype
: STRING
;
name
: STRING
;
label
: STRING
;
blockbody
: '{' (argument | block)* '}'
;
argument
: identifier '=' expression
;
identifier
: IDENTIFIER
;
expression
: section ('.' section)*
;
section
: list
| map
| val
;
val
: NULL
| NUMBER
| string
| BOOL
| IDENTIFIER index?
| DESCRIPTION
| filedecl
| functioncall
| EOF_
;
functioncall
: functionname '(' functionarguments ')'
;
functionname
: IDENTIFIER
;
functionarguments
: //no arguments
| expression (',' expression)*
;
index
: '[' expression ']'
;
filedecl
: 'file' '(' expression ')'
;
list
: '[' expression (',' expression)* ','? ']'
;
map
: '{' argument* '}'
;
string
: STRING
| MULTILINESTRING
;
fragment DIGIT
: [0-9]
;
EOF_
: '<<EOF' .*? 'EOF'
;
NULL
: 'nul'
;
NUMBER
: DIGIT+ ('.' DIGIT+)?
;
BOOL
: 'true'
| 'false'
;
DESCRIPTION
: '<<DESCRIPTION' .*? 'DESCRIPTION'
;
MULTILINESTRING
: '<<-EOF' .*? 'EOF'
;
STRING
: '"' (~ [\r\n"] | '""')* '"'
;
IDENTIFIER
: [a-zA-Z] ([a-zA-Z0-9_-])*
;
COMMENT
: ('#' | '//') ~ [\r\n]* -> channel(HIDDEN)
;
BLOCKCOMMENT
: '/*' .*? '*/' -> channel(HIDDEN)
;
WS
: [ \r\n\t]+ -> skip
;
|
/*
BSD License
Copyright (c) 2020, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar terraform;
file
: (local | module | output | provider | variable | data | resource)+
;
resource
: 'resource' resourcetype name blockbody
;
data
: 'data' resourcetype name blockbody
;
provider
: 'provider' resourcetype blockbody
;
output
: 'output' name blockbody
;
local
: 'locals' blockbody
;
module
: 'module' name blockbody
;
variable
: 'variable' name blockbody
;
block
: blocktype label* blockbody
;
blocktype
: IDENTIFIER
;
resourcetype
: STRING
;
name
: STRING
;
label
: STRING
;
blockbody
: '{' (argument | block)* '}'
;
argument
: identifier '=' expression
;
identifier
: IDENTIFIER
;
expression
// : section ('.' section)*
: RESOURCEREFERENCE
| section
;
RESOURCEREFERENCE
: [a-zA-Z] [a-zA-Z0-9_-]* RESOURCEINDEX? '.' ([a-zA-Z0-9_.-] RESOURCEINDEX?)+
;
RESOURCEINDEX
: '[' [0-9]+ ']'
;
section
: list
| map
| val
;
val
: NULL
| NUMBER
| string
| BOOL
| IDENTIFIER index?
| DESCRIPTION
| filedecl
| functioncall
| EOF_
;
functioncall
: functionname '(' functionarguments ')'
;
functionname
: IDENTIFIER
;
functionarguments
: //no arguments
| expression (',' expression)*
;
index
: '[' expression ']'
;
filedecl
: 'file' '(' expression ')'
;
list
: '[' expression (',' expression)* ','? ']'
;
map
: '{' argument* '}'
;
string
: STRING
| MULTILINESTRING
;
fragment DIGIT
: [0-9]
;
EOF_
: '<<EOF' .*? 'EOF'
;
NULL
: 'nul'
;
NUMBER
: DIGIT+ ('.' DIGIT+)?
;
BOOL
: 'true'
| 'false'
;
DESCRIPTION
: '<<DESCRIPTION' .*? 'DESCRIPTION'
;
MULTILINESTRING
: '<<-EOF' .*? 'EOF'
;
STRING
: '"' (~ [\r\n"] | '""')* '"'
;
IDENTIFIER
: [a-zA-Z] ([a-zA-Z0-9_-])*
;
COMMENT
: ('#' | '//') ~ [\r\n]* -> channel(HIDDEN)
;
BLOCKCOMMENT
: '/*' .*? '*/' -> channel(HIDDEN)
;
WS
: [ \r\n\t]+ -> skip
;
|
Fix IDENTIFIER 'data' problem
|
Fix IDENTIFIER 'data' problem
|
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
|
274ea6e15bbd3c6d91e9ef39f8b33b6119017601
|
src/main/antlr/com/github/oreissig/footran1/parser/Footran.g4
|
src/main/antlr/com/github/oreissig/footran1/parser/Footran.g4
|
grammar Footran;
@header {
package com.github.oreissig.footran1.parser;
}
// parser rules
program : card*;
card : STMTNUM? statement NEWCARD?;
statement : arithmeticFormula
// TODO more to come
;
arithmeticFormula : ID '=' expression;
expression : ID | call | intConst | fpConst;
// treat subscripted variables as function calls
call : ID '(' expression (',' expression)* ')';
intConst : ('+'|'-')? NUMBER ;
fpConst : ('+'|'-')? NUMBER? '.' NUMBER? ('E' intConst)? ;
// lexer rules
// prefix area processing
COMMENT : {getCharPositionInLine() == 0}? 'C' ~('\n')* '\n'? -> skip ;
STMTNUM : {getCharPositionInLine() < 5}? [0-9]+ ;
CONTINUE : NEWCARD . . . . . ~[' '|'0'] -> skip ;
// body processing
ID : {getCharPositionInLine() > 5}? [A-Z][A-Z0-9]* ;
NUMBER : {getCharPositionInLine() > 5}? [0-9]+ ;
// return newlines to parser
NEWCARD : '\r'? '\n' ;
// skip spaces and tabs
WS : ' '+ -> skip ;
|
grammar Footran;
@header {
package com.github.oreissig.footran1.parser;
}
// parser rules
program : card*;
card : STMTNUM? statement NEWCARD?;
statement : arithmeticFormula
// TODO more to come
;
arithmeticFormula : ID '=' expression;
expression : ID | call | intConst | fpConst;
// treat subscripted variables as function calls
call : ID '(' expression (',' expression)* ')';
intConst : ('+'|'-')? NUMBER ;
fpConst : ('+'|'-')? NUMBER? '.' NUMBER? ('E' intConst)? ;
// lexer rules
// prefix area processing
COMMENT : {getCharPositionInLine() == 0}? 'C' ~('\n')* '\n'? -> skip ;
STMTNUM : {getCharPositionInLine() < 5}? [0-9]+ ;
CONTINUE : NEWCARD . . . . . ~[' '|'0'] -> skip ;
// body processing
fragment DIGIT : {getCharPositionInLine() > 5}? [0-9];
fragment LETTER : {getCharPositionInLine() > 5}? [A-Z];
fragment ALFNUM : {getCharPositionInLine() > 5}? [A-Z0-9];
ID : LETTER ALFNUM* ;
NUMBER : DIGIT+ ;
// return newlines to parser
NEWCARD : '\r'? '\n' ;
// skip spaces and tabs
WS : ' '+ -> skip ;
|
use fragments for single chars
|
use fragments for single chars
|
ANTLR
|
isc
|
oreissig/FOOTRAN-I
|
f91e584a8dc177df91049cc2790d45bcb15f6bc3
|
LanguageServer/BisonLexer.g4
|
LanguageServer/BisonLexer.g4
|
// Author -- Ken Domino
// Copyright 2020
// MIT License
lexer grammar BisonLexer;
options {
superClass = BisonLexerAdaptor ;
}
channels {
OFF_CHANNEL // non-default channel for whitespace and comments
}
tokens {
SC_EPILOGUE
}
// ======================= Common fragments =========================
fragment Underscore
: '_'
;
fragment NameStartChar
: 'A'..'Z'
| 'a'..'z'
| '_'
| '\u00C0'..'\u00D6'
| '\u00D8'..'\u00F6'
| '\u00F8'..'\u02FF'
| '\u0370'..'\u037D'
| '\u037F'..'\u1FFF'
| '\u200C'..'\u200D'
| '\u2070'..'\u218F'
| '\u2C00'..'\u2FEF'
| '\u3001'..'\uD7FF'
| '\uF900'..'\uFDCF'
| '\uFDF0'..'\uFFFD'
| '$' // For PHP
; // ignores | ['\u10000-'\uEFFFF] ;
fragment DQuoteLiteral
: DQuote ( EscSeq | ~["\r\n\\] | ( '\\' [\n\r]*) )* DQuote
;
fragment DQuote
: '"'
;
fragment SQuote
: '\''
;
fragment CharLiteral
: SQuote ( EscSeq | ~['\r\n\\] ) SQuote
;
fragment SQuoteLiteral
: SQuote ( EscSeq | ~['\r\n\\] )* SQuote
;
fragment Esc
: '\\'
;
fragment EscSeq
: Esc
([abefnrtv?"'\\] // The standard escaped character set such as tab, newline, etc.
| [xuU]?[0-9]+) // C-style
;
fragment EscAny
: Esc .
;
fragment Id
: NameStartChar NameChar*
;
fragment Type
: ([\t\r\n\f a-zA-Z0-9] | '[' | ']' | '{' | '}' | '.' | '_' | '(' | ')' | ',')+
;
fragment NameChar
: NameStartChar
| '0'..'9'
| Underscore
| '\u00B7'
| '\u0300'..'\u036F'
| '\u203F'..'\u2040'
| '.'
| '-'
;
fragment BlockComment
: '/*'
(
('/' ~'*')
| ~'/'
)*
'*/'
;
fragment LineComment
: '//' ~[\r\n]*
;
fragment LineCommentExt
: '//' ~'\n'* ( '\n' Hws* '//' ~'\n'* )*
;
fragment Ws
: Hws
| Vws
;
fragment Hws
: [ \t]
;
fragment Vws
: [\r\n\f]
;
/* Four types of user code:
- prologue (code between '%{' '%}' in the first section, before %%);
- actions, printers, union, etc, (between braced in the middle section);
- epilogue (everything after the second %%).
- predicate (code between '%?{' and '{' in middle section); */
// -------------------------
// Actions
fragment LBrace
: '{'
;
fragment RBrace
: '}'
;
fragment PercentLBrace
: '%{'
;
fragment PercentRBrace
: '%}'
;
fragment PercentQuestion
: '%?{'
;
fragment ActionCode
: Stuff*
;
fragment Stuff
: EscAny
| DQuoteLiteral
| SQuoteLiteral
| BlockComment
| LineComment
| NestedAction
| ~('{' | '}' | '\'' | '"')
;
fragment NestedPrologue
: PercentLBrace ActionCode PercentRBrace
;
fragment NestedAction
: LBrace ActionCode RBrace
;
fragment NestedPredicate
: PercentQuestion ActionCode RBrace
;
fragment Sp
: Ws*
;
fragment Eqopt
: (Sp [=])?
;
PercentPercent: '%%'
{
++percent_percent_count;
if (percent_percent_count == 1)
{
//this.PushMode(BisonLexer.RuleMode);
return;
} else if (percent_percent_count == 2)
{
this.PushMode(BisonLexer.EpilogueMode);
return;
} else
{
this.Type = BisonLexer.PERCENT_PERCENT;
return;
}
}
;
/*----------------------------.
| Scanning Bison directives. |
`----------------------------*/
/* For directives that are also command line options, the regex must be
"%..."
after "[-_]"s are removed, and the directive must match the --long
option name, with a single string argument. Otherwise, add exceptions
to ../build-aux/cross-options.pl. */
NONASSOC
: '%binary'
;
CODE
: '%code'
;
PERCENT_DEBUG
: '%debug'
;
DEFAULT_PREC
: '%default-prec'
;
DEFINE
: '%define'
;
DEFINES
: '%defines'
;
DESTRUCTOR
: '%destructor'
;
DPREC
: '%dprec'
;
EMPTY_RULE
: '%empty'
;
EXPECT
: '%expect'
;
EXPECT_RR
: '%expect-rr'
;
PERCENT_FILE_PREFIX
: '%file-prefix'
;
INITIAL_ACTION
: '%initial-action'
;
GLR_PARSER
: '%glr-parser'
;
LANGUAGE
: '%language'
;
PERCENT_LEFT
: '%left'
;
LEX
: '%lex-param'
;
LOCATIONS
: '%locations'
;
MERGE
: '%merge'
;
NO_DEFAULT_PREC
: '%no-default-prec'
;
NO_LINES
: '%no-lines'
;
PERCENT_NONASSOC
: '%nonassoc'
;
NONDETERMINISTIC_PARSER
: '%nondeterministic-parser'
;
NTERM
: '%nterm'
;
PARAM
: '%param'
;
PARSE
: '%parse-param'
;
PERCENT_PREC
: '%prec'
;
PRECEDENCE
: '%precedence'
;
PRINTER
: '%printer'
;
REQUIRE
: '%require'
;
PERCENT_RIGHT
: '%right'
;
SKELETON
: '%skeleton'
;
PERCENT_START
: '%start'
;
TOKEN
: '%term'
;
PERCENT_TOKEN
: '%token'
;
TOKEN_TABLE
: '%token'[-_]'table'
;
PERCENT_TYPE
: '%type'
;
PERCENT_UNION
: '%union'
;
VERBOSE
: '%verbose'
;
PERCENT_YACC
: '%yacc'
;
/* Deprecated since Bison 2.3b (2008-05-27), but the warning is
issued only since Bison 3.4. */
PERCENT_PURE_PARSER
: '%pure'[-_]'parser'
;
/* Deprecated since Bison 2.6 (2012-07-19), but the warning is
issued only since Bison 3.3. */
PERCENT_NAME_PREFIX
: '%name'[-_]'prefix'(Eqopt)?(Sp)
;
/* Deprecated since Bison 2.7.90, 2012. */
OBS_DEFAULT_PREC
: '%default'[-_]'prec'
;
OBS_PERCENT_ERROR_VERBOSE
: '%error'[-_]'verbose'
;
OBS_EXPECT_RR
: '%expect'[-_]'rr'
;
OBS_PERCENT_FILE_PREFIX
: '%file-prefix'(Eqopt)
;
OBS_FIXED_OUTPUT
: '%fixed'[-_]'output'[-_]'files'
;
OBS_NO_DEFAULT_PREC
: '%no'[-_]'default'[-_]'prec'
;
OBS_NO_LINES
: '%no'[-_]'lines'
;
OBS_OUTPUT
: '%output' Eqopt
;
OBS_TOKEN_TABLE
: '%token'[-_]'table'
;
BRACED_CODE: NestedAction;
BRACED_PREDICATE: NestedPredicate;
BRACKETED_ID: '[' Id ']';
CHAR: CharLiteral;
COLON: ':';
//EPILOGUE: 'epilogue';
EQUAL: '=';
//ID_COLON: Id ':';
ID: Id;
PERCENT_PERCENT
: PercentPercent
;
PIPE: '|';
SEMICOLON: ';';
TAG: '<' Type '>';
TAG_ANY: '<*>';
TAG_NONE: '<>';
STRING: DQuoteLiteral;
INT: [0-9]+;
LPAREN: '(';
RPAREN: ')';
BLOCK_COMMENT
: BlockComment -> channel(OFF_CHANNEL)
;
LINE_COMMENT
: LineComment -> channel(OFF_CHANNEL)
;
WS : ( Hws | Vws )+ -> channel(OFF_CHANNEL) ;
PROLOGUE
: NestedPrologue
;
// ==============================================================
// Note, all prologue rules can be used in grammar declarations.
// ==============================================================
//mode RuleMode;
mode EpilogueMode;
EPILOGUE: .+ ;
|
// Author -- Ken Domino
// Copyright 2020
// MIT License
lexer grammar BisonLexer;
options {
superClass = BisonLexerAdaptor ;
}
channels {
OFF_CHANNEL // non-default channel for whitespace and comments
}
tokens {
SC_EPILOGUE
}
// ======================= Common fragments =========================
fragment Underscore
: '_'
;
fragment NameStartChar
: 'A'..'Z'
| 'a'..'z'
| '_'
| '\u00C0'..'\u00D6'
| '\u00D8'..'\u00F6'
| '\u00F8'..'\u02FF'
| '\u0370'..'\u037D'
| '\u037F'..'\u1FFF'
| '\u200C'..'\u200D'
| '\u2070'..'\u218F'
| '\u2C00'..'\u2FEF'
| '\u3001'..'\uD7FF'
| '\uF900'..'\uFDCF'
| '\uFDF0'..'\uFFFD'
| '$' // For PHP
; // ignores | ['\u10000-'\uEFFFF] ;
fragment DQuoteLiteral
: DQuote ( EscSeq | ~["\r\n\\] | ( '\\' [\n\r]*) )* DQuote
;
fragment DQuote
: '"'
;
fragment SQuote
: '\''
;
fragment CharLiteral
: SQuote ( EscSeq | ~['\r\n\\] ) SQuote
;
fragment SQuoteLiteral
: SQuote ( EscSeq | ~['\r\n\\] )* SQuote
;
fragment Esc
: '\\'
;
fragment EscSeq
: Esc
([abefnrtv?"'\\] // The standard escaped character set such as tab, newline, etc.
| [xuU]?[0-9]+) // C-style
;
fragment EscAny
: Esc .
;
fragment Id
: NameStartChar NameChar*
;
fragment Type
: ([\t\r\n\f a-zA-Z0-9] | '[' | ']' | '{' | '}' | '.' | '_' | '(' | ')' | ',')+
;
fragment NameChar
: NameStartChar
| '0'..'9'
| Underscore
| '\u00B7'
| '\u0300'..'\u036F'
| '\u203F'..'\u2040'
| '.'
| '-'
;
fragment BlockComment
: '/*'
(
('/' ~'*')
| ~'/'
)*
'*/'
;
fragment LineComment
: '//' ~[\r\n]*
;
fragment LineCommentExt
: '//' ~'\n'* ( '\n' Hws* '//' ~'\n'* )*
;
fragment Ws
: Hws
| Vws
;
fragment Hws
: [ \t]
;
fragment Vws
: [\r\n\f]
;
/* Four types of user code:
- prologue (code between '%{' '%}' in the first section, before %%);
- actions, printers, union, etc, (between braced in the middle section);
- epilogue (everything after the second %%).
- predicate (code between '%?{' and '{' in middle section); */
// -------------------------
// Actions
fragment LBrace
: '{'
;
fragment RBrace
: '}'
;
fragment PercentLBrace
: '%{'
;
fragment PercentRBrace
: '%}'
;
fragment PercentQuestion
: '%?{'
;
fragment ActionCode
: Stuff*
;
fragment Stuff
: EscAny
| DQuoteLiteral
| SQuoteLiteral
| BlockComment
| LineComment
| NestedAction
| ~('{' | '}' | '\'' | '"')
;
fragment NestedPrologue
: PercentLBrace ActionCode PercentRBrace
;
fragment NestedAction
: LBrace ActionCode RBrace
;
fragment NestedPredicate
: PercentQuestion ActionCode RBrace
;
fragment Sp
: Ws*
;
fragment Eqopt
: (Sp [=])?
;
PercentPercent: '%%'
{
++percent_percent_count;
if (percent_percent_count == 1)
{
//this.PushMode(BisonLexer.RuleMode);
return;
} else if (percent_percent_count == 2)
{
this.PushMode(BisonLexer.EpilogueMode);
return;
} else
{
this.Type = BisonLexer.PERCENT_PERCENT;
return;
}
}
;
/*----------------------------.
| Scanning Bison directives. |
`----------------------------*/
/* For directives that are also command line options, the regex must be
"%..."
after "[-_]"s are removed, and the directive must match the --long
option name, with a single string argument. Otherwise, add exceptions
to ../build-aux/cross-options.pl. */
NONASSOC
: '%binary'
;
CODE
: '%code'
;
PERCENT_DEBUG
: '%debug'
;
DEFAULT_PREC
: '%default-prec'
;
DEFINE
: '%define'
;
DEFINES
: '%defines'
;
DESTRUCTOR
: '%destructor'
;
DPREC
: '%dprec'
;
EMPTY_RULE
: '%empty'
;
EXPECT
: '%expect'
;
EXPECT_RR
: '%expect-rr'
;
PERCENT_FILE_PREFIX
: '%file-prefix'
;
INITIAL_ACTION
: '%initial-action'
;
GLR_PARSER
: '%glr-parser'
;
LANGUAGE
: '%language'
;
PERCENT_LEFT
: '%left'
;
LEX
: '%lex-param'
;
LOCATIONS
: '%locations'
;
MERGE
: '%merge'
;
NO_DEFAULT_PREC
: '%no-default-prec'
;
NO_LINES
: '%no-lines'
;
PERCENT_NONASSOC
: '%nonassoc'
;
NONDETERMINISTIC_PARSER
: '%nondeterministic-parser'
;
NTERM
: '%nterm'
;
PARAM
: '%param'
;
PARSE
: '%parse-param'
;
PERCENT_PREC
: '%prec'
;
PRECEDENCE
: '%precedence'
;
PRINTER
: '%printer'
;
REQUIRE
: '%require'
;
PERCENT_RIGHT
: '%right'
;
SKELETON
: '%skeleton'
;
PERCENT_START
: '%start'
;
TOKEN
: '%term'
;
PERCENT_TOKEN
: '%token'
;
TOKEN_TABLE
: '%token'[-_]'table'
;
PERCENT_TYPE
: '%type'
;
PERCENT_UNION
: '%union'
;
VERBOSE
: '%verbose'
;
PERCENT_YACC
: '%yacc'
;
/* Deprecated since Bison 2.3b (2008-05-27), but the warning is
issued only since Bison 3.4. */
PERCENT_PURE_PARSER
: '%pure'[-_]'parser'
;
/* Deprecated since Bison 2.6 (2012-07-19), but the warning is
issued only since Bison 3.3. */
PERCENT_NAME_PREFIX
: '%name'[-_]'prefix'(Eqopt)?(Sp)
;
/* Deprecated since Bison 2.7.90, 2012. */
OBS_DEFAULT_PREC
: '%default'[-_]'prec'
;
OBS_PERCENT_ERROR_VERBOSE
: '%error'[-_]'verbose'
;
OBS_EXPECT_RR
: '%expect'[-_]'rr'
;
OBS_PERCENT_FILE_PREFIX
: '%file-prefix'(Eqopt)
;
OBS_FIXED_OUTPUT
: '%fixed'[-_]'output'[-_]'files'
;
OBS_NO_DEFAULT_PREC
: '%no'[-_]'default'[-_]'prec'
;
OBS_NO_LINES
: '%no'[-_]'lines'
;
OBS_OUTPUT
: '%output' Eqopt
;
OBS_TOKEN_TABLE
: '%token'[-_]'table'
;
BRACED_CODE: NestedAction;
BRACED_PREDICATE: NestedPredicate;
BRACKETED_ID: '[' Id ']';
CHAR: CharLiteral;
COLON: ':';
//EPILOGUE: 'epilogue';
EQUAL: '=';
//ID_COLON: Id ':';
ID: Id;
PERCENT_PERCENT
: PercentPercent
;
PIPE: '|';
SEMICOLON: ';';
TAG: '<' Type '>';
TAG_ANY: '<*>';
TAG_NONE: '<>';
STRING: DQuoteLiteral;
INT: [0-9]+;
LPAREN: '(';
RPAREN: ')';
BLOCK_COMMENT
: BlockComment -> channel(OFF_CHANNEL)
;
LINE_COMMENT
: LineComment -> channel(OFF_CHANNEL)
;
WS : ( Hws | Vws )+ -> channel(OFF_CHANNEL) ;
PROLOGUE
: NestedPrologue
;
// ==============================================================
// Note, all prologue rules can be used in grammar declarations.
// ==============================================================
//mode RuleMode;
mode EpilogueMode;
// Expected: Warning AC0131 greedy block ()+ contains wildcard; the non-greedy syntax ()+? may be preferred LanguageServer
EPILOGUE: .+ ;
|
Add comment for expected warning. It would be good to have #pragma's for Antlr files maybe?
|
Add comment for expected warning. It would be good to have #pragma's for Antlr files maybe?
|
ANTLR
|
mit
|
kaby76/AntlrVSIX,kaby76/AntlrVSIX,kaby76/AntlrVSIX,kaby76/AntlrVSIX,kaby76/AntlrVSIX
|
10d6e3ee9399fda64496b2505bb17c209b3c6509
|
solidity/Solidity.g4
|
solidity/Solidity.g4
|
// Copyright 2016-2017 Federico Bond <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
grammar Solidity;
sourceUnit
: (pragmaDirective | importDirective | contractDefinition)* EOF ;
pragmaDirective
: 'pragma' pragmaName pragmaValue ';' ;
pragmaName
: identifier ;
pragmaValue
: version | expression ;
version
: versionConstraint versionConstraint? ;
versionOperator
: '^' | '>=' | '>' | '<' | '<=' ;
versionConstraint
: versionOperator? VersionLiteral ;
importDeclaration
: identifier ('as' identifier)? ;
importDirective
: 'import' StringLiteral ('as' identifier)? ';'
| 'import' ('*' | identifier) ('as' identifier)? 'from' StringLiteral ';'
| 'import' '{' importDeclaration ( ',' importDeclaration )* '}' 'from' StringLiteral ';' ;
contractDefinition
: ( 'contract' | 'interface' | 'library' ) identifier
( 'is' inheritanceSpecifier (',' inheritanceSpecifier )* )?
'{' contractPart* '}' ;
inheritanceSpecifier
: userDefinedTypeName ( '(' expression ( ',' expression )* ')' )? ;
contractPart
: stateVariableDeclaration
| usingForDeclaration
| structDefinition
| modifierDefinition
| functionDefinition
| eventDefinition
| enumDefinition ;
stateVariableDeclaration
: typeName
( PublicKeyword | InternalKeyword | PrivateKeyword | ConstantKeyword )*
identifier ('=' expression)? ';' ;
usingForDeclaration
: 'using' identifier 'for' ('*' | typeName) ';' ;
structDefinition
: 'struct' identifier
'{' ( variableDeclaration ';' (variableDeclaration ';')* )? '}' ;
modifierDefinition
: 'modifier' identifier parameterList? block ;
modifierInvocation
: identifier ( '(' expressionList? ')' )? ;
functionDefinition
: 'function' identifier? parameterList modifierList returnParameters? ( ';' | block ) ;
returnParameters
: 'returns' parameterList ;
modifierList
: ( modifierInvocation | stateMutability | ExternalKeyword
| PublicKeyword | InternalKeyword | PrivateKeyword )* ;
eventDefinition
: 'event' identifier 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
| simpleStatement ;
expressionStatement
: expression ';' ;
ifStatement
: 'if' '(' expression ')' statement ( 'else' statement )? ;
whileStatement
: 'while' '(' expression ')' statement ;
simpleStatement
: ( variableDeclarationStatement | expressionStatement ) ;
forStatement
: 'for' '(' ( simpleStatement | ';' ) expression? ';' expression? ')' statement ;
inlineAssemblyStatement
: 'assembly' StringLiteral? assemblyBlock ;
doWhileStatement
: 'do' statement 'while' '(' expression ')' ';' ;
continueStatement
: 'continue' ';' ;
breakStatement
: 'break' ';' ;
returnStatement
: 'return' expression? ';' ;
throwStatement
: 'throw' ';' ;
variableDeclarationStatement
: ( 'var' identifierList | variableDeclaration ) ( '=' expression )? ';';
identifierList
: '(' ( identifier? ',' )* identifier? ')' ;
elementaryTypeName
: 'address' | 'bool' | 'string' | 'var' | Int | Uint | 'byte' | Byte | Fixed | Ufixed ;
Int
: 'int' | 'int8' | 'int16' | 'int24' | 'int32' | 'int40' | 'int48' | 'int56' | 'int64' | 'int72' | 'int80' | 'int88' | 'int96' | 'int104' | 'int112' | 'int120' | 'int128' | 'int136' | 'int144' | 'int152' | 'int160' | 'int168' | 'int176' | 'int184' | 'int192' | 'int200' | 'int208' | 'int216' | 'int224' | 'int232' | 'int240' | 'int248' | 'int256' ;
Uint
: 'uint' | 'uint8' | 'uint16' | 'uint24' | 'uint32' | 'uint40' | 'uint48' | 'uint56' | 'uint64' | 'uint72' | 'uint80' | 'uint88' | 'uint96' | 'uint104' | 'uint112' | 'uint120' | 'uint128' | 'uint136' | 'uint144' | 'uint152' | 'uint160' | 'uint168' | 'uint176' | 'uint184' | 'uint192' | 'uint200' | 'uint208' | 'uint216' | 'uint224' | 'uint232' | 'uint240' | 'uint248' | 'uint256' ;
Byte
: 'bytes' | 'bytes1' | 'bytes2' | 'bytes3' | 'bytes4' | 'bytes5' | 'bytes6' | 'bytes7' | 'bytes8' | 'bytes9' | 'bytes10' | 'bytes11' | 'bytes12' | 'bytes13' | 'bytes14' | 'bytes15' | 'bytes16' | 'bytes17' | 'bytes18' | 'bytes19' | 'bytes20' | 'bytes21' | 'bytes22' | 'bytes23' | 'bytes24' | 'bytes25' | 'bytes26' | 'bytes27' | 'bytes28' | 'bytes29' | 'bytes30' | 'bytes31' | 'bytes32' ;
Fixed
: 'fixed' | ( 'fixed' [0-9]+ 'x' [0-9]+ ) ;
Ufixed
: 'ufixed' | ( 'ufixed' [0-9]+ 'x' [0-9]+ ) ;
expression
: expression ('++' | '--')
| 'new' typeName
| expression '[' expression ']'
| expression '(' functionCallArguments ')'
| expression '.' identifier
| '(' expression ')'
| ('++' | '--') expression
| ('+' | '-') expression
| ('after' | 'delete') expression
| '!' expression
| '~' expression
| expression '**' expression
| expression ('*' | '/' | '%') expression
| expression ('+' | '-') expression
| expression ('<<' | '>>') expression
| expression '&' expression
| expression '^' expression
| expression '|' expression
| expression ('<' | '>' | '<=' | '>=') expression
| expression ('==' | '!=') expression
| expression '&&' expression
| expression '||' expression
| expression '?' expression ':' expression
| expression ('=' | '|=' | '^=' | '&=' | '<<=' | '>>=' | '+=' | '-=' | '*=' | '/=' | '%=') expression
| primaryExpression ;
primaryExpression
: BooleanLiteral
| numberLiteral
| HexLiteral
| StringLiteral
| identifier
| tupleExpression
| elementaryTypeNameExpression ;
expressionList
: expression (',' expression)* ;
nameValueList
: nameValue (',' nameValue)* ','? ;
nameValue
: identifier ':' expression ;
functionCallArguments
: '{' nameValueList? '}'
| expressionList? ;
assemblyBlock
: '{' assemblyItem* '}' ;
assemblyItem
: identifier
| assemblyBlock
| assemblyExpression
| assemblyLocalDefinition
| assemblyAssignment
| assemblyStackAssignment
| labelDefinition
| assemblySwitch
| assemblyFunctionDefinition
| assemblyFor
| assemblyIf
| BreakKeyword
| ContinueKeyword
| subAssembly
| numberLiteral
| StringLiteral
| HexLiteral ;
assemblyExpression
: assemblyCall | assemblyLiteral ;
assemblyCall
: ( 'return' | 'address' | 'byte' | identifier ) ( '(' assemblyExpression? ( ',' assemblyExpression )* ')' )? ;
assemblyLocalDefinition
: 'let' assemblyIdentifierOrList ( ':=' assemblyExpression )? ;
assemblyAssignment
: assemblyIdentifierOrList ':=' assemblyExpression ;
assemblyIdentifierOrList
: identifier | '(' assemblyIdentifierList ')' ;
assemblyIdentifierList
: identifier ( ',' identifier )* ;
assemblyStackAssignment
: '=:' identifier ;
labelDefinition
: identifier ':' ;
assemblySwitch
: 'switch' assemblyExpression assemblyCase* ;
assemblyCase
: 'case' assemblyLiteral assemblyBlock
| 'default' assemblyBlock ;
assemblyFunctionDefinition
: 'function' identifier '(' assemblyIdentifierList? ')'
assemblyFunctionReturns? assemblyBlock ;
assemblyFunctionReturns
: ( '->' assemblyIdentifierList ) ;
assemblyFor
: 'for' ( assemblyBlock | assemblyExpression )
assemblyExpression ( assemblyBlock | assemblyExpression ) assemblyBlock ;
assemblyIf
: 'if' assemblyExpression assemblyBlock ;
assemblyLiteral
: StringLiteral | DecimalNumber | HexNumber | HexLiteral ;
subAssembly
: 'assembly' identifier assemblyBlock ;
tupleExpression
: '(' ( expression? ( ',' expression? )* ) ')'
| '[' ( expression ( ',' expression )* )? ']' ;
elementaryTypeNameExpression
: elementaryTypeName ;
numberLiteral
: (DecimalNumber | HexNumber) NumberUnit? ;
identifier
: ('from' | Identifier) ;
VersionLiteral
: [0-9]+ '.' [0-9]+ '.' [0-9]+ ;
BooleanLiteral
: 'true' | 'false' ;
DecimalNumber
: [0-9]+ ( '.' [0-9]* )? ( [eE] [0-9]+ )? ;
HexNumber
: '0x' HexCharacter+ ;
NumberUnit
: 'wei' | 'szabo' | 'finney' | 'ether'
| 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'years' ;
HexLiteral : 'hex' ('"' HexPair* '"' | '\'' HexPair* '\'') ;
fragment
HexPair
: HexCharacter HexCharacter ;
fragment
HexCharacter
: [0-9A-Fa-f] ;
ReservedKeyword
: 'abstract'
| 'after'
| 'case'
| 'catch'
| 'default'
| 'final'
| 'in'
| 'inline'
| 'let'
| 'match'
| 'null'
| 'of'
| 'relocatable'
| 'static'
| 'switch'
| 'try'
| 'type'
| 'typeof' ;
AnonymousKeyword : 'anonymous' ;
BreakKeyword : 'break' ;
ConstantKeyword : 'constant' ;
ContinueKeyword : 'continue' ;
ExternalKeyword : 'external' ;
IndexedKeyword : 'indexed' ;
InternalKeyword : 'internal' ;
PayableKeyword : 'payable' ;
PrivateKeyword : 'private' ;
PublicKeyword : 'public' ;
PureKeyword : 'pure' ;
ViewKeyword : 'view' ;
Identifier
: IdentifierStart IdentifierPart* ;
fragment
IdentifierStart
: [a-zA-Z$_] ;
fragment
IdentifierPart
: [a-zA-Z0-9$_] ;
StringLiteral
: '"' DoubleQuotedStringCharacter* '"'
| '\'' SingleQuotedStringCharacter* '\'' ;
fragment
DoubleQuotedStringCharacter
: ~["\r\n\\] | ('\\' .) ;
fragment
SingleQuotedStringCharacter
: ~['\r\n\\] | ('\\' .) ;
WS
: [ \t\r\n\u000C]+ -> skip ;
COMMENT
: '/*' .*? '*/' -> channel(HIDDEN) ;
LINE_COMMENT
: '//' ~[\r\n]* -> channel(HIDDEN) ;
|
// Copyright 2016-2017 Federico Bond <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
grammar Solidity;
sourceUnit
: (pragmaDirective | importDirective | contractDefinition)* EOF ;
pragmaDirective
: 'pragma' pragmaName pragmaValue ';' ;
pragmaName
: identifier ;
pragmaValue
: version | expression ;
version
: versionConstraint versionConstraint? ;
versionOperator
: '^' | '~' | '>=' | '>' | '<' | '<=' | '=' ;
versionConstraint
: versionOperator? VersionLiteral ;
importDeclaration
: identifier ('as' identifier)? ;
importDirective
: 'import' StringLiteral ('as' identifier)? ';'
| 'import' ('*' | identifier) ('as' identifier)? 'from' StringLiteral ';'
| 'import' '{' importDeclaration ( ',' importDeclaration )* '}' 'from' StringLiteral ';' ;
contractDefinition
: ( 'contract' | 'interface' | 'library' ) identifier
( 'is' inheritanceSpecifier (',' inheritanceSpecifier )* )?
'{' contractPart* '}' ;
inheritanceSpecifier
: userDefinedTypeName ( '(' expression ( ',' expression )* ')' )? ;
contractPart
: stateVariableDeclaration
| usingForDeclaration
| structDefinition
| constructorDefinition
| modifierDefinition
| functionDefinition
| eventDefinition
| enumDefinition ;
stateVariableDeclaration
: typeName
( PublicKeyword | InternalKeyword | PrivateKeyword | ConstantKeyword )*
identifier ('=' expression)? ';' ;
usingForDeclaration
: 'using' identifier 'for' ('*' | typeName) ';' ;
structDefinition
: 'struct' identifier
'{' ( variableDeclaration ';' (variableDeclaration ';')* )? '}' ;
constructorDefinition
: 'constructor' parameterList modifierList block ;
modifierDefinition
: 'modifier' identifier parameterList? block ;
modifierInvocation
: identifier ( '(' expressionList? ')' )? ;
functionDefinition
: 'function' identifier? parameterList modifierList returnParameters? ( ';' | block ) ;
returnParameters
: 'returns' parameterList ;
modifierList
: ( modifierInvocation | stateMutability | ExternalKeyword
| PublicKeyword | InternalKeyword | PrivateKeyword )* ;
eventDefinition
: 'event' identifier eventParameterList AnonymousKeyword? ';' ;
enumValue
: identifier ;
enumDefinition
: 'enum' identifier '{' enumValue? (',' enumValue)* '}' ;
parameterList
: '(' ( parameter (',' parameter)* )? ')' ;
parameter
: typeName storageLocation? identifier? ;
eventParameterList
: '(' ( eventParameter (',' eventParameter)* )? ')' ;
eventParameter
: typeName IndexedKeyword? identifier? ;
functionTypeParameterList
: '(' ( functionTypeParameter (',' functionTypeParameter)* )? ')' ;
functionTypeParameter
: typeName storageLocation? ;
variableDeclaration
: typeName storageLocation? identifier ;
typeName
: elementaryTypeName
| userDefinedTypeName
| mapping
| typeName '[' expression? ']'
| functionTypeName ;
userDefinedTypeName
: identifier ( '.' identifier )* ;
mapping
: 'mapping' '(' elementaryTypeName '=>' typeName ')' ;
functionTypeName
: 'function' functionTypeParameterList
( InternalKeyword | ExternalKeyword | stateMutability )*
( 'returns' functionTypeParameterList )? ;
storageLocation
: 'memory' | 'storage' | 'calldata';
stateMutability
: PureKeyword | ConstantKeyword | ViewKeyword | PayableKeyword ;
block
: '{' statement* '}' ;
statement
: ifStatement
| whileStatement
| forStatement
| block
| inlineAssemblyStatement
| doWhileStatement
| continueStatement
| breakStatement
| returnStatement
| throwStatement
| emitStatement
| simpleStatement ;
expressionStatement
: expression ';' ;
ifStatement
: 'if' '(' expression ')' statement ( 'else' statement )? ;
whileStatement
: 'while' '(' expression ')' statement ;
simpleStatement
: ( variableDeclarationStatement | expressionStatement ) ;
forStatement
: 'for' '(' ( simpleStatement | ';' ) expression? ';' expression? ')' statement ;
inlineAssemblyStatement
: 'assembly' StringLiteral? assemblyBlock ;
doWhileStatement
: 'do' statement 'while' '(' expression ')' ';' ;
continueStatement
: 'continue' ';' ;
breakStatement
: 'break' ';' ;
returnStatement
: 'return' expression? ';' ;
throwStatement
: 'throw' ';' ;
emitStatement
: 'emit' functionCall ';' ;
variableDeclarationStatement
: ( 'var' identifierList | variableDeclaration | '(' variableDeclarationList ')' ) ( '=' expression )? ';';
variableDeclarationList
: variableDeclaration? (',' variableDeclaration? )* ;
identifierList
: '(' ( identifier? ',' )* identifier? ')' ;
elementaryTypeName
: 'address' | 'bool' | 'string' | 'var' | Int | Uint | 'byte' | Byte | Fixed | Ufixed ;
Int
: 'int' | 'int8' | 'int16' | 'int24' | 'int32' | 'int40' | 'int48' | 'int56' | 'int64' | 'int72' | 'int80' | 'int88' | 'int96' | 'int104' | 'int112' | 'int120' | 'int128' | 'int136' | 'int144' | 'int152' | 'int160' | 'int168' | 'int176' | 'int184' | 'int192' | 'int200' | 'int208' | 'int216' | 'int224' | 'int232' | 'int240' | 'int248' | 'int256' ;
Uint
: 'uint' | 'uint8' | 'uint16' | 'uint24' | 'uint32' | 'uint40' | 'uint48' | 'uint56' | 'uint64' | 'uint72' | 'uint80' | 'uint88' | 'uint96' | 'uint104' | 'uint112' | 'uint120' | 'uint128' | 'uint136' | 'uint144' | 'uint152' | 'uint160' | 'uint168' | 'uint176' | 'uint184' | 'uint192' | 'uint200' | 'uint208' | 'uint216' | 'uint224' | 'uint232' | 'uint240' | 'uint248' | 'uint256' ;
Byte
: 'bytes' | 'bytes1' | 'bytes2' | 'bytes3' | 'bytes4' | 'bytes5' | 'bytes6' | 'bytes7' | 'bytes8' | 'bytes9' | 'bytes10' | 'bytes11' | 'bytes12' | 'bytes13' | 'bytes14' | 'bytes15' | 'bytes16' | 'bytes17' | 'bytes18' | 'bytes19' | 'bytes20' | 'bytes21' | 'bytes22' | 'bytes23' | 'bytes24' | 'bytes25' | 'bytes26' | 'bytes27' | 'bytes28' | 'bytes29' | 'bytes30' | 'bytes31' | 'bytes32' ;
Fixed
: 'fixed' | ( 'fixed' [0-9]+ 'x' [0-9]+ ) ;
Ufixed
: 'ufixed' | ( 'ufixed' [0-9]+ 'x' [0-9]+ ) ;
expression
: expression ('++' | '--')
| 'new' typeName
| expression '[' expression ']'
| expression '(' functionCallArguments ')'
| expression '.' identifier
| '(' expression ')'
| ('++' | '--') expression
| ('+' | '-') expression
| ('after' | 'delete') expression
| '!' expression
| '~' expression
| expression '**' expression
| expression ('*' | '/' | '%') expression
| expression ('+' | '-') expression
| expression ('<<' | '>>') expression
| expression '&' expression
| expression '^' expression
| expression '|' expression
| expression ('<' | '>' | '<=' | '>=') expression
| expression ('==' | '!=') expression
| expression '&&' expression
| expression '||' expression
| expression '?' expression ':' expression
| expression ('=' | '|=' | '^=' | '&=' | '<<=' | '>>=' | '+=' | '-=' | '*=' | '/=' | '%=') expression
| primaryExpression ;
primaryExpression
: BooleanLiteral
| numberLiteral
| HexLiteral
| StringLiteral
| identifier
| tupleExpression
| elementaryTypeNameExpression ;
expressionList
: expression (',' expression)* ;
nameValueList
: nameValue (',' nameValue)* ','? ;
nameValue
: identifier ':' expression ;
functionCallArguments
: '{' nameValueList? '}'
| expressionList? ;
functionCall
: expression '(' functionCallArguments ')' ;
assemblyBlock
: '{' assemblyItem* '}' ;
assemblyItem
: identifier
| assemblyBlock
| assemblyExpression
| assemblyLocalDefinition
| assemblyAssignment
| assemblyStackAssignment
| labelDefinition
| assemblySwitch
| assemblyFunctionDefinition
| assemblyFor
| assemblyIf
| BreakKeyword
| ContinueKeyword
| subAssembly
| numberLiteral
| StringLiteral
| HexLiteral ;
assemblyExpression
: assemblyCall | assemblyLiteral ;
assemblyCall
: ( 'return' | 'address' | 'byte' | identifier ) ( '(' assemblyExpression? ( ',' assemblyExpression )* ')' )? ;
assemblyLocalDefinition
: 'let' assemblyIdentifierOrList ( ':=' assemblyExpression )? ;
assemblyAssignment
: assemblyIdentifierOrList ':=' assemblyExpression ;
assemblyIdentifierOrList
: identifier | '(' assemblyIdentifierList ')' ;
assemblyIdentifierList
: identifier ( ',' identifier )* ;
assemblyStackAssignment
: '=:' identifier ;
labelDefinition
: identifier ':' ;
assemblySwitch
: 'switch' assemblyExpression assemblyCase* ;
assemblyCase
: 'case' assemblyLiteral assemblyBlock
| 'default' assemblyBlock ;
assemblyFunctionDefinition
: 'function' identifier '(' assemblyIdentifierList? ')'
assemblyFunctionReturns? assemblyBlock ;
assemblyFunctionReturns
: ( '->' assemblyIdentifierList ) ;
assemblyFor
: 'for' ( assemblyBlock | assemblyExpression )
assemblyExpression ( assemblyBlock | assemblyExpression ) assemblyBlock ;
assemblyIf
: 'if' assemblyExpression assemblyBlock ;
assemblyLiteral
: StringLiteral | DecimalNumber | HexNumber | HexLiteral ;
subAssembly
: 'assembly' identifier assemblyBlock ;
tupleExpression
: '(' ( expression? ( ',' expression? )* ) ')'
| '[' ( expression ( ',' expression )* )? ']' ;
elementaryTypeNameExpression
: elementaryTypeName ;
numberLiteral
: (DecimalNumber | HexNumber) NumberUnit? ;
identifier
: ('from' | Identifier) ;
VersionLiteral
: [0-9]+ '.' [0-9]+ '.' [0-9]+ ;
BooleanLiteral
: 'true' | 'false' ;
DecimalNumber
: [0-9]+ ( '.' [0-9]* )? ( [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) ;
|
Update Solidity grammar with latest constructs
|
Update Solidity grammar with latest constructs
|
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
|
1b77e60abf23611723e4cbd4fc831fea9933efc4
|
Liquid.NET.Grammar/LiquidLexer.g4
|
Liquid.NET.Grammar/LiquidLexer.g4
|
lexer grammar LiquidLexer;
@lexer::header {#pragma warning disable 3021}
@lexer::members {
public static readonly int WHITESPACE = 1;
int arraybracketcount = 0;
}
// MB: TODO: wait for "channels {}" syntax
// see: https://github.com/antlr/antlr4/pull/694
COMMENT : COMMENTSTART ( COMMENT | . )*? COMMENTEND -> skip ; // TODO: skip
fragment COMMENTSTART: TAGSTART [ \t]* 'comment' [ \t]* TAGEND ;
fragment COMMENTEND: TAGSTART [ \t]* 'endcomment' [ \t]* TAGEND ;
RAW : RAWSTART RAWBLOCK RAWEND ;
RAWBLOCK: ( RAW | . )*?;
fragment RAWSTART: TAGSTART [ \t]* 'raw' [ \t]* TAGEND ;
fragment RAWEND: TAGSTART [ \t]* 'endraw' [ \t]* TAGEND ;
TAGSTART : '{%' -> pushMode(INLIQUIDTAG) ;
OUTPUTMKUPSTART : '{{' -> pushMode(INLIQUIDFILTER) ;
//TEXT : .+? ;
TEXT : .+? ;
mode NOMODE;
NUMBER : '-'? INT '.' [0-9]+ EXP? // 1.35, 1.35E-9, 0.3, -4.5
| '-'? INT EXP // 1e10 -3e4
| '-'? INT // -3, 45
;
INT : '0' | [1-9] [0-9]* ; // no leading zeros
fragment EXP : [Ee] [+\-]? INT ; // \- since - means "range" inside [...]
BOOLEAN : 'true' | 'false' ;
STRING : '"' STRDOUBLE '"' | '\'' STRSINGLE '\'' ;
fragment STRDOUBLE : (ESC | ~["\\])* ;
fragment STRSINGLE : (ESC | ~['\\])* ;
fragment ESC : '\\' (["\\/bfnrt] | UNICODE) ;
fragment UNICODE : 'u' HEX HEX HEX HEX ;
fragment HEX : [0-9a-fA-F] ;
LABEL : ALPHA (ALPHA|DIGIT|UNDERSCORE)* ;
fragment UNDERSCORE: '_' ;
fragment ALPHA: [a-zA-Z] ;
fragment DIGIT: [0-9] ;
FILTERPIPE : '|' ;
PERIOD: '.' ;
ARRAYSTART : '[' ;
ARRAYEND : ']' ;
GENERATORSTART : '(';
GENERATOREND : ')';
GENERATORRANGE : '..';
// ========= COMMENT ===================
mode INCOMMENT;
NESTEDCOMMENT : '{%' [ \t]+ 'comment' [ \t]+ '%}' -> pushMode(INCOMMENT);
COMMENT_END: '{%' [ \t]+ 'endcomment' [ \t]+ '%}' -> popMode ;
TEXT1 : .+? -> channel(HIDDEN);
// ========= LIQUID FILTERS ============
mode INLIQUIDFILTER ;
OUTPUTMKUPEND : '}}' -> popMode ;
FILTERPIPE1 : FILTERPIPE -> type(FILTERPIPE) ;
PERIOD1: PERIOD -> type(PERIOD) ;
NUMBER1: NUMBER -> type(NUMBER);
BOOLEAN1: BOOLEAN -> type(BOOLEAN);
STRING1: STRING -> type(STRING);
LABEL1: LABEL -> type(LABEL);
ARRAYSTART1 : '[' -> pushMode(INARRAYINDEX), type(ARRAYSTART) ;
ARRAYEND1 : ']' -> type(ARRAYEND);
COMMA : ',' ;
COLON : ':' ;
WS : [ \t\r\n]+ -> skip ;
mode INARRAYINDEX ;
ARRAYSTART2 : ARRAYSTART {arraybracketcount++; System.Console.WriteLine("** Encountered nested '[' " +arraybracketcount);} -> type(ARRAYSTART);
ARRAYEND2a : {arraybracketcount == 0; }? ARRAYEND {System.Console.WriteLine("** leaving mode " +arraybracketcount);} -> type(ARRAYEND), popMode ;
ARRAYEND2b : {arraybracketcount > 0; }? ARRAYEND { arraybracketcount--; System.Console.WriteLine("* closed nested ']' " +arraybracketcount); } -> type(ARRAYEND);
ARRAYINT: '0' | [1-9] [0-9]* ;
STRING3: STRING -> type(STRING);
LABEL3: LABEL -> type(LABEL);
// ========= LIQUID TAGS ============
mode INLIQUIDTAG ;
TAGEND : '%}' -> popMode ;
INCLUDE_TAG : 'include' ;
IF_TAG : 'if' ;
UNLESS_TAG : 'unless' ;
CASE_TAG : 'case' ;
WHEN_TAG : 'when' ;
ENDCASE_TAG : 'endcase' ;
ELSIF_TAG : 'elsif' ;
ELSE_TAG : 'else' ;
ENDIF_TAG : 'endif' ;
ENDUNLESS_TAG : 'endunless' ;
FOR_TAG : 'for' ;
FOR_IN : 'in';
PARAM_REVERSED: 'reversed';
PARAM_OFFSET: 'offset' ;
PARAM_LIMIT: 'limit' ;
ENDFOR_TAG : 'endfor' ;
CYCLE_TAG : 'cycle' ;
ASSIGN_TAG : 'assign';
CAPTURE_TAG : 'capture';
ENDCAPTURE_TAG : 'endcapture';
INCREMENT_TAG : 'increment';
DECREMENT_TAG : 'decrement';
COLON1 : ':' -> type(COLON);
COMMA1 : ',' -> type(COMMA);
ARRAYSTART3 : '[' -> pushMode(INARRAYINDEX), type(ARRAYSTART) ;
ARRAYEND3 : ']' -> type(ARRAYEND);
ASSIGNEQUALS : '=' ;
PARENOPEN : '(' ;
PARENCLOSE : ')' ;
GT: '>';
GTE: '>=';
EQ: '==';
NEQ: '!=';
LT: '<';
LTE: '<=';
CONTAINS: 'contains';
AND: 'and';
OR: 'or';
MULT: '*' ;
DIV: '/' ;
MOD: '%' ;
ADD: '+' ;
SUB: '-' ;
NEGATIVE : '-' ;
NOT : '!' ;
NUMBER2 : NUMBER -> type(NUMBER);
BOOLEAN2 : BOOLEAN -> type(BOOLEAN);
FILTERPIPE2 : FILTERPIPE -> type(FILTERPIPE) ;
COLON2 : COLON -> type(COLON);
PERIOD2 : PERIOD -> type(PERIOD) ;
STRING2: STRING -> type(STRING);
LABEL2: LABEL -> type(LABEL);
GENERATORRANGE1: GENERATORRANGE -> type(GENERATORRANGE) ;
WS2 : [ \t\r\n]+ -> skip ;
|
lexer grammar LiquidLexer;
@lexer::header {#pragma warning disable 3021}
@lexer::members {
public static readonly int WHITESPACE = 1;
int arraybracketcount = 0;
}
COMMENT : COMMENTSTART ( COMMENT | . )*? COMMENTEND -> skip ; // TODO: skip
fragment COMMENTSTART: TAGSTART [ \t]* 'comment' [ \t]* TAGEND ;
fragment COMMENTEND: TAGSTART [ \t]* 'endcomment' [ \t]* TAGEND ;
RAW : RAWSTART RAWBLOCK RAWEND ;
fragment RAWBLOCK: ( RAW | . )*?;
fragment RAWSTART: TAGSTART [ \t]* 'raw' [ \t]* TAGEND ;
fragment RAWEND: TAGSTART [ \t]* 'endraw' [ \t]* TAGEND ;
TAGSTART : '{%' -> pushMode(INLIQUIDTAG) ;
OUTPUTMKUPSTART : '{{' -> pushMode(INLIQUIDFILTER) ;
//TEXT : .+? ;
TEXT : .+? ;
mode NOMODE;
NUMBER : '-'? INT '.' [0-9]+ EXP? // 1.35, 1.35E-9, 0.3, -4.5
| '-'? INT EXP // 1e10 -3e4
| '-'? INT // -3, 45
;
INT : '0' | [1-9] [0-9]* ; // no leading zeros
fragment EXP : [Ee] [+\-]? INT ; // \- since - means "range" inside [...]
BOOLEAN : 'true' | 'false' ;
STRING : '"' STRDOUBLE '"' | '\'' STRSINGLE '\'' ;
fragment STRDOUBLE : (ESC | ~["\\])* ;
fragment STRSINGLE : (ESC | ~['\\])* ;
fragment ESC : '\\' (["\\/bfnrt] | UNICODE) ;
fragment UNICODE : 'u' HEX HEX HEX HEX ;
fragment HEX : [0-9a-fA-F] ;
LABEL : ALPHA (ALPHA|DIGIT|UNDERSCORE)* ;
fragment UNDERSCORE: '_' ;
fragment ALPHA: [a-zA-Z] ;
fragment DIGIT: [0-9] ;
FILTERPIPE : '|' ;
PERIOD: '.' ;
ARRAYSTART : '[' ;
ARRAYEND : ']' ;
GENERATORSTART : '(';
GENERATOREND : ')';
GENERATORRANGE : '..';
// ========= COMMENT ===================
mode INCOMMENT;
NESTEDCOMMENT : '{%' [ \t]+ 'comment' [ \t]+ '%}' -> pushMode(INCOMMENT);
COMMENT_END: '{%' [ \t]+ 'endcomment' [ \t]+ '%}' -> popMode ;
TEXT1 : .+? -> channel(HIDDEN);
// ========= LIQUID FILTERS ============
mode INLIQUIDFILTER ;
OUTPUTMKUPEND : '}}' -> popMode ;
FILTERPIPE1 : FILTERPIPE -> type(FILTERPIPE) ;
PERIOD1: PERIOD -> type(PERIOD) ;
NUMBER1: NUMBER -> type(NUMBER);
BOOLEAN1: BOOLEAN -> type(BOOLEAN);
STRING1: STRING -> type(STRING);
LABEL1: LABEL -> type(LABEL);
ARRAYSTART1 : '[' -> pushMode(INARRAYINDEX), type(ARRAYSTART) ;
ARRAYEND1 : ']' -> type(ARRAYEND);
COMMA : ',' ;
COLON : ':' ;
WS : [ \t\r\n]+ -> skip ;
mode INARRAYINDEX ;
ARRAYSTART2 : ARRAYSTART {arraybracketcount++; System.Console.WriteLine("** Encountered nested '[' " +arraybracketcount);} -> type(ARRAYSTART);
ARRAYEND2a : {arraybracketcount == 0; }? ARRAYEND {System.Console.WriteLine("** leaving mode " +arraybracketcount);} -> type(ARRAYEND), popMode ;
ARRAYEND2b : {arraybracketcount > 0; }? ARRAYEND { arraybracketcount--; System.Console.WriteLine("* closed nested ']' " +arraybracketcount); } -> type(ARRAYEND);
ARRAYINT: '0' | [1-9] [0-9]* ;
STRING3: STRING -> type(STRING);
LABEL3: LABEL -> type(LABEL);
// ========= LIQUID TAGS ============
mode INLIQUIDTAG ;
TAGEND : '%}' -> popMode ;
INCLUDE_TAG : 'include' ;
IF_TAG : 'if' ;
UNLESS_TAG : 'unless' ;
CASE_TAG : 'case' ;
WHEN_TAG : 'when' ;
ENDCASE_TAG : 'endcase' ;
ELSIF_TAG : 'elsif' ;
ELSE_TAG : 'else' ;
ENDIF_TAG : 'endif' ;
ENDUNLESS_TAG : 'endunless' ;
FOR_TAG : 'for' ;
FOR_IN : 'in';
PARAM_REVERSED: 'reversed';
PARAM_OFFSET: 'offset' ;
PARAM_LIMIT: 'limit' ;
ENDFOR_TAG : 'endfor' ;
CYCLE_TAG : 'cycle' ;
ASSIGN_TAG : 'assign';
CAPTURE_TAG : 'capture';
ENDCAPTURE_TAG : 'endcapture';
INCREMENT_TAG : 'increment';
DECREMENT_TAG : 'decrement';
COLON1 : ':' -> type(COLON);
COMMA1 : ',' -> type(COMMA);
ARRAYSTART3 : '[' -> pushMode(INARRAYINDEX), type(ARRAYSTART) ;
ARRAYEND3 : ']' -> type(ARRAYEND);
ASSIGNEQUALS : '=' ;
PARENOPEN : '(' ;
PARENCLOSE : ')' ;
GT: '>';
GTE: '>=';
EQ: '==';
NEQ: '!=';
LT: '<';
LTE: '<=';
CONTAINS: 'contains';
AND: 'and';
OR: 'or';
MULT: '*' ;
DIV: '/' ;
MOD: '%' ;
ADD: '+' ;
SUB: '-' ;
NEGATIVE : '-' ;
NOT : '!' ;
NUMBER2 : NUMBER -> type(NUMBER);
BOOLEAN2 : BOOLEAN -> type(BOOLEAN);
FILTERPIPE2 : FILTERPIPE -> type(FILTERPIPE) ;
COLON2 : COLON -> type(COLON);
PERIOD2 : PERIOD -> type(PERIOD) ;
STRING2: STRING -> type(STRING);
LABEL2: LABEL -> type(LABEL);
GENERATORRANGE1: GENERATORRANGE -> type(GENERATORRANGE) ;
WS2 : [ \t\r\n]+ -> skip ;
|
Fix lexer warning
|
Fix lexer warning
|
ANTLR
|
mit
|
mikebridge/Liquid.NET,mikebridge/Liquid.NET,mikebridge/Liquid.NET
|
9262be010fc7b651b71218b37bba338b0bcdf22e
|
toml/toml.g4
|
toml/toml.g4
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
grammar toml;
/*
* Parser Rules
*/
document : expression (NL expression)* ;
expression : key_value comment | table comment | comment ;
comment: COMMENT? ;
key_value : key '=' value ;
key : simple_key | dotted_key ;
simple_key : quoted_key | unquoted_key ;
unquoted_key : UNQUOTED_KEY ;
quoted_key : BASIC_STRING | LITERAL_STRING ;
dotted_key : simple_key ('.' simple_key)+ ;
value : string | integer | floating_point | bool_ | date_time | array_ | inline_table ;
string : BASIC_STRING | ML_BASIC_STRING | LITERAL_STRING | ML_LITERAL_STRING ;
integer : DEC_INT | HEX_INT | OCT_INT | BIN_INT ;
floating_point : FLOAT | INF | NAN ;
bool_ : BOOLEAN ;
date_time : OFFSET_DATE_TIME | LOCAL_DATE_TIME | LOCAL_DATE | LOCAL_TIME ;
array_ : '[' array_values? comment_or_nl ']' ;
array_values : (comment_or_nl value ',' array_values comment_or_nl) | comment_or_nl value ','? ;
comment_or_nl : (COMMENT? NL)* ;
table : standard_table | array_table ;
standard_table : '[' key ']' ;
inline_table : '{' inline_table_keyvals '}' ;
inline_table_keyvals : inline_table_keyvals_non_empty? ;
inline_table_keyvals_non_empty : key '=' value (',' inline_table_keyvals_non_empty)? ;
array_table : '[' '[' key ']' ']' ;
/*
* Lexer Rules
*/
WS : [ \t]+ -> skip ;
NL : ('\r'? '\n')+ ;
COMMENT : '#' (~[\n])* ;
fragment DIGIT : [0-9] ;
fragment ALPHA : [A-Za-z] ;
// booleans
BOOLEAN : 'true' | 'false' ;
// strings
fragment ESC : '\\' (["\\/bfnrt] | UNICODE | EX_UNICODE) ;
fragment ML_ESC : '\\' '\r'? '\n' | ESC ;
fragment UNICODE : 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ;
fragment EX_UNICODE : 'U' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ;
BASIC_STRING : '"' (ESC | ~["\\\n])*? '"' ;
ML_BASIC_STRING : '"""' (ML_ESC | ~["\\])*? '"""' ;
LITERAL_STRING : '\'' (~['\n])*? '\'' ;
ML_LITERAL_STRING : '\'\'\'' (.)*? '\'\'\'';
// floating point numbers
fragment EXP : ('e' | 'E') [+-]? ZERO_PREFIXABLE_INT ;
fragment ZERO_PREFIXABLE_INT : DIGIT (DIGIT | '_' DIGIT)* ;
fragment FRAC : '.' ZERO_PREFIXABLE_INT ;
FLOAT : DEC_INT ( EXP | FRAC EXP?) ;
INF : [+-]? 'inf' ;
NAN : [+-]? 'nan' ;
// integers
fragment HEX_DIGIT : [A-Fa-f] | DIGIT ;
fragment DIGIT_1_9 : [1-9] ;
fragment DIGIT_0_7 : [0-7] ;
fragment DIGIT_0_1 : [0-1] ;
DEC_INT : [+-]? (DIGIT | (DIGIT_1_9 (DIGIT | '_' DIGIT)+)) ;
HEX_INT : '0x' HEX_DIGIT (HEX_DIGIT | '_' HEX_DIGIT)* ;
OCT_INT : '0o' DIGIT_0_7 (DIGIT_0_7 | '_' DIGIT_0_7)* ;
BIN_INT : '0b' DIGIT_0_1 (DIGIT_0_1 | '_' DIGIT_0_1)* ;
// dates
fragment YEAR : DIGIT DIGIT DIGIT DIGIT ;
fragment MONTH : DIGIT DIGIT ;
fragment DAY : DIGIT DIGIT ;
fragment DELIM : 'T' | 't' ;
fragment HOUR : DIGIT DIGIT ;
fragment MINUTE : DIGIT DIGIT ;
fragment SECOND : DIGIT DIGIT ;
fragment SECFRAC : '.' DIGIT+ ;
fragment NUMOFFSET : ('+' | '-') HOUR ':' MINUTE ;
fragment OFFSET : 'Z' | NUMOFFSET ;
fragment PARTIAL_TIME : HOUR ':' MINUTE ':' SECOND SECFRAC? ;
fragment FULL_DATE : YEAR '-' MONTH '-' DAY ;
fragment FULL_TIME : PARTIAL_TIME OFFSET ;
OFFSET_DATE_TIME : FULL_DATE DELIM FULL_TIME ;
LOCAL_DATE_TIME : FULL_DATE DELIM PARTIAL_TIME ;
LOCAL_DATE : FULL_DATE ;
LOCAL_TIME : PARTIAL_TIME ;
// keys
UNQUOTED_KEY : (ALPHA | DIGIT | '-' | '_')+ ;
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
grammar toml;
/*
* Parser Rules
*/
document : expression (NL expression)* ;
expression : key_value comment | table comment | comment ;
comment: COMMENT? ;
key_value : key '=' value ;
key : simple_key | dotted_key ;
simple_key : quoted_key | unquoted_key ;
unquoted_key : UNQUOTED_KEY ;
quoted_key : BASIC_STRING | LITERAL_STRING ;
dotted_key : simple_key ('.' simple_key)+ ;
value : string | integer | floating_point | bool_ | date_time | array_ | inline_table ;
string : BASIC_STRING | ML_BASIC_STRING | LITERAL_STRING | ML_LITERAL_STRING ;
integer : DEC_INT | HEX_INT | OCT_INT | BIN_INT ;
floating_point : FLOAT | INF | NAN ;
bool_ : BOOLEAN ;
date_time : OFFSET_DATE_TIME | LOCAL_DATE_TIME | LOCAL_DATE | LOCAL_TIME ;
array_ : '[' array_values? comment_or_nl ']' ;
array_values : (comment_or_nl value 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 newline between value and following comma in inline arrays
|
[TOML] allow newline between value and following comma in inline arrays
|
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
|
e98db56cbaebd3d17094e77370a761ed2ffb7a2f
|
kirikiri-tjs/TJSParser.g4
|
kirikiri-tjs/TJSParser.g4
|
parser grammar TJSParser;
options {
tokenVocab=TJSLexer;
superClass=TJSBaseParser;
}
program
: statement* EOF
;
statement
: block
| variableStatement
| emptyStatement
| classDeclaration
| expressionStatement
| ifStatement
| iterationStatement
| continueStatement
| breakStatement
| returnStatement
| withStatement
| switchStatement
| throwStatement
| tryStatement
| debuggerStatement
| functionDeclaration
| propertyDefinition
;
block
: '{' statement* '}'
;
variableStatement
: varModifier variableDeclarationList eos
;
variableDeclarationList
: variableDeclaration (',' variableDeclaration)*
;
variableDeclaration
: Identifier ('=' singleExpression)? // ECMAScript 6: Array & Object Matching
;
emptyStatement
: SemiColon
;
expressionStatement
: expressionSequence eos
;
ifStatement
: If '(' expressionSequence ')' statement (Else statement)?
;
iterationStatement
: Do statement While '(' expressionSequence ')' eos # DoStatement
| While '(' expressionSequence ')' statement # WhileStatement
| For '(' expressionSequence? ';' expressionSequence? ';' expressionSequence? ')' statement # ForStatement
| For '(' varModifier variableDeclarationList ';' expressionSequence? ';' expressionSequence? ')' statement # ForVarStatement
;
varModifier
: Var | Const
|'('( Var | Const )')'
;
typeConverter
: '('(Int | Real | String )')'
| Int
| Real
| String
;
continueStatement
: Continue eos
;
breakStatement
: Break eos
;
returnStatement
: Return expressionSequence? eos
;
withStatement
: With '(' expressionSequence ')' statement
;
switchStatement
: Switch '(' expressionSequence ')' caseBlock
;
caseBlock
: '{' caseClauses? (defaultClause caseClauses?)? '}'
;
caseClauses
: caseClause+
;
caseClause
: Case expressionSequence ':' statement*
;
defaultClause
: Default ':' statement*
;
throwStatement
: Throw expressionSequence eos
;
tryStatement
: Try block (catchProduction finallyProduction? | finallyProduction)
;
catchProduction
: Catch ('(' Identifier? ')')? block
;
finallyProduction
: Finally block
;
debuggerStatement
: Debugger eos
;
functionDeclaration
: Function Identifier? ('(' functionParameters? ')')? block
;
classDeclaration
: Class Identifier (Extends singleExpression (',' singleExpression)* )? '{' classStatement* '}'
;
classStatement
: variableStatement
| functionDeclaration
| propertyDefinition
| classDeclaration
| singleExpression eos
| ifStatement // TODO: but why?
| emptyStatement
;
propertyDefinition // TJS Property define
: Property Identifier '{'
( Getter ('(' ')')? block
| Setter '(' functionParameter ')' block
)* '}'
;
functionParameters
: functionParameter (',' functionParameter)*
;
functionParameter
: Identifier ('=' singleExpression)? // TJS2, ECMAScript 6: Initialization
| Identifier? '*'
;
arrayLiteral
: varModifier? '[' ','* elementList? ','* ']'
;
elementList
: arrayElement ((','|'=>')+ arrayElement)*
;
arrayElement
: singleExpression
;
objectLiteral
: varModifier? '%[' propertyAssignment? (',' propertyAssignment)* ','?']'
;
propertySeprator
: ':' |'=' | '=>' | ','
;
propertyAssignment
: singleExpression propertySeprator singleExpression // TJS resolve object key in runtime
;
arguments
: '(' tjsArgument? (',' tjsArgument?)* ')'
| '(' ( Ellipsis | '*') ')' // ... means use argument (JS function argument)
;
tjsArgument // In TJS, argument can expanded by using *
: singleExpression '*'?
| '*'
;
expressionSequence
: singleExpression (',' singleExpression)*
;
// TODO: optimize this
singleExpression
: functionDeclaration # FunctionExpression
| singleExpression '[' expressionSequence ']' # MemberIndexExpression
| singleExpression '.' identifierName # MemberDotExpression
| singleExpression arguments # ArgumentsExpression
| New singleExpression arguments? # NewExpression
| singleExpression '++' # PostIncrementExpression
| singleExpression '--' # PostDecreaseExpression
| Delete singleExpression # DeleteExpression
| Void singleExpression? # VoidExpression
| Typeof singleExpression # TypeofExpression
| '++' singleExpression # PreIncrementExpression
| '--' singleExpression # PreDecreaseExpression
| '+' singleExpression # UnaryPlusExpression
| '-' singleExpression # UnaryMinusExpression
| '~' singleExpression # BitNotExpression
| '!' singleExpression # NotExpression
| singleExpression '!' # EvalExpression
| singleExpression ('*' | '/' | '%' | '\\') singleExpression # MultiplicativeExpression
| singleExpression ('+' | '-') singleExpression # AdditiveExpression
| singleExpression ('<<' | '>>' | '>>>') singleExpression # BitShiftExpression
| singleExpression ('<' | '>' | '<=' | '>=') singleExpression # RelationalExpression
| singleExpression Instanceof singleExpression # InstanceofExpression
| singleExpression In singleExpression # InExpression
| singleExpression ('==' | '!=' | '===' | '!==') singleExpression # EqualityExpression
| singleExpression '&' singleExpression # BitAndExpression
| singleExpression '^' singleExpression # BitXOrExpression
| singleExpression '|' singleExpression # BitOrExpression
| singleExpression '&&' singleExpression # LogicalAndExpression
| singleExpression '||' singleExpression # LogicalOrExpression
| singleExpression '?' singleExpression ':' singleExpression # TernaryExpression
| singleExpression '=' singleExpression # AssignmentExpression
| singleExpression '<->' singleExpression # SwapExpression
| singleExpression assignmentOperator singleExpression # AssignmentOperatorExpression
| singleExpression TemplateStringLiteral+ # TemplateStringExpression // ECMAScript 6, TJS has simillar feature
| This # ThisExpression
| Identifier # IdentifierExpression
| Super # SuperExpression
| typeConverter singleExpression # TypeConvertExpression
| literal # LiteralExpression
| arrayLiteral # ArrayLiteralExpression
| objectLiteral # ObjectLiteralExpression
| '(' expressionSequence ')' # ParenthesizedExpression
| singleExpression Incontextof singleExpression # InContextOfExpression
| singleExpression If singleExpression # TJSIfExpression
| Invalidate (('(' identifierName ')') |identifierName) # InvalidateExpression
| '&' singleExpression # TJSRefExpression
| '*' singleExpression # TJSPtrExpression
| '.' identifierName # WithDotExpression
| singleExpression Isvalid # IsValidExpression
| Isvalid singleExpression # IsValidExpression
;
assignmentOperator
: '*='
| '/='
| '%='
| '+='
| '-='
| '<<='
| '>>='
| '>>>='
| '&='
| '^='
| '|='
| '\\='
| '&&='
| '||='
;
literal
: NullLiteral
| BooleanLiteral
| tjsStringLiteral
| octetLiteral
| RegularExpressionLiteral
| numericLiteral
;
tjsStringLiteral // tjs can use C like string literal: "part1""part2"
: (StringLiteral
| TemplateStringLiteral)+
;
octetLiteral
: '<%' // Hack for octet literal
( NonIdentHexByte // 0f 7a 08.....
| OctalIntegerLiteral // 00 07 .....
| DecimalLiteral // 13 75 .....
| Identifier)* // ef b9 .....
'%>' // Remember handle it in type recognization
;
numericLiteral
: DecimalLiteral
| HexIntegerLiteral
| OctalIntegerLiteral
| OctalIntegerLiteral2
| BinaryIntegerLiteral
;
identifierName
: Identifier
| reservedWord
;
reservedWord
: keyword
| NullLiteral
| BooleanLiteral
;
keyword
: Break
| Do
| Instanceof
| Typeof
| Case
| Else
| New
| Var
| Catch
| Finally
| Return
| Void
| Continue
| For
| Switch
| While
| Debugger
| Function
| This
| With
| Default
| If
| Throw
| Delete
| In
| Try
| Class
| Enum
| Extends
| Super
| Const
| Export
| Import
| Static
| Incontextof
;
eos
: SemiColon
| EOF
;
|
parser grammar TJSParser;
options {
tokenVocab=TJSLexer;
superClass=TJSBaseParser;
}
program
: statement* EOF
;
statement
: block
| variableStatement
| emptyStatement
| classDeclaration
| expressionStatement
| ifStatement
| iterationStatement
| continueStatement
| breakStatement
| returnStatement
| withStatement
| switchStatement
| throwStatement
| tryStatement
| debuggerStatement
| function
| property
;
block
: '{' statement* '}'
;
variableStatement
: varModifier variableDeclarations eos
;
variableDeclarations
: variableDeclaration (',' variableDeclaration)*
;
variableDeclaration
: Identifier ('=' expression)?
;
emptyStatement
: SemiColon
;
expressionStatement
: expressionSequence eos
;
ifStatement
: If '(' expressionSequence ')' statement (Else statement)?
;
iterationStatement
: Do statement While '(' expressionSequence ')' eos # DoStatement
| While '(' expressionSequence ')' statement # WhileStatement
| For '(' expressionSequence? ';' expressionSequence? ';' expressionSequence? ')' statement # ForStatement
| For '(' varModifier variableDeclarations ';' expressionSequence? ';' expressionSequence? ')' statement # ForVarStatement
;
varModifier
: Var | Const
|'('( Var | Const )')'
;
typeConverter
: '('(Int | Real | String )')'
| Int
| Real
| String
;
continueStatement
: Continue eos
;
breakStatement
: Break eos
;
returnStatement
: Return expressionSequence? eos
;
withStatement
: With '(' expressionSequence ')' statement
;
switchStatement
: Switch '(' expressionSequence ')' '{' ( caseClause | defaultClause )* '}'
;
caseClause
: Case expressionSequence ':' statement*
;
defaultClause
: Default ':' statement*
;
throwStatement
: Throw expressionSequence eos
;
tryStatement
: Try block catchProduction
;
catchProduction
: Catch ('(' Identifier? ')')? block
;
debuggerStatement
: Debugger eos
;
function
: Function Identifier? ('(' functionParameters? ')')? block
;
classDeclaration
: Class Identifier (Extends expression (',' expression)* )? block
;
property // TJS Property define
: Property Identifier '{'
( Getter ('(' ')')? block
| Setter '(' functionParameter ')' block
)* '}'
;
functionParameters
: functionParameter (',' functionParameter)*
;
functionParameter
: Identifier ('=' expression)? // TJS2, ECMAScript 6: Initialization
| Identifier? '*'
;
arrayLiteral
: varModifier? '[' arrayElementSeprator* elementList? arrayElementSeprator* ']'
;
elementList
: expression (arrayElementSeprator+ expression)*
;
arrayElementSeprator
: ','
| '=>'
;
objectLiteral
: varModifier? '%[' objectProperty? (',' objectProperty)* ','?']'
;
objectProperty
: expression (':' |'=' | '=>' | ',') expression // TJS resolve object key in runtime
;
arguments
: '(' argument? (',' argument?)* ')'
| '(' Ellipsis ')' // ... means use argument (JS function argument)
;
argument
: expression '*'?
| '*'
;
expressionSequence
: expression (',' expression)*
;
expression
: function # FunctionExpression
| expression '[' expressionSequence ']' # MemberIndexExpression
| expression '.' identifierName # MemberDotExpression
| '.' identifierName # WithDotExpression
| expression arguments # ArgumentsExpression
| New expression arguments? # NewExpression
| '&' expression # TJSRefExpression
| '*' expression # TJSPtrExpression
| expression '<->' expression # SwapExpression
| expression '!' # EvalExpression // t.f incontextof 's'! => 0721 (s=%[v=>0721])
| expression Incontextof expression # InContextOfExpression // a incontextof d++ => Error: object++
| expression '++' # PostIncrementExpression
| expression '--' # PostDecreaseExpression
| expression Isvalid # IsValidExpression // t incontextof ctx isvalid => 1
| Delete expression # DeleteExpression // delete a.c isvalid => error
| Isvalid expression # IsValidExpression // isvalid delete a.c => 1
| Typeof expression # TypeofExpression // typeof 1 instanceof "String" => 'Integer'
| expression Instanceof expression # InstanceofExpression // 1 instanceof "Number" isvalid => 0,isvalid 1 instanceof "String"=>1
| Invalidate expression # InvalidateExpression // invalidate a instanceof "Number" => 0
| '++' expression # PreIncrementExpression
| '--' expression # PreDecreaseExpression // typeof 1 + 1 = 'Integer1'
| '+' expression # UnaryPlusExpression
| '-' expression # UnaryMinusExpression
| '~' expression # BitNotExpression
| '!' expression # NotExpression
| expression ('*' | '/' | '%' | '\\') expression # MultiplicativeExpression
| expression ('+' | '-') expression # AdditiveExpression
| expression ('<<' | '>>' | '>>>') expression # BitShiftExpression
| expression ('<' | '>' | '<=' | '>=') expression # RelationalExpression
| expression In expression # InExpression // TODO: any standard for it?
| expression ('==' | '!=' | '===' | '!==') expression # EqualityExpression
| expression '&' expression # BitAndExpression
| expression '^' expression # BitXOrExpression
| expression '|' expression # BitOrExpression
| expression '&&' expression # LogicalAndExpression
| expression '||' expression # LogicalOrExpression
| expression '?' expression ':' expression # TernaryExpression
| expression '=' expression # AssignmentExpression
| expression assignmentOperator expression # AssignmentOperatorExpression
| This # ThisExpression
| Identifier # IdentifierExpression
| Super # SuperExpression
| typeConverter expression # TypeConvertExpression
| literal # LiteralExpression
| arrayLiteral # ArrayLiteralExpression
| objectLiteral # ObjectLiteralExpression
| '(' expressionSequence ')' # ParenthesizedExpression
| expression If expressionSequence # TJSIfExpression // b = c = 1 if a ==> (b=c=1)if a
;
assignmentOperator
: '*='
| '/='
| '%='
| '+='
| '-='
| '<<='
| '>>='
| '>>>='
| '&='
| '^='
| '|='
| '\\='
| '&&='
| '||='
;
literal
: NullLiteral
| BooleanLiteral
| (StringLiteral | TemplateStringLiteral)+
| octetLiteral
| RegularExpressionLiteral
| numericLiteral
| Void
;
octetLiteral
: '<%' // Hack for octet literal
( NonIdentHexByte // 0f 7a 08.....
| OctalIntegerLiteral // 00 07 .....
| DecimalLiteral // 13 75 .....
| Identifier)* // ef b9 .....
'%>' // Remember handle it in type recognization
;
numericLiteral
: DecimalLiteral
| HexIntegerLiteral
| OctalIntegerLiteral
| OctalIntegerLiteral2
| BinaryIntegerLiteral
;
identifierName
: Identifier
| reservedWord
;
reservedWord
: keyword
| NullLiteral
| BooleanLiteral
;
keyword
: Break
| Do
| Instanceof
| Typeof
| Case
| Else
| New
| Var
| Catch
| Finally
| Return
| Void
| Continue
| For
| Switch
| While
| Debugger
| Function
| This
| With
| Default
| If
| Throw
| Delete
| In
| Try
| Class
| Enum
| Extends
| Super
| Const
| Export
| Import
| Static
| Incontextof
;
eos
: SemiColon
| EOF
;
|
Fix expression order, simplify some rule
|
Fix expression order, simplify some rule
|
ANTLR
|
mit
|
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
|
7b3c8c34e9e675ee90342928a77edb89e22852cc
|
cache/src/main/antlr4/net/runelite/cache/script/assembler/rs2asm.g4
|
cache/src/main/antlr4/net/runelite/cache/script/assembler/rs2asm.g4
|
/*
* Copyright (c) 2017, Adam <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar rs2asm;
prog: (header NEWLINE)* (line NEWLINE)+ ;
header: int_stack_count | string_stack_count | int_var_count | string_var_count ;
int_stack_count: '.int_stack_count ' int_stack_value ;
string_stack_count: '.string_stack_count ' string_stack_value ;
int_var_count: '.int_var_count ' int_var_value ;
string_var_count: '.string_var_count ' string_var_value ;
int_stack_value: INT ;
string_stack_value: INT ;
int_var_value: INT ;
string_var_value: INT ;
line: instruction | label | switch_lookup ;
instruction: instruction_name instruction_operand ;
label: 'LABEL' INT ':' ;
instruction_name: name_string | name_opcode ;
name_string: INSTRUCTION ;
name_opcode: INT ;
instruction_operand: operand_int | operand_qstring | operand_label | ;
operand_int: INT ;
operand_qstring: QSTRING ;
operand_label: 'LABEL' INT ;
switch_lookup: switch_key ':' switch_value ;
switch_key: INT ;
switch_value: 'LABEL' INT ;
NEWLINE: '\n'+ ;
INT: '-'? [0-9]+ ;
QSTRING: '"' (~('"' | '\\' | '\r' | '\n') | '\\' ('"' | '\\'))* '"' ;
INSTRUCTION: [a-z0-9_]+ ;
WS: (' ' | '\t')+ -> channel(HIDDEN) ;
|
/*
* Copyright (c) 2017, Adam <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar rs2asm;
prog: (header NEWLINE)* (line NEWLINE)+ ;
header: int_stack_count | string_stack_count | int_var_count | string_var_count ;
int_stack_count: '.int_stack_count ' int_stack_value ;
string_stack_count: '.string_stack_count ' string_stack_value ;
int_var_count: '.int_var_count ' int_var_value ;
string_var_count: '.string_var_count ' string_var_value ;
int_stack_value: INT ;
string_stack_value: INT ;
int_var_value: INT ;
string_var_value: INT ;
line: instruction | label | switch_lookup ;
instruction: instruction_name instruction_operand ;
label: 'LABEL' INT ':' ;
instruction_name: name_string | name_opcode ;
name_string: INSTRUCTION ;
name_opcode: INT ;
instruction_operand: operand_int | operand_qstring | operand_label | ;
operand_int: INT ;
operand_qstring: QSTRING ;
operand_label: 'LABEL' INT ;
switch_lookup: switch_key ':' switch_value ;
switch_key: INT ;
switch_value: 'LABEL' INT ;
NEWLINE: '\n'+ ;
INT: '-'? [0-9]+ ;
QSTRING: '"' (~('"' | '\\' | '\r' | '\n') | '\\' ('"' | '\\'))* '"' ;
INSTRUCTION: [a-z0-9_]+ ;
COMMENT: ';' ~( '\r' | '\n' )* -> channel(HIDDEN) ;
WS: (' ' | '\t')+ -> channel(HIDDEN) ;
|
add comment to rs2asm grammar
|
cache: add comment to rs2asm grammar
|
ANTLR
|
bsd-2-clause
|
runelite/runelite,Noremac201/runelite,abelbriggs1/runelite,devinfrench/runelite,KronosDesign/runelite,Sethtroll/runelite,l2-/runelite,runelite/runelite,runelite/runelite,KronosDesign/runelite,l2-/runelite,abelbriggs1/runelite,devinfrench/runelite,Sethtroll/runelite,abelbriggs1/runelite,Noremac201/runelite
|
a2ad65b2b0d1955275c16fdc025d21e70bf28f81
|
newton.g4
|
newton.g4
|
grammar newton;
tokens { INDENT, DEDENT }
@lexer::header {
import com.yuvalshavit.antlr4.DenterHelper;
}
@lexer::members {
private final DenterHelper newtonDenter = new DenterHelper(NL, newtonParser.INDENT, newtonParser.DEDENT)
{
@Override
public Token pullToken() {
return newtonLexer.super.nextToken();
}
};
@Override
public Token nextToken() {
return newtonDenter.nextToken();
}
}
file : structures
| COMMENT
;
structures : array
| object
;
array : ( DASH value )+
;
value : data NL # ArrayValue
| object # ObjectInArray
;
object : ( pair NL? )+
;
pair : ID COLON data # ObjectValue
| ID COLON INDENT? array+ DEDENT? # ArrayInObject
| ID COLON CLOSED_PAR # EmptyObject
| ID COLON INDENT? object DEDENT? # NestedObject
;
data : ID # String
| NUMBER # NumericValue
| BOOLEAN # BoolValue
| 'null' # NullValue
;
DASH : '-'
;
COLON : ': '
;
CLOSED_PAR : '{}'
;
COMMENT : '#' .*? NL -> skip
;
ID : [a-z_A-Z' ']+
;
NUMBER : REAL
| HEX
| OCTAL
;
BOOLEAN : 'true'
| 'false'
;
REAL : [0-9]+ ( '.' [0-9]+ )*
;
HEX : '0x' [0-9A-Fa-f]+
;
OCTAL : '0c' [0-7]+
;
NL : ('\r'?'\n''\t'*)
;
WS : ' ' -> skip
;
|
grammar newton;
tokens { INDENT, DEDENT }
@lexer::header {
import com.yuvalshavit.antlr4.DenterHelper;
}
@lexer::members {
private final DenterHelper newtonDenter = new DenterHelper(NL, newtonParser.INDENT, newtonParser.DEDENT)
{
@Override
public Token pullToken() {
return newtonLexer.super.nextToken();
}
};
@Override
public Token nextToken() {
return newtonDenter.nextToken();
}
}
file : structures
;
structures : array
| object
;
array : ( DASH value )+
;
value : data NL # ArrayValue
| object # ObjectInArray
;
object : ( pair NL? )+
;
pair : ID COLON data # ObjectValue
| ID COLON INDENT? array+ DEDENT? # ArrayInObject
| ID COLON CLOSED_PAR # EmptyObject
| ID COLON INDENT? object DEDENT? # NestedObject
;
data : ID # String
| NUMBER # NumericValue
| BOOLEAN # BoolValue
| 'null' # NullValue
;
DASH : '-'
;
COLON : ': '
;
CLOSED_PAR : '{}'
;
ID : [a-z_A-Z0-9' '<>/?*$@:;~`\|!&-+{}.]+
;
NUMBER : REAL
| HEX
| OCTAL
;
BOOLEAN : 'true'
| 'false'
;
REAL : [0-9]+ ( '.' [0-9]+ )*
;
HEX : '0x' [0-9A-Fa-f]+
;
OCTAL : '0c' [0-7]+
;
NL : ('\r'?'\n''\t'*)
;
COMMENT : '#' ~[\r\n]* -> skip
;
WS : ' ' -> skip
;
|
support for symbols and number with strings
|
support for symbols and number with strings
|
ANTLR
|
mit
|
Khushmeet/newton,Khushmeet/newton
|
662c7a554017c8dbaf5454373d820331ccfdc221
|
clojure/Clojure.g4
|
clojure/Clojure.g4
|
/* Reworked for grammar specificity by Reid Mckenzie. Did a bunch of
work so that rather than reading "a bunch of crap in parens" some
syntactic information is preserved and recovered. Dec. 14 2014.
Converted to ANTLR 4 by Terence Parr. Unsure of provence. I see
it commited by matthias.koester for clojure-eclipse project on
Oct 5, 2009:
https://code.google.com/p/clojure-eclipse/
Seems to me Laurent Petit had a version of this. I also see
Jingguo Yao submitting a link to a now-dead github project on
Jan 1, 2011.
https://github.com/laurentpetit/ccw/tree/master/clojure-antlr-grammar
Regardless, there are some issues perhaps related to "sugar";
I've tried to fix them.
This parses https://github.com/weavejester/compojure project.
I also note this is hardly a grammar; more like "match a bunch of
crap in parens" but I guess that is LISP for you ;)
*/
grammar Clojure;
file: form *;
form: literal
| list
| vector
| map
| reader_macro
;
forms: form* ;
list: '(' forms ')' ;
vector: '[' forms ']' ;
map: '{' (form form)* '}' ;
set: '#{' forms '}' ;
reader_macro
: lambda
| meta_data
| regex
| var_quote
| host_expr
| set
| tag
| discard
| dispatch
| deref
| quote
| backtick
| unquote
| unquote_splicing
| gensym
;
// TJP added '&' (gather a variable number of arguments)
quote
: '\'' form
;
backtick
: '`' form
;
unquote
: '~' form
;
unquote_splicing
: '~@' form
;
tag
: '^' form form
;
deref
: '@' form
;
gensym
: SYMBOL '#'
;
lambda
: '#(' form* ')'
;
meta_data
: '#^' (map form | form)
;
var_quote
: '#\'' symbol
;
host_expr
: '#+' form form
;
discard
: '#_' form
;
dispatch
: '#' symbol form
;
regex
: '#' string
;
literal
: string
| number
| character
| nil
| BOOLEAN
| keyword
| symbol
| param_name
;
string: STRING;
hex: HEX;
bin: BIN;
bign: BIGN;
number
: FLOAT
| hex
| bin
| bign
| LONG
;
character
: named_char
| u_hex_quad
| any_char
;
named_char: CHAR_NAMED ;
any_char: CHAR_ANY ;
u_hex_quad: CHAR_U ;
nil: NIL;
keyword: macro_keyword | simple_keyword;
simple_keyword: ':' symbol;
macro_keyword: ':' ':' symbol;
symbol: ns_symbol | simple_sym;
simple_sym: SYMBOL;
ns_symbol: NS_SYMBOL;
param_name: PARAM_NAME;
// Lexers
//--------------------------------------------------------------------
STRING : '"' ( ~'"' | '\\' '"' )* '"' ;
// FIXME: Doesn't deal with arbitrary read radixes, BigNums
FLOAT
: '-'? [0-9]+ FLOAT_TAIL
| '-'? 'Infinity'
| '-'? 'NaN'
;
fragment
FLOAT_TAIL
: FLOAT_DECIMAL FLOAT_EXP
| FLOAT_DECIMAL
| FLOAT_EXP
;
fragment
FLOAT_DECIMAL
: '.' [0-9]+
;
fragment
FLOAT_EXP
: [eE] '-'? [0-9]+
;
fragment
HEXD: [0-9a-fA-F] ;
HEX: '0' [xX] HEXD+ ;
BIN: '0' [bB] [10]+ ;
LONG: '-'? [0-9]+[lL]?;
BIGN: '-'? [0-9]+[nN];
CHAR_U
: '\\' 'u'[0-9D-Fd-f] HEXD HEXD HEXD ;
CHAR_NAMED
: '\\' ( 'newline'
| 'return'
| 'space'
| 'tab'
| 'formfeed'
| 'backspace' ) ;
CHAR_ANY
: '\\' . ;
NIL : 'nil';
BOOLEAN : 'true' | 'false' ;
SYMBOL
: '.'
| '/'
| NAME
;
NS_SYMBOL
: NAME '/' SYMBOL
;
PARAM_NAME: '%' ((('1'..'9')('0'..'9')*)|'&')? ;
// Fragments
//--------------------------------------------------------------------
fragment
NAME: SYMBOL_HEAD SYMBOL_REST* (':' SYMBOL_REST+)* ;
fragment
SYMBOL_HEAD
: ~('0' .. '9'
| '^' | '`' | '\'' | '"' | '#' | '~' | '@' | ':' | '/' | '%' | '(' | ')' | '[' | ']' | '{' | '}' // FIXME: could be one group
| [ \n\r\t\,] // FIXME: could be WS
)
;
fragment
SYMBOL_REST
: SYMBOL_HEAD
| '0'..'9'
| '.'
;
// Discard
//--------------------------------------------------------------------
fragment
WS : [ \n\r\t\,] ;
fragment
COMMENT: ';' ~[\r\n]* ;
TRASH
: ( WS | COMMENT ) -> channel(HIDDEN)
;
|
/* Reworked for grammar specificity by Reid Mckenzie. Did a bunch of
work so that rather than reading "a bunch of crap in parens" some
syntactic information is preserved and recovered. Dec. 14 2014.
Converted to ANTLR 4 by Terence Parr. Unsure of provence. I see
it commited by matthias.koester for clojure-eclipse project on
Oct 5, 2009:
https://code.google.com/p/clojure-eclipse/
Seems to me Laurent Petit had a version of this. I also see
Jingguo Yao submitting a link to a now-dead github project on
Jan 1, 2011.
https://github.com/laurentpetit/ccw/tree/master/clojure-antlr-grammar
Regardless, there are some issues perhaps related to "sugar";
I've tried to fix them.
This parses https://github.com/weavejester/compojure project.
I also note this is hardly a grammar; more like "match a bunch of
crap in parens" but I guess that is LISP for you ;)
*/
grammar Clojure;
file: form *;
form: literal
| list
| vector
| map
| reader_macro
;
forms: form* ;
list: '(' forms ')' ;
vector: '[' forms ']' ;
map: '{' (form form)* '}' ;
set: '#{' forms '}' ;
reader_macro
: lambda
| meta_data
| regex
| var_quote
| host_expr
| set
| tag
| discard
| dispatch
| deref
| quote
| backtick
| unquote
| unquote_splicing
| gensym
;
// TJP added '&' (gather a variable number of arguments)
quote
: '\'' form
;
backtick
: '`' form
;
unquote
: '~' form
;
unquote_splicing
: '~@' form
;
tag
: '^' form form
;
deref
: '@' form
;
gensym
: SYMBOL '#'
;
lambda
: '#(' form* ')'
;
meta_data
: '#^' (map form | form)
;
var_quote
: '#\'' symbol
;
host_expr
: '#+' form form
;
discard
: '#_' form
;
dispatch
: '#' symbol form
;
regex
: '#' string
;
literal
: string
| number
| character
| nil
| BOOLEAN
| keyword
| symbol
| param_name
;
string: STRING;
hex: HEX;
bin: BIN;
bign: BIGN;
number
: FLOAT
| hex
| bin
| bign
| LONG
;
character
: named_char
| u_hex_quad
| any_char
;
named_char: CHAR_NAMED ;
any_char: CHAR_ANY ;
u_hex_quad: CHAR_U ;
nil: NIL;
keyword: macro_keyword | simple_keyword;
simple_keyword: ':' symbol;
macro_keyword: ':' ':' symbol;
symbol: ns_symbol | simple_sym;
simple_sym: SYMBOL;
ns_symbol: NS_SYMBOL;
param_name: PARAM_NAME;
// Lexers
//--------------------------------------------------------------------
STRING : '"' ( ~'"' | '\\' '"' )* '"' ;
// FIXME: Doesn't deal with arbitrary read radixes, BigNums
FLOAT
: '-'? [0-9]+ FLOAT_TAIL
| '-'? 'Infinity'
| '-'? 'NaN'
;
fragment
FLOAT_TAIL
: FLOAT_DECIMAL FLOAT_EXP
| FLOAT_DECIMAL
| FLOAT_EXP
;
fragment
FLOAT_DECIMAL
: '.' [0-9]+
;
fragment
FLOAT_EXP
: [eE] '-'? [0-9]+
;
fragment
HEXD: [0-9a-fA-F] ;
HEX: '0' [xX] HEXD+ ;
BIN: '0' [bB] [10]+ ;
LONG: '-'? [0-9]+[lL]?;
BIGN: '-'? [0-9]+[nN];
CHAR_U
: '\\' 'u'[0-9D-Fd-f] HEXD HEXD HEXD ;
CHAR_NAMED
: '\\' ( 'newline'
| 'return'
| 'space'
| 'tab'
| 'formfeed'
| 'backspace' ) ;
CHAR_ANY
: '\\' . ;
NIL : 'nil';
BOOLEAN : 'true' | 'false' ;
SYMBOL
: '.'
| '/'
| NAME
;
NS_SYMBOL
: NAME '/' SYMBOL
;
PARAM_NAME: '%' ((('1'..'9')('0'..'9')*)|'&')? ;
// Fragments
//--------------------------------------------------------------------
fragment
NAME: SYMBOL_HEAD SYMBOL_REST* (':' SYMBOL_REST+)* ;
fragment
SYMBOL_HEAD
: ~('0' .. '9'
| '^' | '`' | '\'' | '"' | '#' | '~' | '@' | ':' | '/' | '%' | '(' | ')' | '[' | ']' | '{' | '}' // FIXME: could be one group
| [ \n\r\t,] // FIXME: could be WS
)
;
fragment
SYMBOL_REST
: SYMBOL_HEAD
| '0'..'9'
| '.'
;
// Discard
//--------------------------------------------------------------------
fragment
WS : [ \n\r\t,] ;
fragment
COMMENT: ';' ~[\r\n]* ;
TRASH
: ( WS | COMMENT ) -> channel(HIDDEN)
;
|
Fix wrong escape sequence for ','
|
Fix wrong escape sequence for ','
|
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
|
4ce7ac331ea19fce0deb02ae6ea0c882716b9445
|
projects/batfish/src/org/batfish/grammar/question/QuestionParametersLexer.g4
|
projects/batfish/src/org/batfish/grammar/question/QuestionParametersLexer.g4
|
lexer grammar QuestionParametersLexer;
options {
superClass = 'org.batfish.grammar.BatfishLexer';
}
@header {
package org.batfish.grammar.question;
}
tokens {
DEC,
IP_ADDRESS,
IP_PREFIX,
MINUS,
REGEX,
STRING_LITERAL
}
// Simple tokens
// Complex tokens
HASH
:
'#' -> channel ( HIDDEN ) , pushMode ( M_Comment )
;
EQUALS
:
'=' -> pushMode ( M_Value )
;
NEWLINE
:
F_NewlineChar+ -> channel ( HIDDEN )
;
VARIABLE
:
F_LeadingVarChar F_VarChar*
;
WS
:
F_WhitespaceChar+ -> channel ( HIDDEN )
;
fragment
F_DecByte
:
(
F_PositiveDecimalDigit F_DecimalDigit F_DecimalDigit
)
|
(
F_PositiveDecimalDigit F_DecimalDigit
)
| F_DecimalDigit
;
fragment
F_DecimalDigit
:
'0' .. '9'
;
fragment
F_LeadingVarChar
:
'A' .. 'Z'
| 'a' .. 'z'
| '_'
;
fragment
F_NewlineChar
:
[\n\r]
;
fragment
F_NonNewlineChar
:
~[\n\r]
;
fragment
F_PositiveDecimalDigit
:
'1' .. '9'
;
fragment
F_VarChar
:
'A' .. 'Z'
| 'a' .. 'z'
| '0' .. '9'
| '_'
;
fragment
F_WhitespaceChar
:
[ \t\u000C]
;
mode M_Comment;
M_Comment_COMMENT
:
F_NonNewlineChar+ -> channel ( HIDDEN )
;
M_Comment_NEWLINE
:
F_NewlineChar+ -> channel ( HIDDEN ) , mode ( DEFAULT_MODE )
;
mode M_Negative;
M_Negative_DEC
:
(
'0'
|
(
F_PositiveDecimalDigit F_DecimalDigit*
)
) -> type ( DEC ) , mode ( DEFAULT_MODE )
;
mode M_QuotedString;
M_QuotedString_TEXT
:
~'"'+ -> type ( STRING_LITERAL )
;
M_QuotedString_DOUBLE_QUOTE
:
'"' -> channel ( HIDDEN ) , mode ( DEFAULT_MODE )
;
mode M_Value;
M_Value_DEC
:
(
'0'
|
(
F_PositiveDecimalDigit F_DecimalDigit*
)
) -> type ( DEC ) , popMode
;
M_Value_DOUBLE_QUOTE
:
'"' -> channel ( HIDDEN ) , pushMode ( M_QuotedString )
;
M_Value_HASH
:
'#' -> channel ( HIDDEN ) , pushMode ( M_Comment )
;
M_Value_IP_ADDRESS
:
F_DecByte '.' F_DecByte '.' F_DecByte '.' F_DecByte -> type ( IP_ADDRESS ) ,
popMode
;
M_Value_IP_PREFIX
:
F_DecByte '.' F_DecByte '.' F_DecByte '.' F_DecByte '/' F_DecimalDigit+ ->
type ( IP_PREFIX ) , popMode
;
M_Value_MINUS
:
'-' -> type ( MINUS ) , pushMode ( M_Negative )
;
M_Value_REGEX
:
'regex<' ~'>'* '>' -> type ( REGEX ) , popMode
;
M_Value_STRING_LITERAL
:
F_LeadingVarChar F_VarChar* -> type ( STRING_LITERAL ) , popMode
;
|
lexer grammar QuestionParametersLexer;
options {
superClass = 'org.batfish.grammar.BatfishLexer';
}
@header {
package org.batfish.grammar.question;
}
tokens {
DEC,
IP_ADDRESS,
IP_PREFIX,
MINUS,
REGEX,
STRING_LITERAL
}
// Simple tokens
// Complex tokens
HASH
:
'#' -> channel ( HIDDEN ) , pushMode ( M_Comment )
;
EQUALS
:
'=' -> pushMode ( M_Value )
;
NEWLINE
:
F_NewlineChar+ -> channel ( HIDDEN )
;
VARIABLE
:
F_LeadingVarChar F_VarChar*
;
WS
:
F_WhitespaceChar+ -> channel ( HIDDEN )
;
fragment
F_DecByte
:
(
F_PositiveDecimalDigit F_DecimalDigit F_DecimalDigit
)
|
(
F_PositiveDecimalDigit F_DecimalDigit
)
| F_DecimalDigit
;
fragment
F_DecimalDigit
:
'0' .. '9'
;
fragment
F_LeadingVarChar
:
'A' .. 'Z'
| 'a' .. 'z'
| '_'
;
fragment
F_NewlineChar
:
[\n\r]
;
fragment
F_NonNewlineChar
:
~[\n\r]
;
fragment
F_PositiveDecimalDigit
:
'1' .. '9'
;
fragment
F_VarChar
:
'A' .. 'Z'
| 'a' .. 'z'
| '0' .. '9'
| '_'
;
fragment
F_WhitespaceChar
:
[ \t\u000C]
;
mode M_Comment;
M_Comment_COMMENT
:
F_NonNewlineChar+ -> channel ( HIDDEN )
;
M_Comment_NEWLINE
:
F_NewlineChar+ -> channel ( HIDDEN ) , mode ( DEFAULT_MODE )
;
mode M_Negative;
M_Negative_DEC
:
(
'0'
|
(
F_PositiveDecimalDigit F_DecimalDigit*
)
) -> type ( DEC ) , mode ( DEFAULT_MODE )
;
mode M_QuotedString;
M_QuotedString_TEXT
:
~'"'+ -> type ( STRING_LITERAL )
;
M_QuotedString_DOUBLE_QUOTE
:
'"' -> channel ( HIDDEN ) , mode ( DEFAULT_MODE )
;
mode M_Value;
M_Value_DEC
:
(
'0'
|
(
F_PositiveDecimalDigit F_DecimalDigit*
)
) -> type ( DEC ) , popMode
;
M_Value_DOUBLE_QUOTE
:
'"' -> channel ( HIDDEN ) , pushMode ( M_QuotedString )
;
M_Value_HASH
:
'#' -> channel ( HIDDEN ) , pushMode ( M_Comment )
;
M_Value_IP_ADDRESS
:
F_DecByte '.' F_DecByte '.' F_DecByte '.' F_DecByte -> type ( IP_ADDRESS ) ,
popMode
;
M_Value_IP_PREFIX
:
F_DecByte '.' F_DecByte '.' F_DecByte '.' F_DecByte '/' F_DecimalDigit+ ->
type ( IP_PREFIX ) , popMode
;
M_Value_MINUS
:
'-' -> type ( MINUS ) , pushMode ( M_Negative )
;
M_Value_REGEX
:
'regex<' ~'>'* '>' -> type ( REGEX ) , popMode
;
M_Value_STRING_LITERAL
:
F_LeadingVarChar F_VarChar* -> type ( STRING_LITERAL ) , popMode
;
M_Value_WS
:
(
F_WhitespaceChar
| F_NewlineChar
)+ -> channel ( HIDDEN )
;
|
fix for whitespace after = in parameters file
|
fix for whitespace after = in parameters file
|
ANTLR
|
apache-2.0
|
arifogel/batfish,intentionet/batfish,arifogel/batfish,batfish/batfish,intentionet/batfish,intentionet/batfish,batfish/batfish,batfish/batfish,dhalperi/batfish,intentionet/batfish,intentionet/batfish,dhalperi/batfish,arifogel/batfish,dhalperi/batfish
|
d7224484d443480158a2a4e94b41d8c589fb82c3
|
src/main/antlr/Scheme.g4
|
src/main/antlr/Scheme.g4
|
grammar Scheme;
options {
language = Java;
}
myrule: '(' IDENTIFIER ')' ;
// Lexer
fragment
INTRALINE_WHITESPACE : [ \t];
fragment
LINE_ENDING : '\n' | '\r\n' | '\r';
LPAREN: '(';
RPAREN: ')';
IDENTIFIER : INITIAL SUBSEQUENT*
| '|' SYMBOL_ELEMENT* '|'
| PECULIAR_IDENTIFIER
;
fragment
INITIAL : LETTER
| SPECIAL_INITIAL
;
fragment
LETTER : [a-zA-Z];
fragment
SPECIAL_INITIAL : '!' | '$' | '%' | '*' | '/' | ':' | '<'
| '=' | '>' | '?' | '^' | '_' | '~';
fragment
SUBSEQUENT : INITIAL | DIGIT | SPECIAL_SUBSEQUENT;
fragment
DIGIT : [0-9];
fragment
HEX_DIGIT : DIGIT | [a-f];
fragment
EXPLICIT_SIGN : '+' | '-';
fragment
SPECIAL_SUBSEQUENT : EXPLICIT_SIGN | '.' | '@';
fragment
INLINE_HEX_ESCAPE : '\\x' HEX_SCALAR_VALUE ';';
fragment
HEX_SCALAR_VALUE : HEX_DIGIT+;
fragment
MNEMONIC_ESCAPE : '\\a' | '\\b' | '\\t' | '\\n' | '\\r';
fragment
PECULIAR_IDENTIFIER : EXPLICIT_SIGN
| EXPLICIT_SIGN SIGN_SUBSEQUENT SUBSEQUENT*
| EXPLICIT_SIGN '.' DOT_SUBSEQUENT SUBSEQUENT*
| '.' DOT_SUBSEQUENT SUBSEQUENT*
;
fragment
DOT_SUBSEQUENT : SIGN_SUBSEQUENT
| '.'
;
fragment
SIGN_SUBSEQUENT : INITIAL | EXPLICIT_SIGN | '@';
fragment
SYMBOL_ELEMENT : ~[|\\] | INLINE_HEX_ESCAPE | MNEMONIC_ESCAPE | '\\|';
BOOLEAN : '#t'
| '#f'
| '#true'
| '#false'
;
CHARACTER : '#\\' | '#\\' CHARACTER_NAME | '#\\x' HEX_SCALAR_VALUE;
fragment
CHARACTER_NAME : 'alarm' | 'backspace' | 'delete' | 'escape'
| 'newline' | 'null' | 'return' | 'space' | 'tab';
STRING : '"' STRING_ELEMENT* '"';
fragment
STRING_ELEMENT : ~["\\]
| MNEMONIC_ESCAPE
| '\\"'
| '\\\\'
| '\\' INTRALINE_WHITESPACE* LINE_ENDING INTRALINE_WHITESPACE*
| INLINE_HEX_ESCAPE
;
// Numbers
NUMBER : NUM_2 | NUM_8 | NUM_10 | NUM_16;
// Binary
fragment
NUM_2 : PREFIX_2 COMPLEX_2;
fragment
COMPLEX_2 : REAL_2 | REAL_2 '@' REAL_2 | REAL_2 '+' UREAL_2 'i'
| REAL_2 '-' UREAL_2 'i' | REAL_2 '+' 'i' | REAL_2 '-' 'i'
| REAL_2 INFNAN 'i' | '+' UREAL_2 'i' | '-' UREAL_2 'i'
| INFNAN 'i' | '+' 'i' | '-' 'i'
;
fragment
REAL_2 : SIGN? UREAL_2 | INFNAN;
fragment
UREAL_2 : UINTEGER_2
| UINTEGER_2 '/' UINTEGER_2
;
fragment
UINTEGER_2 : DIGIT_2+;
fragment
PREFIX_2 : RADIX_2 EXACTNESS?
| EXACTNESS? RADIX_2
;
// Octal
fragment
NUM_8 : PREFIX_8 COMPLEX_8;
fragment
COMPLEX_8 : REAL_8 | REAL_8 '@' REAL_8 | REAL_8 '+' UREAL_8 'i'
| REAL_8 '-' UREAL_8 'i' | REAL_8 '+' 'i' | REAL_8 '-' 'i'
| REAL_8 INFNAN 'i' | '+' UREAL_8 'i' | '-' UREAL_8 'i'
| INFNAN 'i' | '+' 'i' | '-' 'i'
;
fragment
REAL_8 : SIGN? UREAL_8 | INFNAN;
fragment
UREAL_8 : UINTEGER_8
| UINTEGER_8 '/' UINTEGER_8
;
fragment
UINTEGER_8 : DIGIT_8+;
fragment
PREFIX_8 : RADIX_8 EXACTNESS?
| EXACTNESS? RADIX_8
;
// Decimal
fragment
NUM_10 : PREFIX_10 COMPLEX_10;
fragment
COMPLEX_10 : REAL_10 | REAL_10 '@' REAL_10 | REAL_10 '+' UREAL_10 'i'
| REAL_10 '-' UREAL_10 'i' | REAL_10 '+' 'i' | REAL_10 '-' 'i'
| REAL_10 INFNAN 'i' | '+' UREAL_10 'i' | '-' UREAL_10 'i'
| INFNAN 'i' | '+' 'i' | '-' 'i'
;
fragment
REAL_10 : SIGN? UREAL_10 | INFNAN;
fragment
UREAL_10 : UINTEGER_10
| UINTEGER_10 '/' UINTEGER_10
| DECIMAL_10
;
fragment
DECIMAL_10 : UINTEGER_10 SUFFIX?
| '.' DIGIT_10+ SUFFIX?
| DIGIT_10+ '.' DIGIT_10* SUFFIX?
;
fragment
UINTEGER_10 : DIGIT_10+;
fragment
PREFIX_10 : RADIX_10 EXACTNESS?
| EXACTNESS? RADIX_10
;
// Hexadecimal
fragment
NUM_16 : PREFIX_16 COMPLEX_16;
fragment
COMPLEX_16 : REAL_16 | REAL_16 '@' REAL_16 | REAL_16 '+' UREAL_16 'i'
| REAL_16 '-' UREAL_16 'i' | REAL_16 '+' 'i' | REAL_16 '-' 'i'
| REAL_16 INFNAN 'i' | '+' UREAL_16 'i' | '-' UREAL_16 'i'
| INFNAN 'i' | '+' 'i' | '-' 'i'
;
fragment
REAL_16 : SIGN? UREAL_16 | INFNAN;
fragment
UREAL_16 : UINTEGER_16
| UINTEGER_16 '/' UINTEGER_16
;
fragment
UINTEGER_16 : DIGIT_16+;
fragment
PREFIX_16 : RADIX_16 EXACTNESS?
| EXACTNESS? RADIX_16
;
fragment
INFNAN : '+inf.0' | '-inf.0' | '+nan.0' | '-nan.0';
fragment
SUFFIX : EXPONENT_MARKER SIGN? DIGIT_10+;
fragment
SIGN : '+' | '-';
fragment
EXPONENT_MARKER : 'e';
fragment
EXACTNESS : '#i' | '#e';
fragment
RADIX_2 : '#b';
fragment
RADIX_8 : '#o';
fragment
RADIX_10 : '#d';
fragment
RADIX_16 : '#x';
fragment
DIGIT_2 : '0' | '1';
fragment
DIGIT_8 : [0-7];
fragment
DIGIT_10 : DIGIT;
fragment
DIGIT_16 : DIGIT_10 | [a-f];
|
grammar Scheme;
options {
language = Java;
}
myrule: '(' IDENTIFIER ')' ;
// Lexer
fragment
INTRALINE_WHITESPACE : [ \t];
fragment
LINE_ENDING : '\n' | '\r\n' | '\r';
LPAREN : '(';
RPAREN : ')';
VECTORPAREN : '#(';
BYTEPAREN : '#u8(';
QUOTE : '\'';
QUASIQUOTE : '`';
UNQUOTE : ',';
SPLICING_UNQUOTE : ',@';
DOT : '.';
IDENTIFIER : INITIAL SUBSEQUENT*
| '|' SYMBOL_ELEMENT* '|'
| PECULIAR_IDENTIFIER
;
fragment
INITIAL : LETTER
| SPECIAL_INITIAL
;
fragment
LETTER : [a-zA-Z];
fragment
SPECIAL_INITIAL : '!' | '$' | '%' | '*' | '/' | ':' | '<'
| '=' | '>' | '?' | '^' | '_' | '~';
fragment
SUBSEQUENT : INITIAL | DIGIT | SPECIAL_SUBSEQUENT;
fragment
DIGIT : [0-9];
fragment
HEX_DIGIT : DIGIT | [a-f];
fragment
EXPLICIT_SIGN : '+' | '-';
fragment
SPECIAL_SUBSEQUENT : EXPLICIT_SIGN | '.' | '@';
fragment
INLINE_HEX_ESCAPE : '\\x' HEX_SCALAR_VALUE ';';
fragment
HEX_SCALAR_VALUE : HEX_DIGIT+;
fragment
MNEMONIC_ESCAPE : '\\a' | '\\b' | '\\t' | '\\n' | '\\r';
fragment
PECULIAR_IDENTIFIER : EXPLICIT_SIGN
| EXPLICIT_SIGN SIGN_SUBSEQUENT SUBSEQUENT*
| EXPLICIT_SIGN '.' DOT_SUBSEQUENT SUBSEQUENT*
| '.' DOT_SUBSEQUENT SUBSEQUENT*
;
fragment
DOT_SUBSEQUENT : SIGN_SUBSEQUENT
| '.'
;
fragment
SIGN_SUBSEQUENT : INITIAL | EXPLICIT_SIGN | '@';
fragment
SYMBOL_ELEMENT : ~[|\\] | INLINE_HEX_ESCAPE | MNEMONIC_ESCAPE | '\\|';
BOOLEAN : '#t'
| '#f'
| '#true'
| '#false'
;
CHARACTER : '#\\' | '#\\' CHARACTER_NAME | '#\\x' HEX_SCALAR_VALUE;
fragment
CHARACTER_NAME : 'alarm' | 'backspace' | 'delete' | 'escape'
| 'newline' | 'null' | 'return' | 'space' | 'tab';
STRING : '"' STRING_ELEMENT* '"';
fragment
STRING_ELEMENT : ~["\\]
| MNEMONIC_ESCAPE
| '\\"'
| '\\\\'
| '\\' INTRALINE_WHITESPACE* LINE_ENDING INTRALINE_WHITESPACE*
| INLINE_HEX_ESCAPE
;
// Numbers
NUMBER : NUM_2 | NUM_8 | NUM_10 | NUM_16;
// Binary
fragment
NUM_2 : PREFIX_2 COMPLEX_2;
fragment
COMPLEX_2 : REAL_2 | REAL_2 '@' REAL_2 | REAL_2 '+' UREAL_2 'i'
| REAL_2 '-' UREAL_2 'i' | REAL_2 '+' 'i' | REAL_2 '-' 'i'
| REAL_2 INFNAN 'i' | '+' UREAL_2 'i' | '-' UREAL_2 'i'
| INFNAN 'i' | '+' 'i' | '-' 'i'
;
fragment
REAL_2 : SIGN? UREAL_2 | INFNAN;
fragment
UREAL_2 : UINTEGER_2
| UINTEGER_2 '/' UINTEGER_2
;
fragment
UINTEGER_2 : DIGIT_2+;
fragment
PREFIX_2 : RADIX_2 EXACTNESS?
| EXACTNESS? RADIX_2
;
// Octal
fragment
NUM_8 : PREFIX_8 COMPLEX_8;
fragment
COMPLEX_8 : REAL_8 | REAL_8 '@' REAL_8 | REAL_8 '+' UREAL_8 'i'
| REAL_8 '-' UREAL_8 'i' | REAL_8 '+' 'i' | REAL_8 '-' 'i'
| REAL_8 INFNAN 'i' | '+' UREAL_8 'i' | '-' UREAL_8 'i'
| INFNAN 'i' | '+' 'i' | '-' 'i'
;
fragment
REAL_8 : SIGN? UREAL_8 | INFNAN;
fragment
UREAL_8 : UINTEGER_8
| UINTEGER_8 '/' UINTEGER_8
;
fragment
UINTEGER_8 : DIGIT_8+;
fragment
PREFIX_8 : RADIX_8 EXACTNESS?
| EXACTNESS? RADIX_8
;
// Decimal
fragment
NUM_10 : PREFIX_10 COMPLEX_10;
fragment
COMPLEX_10 : REAL_10 | REAL_10 '@' REAL_10 | REAL_10 '+' UREAL_10 'i'
| REAL_10 '-' UREAL_10 'i' | REAL_10 '+' 'i' | REAL_10 '-' 'i'
| REAL_10 INFNAN 'i' | '+' UREAL_10 'i' | '-' UREAL_10 'i'
| INFNAN 'i' | '+' 'i' | '-' 'i'
;
fragment
REAL_10 : SIGN? UREAL_10 | INFNAN;
fragment
UREAL_10 : UINTEGER_10
| UINTEGER_10 '/' UINTEGER_10
| DECIMAL_10
;
fragment
DECIMAL_10 : UINTEGER_10 SUFFIX?
| '.' DIGIT_10+ SUFFIX?
| DIGIT_10+ '.' DIGIT_10* SUFFIX?
;
fragment
UINTEGER_10 : DIGIT_10+;
fragment
PREFIX_10 : RADIX_10 EXACTNESS?
| EXACTNESS? RADIX_10
;
// Hexadecimal
fragment
NUM_16 : PREFIX_16 COMPLEX_16;
fragment
COMPLEX_16 : REAL_16 | REAL_16 '@' REAL_16 | REAL_16 '+' UREAL_16 'i'
| REAL_16 '-' UREAL_16 'i' | REAL_16 '+' 'i' | REAL_16 '-' 'i'
| REAL_16 INFNAN 'i' | '+' UREAL_16 'i' | '-' UREAL_16 'i'
| INFNAN 'i' | '+' 'i' | '-' 'i'
;
fragment
REAL_16 : SIGN? UREAL_16 | INFNAN;
fragment
UREAL_16 : UINTEGER_16
| UINTEGER_16 '/' UINTEGER_16
;
fragment
UINTEGER_16 : DIGIT_16+;
fragment
PREFIX_16 : RADIX_16 EXACTNESS?
| EXACTNESS? RADIX_16
;
fragment
INFNAN : '+inf.0' | '-inf.0' | '+nan.0' | '-nan.0';
fragment
SUFFIX : EXPONENT_MARKER SIGN? DIGIT_10+;
fragment
SIGN : '+' | '-';
fragment
EXPONENT_MARKER : 'e';
fragment
EXACTNESS : '#i' | '#e';
fragment
RADIX_2 : '#b';
fragment
RADIX_8 : '#o';
fragment
RADIX_10 : '#d';
fragment
RADIX_16 : '#x';
fragment
DIGIT_2 : '0' | '1';
fragment
DIGIT_8 : [0-7];
fragment
DIGIT_10 : DIGIT;
fragment
DIGIT_16 : DIGIT_10 | [a-f];
|
Add missing tokens
|
Add missing tokens
|
ANTLR
|
apache-2.0
|
OrangeShark/citrus-scheme
|
b7f011624e1a2158aa89a97a3061b4b34a1e12a8
|
src/main/antlr4/io/burt/jmespath/JmesPath.g4
|
src/main/antlr4/io/burt/jmespath/JmesPath.g4
|
grammar JmesPath;
query : expression EOF ;
expression
: expression '.' (identifier | multiSelectList | multiSelectHash | functionExpression | wildcard='*') # chainExpression
| expression bracketSpecifier # bracketedExpression
| bracketSpecifier # bracketExpression
| expression COMPARATOR expression # comparisonExpression
| expression '&&' expression # andExpression
| expression '||' expression # orExpression
| identifier # identifierExpression
| '!' expression # notExpression
| '(' expression ')' # parenExpression
| '*' # wildcardExpression
| multiSelectList # multiSelectListExpression
| multiSelectHash # multiSelectHashExpression
| literal # literalExpression
| functionExpression # functionCallExpression
| expression '|' expression # pipeExpression
| RAW_STRING # rawStringExpression
| currentNode # currentNodeExpression
;
multiSelectList : '[' expression (',' expression)* ']' ;
multiSelectHash : '{' keyvalExpr (',' keyvalExpr)* '}' ;
keyvalExpr : identifier ':' expression ;
bracketSpecifier
: '[' SIGNED_INT ']' # bracketIndex
| '[' '*' ']' # bracketStar
| '[' slice ']' # bracketSlice
| '[' ']' # bracketFlatten
| '[?' expression ']' # select
;
slice : start=SIGNED_INT? ':' stop=SIGNED_INT? (':' step=SIGNED_INT?)? ;
COMPARATOR
: '<'
| '<='
| '=='
| '>='
| '>'
| '!='
;
functionExpression
: NAME '(' functionArg (',' functionArg)* ')'
| NAME '(' ')'
;
functionArg
: expression
| expressionType
;
currentNode : '@' ;
expressionType : '&' expression ;
RAW_STRING : '\'' (RAW_ESC | ~['\\])* '\'' ;
fragment RAW_ESC : '\\' ['\\] ;
literal : '`' jsonValue '`' ;
identifier
: NAME
| STRING
;
NAME : [a-zA-Z_] [a-zA-Z0-9_]* ;
jsonObject
: '{' jsonObjectPair (',' jsonObjectPair)* '}'
| '{' '}'
;
jsonObjectPair
: STRING ':' jsonValue
;
jsonArray
: '[' jsonValue (',' jsonValue)* ']'
| '[' ']'
;
jsonValue
: STRING # jsonStringValue
| (REAL_OR_EXPONENT_NUMBER | SIGNED_INT) # jsonNumberValue
| jsonObject # jsonObjectValue
| jsonArray # jsonArrayValue
| (t='true' | f='false' | l='null') # jsonConstantValue
;
STRING
: '"' (ESC | ~ ["\\])* '"'
;
fragment ESC
: '\\' (["\\/bfnrt] | UNICODE)
;
fragment UNICODE
: 'u' HEX HEX HEX HEX
;
fragment HEX
: [0-9a-fA-F]
;
REAL_OR_EXPONENT_NUMBER
: '-'? INT '.' [0-9] + EXP?
| '-'? INT EXP
;
SIGNED_INT : '-'? INT ;
fragment INT
: '0'
| [1-9] [0-9]*
;
fragment EXP
: [Ee] [+\-]? INT
;
WS
: [ \t\n\r] + -> skip
;
|
grammar JmesPath;
query : expression EOF ;
expression
: expression '.' (identifier | multiSelectList | multiSelectHash | functionExpression | wildcard='*') # chainExpression
| expression bracketSpecifier # bracketedExpression
| bracketSpecifier # bracketExpression
| expression COMPARATOR expression # comparisonExpression
| expression '&&' expression # andExpression
| expression '||' expression # orExpression
| identifier # identifierExpression
| '!' expression # notExpression
| '(' expression ')' # parenExpression
| '*' # wildcardExpression
| multiSelectList # multiSelectListExpression
| multiSelectHash # multiSelectHashExpression
| literal # literalExpression
| functionExpression # functionCallExpression
| expression '|' expression # pipeExpression
| RAW_STRING # rawStringExpression
| currentNode # currentNodeExpression
;
multiSelectList : '[' expression (',' expression)* ']' ;
multiSelectHash : '{' keyvalExpr (',' keyvalExpr)* '}' ;
keyvalExpr : identifier ':' expression ;
bracketSpecifier
: '[' SIGNED_INT ']' # bracketIndex
| '[' '*' ']' # bracketStar
| '[' slice ']' # bracketSlice
| '[' ']' # bracketFlatten
| '[?' expression ']' # select
;
slice : start=SIGNED_INT? ':' stop=SIGNED_INT? (':' step=SIGNED_INT?)? ;
COMPARATOR
: '<'
| '<='
| '=='
| '>='
| '>'
| '!='
;
functionExpression
: NAME '(' functionArg (',' functionArg)* ')'
| NAME '(' ')'
;
functionArg
: expression
| expressionType
;
currentNode : '@' ;
expressionType : '&' expression ;
RAW_STRING : '\'' (RAW_ESC | ~['\\])* '\'' ;
fragment RAW_ESC : '\\' ['\\] ;
literal : '`' jsonValue '`' ;
identifier
: NAME
| STRING
;
NAME : [a-zA-Z_] [a-zA-Z0-9_]* ;
jsonObject
: '{' jsonObjectPair (',' jsonObjectPair)* '}'
| '{' '}'
;
jsonObjectPair
: STRING ':' jsonValue
;
jsonArray
: '[' jsonValue (',' jsonValue)* ']'
| '[' ']'
;
jsonValue
: STRING # jsonStringValue
| (REAL_OR_EXPONENT_NUMBER | SIGNED_INT) # jsonNumberValue
| jsonObject # jsonObjectValue
| jsonArray # jsonArrayValue
| (t='true' | f='false' | n='null') # jsonConstantValue
;
STRING
: '"' (ESC | ~ ["\\])* '"'
;
fragment ESC
: '\\' (["\\/bfnrt] | UNICODE)
;
fragment UNICODE
: 'u' HEX HEX HEX HEX
;
fragment HEX
: [0-9a-fA-F]
;
REAL_OR_EXPONENT_NUMBER
: '-'? INT '.' [0-9] + EXP?
| '-'? INT EXP
;
SIGNED_INT : '-'? INT ;
fragment INT
: '0'
| [1-9] [0-9]*
;
fragment EXP
: [Ee] [+\-]? INT
;
WS
: [ \t\n\r] + -> skip
;
|
Change a grammar label
|
Change a grammar label
For some reason 'null' is labelled 'l' and not 'n'...
|
ANTLR
|
bsd-3-clause
|
burtcorp/jmespath-java
|
91ada2dd89ac82aaa5a14f7e9dbfba9c5014c1fb
|
src/main/antlr/Scheme.g4
|
src/main/antlr/Scheme.g4
|
grammar Scheme;
@header {
package scheme.antlr;
}
// Parser rules
datum : simpleDatum
| compoundDatum
;
simpleDatum : BOOLEAN # Boolean
| NUMBER # Number
| CHARACTER # Character
| STRING # String
| IDENTIFIER # Identifier
;
compoundDatum : list
| vector
| byteVector
| abbreviation
;
list : '(' datum* ')'
| '(' datum+ '.' datum ')'
;
vector : '#(' datum* ')';
byteVector : '#u8(' NUMBER* ')';
abbreviation : abbrevPrefix datum;
abbrevPrefix : '\'' | '`' | ',' | ',@';
// Lexer rules
fragment
INTRALINE_WHITESPACE : [ \t];
fragment
LINE_ENDING : '\n' | '\r\n' | '\r';
LPAREN : '(';
RPAREN : ')';
VECTORPAREN : '#(';
BYTEPAREN : '#u8(';
QUOTE : '\'';
QUASIQUOTE : '`';
UNQUOTE : ',';
SPLICING_UNQUOTE : ',@';
DOT : '.';
IDENTIFIER : INITIAL SUBSEQUENT*
| '|' SYMBOL_ELEMENT* '|'
| PECULIAR_IDENTIFIER
;
fragment
INITIAL : LETTER
| SPECIAL_INITIAL
;
fragment
LETTER : [a-zA-Z];
fragment
SPECIAL_INITIAL : '!' | '$' | '%' | '*' | '/' | ':' | '<'
| '=' | '>' | '?' | '^' | '_' | '~';
fragment
SUBSEQUENT : INITIAL | DIGIT | SPECIAL_SUBSEQUENT;
fragment
DIGIT : [0-9];
fragment
HEX_DIGIT : DIGIT | [a-f];
fragment
EXPLICIT_SIGN : '+' | '-';
fragment
SPECIAL_SUBSEQUENT : EXPLICIT_SIGN | '.' | '@';
fragment
INLINE_HEX_ESCAPE : '\\x' HEX_SCALAR_VALUE ';';
fragment
HEX_SCALAR_VALUE : HEX_DIGIT+;
fragment
MNEMONIC_ESCAPE : '\\a' | '\\b' | '\\t' | '\\n' | '\\r';
fragment
PECULIAR_IDENTIFIER : EXPLICIT_SIGN
| EXPLICIT_SIGN SIGN_SUBSEQUENT SUBSEQUENT*
| EXPLICIT_SIGN '.' DOT_SUBSEQUENT SUBSEQUENT*
| '.' DOT_SUBSEQUENT SUBSEQUENT*
;
fragment
DOT_SUBSEQUENT : SIGN_SUBSEQUENT
| '.'
;
fragment
SIGN_SUBSEQUENT : INITIAL | EXPLICIT_SIGN | '@';
fragment
SYMBOL_ELEMENT : ~[|\\] | INLINE_HEX_ESCAPE | MNEMONIC_ESCAPE | '\\|';
BOOLEAN : '#t'
| '#f'
| '#true'
| '#false'
;
CHARACTER : '#\\' | '#\\' CHARACTER_NAME | '#\\x' HEX_SCALAR_VALUE;
fragment
CHARACTER_NAME : 'alarm' | 'backspace' | 'delete' | 'escape'
| 'newline' | 'null' | 'return' | 'space' | 'tab';
STRING : '"' STRING_ELEMENT* '"';
fragment
STRING_ELEMENT : ~["\\]
| MNEMONIC_ESCAPE
| '\\"'
| '\\\\'
| '\\' INTRALINE_WHITESPACE* LINE_ENDING INTRALINE_WHITESPACE*
| INLINE_HEX_ESCAPE
;
// Numbers
NUMBER : NUM_2 | NUM_8 | NUM_10 | NUM_16;
// Binary
fragment
NUM_2 : PREFIX_2 COMPLEX_2;
fragment
COMPLEX_2 : REAL_2 | REAL_2 '@' REAL_2 | REAL_2 '+' UREAL_2 'i'
| REAL_2 '-' UREAL_2 'i' | REAL_2 '+' 'i' | REAL_2 '-' 'i'
| REAL_2 INFNAN 'i' | '+' UREAL_2 'i' | '-' UREAL_2 'i'
| INFNAN 'i' | '+' 'i' | '-' 'i'
;
fragment
REAL_2 : SIGN? UREAL_2 | INFNAN;
fragment
UREAL_2 : UINTEGER_2
| UINTEGER_2 '/' UINTEGER_2
;
fragment
UINTEGER_2 : DIGIT_2+;
fragment
PREFIX_2 : RADIX_2 EXACTNESS?
| EXACTNESS? RADIX_2
;
// Octal
fragment
NUM_8 : PREFIX_8 COMPLEX_8;
fragment
COMPLEX_8 : REAL_8 | REAL_8 '@' REAL_8 | REAL_8 '+' UREAL_8 'i'
| REAL_8 '-' UREAL_8 'i' | REAL_8 '+' 'i' | REAL_8 '-' 'i'
| REAL_8 INFNAN 'i' | '+' UREAL_8 'i' | '-' UREAL_8 'i'
| INFNAN 'i' | '+' 'i' | '-' 'i'
;
fragment
REAL_8 : SIGN? UREAL_8 | INFNAN;
fragment
UREAL_8 : UINTEGER_8
| UINTEGER_8 '/' UINTEGER_8
;
fragment
UINTEGER_8 : DIGIT_8+;
fragment
PREFIX_8 : RADIX_8 EXACTNESS?
| EXACTNESS? RADIX_8
;
// Decimal
fragment
NUM_10 : PREFIX_10 COMPLEX_10;
fragment
COMPLEX_10 : REAL_10 | REAL_10 '@' REAL_10 | REAL_10 '+' UREAL_10 'i'
| REAL_10 '-' UREAL_10 'i' | REAL_10 '+' 'i' | REAL_10 '-' 'i'
| REAL_10 INFNAN 'i' | '+' UREAL_10 'i' | '-' UREAL_10 'i'
| INFNAN 'i' | '+' 'i' | '-' 'i'
;
fragment
REAL_10 : SIGN? UREAL_10 | INFNAN;
fragment
UREAL_10 : UINTEGER_10
| UINTEGER_10 '/' UINTEGER_10
| DECIMAL_10
;
fragment
DECIMAL_10 : UINTEGER_10 SUFFIX?
| '.' DIGIT_10+ SUFFIX?
| DIGIT_10+ '.' DIGIT_10* SUFFIX?
;
fragment
UINTEGER_10 : DIGIT_10+;
fragment
PREFIX_10 : RADIX_10 EXACTNESS?
| EXACTNESS? RADIX_10
;
// Hexadecimal
fragment
NUM_16 : PREFIX_16 COMPLEX_16;
fragment
COMPLEX_16 : REAL_16 | REAL_16 '@' REAL_16 | REAL_16 '+' UREAL_16 'i'
| REAL_16 '-' UREAL_16 'i' | REAL_16 '+' 'i' | REAL_16 '-' 'i'
| REAL_16 INFNAN 'i' | '+' UREAL_16 'i' | '-' UREAL_16 'i'
| INFNAN 'i' | '+' 'i' | '-' 'i'
;
fragment
REAL_16 : SIGN? UREAL_16 | INFNAN;
fragment
UREAL_16 : UINTEGER_16
| UINTEGER_16 '/' UINTEGER_16
;
fragment
UINTEGER_16 : DIGIT_16+;
fragment
PREFIX_16 : RADIX_16 EXACTNESS?
| EXACTNESS? RADIX_16
;
fragment
INFNAN : '+inf.0' | '-inf.0' | '+nan.0' | '-nan.0';
fragment
SUFFIX : EXPONENT_MARKER SIGN? DIGIT_10+;
fragment
SIGN : '+' | '-';
fragment
EXPONENT_MARKER : 'e';
fragment
EXACTNESS : '#i' | '#e';
fragment
RADIX_2 : '#b';
fragment
RADIX_8 : '#o';
fragment
RADIX_10 : '#d';
fragment
RADIX_16 : '#x';
fragment
DIGIT_2 : '0' | '1';
fragment
DIGIT_8 : [0-7];
fragment
DIGIT_10 : DIGIT;
fragment
DIGIT_16 : DIGIT_10 | [a-f];
|
grammar Scheme;
@header {
package scheme.antlr;
}
// Parser rules
datum : simpleDatum
| compoundDatum
;
simpleDatum : BOOLEAN # Boolean
| NUMBER # Number
| CHARACTER # Character
| STRING # String
| IDENTIFIER # Identifier
;
compoundDatum : list
| vector
| byteVector
| abbreviation
;
list : '(' datum* ')'
| '(' datum+ '.' datum ')'
;
vector : '#(' datum* ')';
byteVector : '#u8(' NUMBER* ')';
abbreviation : abbrevPrefix datum;
abbrevPrefix : '\'' | '`' | ',' | ',@';
// Lexer rules
fragment
INTRALINE_WHITESPACE : [ \t];
fragment
LINE_ENDING : '\n' | '\r\n' | '\r';
LPAREN : '(';
RPAREN : ')';
VECTORPAREN : '#(';
BYTEPAREN : '#u8(';
QUOTE : '\'';
QUASIQUOTE : '`';
UNQUOTE : ',';
SPLICING_UNQUOTE : ',@';
DOT : '.';
IDENTIFIER : INITIAL SUBSEQUENT*
| '|' SYMBOL_ELEMENT* '|'
| PECULIAR_IDENTIFIER
;
fragment
INITIAL : LETTER
| SPECIAL_INITIAL
;
fragment
LETTER : [a-zA-Z];
fragment
SPECIAL_INITIAL : '!' | '$' | '%' | '*' | '/' | ':' | '<'
| '=' | '>' | '?' | '^' | '_' | '~';
fragment
SUBSEQUENT : INITIAL | DIGIT | SPECIAL_SUBSEQUENT;
fragment
DIGIT : [0-9];
fragment
HEX_DIGIT : DIGIT | [a-f];
fragment
EXPLICIT_SIGN : '+' | '-';
fragment
SPECIAL_SUBSEQUENT : EXPLICIT_SIGN | '.' | '@';
fragment
INLINE_HEX_ESCAPE : '\\x' HEX_SCALAR_VALUE ';';
fragment
HEX_SCALAR_VALUE : HEX_DIGIT+;
fragment
MNEMONIC_ESCAPE : '\\a' | '\\b' | '\\t' | '\\n' | '\\r';
fragment
PECULIAR_IDENTIFIER : EXPLICIT_SIGN
| EXPLICIT_SIGN SIGN_SUBSEQUENT SUBSEQUENT*
| EXPLICIT_SIGN '.' DOT_SUBSEQUENT SUBSEQUENT*
| '.' DOT_SUBSEQUENT SUBSEQUENT*
;
fragment
DOT_SUBSEQUENT : SIGN_SUBSEQUENT
| '.'
;
fragment
SIGN_SUBSEQUENT : INITIAL | EXPLICIT_SIGN | '@';
fragment
SYMBOL_ELEMENT : ~[|\\] | INLINE_HEX_ESCAPE | MNEMONIC_ESCAPE | '\\|';
BOOLEAN : '#t'
| '#f'
| '#true'
| '#false'
;
CHARACTER : '#\\' | '#\\' CHARACTER_NAME | '#\\x' HEX_SCALAR_VALUE;
fragment
CHARACTER_NAME : 'alarm' | 'backspace' | 'delete' | 'escape'
| 'newline' | 'null' | 'return' | 'space' | 'tab';
STRING : '"' STRING_ELEMENT* '"';
fragment
STRING_ELEMENT : ~["\\]
| MNEMONIC_ESCAPE
| '\\"'
| '\\\\'
| '\\' INTRALINE_WHITESPACE* LINE_ENDING INTRALINE_WHITESPACE*
| INLINE_HEX_ESCAPE
;
// Numbers
NUMBER : NUM_2 | NUM_8 | NUM_10 | NUM_16;
// Binary
fragment
NUM_2 : PREFIX_2 COMPLEX_2;
fragment
COMPLEX_2 : REAL_2 | REAL_2 '@' REAL_2 | REAL_2 '+' UREAL_2 'i'
| REAL_2 '-' UREAL_2 'i' | REAL_2 '+' 'i' | REAL_2 '-' 'i'
| REAL_2 INFNAN 'i' | '+' UREAL_2 'i' | '-' UREAL_2 'i'
| INFNAN 'i' | '+' 'i' | '-' 'i'
;
fragment
REAL_2 : SIGN? UREAL_2 | INFNAN;
fragment
UREAL_2 : UINTEGER_2
| UINTEGER_2 '/' UINTEGER_2
;
fragment
UINTEGER_2 : DIGIT_2+;
fragment
PREFIX_2 : RADIX_2 EXACTNESS?
| EXACTNESS? RADIX_2
;
// Octal
fragment
NUM_8 : PREFIX_8 COMPLEX_8;
fragment
COMPLEX_8 : REAL_8 | REAL_8 '@' REAL_8 | REAL_8 '+' UREAL_8 'i'
| REAL_8 '-' UREAL_8 'i' | REAL_8 '+' 'i' | REAL_8 '-' 'i'
| REAL_8 INFNAN 'i' | '+' UREAL_8 'i' | '-' UREAL_8 'i'
| INFNAN 'i' | '+' 'i' | '-' 'i'
;
fragment
REAL_8 : SIGN? UREAL_8 | INFNAN;
fragment
UREAL_8 : UINTEGER_8
| UINTEGER_8 '/' UINTEGER_8
;
fragment
UINTEGER_8 : DIGIT_8+;
fragment
PREFIX_8 : RADIX_8 EXACTNESS?
| EXACTNESS? RADIX_8
;
// Decimal
fragment
NUM_10 : PREFIX_10 COMPLEX_10;
fragment
COMPLEX_10 : REAL_10 | REAL_10 '@' REAL_10 | REAL_10 '+' UREAL_10 'i'
| REAL_10 '-' UREAL_10 'i' | REAL_10 '+' 'i' | REAL_10 '-' 'i'
| REAL_10 INFNAN 'i' | '+' UREAL_10 'i' | '-' UREAL_10 'i'
| INFNAN 'i' | '+' 'i' | '-' 'i'
;
fragment
REAL_10 : SIGN? UREAL_10 | INFNAN;
fragment
UREAL_10 : UINTEGER_10
| UINTEGER_10 '/' UINTEGER_10
| DECIMAL_10
;
fragment
DECIMAL_10 : UINTEGER_10 SUFFIX?
| '.' DIGIT_10+ SUFFIX?
| DIGIT_10+ '.' DIGIT_10* SUFFIX?
;
fragment
UINTEGER_10 : DIGIT_10+;
fragment
PREFIX_10 : RADIX_10? EXACTNESS?
| EXACTNESS? RADIX_10?
;
// Hexadecimal
fragment
NUM_16 : PREFIX_16 COMPLEX_16;
fragment
COMPLEX_16 : REAL_16 | REAL_16 '@' REAL_16 | REAL_16 '+' UREAL_16 'i'
| REAL_16 '-' UREAL_16 'i' | REAL_16 '+' 'i' | REAL_16 '-' 'i'
| REAL_16 INFNAN 'i' | '+' UREAL_16 'i' | '-' UREAL_16 'i'
| INFNAN 'i' | '+' 'i' | '-' 'i'
;
fragment
REAL_16 : SIGN? UREAL_16 | INFNAN;
fragment
UREAL_16 : UINTEGER_16
| UINTEGER_16 '/' UINTEGER_16
;
fragment
UINTEGER_16 : DIGIT_16+;
fragment
PREFIX_16 : RADIX_16 EXACTNESS?
| EXACTNESS? RADIX_16
;
fragment
INFNAN : '+inf.0' | '-inf.0' | '+nan.0' | '-nan.0';
fragment
SUFFIX : EXPONENT_MARKER SIGN? DIGIT_10+;
fragment
SIGN : '+' | '-';
fragment
EXPONENT_MARKER : 'e';
fragment
EXACTNESS : '#i' | '#e';
fragment
RADIX_2 : '#b';
fragment
RADIX_8 : '#o';
fragment
RADIX_10 : '#d';
fragment
RADIX_16 : '#x';
fragment
DIGIT_2 : '0' | '1';
fragment
DIGIT_8 : [0-7];
fragment
DIGIT_10 : DIGIT;
fragment
DIGIT_16 : DIGIT_10 | [a-f];
TRASH : INTRALINE_WHITESPACE -> channel(HIDDEN);
|
Fix grammar for base 10 numbers and ignore ws
|
Fix grammar for base 10 numbers and ignore ws
|
ANTLR
|
apache-2.0
|
OrangeShark/citrus-scheme
|
7b32359a1ecfcea2b098c5dfc643eed4fd5ccc0e
|
MATLAB.g4
|
MATLAB.g4
|
grammar MATLAB;
fileDecl
: (functionDecl | classDecl)? (functionDecl* | partialFunctionDecl*)
| partialFunctionDecl*
| stat* // Script
;
endStat
: (NL|COMMA|SEMI) NL*
;
endStatNL
: NL+
;
// Function declaration without the closing end
partialFunctionDecl
: 'function' outArgs? ID inArgs? endStat statBlock
;
// Normal function declaration including closing end
functionDecl
: partialFunctionDecl 'end' endStatNL NL*
;
// Functions inside method blocks can be comma or semi separated
methodDecl
: partialFunctionDecl 'end' endStat
;
classDecl
: 'classdef' ID endStat
(propBlockDecl|methodBlockDecl)*
'end' (EOF|endStat) NL*
;
propBlockDecl
: 'properties' endStat prop* 'end' endStat
;
methodBlockDecl
: 'methods' endStat methodDecl* 'end' endStat
;
outArgs
: ID '='
| '[' ID (',' ID)* ']' '='
;
inArgs
: '(' ID (',' ID)* ')'
| '(' ')'
;
prop
: ID ('=' expr)? endStat
;
dotRef
: ID ('.' ID)*
;
statBlock
: (stat endStat)*
;
ifStat
: 'if' expr endStat statBlock
('elseif' expr endStat statBlock)*
('else' endStat statBlock)?
'end'
;
whileStat
: 'while' expr endStat statBlock 'end'
;
caseStat
: 'switch' expr endStat
('case' expr endStat statBlock)*
('otherwise' endStat statBlock)?
'end'
;
stat
: dotRef '=' expr
| ifStat
| whileStat
| caseStat
| ID
| NL
;
arraySep
: (COMMA | SEMI)
;
arrayExpr
: '[' expr (arraySep expr)* ']'
| '[' ']'
;
cellExpr
: '{' expr (arraySep expr)* '}'
| '{' '}'
;
expr
: expr '(' exprList ')'
| expr ('\''|'.\''|'.^'|'^') expr
| ('+'|'-''~') expr
| expr ('*'|'.*'|'/'|'./'|'\\'|'.\\') expr
| expr ('+'|'-') expr
| expr ':' expr
| expr ('~'|'=='|'>'|'<'|'>='|'<=') expr
| expr '&' expr
| expr '|' expr
| expr '&&' expr
| expr '||' expr
| dotRef
| NUMBER
| STRING
| arrayExpr
| cellExpr
| '(' expr ')'
;
exprList
: expr (',' expr)*
;
fragment
DIGIT
: [0-9] ;
NL : '\r'?'\n' ;
WS : [ \t]+ -> skip ;
LINECONTINUE
: '...' .*? NL -> skip ;
COMMENT
: '%' .*? NL -> skip ;
COMMA : ',' ;
SEMI : ';' ;
fragment
LETTER
: [a-zA-Z] ;
ID : LETTER (LETTER|DIGIT|'_')* ;
NUMBER : DIGIT+ ;
STRING
: '\'' (ESC|.)*? '\''
;
fragment
ESC : '\'\'' ;
|
grammar MATLAB;
fileDecl
: (functionDecl | classDecl)? (functionDecl* | partialFunctionDecl*)
| partialFunctionDecl*
| stat* // Script
;
endStat
: (NL|COMMA|SEMI) NL*
;
endStatNL
: NL+
;
// Function declaration without the closing end
partialFunctionDecl
: 'function' outArgs? ID inArgs? endStat statBlock
;
// Normal function declaration including closing end
functionDecl
: partialFunctionDecl 'end' endStatNL NL*
;
// Functions inside method blocks can be comma or semi separated
methodDecl
: partialFunctionDecl 'end' endStat
;
classDecl
: 'classdef' ID endStat
(propBlockDecl|methodBlockDecl)*
'end' (EOF|endStat) NL*
;
propBlockDecl
: 'properties' endStat prop* 'end' endStat
;
methodBlockDecl
: 'methods' endStat methodDecl* 'end' endStat
;
outArgs
: ID '='
| '[' ID (',' ID)* ']' '='
;
inArgs
: '(' ID (',' ID)* ')'
| '(' ')'
;
prop
: ID ('=' expr)? endStat
;
dotRef
: ID ('.' ID)*
;
statBlock
: (stat endStat)*
;
ifStat
: 'if' expr endStat statBlock
('elseif' expr endStat statBlock)*
('else' endStat? statBlock)?
'end'
;
whileStat
: 'while' expr endStat statBlock 'end'
;
caseStat
: 'switch' expr endStat
('case' expr endStat statBlock)*
('otherwise' endStat statBlock)?
'end'
;
stat
: dotRef '=' expr
| ifStat
| whileStat
| caseStat
| expr
| NL
;
arraySep
: (COMMA | SEMI)
;
arrayExpr
: '[' expr (arraySep expr)* ']'
| '[' ']'
;
cellExpr
: '{' expr (arraySep expr)* '}'
| '{' '}'
;
expr
: expr '(' exprList ')'
| expr ('\''|'.\''|'.^'|'^') expr
| ('+'|'-'|'~') expr
| expr ('*'|'.*'|'/'|'./'|'\\'|'.\\') expr
| expr ('+'|'-') expr
| expr ':' expr
| expr ('~'|'=='|'>'|'<'|'>='|'<=') expr
| expr '&' expr
| expr '|' expr
| expr '&&' expr
| expr '||' expr
| dotRef
| NUMBER
| STRING
| arrayExpr
| cellExpr
| '(' expr ')'
;
exprList
: expr (',' expr)*
;
fragment
DIGIT
: [0-9] ;
NL : '\r'?'\n' ;
WS : [ \t]+ -> skip ;
LINECONTINUE
: '...' .*? NL -> skip ;
COMMENT
: '%' .*? NL -> skip ;
COMMA : ',' ;
SEMI : ';' ;
fragment
LETTER
: [a-zA-Z] ;
ID : LETTER (LETTER|DIGIT|'_')* ;
NUMBER : DIGIT+ ;
STRING
: '\'' (ESC|.)*? '\''
;
fragment
ESC : '\'\'' ;
|
Fix some errors in the grammar.
|
Fix some errors in the grammar.
|
ANTLR
|
apache-2.0
|
mattmcd/ParseMATLAB,mattmcd/ParseMATLAB
|
9547044e039d85977d1fa18e12321469c8dbc244
|
stringtemplate/LexBasic.g4
|
stringtemplate/LexBasic.g4
|
/*
* [The "BSD license"]
* Copyright (c) 2014-2015 Gerald Rosenberg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* A generally reusable set of fragments for import in to Lexer grammars.
*
* Modified 2015.06.16 gbr -
* -- generalized for inclusion into the ANTLRv4 grammar distribution
*
*/
lexer grammar LexBasic;
import LexUnicode; // Formal set of Unicode ranges
// ======================================================
// Lexer fragments
//
// -----------------------------------
// Whitespace & Comments
fragment Ws : Hws | Vws ;
fragment Hws : [ \t] ;
fragment Vws : [\r\n\f] ;
fragment DocComment : '/**' .*? ('*/' | EOF) ;
fragment BlockComment : '/*' .*? ('*/' | EOF) ;
fragment LineComment : '//' ~[\r\n]* ;
fragment LineCommentExt : '//' ~'\n'* ( '\n' Hws* '//' ~'\n'* )* ;
// -----------------------------------
// Escapes
// Any kind of escaped character that we can embed within ANTLR literal strings.
fragment EscSeq
: Esc
( [btnfr"'\\] // The standard escaped character set such as tab, newline, etc.
| UnicodeEsc // A Unicode escape sequence
| . // Invalid escape character
| EOF // Incomplete at EOF
)
;
fragment EscAny
: Esc .
;
fragment UnicodeEsc
: 'u' (HexDigit (HexDigit (HexDigit HexDigit?)?)?)?
;
fragment OctalEscape
: OctalDigit
| OctalDigit OctalDigit
| [0-3] OctalDigit OctalDigit
;
// -----------------------------------
// Numerals
fragment HexNumeral
: '0' [xX] HexDigits
;
fragment OctalNumeral
: '0' '_' OctalDigits
;
fragment DecimalNumeral
: '0'
| [1-9] DecDigit*
;
fragment BinaryNumeral
: '0' [bB] BinaryDigits
;
// -----------------------------------
// Digits
fragment HexDigits : HexDigit+ ;
fragment DecDigits : DecDigit+ ;
fragment OctalDigits : OctalDigit+ ;
fragment BinaryDigits : BinaryDigit+ ;
fragment HexDigit : [0-9a-fA-F] ;
fragment DecDigit : [0-9] ;
fragment OctalDigit : [0-7] ;
fragment BinaryDigit : [01] ;
// -----------------------------------
// Literals
fragment BoolLiteral : True | False ;
fragment CharLiteral : SQuote ( EscSeq | ~['\r\n\\] ) SQuote ;
fragment SQuoteLiteral : SQuote ( EscSeq | ~['\r\n\\] )* SQuote ;
fragment DQuoteLiteral : DQuote ( EscSeq | ~["\r\n\\] )* DQuote ;
fragment USQuoteLiteral : SQuote ( EscSeq | ~['\r\n\\] )* ;
fragment DecimalFloatingPointLiteral
: DecDigits DOT DecDigits? ExponentPart? FloatTypeSuffix?
| DOT DecDigits ExponentPart? FloatTypeSuffix?
| DecDigits ExponentPart FloatTypeSuffix?
| DecDigits FloatTypeSuffix
;
fragment ExponentPart
: [eE] [+-]? DecDigits
;
fragment FloatTypeSuffix
: [fFdD]
;
fragment HexadecimalFloatingPointLiteral
: HexSignificand BinaryExponent FloatTypeSuffix?
;
fragment HexSignificand
: HexNumeral DOT?
| '0' [xX] HexDigits? DOT HexDigits
;
fragment BinaryExponent
: [pP] [+-]? DecDigits
;
// -----------------------------------
// Character ranges
fragment NameChar
: NameStartChar
| '0'..'9'
| Underscore
| '\u00B7'
| '\u0300'..'\u036F'
| '\u203F'..'\u2040'
;
fragment NameStartChar
: 'A'..'Z'
| 'a'..'z'
| '\u00C0'..'\u00D6'
| '\u00D8'..'\u00F6'
| '\u00F8'..'\u02FF'
| '\u0370'..'\u037D'
| '\u037F'..'\u1FFF'
| '\u200C'..'\u200D'
| '\u2070'..'\u218F'
| '\u2C00'..'\u2FEF'
| '\u3001'..'\uD7FF'
| '\uF900'..'\uFDCF'
| '\uFDF0'..'\uFFFD'
; // ignores | ['\u10000-'\uEFFFF] ;
fragment JavaLetter
: [a-zA-Z$_] // "java letters" below 0xFF
| JavaUnicodeChars
;
fragment JavaLetterOrDigit
: [a-zA-Z0-9$_] // "java letters or digits" below 0xFF
| JavaUnicodeChars
;
// covers all characters above 0xFF which are not a surrogate
// and UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF
fragment JavaUnicodeChars
: ~[\u0000-\u00FF\uD800-\uDBFF] {Character.isJavaIdentifierPart(_input.LA(-1))}?
| [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
// -----------------------------------
// Types
fragment Boolean : 'boolean' ;
fragment Byte : 'byte' ;
fragment Short : 'short' ;
fragment Int : 'int' ;
fragment Long : 'long' ;
fragment Char : 'char' ;
fragment Float : 'float' ;
fragment Double : 'double' ;
fragment True : 'true' ;
fragment False : 'false' ;
// -----------------------------------
// Symbols
fragment Esc : '\\' ;
fragment Colon : ':' ;
fragment DColon : '::' ;
fragment SQuote : '\'' ;
fragment DQuote : '"' ;
fragment BQuote : '`' ;
fragment LParen : '(' ;
fragment RParen : ')' ;
fragment LBrace : '{' ;
fragment RBrace : '}' ;
fragment LBrack : '[' ;
fragment RBrack : ']' ;
fragment RArrow : '->' ;
fragment Lt : '<' ;
fragment Gt : '>' ;
fragment Lte : '<=' ;
fragment Gte : '>=' ;
fragment Equal : '=' ;
fragment NotEqual : '!=' ;
fragment Question : '?' ;
fragment Bang : '!' ;
fragment Star : '*' ;
fragment Slash : '/' ;
fragment Percent : '%' ;
fragment Caret : '^' ;
fragment Plus : '+' ;
fragment Minus : '-' ;
fragment PlusAssign : '+=' ;
fragment MinusAssign : '-=' ;
fragment MulAssign : '*=' ;
fragment DivAssign : '/=' ;
fragment AndAssign : '&=' ;
fragment OrAssign : '|=' ;
fragment XOrAssign : '^=' ;
fragment ModAssign : '%=' ;
fragment LShiftAssign : '<<=' ;
fragment RShiftAssign : '>>=' ;
fragment URShiftAssign : '>>>=';
fragment Underscore : '_' ;
fragment Pipe : '|' ;
fragment Amp : '&' ;
fragment And : '&&' ;
fragment Or : '||' ;
fragment Inc : '++' ;
fragment Dec : '--' ;
fragment LShift : '<<' ;
fragment RShift : '>>' ;
fragment Dollar : '$' ;
fragment Comma : ',' ;
fragment Semi : ';' ;
fragment Dot : '.' ;
fragment Range : '..' ;
fragment Ellipsis : '...' ;
fragment At : '@' ;
fragment Pound : '#' ;
fragment Tilde : '~' ;
|
/*
* [The "BSD license"]
* Copyright (c) 2014-2015 Gerald Rosenberg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* A generally reusable set of fragments for import in to Lexer grammars.
*
* Modified 2015.06.16 gbr -
* -- generalized for inclusion into the ANTLRv4 grammar distribution
*
*/
lexer grammar LexBasic;
import LexUnicode; // Formal set of Unicode ranges
// ======================================================
// Lexer fragments
//
// -----------------------------------
// Whitespace & Comments
fragment Ws : Hws | Vws ;
fragment Hws : [ \t] ;
fragment Vws : [\r\n\f] ;
fragment DocComment : '/**' .*? ('*/' | EOF) ;
fragment BlockComment : '/*' .*? ('*/' | EOF) ;
fragment LineComment : '//' ~[\r\n]* ;
fragment LineCommentExt : '//' ~'\n'* ( '\n' Hws* '//' ~'\n'* )* ;
// -----------------------------------
// Escapes
// Any kind of escaped character that we can embed within ANTLR literal strings.
fragment EscSeq
: Esc
( [btnfr"'\\] // The standard escaped character set such as tab, newline, etc.
| UnicodeEsc // A Unicode escape sequence
| . // Invalid escape character
| EOF // Incomplete at EOF
)
;
fragment EscAny
: Esc .
;
fragment UnicodeEsc
: 'u' (HexDigit (HexDigit (HexDigit HexDigit?)?)?)?
;
fragment OctalEscape
: OctalDigit
| OctalDigit OctalDigit
| [0-3] OctalDigit OctalDigit
;
// -----------------------------------
// Numerals
fragment HexNumeral
: '0' [xX] HexDigits
;
fragment OctalNumeral
: '0' '_' OctalDigits
;
fragment DecimalNumeral
: '0'
| [1-9] DecDigit*
;
fragment BinaryNumeral
: '0' [bB] BinaryDigits
;
// -----------------------------------
// Digits
fragment HexDigits : HexDigit+ ;
fragment DecDigits : DecDigit+ ;
fragment OctalDigits : OctalDigit+ ;
fragment BinaryDigits : BinaryDigit+ ;
fragment HexDigit : [0-9a-fA-F] ;
fragment DecDigit : [0-9] ;
fragment OctalDigit : [0-7] ;
fragment BinaryDigit : [01] ;
// -----------------------------------
// Literals
fragment BoolLiteral : True | False ;
fragment CharLiteral : SQuote ( EscSeq | ~['\r\n\\] ) SQuote ;
fragment SQuoteLiteral : SQuote ( EscSeq | ~['\r\n\\] )* SQuote ;
fragment DQuoteLiteral : DQuote ( EscSeq | ~["\r\n\\] )* DQuote ;
fragment USQuoteLiteral : SQuote ( EscSeq | ~['\r\n\\] )* ;
fragment DecimalFloatingPointLiteral
: DecDigits Dot DecDigits? ExponentPart? FloatTypeSuffix?
| Dot DecDigits ExponentPart? FloatTypeSuffix?
| DecDigits ExponentPart FloatTypeSuffix?
| DecDigits FloatTypeSuffix
;
fragment ExponentPart
: [eE] [+-]? DecDigits
;
fragment FloatTypeSuffix
: [fFdD]
;
fragment HexadecimalFloatingPointLiteral
: HexSignificand BinaryExponent FloatTypeSuffix?
;
fragment HexSignificand
: HexNumeral Dot?
| '0' [xX] HexDigits? Dot HexDigits
;
fragment BinaryExponent
: [pP] [+-]? DecDigits
;
// -----------------------------------
// Character ranges
fragment NameChar
: NameStartChar
| '0'..'9'
| Underscore
| '\u00B7'
| '\u0300'..'\u036F'
| '\u203F'..'\u2040'
;
fragment NameStartChar
: 'A'..'Z'
| 'a'..'z'
| '\u00C0'..'\u00D6'
| '\u00D8'..'\u00F6'
| '\u00F8'..'\u02FF'
| '\u0370'..'\u037D'
| '\u037F'..'\u1FFF'
| '\u200C'..'\u200D'
| '\u2070'..'\u218F'
| '\u2C00'..'\u2FEF'
| '\u3001'..'\uD7FF'
| '\uF900'..'\uFDCF'
| '\uFDF0'..'\uFFFD'
; // ignores | ['\u10000-'\uEFFFF] ;
fragment JavaLetter
: [a-zA-Z$_] // "java letters" below 0xFF
| JavaUnicodeChars
;
fragment JavaLetterOrDigit
: [a-zA-Z0-9$_] // "java letters or digits" below 0xFF
| JavaUnicodeChars
;
// covers all characters above 0xFF which are not a surrogate
// and UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF
fragment JavaUnicodeChars
: ~[\u0000-\u00FF\uD800-\uDBFF] {Character.isJavaIdentifierPart(_input.LA(-1))}?
| [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;
// -----------------------------------
// Types
fragment Boolean : 'boolean' ;
fragment Byte : 'byte' ;
fragment Short : 'short' ;
fragment Int : 'int' ;
fragment Long : 'long' ;
fragment Char : 'char' ;
fragment Float : 'float' ;
fragment Double : 'double' ;
fragment True : 'true' ;
fragment False : 'false' ;
// -----------------------------------
// Symbols
fragment Esc : '\\' ;
fragment Colon : ':' ;
fragment DColon : '::' ;
fragment SQuote : '\'' ;
fragment DQuote : '"' ;
fragment BQuote : '`' ;
fragment LParen : '(' ;
fragment RParen : ')' ;
fragment LBrace : '{' ;
fragment RBrace : '}' ;
fragment LBrack : '[' ;
fragment RBrack : ']' ;
fragment RArrow : '->' ;
fragment Lt : '<' ;
fragment Gt : '>' ;
fragment Lte : '<=' ;
fragment Gte : '>=' ;
fragment Equal : '=' ;
fragment NotEqual : '!=' ;
fragment Question : '?' ;
fragment Bang : '!' ;
fragment Star : '*' ;
fragment Slash : '/' ;
fragment Percent : '%' ;
fragment Caret : '^' ;
fragment Plus : '+' ;
fragment Minus : '-' ;
fragment PlusAssign : '+=' ;
fragment MinusAssign : '-=' ;
fragment MulAssign : '*=' ;
fragment DivAssign : '/=' ;
fragment AndAssign : '&=' ;
fragment OrAssign : '|=' ;
fragment XOrAssign : '^=' ;
fragment ModAssign : '%=' ;
fragment LShiftAssign : '<<=' ;
fragment RShiftAssign : '>>=' ;
fragment URShiftAssign : '>>>=';
fragment Underscore : '_' ;
fragment Pipe : '|' ;
fragment Amp : '&' ;
fragment And : '&&' ;
fragment Or : '||' ;
fragment Inc : '++' ;
fragment Dec : '--' ;
fragment LShift : '<<' ;
fragment RShift : '>>' ;
fragment Dollar : '$' ;
fragment Comma : ',' ;
fragment Semi : ';' ;
fragment Dot : '.' ;
fragment Range : '..' ;
fragment Ellipsis : '...' ;
fragment At : '@' ;
fragment Pound : '#' ;
fragment Tilde : '~' ;
|
Update LexBasic.g4
|
Update LexBasic.g4
DOT to Dot for antlr4-4.7-SNAPSHOT-complete.jar to be happy
|
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
|
0468697b46de73b89bbbeeb24237743a49e1234f
|
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.symbols.*;
import org.antlr.symtab.*;
}
file : script EOF ;
script returns [GlobalScope scope]
: (outer_statement | vardef | function)*
;
function returns [WFunctionSymbol scope]
: 'func' ID '(' formal_args? ')' (':' type)? block
;
formal_args : formal_arg (',' formal_arg)* ;
formal_arg : ID ':' type ;
type: 'int' # IntTypeSpec
| 'float' # FloatTypeSpec
| 'string' # StringTypeSpec
| 'boolean' # BooleanTypeSpec
| '[' ']' # VectorTypeSpec
;
block returns [Scope scope]
: '{' statement* '}';
outer_statement
: 'if' '(' expr ')' statement ('else' statement)? # If
| 'while' '(' expr ')' statement # While
| ID '=' expr # Assign
| ID '[' expr ']' '=' expr # ElementAssign
| call_expr # CallStatement
| 'print' '(' expr? ')' # Print
;
statement
: outer_statement # OuterStuff
| vardef # VarDefStatement
| 'return' expr # Return
| block # BlockStatement
;
vardef : 'var' ID '=' expr ;
expr returns [Type exprType, Type promoteToType]
: expr operator expr # Op
| '-' expr # Negate
| '!' expr # Not
| call_expr # Call
| ID '[' expr ']' # Index
| '(' expr ')' # Parens
| primary # Atom
;
operator : MUL|DIV|ADD|SUB|GT|GE|LT|LE|EQUAL_EQUAL|NOT_EQUAL|OR|AND|DOT ; // no implicit precedence
call_expr returns [Type exprType, Type promoteToType]
: ID '(' expr_list? ')' ;
expr_list : expr (',' expr)* ;
primary returns [Type exprType]
: ID # Identifier
| INT # Integer
| FLOAT # Float
| STRING # String
| '[' expr_list ']' # Vector
;
LPAREN : '(' ;
RPAREN : ')' ;
COLON : ':' ;
COMMA : ',' ;
LBRACK : '[' ;
RBRACK : ']' ;
LBRACE : '{' ;
RBRACE : '}' ;
IF : 'if' ;
ELSE : 'else' ;
WHILE : 'while' ;
VAR : 'var' ;
EQUAL : '=' ;
RETURN : 'return' ;
PRINT : 'print' ;
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) ;
|
/*
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.symbols.*;
import org.antlr.symtab.*;
}
file : script EOF ;
script returns [GlobalScope scope]
: function* statement*
;
function returns [WFunctionSymbol scope]
: 'func' ID '(' formal_args? ')' (':' type)? block
;
formal_args : formal_arg (',' formal_arg)* ;
formal_arg : ID ':' type ;
type: 'int' # IntTypeSpec
| 'float' # FloatTypeSpec
| 'string' # StringTypeSpec
| 'boolean' # BooleanTypeSpec
| '[' ']' # VectorTypeSpec
;
block returns [Scope scope]
: '{' statement* '}';
statement
: 'if' '(' expr ')' statement ('else' statement)? # If
| 'while' '(' expr ')' statement # While
| ID '=' expr # Assign
| ID '[' expr ']' '=' expr # ElementAssign
| call_expr # CallStatement
| 'print' '(' expr? ')' # Print
| vardef # VarDefStatement
| 'return' expr # Return
| block # BlockStatement
;
vardef : 'var' ID '=' expr ;
expr returns [Type exprType, Type promoteToType]
: expr operator expr # Op
| '-' expr # Negate
| '!' expr # Not
| call_expr # Call
| ID '[' expr ']' # Index
| '(' expr ')' # Parens
| primary # Atom
;
operator : MUL|DIV|ADD|SUB|GT|GE|LT|LE|EQUAL_EQUAL|NOT_EQUAL|OR|AND|DOT ; // no implicit precedence
call_expr returns [Type exprType, Type promoteToType]
: ID '(' expr_list? ')' ;
expr_list : expr (',' expr)* ;
primary returns [Type exprType]
: ID # Identifier
| INT # Integer
| FLOAT # Float
| STRING # String
| '[' expr_list ']' # Vector
;
LPAREN : '(' ;
RPAREN : ')' ;
COLON : ':' ;
COMMA : ',' ;
LBRACK : '[' ;
RBRACK : ']' ;
LBRACE : '{' ;
RBRACE : '}' ;
IF : 'if' ;
ELSE : 'else' ;
WHILE : 'while' ;
VAR : 'var' ;
EQUAL : '=' ;
RETURN : 'return' ;
PRINT : 'print' ;
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) ;
|
simplify grammar so no global vars.
|
simplify grammar so no global vars.
|
ANTLR
|
mit
|
YuanyuanZh/wich-c,syuanivy/wich-c,langwich/wich-c,hanjoes/wich-c,hanjoes/wich-c,syuanivy/wich-c,YuanyuanZh/wich-c,langwich/wich-c
|
f4ab0dd3343cb6414179284a5ae8b5b8326e031c
|
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_
;
columnConstraints
: (columnConstraint(COMMA_ columnConstraint)*)?
;
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_
;
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)
;
hashWithBucket
: HASH columnNames withBucket
;
columnIndex
: INDEX indexName (CLUSTERED | NONCLUSTERED)? (WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause? (FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))?
;
indexOnClause
: onSchemaColumn | onFileGroup | onDefault
;
onDefault
: ON DEFAULT
;
tableConstraint
: (CONSTRAINT ignoredIdentifier_)? (tablePrimaryConstraint | tableForeignKeyConstraint | checkConstraint)
;
tablePrimaryConstraint
: primaryKeyUnique (diskTablePrimaryConstraintOption | memoryTablePrimaryConstraintOption)
;
primaryKeyUnique
: primaryKey | UNIQUE
;
diskTablePrimaryConstraintOption
: (CLUSTERED | NONCLUSTERED)? columnNames primaryKeyWithClause? primaryKeyOnClause?
;
memoryTablePrimaryConstraintOption
: NONCLUSTERED (columnNames | hashWithBucket)
;
tableForeignKeyConstraint
: (FOREIGN KEY)? columnNames REFERENCES tableName columnNames foreignKeyOnAction*
;
computedColumnDefinition
: columnName AS expr (PERSISTED(NOT NULL)?)? columnConstraint?
;
columnSetDefinition
: ignoredIdentifier_ IDENTIFIER_ COLUMN_SET FOR ALL_SPARSE_COLUMNS
;
alterTableOp
: ALTER TABLE tableName
;
alterColumn
: modifyColumnSpecification
;
modifyColumnSpecification
: alterColumnOp dataType (COLLATE collationName)? (NULL | NOT NULL)? SPARSE?
;
alterColumnOp
: ALTER COLUMN columnName
;
addColumnSpecification
: (WITH (CHECK | NOCHECK))? ADD (alterColumnAddOption (COMMA_ alterColumnAddOption)* | (columnNameGeneratedClause COMMA_ periodClause| periodClause COMMA_ columnNameGeneratedClause))
;
alterColumnAddOption
: columnDefinition
| computedColumnDefinition
| columnSetDefinition
| tableConstraint
| alterTableTableIndex
| constraintForColumn
;
constraintForColumn
: (CONSTRAINT ignoredIdentifier_)? DEFAULT simpleExpr FOR columnName
;
columnNameWithSortsWithParen
: LP_ columnNameWithSort (COMMA_ columnNameWithSort)* RP_
;
columnNameWithSort
: columnName (ASC | DESC)?
;
columnNameGeneratedClause
: columnNameGenerated DEFAULT simpleExpr (WITH VALUES)? COMMA_ columnNameGenerated
;
columnNameGenerated
: columnName dataTypeName_ GENERATED ALWAYS AS ROW (START | END)? HIDDEN_? (NOT NULL)? (CONSTRAINT ignoredIdentifier_)?
;
alterDrop
: DROP
(
alterTableDropConstraint
| dropColumnSpecification
| dropIndexSpecification
| PERIOD FOR SYSTEM_TIME
)
;
alterTableDropConstraint
: CONSTRAINT? (IF EXISTS)? dropConstraintName (COMMA_ dropConstraintName)*
;
dropConstraintName
: ignoredIdentifier_ dropConstraintWithClause?
;
dropConstraintWithClause
: WITH LP_ dropConstraintOption (COMMA_ dropConstraintOption)* RP_
;
dropConstraintOption
: (MAXDOP EQ_ NUMBER_ | ONLINE EQ_ (ON | OFF) | MOVE TO (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_))
;
dropColumnSpecification
: COLUMN (IF EXISTS)? columnName (COMMA_ columnName)*
;
dropIndexSpecification
: INDEX (IF EXISTS)? indexName (COMMA_ indexName)*
;
alterCheckConstraint
: WITH? (CHECK | NOCHECK) CONSTRAINT (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*))
;
alterTrigger
: (ENABLE| DISABLE) TRIGGER (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*))
;
alterSwitch
: SWITCH (PARTITION expr)? TO tableName (PARTITION expr)? (WITH LP_ lowPriorityLockWait RP_)?
;
alterSet
: SET LP_ (setFileStreamClause | setSystemVersionClause) RP_
;
setFileStreamClause
: FILESTREAM_ON EQ_ (schemaName | ignoredIdentifier_ | STRING_)
;
setSystemVersionClause
: SYSTEM_VERSIONING EQ_ (OFF | alterSetOnClause)
;
alterSetOnClause
: ON
(
LP_ (HISTORY_TABLE EQ_ tableName)?
(COMMA_? DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))?
(COMMA_? HISTORY_RETENTION_PERIOD EQ_ (INFINITE | (NUMBER_ (DAY | DAYS | WEEK | WEEKS | MONTH | MONTHS | YEAR | YEARS))))?
RP_
)?
;
alterTableTableIndex
: indexWithName (indexNonClusterClause | indexClusterClause)
;
indexWithName
: INDEX indexName
;
indexNonClusterClause
: NONCLUSTERED (hashWithBucket | (columnNameWithSortsWithParen alterTableIndexOnClause?))
;
alterTableIndexOnClause
: ON ignoredIdentifier_ | DEFAULT
;
indexClusterClause
: CLUSTERED COLUMNSTORE (WITH COMPRESSION_DELAY EQ_ NUMBER_ MINUTES?)? indexOnClause?
;
alterTableTableOption
: SET LP_ LOCK_ESCALATION EQ_ (AUTO | TABLE | DISABLE) RP_
| MEMORY_OPTIMIZED EQ_ ON
| DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA)
| SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE TABLE tableName fileTableClause_ createDefinitionClause_
;
createIndex
: CREATE 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_)?
;
|
modify columnConstraints rule
|
modify columnConstraints rule
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
|
697fbc09c18cd81716d8a8cabf1ccf371afbf251
|
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DCLStatement.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/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 (privileges_ ON onObjectClause_ | ignoredIdentifiers_)
;
revoke
: REVOKE (GRANT OPTION FOR)? (privileges_ ON onObjectClause_ | ignoredIdentifiers_)
;
privileges_
: privilegeType_ columnNames? (COMMA_ privilegeType_ columnNames?)*
;
privilegeType_
: ALL PRIVILEGES?
| SELECT
| INSERT
| UPDATE
| DELETE
| TRUNCATE
| REFERENCES
| TRIGGER
| CREATE
| CONNECT
| TEMPORARY
| TEMP
| EXECUTE
| USAGE
;
onObjectClause_
: SEQUENCE
| DATABASE
| DOMAIN
| FOREIGN
| FUNCTION
| PROCEDURE
| ROUTINE
| ALL
| LANGUAGE
| LARGE OBJECT
| SCHEMA
| TABLESPACE
| TYPE
| TABLE? tableName (COMMA_ tableName)*
;
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 (privilegeClause_ | roleClause_)
;
revoke
: REVOKE optionForClause_? (privilegeClause_ | roleClause_)
;
privilegeClause_
: privileges_ ON onObjectClause_
;
roleClause_
: ignoredIdentifiers_
;
optionForClause_
: (GRANT | ADMIN) OPTION FOR
;
privileges_
: privilegeType_ columnNames? (COMMA_ privilegeType_ columnNames?)*
;
privilegeType_
: SELECT
| INSERT
| UPDATE
| DELETE
| TRUNCATE
| REFERENCES
| TRIGGER
| CREATE
| CONNECT
| TEMPORARY
| TEMP
| EXECUTE
| USAGE
| ALL PRIVILEGES?
;
onObjectClause_
: TABLE? tableName (COMMA_ tableName)*
| DATABASE
| SCHEMA
| DOMAIN
| FOREIGN
| FUNCTION
| PROCEDURE
| ROUTINE
| ALL
| LANGUAGE
| LARGE OBJECT
| TABLESPACE
| TYPE
| SEQUENCE
;
createUser
: CREATE USER
;
dropUser
: DROP USER
;
alterUser
: ALTER USER
;
createRole
: CREATE ROLE
;
dropRole
: DROP ROLE
;
alterRole
: ALTER ROLE
;
|
modify dcl pg g4
|
modify dcl pg g4
|
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
|
1cfe330b56aa98640e1d50f2da6a412508511b06
|
omni-cx2x/src/cx2x/translator/language/Claw.g4
|
omni-cx2x/src/cx2x/translator/language/Claw.g4
|
/*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
/**
* ANTLR 4 Grammar file for the CLAW directive language.
*
* @author clementval
*/
grammar Claw;
@header
{
import java.util.List;
import java.util.ArrayList;
import cx2x.translator.common.Constant;
import cx2x.translator.misc.Utility;
import cx2x.translator.pragma.*;
}
/*----------------------------------------------------------------------------
* PARSER RULES
*----------------------------------------------------------------------------*/
/*
* Entry point for the analyzis of a CLAW directive.
* Return a CLawLanguage object with all needed information.
*/
analyze returns [ClawLanguage l]
@init{
$l = new ClawLanguage();
}
:
CLAW directive[$l]
;
ids_list[List<String> ids]
:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids]
;
directive[ClawLanguage l]
@init{
List<ClawMapping> m = new ArrayList<>();
List<String> o = new ArrayList<>();
}
:
// loop-fusion directive
LFUSION { $l.setDirective(ClawDirective.LOOP_FUSION); } group_option[$l] EOF
// loop-interchange directive
| LINTERCHANGE { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } indexes_option[$l] EOF
// loop-extract directive
| LEXTRACT range_option mapping_option_list[m] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF
{
$l.setDirective(ClawDirective.LOOP_EXTRACT);
$l.setRange($range_option.r);
$l.setMappings(m);
}
// remove directive
| REMOVE { $l.setDirective(ClawDirective.REMOVE); } EOF
| END REMOVE { $l.setDirective(ClawDirective.END_REMOVE); } EOF
// Kcache directive
| KCACHE offset_list[o]
{
$l.setDirective(ClawDirective.KCACHE);
$l.setOffsets(o);
}
;
group_option[ClawLanguage l]:
GROUP '(' group_name=IDENTIFIER ')'
{ $l.setGroupOption($group_name.text); }
| /* empty */
;
fusion_optional[ClawLanguage l]:
FUSION group_option[$l] { $l.setFusionOption(); }
| /* empty */
;
parallel_optional[ClawLanguage l]:
PARALLEL { $l.setParallelOption(); }
| /* empty */
;
acc_optional[ClawLanguage l]
@init{
List<String> tempAcc = new ArrayList<>();
}
:
ACC '(' identifiers[tempAcc] ')' { $l.setAccClauses(Utility.join(" ", tempAcc)); }
| /* empty */
;
identifiers[List<String> ids]:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids]
;
indexes_option[ClawLanguage l]
@init{
List<String> indexes = new ArrayList();
}
:
'(' ids_list[indexes] ')' { $l.setIndexes(indexes); }
| /* empty */
;
offset_list[List<String> offsets]:
offset[$offsets]
| offset[$offsets] offset_list[$offsets]
;
offset[List<String> offsets]:
n=NUMBER { $offsets.add($n.text); }
| '-' n=NUMBER { $offsets.add("-" + $n.text); }
| '+' n=NUMBER { $offsets.add($n.text); }
;
range_option returns [ClawRange r]
@init{
$r = new ClawRange();
}
:
RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ')'
{
$r.setInductionVar($induction.text);
$r.setLowerBound($lower.text);
$r.setUpperBound($upper.text);
$r.setStep(Constant.DEFAULT_STEP_VALUE);
}
| RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ',' step=IDENTIFIER ')'
{
$r.setInductionVar($induction.text);
$r.setLowerBound($lower.text);
$r.setUpperBound($upper.text);
$r.setStep($step.text);
}
;
mapping_var returns [ClawMappingVar mappingVar]:
lhs=IDENTIFIER '/' rhs=IDENTIFIER
{
$mappingVar = new ClawMappingVar($lhs.text, $rhs.text);
}
| i=IDENTIFIER
{
$mappingVar = new ClawMappingVar($i.text, $i.text);
}
;
mapping_var_list[List<ClawMappingVar> vars]:
mv=mapping_var { $vars.add($mv.mappingVar); }
| mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars]
;
mapping_option returns [ClawMapping mapping]
@init{
$mapping = new ClawMapping();
List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>();
List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>();
$mapping.setMappedVariables(listMapped);
$mapping.setMappingVariables(listMapping);
}
:
MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')'
;
mapping_option_list[List<ClawMapping> mappings]:
m=mapping_option { $mappings.add($m.mapping); }
| m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings]
;
/*----------------------------------------------------------------------------
* LEXER RULES
*----------------------------------------------------------------------------*/
// Start point
CLAW : 'claw';
// Directives
END : 'end';
KCACHE : 'kcache';
LFUSION : 'loop-fusion';
LINTERCHANGE : 'loop-interchange';
LEXTRACT : 'loop-extract';
REMOVE : 'remove';
// Options
ACC : 'acc';
FUSION : 'fusion';
GROUP : 'group';
MAP : 'map';
PARALLEL : 'parallel';
RANGE : 'range';
// Special elements
IDENTIFIER : [a-zA-Z_$0-9] [a-zA-Z_$0-9]* ;
NUMBER : (DIGIT)+ ;
fragment DIGIT : '0'..'9' ;
// Skip whitspaces
WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
|
/*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
/**
* ANTLR 4 Grammar file for the CLAW directive language.
*
* @author clementval
*/
grammar Claw;
@header
{
import java.util.List;
import java.util.ArrayList;
import cx2x.translator.common.Constant;
import cx2x.translator.misc.Utility;
import cx2x.translator.pragma.*;
}
/*----------------------------------------------------------------------------
* PARSER RULES
*----------------------------------------------------------------------------*/
/*
* Entry point for the analyzis of a CLAW directive.
* Return a CLawLanguage object with all needed information.
*/
analyze returns [ClawLanguage l]
@init{
$l = new ClawLanguage();
}
:
CLAW directive[$l]
;
ids_list[List<String> ids]
:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids]
;
directive[ClawLanguage l]
@init{
List<ClawMapping> m = new ArrayList<>();
List<String> o = new ArrayList<>();
}
:
// loop-fusion directive
LFUSION { $l.setDirective(ClawDirective.LOOP_FUSION); } group_option[$l] EOF
// loop-interchange directive
| LINTERCHANGE { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } indexes_option[$l] EOF
// loop-extract directive
| LEXTRACT range_option mapping_option_list[m] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF
{
$l.setDirective(ClawDirective.LOOP_EXTRACT);
$l.setRange($range_option.r);
$l.setMappings(m);
}
// remove directive
| REMOVE { $l.setDirective(ClawDirective.REMOVE); } EOF
| END REMOVE { $l.setDirective(ClawDirective.END_REMOVE); } EOF
// Kcache directive
| KCACHE offset_list_optional[o]
{
$l.setDirective(ClawDirective.KCACHE);
$l.setOffsets(o);
}
;
group_option[ClawLanguage l]:
GROUP '(' group_name=IDENTIFIER ')'
{ $l.setGroupOption($group_name.text); }
| /* empty */
;
fusion_optional[ClawLanguage l]:
FUSION group_option[$l] { $l.setFusionOption(); }
| /* empty */
;
parallel_optional[ClawLanguage l]:
PARALLEL { $l.setParallelOption(); }
| /* empty */
;
acc_optional[ClawLanguage l]
@init{
List<String> tempAcc = new ArrayList<>();
}
:
ACC '(' identifiers[tempAcc] ')' { $l.setAccClauses(Utility.join(" ", tempAcc)); }
| /* empty */
;
identifiers[List<String> ids]:
i=IDENTIFIER { $ids.add($i.text); }
| i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids]
;
indexes_option[ClawLanguage l]
@init{
List<String> indexes = new ArrayList();
}
:
'(' ids_list[indexes] ')' { $l.setIndexes(indexes); }
| /* empty */
;
offset_list_optional[List<String> offsets]:
offset_list[$offsets]
| /* empty */
;
offset_list[List<String> offsets]:
offset[$offsets]
| offset[$offsets] offset_list[$offsets]
;
offset[List<String> offsets]:
n=NUMBER { $offsets.add($n.text); }
| '-' n=NUMBER { $offsets.add("-" + $n.text); }
| '+' n=NUMBER { $offsets.add($n.text); }
;
range_option returns [ClawRange r]
@init{
$r = new ClawRange();
}
:
RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')'
{
$r.setInductionVar($induction.text);
$r.setLowerBound($lower.text);
$r.setUpperBound($upper.text);
$r.setStep(Constant.DEFAULT_STEP_VALUE);
}
| RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')'
{
$r.setInductionVar($induction.text);
$r.setLowerBound($lower.text);
$r.setUpperBound($upper.text);
$r.setStep($step.text);
}
;
range_id returns [String text]:
n=NUMBER { $text = $n.text; }
| i=IDENTIFIER { $text = $i.text; }
;
mapping_var returns [ClawMappingVar mappingVar]:
lhs=IDENTIFIER '/' rhs=IDENTIFIER
{
$mappingVar = new ClawMappingVar($lhs.text, $rhs.text);
}
| i=IDENTIFIER
{
$mappingVar = new ClawMappingVar($i.text, $i.text);
}
;
mapping_var_list[List<ClawMappingVar> vars]:
mv=mapping_var { $vars.add($mv.mappingVar); }
| mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars]
;
mapping_option returns [ClawMapping mapping]
@init{
$mapping = new ClawMapping();
List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>();
List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>();
$mapping.setMappedVariables(listMapped);
$mapping.setMappingVariables(listMapping);
}
:
MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')'
;
mapping_option_list[List<ClawMapping> mappings]:
m=mapping_option { $mappings.add($m.mapping); }
| m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings]
;
/*----------------------------------------------------------------------------
* LEXER RULES
*----------------------------------------------------------------------------*/
// Start point
CLAW : 'claw';
// Directives
END : 'end';
KCACHE : 'kcache';
LFUSION : 'loop-fusion';
LINTERCHANGE : 'loop-interchange';
LEXTRACT : 'loop-extract';
REMOVE : 'remove';
// Options
ACC : 'acc';
FUSION : 'fusion';
GROUP : 'group';
MAP : 'map';
PARALLEL : 'parallel';
RANGE : 'range';
// Special elements
IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9]* ;
NUMBER : (DIGIT)+ ;
fragment DIGIT : [0-9] ;
// Skip whitspaces
WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
|
Add offsets list to kcache directive + fix IDENTIFIER rule
|
Add offsets list to kcache directive + fix IDENTIFIER rule
|
ANTLR
|
bsd-2-clause
|
clementval/claw-compiler,clementval/claw-compiler
|
b41a24f314816bf641dd3f1621b53031a3959f6d
|
src/grammar/RustLexer.g4
|
src/grammar/RustLexer.g4
|
lexer grammar RustLexer;
tokens {
EQ, LT, LE, EQEQ, NE, GE, GT, ANDAND, OROR, NOT, TILDE, PLUT,
MINUS, STAR, SLASH, PERCENT, CARET, AND, OR, SHL, SHR, BINOP,
BINOPEQ, AT, DOT, DOTDOT, DOTDOTDOT, COMMA, SEMI, COLON,
MOD_SEP, RARROW, FAT_ARROW, LPAREN, RPAREN, LBRACKET, RBRACKET,
LBRACE, RBRACE, POUND, DOLLAR, UNDERSCORE, LIT_CHAR,
LIT_INTEGER, LIT_FLOAT, LIT_STR, LIT_STR_RAW, LIT_BINARY,
LIT_BINARY_RAW, IDENT, LIFETIME, WHITESPACE, DOC_COMMENT,
COMMENT
}
/* Note: due to antlr limitations, we can't represent XID_start and
* XID_continue properly. ASCII-only substitute. */
fragment XID_start : [_a-zA-Z] ;
fragment XID_continue : [_a-zA-Z0-9] ;
/* Expression-operator symbols */
EQ : '=' ;
LT : '<' ;
LE : '<=' ;
EQEQ : '==' ;
NE : '!=' ;
GE : '>=' ;
GT : '>' ;
ANDAND : '&&' ;
OROR : '||' ;
NOT : '!' ;
TILDE : '~' ;
PLUS : '+' ;
MINUS : '-' ;
STAR : '*' ;
SLASH : '/' ;
PERCENT : '%' ;
CARET : '^' ;
AND : '&' ;
OR : '|' ;
SHL : '<<' ;
SHR : '>>' ;
BINOP
: PLUS
| SLASH
| MINUS
| STAR
| PERCENT
| CARET
| AND
| OR
| SHL
| SHR
;
BINOPEQ : BINOP EQ ;
/* "Structural symbols" */
AT : '@' ;
DOT : '.' ;
DOTDOT : '..' ;
DOTDOTDOT : '...' ;
COMMA : ',' ;
SEMI : ';' ;
COLON : ':' ;
MOD_SEP : '::' ;
RARROW : '->' ;
FAT_ARROW : '=>' ;
LPAREN : '(' ;
RPAREN : ')' ;
LBRACKET : '[' ;
RBRACKET : ']' ;
LBRACE : '{' ;
RBRACE : '}' ;
POUND : '#';
DOLLAR : '$' ;
UNDERSCORE : '_' ;
// Literals
fragment HEXIT
: [0-9a-fA-F]
;
fragment CHAR_ESCAPE
: [nrt\\'"0]
| [xX] HEXIT HEXIT
| 'u' HEXIT HEXIT HEXIT HEXIT
| 'U' HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT
;
fragment SUFFIX
: IDENT
;
LIT_CHAR
: '\'' ( '\\' CHAR_ESCAPE | ~[\\'\n\t\r] ) '\'' SUFFIX?
;
LIT_BYTE
: 'b\'' ( '\\' ( [xX] HEXIT HEXIT | [nrt\\'"0] ) | ~[\\'\n\t\r] ) '\'' SUFFIX?
;
LIT_INTEGER
: [0-9][0-9_]* SUFFIX?
| '0b' [01][01_]* SUFFIX?
| '0o' [0-7][0-7_]* SUFFIX?
| '0x' [0-9a-fA-F][0-9a-fA-F_]* SUFFIX?
;
LIT_FLOAT
: [0-9][0-9_]* ( '.' {_input.LA(1) != '.'}?
| ('.' [0-9][0-9_]*)? ([eE] [-+]? [0-9][0-9_]*)? SUFFIX?)
;
LIT_STR
: '"' ('\\\n' | '\\\r\n' | '\\' CHAR_ESCAPE | .)*? '"' SUFFIX?
;
LIT_BINARY : 'b' LIT_STR SUFFIX?;
LIT_BINARY_RAW : 'rb' LIT_STR_RAW SUFFIX?;
/* this is a bit messy */
fragment LIT_STR_RAW_INNER
: '"' .*? '"'
| LIT_STR_RAW_INNER2
;
fragment LIT_STR_RAW_INNER2
: POUND LIT_STR_RAW_INNER POUND
;
LIT_STR_RAW
: 'r' LIT_STR_RAW_INNER SUFFIX?
;
IDENT : XID_start XID_continue* ;
LIFETIME : '\'' IDENT ;
WHITESPACE : [ \r\n\t]+ ;
UNDOC_COMMENT : '////' ~[\r\n]* -> type(COMMENT) ;
YESDOC_COMMENT : '///' ~[\r\n]* -> type(DOC_COMMENT) ;
OUTER_DOC_COMMENT : '//!' ~[\r\n]* -> type(DOC_COMMENT) ;
LINE_COMMENT : '//' ~[\r\n]* -> type(COMMENT) ;
DOC_BLOCK_COMMENT
: ('/**' ~[*] | '/*!') (DOC_BLOCK_COMMENT | .)*? '*/' -> type(DOC_COMMENT)
;
BLOCK_COMMENT : '/*' (BLOCK_COMMENT | .)*? '*/' -> type(COMMENT) ;
|
lexer grammar RustLexer;
tokens {
EQ, LT, LE, EQEQ, NE, GE, GT, ANDAND, OROR, NOT, TILDE, PLUT,
MINUS, STAR, SLASH, PERCENT, CARET, AND, OR, SHL, SHR, BINOP,
BINOPEQ, AT, DOT, DOTDOT, DOTDOTDOT, COMMA, SEMI, COLON,
MOD_SEP, RARROW, FAT_ARROW, LPAREN, RPAREN, LBRACKET, RBRACKET,
LBRACE, RBRACE, POUND, DOLLAR, UNDERSCORE, LIT_CHAR,
LIT_INTEGER, LIT_FLOAT, LIT_STR, LIT_STR_RAW, LIT_BINARY,
LIT_BINARY_RAW, IDENT, LIFETIME, WHITESPACE, DOC_COMMENT,
COMMENT
}
/* Note: due to antlr limitations, we can't represent XID_start and
* XID_continue properly. ASCII-only substitute. */
fragment XID_start : [_a-zA-Z] ;
fragment XID_continue : [_a-zA-Z0-9] ;
/* Expression-operator symbols */
EQ : '=' ;
LT : '<' ;
LE : '<=' ;
EQEQ : '==' ;
NE : '!=' ;
GE : '>=' ;
GT : '>' ;
ANDAND : '&&' ;
OROR : '||' ;
NOT : '!' ;
TILDE : '~' ;
PLUS : '+' ;
MINUS : '-' ;
STAR : '*' ;
SLASH : '/' ;
PERCENT : '%' ;
CARET : '^' ;
AND : '&' ;
OR : '|' ;
SHL : '<<' ;
SHR : '>>' ;
BINOP
: PLUS
| SLASH
| MINUS
| STAR
| PERCENT
| CARET
| AND
| OR
| SHL
| SHR
;
BINOPEQ : BINOP EQ ;
/* "Structural symbols" */
AT : '@' ;
DOT : '.' ;
DOTDOT : '..' ;
DOTDOTDOT : '...' ;
COMMA : ',' ;
SEMI : ';' ;
COLON : ':' ;
MOD_SEP : '::' ;
RARROW : '->' ;
FAT_ARROW : '=>' ;
LPAREN : '(' ;
RPAREN : ')' ;
LBRACKET : '[' ;
RBRACKET : ']' ;
LBRACE : '{' ;
RBRACE : '}' ;
POUND : '#';
DOLLAR : '$' ;
UNDERSCORE : '_' ;
// Literals
fragment HEXIT
: [0-9a-fA-F]
;
fragment CHAR_ESCAPE
: [nrt\\'"0]
| [xX] HEXIT HEXIT
| 'u' HEXIT HEXIT HEXIT HEXIT
| 'U' HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT
;
fragment SUFFIX
: IDENT
;
LIT_CHAR
: '\'' ( '\\' CHAR_ESCAPE | ~[\\'\n\t\r] ) '\'' SUFFIX?
;
LIT_BYTE
: 'b\'' ( '\\' ( [xX] HEXIT HEXIT | [nrt\\'"0] ) | ~[\\'\n\t\r] ) '\'' SUFFIX?
;
LIT_INTEGER
: [0-9][0-9_]* SUFFIX?
| '0b' [01][01_]* SUFFIX?
| '0o' [0-7][0-7_]* SUFFIX?
| '0x' [0-9a-fA-F][0-9a-fA-F_]* SUFFIX?
;
LIT_FLOAT
: [0-9][0-9_]* ('.' {
/* dot followed by another dot is a range, no float */
_input.LA(1) != '.' &&
/* dot followed by an identifier is an integer with a function call, no float */
_input.LA(1) != '_' &&
_input.LA(1) != 'a' &&
_input.LA(1) != 'b' &&
_input.LA(1) != 'c' &&
_input.LA(1) != 'd' &&
_input.LA(1) != 'e' &&
_input.LA(1) != 'f' &&
_input.LA(1) != 'g' &&
_input.LA(1) != 'h' &&
_input.LA(1) != 'i' &&
_input.LA(1) != 'j' &&
_input.LA(1) != 'k' &&
_input.LA(1) != 'l' &&
_input.LA(1) != 'm' &&
_input.LA(1) != 'n' &&
_input.LA(1) != 'o' &&
_input.LA(1) != 'p' &&
_input.LA(1) != 'q' &&
_input.LA(1) != 'r' &&
_input.LA(1) != 's' &&
_input.LA(1) != 't' &&
_input.LA(1) != 'u' &&
_input.LA(1) != 'v' &&
_input.LA(1) != 'w' &&
_input.LA(1) != 'x' &&
_input.LA(1) != 'y' &&
_input.LA(1) != 'z' &&
_input.LA(1) != 'A' &&
_input.LA(1) != 'B' &&
_input.LA(1) != 'C' &&
_input.LA(1) != 'D' &&
_input.LA(1) != 'E' &&
_input.LA(1) != 'F' &&
_input.LA(1) != 'G' &&
_input.LA(1) != 'H' &&
_input.LA(1) != 'I' &&
_input.LA(1) != 'J' &&
_input.LA(1) != 'K' &&
_input.LA(1) != 'L' &&
_input.LA(1) != 'M' &&
_input.LA(1) != 'N' &&
_input.LA(1) != 'O' &&
_input.LA(1) != 'P' &&
_input.LA(1) != 'Q' &&
_input.LA(1) != 'R' &&
_input.LA(1) != 'S' &&
_input.LA(1) != 'T' &&
_input.LA(1) != 'U' &&
_input.LA(1) != 'V' &&
_input.LA(1) != 'W' &&
_input.LA(1) != 'X' &&
_input.LA(1) != 'Y' &&
_input.LA(1) != 'Z'
}? | ('.' [0-9][0-9_]*)? ([eE] [-+]? [0-9][0-9_]*)? SUFFIX?)
;
LIT_STR
: '"' ('\\\n' | '\\\r\n' | '\\' CHAR_ESCAPE | .)*? '"' SUFFIX?
;
LIT_BINARY : 'b' LIT_STR SUFFIX?;
LIT_BINARY_RAW : 'rb' LIT_STR_RAW SUFFIX?;
/* this is a bit messy */
fragment LIT_STR_RAW_INNER
: '"' .*? '"'
| LIT_STR_RAW_INNER2
;
fragment LIT_STR_RAW_INNER2
: POUND LIT_STR_RAW_INNER POUND
;
LIT_STR_RAW
: 'r' LIT_STR_RAW_INNER SUFFIX?
;
IDENT : XID_start XID_continue* ;
LIFETIME : '\'' IDENT ;
WHITESPACE : [ \r\n\t]+ ;
UNDOC_COMMENT : '////' ~[\r\n]* -> type(COMMENT) ;
YESDOC_COMMENT : '///' ~[\r\n]* -> type(DOC_COMMENT) ;
OUTER_DOC_COMMENT : '//!' ~[\r\n]* -> type(DOC_COMMENT) ;
LINE_COMMENT : '//' ~[\r\n]* -> type(COMMENT) ;
DOC_BLOCK_COMMENT
: ('/**' ~[*] | '/*!') (DOC_BLOCK_COMMENT | .)*? '*/' -> type(DOC_COMMENT)
;
BLOCK_COMMENT : '/*' (BLOCK_COMMENT | .)*? '*/' -> type(COMMENT) ;
|
Handle function calls to integers in model lexer correctly
|
Handle function calls to integers in model lexer correctly
closes #15877
|
ANTLR
|
apache-2.0
|
l0kod/rust,AerialX/rust-rt-minimal,gifnksm/rust,jashank/rust,aepsil0n/rust,dinfuehr/rust,dinfuehr/rust,jroesch/rust,rprichard/rust,kimroen/rust,carols10cents/rust,zubron/rust,zubron/rust,AerialX/rust-rt-minimal,zubron/rust,kimroen/rust,KokaKiwi/rust,aneeshusa/rust,dwillmer/rust,nwin/rust,AerialX/rust,kwantam/rust,pshc/rust,zaeleus/rust,ktossell/rust,miniupnp/rust,mvdnes/rust,andars/rust,mvdnes/rust,graydon/rust,rprichard/rust,ktossell/rust,kwantam/rust,aidancully/rust,l0kod/rust,aidancully/rust,victorvde/rust,defuz/rust,XMPPwocky/rust,ejjeong/rust,TheNeikos/rust,mihneadb/rust,miniupnp/rust,dwillmer/rust,AerialX/rust-rt-minimal,mdinger/rust,andars/rust,kwantam/rust,ruud-v-a/rust,omasanori/rust,dwillmer/rust,andars/rust,AerialX/rust,philyoon/rust,rprichard/rust,mvdnes/rust,gifnksm/rust,zaeleus/rust,aidancully/rust,ebfull/rust,aidancully/rust,GBGamer/rust,hauleth/rust,graydon/rust,GBGamer/rust,krzysz00/rust,jashank/rust,rohitjoshi/rust,vhbit/rust,mihneadb/rust,gifnksm/rust,zachwick/rust,richo/rust,vhbit/rust,mihneadb/rust,ruud-v-a/rust,jroesch/rust,aepsil0n/rust,avdi/rust,seanrivera/rust,bombless/rust-docs-chinese,ebfull/rust,nwin/rust,reem/rust,nwin/rust,graydon/rust,omasanori/rust,avdi/rust,dwillmer/rust,dwillmer/rust,aepsil0n/rust,carols10cents/rust,TheNeikos/rust,rprichard/rust,ebfull/rust,rohitjoshi/rust,GBGamer/rust,zachwick/rust,l0kod/rust,miniupnp/rust,kwantam/rust,mdinger/rust,cllns/rust,nwin/rust,zachwick/rust,AerialX/rust,richo/rust,sae-bom/rust,zachwick/rust,nwin/rust,dwillmer/rust,KokaKiwi/rust,reem/rust,vhbit/rust,AerialX/rust,pshc/rust,victorvde/rust,zachwick/rust,miniupnp/rust,carols10cents/rust,aepsil0n/rust,cllns/rust,bombless/rust,AerialX/rust-rt-minimal,mahkoh/rust,robertg/rust,mihneadb/rust,robertg/rust,mdinger/rust,GBGamer/rust,aepsil0n/rust,dwillmer/rust,defuz/rust,mvdnes/rust,pshc/rust,reem/rust,robertg/rust,carols10cents/rust,untitaker/rust,gifnksm/rust,seanrivera/rust,aidancully/rust,TheNeikos/rust,ebfull/rust,kwantam/rust,jashank/rust,ruud-v-a/rust,carols10cents/rust,nwin/rust,graydon/rust,hauleth/rust,ejjeong/rust,pelmers/rust,ktossell/rust,krzysz00/rust,pshc/rust,hauleth/rust,untitaker/rust,jroesch/rust,mahkoh/rust,kimroen/rust,GBGamer/rust,graydon/rust,vhbit/rust,omasanori/rust,ruud-v-a/rust,mahkoh/rust,TheNeikos/rust,richo/rust,robertg/rust,defuz/rust,omasanori/rust,vhbit/rust,dinfuehr/rust,philyoon/rust,aepsil0n/rust,jroesch/rust,jashank/rust,XMPPwocky/rust,l0kod/rust,sae-bom/rust,sae-bom/rust,miniupnp/rust,mahkoh/rust,pshc/rust,miniupnp/rust,ktossell/rust,krzysz00/rust,carols10cents/rust,sae-bom/rust,dinfuehr/rust,zaeleus/rust,KokaKiwi/rust,pelmers/rust,hauleth/rust,jashank/rust,nwin/rust,philyoon/rust,defuz/rust,dinfuehr/rust,sae-bom/rust,victorvde/rust,graydon/rust,omasanori/rust,philyoon/rust,vhbit/rust,ruud-v-a/rust,zubron/rust,mihneadb/rust,krzysz00/rust,krzysz00/rust,jashank/rust,KokaKiwi/rust,hauleth/rust,zaeleus/rust,richo/rust,omasanori/rust,victorvde/rust,ejjeong/rust,avdi/rust,miniupnp/rust,GBGamer/rust,TheNeikos/rust,rohitjoshi/rust,bombless/rust,ebfull/rust,aneeshusa/rust,GBGamer/rust,zaeleus/rust,pelmers/rust,defuz/rust,nwin/rust,kimroen/rust,l0kod/rust,l0kod/rust,kimroen/rust,rprichard/rust,zachwick/rust,jroesch/rust,victorvde/rust,l0kod/rust,kimroen/rust,robertg/rust,victorvde/rust,philyoon/rust,vhbit/rust,aidancully/rust,richo/rust,reem/rust,mahkoh/rust,pshc/rust,jroesch/rust,mdinger/rust,untitaker/rust,krzysz00/rust,gifnksm/rust,cllns/rust,aneeshusa/rust,XMPPwocky/rust,robertg/rust,ktossell/rust,mdinger/rust,bombless/rust,gifnksm/rust,avdi/rust,defuz/rust,zubron/rust,mvdnes/rust,hauleth/rust,ejjeong/rust,bombless/rust,zubron/rust,untitaker/rust,philyoon/rust,zaeleus/rust,rprichard/rust,reem/rust,mahkoh/rust,mvdnes/rust,seanrivera/rust,ktossell/rust,AerialX/rust-rt-minimal,rohitjoshi/rust,KokaKiwi/rust,richo/rust,GBGamer/rust,mihneadb/rust,rohitjoshi/rust,andars/rust,ktossell/rust,jroesch/rust,zubron/rust,cllns/rust,jashank/rust,aneeshusa/rust,seanrivera/rust,ejjeong/rust,AerialX/rust-rt-minimal,sae-bom/rust,vhbit/rust,pelmers/rust,kwantam/rust,bombless/rust,mdinger/rust,l0kod/rust,TheNeikos/rust,untitaker/rust,pelmers/rust,AerialX/rust,KokaKiwi/rust,AerialX/rust,pshc/rust,seanrivera/rust,XMPPwocky/rust,ejjeong/rust,jashank/rust,zubron/rust,reem/rust,ebfull/rust,jroesch/rust,XMPPwocky/rust,avdi/rust,aneeshusa/rust,cllns/rust,dinfuehr/rust,kimroen/rust,rohitjoshi/rust,XMPPwocky/rust,pelmers/rust,cllns/rust,dwillmer/rust,andars/rust,avdi/rust,aneeshusa/rust,pshc/rust,seanrivera/rust,andars/rust,ruud-v-a/rust,untitaker/rust,bombless/rust,miniupnp/rust
|
dd68eaa1600f622d92e871891a2ee343f9c08571
|
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: 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);
//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 EOL token
|
remove EOL token
|
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
|
d5a33f12b68076673784f058fe6135efedbbe460
|
vrj.g4
|
vrj.g4
|
grammar vrj;
init: (
typeDefinition |
nativeDefinition |
globalDefinition |
functionDefinition |
libraryDefinition |
structDefinition |
NL
)* EOF;
visibility: 'private' | 'public';
name: ID ('.' ID)*;
type: ID | '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 |
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')? name ('=' expression)? NL;
globalDefinition:
'globals' NL
((('constant')? variableStatement) | NL)*
'endglobals' NL;
loopStatement:
'loop' NL
statements
'endloop' NL;
elseIfStatement: 'elseif' expression 'then' NL statements;
elseStatement: 'else' NL statements;
ifStatement:
'if' expression 'then' NL
statements
elseIfStatement*
elseStatement?
'endif' NL;
statement:
'local' variableStatement #LocalVariable |
'set' variableExpression '=' expression NL #SetVariable |
'exitwhen' expression NL #Exitwhen |
'call' functionExpression NL #FunctionCall |
'return' expression? NL #Return |
ifStatement #IgnoreIf |
loopStatement #IgnoreLoop;
statements: (statement | NL)*;
functionDefinition:
visibility? 'function' functionSignature
statements
'endfunction' NL;
libraryRequirementExpression: name (',' name)*;
libraryDefinition:
'library' name ('initializer' initializer=name)? ('requires' libraryRequirementExpression)? NL
(globalDefinition | functionDefinition | structDefinition | NL)*
'endlibrary' NL;
propertyStatement:
visibility? variableStatement;
methodDefinition:
visibility? 'method' functionSignature
statements
'endmethod' NL;
structDefinition:
visibility? 'struct' name ('extends' 'array')? NL
(propertyStatement | methodDefinition | NL)*
'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);
|
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);
|
Extend grammar to support static
|
Extend grammar to support static
|
ANTLR
|
mit
|
Ruk33/vrJASS2
|
fade6db8c9582ce168ee5abda299c09bd2f9a338
|
src/net/hillsdon/reviki/wiki/renderer/creole/parser/CreoleTokens.g4
|
src/net/hillsdon/reviki/wiki/renderer/creole/parser/CreoleTokens.g4
|
/* Todo:
* - Comments justifying and explaining every rule.
*/
lexer grammar CreoleTokens;
@members {
public boolean inHeader = false;
public boolean start = false;
public boolean bold = false;
public boolean italic = false;
public boolean strike = false;
public int olistLevel = 0;
public int ulistLevel = 0;
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) {
_input.seek(_input.index() - 1);
}
setText(prefix);
inHeader = true;
} else {
setType(Any);
}
}
public void setStart() {
String next1 = _input.getText(new Interval(_input.index(), _input.index()));
String next2 = _input.getText(new Interval(_input.index() + 1, _input.index() + 1));
start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#"));
}
public void doUlist(int level) {
ulistLevel = level;
_input.seek(_input.index() - 1);
setStart();
}
public void doOlist(int level) {
olistLevel = level;
_input.seek(_input.index() - 1);
setStart();
}
public void resetFormatting() {
bold = false;
italic = false;
strike = false;
}
public void doUrl() {
String url = getText();
String last = url.substring(url.length()-1);
String next = _input.getText(new Interval(_input.index(), _input.index()));
if((last + next).equals("//")) {
_input.seek(_input.index() - 1);
setText(url.substring(0, url.length() - 1));
}
}
}
/* ***** Headings ***** */
HSt : LINE '='+ ~'=' WS? {doHdr();} ;
HEnd : ' '* '='* ('\r'? '\n' {_input.seek(_input.index()-1);} | EOF) {inHeader}? {inHeader = false; resetFormatting();} ;
/* ***** Lists ***** */
U1 : START '*' ~'*' {doUlist(1); resetFormatting();} ;
U2 : START '**' ~'*' {ulistLevel >= 1}? {doUlist(2); resetFormatting();} ;
U3 : START '***' ~'*' {ulistLevel >= 2}? {doUlist(3); resetFormatting();} ;
U4 : START '****' ~'*' {ulistLevel >= 3}? {doUlist(4); resetFormatting();} ;
U5 : START '*****' ~'*' {ulistLevel >= 4}? {doUlist(5); resetFormatting();} ;
O1 : START '#' ~'#' {doOlist(1); resetFormatting();} ;
O2 : START '##' ~'#' {olistLevel >= 1}? {doOlist(2); resetFormatting();} ;
O3 : START '###' ~'#' {olistLevel >= 2}? {doOlist(3); resetFormatting();} ;
O4 : START '####' ~'#' {olistLevel >= 3}? {doOlist(4); resetFormatting();} ;
O5 : START '#####' ~'#' {olistLevel >= 4}? {doOlist(5); resetFormatting();} ;
/* ***** Horizontal Rules ***** */
Rule : LINE '---' '-'+? {resetFormatting();} ;
/* ***** Tables ***** */
CellSep : '|' {resetFormatting();} ;
TdStart : '|' {resetFormatting();} ;
ThStart : '|=' {resetFormatting();} ;
/* ***** Inline Formatting ***** */
BSt : '**' {!bold}? {bold=true;} ;
ISt : '//' {!italic}? {italic=true;} ;
SSt : '--' {!strike}? {strike=true;} ;
BEnd : '**' {bold}? {bold=false;} ;
IEnd : '//' {italic}? {italic=false;} ;
SEnd : '--' {strike}? {strike=false;} ;
NoWiki : '{{{' -> mode(PREFORMATTED_INLINE) ;
/* ***** Links ***** */
LiSt : '[[' -> mode(LINK) ;
ImSt : '{{' -> mode(LINK) ;
/* ***** Breaks ***** */
InlineBrk : '\\\\' ;
ParBreak : LineBreak LineBreak+ {resetFormatting();} ;
LineBreak : '\r'? '\n'+? ;
/* ***** Links ***** */
RawUrl : ('http' | 'ftp') '://' (~(' '|'\t'|'\r'|'\n'|'/')+ '/'?)+ {doUrl();};
WikiWords : (ALNUM+ ':')? (UPPER ((ALNUM|'.')* ALNUM)*) (UPPER ((ALNUM|'.')* ALNUM)*)+;
/* ***** Miscellaneous ***** */
Any : . ;
WS : (' '|'\t'|'\r'|'\n')+ -> skip ;
fragment START : {start}? | LINE ;
fragment LINE : ({getCharPositionInLine()==0}? WS? | LineBreak WS?);
fragment ALNUM : (ALPHA | DIGIT) ;
fragment ALPHA : (UPPER | LOWER) ;
fragment UPPER : ('A'..'Z') ;
fragment LOWER : ('a'..'z') ;
fragment DIGIT : ('0'..'9') ;
/* ***** Contextual stuff ***** */
mode LINK;
LiEnd : ']]' -> mode(DEFAULT_MODE) ;
ImEnd : '}}' -> mode(DEFAULT_MODE) ;
Sep : '|' ;
InLink : ~(']'|'}'|'|')+ ;
mode PREFORMATTED_INLINE;
AnyInlineText : ~('\r'|'\n') -> more;
AnyBlockText : AnyInlineText* LineBreak -> mode(PREFORMATTED_BLOCK), more ;
EndNoWikiInline : '}}}' (~'}' {_input.seek(_input.index()-1);} | EOF) -> mode(DEFAULT_MODE) ;
mode PREFORMATTED_BLOCK;
AnyText : . -> more ;
EndNoWikiBlock : LINE '}}}' -> mode(DEFAULT_MODE) ;
|
/* Todo:
* - Comments justifying and explaining every rule.
*/
lexer grammar CreoleTokens;
@members {
public boolean inHeader = false;
public boolean start = false;
public boolean bold = false;
public boolean italic = false;
public boolean strike = false;
public int olistLevel = 0;
public int ulistLevel = 0;
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) {
_input.seek(_input.index() - 1);
}
setText(prefix);
inHeader = true;
} else {
setType(Any);
}
}
public void setStart() {
String next1 = _input.getText(new Interval(_input.index(), _input.index()));
String next2 = _input.getText(new Interval(_input.index() + 1, _input.index() + 1));
start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#"));
}
public void doUlist(int level) {
ulistLevel = level;
_input.seek(_input.index() - 1);
setStart();
}
public void doOlist(int level) {
olistLevel = level;
_input.seek(_input.index() - 1);
setStart();
}
public void resetFormatting() {
bold = false;
italic = false;
strike = false;
}
public void doUrl() {
String url = getText();
String last = url.substring(url.length()-1);
String next = _input.getText(new Interval(_input.index(), _input.index()));
if((last + next).equals("//")) {
_input.seek(_input.index() - 1);
setText(url.substring(0, url.length() - 1));
}
}
}
/* ***** Headings ***** */
HSt : LINE '='+ ~'=' WS? {doHdr();} ;
HEnd : ' '* '='* ('\r'? '\n' {_input.seek(_input.index()-1);} | EOF) {inHeader}? {inHeader = false; resetFormatting();} ;
/* ***** Lists ***** */
U1 : START '*' ~'*' {doUlist(1); resetFormatting();} ;
U2 : START '**' ~'*' {ulistLevel >= 1}? {doUlist(2); resetFormatting();} ;
U3 : START '***' ~'*' {ulistLevel >= 2}? {doUlist(3); resetFormatting();} ;
U4 : START '****' ~'*' {ulistLevel >= 3}? {doUlist(4); resetFormatting();} ;
U5 : START '*****' ~'*' {ulistLevel >= 4}? {doUlist(5); resetFormatting();} ;
O1 : START '#' ~'#' {doOlist(1); resetFormatting();} ;
O2 : START '##' ~'#' {olistLevel >= 1}? {doOlist(2); resetFormatting();} ;
O3 : START '###' ~'#' {olistLevel >= 2}? {doOlist(3); resetFormatting();} ;
O4 : START '####' ~'#' {olistLevel >= 3}? {doOlist(4); resetFormatting();} ;
O5 : START '#####' ~'#' {olistLevel >= 4}? {doOlist(5); resetFormatting();} ;
/* ***** Horizontal Rules ***** */
Rule : LINE '---' '-'+? {resetFormatting();} ;
/* ***** Tables ***** */
CellSep : '|' {resetFormatting();} ;
TdStart : '|' {resetFormatting();} ;
ThStart : '|=' {resetFormatting();} ;
/* ***** Inline Formatting ***** */
BSt : '**' {!bold}? {bold=true;} ;
ISt : '//' {!italic}? {italic=true;} ;
SSt : '--' {!strike}? {strike=true;} ;
BEnd : '**' {bold}? {bold=false;} ;
IEnd : '//' {italic}? {italic=false;} ;
SEnd : '--' {strike}? {strike=false;} ;
NoWiki : '{{{' -> mode(PREFORMATTED_INLINE) ;
/* ***** Links ***** */
LiSt : '[[' -> mode(LINK) ;
ImSt : '{{' -> mode(LINK) ;
/* ***** Breaks ***** */
InlineBrk : '\\\\' ;
ParBreak : LineBreak LineBreak+ {resetFormatting();} ;
LineBreak : '\r'? '\n'+? ;
/* ***** Links ***** */
RawUrl : ('http' | 'ftp') '://' (~(' '|'\t'|'\r'|'\n'|'/')+ '/'?)+ {doUrl();};
WikiWords : (ALNUM+ ':')? (UPPER ((ALNUM|'.')* ALNUM)*) (UPPER ((ALNUM|'.')* ALNUM)*)+;
/* ***** Miscellaneous ***** */
Any : . ;
WS : (' '|'\t'|'\r'|'\n')+ -> skip ;
fragment START : {start}? | LINE ;
fragment LINE : ({getCharPositionInLine()==0}? WS? | LineBreak WS?);
fragment ALNUM : (ALPHA | DIGIT) ;
fragment ALPHA : (UPPER | LOWER) ;
fragment UPPER : ('A'..'Z') ;
fragment LOWER : ('a'..'z') ;
fragment DIGIT : ('0'..'9') ;
/* ***** Contextual stuff ***** */
mode LINK;
LiEnd : ']]' -> mode(DEFAULT_MODE) ;
ImEnd : '}}' -> mode(DEFAULT_MODE) ;
Sep : '|' ;
InLink : ~(']'|'}'|'|')+ ;
mode PREFORMATTED_INLINE;
AnyInlineText : ~('\r'|'\n') -> more;
OopsItsABlock : ('\r'|'\n') -> mode(PREFORMATTED_BLOCK), more ;
EndNoWikiInline : '}}}' (~'}' {_input.seek(_input.index()-1);} | EOF) -> mode(DEFAULT_MODE) ;
mode PREFORMATTED_BLOCK;
AnyText : . -> more ;
EndNoWikiBlock : LINE '}}}' -> mode(DEFAULT_MODE) ;
|
Fix inline nowiki not being correctly tokenised when it's followed by a linebreak
|
Fix inline nowiki not being correctly tokenised when it's followed by a linebreak
|
ANTLR
|
apache-2.0
|
CoreFiling/reviki,CoreFiling/reviki,strr/reviki,ashirley/reviki,strr/reviki,ashirley/reviki,CoreFiling/reviki,CoreFiling/reviki,strr/reviki,strr/reviki,ashirley/reviki,ashirley/reviki,ashirley/reviki,CoreFiling/reviki,strr/reviki
|
e664f90f56d8d1cd4c82c14bd525b268c2d4ba04
|
src/main/antlr/com/github/oreissig/footran1/parser/Footran.g4
|
src/main/antlr/com/github/oreissig/footran1/parser/Footran.g4
|
/*
* A grammar for the original version of FORTRAN as described
* by IBM's programmer's reference manual from 1956:
* http://www.fortran.com/FortranForTheIBM704.pdf
*
* This grammar tries to keep its wording close to the original
* language reference, e.g. an array is called subscripted
* variable.
*/
grammar Footran;
@header {
package com.github.oreissig.footran1.parser;
}
@lexer::members {
/**
* FORTRAN-I encapsulates type information in its identifiers, but
* unfortunately there are cases that require context to be certain:
* IDs with 4 or more characters ending with 'F' may either denote a
* non-subscripted variable or a function.
*
* @param text the ID to analyze
* @return true if we know for sure, that text is a variable ID
*/
private boolean isVariable(String text) {
return text.length() < 4 || !text.endsWith("F");
}
}
// parser rules
program : card*;
card : STMTNUM? statement NEWCARD?;
statement : arithmeticFormula
// TODO more to come
;
arithmeticFormula : (VAR_ID | FUNC_CANDIDATE | subscript) '=' expression;
subscript : variable=VAR_ID '(' subscriptExpression (',' subscriptExpression (',' subscriptExpression)?)? ')';
subscriptExpression : variable=VAR_ID | constant=ufixedConst | sum=subscriptSum;
subscriptSum : product=subscriptMult (sign summand=ufixedConst)?;
subscriptMult : (factor=ufixedConst '*')? index=VAR_ID;
expression : sign? unsigned=unsignedExpression;
unsignedExpression : '(' expression ')' | var=VAR_ID | functionCall | ufixedConst | ufloatConst;
functionCall : function=FUNC_CANDIDATE '(' expression (',' expression)* ')';
ufixedConst : NUMBER ;
fixedConst : sign? unsigned=ufixedConst ;
ufloatConst : integer=NUMBER? '.' (fraction=NUMBER | fractionE=FLOAT_FRAC exponent=fixedConst)? ;
floatConst : sign? unsigned=ufloatConst ;
sign : (PLUS|MINUS);
// lexer rules
// prefix area processing
COMMENT : {getCharPositionInLine() == 0}? 'C' ~('\n')* '\n'? -> skip ;
STMTNUM : {getCharPositionInLine() < 5}? [0-9]+ ;
CONTINUE : NEWCARD . . . . . ~[' '|'0'] -> skip ;
// body processing
fragment DIGIT : {getCharPositionInLine() > 5}? [0-9];
fragment LETTER : {getCharPositionInLine() > 5}? [A-Z];
fragment ALFNUM : {getCharPositionInLine() > 5}? [A-Z0-9];
NUMBER : DIGIT+ ;
// use a separate token to avoid recognizing the float exponential E as ID
FLOAT_FRAC : NUMBER 'E';
VAR_ID : LETTER ALFNUM* {isVariable(getText())}? ;
// function candidate refers to either a function or a non-subscripted variable
FUNC_CANDIDATE : LETTER ALFNUM+ {!isVariable(getText())}? ;
PLUS : '+';
MINUS : '-';
// return newlines to parser
NEWCARD : '\r'? '\n' ;
// skip spaces and tabs
WS : ' '+ -> skip ;
|
/*
* A grammar for the original version of FORTRAN as described
* by IBM's programmer's reference manual from 1956:
* http://www.fortran.com/FortranForTheIBM704.pdf
*
* This grammar tries to keep its wording close to the original
* language reference, e.g. an array is called subscripted
* variable.
*/
grammar Footran;
@header {
package com.github.oreissig.footran1.parser;
}
@lexer::members {
/**
* FORTRAN-I encapsulates type information in its identifiers, but
* unfortunately there are cases that require context to be certain:
* IDs with 4 or more characters ending with 'F' may either denote a
* non-subscripted variable or a function.
*
* @param text the ID to analyze
* @return true if we know for sure, that text is a variable ID
*/
private boolean isVariable(String text) {
return text.length() < 4 || !text.endsWith("F");
}
}
// parser rules
program : card*;
card : STMTNUM? statement NEWCARD?;
statement : arithmeticFormula
// TODO more to come
;
arithmeticFormula : (VAR_ID | FUNC_CANDIDATE | subscript) '=' expression;
subscript : variable=VAR_ID '(' subscriptExpression (',' subscriptExpression (',' subscriptExpression)?)? ')';
subscriptExpression : variable=VAR_ID | constant=ufixedConst | sum=subscriptSum;
subscriptSum : product=subscriptMult (sign summand=ufixedConst)?;
subscriptMult : (factor=ufixedConst '*')? index=VAR_ID;
expression : sign? unsigned=unsignedExpression;
unsignedExpression : '(' expression ')' | var=VAR_ID | functionCall | ufixedConst | ufloatConst;
functionCall : function=FUNC_CANDIDATE '(' expression (',' expression)* ')';
ufixedConst : NUMBER ;
fixedConst : sign? unsigned=ufixedConst ;
ufloatConst : integer=NUMBER? '.' (fraction=NUMBER | fractionE=FLOAT_FRAC exponent=fixedConst)? ;
floatConst : sign? unsigned=ufloatConst ;
sign : (PLUS|MINUS);
mulOp : (MUL|DIV);
// lexer rules
// prefix area processing
COMMENT : {getCharPositionInLine() == 0}? 'C' ~('\n')* '\n'? -> skip ;
STMTNUM : {getCharPositionInLine() < 5}? [0-9]+ ;
CONTINUE : NEWCARD . . . . . ~[' '|'0'] -> skip ;
// body processing
fragment DIGIT : {getCharPositionInLine() > 5}? [0-9];
fragment LETTER : {getCharPositionInLine() > 5}? [A-Z];
fragment ALFNUM : {getCharPositionInLine() > 5}? [A-Z0-9];
NUMBER : DIGIT+ ;
// use a separate token to avoid recognizing the float exponential E as ID
FLOAT_FRAC : NUMBER 'E';
VAR_ID : LETTER ALFNUM* {isVariable(getText())}? ;
// function candidate refers to either a function or a non-subscripted variable
FUNC_CANDIDATE : LETTER ALFNUM+ {!isVariable(getText())}? ;
PLUS : '+';
MINUS : '-';
MUL : '*';
DIV : '/';
POWER : '**';
// return newlines to parser
NEWCARD : '\r'? '\n' ;
// skip spaces and tabs
WS : ' '+ -> skip ;
|
prepare arithmetic expression parsing
|
prepare arithmetic expression parsing
|
ANTLR
|
isc
|
oreissig/FOOTRAN-I
|
c51a93531861c98e91e23afde447be5ba15fa65d
|
javascript/JavaScriptParser.g4
|
javascript/JavaScriptParser.g4
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 by Bart Kiers (original author) and Alexandre Vitorelli (contributor -> ported to CSharp)
* Copyright (c) 2017 by Ivan Kochurkin (Positive Technologies):
added ECMAScript 6 support, cleared and transformed to the universal grammar.
* Copyright (c) 2018 by Juan Alvarez (contributor -> ported to Go)
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
parser grammar JavaScriptParser;
options {
tokenVocab=JavaScriptLexer;
superClass=JavaScriptBaseParser;
}
program
: sourceElements? EOF
;
sourceElement
: Export? statement
;
statement
: block
| variableStatement
| emptyStatement
| classDeclaration
| expressionStatement
| ifStatement
| iterationStatement
| continueStatement
| breakStatement
| returnStatement
| withStatement
| labelledStatement
| switchStatement
| throwStatement
| tryStatement
| debuggerStatement
| functionDeclaration
;
block
: '{' statementList? '}'
;
statementList
: statement+
;
variableStatement
: varModifier variableDeclarationList eos
;
variableDeclarationList
: variableDeclaration (',' variableDeclaration)*
;
variableDeclaration
: (Identifier | arrayLiteral | objectLiteral) ('=' singleExpression)? // ECMAScript 6: Array & Object Matching
;
emptyStatement
: SemiColon
;
expressionStatement
: {this.notOpenBraceAndNotFunction()}? expressionSequence eos
;
ifStatement
: If '(' expressionSequence ')' statement (Else statement)?
;
iterationStatement
: Do statement While '(' expressionSequence ')' eos # DoStatement
| While '(' expressionSequence ')' statement # WhileStatement
| For '(' expressionSequence? ';' expressionSequence? ';' expressionSequence? ')' statement # ForStatement
| For '(' varModifier variableDeclarationList ';' expressionSequence? ';' expressionSequence? ')'
statement # ForVarStatement
| For '(' singleExpression (In | Identifier{this.p("of")}?) expressionSequence ')' statement # ForInStatement
| For '(' varModifier variableDeclaration (In | Identifier{this.p("of")}?) expressionSequence ')' statement # ForVarInStatement
;
varModifier // let, const - ECMAScript 6
: Var
| Let
| Const
;
continueStatement
: Continue ({this.notLineTerminator()}? Identifier)? eos
;
breakStatement
: Break ({this.notLineTerminator()}? Identifier)? eos
;
returnStatement
: Return ({this.notLineTerminator()}? expressionSequence)? eos
;
withStatement
: With '(' expressionSequence ')' statement
;
switchStatement
: Switch '(' expressionSequence ')' caseBlock
;
caseBlock
: '{' caseClauses? (defaultClause caseClauses?)? '}'
;
caseClauses
: caseClause+
;
caseClause
: Case expressionSequence ':' statementList?
;
defaultClause
: Default ':' statementList?
;
labelledStatement
: Identifier ':' statement
;
throwStatement
: Throw {this.notLineTerminator()}? expressionSequence eos
;
tryStatement
: Try block (catchProduction finallyProduction? | finallyProduction)
;
catchProduction
: Catch '(' Identifier ')' block
;
finallyProduction
: Finally block
;
debuggerStatement
: Debugger eos
;
functionDeclaration
: Function Identifier '(' formalParameterList? ')' '{' functionBody '}'
;
classDeclaration
: Class Identifier classTail
;
classTail
: (Extends singleExpression)? '{' classElement* '}'
;
classElement
: (Static | {n("static")}? Identifier)? methodDefinition
| emptyStatement
;
methodDefinition
: propertyName '(' formalParameterList? ')' '{' functionBody '}'
| getter '(' ')' '{' functionBody '}'
| setter '(' formalParameterList? ')' '{' functionBody '}'
| generatorMethod
;
generatorMethod
: '*'? Identifier '(' formalParameterList? ')' '{' functionBody '}'
;
formalParameterList
: formalParameterArg (',' formalParameterArg)* (',' lastFormalParameterArg)?
| lastFormalParameterArg
| arrayLiteral // ECMAScript 6: Parameter Context Matching
| objectLiteral // ECMAScript 6: Parameter Context Matching
;
formalParameterArg
: Identifier ('=' singleExpression)? // ECMAScript 6: Initialization
;
lastFormalParameterArg // ECMAScript 6: Rest Parameter
: Ellipsis Identifier
;
functionBody
: sourceElements?
;
sourceElements
: sourceElement+
;
arrayLiteral
: '[' ','* elementList? ','* ']'
;
elementList
: singleExpression (','+ singleExpression)* (','+ lastElement)?
| lastElement
;
lastElement // ECMAScript 6: Spread Operator
: Ellipsis Identifier
;
objectLiteral
: '{' (propertyAssignment (',' propertyAssignment)*)? ','? '}'
;
propertyAssignment
: propertyName (':' |'=') singleExpression # PropertyExpressionAssignment
| '[' singleExpression ']' ':' singleExpression # ComputedPropertyExpressionAssignment
| getter '(' ')' '{' functionBody '}' # PropertyGetter
| setter '(' Identifier ')' '{' functionBody '}' # PropertySetter
| generatorMethod # MethodProperty
| Identifier # PropertyShorthand
;
propertyName
: identifierName
| StringLiteral
| numericLiteral
;
arguments
: '('(
singleExpression (',' singleExpression)* (',' lastArgument)? |
lastArgument
)?')'
;
lastArgument // ECMAScript 6: Spread Operator
: Ellipsis Identifier
;
expressionSequence
: singleExpression (',' singleExpression)*
;
singleExpression
: Function Identifier? '(' formalParameterList? ')' '{' functionBody '}' # FunctionExpression
| Class Identifier? classTail # ClassExpression
| singleExpression '[' expressionSequence ']' # MemberIndexExpression
| singleExpression '.' identifierName # MemberDotExpression
| singleExpression arguments # ArgumentsExpression
| New singleExpression arguments? # NewExpression
| singleExpression {this.notLineTerminator()}? '++' # PostIncrementExpression
| singleExpression {this.notLineTerminator()}? '--' # PostDecreaseExpression
| Delete singleExpression # DeleteExpression
| Void singleExpression # VoidExpression
| Typeof singleExpression # TypeofExpression
| '++' singleExpression # PreIncrementExpression
| '--' singleExpression # PreDecreaseExpression
| '+' singleExpression # UnaryPlusExpression
| '-' singleExpression # UnaryMinusExpression
| '~' singleExpression # BitNotExpression
| '!' singleExpression # NotExpression
| singleExpression ('*' | '/' | '%') singleExpression # MultiplicativeExpression
| singleExpression ('+' | '-') singleExpression # AdditiveExpression
| singleExpression ('<<' | '>>' | '>>>') singleExpression # BitShiftExpression
| singleExpression ('<' | '>' | '<=' | '>=') singleExpression # RelationalExpression
| singleExpression Instanceof singleExpression # InstanceofExpression
| singleExpression In singleExpression # InExpression
| singleExpression ('==' | '!=' | '===' | '!==') singleExpression # EqualityExpression
| singleExpression '&' singleExpression # BitAndExpression
| singleExpression '^' singleExpression # BitXOrExpression
| singleExpression '|' singleExpression # BitOrExpression
| singleExpression '&&' singleExpression # LogicalAndExpression
| singleExpression '||' singleExpression # LogicalOrExpression
| singleExpression '?' singleExpression ':' singleExpression # TernaryExpression
| singleExpression '=' singleExpression # AssignmentExpression
| singleExpression assignmentOperator singleExpression # AssignmentOperatorExpression
| singleExpression TemplateStringLiteral # TemplateStringExpression // ECMAScript 6
| This # ThisExpression
| Identifier # IdentifierExpression
| Super # SuperExpression
| literal # LiteralExpression
| arrayLiteral # ArrayLiteralExpression
| objectLiteral # ObjectLiteralExpression
| '(' expressionSequence ')' # ParenthesizedExpression
| arrowFunctionParameters '=>' arrowFunctionBody # ArrowFunctionExpression // ECMAScript 6
;
arrowFunctionParameters
: Identifier
| '(' formalParameterList? ')'
;
arrowFunctionBody
: singleExpression
| '{' functionBody '}'
;
assignmentOperator
: '*='
| '/='
| '%='
| '+='
| '-='
| '<<='
| '>>='
| '>>>='
| '&='
| '^='
| '|='
;
literal
: NullLiteral
| BooleanLiteral
| StringLiteral
| TemplateStringLiteral
| RegularExpressionLiteral
| numericLiteral
;
numericLiteral
: DecimalLiteral
| HexIntegerLiteral
| OctalIntegerLiteral
| OctalIntegerLiteral2
| BinaryIntegerLiteral
;
identifierName
: Identifier
| reservedWord
;
reservedWord
: keyword
| NullLiteral
| BooleanLiteral
;
keyword
: Break
| Do
| Instanceof
| Typeof
| Case
| Else
| New
| Var
| Catch
| Finally
| Return
| Void
| Continue
| For
| Switch
| While
| Debugger
| Function
| This
| With
| Default
| If
| Throw
| Delete
| In
| Try
| Class
| Enum
| Extends
| Super
| Const
| Export
| Import
| Implements
| Let
| Private
| Public
| Interface
| Package
| Protected
| Static
| Yield
;
getter
: Identifier{this.p("get")}? propertyName
;
setter
: Identifier{this.p("set")}? propertyName
;
eos
: SemiColon
| EOF
| {this.lineTerminatorAhead()}?
| {this.closeBrace()}?
;
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 by Bart Kiers (original author) and Alexandre Vitorelli (contributor -> ported to CSharp)
* Copyright (c) 2017 by Ivan Kochurkin (Positive Technologies):
added ECMAScript 6 support, cleared and transformed to the universal grammar.
* Copyright (c) 2018 by Juan Alvarez (contributor -> ported to Go)
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
parser grammar JavaScriptParser;
options {
tokenVocab=JavaScriptLexer;
superClass=JavaScriptBaseParser;
}
program
: sourceElements? EOF
;
sourceElement
: Export? statement
;
statement
: block
| variableStatement
| emptyStatement
| classDeclaration
| expressionStatement
| ifStatement
| iterationStatement
| continueStatement
| breakStatement
| returnStatement
| withStatement
| labelledStatement
| switchStatement
| throwStatement
| tryStatement
| debuggerStatement
| functionDeclaration
;
block
: '{' statementList? '}'
;
statementList
: statement+
;
variableStatement
: varModifier variableDeclarationList eos
;
variableDeclarationList
: variableDeclaration (',' variableDeclaration)*
;
variableDeclaration
: (Identifier | arrayLiteral | objectLiteral) ('=' singleExpression)? // ECMAScript 6: Array & Object Matching
;
emptyStatement
: SemiColon
;
expressionStatement
: {this.notOpenBraceAndNotFunction()}? expressionSequence eos
;
ifStatement
: If '(' expressionSequence ')' statement (Else statement)?
;
iterationStatement
: Do statement While '(' expressionSequence ')' eos # DoStatement
| While '(' expressionSequence ')' statement # WhileStatement
| For '(' expressionSequence? ';' expressionSequence? ';' expressionSequence? ')' statement # ForStatement
| For '(' varModifier variableDeclarationList ';' expressionSequence? ';' expressionSequence? ')'
statement # ForVarStatement
| For '(' singleExpression (In | Identifier{this.p("of")}?) expressionSequence ')' statement # ForInStatement
| For '(' varModifier variableDeclaration (In | Identifier{this.p("of")}?) expressionSequence ')' statement # ForVarInStatement
;
varModifier // let, const - ECMAScript 6
: Var
| Let
| Const
;
continueStatement
: Continue ({this.notLineTerminator()}? Identifier)? eos
;
breakStatement
: Break ({this.notLineTerminator()}? Identifier)? eos
;
returnStatement
: Return ({this.notLineTerminator()}? expressionSequence)? eos
;
withStatement
: With '(' expressionSequence ')' statement
;
switchStatement
: Switch '(' expressionSequence ')' caseBlock
;
caseBlock
: '{' caseClauses? (defaultClause caseClauses?)? '}'
;
caseClauses
: caseClause+
;
caseClause
: Case expressionSequence ':' statementList?
;
defaultClause
: Default ':' statementList?
;
labelledStatement
: Identifier ':' statement
;
throwStatement
: Throw {this.notLineTerminator()}? expressionSequence eos
;
tryStatement
: Try block (catchProduction finallyProduction? | finallyProduction)
;
catchProduction
: Catch '(' Identifier ')' block
;
finallyProduction
: Finally block
;
debuggerStatement
: Debugger eos
;
functionDeclaration
: Function Identifier '(' formalParameterList? ')' '{' functionBody '}'
;
classDeclaration
: Class Identifier classTail
;
classTail
: (Extends singleExpression)? '{' classElement* '}'
;
classElement
: (Static | {this.n("static")}? Identifier)? methodDefinition
| emptyStatement
;
methodDefinition
: propertyName '(' formalParameterList? ')' '{' functionBody '}'
| getter '(' ')' '{' functionBody '}'
| setter '(' formalParameterList? ')' '{' functionBody '}'
| generatorMethod
;
generatorMethod
: '*'? Identifier '(' formalParameterList? ')' '{' functionBody '}'
;
formalParameterList
: formalParameterArg (',' formalParameterArg)* (',' lastFormalParameterArg)?
| lastFormalParameterArg
| arrayLiteral // ECMAScript 6: Parameter Context Matching
| objectLiteral // ECMAScript 6: Parameter Context Matching
;
formalParameterArg
: Identifier ('=' singleExpression)? // ECMAScript 6: Initialization
;
lastFormalParameterArg // ECMAScript 6: Rest Parameter
: Ellipsis Identifier
;
functionBody
: sourceElements?
;
sourceElements
: sourceElement+
;
arrayLiteral
: '[' ','* elementList? ','* ']'
;
elementList
: singleExpression (','+ singleExpression)* (','+ lastElement)?
| lastElement
;
lastElement // ECMAScript 6: Spread Operator
: Ellipsis Identifier
;
objectLiteral
: '{' (propertyAssignment (',' propertyAssignment)*)? ','? '}'
;
propertyAssignment
: propertyName (':' |'=') singleExpression # PropertyExpressionAssignment
| '[' singleExpression ']' ':' singleExpression # ComputedPropertyExpressionAssignment
| getter '(' ')' '{' functionBody '}' # PropertyGetter
| setter '(' Identifier ')' '{' functionBody '}' # PropertySetter
| generatorMethod # MethodProperty
| Identifier # PropertyShorthand
;
propertyName
: identifierName
| StringLiteral
| numericLiteral
;
arguments
: '('(
singleExpression (',' singleExpression)* (',' lastArgument)? |
lastArgument
)?')'
;
lastArgument // ECMAScript 6: Spread Operator
: Ellipsis Identifier
;
expressionSequence
: singleExpression (',' singleExpression)*
;
singleExpression
: Function Identifier? '(' formalParameterList? ')' '{' functionBody '}' # FunctionExpression
| Class Identifier? classTail # ClassExpression
| singleExpression '[' expressionSequence ']' # MemberIndexExpression
| singleExpression '.' identifierName # MemberDotExpression
| singleExpression arguments # ArgumentsExpression
| New singleExpression arguments? # NewExpression
| singleExpression {this.notLineTerminator()}? '++' # PostIncrementExpression
| singleExpression {this.notLineTerminator()}? '--' # PostDecreaseExpression
| Delete singleExpression # DeleteExpression
| Void singleExpression # VoidExpression
| Typeof singleExpression # TypeofExpression
| '++' singleExpression # PreIncrementExpression
| '--' singleExpression # PreDecreaseExpression
| '+' singleExpression # UnaryPlusExpression
| '-' singleExpression # UnaryMinusExpression
| '~' singleExpression # BitNotExpression
| '!' singleExpression # NotExpression
| singleExpression ('*' | '/' | '%') singleExpression # MultiplicativeExpression
| singleExpression ('+' | '-') singleExpression # AdditiveExpression
| singleExpression ('<<' | '>>' | '>>>') singleExpression # BitShiftExpression
| singleExpression ('<' | '>' | '<=' | '>=') singleExpression # RelationalExpression
| singleExpression Instanceof singleExpression # InstanceofExpression
| singleExpression In singleExpression # InExpression
| singleExpression ('==' | '!=' | '===' | '!==') singleExpression # EqualityExpression
| singleExpression '&' singleExpression # BitAndExpression
| singleExpression '^' singleExpression # BitXOrExpression
| singleExpression '|' singleExpression # BitOrExpression
| singleExpression '&&' singleExpression # LogicalAndExpression
| singleExpression '||' singleExpression # LogicalOrExpression
| singleExpression '?' singleExpression ':' singleExpression # TernaryExpression
| singleExpression '=' singleExpression # AssignmentExpression
| singleExpression assignmentOperator singleExpression # AssignmentOperatorExpression
| singleExpression TemplateStringLiteral # TemplateStringExpression // ECMAScript 6
| This # ThisExpression
| Identifier # IdentifierExpression
| Super # SuperExpression
| literal # LiteralExpression
| arrayLiteral # ArrayLiteralExpression
| objectLiteral # ObjectLiteralExpression
| '(' expressionSequence ')' # ParenthesizedExpression
| arrowFunctionParameters '=>' arrowFunctionBody # ArrowFunctionExpression // ECMAScript 6
;
arrowFunctionParameters
: Identifier
| '(' formalParameterList? ')'
;
arrowFunctionBody
: singleExpression
| '{' functionBody '}'
;
assignmentOperator
: '*='
| '/='
| '%='
| '+='
| '-='
| '<<='
| '>>='
| '>>>='
| '&='
| '^='
| '|='
;
literal
: NullLiteral
| BooleanLiteral
| StringLiteral
| TemplateStringLiteral
| RegularExpressionLiteral
| numericLiteral
;
numericLiteral
: DecimalLiteral
| HexIntegerLiteral
| OctalIntegerLiteral
| OctalIntegerLiteral2
| BinaryIntegerLiteral
;
identifierName
: Identifier
| reservedWord
;
reservedWord
: keyword
| NullLiteral
| BooleanLiteral
;
keyword
: Break
| Do
| Instanceof
| Typeof
| Case
| Else
| New
| Var
| Catch
| Finally
| Return
| Void
| Continue
| For
| Switch
| While
| Debugger
| Function
| This
| With
| Default
| If
| Throw
| Delete
| In
| Try
| Class
| Enum
| Extends
| Super
| Const
| Export
| Import
| Implements
| Let
| Private
| Public
| Interface
| Package
| Protected
| Static
| Yield
;
getter
: Identifier{this.p("get")}? propertyName
;
setter
: Identifier{this.p("set")}? propertyName
;
eos
: SemiColon
| EOF
| {this.lineTerminatorAhead()}?
| {this.closeBrace()}?
;
|
Fix issue with function "n" in go
|
Javascript: Fix issue with function "n" in go
|
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
|
b08bfd8654c9fc39a0ed1b5a4a4f2754cd30f705
|
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
|
70d984f0fbbcd1b77d341a357e11a55f5adedde1
|
src/main/antlr/Trinity.g4
|
src/main/antlr/Trinity.g4
|
grammar Trinity;
import LexerRules; // includes all rules from LexerRules.g4
prog: (functionDecl | stmt)* ;
// Declarations
constDecl: type ID '=' semiExpr;
functionDecl: type ID '(' formalParameters? ')' 'do' block 'end' ;
formalParameters: formalParameter (',' formalParameter)* ;
formalParameter: type ID ;
type: ('Boolean' | 'Scalar') # PrimitiveType
| 'Vector' '[' (NUMBER|ID) ']' # VectorType
| 'Matrix' '[' (NUMBER|ID) ',' (NUMBER|ID) ']' # MatrixType ;
// Statements
block: stmt* ('return' semiExpr)? ;
semiExpr: expr LINETERMINATOR;
stmt: constDecl # ConstDeclaration
| semiExpr # SingleExpression
| 'for' type ID 'in' expr 'do' block 'end' # ForLoop
| 'if' expr 'then' block
('elseif' expr 'then' block)*
('else' block)? 'end' # IfStatement
| 'do' block 'end' # BlockStatement
;
// Expressions
// TODO: no sub-matrix sub-vector indexing (range) for now (maybe we don't need it)
expr: ID '(' exprList? ')' # FunctionCall
| ID '[' expr ']' # SingleIndexing
| ID '[' expr ',' expr ']' # DoubleIndexing
| '-' expr # Negate
| '!' expr # Not
| expr '\'' # Transpose
| <assoc=right> expr op='^' expr # Exponent
| expr op=('*'|'/'|'%') expr # MultDivMod
| expr op=('+'|'-') expr # AddSub
| expr op=('<'|'>'|'<='|'>=') expr # Relation
| expr op=('=='|'!=') expr # Equality
| expr op='and' expr # And
| expr op='or' expr # Or
| ID # Identifier
| NUMBER # Number
| BOOL # Boolean
| matrix # MatrixLit
| vector # VectorLit // TODO: naming
| '(' expr ')' # Parens
;
exprList: expr (',' expr)* ;
vector: '[' (exprList | range) ']' ;
matrix: vector vector+ ; // [][]...[]
range: NUMBER '..' NUMBER ;
|
grammar Trinity;
import LexerRules; // includes all rules from LexerRules.g4
prog: (functionDecl | stmt)* ;
// Declarations
constDecl: type ID '=' semiExpr;
functionDecl: type ID '(' formalParameters? ')' 'do' block 'end' ;
formalParameters: formalParameter (',' formalParameter)* ;
formalParameter: type ID ;
type: ('Boolean' | 'Scalar') # PrimitiveType
| 'Vector' '[' (NUMBER|ID) ']' # VectorType
| 'Matrix' '[' (NUMBER|ID) ',' (NUMBER|ID) ']' # MatrixType ;
// Statements
block: stmt* ('return' semiExpr)? ;
semiExpr: expr LINETERMINATOR;
stmt: constDecl # ConstDeclaration
| semiExpr # SingleExpression
| 'for' type ID 'in' expr 'do' block 'end' # ForLoop
| 'if' expr 'then' block
('elseif' expr 'then' block)*
('else' block)? 'end' # IfStatement
| 'do' block 'end' # BlockStatement
;
// Expressions
expr: ID '(' exprList? ')' # FunctionCall
| ID '[' expr ']' # SingleIndexing
| ID '[' expr ',' expr ']' # DoubleIndexing
| '-' expr # Negate
| '!' expr # Not
| expr '\'' # Transpose
| <assoc=right> expr op='^' expr # Exponent
| expr op=('*'|'/'|'%') expr # MultDivMod
| expr op=('+'|'-') expr # AddSub
| expr op=('<'|'>'|'<='|'>=') expr # Relation
| expr op=('=='|'!=') expr # Equality
| expr op='and' expr # And
| expr op='or' expr # Or
| ID # Identifier
| NUMBER # Number
| BOOL # Boolean
| matrix # MatrixLit
| vector # VectorLit
| '(' expr ')' # Parens
;
exprList: expr (',' expr)* ;
vector: '[' (exprList | range) ']' ;
matrix: vector vector+ ;
range: NUMBER '..' NUMBER ;
|
remove comments
|
remove comments
|
ANTLR
|
mit
|
Medeah/Trinity,Medeah/Trinity
|
47bba02a5adf4e2159114a841dc11cde570be2fd
|
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 TEMPORARY? TABLE (IF NOT EXISTS)? tableName (LP_ createDefinitions_ RP_ | createLike_)
;
createLike_
: LIKE tableName | LP_ LIKE tableName RP_
;
createIndex
: CREATE (UNIQUE | FULLTEXT | SPATIAL)? INDEX indexName indexType_? ON tableName
;
alterTable
: ALTER TABLE tableName alterSpecifications_?
;
dropTable
: DROP TEMPORARY? TABLE (IF EXISTS)? tableName (COMMA_ tableName)*
;
dropIndex
: DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName
;
truncateTable
: TRUNCATE TABLE? tableName
;
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)
;
generatedDataType_
: commonDataTypeOption_
| (GENERATED ALWAYS)? AS expr
| (VIRTUAL | STORED)
;
commonDataTypeOption_
: primaryKey | UNIQUE KEY? | NOT? NULL | collateClause_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_
;
referenceDefinition_
: REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)*
;
referenceOption_
: RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT
;
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_
;
checkConstraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)?
;
alterSpecifications_
: alterSpecification_ (COMMA_ alterSpecification_)*
;
alterSpecification_
: tableOptions_
| addColumnSpecification
| addIndexSpecification
| addConstraintSpecification
| ADD checkConstraintDefinition_
| DROP CHECK ignoredIdentifier_
| ALTER CHECK ignoredIdentifier_ NOT? ENFORCED
| ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY)
| ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT)
| ALTER INDEX indexName (VISIBLE | INVISIBLE)
| changeColumnSpecification
| DEFAULT? characterSet_ collateClause_?
| CONVERT TO characterSet_ collateClause_?
| (DISABLE | ENABLE) KEYS
| (DISCARD | IMPORT_) TABLESPACE
| dropColumnSpecification
| dropIndexSpecification
| dropPrimaryKeySpecification
| DROP FOREIGN KEY ignoredIdentifier_
| FORCE
| LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE)
| modifyColumnSpecification
// TODO hongjun investigate ORDER BY col_name [, col_name] ...
| ORDER BY columnName (COMMA_ columnName)*
| renameColumnSpecification
| renameIndexSpecification
| renameTableSpecification_
| (WITHOUT | WITH) VALIDATION
| ADD PARTITION LP_ partitionDefinition_ RP_
| DROP PARTITION ignoredIdentifiers_
| DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| TRUNCATE PARTITION (ignoredIdentifiers_ | ALL)
| COALESCE PARTITION NUMBER_
| REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_
| EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)?
| ANALYZE PARTITION (ignoredIdentifiers_ | ALL)
| CHECK PARTITION (ignoredIdentifiers_ | ALL)
| OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL)
| REBUILD PARTITION (ignoredIdentifiers_ | ALL)
| REPAIR PARTITION (ignoredIdentifiers_ | ALL)
| REMOVE PARTITIONING
| UPGRADE PARTITIONING
;
tableOptions_
: tableOption_ (COMMA_? tableOption_)*
;
tableOption_
: AUTO_INCREMENT EQ_? NUMBER_
| AVG_ROW_LENGTH EQ_? NUMBER_
| DEFAULT? (characterSet_ | collateClause_)
| CHECKSUM EQ_? NUMBER_
| COMMENT EQ_? STRING_
| COMPRESSION EQ_? STRING_
| CONNECTION EQ_? STRING_
| (DATA | INDEX) DIRECTORY EQ_? STRING_
| DELAY_KEY_WRITE EQ_? NUMBER_
| ENCRYPTION EQ_? STRING_
| ENGINE EQ_? ignoredIdentifier_
| INSERT_METHOD EQ_? (NO | FIRST | LAST)
| KEY_BLOCK_SIZE EQ_? NUMBER_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| PACK_KEYS EQ_? (NUMBER_ | DEFAULT)
| PASSWORD EQ_? STRING_
| ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT)
| STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_)
| STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_)
| STATS_SAMPLE_PAGES EQ_? NUMBER_
| TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))?
| UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_
;
addColumnSpecification
: ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_)
;
firstOrAfterColumn
: FIRST | AFTER columnName
;
addIndexSpecification
: ADD indexDefinition_
;
addConstraintSpecification
: ADD constraintDefinition_
;
changeColumnSpecification
: CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn?
;
dropColumnSpecification
: DROP COLUMN? columnName
;
dropIndexSpecification
: DROP (INDEX | KEY) indexName
;
dropPrimaryKeySpecification
: DROP primaryKey
;
modifyColumnSpecification
: MODIFY COLUMN? columnDefinition firstOrAfterColumn?
;
// TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
// TODO hongjun: should support renameIndexSpecification on mysql
renameIndexSpecification
: RENAME (INDEX | KEY) indexName TO indexName
;
// TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table
renameTableSpecification_
: RENAME (TO | AS)? newTableName
;
newTableName
: identifier_
;
partitionDefinitions_
: LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_
;
partitionDefinition_
: PARTITION identifier_
(VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))?
partitionDefinitionOption_*
(LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)?
;
partitionLessThanValue_
: LP_ (expr | partitionValueList_) RP_ | MAXVALUE
;
partitionValueList_
: literals (COMMA_ literals)*
;
partitionDefinitionOption_
: STORAGE? ENGINE EQ_? identifier_
| COMMENT EQ_? STRING_
| DATA DIRECTORY EQ_? STRING_
| INDEX DIRECTORY EQ_? STRING_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| TABLESPACE EQ_? identifier_
;
subpartitionDefinition_
: SUBPARTITION identifier_ partitionDefinitionOption_*
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE temporaryClause_ TABLE existClause_ tableName (createDefinitionClause_ | createLikeClause_)
;
createIndex
: CREATE (UNIQUE | FULLTEXT | SPATIAL)? INDEX indexName indexType_? ON tableName
;
alterTable
: ALTER TABLE tableName alterSpecifications_?
;
dropTable
: DROP TEMPORARY? TABLE (IF EXISTS)? tableName (COMMA_ tableName)*
;
dropIndex
: DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName
;
truncateTable
: TRUNCATE TABLE? tableName
;
temporaryClause_
: TEMPORARY?
;
existClause_
: (IF NOT EXISTS)?
;
createDefinitionClause_
: LP_ createDefinitions_ RP_
;
createLikeClause_
: LP_? LIKE tableName RP_?
;
createDefinitions_
: createDefinition_ (COMMA_ createDefinition_)*
;
createDefinition_
: columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_
;
columnDefinition
: columnName dataType (inlineDataType_* | generatedDataType_*)
;
indexDefinition_
: (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
constraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_)
;
checkConstraintDefinition_
: (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)?
;
inlineDataType_
: commonDataTypeOption_
| AUTO_INCREMENT
| DEFAULT (literals | expr)
| COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT)
| STORAGE (DISK | MEMORY | DEFAULT)
;
generatedDataType_
: commonDataTypeOption_
| (GENERATED ALWAYS)? AS expr
| (VIRTUAL | STORED)
;
commonDataTypeOption_
: primaryKey | UNIQUE KEY? | NOT? NULL | collateClause_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_
;
referenceDefinition_
: REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)*
;
referenceOption_
: RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT
;
indexType_
: USING (BTREE | HASH)
;
keyParts_
: LP_ keyPart_ (COMMA_ keyPart_)* RP_
;
keyPart_
: (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)?
;
indexOption_
: KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE
;
primaryKeyOption_
: primaryKey indexType_? columnNames indexOption_*
;
primaryKey
: PRIMARY? KEY
;
uniqueOption_
: UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_*
;
foreignKeyOption_
: FOREIGN KEY indexName? columnNames referenceDefinition_
;
alterSpecifications_
: alterSpecification_ (COMMA_ alterSpecification_)*
;
alterSpecification_
: tableOptions_
| addColumnSpecification
| addIndexSpecification
| addConstraintSpecification
| ADD checkConstraintDefinition_
| DROP CHECK ignoredIdentifier_
| ALTER CHECK ignoredIdentifier_ NOT? ENFORCED
| ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY)
| ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT)
| ALTER INDEX indexName (VISIBLE | INVISIBLE)
| changeColumnSpecification
| DEFAULT? characterSet_ collateClause_?
| CONVERT TO characterSet_ collateClause_?
| (DISABLE | ENABLE) KEYS
| (DISCARD | IMPORT_) TABLESPACE
| dropColumnSpecification
| dropIndexSpecification
| dropPrimaryKeySpecification
| DROP FOREIGN KEY ignoredIdentifier_
| FORCE
| LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE)
| modifyColumnSpecification
// TODO hongjun investigate ORDER BY col_name [, col_name] ...
| ORDER BY columnName (COMMA_ columnName)*
| renameColumnSpecification
| renameIndexSpecification
| renameTableSpecification_
| (WITHOUT | WITH) VALIDATION
| ADD PARTITION LP_ partitionDefinition_ RP_
| DROP PARTITION ignoredIdentifiers_
| DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE
| TRUNCATE PARTITION (ignoredIdentifiers_ | ALL)
| COALESCE PARTITION NUMBER_
| REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_
| EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)?
| ANALYZE PARTITION (ignoredIdentifiers_ | ALL)
| CHECK PARTITION (ignoredIdentifiers_ | ALL)
| OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL)
| REBUILD PARTITION (ignoredIdentifiers_ | ALL)
| REPAIR PARTITION (ignoredIdentifiers_ | ALL)
| REMOVE PARTITIONING
| UPGRADE PARTITIONING
;
tableOptions_
: tableOption_ (COMMA_? tableOption_)*
;
tableOption_
: AUTO_INCREMENT EQ_? NUMBER_
| AVG_ROW_LENGTH EQ_? NUMBER_
| DEFAULT? (characterSet_ | collateClause_)
| CHECKSUM EQ_? NUMBER_
| COMMENT EQ_? STRING_
| COMPRESSION EQ_? STRING_
| CONNECTION EQ_? STRING_
| (DATA | INDEX) DIRECTORY EQ_? STRING_
| DELAY_KEY_WRITE EQ_? NUMBER_
| ENCRYPTION EQ_? STRING_
| ENGINE EQ_? ignoredIdentifier_
| INSERT_METHOD EQ_? (NO | FIRST | LAST)
| KEY_BLOCK_SIZE EQ_? NUMBER_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| PACK_KEYS EQ_? (NUMBER_ | DEFAULT)
| PASSWORD EQ_? STRING_
| ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT)
| STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_)
| STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_)
| STATS_SAMPLE_PAGES EQ_? NUMBER_
| TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))?
| UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_
;
addColumnSpecification
: ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_)
;
firstOrAfterColumn
: FIRST | AFTER columnName
;
addIndexSpecification
: ADD indexDefinition_
;
addConstraintSpecification
: ADD constraintDefinition_
;
changeColumnSpecification
: CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn?
;
dropColumnSpecification
: DROP COLUMN? columnName
;
dropIndexSpecification
: DROP (INDEX | KEY) indexName
;
dropPrimaryKeySpecification
: DROP primaryKey
;
modifyColumnSpecification
: MODIFY COLUMN? columnDefinition firstOrAfterColumn?
;
// TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
// TODO hongjun: should support renameIndexSpecification on mysql
renameIndexSpecification
: RENAME (INDEX | KEY) indexName TO indexName
;
// TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table
renameTableSpecification_
: RENAME (TO | AS)? newTableName
;
newTableName
: identifier_
;
partitionDefinitions_
: LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_
;
partitionDefinition_
: PARTITION identifier_
(VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))?
partitionDefinitionOption_*
(LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)?
;
partitionLessThanValue_
: LP_ (expr | partitionValueList_) RP_ | MAXVALUE
;
partitionValueList_
: literals (COMMA_ literals)*
;
partitionDefinitionOption_
: STORAGE? ENGINE EQ_? identifier_
| COMMENT EQ_? STRING_
| DATA DIRECTORY EQ_? STRING_
| INDEX DIRECTORY EQ_? STRING_
| MAX_ROWS EQ_? NUMBER_
| MIN_ROWS EQ_? NUMBER_
| TABLESPACE EQ_? identifier_
;
subpartitionDefinition_
: SUBPARTITION identifier_ partitionDefinitionOption_*
;
|
add existClause_
|
add existClause_
|
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
|
160d5a00bfc239d6bb7272c70ab0325269cd5a19
|
analyzer/src/main/antlr4/nl/basjes/parse/useragent/parser/UserAgentTreeWalker.g4
|
analyzer/src/main/antlr4/nl/basjes/parse/useragent/parser/UserAgentTreeWalker.g4
|
/*
* Yet Another UserAgent Analyzer
* Copyright (C) 2013-2019 Niels Basjes
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar UserAgentTreeWalker;
// ===============================================================
VALUENAME : [a-zA-Z][a-zA-Z0-9]+ ;
VALUE : DOUBLEQUOTE ( '\\' [btnfr"'\\] | ~[\\"] )* DOUBLEQUOTE ;
UP : '^' ;
NEXT : '>' ;
NEXT2 : '>>' ;
NEXT3 : '>>>' ;
NEXT4 : '>>>>' ;
PREV : '<' ;
PREV2 : '<<' ;
PREV3 : '<<<' ;
PREV4 : '<<<<' ;
DOT : '.' ;
MINUS : '-' ;
STAR : '*' ;
IN : '?' ;
NUMBER : [0-9]+ ;
BLOCKOPEN : '[' ;
BLOCKCLOSE : ']' ;
BRACEOPEN : '(' ;
BRACECLOSE : ')' ;
DOUBLEQUOTE : '"' ;
COLON : ':' ;
SEMICOLON : ';' ;
SPACE : (' '|'\t')+ -> skip;
NOTEQUALS : '!=' ;
EQUALS : '=' ;
CONTAINS : '~' ;
STARTSWITH : '{' ;
ENDSWITH : '}' ;
BACKTOFULL : '@' ;
// ===============================================================
// TridentName[agent.(1)product.(2-4)comments.(*)product.name="Trident"^.(*)version~"7.";"DefaultValue"]
// LookUp[TridentName;agent.(1)product.(2-4)comments.(*)product.name#1="Trident"^.(*)version%1="7.";"DefaultValue"]
matcherRequire : matcher EOF #matcherBase
// | '__SyntaxError__' EQUALS value=VALUE #isSyntaxError
| 'IsNull' BLOCKOPEN matcher BLOCKCLOSE EOF #matcherPathIsNull
;
matcherExtract : expression=matcher EOF;
// Is a bit duplicate but this gives a lot of clarity in the code
matcherVariable : expression=matcher EOF;
matcher : basePath #matcherPath
| 'Concat' BLOCKOPEN prefix=VALUE SEMICOLON matcher SEMICOLON postfix=VALUE BLOCKCLOSE #matcherConcat
| 'Concat' BLOCKOPEN prefix=VALUE SEMICOLON matcher BLOCKCLOSE #matcherConcatPrefix
| 'Concat' BLOCKOPEN matcher SEMICOLON postfix=VALUE BLOCKCLOSE #matcherConcatPostfix
| 'NormalizeBrand' BLOCKOPEN matcher BLOCKCLOSE #matcherNormalizeBrand
| 'CleanVersion' BLOCKOPEN matcher BLOCKCLOSE #matcherCleanVersion
| 'LookUp' BLOCKOPEN lookup=VALUENAME SEMICOLON matcher (SEMICOLON defaultValue=VALUE )? BLOCKCLOSE #matcherPathLookup
| 'LookUpPrefix' BLOCKOPEN lookup=VALUENAME SEMICOLON matcher (SEMICOLON defaultValue=VALUE )? BLOCKCLOSE #matcherPathLookupPrefix
| 'IsInLookUpPrefix' BLOCKOPEN lookup=VALUENAME SEMICOLON matcher BLOCKCLOSE #matcherPathIsInLookupPrefix
| matcher wordRange #matcherWordRange
;
basePath : value=VALUE #pathFixedValue
| '@' variable=VALUENAME (nextStep=path)? #pathVariable
| 'agent' (nextStep=path)? #pathWalk
;
path : DOT numberRange name=VALUENAME (nextStep=path)? #stepDown
| UP (nextStep=path)? #stepUp
| NEXT (nextStep=path)? #stepNext
| NEXT2 (nextStep=path)? #stepNext2
| NEXT3 (nextStep=path)? #stepNext3
| NEXT4 (nextStep=path)? #stepNext4
| PREV (nextStep=path)? #stepPrev
| PREV2 (nextStep=path)? #stepPrev2
| PREV3 (nextStep=path)? #stepPrev3
| PREV4 (nextStep=path)? #stepPrev4
| EQUALS value=VALUE (nextStep=path)? #stepEqualsValue
| NOTEQUALS value=VALUE (nextStep=path)? #stepNotEqualsValue
| STARTSWITH value=VALUE (nextStep=path)? #stepStartsWithValue
| ENDSWITH value=VALUE (nextStep=path)? #stepEndsWithValue
| CONTAINS value=VALUE (nextStep=path)? #stepContainsValue
| IN set=VALUENAME (nextStep=path)? #stepIsInSet
| wordRange (nextStep=path)? #stepWordRange
| BACKTOFULL (nextStep=path)? #stepBackToFull
;
numberRange : ( BRACEOPEN rangeStart=NUMBER MINUS rangeEnd=NUMBER BRACECLOSE ) #numberRangeStartToEnd
| ( BRACEOPEN MINUS rangeEnd=NUMBER BRACECLOSE ) #numberRangeOpenStartToEnd
| ( BRACEOPEN rangeStart=NUMBER MINUS BRACECLOSE ) #numberRangeStartToOpenEnd
| ( BRACEOPEN count=NUMBER BRACECLOSE ) #numberRangeSingleValue
| ( BRACEOPEN STAR BRACECLOSE ) #numberRangeAll
| ( ) #numberRangeEmpty
;
wordRange : ( BLOCKOPEN firstWord=NUMBER MINUS lastWord=NUMBER BLOCKCLOSE ) #wordRangeStartToEnd
| ( BLOCKOPEN MINUS lastWord=NUMBER BLOCKCLOSE ) #wordRangeFirstWords
| ( BLOCKOPEN firstWord=NUMBER MINUS BLOCKCLOSE ) #wordRangeLastWords
| ( BLOCKOPEN singleWord=NUMBER BLOCKCLOSE ) #wordRangeSingleWord
;
|
/*
* Yet Another UserAgent Analyzer
* Copyright (C) 2013-2019 Niels Basjes
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar UserAgentTreeWalker;
// ===============================================================
PATHTOKENNAME : ('agent' | 'product' | 'name' | 'version' | 'comments' | 'entry' | 'text' | 'url' | 'email' | 'base64' | 'uuid' | 'keyvalue' | 'key' | 'value' );
VALUENAME : PATHTOKENNAME | [a-zA-Z][a-zA-Z0-9]+ ;
VALUE : DOUBLEQUOTE ( '\\' [btnfr"'\\] | ~[\\"] )* DOUBLEQUOTE ;
UP : '^' ;
NEXT : '>' ;
NEXT2 : '>>' ;
NEXT3 : '>>>' ;
NEXT4 : '>>>>' ;
PREV : '<' ;
PREV2 : '<<' ;
PREV3 : '<<<' ;
PREV4 : '<<<<' ;
DOT : '.' ;
MINUS : '-' ;
STAR : '*' ;
IN : '?' ;
NUMBER : [0-9]+ ;
BLOCKOPEN : '[' ;
BLOCKCLOSE : ']' ;
BRACEOPEN : '(' ;
BRACECLOSE : ')' ;
DOUBLEQUOTE : '"' ;
COLON : ':' ;
SEMICOLON : ';' ;
SPACE : (' '|'\t')+ -> skip;
NOTEQUALS : '!=' ;
EQUALS : '=' ;
CONTAINS : '~' ;
STARTSWITH : '{' ;
ENDSWITH : '}' ;
BACKTOFULL : '@' ;
// ===============================================================
// TridentName[agent.(1)product.(2-4)comments.(*)product.name="Trident"^.(*)version~"7.";"DefaultValue"]
// LookUp[TridentName;agent.(1)product.(2-4)comments.(*)product.name#1="Trident"^.(*)version%1="7.";"DefaultValue"]
matcherRequire : matcher EOF #matcherBase
// | '__SyntaxError__' EQUALS value=VALUE #isSyntaxError
| 'IsNull' BLOCKOPEN matcher BLOCKCLOSE EOF #matcherPathIsNull
;
matcherExtract : expression=matcher EOF;
// Is a bit duplicate but this gives a lot of clarity in the code
matcherVariable : expression=matcher EOF;
matcher : basePath #matcherPath
| 'Concat' BLOCKOPEN prefix=VALUE SEMICOLON matcher SEMICOLON postfix=VALUE BLOCKCLOSE #matcherConcat
| 'Concat' BLOCKOPEN prefix=VALUE SEMICOLON matcher BLOCKCLOSE #matcherConcatPrefix
| 'Concat' BLOCKOPEN matcher SEMICOLON postfix=VALUE BLOCKCLOSE #matcherConcatPostfix
| 'NormalizeBrand' BLOCKOPEN matcher BLOCKCLOSE #matcherNormalizeBrand
| 'CleanVersion' BLOCKOPEN matcher BLOCKCLOSE #matcherCleanVersion
| 'LookUp' BLOCKOPEN lookup=VALUENAME SEMICOLON matcher (SEMICOLON defaultValue=VALUE )? BLOCKCLOSE #matcherPathLookup
| 'LookUpPrefix' BLOCKOPEN lookup=VALUENAME SEMICOLON matcher (SEMICOLON defaultValue=VALUE )? BLOCKCLOSE #matcherPathLookupPrefix
| 'IsInLookUpPrefix' BLOCKOPEN lookup=VALUENAME SEMICOLON matcher BLOCKCLOSE #matcherPathIsInLookupPrefix
| matcher wordRange #matcherWordRange
;
basePath : value=VALUE #pathFixedValue
| '@' variable=VALUENAME (nextStep=path)? #pathVariable
| 'agent' (nextStep=path)? #pathWalk
;
path : DOT numberRange name=PATHTOKENNAME (nextStep=path)? #stepDown
| UP (nextStep=path)? #stepUp
| NEXT (nextStep=path)? #stepNext
| NEXT2 (nextStep=path)? #stepNext2
| NEXT3 (nextStep=path)? #stepNext3
| NEXT4 (nextStep=path)? #stepNext4
| PREV (nextStep=path)? #stepPrev
| PREV2 (nextStep=path)? #stepPrev2
| PREV3 (nextStep=path)? #stepPrev3
| PREV4 (nextStep=path)? #stepPrev4
| EQUALS value=VALUE (nextStep=path)? #stepEqualsValue
| NOTEQUALS value=VALUE (nextStep=path)? #stepNotEqualsValue
| STARTSWITH value=VALUE (nextStep=path)? #stepStartsWithValue
| ENDSWITH value=VALUE (nextStep=path)? #stepEndsWithValue
| CONTAINS value=VALUE (nextStep=path)? #stepContainsValue
| IN set=VALUENAME (nextStep=path)? #stepIsInSet
| wordRange (nextStep=path)? #stepWordRange
| BACKTOFULL (nextStep=path)? #stepBackToFull
;
numberRange : ( BRACEOPEN rangeStart=NUMBER MINUS rangeEnd=NUMBER BRACECLOSE ) #numberRangeStartToEnd
| ( BRACEOPEN MINUS rangeEnd=NUMBER BRACECLOSE ) #numberRangeOpenStartToEnd
| ( BRACEOPEN rangeStart=NUMBER MINUS BRACECLOSE ) #numberRangeStartToOpenEnd
| ( BRACEOPEN count=NUMBER BRACECLOSE ) #numberRangeSingleValue
| ( BRACEOPEN STAR BRACECLOSE ) #numberRangeAll
| ( ) #numberRangeEmpty
;
wordRange : ( BLOCKOPEN firstWord=NUMBER MINUS lastWord=NUMBER BLOCKCLOSE ) #wordRangeStartToEnd
| ( BLOCKOPEN MINUS lastWord=NUMBER BLOCKCLOSE ) #wordRangeFirstWords
| ( BLOCKOPEN firstWord=NUMBER MINUS BLOCKCLOSE ) #wordRangeLastWords
| ( BLOCKOPEN singleWord=NUMBER BLOCKCLOSE ) #wordRangeSingleWord
;
|
Make the rule parser a bit more strict
|
Make the rule parser a bit more strict
|
ANTLR
|
apache-2.0
|
nielsbasjes/yauaa,nielsbasjes/yauaa,nielsbasjes/yauaa,nielsbasjes/yauaa
|
88ad5f9e9a9900834a7a105c6eabd58a848b5323
|
lisa/lisa.g4
|
lisa/lisa.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 lisa;
program: declaration_block program_block;
declaration_block: 'declare' '{' declaration_statements '}';
declaration_statements: declaration_statement+;
declaration_statement: type ID ';';
type: 'int' | 'dfa' | 'nfa' | 'regex' | 'bool' | 'string';
program_block: 'program' '{' statements '}';
statements: statement+;
statement:
expression_statement
| if_statement
| while_statement
| generating_statement
| ('break' ';')
| ('continue' ';');
generating_statement:
'generate' '(' generator_type ',' 'int' ',' 'int' ')' statement;
generator_type: 'random' | 'enumerate';
expression_statement: expression ';';
if_statement: 'if' '(' expression ')' statement;
while_statement: WHILE '(' expression ')' statement;
expression: (variable (exprop expression)*) | simple_expression;
exprop: '=' | '-+' | '*=' | '/=' | '+=';
simple_expression: or_expression ('||' or_expression)*;
or_expression:
unary_relationexpression ('&&' unary_relationexpression)*;
unary_relationexpression: '!'? relation_expression;
relation_expression: add_expression (relop add_expression)*;
relop: '<=' | '>=' | '==' | '!=' | '>' | '>';
add_expression: term (addop term)*;
addop: '-' | '+';
term: factor (multop factor)*;
multop: '*' | '/' | '%';
factor: '(' simple_expression ')' | constant;
constant:
integer
| TRUE
| FALSE
| 'next'
| 'hasnext'
| variable
| STRINGLITERAL
| function
| type;
integer: ('+' | '-')? INTEGER;
function: ID '(' parameter_list ')';
parameter_list: simple_expression (',' simple_expression)*;
variable: ID;
TRUE: 'TRUE';
FALSE: 'FALSE';
WHILE: 'WHILE';
INTEGER: [1-9]([0-9]*);
ID: [a-zA-Z] ([a-z0-9A-Z_]*);
STRINGLITERAL: '"' .*? '"';
COMMENT: '//' ~[\r\n]* -> skip;
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 lisa;
program: declaration_block program_block;
declaration_block: 'declare' '{' declaration_statements '}';
declaration_statements: declaration_statement+;
declaration_statement: type_ ID ';';
type_: 'int' | 'dfa' | 'nfa' | 'regex' | 'bool' | 'string';
program_block: 'program' '{' statements '}';
statements: statement+;
statement:
expression_statement
| if_statement
| while_statement
| generating_statement
| ('break' ';')
| ('continue' ';');
generating_statement:
'generate' '(' generator_type ',' 'int' ',' 'int' ')' statement;
generator_type: 'random' | 'enumerate';
expression_statement: expression ';';
if_statement: 'if' '(' expression ')' statement;
while_statement: WHILE '(' expression ')' statement;
expression: (variable (exprop expression)*) | simple_expression;
exprop: '=' | '-+' | '*=' | '/=' | '+=';
simple_expression: or_expression ('||' or_expression)*;
or_expression:
unary_relationexpression ('&&' unary_relationexpression)*;
unary_relationexpression: '!'? relation_expression;
relation_expression: add_expression (relop add_expression)*;
relop: '<=' | '>=' | '==' | '!=' | '>' | '>';
add_expression: term (addop term)*;
addop: '-' | '+';
term: factor (multop factor)*;
multop: '*' | '/' | '%';
factor: '(' simple_expression ')' | constant;
constant:
integer
| TRUE
| FALSE
| 'next'
| 'hasnext'
| variable
| STRINGLITERAL
| function
| type_;
integer: ('+' | '-')? INTEGER;
function: ID '(' parameter_list ')';
parameter_list: simple_expression (',' simple_expression)*;
variable: ID;
TRUE: 'TRUE';
FALSE: 'FALSE';
WHILE: 'WHILE';
INTEGER: [1-9]([0-9]*);
ID: [a-zA-Z] ([a-z0-9A-Z_]*);
STRINGLITERAL: '"' .*? '"';
COMMENT: '//' ~[\r\n]* -> skip;
WS: [ \r\n\t]+ -> skip;
|
fix symbol conflict
|
fix symbol conflict
|
ANTLR
|
mit
|
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
|
8133624e7485934955687197637c96b361f38956
|
grammar/C.g4
|
grammar/C.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.
*/
/** C 2011 grammar built from the C11 Spec */
grammar C;
primaryExpression
: Identifier
| Constant
| StringLiteral+
| '(' expression ')'
| genericSelection
| '__extension__'? '(' compoundStatement ')' // Blocks (GCC extension)
| '__builtin_va_arg' '(' unaryExpression ',' typeName ')'
| '__builtin_offsetof' '(' typeName ',' unaryExpression ')'
;
genericSelection
: '_Generic' '(' assignmentExpression ',' genericAssocList ')'
;
genericAssocList
: genericAssociation
| genericAssocList ',' genericAssociation
;
genericAssociation
: typeName ':' assignmentExpression
| 'default' ':' assignmentExpression
;
postfixExpression
: primaryExpression
| postfixExpression '[' expression ']'
| postfixExpression '(' argumentExpressionList? ')'
| postfixExpression '.' Identifier
| postfixExpression '->' Identifier
| postfixExpression '++'
| postfixExpression '--'
| '(' typeName ')' '{' initializerList '}'
| '(' typeName ')' '{' initializerList ',' '}'
| '__extension__' '(' typeName ')' '{' initializerList '}'
| '__extension__' '(' typeName ')' '{' initializerList ',' '}'
;
argumentExpressionList
: assignmentExpression
| argumentExpressionList ',' assignmentExpression
;
unaryExpression
: postfixExpression
| '++' unaryExpression
| '--' unaryExpression
| unaryOperator castExpression
| 'sizeof' unaryExpression
| 'sizeof' '(' typeName ')'
| '_Alignof' '(' typeName ')'
| '&&' Identifier // GCC extension address of label
;
unaryOperator
: '&' | '*' | '+' | '-' | '~' | '!'
;
castExpression
: unaryExpression
| '(' typeName ')' castExpression
| '__extension__' '(' typeName ')' castExpression
;
multiplicativeExpression
: castExpression
| multiplicativeExpression '*' castExpression
| multiplicativeExpression '/' castExpression
| multiplicativeExpression '%' castExpression
;
additiveExpression
: multiplicativeExpression
| additiveExpression '+' multiplicativeExpression
| additiveExpression '-' multiplicativeExpression
;
shiftExpression
: additiveExpression
| shiftExpression '<<' additiveExpression
| shiftExpression '>>' additiveExpression
;
relationalExpression
: shiftExpression
| relationalExpression '<' shiftExpression
| relationalExpression '>' shiftExpression
| relationalExpression '<=' shiftExpression
| relationalExpression '>=' shiftExpression
;
equalityExpression
: relationalExpression
| equalityExpression '==' relationalExpression
| equalityExpression '!=' relationalExpression
;
andExpression
: equalityExpression
| andExpression '&' equalityExpression
;
exclusiveOrExpression
: andExpression
| exclusiveOrExpression '^' andExpression
;
inclusiveOrExpression
: exclusiveOrExpression
| inclusiveOrExpression '|' exclusiveOrExpression
;
logicalAndExpression
: inclusiveOrExpression
| logicalAndExpression '&&' inclusiveOrExpression
;
logicalOrExpression
: logicalAndExpression
| logicalOrExpression '||' logicalAndExpression
;
conditionalExpression
: logicalOrExpression ('?' expression ':' conditionalExpression)?
;
assignmentExpression
: conditionalExpression
| unaryExpression assignmentOperator assignmentExpression
;
assignmentOperator
: '=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '&=' | '^=' | '|='
;
expression
: assignmentExpression
| expression ',' assignmentExpression
;
constantExpression
: conditionalExpression
;
declaration
: declarationSpecifiers initDeclaratorList? ';'
| staticAssertDeclaration
;
declarationSpecifiers
: declarationSpecifier+
;
declarationSpecifiers2
: declarationSpecifier+
;
declarationSpecifier
: storageClassSpecifier
| typeSpecifier
| typeQualifier
| functionSpecifier
| alignmentSpecifier
;
initDeclaratorList
: initDeclarator
| initDeclaratorList ',' initDeclarator
;
initDeclarator
: declarator
| declarator '=' initializer
;
storageClassSpecifier
: 'typedef'
| 'extern'
| 'static'
| '_Thread_local'
| 'auto'
| 'register'
;
typeSpecifier
: ('void'
| 'char'
| 'short'
| 'int'
| 'long'
| 'float'
| 'double'
| 'signed'
| 'unsigned'
| '_Bool'
| '_Complex'
| '__m128'
| '__m128d'
| '__m128i')
| '__extension__' '(' ('__m128' | '__m128d' | '__m128i') ')'
| atomicTypeSpecifier
| structOrUnionSpecifier
| enumSpecifier
| typedefName
| '__typeof__' '(' constantExpression ')' // GCC extension
;
structOrUnionSpecifier
: structOrUnion Identifier? '{' structDeclarationList '}'
| structOrUnion Identifier
;
structOrUnion
: 'struct'
| 'union'
;
structDeclarationList
: structDeclaration
| structDeclarationList structDeclaration
;
structDeclaration
: specifierQualifierList structDeclaratorList? ';'
| staticAssertDeclaration
;
specifierQualifierList
: typeSpecifier specifierQualifierList?
| typeQualifier specifierQualifierList?
;
structDeclaratorList
: structDeclarator
| structDeclaratorList ',' structDeclarator
;
structDeclarator
: declarator
| declarator? ':' constantExpression
;
enumSpecifier
: 'enum' Identifier? '{' enumeratorList '}'
| 'enum' Identifier? '{' enumeratorList ',' '}'
| 'enum' Identifier
;
enumeratorList
: enumerator
| enumeratorList ',' enumerator
;
enumerator
: enumerationConstant
| enumerationConstant '=' constantExpression
;
enumerationConstant
: Identifier
;
atomicTypeSpecifier
: '_Atomic' '(' typeName ')'
;
typeQualifier
: 'const'
| 'restrict'
| 'volatile'
| '_Atomic'
;
functionSpecifier
: ('inline'
| '_Noreturn'
| '__inline__' // GCC extension
| '__stdcall')
| gccAttributeSpecifier
| '__declspec' '(' Identifier ')'
;
alignmentSpecifier
: '_Alignas' '(' typeName ')'
| '_Alignas' '(' constantExpression ')'
;
declarator
: pointer? directDeclarator gccDeclaratorExtension*
;
directDeclarator
: Identifier
| '(' declarator ')'
| directDeclarator '[' typeQualifierList? assignmentExpression? ']'
| directDeclarator '[' 'static' typeQualifierList? assignmentExpression ']'
| directDeclarator '[' typeQualifierList 'static' assignmentExpression ']'
| directDeclarator '[' typeQualifierList? '*' ']'
| directDeclarator '(' parameterTypeList ')'
| directDeclarator '(' identifierList? ')'
;
gccDeclaratorExtension
: '__asm' '(' StringLiteral+ ')'
| gccAttributeSpecifier
;
gccAttributeSpecifier
: '__attribute__' '(' '(' gccAttributeList ')' ')'
;
gccAttributeList
: gccAttribute (',' gccAttribute)*
| // empty
;
gccAttribute
: ~(',' | '(' | ')') // relaxed def for "identifier or reserved word"
('(' argumentExpressionList? ')')?
| // empty
;
nestedParenthesesBlock
: ( ~('(' | ')')
| '(' nestedParenthesesBlock ')'
)*
;
pointer
: '*' typeQualifierList?
| '*' typeQualifierList? pointer
| '^' typeQualifierList? // Blocks language extension
| '^' typeQualifierList? pointer // Blocks language extension
;
typeQualifierList
: typeQualifier
| typeQualifierList typeQualifier
;
parameterTypeList
: parameterList
| parameterList ',' '...'
;
parameterList
: parameterDeclaration
| parameterList ',' parameterDeclaration
;
parameterDeclaration
: declarationSpecifiers declarator
| declarationSpecifiers2 abstractDeclarator?
;
identifierList
: Identifier
| identifierList ',' Identifier
;
typeName
: specifierQualifierList abstractDeclarator?
;
abstractDeclarator
: pointer
| pointer? directAbstractDeclarator gccDeclaratorExtension*
;
directAbstractDeclarator
: '(' abstractDeclarator ')' gccDeclaratorExtension*
| '[' typeQualifierList? assignmentExpression? ']'
| '[' 'static' typeQualifierList? assignmentExpression ']'
| '[' typeQualifierList 'static' assignmentExpression ']'
| '[' '*' ']'
| '(' parameterTypeList? ')' gccDeclaratorExtension*
| directAbstractDeclarator '[' typeQualifierList? assignmentExpression? ']'
| directAbstractDeclarator '[' 'static' typeQualifierList? assignmentExpression ']'
| directAbstractDeclarator '[' typeQualifierList 'static' assignmentExpression ']'
| directAbstractDeclarator '[' '*' ']'
| directAbstractDeclarator '(' parameterTypeList? ')' gccDeclaratorExtension*
;
typedefName
: Identifier
;
initializer
: assignmentExpression
| '{' initializerList '}'
| '{' initializerList ',' '}'
;
initializerList
: designation? initializer
| initializerList ',' designation? initializer
;
designation
: designatorList '='
;
designatorList
: designator
| designatorList designator
;
designator
: '[' constantExpression ']'
| '.' Identifier
;
staticAssertDeclaration
: '_Static_assert' '(' constantExpression ',' StringLiteral+ ')' ';'
;
statement
: labeledStatement
| compoundStatement
| expressionStatement
| selectionStatement
| iterationStatement
| jumpStatement
| ('__asm' | '__asm__') ('volatile' | '__volatile__') '(' (logicalOrExpression (',' logicalOrExpression)*)? (':' (logicalOrExpression (',' logicalOrExpression)*)?)* ')' ';'
;
labeledStatement
: Identifier ':' statement
| 'case' constantExpression ':' statement
| 'default' ':' statement
;
compoundStatement
: '{' blockItemList? '}'
;
blockItemList
: blockItem
| blockItemList blockItem
;
blockItem
: declaration
| statement
;
expressionStatement
: expression? ';'
;
selectionStatement
: 'if' '(' expression ')' statement ('else' statement)?
| 'switch' '(' expression ')' statement
;
iterationStatement
: 'while' '(' expression ')' statement
| 'do' statement 'while' '(' expression ')' ';'
| 'for' '(' expression? ';' expression? ';' expression? ')' statement
| 'for' '(' declaration expression? ';' expression? ')' statement
;
jumpStatement
: 'goto' Identifier ';'
| 'continue' ';'
| 'break' ';'
| 'return' expression? ';'
| 'goto' unaryExpression ';' // GCC extension
;
compilationUnit
: translationUnit? EOF
;
translationUnit
: externalDeclaration
| translationUnit externalDeclaration
;
externalDeclaration
: functionDefinition
| declaration
| ';' // stray ;
;
functionDefinition
: declarationSpecifiers? declarator declarationList? compoundStatement
;
declarationList
: declaration
| declarationList declaration
;
Auto : 'auto';
Break : 'break';
Case : 'case';
Char : 'char';
Const : 'const';
Continue : 'continue';
Default : 'default';
Do : 'do';
Double : 'double';
Else : 'else';
Enum : 'enum';
Extern : 'extern';
Float : 'float';
For : 'for';
Goto : 'goto';
If : 'if';
Inline : 'inline';
Int : 'int';
Long : 'long';
Register : 'register';
Restrict : 'restrict';
Return : 'return';
Short : 'short';
Signed : 'signed';
Sizeof : 'sizeof';
Static : 'static';
Struct : 'struct';
Switch : 'switch';
Typedef : 'typedef';
Union : 'union';
Unsigned : 'unsigned';
Void : 'void';
Volatile : 'volatile';
While : 'while';
Alignas : '_Alignas';
Alignof : '_Alignof';
Atomic : '_Atomic';
Bool : '_Bool';
Complex : '_Complex';
Generic : '_Generic';
Imaginary : '_Imaginary';
Noreturn : '_Noreturn';
StaticAssert : '_Static_assert';
ThreadLocal : '_Thread_local';
LeftParen : '(';
RightParen : ')';
LeftBracket : '[';
RightBracket : ']';
LeftBrace : '{';
RightBrace : '}';
Less : '<';
LessEqual : '<=';
Greater : '>';
GreaterEqual : '>=';
LeftShift : '<<';
RightShift : '>>';
Plus : '+';
PlusPlus : '++';
Minus : '-';
MinusMinus : '--';
Star : '*';
Div : '/';
Mod : '%';
And : '&';
Or : '|';
AndAnd : '&&';
OrOr : '||';
Caret : '^';
Not : '!';
Tilde : '~';
Question : '?';
Colon : ':';
Semi : ';';
Comma : ',';
Assign : '=';
// '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '&=' | '^=' | '|='
StarAssign : '*=';
DivAssign : '/=';
ModAssign : '%=';
PlusAssign : '+=';
MinusAssign : '-=';
LeftShiftAssign : '<<=';
RightShiftAssign : '>>=';
AndAssign : '&=';
XorAssign : '^=';
OrAssign : '|=';
Equal : '==';
NotEqual : '!=';
Arrow : '->';
Dot : '.';
Ellipsis : '...';
Identifier
: IdentifierNondigit
( IdentifierNondigit
| Digit
)*
;
fragment
IdentifierNondigit
: Nondigit
| UniversalCharacterName
//| // other implementation-defined characters...
;
fragment
Nondigit
: [a-zA-Z_]
;
fragment
Digit
: [0-9]
;
fragment
UniversalCharacterName
: '\\u' HexQuad
| '\\U' HexQuad HexQuad
;
fragment
HexQuad
: HexadecimalDigit HexadecimalDigit HexadecimalDigit HexadecimalDigit
;
Constant
: IntegerConstant
| FloatingConstant
//| EnumerationConstant
| CharacterConstant
;
fragment
IntegerConstant
: DecimalConstant IntegerSuffix?
| OctalConstant IntegerSuffix?
| HexadecimalConstant IntegerSuffix?
| BinaryConstant
;
fragment
BinaryConstant
: '0' [bB] [0-1]+
;
fragment
DecimalConstant
: NonzeroDigit Digit*
;
fragment
OctalConstant
: '0' OctalDigit*
;
fragment
HexadecimalConstant
: HexadecimalPrefix HexadecimalDigit+
;
fragment
HexadecimalPrefix
: '0' [xX]
;
fragment
NonzeroDigit
: [1-9]
;
fragment
OctalDigit
: [0-7]
;
fragment
HexadecimalDigit
: [0-9a-fA-F]
;
fragment
IntegerSuffix
: UnsignedSuffix LongSuffix?
| UnsignedSuffix LongLongSuffix
| LongSuffix UnsignedSuffix?
| LongLongSuffix UnsignedSuffix?
;
fragment
UnsignedSuffix
: [uU]
;
fragment
LongSuffix
: [lL]
;
fragment
LongLongSuffix
: 'll' | 'LL'
;
fragment
FloatingConstant
: DecimalFloatingConstant
| HexadecimalFloatingConstant
;
fragment
DecimalFloatingConstant
: FractionalConstant ExponentPart? FloatingSuffix?
| DigitSequence ExponentPart FloatingSuffix?
;
fragment
HexadecimalFloatingConstant
: HexadecimalPrefix HexadecimalFractionalConstant BinaryExponentPart FloatingSuffix?
| HexadecimalPrefix HexadecimalDigitSequence BinaryExponentPart FloatingSuffix?
;
fragment
FractionalConstant
: DigitSequence? '.' DigitSequence
| DigitSequence '.'
;
fragment
ExponentPart
: 'e' Sign? DigitSequence
| 'E' Sign? DigitSequence
;
fragment
Sign
: '+' | '-'
;
fragment
DigitSequence
: Digit+
;
fragment
HexadecimalFractionalConstant
: HexadecimalDigitSequence? '.' HexadecimalDigitSequence
| HexadecimalDigitSequence '.'
;
fragment
BinaryExponentPart
: 'p' Sign? DigitSequence
| 'P' Sign? DigitSequence
;
fragment
HexadecimalDigitSequence
: HexadecimalDigit+
;
fragment
FloatingSuffix
: 'f' | 'l' | 'F' | 'L'
;
fragment
CharacterConstant
: '\'' CCharSequence '\''
| 'L\'' CCharSequence '\''
| 'u\'' CCharSequence '\''
| 'U\'' CCharSequence '\''
;
fragment
CCharSequence
: CChar+
;
fragment
CChar
: ~['\\\r\n]
| EscapeSequence
;
fragment
EscapeSequence
: SimpleEscapeSequence
| OctalEscapeSequence
| HexadecimalEscapeSequence
| UniversalCharacterName
;
fragment
SimpleEscapeSequence
: '\\' ['"?abfnrtv\\]
;
fragment
OctalEscapeSequence
: '\\' OctalDigit
| '\\' OctalDigit OctalDigit
| '\\' OctalDigit OctalDigit OctalDigit
;
fragment
HexadecimalEscapeSequence
: '\\x' HexadecimalDigit+
;
StringLiteral
: EncodingPrefix? '"' SCharSequence? '"'
;
fragment
EncodingPrefix
: 'u8'
| 'u'
| 'U'
| 'L'
;
fragment
SCharSequence
: SChar+
;
fragment
SChar
: ~["\\\r\n]
| EscapeSequence
| '\\\n' // Added line
| '\\\r\n' // Added line
;
ComplexDefine
: '#' Whitespace? 'define' ~[#]*
-> skip
;
// ignore the following asm blocks:
/*
asm
{
mfspr x, 286;
}
*/
AsmBlock
: 'asm' ~'{'* '{' ~'}'* '}'
-> skip
;
// ignore the lines generated by c preprocessor
// sample line : '#line 1 "/home/dm/files/dk1.h" 1'
LineAfterPreprocessing
: '#line' Whitespace* ~[\r\n]*
-> skip
;
LineDirective
: '#' Whitespace? DecimalConstant Whitespace? StringLiteral ~[\r\n]*
-> skip
;
PragmaDirective
: '#' Whitespace? 'pragma' Whitespace ~[\r\n]*
-> skip
;
Whitespace
: [ \t]+
-> skip
;
Newline
: ( '\r' '\n'?
| '\n'
)
-> skip
;
BlockComment
: '/*' .*? '*/'
-> skip
;
LineComment
: '//' ~[\r\n]*
-> skip
;
|
/*
[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.
*/
/** C 2011 grammar built from the C11 Spec */
grammar C;
primaryExpression
: Identifier
| Constant
| StringLiteral+
| '(' expression ')'
;
postfixExpression
: primaryExpression
| postfixExpression '[' expression ']'
| postfixExpression '(' argumentExpressionList? ')'
| postfixExpression '.' Identifier
| postfixExpression '->' Identifier
| postfixExpression '++'
| postfixExpression '--'
;
argumentExpressionList
: assignmentExpression
| argumentExpressionList ',' assignmentExpression
;
unaryExpression
: postfixExpression
| '++' unaryExpression
| '--' unaryExpression
| unaryOperator castExpression
;
unaryOperator
: '&' | '*' | '+' | '-' | '~' | '!'
;
castExpression
: unaryExpression
| '(' typeName ')' castExpression
;
multiplicativeExpression
: castExpression
| multiplicativeExpression '*' castExpression
| multiplicativeExpression '/' castExpression
| multiplicativeExpression '%' castExpression
;
additiveExpression
: multiplicativeExpression
| additiveExpression '+' multiplicativeExpression
| additiveExpression '-' multiplicativeExpression
;
shiftExpression
: additiveExpression
| shiftExpression '<<' additiveExpression
| shiftExpression '>>' additiveExpression
;
relationalExpression
: shiftExpression
| relationalExpression '<' shiftExpression
| relationalExpression '>' shiftExpression
| relationalExpression '<=' shiftExpression
| relationalExpression '>=' shiftExpression
;
equalityExpression
: relationalExpression
| equalityExpression '==' relationalExpression
| equalityExpression '!=' relationalExpression
;
andExpression
: equalityExpression
| andExpression '&' equalityExpression
;
exclusiveOrExpression
: andExpression
| exclusiveOrExpression '^' andExpression
;
inclusiveOrExpression
: exclusiveOrExpression
| inclusiveOrExpression '|' exclusiveOrExpression
;
logicalAndExpression
: inclusiveOrExpression
| logicalAndExpression '&&' inclusiveOrExpression
;
logicalOrExpression
: logicalAndExpression
| logicalOrExpression '||' logicalAndExpression
;
conditionalExpression
: logicalOrExpression ('?' expression ':' conditionalExpression)?
;
assignmentExpression
: conditionalExpression
| unaryExpression assignmentOperator assignmentExpression
;
assignmentOperator
: '=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '&=' | '^=' | '|='
;
expression
: assignmentExpression
| expression ',' assignmentExpression
;
constantExpression
: conditionalExpression
;
declaration
: declarationSpecifiers initDeclaratorList? ';'
;
declarationSpecifiers
: declarationSpecifier+
;
declarationSpecifier
: typeSpecifier
| typeQualifier
;
initDeclaratorList
: initDeclarator
| initDeclaratorList ',' initDeclarator
;
initDeclarator
: declarator
| declarator '=' initializer
;
typeSpecifier
: ('void'
| 'char'
| 'int'
| 'float'
| atomicTypeSpecifier
| structOrUnionSpecifier
| enumSpecifier
| typedefName
| '__typeof__' '(' constantExpression ')' // GCC extension
;
structOrUnionSpecifier
: structOrUnion Identifier? '{' structDeclarationList '}'
| structOrUnion Identifier
;
structOrUnion
: 'struct'
| 'union'
;
structDeclarationList
: structDeclaration
| structDeclarationList structDeclaration
;
structDeclaration
: specifierQualifierList structDeclaratorList? ';'
| staticAssertDeclaration
;
specifierQualifierList
: typeSpecifier specifierQualifierList?
| typeQualifier specifierQualifierList?
;
structDeclaratorList
: structDeclarator
| structDeclaratorList ',' structDeclarator
;
structDeclarator
: declarator
| declarator? ':' constantExpression
;
typeQualifier
: 'const'
;
declarator
: pointer? directDeclarator
;
directDeclarator
: Identifier
| '(' declarator ')'
| directDeclarator '[' typeQualifierList? assignmentExpression? ']'
| directDeclarator '(' parameterTypeList ')'
| directDeclarator '(' identifierList? ')'
;
pointer
: '*' typeQualifierList?
| '*' typeQualifierList? pointer
;
typeQualifierList
: typeQualifier
| typeQualifierList typeQualifier
;
parameterTypeList
: parameterList
| parameterList ',' '...'
;
parameterList
: parameterDeclaration
| parameterList ',' parameterDeclaration
;
parameterDeclaration
: declarationSpecifiers declarator
| declarationSpecifiers2
;
identifierList
: Identifier
| identifierList ',' Identifier
;
typeName
: specifierQualifierList
;
typedefName
: Identifier
;
initializer
: assignmentExpression
| '{' initializerList '}'
| '{' initializerList ',' '}'
;
initializerList
: designation? initializer
| initializerList ',' designation? initializer
;
designation
: designatorList '='
;
designatorList
: designator
| designatorList designator
;
designator
: '[' constantExpression ']'
| '.' Identifier
;
statement
: compoundStatement
| expressionStatement
| selectionStatement
| iterationStatement
| jumpStatement
;
compoundStatement
: '{' blockItemList? '}'
;
blockItemList
: blockItem
| blockItemList blockItem
;
blockItem
: declaration
| statement
;
expressionStatement
: expression? ';'
;
selectionStatement
: 'if' '(' expression ')' statement ('else' statement)?
;
iterationStatement
: 'while' '(' expression ')' statement
| 'do' statement 'while' '(' expression ')' ';'
| 'for' '(' expression? ';' expression? ';' expression? ')' statement
| 'for' '(' declaration expression? ';' expression? ')' statement
;
jumpStatement
: 'continue' ';'
| 'break' ';'
| 'return' expression? ';'
;
compilationUnit
: translationUnit? EOF
;
translationUnit
: externalDeclaration
| translationUnit externalDeclaration
;
externalDeclaration
: functionDefinition
| declaration
| ';' // stray ;
;
functionDefinition
: declarationSpecifiers? declarator declarationList? compoundStatement
;
declarationList
: declaration
| declarationList declaration
;
Identifier
: IdentifierNondigit
( IdentifierNondigit
| Digit
)*
;
fragment
IdentifierNondigit
: Nondigit
| UniversalCharacterName
//| // other implementation-defined characters...
;
fragment
Nondigit
: [a-zA-Z_]
;
fragment
Digit
: [0-9]
;
fragment
UniversalCharacterName
: '\\u' HexQuad
| '\\U' HexQuad HexQuad
;
fragment
HexQuad
: HexadecimalDigit HexadecimalDigit HexadecimalDigit HexadecimalDigit
;
Constant
: IntegerConstant
| FloatingConstant
//| EnumerationConstant
| CharacterConstant
;
fragment
IntegerConstant
: DecimalConstant
| OctalConstant
| HexadecimalConstant
| BinaryConstant
;
fragment
BinaryConstant
: '0' [bB] [0-1]+
;
// In real C, `0` starts an octal constant. We simplify things here:
fragment
DecimalConstant
: Digit+
;
fragment
NonzeroDigit
: [1-9]
;
fragment
FloatingConstant
: DecimalFloatingConstant
;
fragment
DecimalFloatingConstant
: FractionalConstant ExponentPart?
| DigitSequence ExponentPart
;
fragment
FractionalConstant
: DigitSequence? '.' DigitSequence
| DigitSequence '.'
;
fragment
ExponentPart
: 'e' Sign? DigitSequence
| 'E' Sign? DigitSequence
;
fragment
Sign
: '+' | '-'
;
fragment
DigitSequence
: Digit+
;
fragment
CharacterConstant
: '\'' CCharSequence '\''
;
fragment
CCharSequence
: CChar+
;
fragment
CChar
: ~['\\\r\n]
| EscapeSequence
;
fragment
EscapeSequence
: SimpleEscapeSequence
;
fragment
SimpleEscapeSequence
: '\\' ['"?abfnrtv\\]
;
StringLiteral
: '"' SCharSequence? '"'
;
fragment
SCharSequence
: SChar+
;
fragment
SChar
: ~["\\\r\n]
| EscapeSequence
| '\\\n' // Added line
| '\\\r\n' // Added line
;
Whitespace
: [ \t]+
-> skip
;
Newline
: ( '\r' '\n'?
| '\n'
)
-> skip
;
BlockComment
: '/*' .*? '*/'
-> skip
;
LineComment
: '//' ~[\r\n]*
-> skip
;
|
Remove fluff from C.g4
|
Remove fluff from C.g4
|
ANTLR
|
mit
|
Sibert-Aerts/c2p,Sibert-Aerts/c2p,Sibert-Aerts/c2p
|
358d1ebdb2025b378640406ad1b77ba990d665a5
|
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
LFUSION group_clause_optional[$l] collapse_optional[$l] EOF
{ $l.setDirective(ClawDirective.LOOP_FUSION); }
// loop-interchange directive
| LINTERCHANGE indexes_option[$l] parallel_optional[$l] acc_optional[$l] EOF
{ $l.setDirective(ClawDirective.LOOP_INTERCHANGE); }
// loop-extract directive
| LEXTRACT range_option mapping_option_list[m] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF
{
$l.setDirective(ClawDirective.LOOP_EXTRACT);
$l.setRange($range_option.r);
$l.setMappings(m);
}
// remove directive
| REMOVE EOF
{ $l.setDirective(ClawDirective.REMOVE); }
| END REMOVE EOF
{
$l.setDirective(ClawDirective.REMOVE);
$l.setEndPragma();
}
// Kcache directive
| KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF
{
$l.setDirective(ClawDirective.KCACHE);
$l.setOffsets(i);
}
| KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF
{
$l.setDirective(ClawDirective.KCACHE);
$l.setOffsets(i);
$l.setInitClause();
}
// Array notation transformation directive
| ARRAY_TRANS induction_optional[$l] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF
{ $l.setDirective(ClawDirective.ARRAY_TRANSFORM); }
| END ARRAY_TRANS
{
$l.setDirective(ClawDirective.ARRAY_TRANSFORM);
$l.setEndPragma();
}
// loop-hoist directive
| LHOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF
{
$l.setHoistInductionVars(o);
$l.setDirective(ClawDirective.LOOP_HOIST);
}
| END LHOIST EOF
{
$l.setDirective(ClawDirective.LOOP_HOIST);
$l.setEndPragma();
}
// on the fly directive
| ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')'
{
$l.setDirective(ClawDirective.ARRAY_TO_CALL);
$l.setFctParams(o);
$l.setFctName($fct_name.text);
$l.setArrayName($array_name.text);
}
// parallelize directive
| define_option[$l]* PARALLELIZE data_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';
// Directives
ARRAY_TRANS : 'array-transform';
ARRAY_TO_CALL: 'call';
DEFINE : 'define';
END : 'end';
KCACHE : 'kcache';
LEXTRACT : 'loop-extract';
LFUSION : 'loop-fusion';
LHOIST : 'loop-hoist';
LINTERCHANGE : 'loop-interchange';
PARALLELIZE : 'parallelize';
REMOVE : 'remove';
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_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(); };
|
Refactor Lxx lexer rules to LOOPxx
|
Refactor Lxx lexer rules to LOOPxx
|
ANTLR
|
bsd-2-clause
|
clementval/claw-compiler,clementval/claw-compiler
|
fb6a90851e5033d01013fd3d25580c3a4bc932e1
|
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
|
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
|
grammar OracleDCLStatement;
import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol;
/**
* each statement has a url,
* each base url : https://docs.oracle.com/database/121/SQLRF/.
* no begin statement in oracle
*/
//statements_9014.htm#SQLRF01603
grant
: GRANT
(
(grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))?
| grantRolesToPrograms
)
;
grantSystemPrivileges
: systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)?
;
systemObjects
: systemObject(COMMA systemObject)*
;
systemObject
: ALL PRIVILEGES
| roleName
| ID *?
;
grantees
: grantee (COMMA grantee)*
;
grantee
: userName
| roleName
| PUBLIC
;
granteeIdentifiedBy
: userNames IDENTIFIED BY STRING (COMMA STRING)*
;
grantObjectPrivilegeClause
: grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause
TO grantees (WITH HIERARCHY OPTION)?(WITH GRANT OPTION)?
;
grantObjectPrivilege
: objectPrivilege columnList?
;
objectPrivilege
: ID *?
| ALL PRIVILEGES?
;
onObjectClause
: ON
(
schemaName? ID
| USER userName ( COMMA userName)*
| (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID
)
;
grantRolesToPrograms
: roleNames TO programUnits
;
programUnits
: programUnit (COMMA programUnit)*
;
programUnit
: (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID
;
revoke
: REVOKE
(
(revokeSystemPrivileges | revokeObjectPrivileges) (CONTAINER EQ_ (CURRENT | ALL))?
| revokeRolesFromPrograms
)
;
revokeSystemPrivileges
: systemObjects FROM
;
revokeObjectPrivileges
: objectPrivilege (COMMA objectPrivilege)* onObjectClause
FROM grantees
(CASCADE CONSTRAINTS | FORCE)?
;
revokeRolesFromPrograms
: (roleNames | ALL) FROM programUnits
;
createUser
: CREATE USER userName IDENTIFIED
(BY STRING | (EXTERNALLY | GLOBALLY) ( AS STRING)?)
(
DEFAULT TABLESPACE ID
| TEMPORARY TABLESPACE ID
| (QUOTA (sizeClause | UNLIMITED) ON ID)
| PROFILE ID
| PASSWORD EXPIRE
| ACCOUNT (LOCK | UNLOCK)
| ENABLE EDITIONS
| CONTAINER EQ_ (CURRENT | ALL)
)*
;
sizeClause
: NUMBER ID?
;
proxyClause
: (GRANT | REVOKE) CONNECT THROUGH ( ENTERPRISE USERS | userName dbUserProxyClauses?)
;
dbUserProxyClauses
: (WITH
(
ROLE (ALL EXCEPT)? roleNames
| NO ROLES
)
)?
(AUTHENTICATION REQUIRED )?
;
|
grammar OracleDCLStatement;
import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol;
/**
* each statement has a url,
* each base url : https://docs.oracle.com/database/121/SQLRF/.
* no begin statement in oracle
*/
//statements_9014.htm#SQLRF01603
grant
: GRANT
(
(grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))?
| grantRolesToPrograms
)
;
grantSystemPrivileges
: systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)?
;
systemObjects
: systemObject(COMMA systemObject)*
;
systemObject
: ALL PRIVILEGES
| roleName
| ID *?
;
grantees
: grantee (COMMA grantee)*
;
grantee
: userName
| roleName
| PUBLIC
;
granteeIdentifiedBy
: userNames IDENTIFIED BY STRING (COMMA STRING)*
;
grantObjectPrivilegeClause
: grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause
TO grantees (WITH HIERARCHY OPTION)?(WITH GRANT OPTION)?
;
grantObjectPrivilege
: objectPrivilege columnList?
;
objectPrivilege
: ID *?
| ALL PRIVILEGES?
;
onObjectClause
: ON
(
schemaName? ID
| USER userName ( COMMA userName)*
| (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID
)
;
grantRolesToPrograms
: roleNames TO programUnits
;
programUnits
: programUnit (COMMA programUnit)*
;
programUnit
: (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID
;
revoke
: REVOKE
(
(revokeSystemPrivileges | revokeObjectPrivileges) (CONTAINER EQ_ (CURRENT | ALL))?
| revokeRolesFromPrograms
)
;
revokeSystemPrivileges
: systemObjects FROM
;
revokeObjectPrivileges
: objectPrivilege (COMMA objectPrivilege)* onObjectClause
FROM grantees
(CASCADE CONSTRAINTS | FORCE)?
;
revokeRolesFromPrograms
: (roleNames | ALL) FROM programUnits
;
createUser
: CREATE USER userName IDENTIFIED
(BY STRING | (EXTERNALLY | GLOBALLY) ( AS STRING)?)
(
DEFAULT TABLESPACE ID
| TEMPORARY TABLESPACE ID
| (QUOTA (sizeClause | UNLIMITED) ON ID)
| PROFILE ID
| PASSWORD EXPIRE
| ACCOUNT (LOCK | UNLOCK)
| ENABLE EDITIONS
| CONTAINER EQ_ (CURRENT | ALL)
)*
;
sizeClause
: NUMBER ID?
;
containerDataClause
: (
SET CONTAINER_DATA EQ_ ( ALL | DEFAULT | idList )
|(ADD |REMOVE) CONTAINER_DATA EQ_ idList
)
(FOR schemaName? ID)?
;
proxyClause
: (GRANT | REVOKE) CONNECT THROUGH ( ENTERPRISE USERS | userName dbUserProxyClauses?)
;
dbUserProxyClauses
: (WITH
(
ROLE (ALL EXCEPT)? roleNames
| NO ROLES
)
)?
(AUTHENTICATION REQUIRED )?
;
|
add containerDataClause
|
add containerDataClause
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
|
8ebff1baa859deb1fee6708575a8937d04115191
|
sharding-core/src/main/antlr4/imports/BaseRule.g4
|
sharding-core/src/main/antlr4/imports/BaseRule.g4
|
//rule in this file does not allow override
grammar BaseRule;
import DataType,Keyword,Symbol;
ID:
(BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_? DOT)?
(BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_?)
|[a-zA-Z_$0-9]+ DOT ASTERISK
;
schemaName: ID;
tableName: ID;
columnName: ID;
tablespaceName: ID;
collationName: STRING | ID;
indexName: ID;
alias: ID;
cteName:ID;
parserName: ID;
extensionName: ID;
rowName: ID;
opclass: ID;
fileGroup: ID;
groupName: ID;
constraintName: ID;
keyName: ID;
typeName: ID;
xmlSchemaCollection:ID;
columnSetName: ID;
directoryName: ID;
triggerName: ID;
roleName: ID;
partitionName: ID;
rewriteRuleName: ID;
ownerName: ID;
userName: ID;
ifExists
: IF EXISTS;
ifNotExists
: IF NOT EXISTS;
dataTypeLength
: LP_ (NUMBER (COMMA NUMBER)?)? RP_
;
nullNotnull
: NULL
| NOT NULL
;
primaryKey
: PRIMARY? KEY
;
matchNone
: 'Default does not match anything'
;
idList
: LP_ ID (COMMA ID)* RP_
;
rangeClause
: NUMBER (COMMA NUMBER)*
| NUMBER OFFSET NUMBER
;
tableNamesWithParen
: LP_ tableNames RP_
;
tableNames
: tableName (COMMA tableName)*
;
columnNamesWithParen
: LP_ columnNames RP_
;
columnNames
: columnName (COMMA columnName)*
;
columnList
: LP_ columnNames RP_
;
indexNames
: indexName (COMMA indexName)*
;
rowNames
: rowName (COMMA rowName)*
;
roleNames
: roleName (COMMA roleName)*
;
userNames
: userName (COMMA userName)*
;
bitExprs:
bitExpr (COMMA bitExpr)*
;
exprs
: expr (COMMA expr)*
;
exprsWithParen
: LP_ exprs RP_
;
//https://dev.mysql.com/doc/refman/8.0/en/expressions.html
expr
: expr OR expr
| expr OR_ expr
| expr XOR expr
| expr AND expr
| expr AND_ expr
| LP_ expr RP_
| NOT expr
| NOT_ expr
| booleanPrimary
| exprRecursive
;
exprRecursive
: matchNone
;
booleanPrimary
: booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL)
| booleanPrimary SAFE_EQ predicate
| booleanPrimary comparisonOperator predicate
| booleanPrimary comparisonOperator (ALL | ANY) subquery
| predicate
;
comparisonOperator
: EQ_
| GTE
| GT
| LTE
| LT
| NEQ_
| NEQ
;
predicate
: bitExpr NOT? IN subquery
| bitExpr NOT? IN LP_ simpleExpr ( COMMA simpleExpr)* RP_
| bitExpr NOT? BETWEEN simpleExpr AND predicate
| bitExpr SOUNDS LIKE simpleExpr
| bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)*
| bitExpr NOT? REGEXP simpleExpr
| bitExpr
;
bitExpr
: bitExpr BIT_INCLUSIVE_OR bitExpr
| bitExpr BIT_AND bitExpr
| bitExpr SIGNED_LEFT_SHIFT bitExpr
| bitExpr SIGNED_RIGHT_SHIFT bitExpr
| bitExpr PLUS bitExpr
| bitExpr MINUS bitExpr
| bitExpr ASTERISK bitExpr
| bitExpr SLASH bitExpr
| bitExpr MOD bitExpr
| bitExpr MOD_ bitExpr
| bitExpr BIT_EXCLUSIVE_OR bitExpr
//| bitExpr '+' interval_expr
//| bitExpr '-' interval_expr
| simpleExpr
;
simpleExpr
: functionCall
| liter
| ID
| simpleExpr collateClause
//| param_marker
//| variable
| simpleExpr AND_ simpleExpr
| PLUS simpleExpr
| MINUS simpleExpr
| UNARY_BIT_COMPLEMENT simpleExpr
| NOT_ simpleExpr
| BINARY simpleExpr
| LP_ expr RP_
| ROW LP_ simpleExpr( COMMA simpleExpr)* RP_
| subquery
| EXISTS subquery
// | (identifier expr)
//| match_expr
//| case_expr
// | interval_expr
|privateExprOfDb
;
functionCall
: ID LP_( bitExprs?) RP_
;
privateExprOfDb
: matchNone
;
liter
: QUESTION
| NUMBER
| TRUE
| FALSE
| NULL
| LBE_ ID STRING RBE_
| HEX_DIGIT
| ID? STRING collateClause?
| (DATE | TIME |TIMESTAMP) STRING
| ID? BIT_NUM collateClause?
;
subquery
: matchNone
;
collateClause
: matchNone
;
orderByClause
: ORDER BY groupByItem (COMMA groupByItem)*
;
groupByItem
: (columnName | NUMBER |expr) (ASC|DESC)?
;
|
//rule in this file does not allow override
grammar BaseRule;
import DataType,Keyword,Symbol;
ID:
(BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_? DOT)?
(BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_?)
|[a-zA-Z_$0-9]+ DOT ASTERISK
;
schemaName: ID;
tableName: ID;
columnName: ID;
tablespaceName: ID;
collationName: STRING | ID;
indexName: ID;
alias: ID;
cteName:ID;
parserName: ID;
extensionName: ID;
rowName: ID;
opclass: ID;
fileGroup: ID;
groupName: ID;
constraintName: ID;
keyName: ID;
typeName: ID;
xmlSchemaCollection:ID;
columnSetName: ID;
directoryName: ID;
triggerName: ID;
roleName: ID;
partitionName: ID;
rewriteRuleName: ID;
ownerName: ID;
userName: ID;
ifExists
: IF EXISTS;
ifNotExists
: IF NOT EXISTS;
dataTypeLength
: LP_ (NUMBER (COMMA NUMBER)?)? RP_
;
nullNotnull
: NULL
| NOT NULL
;
primaryKey
: PRIMARY? KEY
;
matchNone
: 'Default does not match anything'
;
ids
: ID (COMMA ID)*
;
idList
: LP_ ids RP_
;
rangeClause
: NUMBER (COMMA NUMBER)*
| NUMBER OFFSET NUMBER
;
tableNamesWithParen
: LP_ tableNames RP_
;
tableNames
: tableName (COMMA tableName)*
;
columnNamesWithParen
: LP_ columnNames RP_
;
columnNames
: columnName (COMMA columnName)*
;
columnList
: LP_ columnNames RP_
;
indexNames
: indexName (COMMA indexName)*
;
rowNames
: rowName (COMMA rowName)*
;
roleNames
: roleName (COMMA roleName)*
;
userNames
: userName (COMMA userName)*
;
bitExprs:
bitExpr (COMMA bitExpr)*
;
exprs
: expr (COMMA expr)*
;
exprsWithParen
: LP_ exprs RP_
;
//https://dev.mysql.com/doc/refman/8.0/en/expressions.html
expr
: expr OR expr
| expr OR_ expr
| expr XOR expr
| expr AND expr
| expr AND_ expr
| LP_ expr RP_
| NOT expr
| NOT_ expr
| booleanPrimary
| exprRecursive
;
exprRecursive
: matchNone
;
booleanPrimary
: booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL)
| booleanPrimary SAFE_EQ predicate
| booleanPrimary comparisonOperator predicate
| booleanPrimary comparisonOperator (ALL | ANY) subquery
| predicate
;
comparisonOperator
: EQ_
| GTE
| GT
| LTE
| LT
| NEQ_
| NEQ
;
predicate
: bitExpr NOT? IN subquery
| bitExpr NOT? IN LP_ simpleExpr ( COMMA simpleExpr)* RP_
| bitExpr NOT? BETWEEN simpleExpr AND predicate
| bitExpr SOUNDS LIKE simpleExpr
| bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)*
| bitExpr NOT? REGEXP simpleExpr
| bitExpr
;
bitExpr
: bitExpr BIT_INCLUSIVE_OR bitExpr
| bitExpr BIT_AND bitExpr
| bitExpr SIGNED_LEFT_SHIFT bitExpr
| bitExpr SIGNED_RIGHT_SHIFT bitExpr
| bitExpr PLUS bitExpr
| bitExpr MINUS bitExpr
| bitExpr ASTERISK bitExpr
| bitExpr SLASH bitExpr
| bitExpr MOD bitExpr
| bitExpr MOD_ bitExpr
| bitExpr BIT_EXCLUSIVE_OR bitExpr
//| bitExpr '+' interval_expr
//| bitExpr '-' interval_expr
| simpleExpr
;
simpleExpr
: functionCall
| liter
| ID
| simpleExpr collateClause
//| param_marker
//| variable
| simpleExpr AND_ simpleExpr
| PLUS simpleExpr
| MINUS simpleExpr
| UNARY_BIT_COMPLEMENT simpleExpr
| NOT_ simpleExpr
| BINARY simpleExpr
| LP_ expr RP_
| ROW LP_ simpleExpr( COMMA simpleExpr)* RP_
| subquery
| EXISTS subquery
// | (identifier expr)
//| match_expr
//| case_expr
// | interval_expr
|privateExprOfDb
;
functionCall
: ID LP_( bitExprs?) RP_
;
privateExprOfDb
: matchNone
;
liter
: QUESTION
| NUMBER
| TRUE
| FALSE
| NULL
| LBE_ ID STRING RBE_
| HEX_DIGIT
| ID? STRING collateClause?
| (DATE | TIME |TIMESTAMP) STRING
| ID? BIT_NUM collateClause?
;
subquery
: matchNone
;
collateClause
: matchNone
;
orderByClause
: ORDER BY groupByItem (COMMA groupByItem)*
;
groupByItem
: (columnName | NUMBER |expr) (ASC|DESC)?
;
|
add ids
|
add ids
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
|
6daabbd569648c693396ada8d3f986e80f07a439
|
sharding-jdbc-ddl-parser/src/main/antlr4/imports/Symbol.g4
|
sharding-jdbc-ddl-parser/src/main/antlr4/imports/Symbol.g4
|
lexer grammar Symbol;
AND_SYM: '&&';
OR_SYM: '||';
NOT_SYM: '!';
UNARY_BIT_COMPLEMENT: '~';
BIT_INCLUSIVE_OR: '|';
BIT_AND: '&';
SIGNED_LEFT_SHIFT: '<<';
SIGNED_RIGHT_SHIFT: '>>';
BIT_EXCLUSIVE_OR: '^';
MOD_SYM: '%';
PLUS: '+' ;
MINUS: '-' ;
ASTERISK: '*' ;
SLASH: '/' ;
DOT: '.';
SAFE_EQ: '<=>';
EQ: '==';
EQ_OR_ASSIGN: '=';
NEQ: '!=';
NEQ_SYM: '<>';
GT: '>';
GTE: '>=';
LT: '<' ;
LTE: '<=' ;
LEFT_PAREN: '(';
RIGHT_PAREN: ')';
LEFT_BRACE: '{';
RIGHT_BRACE: '}';
COMMA: ',';
DOUBLE_QUOTA: '"';
SINGLE_QUOTA: '\'';
BACK_QUOTA: '`';
UL_: '_';
QUESTION: '?' ;
fragment A: [Aa];
fragment B: [Bb];
fragment C: [Cc];
fragment D: [Dd];
fragment E: [Ee];
fragment F: [Ff];
fragment G: [Gg];
fragment H: [Hh];
fragment I: [Ii];
fragment J: [Jj];
fragment K: [Kk];
fragment L: [Ll];
fragment M: [Mm];
fragment N: [Nn];
fragment O: [Oo];
fragment P: [Pp];
fragment Q: [Qq];
fragment R: [Rr];
fragment S: [Ss];
fragment T: [Tt];
fragment U: [Uu];
fragment V: [Vv];
fragment W: [Ww];
fragment X: [Xx];
fragment Y: [Yy];
fragment Z: [Zz];
|
lexer grammar Symbol;
AND_SYM: '&&';
OR_SYM: '||';
NOT_SYM: '!';
UNARY_BIT_COMPLEMENT: '~';
BIT_INCLUSIVE_OR: '|';
BIT_AND: '&';
SIGNED_LEFT_SHIFT: '<<';
SIGNED_RIGHT_SHIFT: '>>';
BIT_EXCLUSIVE_OR: '^';
MOD_SYM: '%';
COLON:':';
PLUS: '+' ;
MINUS: '-' ;
ASTERISK: '*' ;
SLASH: '/' ;
DOT: '.';
SAFE_EQ: '<=>';
EQ: '==';
EQ_OR_ASSIGN: '=';
NEQ: '!=';
NEQ_SYM: '<>';
GT: '>';
GTE: '>=';
LT: '<' ;
LTE: '<=' ;
LEFT_PAREN: '(';
RIGHT_PAREN: ')';
LEFT_BRACE: '{';
RIGHT_BRACE: '}';
LEFT_BRACKET:'[';
RIGHT_BRACKET:']';
COMMA: ',';
DOUBLE_QUOTA: '"';
SINGLE_QUOTA: '\'';
BACK_QUOTA: '`';
UL_: '_';
QUESTION: '?' ;
fragment A: [Aa];
fragment B: [Bb];
fragment C: [Cc];
fragment D: [Dd];
fragment E: [Ee];
fragment F: [Ff];
fragment G: [Gg];
fragment H: [Hh];
fragment I: [Ii];
fragment J: [Jj];
fragment K: [Kk];
fragment L: [Ll];
fragment M: [Mm];
fragment N: [Nn];
fragment O: [Oo];
fragment P: [Pp];
fragment Q: [Qq];
fragment R: [Rr];
fragment S: [Ss];
fragment T: [Tt];
fragment U: [Uu];
fragment V: [Vv];
fragment W: [Ww];
fragment X: [Xx];
fragment Y: [Yy];
fragment Z: [Zz];
|
add symbol ':' '[' ']'
|
add symbol ':' '[' ']'
|
ANTLR
|
apache-2.0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
|
da327595f8ae239932c1c650bd65a34e7f80c447
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/BaseRule.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/BaseRule.g4
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar BaseRule;
import Symbol, Keyword, MySQLKeyword, Literals;
parameterMarker
: QUESTION_
;
literals
: stringLiterals
| numberLiterals
| dateTimeLiterals
| hexadecimalLiterals
| bitValueLiterals
| booleanLiterals
| nullValueLiterals
;
stringLiterals
: characterSetName_? STRING_ collateClause_?
;
numberLiterals
: MINUS_? NUMBER_
;
dateTimeLiterals
: (DATE | TIME | TIMESTAMP) STRING_
| LBE_ identifier_ STRING_ RBE_
;
hexadecimalLiterals
: characterSetName_? HEX_DIGIT_ collateClause_?
;
bitValueLiterals
: characterSetName_? BIT_NUM_ collateClause_?
;
booleanLiterals
: TRUE | FALSE
;
nullValueLiterals
: NULL
;
identifier_
: IDENTIFIER_ | unreservedWord_
;
variable_
: (AT_? AT_)? (GLOBAL | PERSIST | PERSIST_ONLY | SESSION)? DOT_? identifier_
;
scope_
: (GLOBAL | PERSIST | PERSIST_ONLY | SESSION)
| AT_ AT_ (GLOBAL | PERSIST | PERSIST_ONLY | SESSION) DOT_
;
unreservedWord_
: ACCOUNT | ACTION | AFTER | ALGORITHM | ALWAYS | ANY | AUTO_INCREMENT
| AVG_ROW_LENGTH | BEGIN | BTREE | CHAIN | CHARSET | CHECKSUM | CIPHER
| CLIENT | COALESCE | COLUMNS | COLUMN_FORMAT | COMMENT | COMMIT | COMMITTED
| COMPACT | COMPRESSED | COMPRESSION | CONNECTION | CONSISTENT | CURRENT | DATA
| DATE | DELAY_KEY_WRITE | DISABLE | DISCARD | DISK | DUPLICATE | ENABLE
| ENCRYPTION | ENFORCED | END | ENGINE | ESCAPE | EVENT | EXCHANGE
| EXECUTE | FILE | FIRST | FIXED | FOLLOWING | GLOBAL | HASH
| IMPORT_ | INSERT_METHOD | INVISIBLE | KEY_BLOCK_SIZE | LAST | LESS
| LEVEL | MAX_ROWS | MEMORY | MIN_ROWS | MODIFY | NO | NONE | OFFSET
| PACK_KEYS | PARSER | PARTIAL | PARTITIONING | PASSWORD | PERSIST | PERSIST_ONLY
| PRECEDING | PRIVILEGES | PROCESS | PROXY | QUICK | REBUILD | REDUNDANT
| RELOAD | REMOVE | REORGANIZE | REPAIR | REVERSE | ROLLBACK | ROLLUP
| ROW_FORMAT | SAVEPOINT | SESSION | SHUTDOWN | SIMPLE | SLAVE | SOUNDS
| SQL_BIG_RESULT | SQL_BUFFER_RESULT | SQL_CACHE | SQL_NO_CACHE | START | STATS_AUTO_RECALC | STATS_PERSISTENT
| STATS_SAMPLE_PAGES | STORAGE | SUBPARTITION | SUPER | TABLES | TABLESPACE | TEMPORARY
| THAN | TIME | TIMESTAMP | TRANSACTION | TRUNCATE | UNBOUNDED | UNKNOWN
| UPGRADE | VALIDATION | VALUE | VIEW | VISIBLE | WEIGHT_STRING | WITHOUT
| MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH
| QUARTER | YEAR | AGAINST | LANGUAGE | MODE | QUERY | EXPANSION
| BOOLEAN | MAX | MIN | SUM | COUNT | AVG | BIT_AND
| BIT_OR | BIT_XOR | GROUP_CONCAT | JSON_ARRAYAGG | JSON_OBJECTAGG | STD | STDDEV
| STDDEV_POP | STDDEV_SAMP | VAR_POP | VAR_SAMP | VARIANCE | EXTENDED | STATUS
| FIELDS | INDEXES | USER | ROLE | OJ | AUTOCOMMIT | OFF | ROTATE | INSTANCE | MASTER | BINLOG |ERROR
| SCHEDULE | COMPLETION | DO | DEFINER | START | EVERY | HOST | SOCKET | OWNER | PORT | RETURNS | CONTAINS
| SECURITY | INVOKER | UNDEFINED | MERGE | TEMPTABLE | CASCADED | LOCAL | SERVER | WRAPPER | OPTIONS | DATAFILE
| FILE_BLOCK_SIZE | EXTENT_SIZE | INITIAL_SIZE | AUTOEXTEND_SIZE | MAX_SIZE | NODEGROUP
| WAIT | LOGFILE | UNDOFILE | UNDO_BUFFER_SIZE | REDO_BUFFER_SIZE | DEFINITION | ORGANIZATION
| DESCRIPTION | REFERENCE | FOLLOWS | PRECEDES | NAME |CLOSE | OPEN | NEXT | HANDLER | PREV
| IMPORT | CONCURRENT | XML | POSITION | SHARE | DUMPFILE | CLONE | AGGREGATE | INSTALL | UNINSTALL
| RESOURCE | FLUSH | RESET | RESTART | HOSTS | RELAY | EXPORT | USER_RESOURCES | SLOW | GENERAL | CACHE
| SUBJECT | ISSUER | OLD | RANDOM | RETAIN | MAX_USER_CONNECTIONS | MAX_CONNECTIONS_PER_HOUR | MAX_UPDATES_PER_HOUR
| MAX_QUERIES_PER_HOUR | REUSE | OPTIONAL | HISTORY | NEVER | EXPIRE | TYPE | UNIX_TIMESTAMP | LOWER | UPPER | CONTEXT
;
schemaName
: identifier_
;
tableName
: (owner DOT_)? name
;
columnName
: (owner DOT_)? name
;
userName
: STRING_ AT_ STRING_
| 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_
;
groupName
: IDENTIFIER_
;
shardLibraryName
: STRING_
;
componentName
: STRING_
;
pluginName
: IDENTIFIER_
;
hostName
: STRING_
;
port
: NUMBER_
;
cloneInstance
: userName AT_ hostName COLON_ port
;
cloneDir
: IDENTIFIER_
;
channelName
: IDENTIFIER_
;
logName
: identifier_
;
roleName
: (STRING_ | IDENTIFIER_) AT_ (STRING_ IDENTIFIER_) | IDENTIFIER_
;
engineName
: IDENTIFIER_
;
triggerName
: IDENTIFIER_
;
triggerTime
: BEFORE | AFTER
;
userOrRole
: userName | roleName
;
partitionName
: IDENTIFIER_
;
triggerEvent
: INSERT | UPDATE | DELETE
;
triggerOrder
: (FOLLOWS | PRECEDES) triggerName
;
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_ | valuesFunction_
;
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_
;
valuesFunction_
: VALUES LP_ columnName 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 | LEFT | RIGHT
| LOWER | UNIX_TIMESTAMP | UPPER
;
matchExpression_
: MATCH columnNames AGAINST (expr matchSearchModifier_?)
;
matchSearchModifier_
: IN NATURAL LANGUAGE MODE | IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION | IN BOOLEAN MODE | WITH QUERY EXPANSION
;
caseExpression_
: CASE simpleExpr? caseWhen_+ caseElse_? END
;
caseWhen_
: WHEN expr THEN expr
;
caseElse_
: ELSE expr
;
intervalExpression_
: INTERVAL expr intervalUnit_
;
intervalUnit_
: MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH
| QUARTER | YEAR | SECOND_MICROSECOND | MINUTE_MICROSECOND | MINUTE_SECOND | HOUR_MICROSECOND | HOUR_SECOND
| HOUR_MINUTE | DAY_MICROSECOND | DAY_SECOND | DAY_MINUTE | DAY_HOUR | YEAR_MONTH
;
subquery
: 'Default does not match anything'
;
orderByClause
: ORDER BY orderByItem (COMMA_ orderByItem)*
;
orderByItem
: (columnName | numberLiterals | expr) (ASC | DESC)?
;
dataType
: dataTypeName_ dataTypeLength? characterSet_? collateClause_? UNSIGNED? ZEROFILL? | dataTypeName_ LP_ STRING_ (COMMA_ STRING_)* RP_ characterSet_? collateClause_?
;
dataTypeName_
: identifier_ identifier_?
;
dataTypeLength
: LP_ NUMBER_ (COMMA_ NUMBER_)? RP_
;
characterSet_
: (CHARACTER | CHAR) SET EQ_? ignoredIdentifier_
;
collateClause_
: COLLATE EQ_? (STRING_ | ignoredIdentifier_)
;
ignoredIdentifier_
: identifier_ (DOT_ identifier_)?
;
ignoredIdentifiers_
: ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar BaseRule;
import Symbol, Keyword, MySQLKeyword, Literals;
parameterMarker
: QUESTION_
;
literals
: stringLiterals
| numberLiterals
| dateTimeLiterals
| hexadecimalLiterals
| bitValueLiterals
| booleanLiterals
| nullValueLiterals
;
stringLiterals
: characterSetName_? STRING_ collateClause_?
;
numberLiterals
: MINUS_? NUMBER_
;
dateTimeLiterals
: (DATE | TIME | TIMESTAMP) STRING_
| LBE_ identifier_ STRING_ RBE_
;
hexadecimalLiterals
: characterSetName_? HEX_DIGIT_ collateClause_?
;
bitValueLiterals
: characterSetName_? BIT_NUM_ collateClause_?
;
booleanLiterals
: TRUE | FALSE
;
nullValueLiterals
: NULL
;
identifier_
: IDENTIFIER_ | unreservedWord_
;
variable_
: (AT_? AT_)? (GLOBAL | PERSIST | PERSIST_ONLY | SESSION)? DOT_? identifier_
;
scope_
: (GLOBAL | PERSIST | PERSIST_ONLY | SESSION)
| AT_ AT_ (GLOBAL | PERSIST | PERSIST_ONLY | SESSION) DOT_
;
unreservedWord_
: ACCOUNT | ACTION | AFTER | ALGORITHM | ALWAYS | ANY | AUTO_INCREMENT
| AVG_ROW_LENGTH | BEGIN | BTREE | CHAIN | CHARSET | CHECKSUM | CIPHER
| CLIENT | COALESCE | COLUMNS | COLUMN_FORMAT | COMMENT | COMMIT | COMMITTED
| COMPACT | COMPRESSED | COMPRESSION | CONNECTION | CONSISTENT | CURRENT | DATA
| DATE | DELAY_KEY_WRITE | DISABLE | DISCARD | DISK | DUPLICATE | ENABLE
| ENCRYPTION | ENFORCED | END | ENGINE | ESCAPE | EVENT | EXCHANGE
| EXECUTE | FILE | FIRST | FIXED | FOLLOWING | GLOBAL | HASH
| IMPORT_ | INSERT_METHOD | INVISIBLE | KEY_BLOCK_SIZE | LAST | LESS
| LEVEL | MAX_ROWS | MEMORY | MIN_ROWS | MODIFY | NO | NONE | OFFSET
| PACK_KEYS | PARSER | PARTIAL | PARTITIONING | PASSWORD | PERSIST | PERSIST_ONLY
| PRECEDING | PRIVILEGES | PROCESS | PROXY | QUICK | REBUILD | REDUNDANT
| RELOAD | REMOVE | REORGANIZE | REPAIR | REVERSE | ROLLBACK | ROLLUP
| ROW_FORMAT | SAVEPOINT | SESSION | SHUTDOWN | SIMPLE | SLAVE | SOUNDS
| SQL_BIG_RESULT | SQL_BUFFER_RESULT | SQL_CACHE | SQL_NO_CACHE | START | STATS_AUTO_RECALC | STATS_PERSISTENT
| STATS_SAMPLE_PAGES | STORAGE | SUBPARTITION | SUPER | TABLES | TABLESPACE | TEMPORARY
| THAN | TIME | TIMESTAMP | TRANSACTION | TRUNCATE | UNBOUNDED | UNKNOWN
| UPGRADE | VALIDATION | VALUE | VIEW | VISIBLE | WEIGHT_STRING | WITHOUT
| MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH
| QUARTER | YEAR | AGAINST | LANGUAGE | MODE | QUERY | EXPANSION
| BOOLEAN | MAX | MIN | SUM | COUNT | AVG | BIT_AND
| BIT_OR | BIT_XOR | GROUP_CONCAT | JSON_ARRAYAGG | JSON_OBJECTAGG | STD | STDDEV
| STDDEV_POP | STDDEV_SAMP | VAR_POP | VAR_SAMP | VARIANCE | EXTENDED | STATUS
| FIELDS | INDEXES | USER | ROLE | OJ | AUTOCOMMIT | OFF | ROTATE | INSTANCE | MASTER | BINLOG |ERROR
| SCHEDULE | COMPLETION | DO | DEFINER | START | EVERY | HOST | SOCKET | OWNER | PORT | RETURNS | CONTAINS
| SECURITY | INVOKER | UNDEFINED | MERGE | TEMPTABLE | CASCADED | LOCAL | SERVER | WRAPPER | OPTIONS | DATAFILE
| FILE_BLOCK_SIZE | EXTENT_SIZE | INITIAL_SIZE | AUTOEXTEND_SIZE | MAX_SIZE | NODEGROUP
| WAIT | LOGFILE | UNDOFILE | UNDO_BUFFER_SIZE | REDO_BUFFER_SIZE | DEFINITION | ORGANIZATION
| DESCRIPTION | REFERENCE | FOLLOWS | PRECEDES | NAME |CLOSE | OPEN | NEXT | HANDLER | PREV
| IMPORT | CONCURRENT | XML | POSITION | SHARE | DUMPFILE | CLONE | AGGREGATE | INSTALL | UNINSTALL
| RESOURCE | FLUSH | RESET | RESTART | HOSTS | RELAY | EXPORT | USER_RESOURCES | SLOW | GENERAL | CACHE
| SUBJECT | ISSUER | OLD | RANDOM | RETAIN | MAX_USER_CONNECTIONS | MAX_CONNECTIONS_PER_HOUR | MAX_UPDATES_PER_HOUR
| MAX_QUERIES_PER_HOUR | REUSE | OPTIONAL | HISTORY | NEVER | EXPIRE | TYPE | UNIX_TIMESTAMP | LOWER | UPPER | CONTEXT
| CODE
;
schemaName
: identifier_
;
tableName
: (owner DOT_)? name
;
columnName
: (owner DOT_)? name
;
userName
: STRING_ AT_ STRING_
| 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_
;
groupName
: IDENTIFIER_
;
shardLibraryName
: STRING_
;
componentName
: STRING_
;
pluginName
: IDENTIFIER_
;
hostName
: STRING_
;
port
: NUMBER_
;
cloneInstance
: userName AT_ hostName COLON_ port
;
cloneDir
: IDENTIFIER_
;
channelName
: IDENTIFIER_
;
logName
: identifier_
;
roleName
: (STRING_ | IDENTIFIER_) AT_ (STRING_ IDENTIFIER_) | IDENTIFIER_
;
engineName
: IDENTIFIER_
;
triggerName
: IDENTIFIER_
;
triggerTime
: BEFORE | AFTER
;
userOrRole
: userName | roleName
;
partitionName
: IDENTIFIER_
;
triggerEvent
: INSERT | UPDATE | DELETE
;
triggerOrder
: (FOLLOWS | PRECEDES) triggerName
;
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_ | valuesFunction_
;
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_
;
valuesFunction_
: VALUES LP_ columnName 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 | LEFT | RIGHT
| LOWER | UNIX_TIMESTAMP | UPPER
;
matchExpression_
: MATCH columnNames AGAINST (expr matchSearchModifier_?)
;
matchSearchModifier_
: IN NATURAL LANGUAGE MODE | IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION | IN BOOLEAN MODE | WITH QUERY EXPANSION
;
caseExpression_
: CASE simpleExpr? caseWhen_+ caseElse_? END
;
caseWhen_
: WHEN expr THEN expr
;
caseElse_
: ELSE expr
;
intervalExpression_
: INTERVAL expr intervalUnit_
;
intervalUnit_
: MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH
| QUARTER | YEAR | SECOND_MICROSECOND | MINUTE_MICROSECOND | MINUTE_SECOND | HOUR_MICROSECOND | HOUR_SECOND
| HOUR_MINUTE | DAY_MICROSECOND | DAY_SECOND | DAY_MINUTE | DAY_HOUR | YEAR_MONTH
;
subquery
: 'Default does not match anything'
;
orderByClause
: ORDER BY orderByItem (COMMA_ orderByItem)*
;
orderByItem
: (columnName | numberLiterals | expr) (ASC | DESC)?
;
dataType
: dataTypeName_ dataTypeLength? characterSet_? collateClause_? UNSIGNED? ZEROFILL? | dataTypeName_ LP_ STRING_ (COMMA_ STRING_)* RP_ characterSet_? collateClause_?
;
dataTypeName_
: identifier_ identifier_?
;
dataTypeLength
: LP_ NUMBER_ (COMMA_ NUMBER_)? RP_
;
characterSet_
: (CHARACTER | CHAR) SET EQ_? ignoredIdentifier_
;
collateClause_
: COLLATE EQ_? (STRING_ | ignoredIdentifier_)
;
ignoredIdentifier_
: identifier_ (DOT_ identifier_)?
;
ignoredIdentifiers_
: ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*
;
|
Fix faill insert code colum (#3417)
|
Fix faill insert code colum (#3417)
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
|
c9c168ecb9cc3d2815aa3d108cb2afbcec1dac74
|
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 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
;
constraint_operator
: GREATER_THAN
| LESS_THAN
| GREATER_THAN_OR_EQUAL
| LESS_THAN_OR_EQUAL
| EQUAL_TO
;
constraint_literal
: INTEGER_LITERAL
;
constraint_predicate
: constraint_operator CONSTRAINT_INLINE_WS constraint_literal
;
constraint_expression
: constraint_predicate
| NEGATION 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
;
implementationSpec
: (VALUE | BEAN ) INLINE_WS Identifier (INLINE_WS EXTENDS INLINE_WS Identifier)? (INLINE_WS StringLiteral)? LINE_BREAK
(INLINE_WS? props)?
(INLINE_WS? opts)?
;
typeSpec
: TYPE INLINE_WS Identifier (INLINE_WS StringLiteral)? LINE_BREAK
(INLINE_WS? props)?
;
author
: AUTHOR INLINE_WS StringLiteral
;
spec
: LINE_BREAK*
(author LINE_BREAK+)?
package_name LINE_BREAK+
(imports LINE_BREAK*)?
((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 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
;
constraint_operator
: GREATER_THAN
| LESS_THAN
| GREATER_THAN_OR_EQUAL
| LESS_THAN_OR_EQUAL
| EQUAL_TO
;
constraint_literal
: INTEGER_LITERAL
;
constraint_predicate
: constraint_operator CONSTRAINT_INLINE_WS constraint_literal
;
constraint_expression
: constraint_predicate
| NEGATION 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
;
implementationSpec
: (VALUE | BEAN ) INLINE_WS Identifier (INLINE_WS EXTENDS INLINE_WS Identifier)? (INLINE_WS StringLiteral)? LINE_BREAK
(INLINE_WS? props)?
(INLINE_WS? opts)?
;
typeSpec
: TYPE INLINE_WS Identifier (INLINE_WS StringLiteral)? LINE_BREAK
(INLINE_WS? props)?
;
author
: AUTHOR INLINE_WS StringLiteral
;
spec
: LINE_BREAK*
(author LINE_BREAK+)?
package_name LINE_BREAK+
(imports LINE_BREAK*)?
((typeSpec | implementationSpec) LINE_BREAK*)+
;
|
Make whitespace following opening and preceding closing parenthesis optional.
|
Make whitespace following opening and preceding closing parenthesis optional.
|
ANTLR
|
bsd-3-clause
|
mattunderscorechampion/specky,mattunderscorechampion/specky,mattunderscorechampion/specky
|
441d48d811aca394ce29aa2219eb5df155d4ca06
|
src/main/antlr/BrygLexer.g4
|
src/main/antlr/BrygLexer.g4
|
/**
* Thanks to
* https://github.com/antlr/grammars-v4/blob/master/python3/Python3.g4
* for the base of an indentation-sensitive lexer in ANTLR!
*/
lexer grammar BrygLexer;
@header {
package io.collap.bryg.parser;
}
tokens { INDENT, DEDENT }
@lexer::members {
// A queue where extra tokens are pushed on (see the NEWLINE lexer rule).
private java.util.Queue<Token> tokens = new java.util.LinkedList<> ();
// The stack that keeps track of the indentation level.
private java.util.Stack<Integer> indents = new java.util.Stack<Integer> () {
{
push (0);
}
};
// The amount of opened braces, brackets and parenthesis.
private int opened = 0;
private String currentBlockString = null; // TODO: Make this a StringBuilder for improved performance!
@Override
public void emit(Token t) {
super.setToken(t);
if (t instanceof CommonToken) {
((CommonToken) t).setLine (getLine ());
}
tokens.offer(t);
}
@Override
public Token nextToken() {
// Check if the end-of-file is ahead and there are still some DEDENTS expected.
if (_input.LA(1) == EOF && !this.indents.isEmpty()) {
// First emit an extra line break that serves as the end of the statement.
this.emit(new CommonToken(NEWLINE, "NEWLINE"));
// Now emit as much DEDENT tokens until we reach the leftmost column.
dedent (0);
}
Token next = super.nextToken();
return tokens.isEmpty() ? next : tokens.poll();
}
// Calculates the indentation of the provided spaces, taking the
// following rules into account:
//
// "Tabs are replaced (from left to right) by one to eight spaces
// such that the total number of characters up to and including
// the replacement is a multiple of eight [...]"
//
// -- https://docs.python.org/3.1/reference/lexical_analysis.html#indentation
static int getIndentationCount(String spaces) {
int count = 0;
// TODO: Mark tabs as syntax error!
for (char ch : spaces.toCharArray()) {
switch (ch) {
case '\t':
count += 8 - (count % 8);
break;
default:
// A normal space char.
count++;
}
}
return count;
}
/**
* Pops indents from the stack until 'indent' is reached.
* Also emits DEDENT tokens if shouldEmit is true.
*/
private void dedent (int indent) {
while (!indents.isEmpty () && indents.peek () > indent) {
emit (new CommonToken (DEDENT, "DEDENT"));
indents.pop ();
}
}
private String[] splitTextAndSpaces (String input) {
return input.split ("\r?\n|\r");
}
private void handlePossibleBlockStringDedent (int indent) {
/* Check if the current line is a blank line. If it is, ignore the dedent. */
int next = _input.LA (1);
if (next != '\n' && next != '\r') {
if (next == EOF) {
indent = 0; /* Dedent everything. */
}
/* Remove \n and/or \r from block string end. */
int end = currentBlockString.length ();
char lastChar = currentBlockString.charAt (end - 1);
if (lastChar == '\n') {
end -= 1;
if (currentBlockString.charAt (end - 1) == '\r') {
end -= 1;
}
}else if (lastChar == '\r') {
end -= 1;
}
if (end != currentBlockString.length ()) {
currentBlockString = currentBlockString.substring (0, end);
}
/* Close block string. */
emit (new CommonToken (String, currentBlockString));
emit (new CommonToken (NEWLINE, "NEWLINE")); /* As a block string counts as a string, much
like a string on a single line, a NEWLINE
token must be emitted after it. */
indents.pop (); /* Pop the indent corresponding to the block string. */
dedent (indent); /* Dedent the rest if applicable. */
popMode ();
}
}
private boolean isNextCharNewlineOrEOF () {
int next = _input.LA (1);
return next == '\n' || next == '\r' || next == EOF;
}
}
//
// Keywords
//
NOT : 'not';
AND : 'and';
OR : 'or';
IN : 'in';
OPT : 'opt';
IS : 'is';
EACH : 'each';
WHILE : 'while';
ELSE : 'else';
IF : 'if';
MUT : 'mut';
VAL : 'val';
NULL : 'null';
TRUE : 'true';
FALSE : 'false';
Identifier
: Letter
(Letter | Number)*
;
Float
: Number+ ('.' Number+)? ('f' | 'F')
;
Double
: Number+ '.' Number+
;
Integer
: Number+
;
String
: '\'' ('\\\'' | ~('\'' | '\n' | '\r'))* '\''
{
/* The block is needed so the namespace is not polluted. */
{
/* Remove single quotations. */
String string = getText ();
setText (string.substring (1, string.length () - 1));
}
}
| ':' (' ')* (~('\n' | '\r' | ' ')) (~('\n' | '\r'))*
{
{
/* Remove colon and trim string. */
String string = getText ();
setText (string.substring (1).trim ());
}
}
;
BlockString
: ':' (NewlineChar SPACES?)+ // Newline and spaces can occur more than once to account for blank lines.
{
/* Measure indentation. Only if the indentation is greater in the next line is the block string valid! */
boolean isValidBlockString = false;
String[] fragments = splitTextAndSpaces (getText ());
if (fragments.length >= 2) {
String spaces = fragments[fragments.length - 1];
int indent = getIndentationCount (spaces);
int previous = indents.peek ();
if (indent > previous) {
isValidBlockString = true;
indents.push (indent);
}else if (indent < previous) {
/* This has to be taken care of, because the spaces are consumed in the token.
Otherwise we would possibly forget a DEDENT token. */
dedent (indent);
}
}
skip ();
if (isValidBlockString) {
currentBlockString = "";
pushMode (block_string);
}else {
/* Otherwise, emit a string token with an empty string.
This corresponds to the second alternative of String,
which has specifically been narrowed to allow the
BlockString token. A NEWLINE token has to be emitted as well,
after one was consumed. */
emit (new CommonToken (String, ""));
emit (new CommonToken (NEWLINE, "NEWLINE"));
}
}
;
NEWLINE
: NewlineChar SPACES?
{
String spaces = getText().replaceAll("[\r\n]+", ""); // TODO: Replace with faster algorithm!
int next = _input.LA(1);
if (opened > 0 || next == '\r' || next == '\n' || next == ';') {
// If we're inside a list or on a blank line, ignore all indents,
// dedents and line breaks.
skip();
}
else {
emit(new CommonToken(NEWLINE, "NEWLINE"));
int indent = getIndentationCount(spaces);
int previous = indents.peek();
if (indent == previous) {
// skip indents of the same size as the present indent-size
skip();
}
else if (indent > previous) {
indents.push(indent);
emit(new CommonToken(INDENT, "INDENT"));
}
else {
dedent (indent);
}
}
}
;
NewlineChar
: '\r'? '\n'
| '\r'
;
DOT : '.';
COMMA : ',';
COLON : ':';
BACKTICK : '`';
AT : '@';
QUEST : '?';
INC : '++';
DEC : '--';
PLUS : '+';
MINUS : '-';
MUL : '*';
DIV : '/';
REM : '%';
BNOT : '~';
BAND : '&';
BOR : '|';
BXOR : '^';
RGT : '>';
RGE : '>=';
RLT : '<';
RLE : '<=';
REQ : '==';
RNE : '!=';
REFEQ : '===';
REFNE : '!==';
SIG_LSHIFT : '<<';
SIG_RSHIFT : '>>';
UNSIG_RSHIFT : '>>>';
ASSIGN : '=';
ADD_ASSIGN : '+=';
SUB_ASSIGN : '-=';
MUL_ASSIGN : '*=';
DIV_ASSIGN : '/=';
REM_ASSIGN : '%=';
BAND_ASSIGN : '&=';
BOR_ASSIGN : '|=';
BXOR_ASSIGN : '^=';
SIG_LSHIFT_ASSIGN : '<<=';
SIG_RSHIFT_ASSIGN : '>>=';
UNSIG_RSHIFT_ASSIGN : '>>>=';
LPAREN : '(' { opened++; };
RPAREN : ')' { opened--; };
Skip
: (SPACES | COMMENT) -> skip
;
UnknownChar
: .
;
fragment
Letter
: ( LetterUpper
| LetterLower
)
;
fragment
LetterUpper
: [A-Z]
;
fragment
LetterLower
: [a-z]
;
fragment
Number
: [0-9]
;
fragment SPACES
: [ \t]+
;
fragment COMMENT
: ';' ~[\r\n]*
;
mode block_string;
Text
: (~('\n' | '\r'))* NewlineChar SPACES?
{
/* The strategy here:
- When a dedent is detected, a String token is emitted with the string content that was captured
and the mode is popped from the mode stack. Blank lines do not count towards dedents. No DEDENT
token is emitted.
- When the indent stays the same only the text is added.
- When the indent increases, no INDENT token is pushed, because the extra indent is counted
towards the string. */
String fullText = getText ();
String[] fragments = splitTextAndSpaces (fullText);
if (fragments.length == 2) {
String text = fragments[0];
String spaces = fragments[1];
/* Include \r and \n. */
currentBlockString += text + fullText.substring (text.length (), fullText.length () - spaces.length ());
/* Check indent. */
int indent = getIndentationCount (spaces);
int previous = indents.peek ();
if (indent > previous) {
/* Preserve indent, unless the line is a blank line. */
if (!isNextCharNewlineOrEOF ()) {
/* Append the actual text indentation. */
currentBlockString += spaces.substring (0, indent - previous);
}
}else if (indent < previous) {
handlePossibleBlockStringDedent (indent);
}
}else if (fragments.length == 1) {
currentBlockString += fragments[0];
handlePossibleBlockStringDedent (0);
}
skip ();
}
| (~('\n' | '\r'))+ // This case happens when the block string ends with EOF.
{
currentBlockString += getText ();
handlePossibleBlockStringDedent (0);
skip ();
}
;
|
/**
* Thanks to
* https://github.com/antlr/grammars-v4/blob/master/python3/Python3.g4
* for the base of an indentation-sensitive lexer in ANTLR!
*/
lexer grammar BrygLexer;
@header {
package io.collap.bryg.parser;
}
tokens { INDENT, DEDENT }
@lexer::members {
// A queue where extra tokens are pushed on (see the NEWLINE lexer rule).
private java.util.Queue<Token> tokens = new java.util.LinkedList<> ();
// The stack that keeps track of the indentation level.
private java.util.Stack<Integer> indents = new java.util.Stack<Integer> () {
{
push (0);
}
};
// The amount of opened braces, brackets and parenthesis.
private int opened = 0;
private String currentBlockString = null; // TODO: Make this a StringBuilder for improved performance!
@Override
public void emit(Token t) {
super.setToken(t);
if (t instanceof CommonToken) {
((CommonToken) t).setLine (getLine ());
}
tokens.offer(t);
}
@Override
public Token nextToken() {
// Check if the end-of-file is ahead and there are still some DEDENTS expected.
if (_input.LA(1) == EOF && !this.indents.isEmpty()) {
// First emit an extra line break that serves as the end of the statement.
this.emit(new CommonToken(NEWLINE, "NEWLINE"));
// Now emit as much DEDENT tokens until we reach the leftmost column.
dedent (0);
}
Token next = super.nextToken();
return tokens.isEmpty() ? next : tokens.poll();
}
// Calculates the indentation of the provided spaces, taking the
// following rules into account:
//
// "Tabs are replaced (from left to right) by one to eight spaces
// such that the total number of characters up to and including
// the replacement is a multiple of eight [...]"
//
// -- https://docs.python.org/3.1/reference/lexical_analysis.html#indentation
static int getIndentationCount(String spaces) {
int count = 0;
// TODO: Mark tabs as syntax error!
for (char ch : spaces.toCharArray()) {
switch (ch) {
case '\t':
count += 8 - (count % 8);
break;
default:
// A normal space char.
count++;
}
}
return count;
}
/**
* Pops indents from the stack until 'indent' is reached.
* Also emits DEDENT tokens if shouldEmit is true.
*/
private void dedent (int indent) {
while (!indents.isEmpty () && indents.peek () > indent) {
emit (new CommonToken (DEDENT, "DEDENT"));
indents.pop ();
}
}
private String[] splitTextAndSpaces (String input) {
return input.split ("\r?\n|\r");
}
private void handlePossibleBlockStringDedent (int indent) {
/* Check if the current line is a blank line. If it is, ignore the dedent. */
int next = _input.LA (1);
if (next != '\n' && next != '\r') {
if (next == EOF) {
indent = 0; /* Dedent everything. */
}
/* Remove \n and/or \r from block string end. */
int end = currentBlockString.length ();
char lastChar = currentBlockString.charAt (end - 1);
if (lastChar == '\n') {
end -= 1;
if (currentBlockString.charAt (end - 1) == '\r') {
end -= 1;
}
}else if (lastChar == '\r') {
end -= 1;
}
if (end != currentBlockString.length ()) {
currentBlockString = currentBlockString.substring (0, end);
}
/* Close block string. */
emit (new CommonToken (String, currentBlockString));
emit (new CommonToken (NEWLINE, "NEWLINE")); /* As a block string counts as a string, much
like a string on a single line, a NEWLINE
token must be emitted after it. */
indents.pop (); /* Pop the indent corresponding to the block string. */
dedent (indent); /* Dedent the rest if applicable. */
popMode ();
}
}
private boolean isNextCharNewlineOrEOF () {
int next = _input.LA (1);
return next == '\n' || next == '\r' || next == EOF;
}
}
//
// Keywords
//
NOT : 'not';
AND : 'and';
OR : 'or';
IN : 'in';
OPT : 'opt';
IS : 'is';
EACH : 'each';
WHILE : 'while';
ELSE : 'else';
IF : 'if';
MUT : 'mut';
VAL : 'val';
NULL : 'null';
TRUE : 'true';
FALSE : 'false';
Identifier
: Letter
(Letter | Number)*
;
Float
: Number+ ('.' Number+)? ('f' | 'F')
;
Double
: Number+ '.' Number+
;
Integer
: Number+
;
String
: '\'' ('\\\'' | ~('\'' | '\n' | '\r'))* '\''
{
/* The block is needed so the namespace is not polluted. */
{
/* Remove single quotations. */
String string = getText ();
setText (string.substring (1, string.length () - 1));
}
}
| ':' (' ')* (~('\n' | '\r' | ' ')) (~('\n' | '\r'))*
{
{
/* Remove colon and trim string. */
String string = getText ();
setText (string.substring (1).trim ());
}
}
;
BlockString
: ':' (NewlineChar SPACES?)+ // Newline and spaces can occur more than once to account for blank lines.
{
/* Measure indentation. Only if the indentation is greater in the next line is the block string valid! */
boolean isValidBlockString = false;
String[] fragments = splitTextAndSpaces (getText ());
if (fragments.length >= 2) {
String spaces = fragments[fragments.length - 1];
int indent = getIndentationCount (spaces);
int previous = indents.peek ();
if (indent > previous) {
isValidBlockString = true;
indents.push (indent);
}else if (indent < previous) {
/* This has to be taken care of, because the spaces are consumed in the token.
Otherwise we would possibly forget a DEDENT token. */
dedent (indent);
}
}
skip ();
if (isValidBlockString) {
currentBlockString = "";
pushMode (block_string);
}else {
/* Otherwise, emit a string token with an empty string.
This corresponds to the second alternative of String,
which has specifically been narrowed to allow the
BlockString token. A NEWLINE token has to be emitted as well,
after one was consumed. */
emit (new CommonToken (String, ""));
emit (new CommonToken (NEWLINE, "NEWLINE"));
}
}
;
NEWLINE
: NewlineChar SPACES?
{
String spaces = getText().replaceAll("[\r\n]+", ""); // TODO: Replace with faster algorithm!
int next = _input.LA(1);
if (opened > 0 || next == '\r' || next == '\n' || next == ';') {
// If we're inside a list or on a blank line, ignore all indents,
// dedents and line breaks.
skip();
}
else {
emit(new CommonToken(NEWLINE, "NEWLINE"));
int indent = getIndentationCount(spaces);
int previous = indents.peek();
if (indent == previous) {
// skip indents of the same size as the present indent-size
skip();
}
else if (indent > previous) {
indents.push(indent);
emit(new CommonToken(INDENT, "INDENT"));
}
else {
dedent (indent);
}
}
}
;
NewlineChar
: '\r'? '\n'
| '\r'
;
DOT : '.';
COMMA : ',';
COLON : ':';
BACKTICK : '`';
AT : '@';
QUEST : '?';
INC : '++';
DEC : '--';
PLUS : '+';
MINUS : '-';
MUL : '*';
DIV : '/';
REM : '%';
BNOT : '~';
BAND : '&';
BOR : '|';
BXOR : '^';
RGT : '>';
RGE : '>=';
RLT : '<';
RLE : '<=';
REQ : '==';
RNE : '!=';
REFEQ : '===';
REFNE : '!==';
SIG_LSHIFT : '<<';
SIG_RSHIFT : '>>';
UNSIG_RSHIFT : '>>>';
ASSIGN : '=';
ADD_ASSIGN : '+=';
SUB_ASSIGN : '-=';
MUL_ASSIGN : '*=';
DIV_ASSIGN : '/=';
REM_ASSIGN : '%=';
BAND_ASSIGN : '&=';
BOR_ASSIGN : '|=';
BXOR_ASSIGN : '^=';
SIG_LSHIFT_ASSIGN : '<<=';
SIG_RSHIFT_ASSIGN : '>>=';
UNSIG_RSHIFT_ASSIGN : '>>>=';
LPAREN : '(' { opened++; };
RPAREN : ')' { opened--; };
Skip
: (SPACES | COMMENT) -> skip
;
UnknownChar
: .
;
fragment
Letter
: ( LetterUpper
| LetterLower
)
;
fragment
LetterUpper
: [A-Z]
;
fragment
LetterLower
: [a-z]
;
fragment
Number
: [0-9]
;
fragment SPACES
: [ \t]+
;
fragment COMMENT
: ';' ~[\r\n]*
;
mode block_string;
Text
: (~('\n' | '\r'))* NewlineChar SPACES?
{
/* The strategy here:
- When a dedent is detected, a String token is emitted with the string content that was captured
and the mode is popped from the mode stack. Blank lines do not count towards dedents. No DEDENT
token is emitted.
- When the indent stays the same only the text is added.
- When the indent increases, no INDENT token is pushed, because the extra indent is counted
towards the string. */
String fullText = getText ();
String[] fragments = splitTextAndSpaces (fullText);
if (fragments.length == 2) { /* Newline and spaces. */
String text = fragments[0];
String spaces = fragments[1];
/* Include \r and \n. */
currentBlockString += text + fullText.substring (text.length (), fullText.length () - spaces.length ());
/* Check indent. */
int indent = getIndentationCount (spaces);
int previous = indents.peek ();
if (indent > previous) {
/* Preserve indent, unless the line is a blank line. */
if (!isNextCharNewlineOrEOF ()) {
/* Append the actual text indentation. */
currentBlockString += spaces.substring (0, indent - previous);
}
}else if (indent < previous) {
handlePossibleBlockStringDedent (indent);
}
}else if (fragments.length == 1) { /* Only text without spaces. */
currentBlockString += fragments[0];
handlePossibleBlockStringDedent (0);
}else {
/* When no tokens are found, the next line is either blank or
a proper dedented line. In the latter case, the block string
needs to be closed. */
handlePossibleBlockStringDedent (0);
}
skip ();
}
| (~('\n' | '\r'))+ // This case happens when the block string ends with EOF.
{
currentBlockString += getText ();
handlePossibleBlockStringDedent (0);
skip ();
}
;
|
Fix block strings not being closed on a blank line before a proper line with no indent.
|
Fix block strings not being closed on a blank line before a proper line with no indent.
|
ANTLR
|
mit
|
Collap/bryg
|
c794d89dec2032e36a59b0536109ab2923afb2cf
|
src/main/antlr4/org/graphwalker/io/yed/YEdVertexParser.g4
|
src/main/antlr4/org/graphwalker/io/yed/YEdVertexParser.g4
|
parser grammar YEdVertexParser;
options {
tokenVocab=YEdLabelLexer;
}
parse
: (start | (name? shared? blocked? actions?))? EOF
| (start | (name? shared? actions? blocked?))? EOF
| (start | (name? blocked? shared? actions?))? EOF
| (start | (name? blocked? actions? shared?))? EOF
| (start | (name? actions? shared? blocked?))? EOF
| (start | (name? actions? blocked? shared?))? EOF
| (start | (shared? name? actions? blocked?))? EOF
| (start | (shared? name? blocked? actions?))? EOF
| (start | (shared? blocked? actions? name?))? EOF
| (start | (shared? blocked? name? actions?))? EOF
| (start | (shared? actions? blocked? name?))? EOF
| (start | (shared? actions? name? blocked?))? EOF
| (start | (blocked? name? shared? actions?))? EOF
| (start | (blocked? name? actions? shared?))? EOF
| (start | (blocked? shared? name? actions?))? EOF
| (start | (blocked? shared? actions? name?))? EOF
| (start | (blocked? actions? name? shared?))? EOF
| (start | (blocked? actions? shared? name?))? EOF
| (start | (actions? name? blocked? shared?))? EOF
| (start | (actions? name? shared? blocked?))? EOF
| (start | (actions? shared? blocked? name?))? EOF
| (start | (actions? shared? name? blocked?))? EOF
| (start | (actions? blocked? shared? name?))? EOF
| (start | (actions? blocked? name? shared?))? EOF
;
start
: START
;
shared
: SHARED COLON Identifier
;
name
: Identifier
;
blocked
: BLOCKED
;
actions
: INIT COLON (action)+
;
action
: ~(SEMICOLON)* SEMICOLON
;
|
parser grammar YEdVertexParser;
options {
tokenVocab=YEdLabelLexer;
}
parse
: (start | (name? shared? blocked? actions?)) EOF
| (start | (name? shared? actions? blocked?)) EOF
| (start | (name? blocked? shared? actions?)) EOF
| (start | (name? blocked? actions? shared?)) EOF
| (start | (name? actions? shared? blocked?)) EOF
| (start | (name? actions? blocked? shared?)) EOF
| (start | (shared? name? actions? blocked?)) EOF
| (start | (shared? name? blocked? actions?)) EOF
| (start | (shared? blocked? actions? name?)) EOF
| (start | (shared? blocked? name? actions?)) EOF
| (start | (shared? actions? blocked? name?)) EOF
| (start | (shared? actions? name? blocked?)) EOF
| (start | (blocked? name? shared? actions?)) EOF
| (start | (blocked? name? actions? shared?)) EOF
| (start | (blocked? shared? name? actions?)) EOF
| (start | (blocked? shared? actions? name?)) EOF
| (start | (blocked? actions? name? shared?)) EOF
| (start | (blocked? actions? shared? name?)) EOF
| (start | (actions? name? blocked? shared?)) EOF
| (start | (actions? name? shared? blocked?)) EOF
| (start | (actions? shared? blocked? name?)) EOF
| (start | (actions? shared? name? blocked?)) EOF
| (start | (actions? blocked? shared? name?)) EOF
| (start | (actions? blocked? name? shared?)) EOF
;
start
: START
;
shared
: SHARED COLON Identifier
;
name
: Identifier
;
blocked
: BLOCKED
;
actions
: INIT COLON (action)+
;
action
: ~(SEMICOLON)* SEMICOLON
;
|
Fix antlr4 warnings
|
Fix antlr4 warnings
|
ANTLR
|
mit
|
KristianKarl/graphwalker-project,GraphWalker/graphwalker-project,GraphWalker/graphwalker-project,KristianKarl/graphwalker-project,GraphWalker/graphwalker-project,KristianKarl/graphwalker-project
|
1dba1e1a090605b246065a2d693f72f65437257c
|
oberon0/src/main/antlr4/Oberon0.g4
|
oberon0/src/main/antlr4/Oberon0.g4
|
grammar Oberon0;
// PARSER
selector
: ('.' Identifier | '[' expression ']')*
;
number
: Integer
;
factor
: Identifier selector
| number
| '(' expression ')'
| '~' factor
;
term
: factor (op=('*' | 'DIV' | 'MOD' | '&') factor)*
;
simpleExpression
: (sign=('+' | '-'))? term (op=('+' | '-' | 'OR') term)*
;
expression
: simpleExpression (op=('=' | '#' | '<' | '<=' | '>' | '>=') simpleExpression)?
;
assignment
: Identifier selector ':=' expression
;
actualParameters
: '(' (expression (',' expression)* )? ')'
;
procedureCall
: Identifier selector (actualParameters)?
;
ifStatement
: 'IF' expression 'THEN' statementSequence
('ELSEIF' expression 'THEN' statementSequence)*
('ELSE' statementSequence)? 'END'
;
whileStatement
: 'WHILE' expression 'DO' statementSequence 'END'
;
statement
: (assignment | procedureCall | ifStatement | whileStatement)?
;
statementSequence
: statement (';' statement)
;
identList
: Identifier (',' Identifier)*
;
arrayType
: 'ARRAY' expression 'OF' type
;
fieldList
: (identList ':' type)?
;
recordType
: 'RECORD' fieldList (';' fieldList) 'END'
;
type
: Identifier
| arrayType
| recordType
;
fpSection
: 'VAR'? identList ':' type
;
formalParameters
: '(' (fpSection (';' fpSection)* )? ')'
;
procedureHeading
: 'PROCEDURE' Identifier formalParameters?
;
procedureBody
: declarations ('BEGIN' statementSequence)? 'END' Identifier
;
procedureDeclaration
: procedureHeading ';' procedureBody
;
declarations
: ('CONST' (Identifier '=' expression ';')* )?
('TYPE' (Identifier '=' type ';')* )?
('VAR' (identList ':' type ';')* )?
(procedureDeclaration ';')*
;
module
: 'MODULE' Identifier ';' declarations ('BEGIN' statementSequence)?
'END' Identifier '.'
;
// LEXER
// keywords
DIV : 'DIV' ;
MOD : 'MOD' ;
OR : 'OR' ;
IF : 'IF' ;
THEN : 'THEN' ;
ELSEIF : 'ELSEIF' ;
ELSE : 'ELSE' ;
END : 'END' ;
BEGIN : 'BEGIN' ;
WHILE : 'WHILE' ;
DO : 'DO' ;
ARRAY : 'ARRAY' ;
OF : 'OF' ;
RECORD : 'RECORD' ;
VAR : 'VAR' ;
PROCEDURE : 'PROCEDURE' ;
CONST : 'CONST' ;
TYPE : 'TYPE' ;
MODULE : 'MODULE' ;
// Punctuations and operators
DOT : '.' ;
LBRACKET : '[' ;
RBRACKET : ']' ;
LPAREN : '(' ;
RPAREN : ')' ;
TILDA : '~' ;
MUL : '*' ;
AND : '&' ;
PLUS : '+' ;
MINUS : '-' ;
EQUAL : '=' ;
SHARP : '#' ;
LT : '<' ;
LE : '<=' ;
GT : '>' ;
GE : '>=' ;
ASSIGN : ':=' ;
COMA : ',' ;
SEMI : ';' ;
COLON : ':' ;
Identifier
: Letter (Letter | Digit)*
;
Integer
: Digit+
;
Digit
: [0-9]
;
Letter
: [a-zA-Z_]
;
|
grammar Oberon0;
// PARSER
selector
: ('.' Identifier | '[' expression ']')*
;
number
: Integer
;
factor
: Identifier selector
| number
| '(' expression ')'
| '~' factor
;
term
: factor (op=('*' | 'DIV' | 'MOD' | '&') factor)*
;
simpleExpression
: (sign=('+' | '-'))? term (op=('+' | '-' | 'OR') term)*
;
expression
: simpleExpression (op=('=' | '#' | '<' | '<=' | '>' | '>=') simpleExpression)?
;
assignment
: Identifier selector ':=' expression
;
actualParameters
: '(' (expression (',' expression)* )? ')'
;
procedureCall
: Identifier selector (actualParameters)?
;
ifStatement
: 'IF' expression 'THEN' statementSequence
('ELSEIF' expression 'THEN' statementSequence)*
('ELSE' statementSequence)? 'END'
;
whileStatement
: 'WHILE' expression 'DO' statementSequence 'END'
;
statement
: (assignment | procedureCall | ifStatement | whileStatement)?
;
statementSequence
: statement (';' statement)
;
identList
: Identifier (',' Identifier)*
;
arrayType
: 'ARRAY' expression 'OF' type
;
fieldList
: (identList ':' type)?
;
recordType
: 'RECORD' fieldList (';' fieldList) 'END'
;
type
: Identifier
| arrayType
| recordType
;
fpSection
: 'VAR'? identList ':' type
;
formalParameters
: '(' (fpSection (';' fpSection)* )? ')'
;
procedureHeading
: 'PROCEDURE' Identifier formalParameters?
;
procedureBody
: declarations ('BEGIN' statementSequence)? 'END' Identifier
;
procedureDeclaration
: procedureHeading ';' procedureBody
;
declarations
: ('CONST' (Identifier '=' expression ';')* )?
('TYPE' (Identifier '=' type ';')* )?
('VAR' (identList ':' type ';')* )?
(procedureDeclaration ';')*
;
module
: 'MODULE' Identifier ';' declarations ('BEGIN' statementSequence)?
'END' Identifier '.'
;
// LEXER
// keywords
DIV : 'DIV' ;
MOD : 'MOD' ;
OR : 'OR' ;
IF : 'IF' ;
THEN : 'THEN' ;
ELSEIF : 'ELSEIF' ;
ELSE : 'ELSE' ;
END : 'END' ;
BEGIN : 'BEGIN' ;
WHILE : 'WHILE' ;
DO : 'DO' ;
ARRAY : 'ARRAY' ;
OF : 'OF' ;
RECORD : 'RECORD' ;
VAR : 'VAR' ;
PROCEDURE : 'PROCEDURE' ;
CONST : 'CONST' ;
TYPE : 'TYPE' ;
MODULE : 'MODULE' ;
// Punctuations and operators
DOT : '.' ;
LBRACKET : '[' ;
RBRACKET : ']' ;
LPAREN : '(' ;
RPAREN : ')' ;
TILDA : '~' ;
MUL : '*' ;
AND : '&' ;
PLUS : '+' ;
MINUS : '-' ;
EQUAL : '=' ;
SHARP : '#' ;
LT : '<' ;
LE : '<=' ;
GT : '>' ;
GE : '>=' ;
ASSIGN : ':=' ;
COMA : ',' ;
SEMI : ';' ;
COLON : ':' ;
Identifier
: Letter (Letter | Digit)*
;
Integer
: Digit+
;
Digit
: [0-9]
;
Letter
: [a-zA-Z_]
;
// Whitespace and comments
//
WS : [ \t\r\n\u000C]+ -> skip
;
COMMENT
: '/*' .*? '*/' -> skip
;
LINE_COMMENT
: '//' ~[\r\n]* -> skip
;
|
Add comments and whitespaces to the Lexer
|
Add comments and whitespaces to the Lexer
|
ANTLR
|
bsd-3-clause
|
amanjpro/languages-a-la-carte,amanjpro/languages-a-la-carte
|
550a079093c07e60682b2404e158f06ac37d4887
|
cache/src/main/antlr4/net/runelite/cache/script/assembler/rs2asm.g4
|
cache/src/main/antlr4/net/runelite/cache/script/assembler/rs2asm.g4
|
/*
* Copyright (c) 2017, Adam <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar rs2asm;
prog: (header NEWLINE)* (line NEWLINE)+ ;
header: id | int_stack_count | string_stack_count | int_var_count | string_var_count ;
id: '.id ' id_value ;
int_stack_count: '.int_stack_count ' int_stack_value ;
string_stack_count: '.string_stack_count ' string_stack_value ;
int_var_count: '.int_var_count ' int_var_value ;
string_var_count: '.string_var_count ' string_var_value ;
id_value: INT ;
int_stack_value: INT ;
string_stack_value: INT ;
int_var_value: INT ;
string_var_value: INT ;
line: instruction | label | switch_lookup ;
instruction: instruction_name instruction_operand ;
label: 'LABEL' INT ':' ;
instruction_name: name_string | name_opcode ;
name_string: INSTRUCTION ;
name_opcode: INT ;
instruction_operand: operand_int | operand_qstring | operand_label | ;
operand_int: INT ;
operand_qstring: QSTRING ;
operand_label: 'LABEL' INT ;
switch_lookup: switch_key ':' switch_value ;
switch_key: INT ;
switch_value: 'LABEL' INT ;
NEWLINE: '\n'+ ;
INT: '-'? [0-9]+ ;
QSTRING: '"' (~('"' | '\\' | '\r' | '\n') | '\\' ('"' | '\\'))* '"' ;
INSTRUCTION: [a-z0-9_]+ ;
COMMENT: ';' ~( '\r' | '\n' )* -> channel(HIDDEN) ;
WS: (' ' | '\t')+ -> channel(HIDDEN) ;
|
/*
* Copyright (c) 2017, Adam <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar rs2asm;
prog: (header NEWLINE)* (line NEWLINE)+ ;
header: id | int_stack_count | string_stack_count | int_var_count | string_var_count ;
id: '.id ' id_value ;
int_stack_count: '.int_stack_count ' int_stack_value ;
string_stack_count: '.string_stack_count ' string_stack_value ;
int_var_count: '.int_var_count ' int_var_value ;
string_var_count: '.string_var_count ' string_var_value ;
id_value: INT ;
int_stack_value: INT ;
string_stack_value: INT ;
int_var_value: INT ;
string_var_value: INT ;
line: instruction | label | switch_lookup ;
instruction: instruction_name instruction_operand ;
label: 'LABEL' INT ':' ;
instruction_name: name_string | name_opcode ;
name_string: INSTRUCTION ;
name_opcode: INT ;
instruction_operand: operand_int | operand_qstring | operand_label | ;
operand_int: INT ;
operand_qstring: QSTRING ;
operand_label: 'LABEL' INT ;
switch_lookup: switch_key ':' switch_value ;
switch_key: INT ;
switch_value: 'LABEL' INT ;
NEWLINE: ( '\r' | '\n' )+ ;
INT: '-'? [0-9]+ ;
QSTRING: '"' (~('"' | '\\' | '\r' | '\n') | '\\' ('"' | '\\'))* '"' ;
INSTRUCTION: [a-z0-9_]+ ;
COMMENT: ';' ~( '\r' | '\n' )* -> channel(HIDDEN) ;
WS: (' ' | '\t')+ -> channel(HIDDEN) ;
|
allow carriage returns in newlines in scripts
|
cache: allow carriage returns in newlines in scripts
|
ANTLR
|
bsd-2-clause
|
KronosDesign/runelite,devinfrench/runelite,Sethtroll/runelite,abelbriggs1/runelite,runelite/runelite,KronosDesign/runelite,runelite/runelite,Noremac201/runelite,abelbriggs1/runelite,Sethtroll/runelite,runelite/runelite,abelbriggs1/runelite,l2-/runelite,Noremac201/runelite,l2-/runelite,devinfrench/runelite
|
e07d83f16345af60963bb69e0b992f7b059325aa
|
container-search/src/main/antlr4/com/yahoo/search/yql/yqlplus.g4
|
container-search/src/main/antlr4/com/yahoo/search/yql/yqlplus.g4
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
grammar yqlplus;
options {
superClass = ParserBase;
language = Java;
}
@header {
import java.util.Stack;
import com.yahoo.search.yql.*;
}
@parser::members {
protected static class expression_scope {
boolean in_select;
}
protected Stack<expression_scope> expression_stack = new Stack();
}
// tokens
SELECT : 'select';
LIMIT : 'limit';
OFFSET : 'offset';
WHERE : 'where';
ORDERBY : 'order by';
DESC : 'desc';
ASC :;
FROM : 'from';
SOURCES : 'sources';
AS : 'as';
ON : 'on'; // TODO: not used?
COMMA : ',';
OUTPUT : 'output';
COUNT : 'count';
TRUE : 'true';
FALSE : 'false';
// brackets and other tokens in literals
LPAREN : '(';
RPAREN : ')';
LBRACKET : '[';
RBRACKET : ']';
LBRACE : '{';
RBRACE : '}';
COLON : ':';
PIPE : '|';
// operators
AND : 'and';
OR : 'or';
NOT_IN : 'not in';
IN : 'in';
QUERY_ARRAY :;
LT : '<';
GT : '>';
LTEQ : '<=';
GTEQ : '>=';
NEQ : '!=';
STAR : '*';
EQ : '=';
LIKE : 'like';
CONTAINS : 'contains';
NOTLIKE : 'not like';
MATCHES : 'matches';
NOTMATCHES : 'not matches';
// effectively unary operators
IS_NULL : 'is null';
IS_NOT_NULL : 'is not null';
// dereference
DOT : '.';
AT : '@';
// quotes
SQ : '\'';
DQ : '"';
// statement delimiter
SEMI : ';';
TIMEOUT : 'timeout';
/*------------------------------------------------------------------
* LEXER RULES
*------------------------------------------------------------------*/
ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_'|':'|'-')*
;
LONG_INT : '-'?'0'..'9'+ ('L'|'l')
;
INT : '-'?'0'..'9'+
;
FLOAT
: ('-')?('0'..'9')+ '.' ('0'..'9')* EXPONENT?
| ('-')?'.' ('0'..'9')+ EXPONENT?
| ('-')?('0'..'9')+ EXPONENT
;
fragment
EXPONENT : ('e'|'E') ('+'|'-')? ('0'..'9')+ ;
fragment
DIGIT : '0'..'9'
;
fragment
LETTER : 'a'..'z'
| 'A'..'Z'
;
STRING : '"' ( ESC_SEQ | ~('\\'| '"') )* '"'
| '\'' ( ESC_SEQ | ~('\\' | '\'') )* '\''
;
fragment
HEX_DIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ;
fragment
ESC_SEQ
: '\\' ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\'|'/')
| UNICODE_ESC
;
fragment
UNICODE_ESC
: '\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
;
WS : ( ' '
| '\t'
| '\r'
| '\n'
) -> channel(HIDDEN)
;
COMMENT
: ( ('//') ~('\n'|'\r')* '\r'? '\n'?
| '/*' .*? '*/'
)
-> channel(HIDDEN)
;
VESPA_GROUPING
: ('all' | 'each') WS* VESPA_GROUPING_ARG WS*
('as' WS* VESPA_GROUPING_ARG WS*)?
('where' WS* VESPA_GROUPING_ARG)?
;
fragment
VESPA_GROUPING_ARG
: ('(' | '[' | '<')
( ~('(' | '[' | '<' | ')' | ']' | '>') | VESPA_GROUPING_ARG )*
(')' | ']' | '>')
;
// --------- parser rules ------------
ident
: keyword_as_ident //{addChild(new TerminalNodeImpl(keyword_as_ident.getText()));}
| ID
;
keyword_as_ident
: SELECT | LIMIT | OFFSET | WHERE | 'order' | 'by' | DESC | ON | OUTPUT | COUNT | SOURCES | MATCHES | LIKE
;
program : (statement SEMI)* EOF
;
moduleId
: ID
;
moduleName
: literalString
| namespaced_name
;
statement
: output_statement
;
output_statement
: source_statement output_spec?
;
source_statement
: query_statement (PIPE pipeline_step)*
;
pipeline_step
: namespaced_name arguments[false]?
| vespa_grouping
;
vespa_grouping
: VESPA_GROUPING
| annotation VESPA_GROUPING
;
output_spec
: (OUTPUT AS ident)
| (OUTPUT COUNT AS ident)
;
query_statement
: select_statement
;
select_statement
: SELECT select_field_spec select_source? where? orderby? limit? offset? timeout?
;
select_field_spec
: project_spec
| STAR
;
project_spec
: field_def (COMMA field_def)*
;
timeout
: TIMEOUT fixed_or_parameter
;
select_source
: select_source_all
| select_source_multi
| select_source_from
;
select_source_all
: FROM SOURCES STAR
;
select_source_multi
: FROM SOURCES source_list
;
select_source_from
: FROM source_spec
;
source_list
: namespaced_name (COMMA namespaced_name )*
;
source_spec
: ( data_source (alias_def { ($data_source.ctx).addChild($alias_def.ctx); })? )
;
alias_def
: (AS? ID)
;
data_source
: call_source
| LPAREN source_statement RPAREN
| sequence_source
;
call_source
: namespaced_name arguments[true]?
;
sequence_source
: AT ident
;
namespaced_name
: (ident (DOT ident)* (DOT STAR)?)
;
orderby
: ORDERBY orderby_fields
;
orderby_fields
: orderby_field (COMMA orderby_field)*
;
orderby_field
: expression[true] DESC
| expression[true] ('asc')?
;
limit
: LIMIT fixed_or_parameter
;
offset
: OFFSET fixed_or_parameter
;
where
: WHERE expression[true]
;
field_def
: expression[true] alias_def?
;
mapExpression
: LBRACE propertyNameAndValue? (COMMA propertyNameAndValue)* RBRACE
;
constantMapExpression
: LBRACE constantPropertyNameAndValue? (COMMA constantPropertyNameAndValue)* RBRACE
;
arguments[boolean in_select]
: LPAREN RPAREN
| LPAREN (argument[$in_select] (COMMA argument[$in_select])*) RPAREN
;
argument[boolean in_select]
: expression[$in_select]
;
// --------- expressions ------------
expression [boolean select]
@init {
expression_stack.push(new expression_scope());
expression_stack.peek().in_select = select;
}
@after {
expression_stack.pop();
}
: annotateExpression
| logicalORExpression
| nullOperator
;
nullOperator
: 'null'
;
annotateExpression
: annotation logicalORExpression
;
annotation
: LBRACKET constantMapExpression RBRACKET
;
logicalORExpression
: logicalANDExpression (OR logicalANDExpression)+
| logicalANDExpression
;
logicalANDExpression
: equalityExpression (AND equalityExpression)*
;
equalityExpression
: relationalExpression ( ((IN | NOT_IN) inNotInTarget)
| (IS_NULL | IS_NOT_NULL)
| (equalityOp relationalExpression) )
| relationalExpression
;
inNotInTarget
: {expression_stack.peek().in_select}? LPAREN select_statement RPAREN
| literal_list
;
equalityOp
: (EQ | NEQ | LIKE | NOTLIKE | MATCHES | NOTMATCHES | CONTAINS)
;
relationalExpression
: additiveExpression (relationalOp additiveExpression)?
;
relationalOp
: (LT | GT | LTEQ | GTEQ)
;
additiveExpression
: multiplicativeExpression (additiveOp additiveExpression)?
;
additiveOp
: '+'
| '-'
;
multiplicativeExpression
: unaryExpression (multOp multiplicativeExpression)?
;
multOp
: '*'
| '/'
| '%'
;
unaryOp
: '-'
| '!'
;
unaryExpression
: dereferencedExpression
| unaryOp dereferencedExpression
;
dereferencedExpression
@init{
boolean in_select = expression_stack.peek().in_select;
}
: primaryExpression
(
indexref[in_select]
| propertyref
)*
;
indexref[boolean in_select]
: LBRACKET idx=expression[in_select] RBRACKET
;
propertyref
: DOT nm=ID
;
operatorCall
@init{
boolean in_select = expression_stack.peek().in_select;
}
: multOp arguments[in_select]
| additiveOp arguments[in_select]
| AND arguments[in_select]
| OR arguments[in_select]
;
primaryExpression
@init {
boolean in_select = expression_stack.peek().in_select;
}
: callExpresion[in_select]
| parameter
| fieldref
| scalar_literal
| arrayLiteral
| mapExpression
| LPAREN expression[in_select] RPAREN
;
callExpresion[boolean in_select]
: namespaced_name arguments[in_select]
;
fieldref
: namespaced_name
;
arrayLiteral
@init {
boolean in_select = expression_stack.peek().in_select;
}
: LBRACKET expression[in_select]? (COMMA expression[in_select])* RBRACKET
;
// a parameter is an argument from outside the YQL statement
parameter
: AT ident
;
propertyNameAndValue
: propertyName ':' expression[{expression_stack.peek().in_select}] //{return (PROPERTY propertyName expression);}
;
constantPropertyNameAndValue
: propertyName ':' constantExpression
;
propertyName
: ID
| literalString
;
constantExpression
: scalar_literal
| constantMapExpression
| constantArray
| parameter
;
constantArray
: LBRACKET i+=constantExpression? (COMMA i+=constantExpression)* RBRACKET
;
scalar_literal
: TRUE
| FALSE
| STRING
| LONG_INT
| INT
| FLOAT
;
literalString
: STRING
;
array_parameter
: AT i=ident {isArrayParameter($i.ctx)}?
;
literal_list
: LPAREN literal_element (COMMA literal_element)* RPAREN
;
literal_element
: scalar_literal
| parameter
;
fixed_or_parameter
: INT
| parameter
;
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
grammar yqlplus;
options {
superClass = ParserBase;
language = Java;
}
@header {
import java.util.Stack;
import com.yahoo.search.yql.*;
}
@parser::members {
protected static class expression_scope {
boolean in_select;
}
protected Stack<expression_scope> expression_stack = new Stack();
}
// tokens
SELECT : 'select';
LIMIT : 'limit';
OFFSET : 'offset';
WHERE : 'where';
ORDERBY : 'order by';
DESC : 'desc';
ASC :;
FROM : 'from';
SOURCES : 'sources';
AS : 'as';
COMMA : ',';
OUTPUT : 'output';
COUNT : 'count';
TRUE : 'true';
FALSE : 'false';
// brackets and other tokens in literals
LPAREN : '(';
RPAREN : ')';
LBRACKET : '[';
RBRACKET : ']';
LBRACE : '{';
RBRACE : '}';
COLON : ':';
PIPE : '|';
// operators
AND : 'and';
OR : 'or';
NOT_IN : 'not in';
IN : 'in';
QUERY_ARRAY :;
LT : '<';
GT : '>';
LTEQ : '<=';
GTEQ : '>=';
NEQ : '!=';
STAR : '*';
EQ : '=';
LIKE : 'like';
CONTAINS : 'contains';
NOTLIKE : 'not like';
MATCHES : 'matches';
NOTMATCHES : 'not matches';
// effectively unary operators
IS_NULL : 'is null';
IS_NOT_NULL : 'is not null';
// dereference
DOT : '.';
AT : '@';
// quotes
SQ : '\'';
DQ : '"';
// statement delimiter
SEMI : ';';
TIMEOUT : 'timeout';
/*------------------------------------------------------------------
* LEXER RULES
*------------------------------------------------------------------*/
ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_'|':'|'-')*
;
LONG_INT : '-'?'0'..'9'+ ('L'|'l')
;
INT : '-'?'0'..'9'+
;
FLOAT
: ('-')?('0'..'9')+ '.' ('0'..'9')* EXPONENT?
| ('-')?'.' ('0'..'9')+ EXPONENT?
| ('-')?('0'..'9')+ EXPONENT
;
fragment
EXPONENT : ('e'|'E') ('+'|'-')? ('0'..'9')+ ;
fragment
DIGIT : '0'..'9'
;
fragment
LETTER : 'a'..'z'
| 'A'..'Z'
;
STRING : '"' ( ESC_SEQ | ~('\\'| '"') )* '"'
| '\'' ( ESC_SEQ | ~('\\' | '\'') )* '\''
;
fragment
HEX_DIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ;
fragment
ESC_SEQ
: '\\' ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\'|'/')
| UNICODE_ESC
;
fragment
UNICODE_ESC
: '\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
;
WS : ( ' '
| '\t'
| '\r'
| '\n'
) -> channel(HIDDEN)
;
COMMENT
: ( ('//') ~('\n'|'\r')* '\r'? '\n'?
| '/*' .*? '*/'
)
-> channel(HIDDEN)
;
VESPA_GROUPING
: ('all' | 'each') WS* VESPA_GROUPING_ARG WS*
('as' WS* VESPA_GROUPING_ARG WS*)?
('where' WS* VESPA_GROUPING_ARG)?
;
fragment
VESPA_GROUPING_ARG
: ('(' | '[' | '<')
( ~('(' | '[' | '<' | ')' | ']' | '>') | VESPA_GROUPING_ARG )*
(')' | ']' | '>')
;
// --------- parser rules ------------
ident
: keyword_as_ident //{addChild(new TerminalNodeImpl(keyword_as_ident.getText()));}
| ID
;
keyword_as_ident
: SELECT | LIMIT | OFFSET | WHERE | 'order' | 'by' | DESC | OUTPUT | COUNT | SOURCES | MATCHES | LIKE
;
program : (statement SEMI)* EOF
;
moduleId
: ID
;
moduleName
: literalString
| namespaced_name
;
statement
: output_statement
;
output_statement
: source_statement output_spec?
;
source_statement
: query_statement (PIPE pipeline_step)*
;
pipeline_step
: namespaced_name arguments[false]?
| vespa_grouping
;
vespa_grouping
: VESPA_GROUPING
| annotation VESPA_GROUPING
;
output_spec
: (OUTPUT AS ident)
| (OUTPUT COUNT AS ident)
;
query_statement
: select_statement
;
select_statement
: SELECT select_field_spec select_source? where? orderby? limit? offset? timeout?
;
select_field_spec
: project_spec
| STAR
;
project_spec
: field_def (COMMA field_def)*
;
timeout
: TIMEOUT fixed_or_parameter
;
select_source
: select_source_all
| select_source_multi
| select_source_from
;
select_source_all
: FROM SOURCES STAR
;
select_source_multi
: FROM SOURCES source_list
;
select_source_from
: FROM source_spec
;
source_list
: namespaced_name (COMMA namespaced_name )*
;
source_spec
: ( data_source (alias_def { ($data_source.ctx).addChild($alias_def.ctx); })? )
;
alias_def
: (AS? ID)
;
data_source
: call_source
| LPAREN source_statement RPAREN
| sequence_source
;
call_source
: namespaced_name arguments[true]?
;
sequence_source
: AT ident
;
namespaced_name
: (ident (DOT ident)* (DOT STAR)?)
;
orderby
: ORDERBY orderby_fields
;
orderby_fields
: orderby_field (COMMA orderby_field)*
;
orderby_field
: expression[true] DESC
| expression[true] ('asc')?
;
limit
: LIMIT fixed_or_parameter
;
offset
: OFFSET fixed_or_parameter
;
where
: WHERE expression[true]
;
field_def
: expression[true] alias_def?
;
mapExpression
: LBRACE propertyNameAndValue? (COMMA propertyNameAndValue)* RBRACE
;
constantMapExpression
: LBRACE constantPropertyNameAndValue? (COMMA constantPropertyNameAndValue)* RBRACE
;
arguments[boolean in_select]
: LPAREN RPAREN
| LPAREN (argument[$in_select] (COMMA argument[$in_select])*) RPAREN
;
argument[boolean in_select]
: expression[$in_select]
;
// --------- expressions ------------
expression [boolean select]
@init {
expression_stack.push(new expression_scope());
expression_stack.peek().in_select = select;
}
@after {
expression_stack.pop();
}
: annotateExpression
| logicalORExpression
| nullOperator
;
nullOperator
: 'null'
;
annotateExpression
: annotation logicalORExpression
;
annotation
: LBRACKET constantMapExpression RBRACKET
;
logicalORExpression
: logicalANDExpression (OR logicalANDExpression)+
| logicalANDExpression
;
logicalANDExpression
: equalityExpression (AND equalityExpression)*
;
equalityExpression
: relationalExpression ( ((IN | NOT_IN) inNotInTarget)
| (IS_NULL | IS_NOT_NULL)
| (equalityOp relationalExpression) )
| relationalExpression
;
inNotInTarget
: {expression_stack.peek().in_select}? LPAREN select_statement RPAREN
| literal_list
;
equalityOp
: (EQ | NEQ | LIKE | NOTLIKE | MATCHES | NOTMATCHES | CONTAINS)
;
relationalExpression
: additiveExpression (relationalOp additiveExpression)?
;
relationalOp
: (LT | GT | LTEQ | GTEQ)
;
additiveExpression
: multiplicativeExpression (additiveOp additiveExpression)?
;
additiveOp
: '+'
| '-'
;
multiplicativeExpression
: unaryExpression (multOp multiplicativeExpression)?
;
multOp
: '*'
| '/'
| '%'
;
unaryOp
: '-'
| '!'
;
unaryExpression
: dereferencedExpression
| unaryOp dereferencedExpression
;
dereferencedExpression
@init{
boolean in_select = expression_stack.peek().in_select;
}
: primaryExpression
(
indexref[in_select]
| propertyref
)*
;
indexref[boolean in_select]
: LBRACKET idx=expression[in_select] RBRACKET
;
propertyref
: DOT nm=ID
;
operatorCall
@init{
boolean in_select = expression_stack.peek().in_select;
}
: multOp arguments[in_select]
| additiveOp arguments[in_select]
| AND arguments[in_select]
| OR arguments[in_select]
;
primaryExpression
@init {
boolean in_select = expression_stack.peek().in_select;
}
: callExpresion[in_select]
| parameter
| fieldref
| scalar_literal
| arrayLiteral
| mapExpression
| LPAREN expression[in_select] RPAREN
;
callExpresion[boolean in_select]
: namespaced_name arguments[in_select]
;
fieldref
: namespaced_name
;
arrayLiteral
@init {
boolean in_select = expression_stack.peek().in_select;
}
: LBRACKET expression[in_select]? (COMMA expression[in_select])* RBRACKET
;
// a parameter is an argument from outside the YQL statement
parameter
: AT ident
;
propertyNameAndValue
: propertyName ':' expression[{expression_stack.peek().in_select}] //{return (PROPERTY propertyName expression);}
;
constantPropertyNameAndValue
: propertyName ':' constantExpression
;
propertyName
: ID
| literalString
;
constantExpression
: scalar_literal
| constantMapExpression
| constantArray
| parameter
;
constantArray
: LBRACKET i+=constantExpression? (COMMA i+=constantExpression)* RBRACKET
;
scalar_literal
: TRUE
| FALSE
| STRING
| LONG_INT
| INT
| FLOAT
;
literalString
: STRING
;
array_parameter
: AT i=ident {isArrayParameter($i.ctx)}?
;
literal_list
: LPAREN literal_element (COMMA literal_element)* RPAREN
;
literal_element
: scalar_literal
| parameter
;
fixed_or_parameter
: INT
| parameter
;
|
Remove unsupported constructs
|
Remove unsupported constructs
|
ANTLR
|
apache-2.0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
60ec26064eeb31628a07c38de23c62334efb81be
|
resources/LineGrammar.g4
|
resources/LineGrammar.g4
|
grammar LineGrammar;
/*
LineGrammer is a lightweight grammer for specifying a combination of melody line and harmonic context track.
It uses the python module line_constructor.py as an assist to build these items, and the module
line_grammar_executor as a exposed api to using this grammer to parse strings into lines and harmonic_context_tracks.
The grammar is relative easy:
{ ... } is how you start
{ ... [ ... [...] ... ] ...} as a way to do nested beams
{ ... (dur, #)[ ... ] ...] } as a way to do tuplets with dur being a unit duration, and # the number of them
dur * # is the full (locked) duration of the tuplet no matter how many notes
Notes: (duration) (letter) (alteration) : (register), e.g. hEb:5 is half note Eb in register 5
for convenience:
1) register may be specified once and assumed in further notes for that level, e.g. line, beam, tuplet.
2) same for duration, e.g. i is eight note, and further notes on same level are eights.
Example: '{ C:5 D Eb F (1:8, 2)[C:3 D:4 E] [i@C#:3 sBb D:4 Fbb]}'
Harmonic Contexts:
These are:
< ... >
< tonality : chord> where tonality is like Db-Major and chord is either say Eb-Min or ii.
< : chord> means tonality is picked up from where last specified.
Harmonic contexts are dropped whereever they start to take effect - duration and position are automatically
calculated.
Example: '{ <E-Major:iv> C:5 D Eb F (1:8, 2)[C:3 D:4 E] <:v> [i@C#:3 sBb D:4 Fbb]}'
NOTE: Ties are in the syntax but not supported at this time.
*/
@header {
from structure.LineGrammar.core.line_constructor import LineConstructor
import sys
}
@members {
self.lc = LineConstructor();
self._notelist = list()
}
/* This is the entry rule of our parser. */
motif: LINEBEGIN ( motificElement )+ LINEEND;
motificElement: ( (primitiveNote {self.lc.add_note($primitiveNote.n)} | harmonicTag)
| beam
| tuplet)
;
primitiveNote returns [n]
locals [dots=0, dur=None, ties=False]:
(duration {$dur = $duration.d} ( DOT {$dots = $dots + 1} )*)?
pitch
( TIE {$ties = True})? {$n = self.lc.construct_note($pitch.p, $dur, $dots, $ties)}
;
beam: '[' {self.lc.start_level()}
( motificElement )+
']' {self.lc.end_level()}
;
tuplet:
'(' duration ',' dur_int=INT ')'
'[' {self.lc.start_level($duration.d, dur_int=$dur_int.int)}
( motificElement )+
']' {self.lc.end_level()}
;
pitch returns [p]
locals [tt=None ,alert=None, reg=None]:
tone {$tt = $tone.t}
(':' INT {$reg = $INT.int})? {$p=self.lc.construct_pitch($tt, $reg)};
tone returns [t=None]:
(ltrs=NOTELETTERS {$t=LineConstructor.construct_tone_from_tone_letters($ltrs.text)});
duration returns[d]:
( DURATIONLETTER {$d = LineConstructor.construct_duration_by_shorthand($DURATIONLETTER.text) }
| COMMON_DURATION_CHORD_NUMERAL_LETTERS {$d = LineConstructor.construct_duration_by_shorthand($COMMON_DURATION_CHORD_NUMERAL_LETTERS.text) }
| '(' durationFraction ')' {$d = LineConstructor.construct_duration($durationFraction.f[0], $durationFraction.f[1])});
durationFraction returns [f]:
numerator=INT ':' denominator=INT {$f = ($numerator.int, $denominator.int)};
tonality returns [tonal]:
tone '-' MODALITY {$tonal = self.lc.construct_tonality($tone.t, $MODALITY.text)};
chordTemplate returns [ctemplate]:
(tone '-' CHORDMODALITY {$ctemplate = self.lc.construct_chord_template($tone.t, $CHORDMODALITY.text)})
| CHORDNUMERAL {$ctemplate = self.lc.construct_chord_template(None, $CHORDNUMERAL.text)}
| COMMON_DURATION_CHORD_NUMERAL_LETTERS {$ctemplate = self.lc.construct_chord_template(None, $COMMON_DURATION_CHORD_NUMERAL_LETTERS.text)}
;
harmonicTag returns[ht]:
'<'
(( tonality ':' chordTemplate {$ht=self.lc.construct_harmonic_tag($tonality.tonal, $chordTemplate.ctemplate)})
| ( ':' chordTemplate {$ht=self.lc.construct_harmonic_tag(None, $chordTemplate.ctemplate)}))
'>'
;
DOT: '@';
TIE: '-';
INT : [0-9]+ ;
LINEBEGIN : '{';
LINEEND: '}';
WS : [ \t]+ -> skip ; // toss out whitespace
COMMON_DURATION_CHORD_NUMERAL_LETTERS: ('I' | 'i' );
DURATIONLETTER: ('W' | 'w' | 'H' | 'h' | 'Q' | 'q' | 'S' | 's' | 'T' | 't' | 'X' | 'x');
ALTERATION: ('bb' | '#' | '##');
MODALITY: ('Major' | 'Natural' | 'Melodic' | 'Harmonic' | 'Minor');
CHORDNUMERAL: ('II' | 'III' | 'IV' | 'V' | 'VI' | 'VII' | 'ii' | 'iii' | 'iv' | 'v' | 'vi' | 'vii');
CHORDMODALITY: ('Maj' | 'Min' | 'Aug' | 'Dim') ;
NOTELETTERS: ('C' | 'D' | 'E' | 'F' | 'G' | 'A' | 'B' | 'c' | 'd' | 'e' | 'f' | 'g' | 'a' | 'b' |
'Cb' | 'Db' | 'Eb' | 'Fb' | 'Gb' | 'Ab' | 'Bb' | 'cb' | 'db' | 'eb' | 'fb' | 'gb' | 'ab' | 'bb' |
'Cbb' | 'Dbb' | 'Ebb' | 'Fbb' | 'Gbb' | 'Abb' | 'Bbb' | 'cbb' | 'dbb' | 'ebb' | 'fbb' | 'gbb' | 'abb' | 'bbb' |
'C#' | 'D#' | 'E#' | 'F#' | 'G#' | 'A#' | 'B#' | 'c#' | 'd#' | 'e#' | 'f#' | 'g#' | 'a#' | 'b#' |
'C##' | 'D##' | 'E##' | 'F##' | 'G##' | 'A##' | 'B##' | 'c##' | 'd##' | 'e##' | 'f##' | 'g##' | 'a##' | 'b##'
);
|
grammar LineGrammar;
/*
LineGrammer is a lightweight grammer for specifying a combination of melody line and harmonic context track.
It uses the python module line_constructor.py as an assist to build these items, and the module
line_grammar_executor as a exposed api to using this grammer to parse strings into lines and harmonic_context_tracks.
The grammar is relative easy:
{ ... } is how you start
{ ... [ ... [...] ... ] ...} as a way to do nested beams
{ ... (dur, #)[ ... ] ...] } as a way to do tuplets with dur being a unit duration, and # the number of them
dur * # is the full (locked) duration of the tuplet no matter how many notes
Notes: (duration) (letter) (alteration) : (register), e.g. hEb:5 is half note Eb in register 5
for convenience:
1) register may be specified once and assumed in further notes for that level, e.g. line, beam, tuplet.
2) same for duration, e.g. i is eight note, and further notes on same level are eights.
Example: '{ C:5 D Eb F (1:8, 2)[C:3 D:4 E] [i@C#:3 sBb D:4 Fbb]}'
Harmonic Contexts:
These are:
< ... >
< tonality : chord> where tonality is like Db-Major and chord is either say Eb-Min or ii.
< : chord> means tonality is picked up from where last specified.
Harmonic contexts are dropped whereever they start to take effect - duration and position are automatically
calculated.
Example: '{ <E-Major:iv> C:5 D Eb F (1:8, 2)[C:3 D:4 E] <:v> [i@C#:3 sBb D:4 Fbb]}'
Secondary chords:
General notation for the chord:
<NUMERAL>(ChordType)?/(NUMERAL)('-' MODALITY)
e.g. <F-Minor: IIIDom7/V-Melodic>, <C-Major, V/V>
NOTE: Ties are in the syntax but not supported at this time.
*/
@header {
from structure.LineGrammar.core.line_constructor import LineConstructor
import sys
}
@members {
self.lc = LineConstructor();
self._notelist = list()
}
/* This is the entry rule of our parser. */
motif: LINEBEGIN ( motificElement )+ LINEEND;
motificElement: ( (primitiveNote {self.lc.add_note($primitiveNote.n)} | harmonicTag)
| beam
| tuplet)
;
primitiveNote returns [n]
locals [dots=0, dur=None, ties=False]:
(duration {$dur = $duration.d} ( DOT {$dots = $dots + 1} )*)?
pitch
( TIE {$ties = True})? {$n = self.lc.construct_note($pitch.p, $dur, $dots, $ties)}
;
beam: '[' {self.lc.start_level()}
( motificElement )+
']' {self.lc.end_level()}
;
tuplet:
'(' duration ',' dur_int=INT ')'
'[' {self.lc.start_level($duration.d, dur_int=$dur_int.int)}
( motificElement )+
']' {self.lc.end_level()}
;
pitch returns [p]
locals [tt=None, alert=None, reg=None]:
tone {$tt = $tone.t}
(':' INT {$reg = $INT.int})? {$p=self.lc.construct_pitch($tt, $reg)};
tone returns [t=None]:
(ltrs=NOTELETTERS {$t=LineConstructor.construct_tone_from_tone_letters($ltrs.text)});
duration returns[d]:
( DURATIONLETTER {$d = LineConstructor.construct_duration_by_shorthand($DURATIONLETTER.text) }
| COMMON_DURATION_CHORD_NUMERAL_LETTERS {$d = LineConstructor.construct_duration_by_shorthand($COMMON_DURATION_CHORD_NUMERAL_LETTERS.text) }
| '(' durationFraction ')' {$d = LineConstructor.construct_duration($durationFraction.f[0], $durationFraction.f[1])});
durationFraction returns [f]:
numerator=INT ':' denominator=INT {$f = ($numerator.int, $denominator.int)};
tonality returns [tonal]
locals [modal_index=0]:
tone '-' MODALITY ('(' INT {$modal_index = $INT.int}')')? {$tonal = self.lc.construct_tonality($tone.t, $MODALITY.text, $modal_index)};
chordTemplate returns [ctemplate]
locals [cm=None, secondary_numeral=None, secondary_modality=None]:
(tone '-' CHORDMODALITY {$ctemplate = self.lc.construct_chord_template($tone.t, None, $CHORDMODALITY.text)})
| ((CHORDNUMERAL (CHORDMODALITY {$cm=$CHORDMODALITY.text})? {$ctemplate = self.lc.construct_chord_template(None, $CHORDNUMERAL.text, $cm)}
| COMMON_DURATION_CHORD_NUMERAL_LETTERS (CHORDMODALITY {$cm=$CHORDMODALITY.text})? {$ctemplate = self.lc.construct_chord_template(None, $COMMON_DURATION_CHORD_NUMERAL_LETTERS.text, $cm)})
( '/' (CHORDNUMERAL {$secondary_numeral=$CHORDNUMERAL.text} | COMMON_DURATION_CHORD_NUMERAL_LETTERS {$secondary_numeral=$COMMON_DURATION_CHORD_NUMERAL_LETTERS.text})
('-' MODALITY {$secondary_modality=$MODALITY.text})? {$ctemplate = self.lc.construct_secondary_chord_template($ctemplate, $secondary_numeral, $secondary_modality)})?
)
;
harmonicTag returns[ht]:
'<'
(( tonality ':' chordTemplate {$ht=self.lc.construct_harmonic_tag($tonality.tonal, $chordTemplate.ctemplate)})
| ( ':' chordTemplate {$ht=self.lc.construct_harmonic_tag(None, $chordTemplate.ctemplate)}))
'>'
;
DOT: '@';
TIE: '-';
INT : [0-9]+ ;
LINEBEGIN : '{';
LINEEND: '}';
WS : [ \t]+ -> skip ; // toss out whitespace
COMMON_DURATION_CHORD_NUMERAL_LETTERS: ('I' | 'i' );
DURATIONLETTER: ('W' | 'w' | 'H' | 'h' | 'Q' | 'q' | 'S' | 's' | 'T' | 't' | 'X' | 'x');
ALTERATION: ('bb' | '#' | '##');
MODALITY: ('Major' | 'Natural' | 'Melodic' | 'Harmonic' | 'Minor');
CHORDNUMERAL: ('II' | 'III' | 'IV' | 'V' | 'VI' | 'VII' | 'ii' | 'iii' | 'iv' | 'v' | 'vi' | 'vii');
CHORDMODALITY: ('Maj7' | 'Min7' | 'Dom7' | 'Maj' | 'Min' | 'Aug' | 'Dim' | 'HalfDim7') ;
NOTELETTERS: ('C' | 'D' | 'E' | 'F' | 'G' | 'A' | 'B' | 'c' | 'd' | 'e' | 'f' | 'g' | 'a' | 'b' |
'Cb' | 'Db' | 'Eb' | 'Fb' | 'Gb' | 'Ab' | 'Bb' | 'cb' | 'db' | 'eb' | 'fb' | 'gb' | 'ab' | 'bb' |
'Cbb' | 'Dbb' | 'Ebb' | 'Fbb' | 'Gbb' | 'Abb' | 'Bbb' | 'cbb' | 'dbb' | 'ebb' | 'fbb' | 'gbb' | 'abb' | 'bbb' |
'C#' | 'D#' | 'E#' | 'F#' | 'G#' | 'A#' | 'B#' | 'c#' | 'd#' | 'e#' | 'f#' | 'g#' | 'a#' | 'b#' |
'C##' | 'D##' | 'E##' | 'F##' | 'G##' | 'A##' | 'B##' | 'c##' | 'd##' | 'e##' | 'f##' | 'g##' | 'a##' | 'b##' | 'R' | 'r'
);
|
Add secondary dominant chords to grammar.
|
Add secondary dominant chords to grammar.
|
ANTLR
|
mit
|
dpazel/music_rep
|
4e765f6754b8fede9ecf6cf09db744e195411cd5
|
client/src/main/antlr4/com/metamx/druid/sql/antlr4/DruidSQL.g4
|
client/src/main/antlr4/com/metamx/druid/sql/antlr4/DruidSQL.g4
|
grammar DruidSQL;
/*
@lexer::header {
package com.metamx.druid.sql.antlr;
}
*/
/*
TODO: handle both multiply / division, addition - subtraction
unary minus
*/
@header {
import com.metamx.druid.aggregation.post.*;
import com.metamx.druid.aggregation.*;
import com.metamx.druid.query.filter.*;
import com.metamx.druid.query.dimension.*;
import com.metamx.druid.*;
import com.google.common.base.*;
import com.google.common.collect.Lists;
import org.joda.time.*;
import java.text.*;
import java.util.*;
}
@parser::members {
public Map<String, AggregatorFactory> aggregators = new LinkedHashMap<String, AggregatorFactory>();
public List<PostAggregator> postAggregators = new LinkedList<PostAggregator>();
public DimFilter filter;
public List<org.joda.time.Interval> intervals;
public QueryGranularity granularity = QueryGranularity.ALL;
public Map<String, DimensionSpec> groupByDimensions = new LinkedHashMap<String, DimensionSpec>();
String dataSourceName = null;
public String getDataSource() {
return dataSourceName;
}
public String unescape(String quoted) {
String unquote = quoted.trim().replaceFirst("^'(.*)'\$", "\$1");
return unquote.replace("''", "'");
}
AggregatorFactory evalAgg(String name, int fn) {
switch (fn) {
case SUM: return new DoubleSumAggregatorFactory("sum("+name+")", name);
case MIN: return new MinAggregatorFactory("min("+name+")", name);
case MAX: return new MaxAggregatorFactory("max("+name+")", name);
case COUNT: return new CountAggregatorFactory(name);
}
throw new IllegalArgumentException("Unknown function [" + fn + "]");
}
PostAggregator evalArithmeticPostAggregator(PostAggregator a, List<Token> ops, List<PostAggregator> b) {
if(b.isEmpty()) return a;
else {
int i = 0;
PostAggregator root = a;
while(i < ops.size()) {
List<PostAggregator> list = new LinkedList<PostAggregator>();
List<String> names = new LinkedList<String>();
names.add(root.getName());
list.add(root);
Token op = ops.get(i);
while(i < ops.size() && ops.get(i).getType() == op.getType()) {
PostAggregator e = b.get(i);
list.add(e);
names.add(e.getName());
i++;
}
root = new ArithmeticPostAggregator("("+Joiner.on(op.getText()).join(names)+")", op.getText(), list);
}
return root;
}
}
}
AND: 'and';
OR: 'or';
SUM: 'sum';
MIN: 'min';
MAX: 'max';
COUNT: 'count';
AS: 'as';
OPEN: '(';
CLOSE: ')';
STAR: '*';
NOT: '!' ;
PLUS: '+';
MINUS: '-';
DIV: '/';
COMMA: ',';
GROUP: 'group';
IDENT : (LETTER)(LETTER | DIGIT | '_')* ;
QUOTED_STRING : '\'' ( ESC | ~'\'' )*? '\'' ;
ESC : '\'' '\'';
NUMBER: ('+'|'-')?DIGIT*'.'?DIGIT+(EXPONENT)?;
EXPONENT: ('e') ('+'|'-')? ('0'..'9')+;
fragment DIGIT : '0'..'9';
fragment LETTER : 'a'..'z' | 'A'..'Z';
LINE_COMMENT : '--' .*? '\r'? '\n' -> skip ;
COMMENT : '/*' .*? '*/' -> skip ;
WS : (' '| '\t' | '\r' '\n' | '\n' | '\r')+ -> skip;
query
: select_stmt where_stmt (groupby_stmt)?
;
select_stmt
: 'select' e+=aliasedExpression (',' e+=aliasedExpression)* 'from' datasource {
for(AliasedExpressionContext a : $e) { postAggregators.add(a.p); }
this.dataSourceName = $datasource.text;
}
;
where_stmt
: 'where' f=timeAndDimFilter {
if($f.filter != null) this.filter = $f.filter;
this.intervals = Lists.newArrayList($f.interval);
}
;
groupby_stmt
: GROUP 'by' groupByExpression ( COMMA! groupByExpression )*
;
groupByExpression
: gran=granularityFn {this.granularity = $gran.granularity;}
| dim=IDENT { this.groupByDimensions.put($dim.text, new DefaultDimensionSpec($dim.text, $dim.text)); }
;
datasource
: IDENT
;
aliasedExpression returns [PostAggregator p]
: expression ( AS^ name=IDENT )? {
if($name != null) {
postAggregators.add($expression.p);
$p = new FieldAccessPostAggregator($name.text, $expression.p.getName());
}
else $p = $expression.p;
}
;
expression returns [PostAggregator p]
: additiveExpression { $p = $additiveExpression.p; }
;
additiveExpression returns [PostAggregator p]
: a=multiplyExpression (( ops+=PLUS^ | ops+=MINUS^ ) b+=multiplyExpression)* {
List<PostAggregator> rhs = new LinkedList<PostAggregator>();
for(MultiplyExpressionContext e : $b) rhs.add(e.p);
$p = evalArithmeticPostAggregator($a.p, $ops, rhs);
}
;
multiplyExpression returns [PostAggregator p]
: a=unaryExpression ((ops+= STAR | ops+=DIV ) b+=unaryExpression)* {
List<PostAggregator> rhs = new LinkedList<PostAggregator>();
for(UnaryExpressionContext e : $b) rhs.add(e.p);
$p = evalArithmeticPostAggregator($a.p, $ops, rhs);
}
;
unaryExpression returns [PostAggregator p]
: MINUS e=unaryExpression {
$p = new ArithmeticPostAggregator(
"-"+$e.p.getName(),
"*",
Lists.newArrayList($e.p, new ConstantPostAggregator("-1", -1.0))
);
}
| PLUS e=unaryExpression { $p = $e.p; }
| primaryExpression { $p = $primaryExpression.p; }
;
primaryExpression returns [PostAggregator p]
: constant { $p = $constant.c; }
| aggregate {
aggregators.put($aggregate.agg.getName(), $aggregate.agg);
$p = new FieldAccessPostAggregator($aggregate.agg.getName(), $aggregate.agg.getName());
}
| OPEN! e=expression CLOSE! { $p = $e.p; }
;
aggregate returns [AggregatorFactory agg]
: fn=( SUM^ | MIN^ | MAX^ ) OPEN! name=(IDENT|COUNT) CLOSE! { $agg = evalAgg($name.text, $fn.type); }
| fn=COUNT OPEN! STAR CLOSE! { $agg = evalAgg("count(*)", $fn.type); }
;
constant returns [ConstantPostAggregator c]
: value=NUMBER { double v = Double.parseDouble($value.text); $c = new ConstantPostAggregator(Double.toString(v), v); }
;
/* time filters must be top level filters */
timeAndDimFilter returns [DimFilter filter, org.joda.time.Interval interval]
: t=timeFilter (AND f=dimFilter)? {
if($f.ctx != null) $filter = $f.filter;
$interval = $t.interval;
}
| (f=dimFilter)? AND t=timeFilter {
if($f.ctx != null) $filter = $f.filter;
$interval = $t.interval;
}
;
dimFilter returns [DimFilter filter]
: e=orDimFilter { $filter = $e.filter; }
;
orDimFilter returns [DimFilter filter]
: a=andDimFilter (OR^ b+=andDimFilter)* {
if($b.isEmpty()) $filter = $a.filter;
else {
List<DimFilter> rest = new ArrayList<DimFilter>();
for(AndDimFilterContext e : $b) rest.add(e.filter);
$filter = new OrDimFilter(Lists.asList($a.filter, rest.toArray(new DimFilter[]{})));
}
}
;
andDimFilter returns [DimFilter filter]
: a=primaryDimFilter (AND^ b+=primaryDimFilter)* {
if($b.isEmpty()) $filter = $a.filter;
else {
List<DimFilter> rest = new ArrayList<DimFilter>();
for(PrimaryDimFilterContext e : $b) rest.add(e.filter);
$filter = new AndDimFilter(Lists.asList($a.filter, rest.toArray(new DimFilter[]{})));
}
}
;
primaryDimFilter returns [DimFilter filter]
: e=selectorDimFilter { $filter = $e.filter; }
| NOT f=dimFilter { $filter = new NotDimFilter($f.filter); }
| OPEN! f=dimFilter CLOSE! { $filter = $f.filter; }
;
selectorDimFilter returns [SelectorDimFilter filter]
: dimension=IDENT '=' value=QUOTED_STRING {
$filter = new SelectorDimFilter($dimension.text, unescape($value.text));
}
;
timeFilter returns [org.joda.time.Interval interval, QueryGranularity granularity]
: 'timestamp' 'between' s=timestamp AND e=timestamp {
$interval = new org.joda.time.Interval($s.t, $e.t);
}
;
granularityFn returns [QueryGranularity granularity]
: 'granularity' OPEN! 'timestamp' ',' str=QUOTED_STRING CLOSE! {
String granStr = unescape($str.text);
try {
$granularity = QueryGranularity.fromString(granStr);
} catch(IllegalArgumentException e) {
$granularity = new PeriodGranularity(new Period(granStr), null, null);
}
}
;
timestamp returns [DateTime t]
: NUMBER {
String str = $NUMBER.text.trim();
try {
$t = new DateTime(NumberFormat.getInstance().parse(str));
}
catch(ParseException e) {
throw new IllegalArgumentException("Unable to parse number [" + str + "]");
}
}
| QUOTED_STRING { $t = new DateTime(unescape($QUOTED_STRING.text)); }
;
|
grammar DruidSQL;
@header {
import com.metamx.druid.aggregation.post.*;
import com.metamx.druid.aggregation.*;
import com.metamx.druid.query.filter.*;
import com.metamx.druid.query.dimension.*;
import com.metamx.druid.*;
import com.google.common.base.*;
import com.google.common.collect.Lists;
import org.joda.time.*;
import java.text.*;
import java.util.*;
}
@parser::members {
public Map<String, AggregatorFactory> aggregators = new LinkedHashMap<String, AggregatorFactory>();
public List<PostAggregator> postAggregators = new LinkedList<PostAggregator>();
public DimFilter filter;
public List<org.joda.time.Interval> intervals;
public QueryGranularity granularity = QueryGranularity.ALL;
public Map<String, DimensionSpec> groupByDimensions = new LinkedHashMap<String, DimensionSpec>();
String dataSourceName = null;
public String getDataSource() {
return dataSourceName;
}
public String unescape(String quoted) {
String unquote = quoted.trim().replaceFirst("^'(.*)'\$", "\$1");
return unquote.replace("''", "'");
}
AggregatorFactory evalAgg(String name, int fn) {
switch (fn) {
case SUM: return new DoubleSumAggregatorFactory("sum("+name+")", name);
case MIN: return new MinAggregatorFactory("min("+name+")", name);
case MAX: return new MaxAggregatorFactory("max("+name+")", name);
case COUNT: return new CountAggregatorFactory(name);
}
throw new IllegalArgumentException("Unknown function [" + fn + "]");
}
PostAggregator evalArithmeticPostAggregator(PostAggregator a, List<Token> ops, List<PostAggregator> b) {
if(b.isEmpty()) return a;
else {
int i = 0;
PostAggregator root = a;
while(i < ops.size()) {
List<PostAggregator> list = new LinkedList<PostAggregator>();
List<String> names = new LinkedList<String>();
names.add(root.getName());
list.add(root);
Token op = ops.get(i);
while(i < ops.size() && ops.get(i).getType() == op.getType()) {
PostAggregator e = b.get(i);
list.add(e);
names.add(e.getName());
i++;
}
root = new ArithmeticPostAggregator("("+Joiner.on(op.getText()).join(names)+")", op.getText(), list);
}
return root;
}
}
}
AND: 'and';
OR: 'or';
SUM: 'sum';
MIN: 'min';
MAX: 'max';
COUNT: 'count';
AS: 'as';
OPEN: '(';
CLOSE: ')';
STAR: '*';
NOT: '!' ;
PLUS: '+';
MINUS: '-';
DIV: '/';
COMMA: ',';
GROUP: 'group';
IDENT : (LETTER)(LETTER | DIGIT | '_')* ;
QUOTED_STRING : '\'' ( ESC | ~'\'' )*? '\'' ;
ESC : '\'' '\'';
NUMBER: ('+'|'-')?DIGIT*'.'?DIGIT+(EXPONENT)?;
EXPONENT: ('e') ('+'|'-')? ('0'..'9')+;
fragment DIGIT : '0'..'9';
fragment LETTER : 'a'..'z' | 'A'..'Z';
LINE_COMMENT : '--' .*? '\r'? '\n' -> skip ;
COMMENT : '/*' .*? '*/' -> skip ;
WS : (' '| '\t' | '\r' '\n' | '\n' | '\r')+ -> skip;
query
: select_stmt where_stmt (groupby_stmt)?
;
select_stmt
: 'select' e+=aliasedExpression (',' e+=aliasedExpression)* 'from' datasource {
for(AliasedExpressionContext a : $e) { postAggregators.add(a.p); }
this.dataSourceName = $datasource.text;
}
;
where_stmt
: 'where' f=timeAndDimFilter {
if($f.filter != null) this.filter = $f.filter;
this.intervals = Lists.newArrayList($f.interval);
}
;
groupby_stmt
: GROUP 'by' groupByExpression ( COMMA! groupByExpression )*
;
groupByExpression
: gran=granularityFn {this.granularity = $gran.granularity;}
| dim=IDENT { this.groupByDimensions.put($dim.text, new DefaultDimensionSpec($dim.text, $dim.text)); }
;
datasource
: IDENT
;
aliasedExpression returns [PostAggregator p]
: expression ( AS^ name=IDENT )? {
if($name != null) {
postAggregators.add($expression.p);
$p = new FieldAccessPostAggregator($name.text, $expression.p.getName());
}
else $p = $expression.p;
}
;
expression returns [PostAggregator p]
: additiveExpression { $p = $additiveExpression.p; }
;
additiveExpression returns [PostAggregator p]
: a=multiplyExpression (( ops+=PLUS^ | ops+=MINUS^ ) b+=multiplyExpression)* {
List<PostAggregator> rhs = new LinkedList<PostAggregator>();
for(MultiplyExpressionContext e : $b) rhs.add(e.p);
$p = evalArithmeticPostAggregator($a.p, $ops, rhs);
}
;
multiplyExpression returns [PostAggregator p]
: a=unaryExpression ((ops+= STAR | ops+=DIV ) b+=unaryExpression)* {
List<PostAggregator> rhs = new LinkedList<PostAggregator>();
for(UnaryExpressionContext e : $b) rhs.add(e.p);
$p = evalArithmeticPostAggregator($a.p, $ops, rhs);
}
;
unaryExpression returns [PostAggregator p]
: MINUS e=unaryExpression {
$p = new ArithmeticPostAggregator(
"-"+$e.p.getName(),
"*",
Lists.newArrayList($e.p, new ConstantPostAggregator("-1", -1.0))
);
}
| PLUS e=unaryExpression { $p = $e.p; }
| primaryExpression { $p = $primaryExpression.p; }
;
primaryExpression returns [PostAggregator p]
: constant { $p = $constant.c; }
| aggregate {
aggregators.put($aggregate.agg.getName(), $aggregate.agg);
$p = new FieldAccessPostAggregator($aggregate.agg.getName(), $aggregate.agg.getName());
}
| OPEN! e=expression CLOSE! { $p = $e.p; }
;
aggregate returns [AggregatorFactory agg]
: fn=( SUM^ | MIN^ | MAX^ ) OPEN! name=(IDENT|COUNT) CLOSE! { $agg = evalAgg($name.text, $fn.type); }
| fn=COUNT OPEN! STAR CLOSE! { $agg = evalAgg("count(*)", $fn.type); }
;
constant returns [ConstantPostAggregator c]
: value=NUMBER { double v = Double.parseDouble($value.text); $c = new ConstantPostAggregator(Double.toString(v), v); }
;
/* time filters must be top level filters */
timeAndDimFilter returns [DimFilter filter, org.joda.time.Interval interval]
: t=timeFilter (AND f=dimFilter)? {
if($f.ctx != null) $filter = $f.filter;
$interval = $t.interval;
}
| (f=dimFilter)? AND t=timeFilter {
if($f.ctx != null) $filter = $f.filter;
$interval = $t.interval;
}
;
dimFilter returns [DimFilter filter]
: e=orDimFilter { $filter = $e.filter; }
;
orDimFilter returns [DimFilter filter]
: a=andDimFilter (OR^ b+=andDimFilter)* {
if($b.isEmpty()) $filter = $a.filter;
else {
List<DimFilter> rest = new ArrayList<DimFilter>();
for(AndDimFilterContext e : $b) rest.add(e.filter);
$filter = new OrDimFilter(Lists.asList($a.filter, rest.toArray(new DimFilter[]{})));
}
}
;
andDimFilter returns [DimFilter filter]
: a=primaryDimFilter (AND^ b+=primaryDimFilter)* {
if($b.isEmpty()) $filter = $a.filter;
else {
List<DimFilter> rest = new ArrayList<DimFilter>();
for(PrimaryDimFilterContext e : $b) rest.add(e.filter);
$filter = new AndDimFilter(Lists.asList($a.filter, rest.toArray(new DimFilter[]{})));
}
}
;
primaryDimFilter returns [DimFilter filter]
: e=selectorDimFilter { $filter = $e.filter; }
| NOT f=dimFilter { $filter = new NotDimFilter($f.filter); }
| OPEN! f=dimFilter CLOSE! { $filter = $f.filter; }
;
selectorDimFilter returns [SelectorDimFilter filter]
: dimension=IDENT '=' value=QUOTED_STRING {
$filter = new SelectorDimFilter($dimension.text, unescape($value.text));
}
;
timeFilter returns [org.joda.time.Interval interval, QueryGranularity granularity]
: 'timestamp' 'between' s=timestamp AND e=timestamp {
$interval = new org.joda.time.Interval($s.t, $e.t);
}
;
granularityFn returns [QueryGranularity granularity]
: 'granularity' OPEN! 'timestamp' ',' str=QUOTED_STRING CLOSE! {
String granStr = unescape($str.text);
try {
$granularity = QueryGranularity.fromString(granStr);
} catch(IllegalArgumentException e) {
$granularity = new PeriodGranularity(new Period(granStr), null, null);
}
}
;
timestamp returns [DateTime t]
: NUMBER {
String str = $NUMBER.text.trim();
try {
$t = new DateTime(NumberFormat.getInstance().parse(str));
}
catch(ParseException e) {
throw new IllegalArgumentException("Unable to parse number [" + str + "]");
}
}
| QUOTED_STRING { $t = new DateTime(unescape($QUOTED_STRING.text)); }
;
|
remove obsolete comments
|
remove obsolete comments
|
ANTLR
|
apache-2.0
|
Deebs21/druid,metamx/druid,monetate/druid,haoch/druid,Deebs21/druid,amikey/druid,noddi/druid,skyportsystems/druid,zengzhihai110/druid,leventov/druid,elijah513/druid,druid-io/druid,767326791/druid,deltaprojects/druid,friedhardware/druid,se7entyse7en/druid,lcp0578/druid,rasahner/druid,minewhat/druid,Kleagleguo/druid,metamx/druid,zhiqinghuang/druid,lizhanhui/data_druid,leventov/druid,eshen1991/druid,deltaprojects/druid,haoch/druid,KurtYoung/druid,yaochitc/druid-dev,pombredanne/druid,zhaown/druid,guobingkun/druid,minewhat/druid,praveev/druid,lcp0578/druid,erikdubbelboer/druid,liquidm/druid,fjy/druid,zhihuij/druid,mrijke/druid,zhiqinghuang/druid,du00cs/druid,du00cs/druid,nvoron23/druid,winval/druid,premc/druid,KurtYoung/druid,monetate/druid,cocosli/druid,dclim/druid,eshen1991/druid,zhaown/druid,implydata/druid,b-slim/druid,milimetric/druid,amikey/druid,Deebs21/druid,zxs/druid,zhihuij/druid,andy256/druid,gianm/druid,leventov/druid,smartpcr/druid,Fokko/druid,redBorder/druid,cocosli/druid,pjain1/druid,implydata/druid,haoch/druid,lizhanhui/data_druid,leventov/druid,deltaprojects/druid,nvoron23/druid,andy256/druid,minewhat/druid,OttoOps/druid,pombredanne/druid,mghosh4/druid,pjain1/druid,erikdubbelboer/druid,penuel-leo/druid,zengzhihai110/druid,himanshug/druid,zhihuij/druid,mangeshpardeshiyahoo/druid,michaelschiff/druid,elijah513/druid,lcp0578/druid,mghosh4/druid,jon-wei/druid,mrijke/druid,deltaprojects/druid,winval/druid,dkhwangbo/druid,authbox-lib/druid,andy256/druid,pdeva/druid,winval/druid,noddi/druid,smartpcr/druid,nvoron23/druid,monetate/druid,nishantmonu51/druid,himanshug/druid,zhihuij/druid,zxs/druid,lcp0578/druid,zxs/druid,elijah513/druid,nishantmonu51/druid,andy256/druid,praveev/druid,michaelschiff/druid,pdeva/druid,rasahner/druid,pombredanne/druid,mangeshpardeshiyahoo/druid,wenjixin/druid,nvoron23/druid,pdeva/druid,guobingkun/druid,zhaown/druid,calliope7/druid,dkhwangbo/druid,calliope7/druid,taochaoqiang/druid,eshen1991/druid,redBorder/druid,winval/druid,taochaoqiang/druid,zhihuij/druid,mangeshpardeshiyahoo/druid,friedhardware/druid,taochaoqiang/druid,tubemogul/druid,nishantmonu51/druid,monetate/druid,praveev/druid,amikey/druid,implydata/druid,Fokko/druid,kevintvh/druid,anupkumardixit/druid,milimetric/druid,anupkumardixit/druid,milimetric/druid,solimant/druid,deltaprojects/druid,Deebs21/druid,solimant/druid,tubemogul/druid,mrijke/druid,solimant/druid,yaochitc/druid-dev,druid-io/druid,potto007/druid-avro,qix/druid,elijah513/druid,solimant/druid,fjy/druid,OttoOps/druid,anupkumardixit/druid,skyportsystems/druid,optimizely/druid,leventov/druid,potto007/druid-avro,du00cs/druid,calliope7/druid,zxs/druid,767326791/druid,wenjixin/druid,wenjixin/druid,Kleagleguo/druid,tubemogul/druid,du00cs/druid,friedhardware/druid,du00cs/druid,pombredanne/druid,michaelschiff/druid,mghosh4/druid,skyportsystems/druid,mangeshpardeshiyahoo/druid,kevintvh/druid,erikdubbelboer/druid,zengzhihai110/druid,smartpcr/druid,jon-wei/druid,liquidm/druid,pjain1/druid,knoguchi/druid,premc/druid,b-slim/druid,kevintvh/druid,knoguchi/druid,mghosh4/druid,zhiqinghuang/druid,nishantmonu51/druid,optimizely/druid,767326791/druid,praveev/druid,anupkumardixit/druid,lizhanhui/data_druid,pdeva/druid,michaelschiff/druid,potto007/druid-avro,haoch/druid,premc/druid,optimizely/druid,mghosh4/druid,elijah513/druid,yaochitc/druid-dev,liquidm/druid,friedhardware/druid,gianm/druid,rasahner/druid,friedhardware/druid,noddi/druid,eshen1991/druid,penuel-leo/druid,pjain1/druid,knoguchi/druid,liquidm/druid,b-slim/druid,skyportsystems/druid,qix/druid,Fokko/druid,optimizely/druid,KurtYoung/druid,jon-wei/druid,pdeva/druid,noddi/druid,nishantmonu51/druid,fjy/druid,Fokko/druid,solimant/druid,KurtYoung/druid,knoguchi/druid,se7entyse7en/druid,optimizely/druid,implydata/druid,praveev/druid,andy256/druid,nishantmonu51/druid,b-slim/druid,dkhwangbo/druid,Kleagleguo/druid,druid-io/druid,OttoOps/druid,kevintvh/druid,OttoOps/druid,penuel-leo/druid,mrijke/druid,erikdubbelboer/druid,eshen1991/druid,zhaown/druid,deltaprojects/druid,authbox-lib/druid,druid-io/druid,zhaown/druid,michaelschiff/druid,calliope7/druid,Fokko/druid,milimetric/druid,amikey/druid,winval/druid,yaochitc/druid-dev,dkhwangbo/druid,deltaprojects/druid,gianm/druid,Kleagleguo/druid,cocosli/druid,se7entyse7en/druid,amikey/druid,Fokko/druid,skyportsystems/druid,monetate/druid,Fokko/druid,jon-wei/druid,jon-wei/druid,se7entyse7en/druid,fjy/druid,nvoron23/druid,Deebs21/druid,dclim/druid,himanshug/druid,minewhat/druid,gianm/druid,authbox-lib/druid,767326791/druid,druid-io/druid,potto007/druid-avro,lizhanhui/data_druid,zhiqinghuang/druid,metamx/druid,himanshug/druid,implydata/druid,wenjixin/druid,zhiqinghuang/druid,mghosh4/druid,potto007/druid-avro,dclim/druid,rasahner/druid,mghosh4/druid,lcp0578/druid,taochaoqiang/druid,pjain1/druid,dkhwangbo/druid,monetate/druid,tubemogul/druid,knoguchi/druid,guobingkun/druid,qix/druid,haoch/druid,authbox-lib/druid,jon-wei/druid,guobingkun/druid,michaelschiff/druid,kevintvh/druid,penuel-leo/druid,b-slim/druid,rasahner/druid,penuel-leo/druid,liquidm/druid,KurtYoung/druid,monetate/druid,tubemogul/druid,himanshug/druid,metamx/druid,guobingkun/druid,redBorder/druid,redBorder/druid,lizhanhui/data_druid,qix/druid,OttoOps/druid,zengzhihai110/druid,wenjixin/druid,anupkumardixit/druid,dclim/druid,nishantmonu51/druid,Kleagleguo/druid,premc/druid,implydata/druid,noddi/druid,mrijke/druid,milimetric/druid,cocosli/druid,pjain1/druid,michaelschiff/druid,gianm/druid,gianm/druid,dclim/druid,metamx/druid,gianm/druid,cocosli/druid,pjain1/druid,pombredanne/druid,calliope7/druid,authbox-lib/druid,fjy/druid,qix/druid,redBorder/druid,liquidm/druid,erikdubbelboer/druid,smartpcr/druid,smartpcr/druid,jon-wei/druid,yaochitc/druid-dev,767326791/druid,premc/druid,taochaoqiang/druid,mangeshpardeshiyahoo/druid,zengzhihai110/druid,zxs/druid,se7entyse7en/druid,minewhat/druid
|
c1b4661a9caf3dad712bd6a2f8d8533bab53b88a
|
mumps/mumps.g4
|
mumps/mumps.g4
|
/*
BSD License
Copyright (c) 2013, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar mumps;
program
: routine+
;
routine
: routinename routinebody
;
routinename
: PERCENT? identifier (LPAREN paramlist? RPAREN)? (SPACE+ comment)? CR
;
paramlist
: param (COMMA param)*
;
param
: variable
;
routinebody
: line+
;
line
: SPACE+ (label SPACE)? command* (SPACE+ comment)? CR
;
label
: identifier
;
command
: set
| form
| commandname (SPACE arglist)?
;
commandname
: (BREAK | CLOSE | DO | ELSE | FOR | GOTO | HALT | HANG | IF | JOB
| KILL | LOCK | MERGE | NEW | OPEN | QUIT | READ | SET | TCOMMIT
| TRESTART | TROLLBACK | TSTART | USE | VIEW | WRITE1 | WRITE2 | XECUTE)
;
arglist
: arg (SPACE* COMMA arg)*
;
arg
: expression
| (BANG
| STRING_LITERAL)
;
expression
: term (SPACE* (ADD | MULTIPLY | SUBTRACT | DIVIDE) expression)*
;
term
: variable
| NUMBER
| LPAREN expression RPAREN
;
comment
: SEMICOLON ~(CR)*
;
identifier
: IDENTIFIER
;
variable
: (CARAT | DOLLAR | AMPERSAND)* identifier
;
set
: SET SPACE+ assign (',' assign)*
;
assign
: (LPAREN? arglist RPAREN?)? SPACE* EQUALS SPACE* arg
;
form
: FOR SPACE+ term EQUALS term COLON term SPACE* (command SPACE?)* COLON (term (LT | GT) term)
;
BREAK
: B R E A K
;
CLOSE
: C L O S E
;
DO
: D O
;
ELSE
: E L S E
;
FOR
: F O R
;
GOTO
: G O T O
;
HALT
: H A L T
;
HANG
: H A N G
;
IF
: I F
;
JOB
: J O B
;
KILL
: K I L L
;
LOCK
: L O C K
;
MERGE
: M E R G E
;
NEW
: N E W
;
OPEN
: O P E N
;
QUIT
: Q U I T
;
READ
: R E A D
;
SET
: S E T
;
TCOMMIT
: T C O M M I T
;
TRESTART
: T R E S T A R T
;
TROLLBACK
: T R O L L B A C K
;
TSTART
: T S T A R T
;
USE
: U S E
;
VIEW
: V I E W
;
WRITE1
: W R I T E
;
WRITE2
: W
;
XECUTE
: X E C U T E
;
SEMICOLON
: ';'
;
COLON
: ':'
;
COMMA
: ','
;
DOLLAR
: '$'
;
PERCENT
: '%'
;
AMPERSAND
: '&'
;
INDIRECT
: '@'
;
CARAT
: '^'
;
BANG
: '!'
;
LPAREN
: '('
;
RPAREN
: ')'
;
GT
: '>'
;
LT
: '<'
;
ADD
: '+'
;
SUBTRACT
: '-'
;
MULTIPLY
: '*'
;
DIVIDE
: '/'
;
EQUALS
: '='
;
IDENTIFIER
: ('a'..'z' | 'A'..'Z') ('a'..'z'|'A'..'Z'|'0'..'9')*
;
STRING_LITERAL
: '\"' ('\"\"' | ~('\"'))* '\"'
;
NUMBER
: ('0'..'9')+ ('.' ('0'..'9')+)?
;
SPACE
: ' '
;
fragment A:('a'|'A');
fragment B:('b'|'B');
fragment C:('c'|'C');
fragment D:('d'|'D');
fragment E:('e'|'E');
fragment F:('f'|'F');
fragment G:('g'|'G');
fragment H:('h'|'H');
fragment I:('i'|'I');
fragment J:('j'|'J');
fragment K:('k'|'K');
fragment L:('l'|'L');
fragment M:('m'|'M');
fragment N:('n'|'N');
fragment O:('o'|'O');
fragment P:('p'|'P');
fragment Q:('q'|'Q');
fragment R:('r'|'R');
fragment S:('s'|'S');
fragment T:('t'|'T');
fragment U:('u'|'U');
fragment V:('v'|'V');
fragment W:('w'|'W');
fragment X:('x'|'X');
fragment Y:('y'|'Y');
fragment Z:('z'|'Z');
CR
: '\n'
;
WS
: [\t]->skip
;
|
/*
BSD License
Copyright (c) 2013, Tom Everett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Tom Everett nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar mumps;
program
: routine+
;
routine
: routinename routinebody
;
routinename
: PERCENT? identifier (LPAREN paramlist? RPAREN)? (SPACE+ comment)? CR
;
paramlist
: param (COMMA param)*
;
param
: variable
;
routinebody
: line+
;
line
: SPACE+ (label SPACE)? command* (SPACE+ comment)? CR
;
label
: identifier
;
command
: set
| form
| commandname (SPACE arglist)?
;
commandname
: (BREAK | CLOSE | DO | ELSE | GOTO | HALT | HANG | IF | JOB
| KILL | LOCK | MERGE | NEW | OPEN | READ | TCOMMIT
| TRESTART | TROLLBACK | TSTART | USE | VIEW| XECUTE)
| set
| form
| write
| quit
;
arglist
: arg (SPACE* COMMA arg)*
;
arg
: expression
| (BANG
| STRING_LITERAL)
;
expression
: term (SPACE* (ADD | MULTIPLY | SUBTRACT | DIVIDE) expression)*
;
term
: variable
| NUMBER
| LPAREN expression RPAREN
;
comment
: SEMICOLON ~(CR)*
;
identifier
: IDENTIFIER
;
variable
: (CARAT | DOLLAR | AMPERSAND)* identifier
;
set
: (SET1 | SET2) SPACE+ assign (',' assign)*
;
assign
: (LPAREN? arglist RPAREN?)? SPACE* EQUALS SPACE* arg
;
form
: FOR SPACE+ term EQUALS term COLON term SPACE* (command SPACE?)* COLON (term (LT | GT) term)
;
write
: (WRITE1 | WRITE2) SPACE* arglist
;
quit
: QUIT
;
BREAK
: B R E A K
;
CLOSE
: C L O S E
;
DO
: D O
;
ELSE
: E L S E
;
FOR
: F O R
;
GOTO
: G O T O
;
HALT
: H A L T
;
HANG
: H A N G
;
IF
: I F
;
JOB
: J O B
;
KILL
: K I L L
;
LOCK
: L O C K
;
MERGE
: M E R G E
;
NEW
: N E W
;
OPEN
: O P E N
;
QUIT
: Q U I T
;
READ
: R E A D
;
SET1
: S E T
;
SET2
: S
;
TCOMMIT
: T C O M M I T
;
TRESTART
: T R E S T A R T
;
TROLLBACK
: T R O L L B A C K
;
TSTART
: T S T A R T
;
USE
: U S E
;
VIEW
: V I E W
;
WRITE1
: W R I T E
;
WRITE2
: W
;
XECUTE
: X E C U T E
;
SEMICOLON
: ';'
;
COLON
: ':'
;
COMMA
: ','
;
DOLLAR
: '$'
;
PERCENT
: '%'
;
AMPERSAND
: '&'
;
INDIRECT
: '@'
;
CARAT
: '^'
;
BANG
: '!'
;
LPAREN
: '('
;
RPAREN
: ')'
;
GT
: '>'
;
LT
: '<'
;
ADD
: '+'
;
SUBTRACT
: '-'
;
MULTIPLY
: '*'
;
DIVIDE
: '/'
;
EQUALS
: '='
;
IDENTIFIER
: ('a'..'z' | 'A'..'Z') ('a'..'z'|'A'..'Z'|'0'..'9')*
;
STRING_LITERAL
: '\"' ('\"\"' | ~('\"'))* '\"'
;
NUMBER
: ('0'..'9')+ ('.' ('0'..'9')+)?
;
SPACE
: ' '
;
fragment A:('a'|'A');
fragment B:('b'|'B');
fragment C:('c'|'C');
fragment D:('d'|'D');
fragment E:('e'|'E');
fragment F:('f'|'F');
fragment G:('g'|'G');
fragment H:('h'|'H');
fragment I:('i'|'I');
fragment J:('j'|'J');
fragment K:('k'|'K');
fragment L:('l'|'L');
fragment M:('m'|'M');
fragment N:('n'|'N');
fragment O:('o'|'O');
fragment P:('p'|'P');
fragment Q:('q'|'Q');
fragment R:('r'|'R');
fragment S:('s'|'S');
fragment T:('t'|'T');
fragment U:('u'|'U');
fragment V:('v'|'V');
fragment W:('w'|'W');
fragment X:('x'|'X');
fragment Y:('y'|'Y');
fragment Z:('z'|'Z');
CR
: '\n'
;
WS
: [\t]->skip
;
|
break out the commands
|
break out the commands
|
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
|
995a32bff307a94bdcdff1de786d00daf35900b6
|
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;
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;
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 grantee
|
add grantee
|
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
|
8c1739f6adf9b2e87568208f4b27e10e1fd3c0b0
|
sdmap/src/sdmap/Parser/G4/Sdmap.g4
|
sdmap/src/sdmap/Parser/G4/Sdmap.g4
|
grammar Sdmap;
options { tokenVocab=SdmapLexerBase; }
root:
namespace | namedSql*;
namespace:
'namespace' NSSyntax
'{'
namedSql*
'}';
coreSql:
(directive | plainText)+;
plainText:
SQLText;
namedSql:
BeginNamedSql
coreSql
EndSql;
unnamedSql:
BeginUnnamedSql
coreSql
EndSql;
directive:
BeginMacro
directiveParameters*
EndMacro;
directiveParameters:
NSSyntax |
value |
unnamedSql;
value:
STRING |
NUMBER |
DATE;
|
grammar Sdmap;
options { tokenVocab=SdmapLexerBase; }
root:
namespace | namedSql*;
namespace:
'namespace' NSSyntax
'{'
namedSql*
'}';
coreSql:
(macro | plainText)+;
plainText:
SQLText;
namedSql:
BeginNamedSql
coreSql
EndSql;
unnamedSql:
BeginUnnamedSql
coreSql
EndSql;
macro:
BeginMacro
macroParameter? (',' macroParameter)*
EndMacro;
macroParameter:
NSSyntax |
value |
unnamedSql;
value:
STRING |
NUMBER |
DATE;
|
rename directive to macro
|
rename directive to macro
|
ANTLR
|
mit
|
sdcb/sdmap
|
f59b69c28e2580b295b3e3e765569e47f489a320
|
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
( ( 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;
|
// 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 (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 | POWER expr)
(comp_for | (COMMA (test COLON test | POWER expr))* (COMMA)?)) |
((test | star_expr)
(comp_for | (COMMA (test | star_expr))* (COMMA)?)) )
;
classdef: CLASS NAME (OPEN_PAREN (arglist)? CLOSE_PAREN)? COLON suite
;
arglist: argument (COMMA argument)* (COMMA)?
// The reason that keywords are test nodes instead of NAME is that using NAME
// results in an ambiguity. ast.c makes sure it's a NAME.
;
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 for Annotated assignment and dictionary initializer
|
Fix for Annotated assignment and dictionary initializer
|
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
|
b4f01259d97f62c303c33eed56eb7d4369f6c43c
|
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
|
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
|
/* Todo:
* - Comments justifying and explaining every rule.
*/
lexer grammar CreoleTokens;
options { superClass=ContextSensitiveLexer; }
@members {
Formatting bold;
Formatting italic;
Formatting strike;
public void setupFormatting() {
bold = new Formatting("**");
italic = new Formatting("//");
strike = new Formatting("--");
inlineFormatting.add(bold);
inlineFormatting.add(italic);
inlineFormatting.add(strike);
}
public boolean inHeader = false;
public boolean start = false;
public int listLevel = 0;
boolean nowiki = false;
boolean cpp = false;
boolean html = false;
boolean java = false;
boolean xhtml = false;
boolean xml = false;
boolean intr = false;
public void doHdr() {
String prefix = getText().trim();
boolean seekback = false;
if(!prefix.substring(prefix.length() - 1).equals("=")) {
prefix = prefix.substring(0, prefix.length() - 1);
seekback = true;
}
if(prefix.length() <= 6) {
if(seekback) {
seek(-1);
}
setText(prefix);
inHeader = true;
} else {
setType(Any);
}
}
public void setStart() {
String next1 = next();
String next2 = get(1);
start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#"));
}
public void doList(int level) {
listLevel = level;
seek(-1);
setStart();
resetFormatting();
}
public void doUrl() {
String url = getText();
String last = url.substring(url.length()-1);
String next = next();
if((last + next).equals("//") || last.equals(".") || last.equals(",")) {
seek(-1);
setText(url.substring(0, url.length() - 1));
}
}
public void breakOut() {
resetFormatting();
listLevel = 0;
inHeader = false;
intr = false;
nowiki = false;
cpp = false;
html = false;
java = false;
xhtml = false;
xml = false;
}
public String[] thisKillsTheFormatting() {
String[] ends = new String[4];
if(inHeader || intr || listLevel > 0) {
ends[0] = "\n";
} else {
ends[0] = null;
}
if(intr) {
ends[1] = "|";
} else {
ends[1] = null;
}
ends[2] = "\n\n";
ends[3] = "\r\n\r\n";
return ends;
}
public boolean checkWW() {
String ww = getText();
String prior = get(-ww.length() - 1);
String next = next();
return !(prior.matches("\\w") || next.matches("\\w"));
}
}
/* ***** Headings ***** */
HSt : LINE '='+ ~'=' WS? {doHdr();} ;
HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ;
/* ***** Lists ***** */
U1 : START '*' ~'*' {doList(1);} ;
U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ;
U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ;
U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ;
U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ;
O1 : START '#' ~'#' {doList(1);} ;
O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ;
O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ;
O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ;
O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ;
/* ***** Horizontal Rules ***** */
Rule : LINE '---' '-'+? {breakOut();} ;
/* ***** Tables ***** */
TdStartLn : LINE '|' {intr=true; setType(TdStart);} ;
ThStartLn : LINE '|=' {intr=true; setType(ThStart);} ;
RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ;
TdStart : '|' {intr}? {breakOut(); intr=true;} ;
ThStart : '|=' {intr}? {breakOut(); intr=true;} ;
/* ***** Inline Formatting ***** */
BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ;
ISt : '//' {!italic.active}? {setFormatting(italic, Any);} ;
SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ;
BEnd : '**' {bold.active}? {unsetFormatting(bold);} ;
IEnd : '//' {italic.active}? {unsetFormatting(italic);} ;
SEnd : '--' {strike.active}? {unsetFormatting(strike);} ;
NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ;
StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ;
StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ;
StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ;
StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ;
StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ;
/* ***** Links ***** */
LiSt : '[[' -> mode(LINK) ;
ImSt : '{{' -> mode(LINK) ;
/* ***** Breaks ***** */
InlineBrk : '\\\\' ;
ParBreak : LineBreak LineBreak+ {breakOut();} ;
LineBreak : '\r'? '\n' ;
/* ***** Links ***** */
RawUrl : (('http' 's'? | 'ftp') '://' | 'mailto:') (~(' '|'\t'|'\r'|'\n'|'/'|'|'|'['|']')+ '/'?)+ {doUrl();};
WikiWords : ((INTERWIKI UPNUM | UPPER) (ABBR | CAMEL) | INTERWIKI UPNUM+) {checkWW()}? ;
fragment INTERWIKI : ALPHA+ ':' ;
fragment ABBR : UPPER UPPER+ ;
fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ;
/* ***** Macros ***** */
MacroSt : '<<' -> mode(MACRO) ;
/* ***** Miscellaneous ***** */
Any : . ;
WS : (' '|'\t')+ ;
fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ;
fragment START : {start}? | LINE ;
fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*;
fragment LOWNUM : (LOWER | DIGIT) ;
fragment UPNUM : (UPPER | DIGIT) ;
fragment ALNUM : (ALPHA | DIGIT) ;
fragment ALPHA : (UPPER | LOWER) ;
fragment UPPER : ('A'..'Z') ;
fragment LOWER : ('a'..'z') ;
fragment DIGIT : ('0'..'9') ;
/* ***** Contextual stuff ***** */
mode LINK;
LiEnd : ']]' -> mode(DEFAULT_MODE) ;
ImEnd : '}}' -> mode(DEFAULT_MODE) ;
Sep : '|' ;
InLink : ~(']'|'}'|'|')+ ;
mode MACRO;
MacroName : ~(':'|'>')+ ;
MacroSep : ':' -> mode(MACRO_ARGS) ;
mode MACRO_ARGS;
MacroArgs : . -> more ;
MacroEnd : '>>' -> mode(DEFAULT_MODE) ;
mode CODE_INLINE;
AnyInline : ~('\r'|'\n') -> more;
OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ;
EndNoWikiInline : '}}}' (~'}' {seek(-1);} | EOF) {nowiki}? -> mode(DEFAULT_MODE) ;
EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ;
EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ;
EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ;
EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ;
EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
mode CODE_BLOCK;
AnyText : . -> more ;
EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ;
EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ;
EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ;
EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ;
EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ;
EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
|
/* Todo:
* - Comments justifying and explaining every rule.
*/
lexer grammar CreoleTokens;
options { superClass=ContextSensitiveLexer; }
@members {
Formatting bold;
Formatting italic;
Formatting strike;
public void setupFormatting() {
bold = new Formatting("**");
italic = new Formatting("//");
strike = new Formatting("--");
inlineFormatting.add(bold);
inlineFormatting.add(italic);
inlineFormatting.add(strike);
}
public boolean inHeader = false;
public boolean start = false;
public int listLevel = 0;
boolean nowiki = false;
boolean cpp = false;
boolean html = false;
boolean java = false;
boolean xhtml = false;
boolean xml = false;
boolean intr = false;
public void doHdr() {
String prefix = getText().trim();
boolean seekback = false;
if(!prefix.substring(prefix.length() - 1).equals("=")) {
prefix = prefix.substring(0, prefix.length() - 1);
seekback = true;
}
if(prefix.length() <= 6) {
if(seekback) {
seek(-1);
}
setText(prefix);
inHeader = true;
} else {
setType(Any);
}
}
public void setStart() {
String next1 = next();
String next2 = get(1);
start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#"));
}
public void doList(int level) {
listLevel = level;
seek(-1);
setStart();
resetFormatting();
}
public void doUrl() {
String url = getText();
String last = url.substring(url.length()-1);
String next = next();
if((last + next).equals("//") || last.equals(".") || last.equals(",")) {
seek(-1);
setText(url.substring(0, url.length() - 1));
}
}
public void breakOut() {
resetFormatting();
listLevel = 0;
inHeader = false;
intr = false;
nowiki = false;
cpp = false;
html = false;
java = false;
xhtml = false;
xml = false;
}
public String[] thisKillsTheFormatting() {
String[] ends = new String[4];
if(inHeader || intr || listLevel > 0) {
ends[0] = "\n";
} else {
ends[0] = null;
}
if(intr) {
ends[1] = "|";
} else {
ends[1] = null;
}
ends[2] = "\n\n";
ends[3] = "\r\n\r\n";
return ends;
}
public boolean checkWW() {
String ww = getText();
String prior = get(-ww.length() - 1);
String next = next();
return !(prior.matches("\\w") || next.matches("\\w"));
}
}
/* ***** Headings ***** */
HSt : LINE '='+ ~'=' WS? {doHdr();} ;
HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ;
/* ***** Lists ***** */
U1 : START '*' ~'*' {doList(1);} ;
U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ;
U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ;
U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ;
U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ;
O1 : START '#' ~'#' {doList(1);} ;
O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ;
O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ;
O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ;
O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ;
/* ***** Horizontal Rules ***** */
Rule : LINE '---' '-'+? {breakOut();} ;
/* ***** Tables ***** */
TdStartLn : LINE '|' {intr=true; setType(TdStart);} ;
ThStartLn : LINE '|=' {intr=true; setType(ThStart);} ;
RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ;
TdStart : '|' {intr}? {breakOut(); intr=true;} ;
ThStart : '|=' {intr}? {breakOut(); intr=true;} ;
/* ***** Inline Formatting ***** */
BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ;
ISt : '//' {!italic.active}? {setFormatting(italic, Any);} ;
SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ;
BEnd : '**' {bold.active}? {unsetFormatting(bold);} ;
IEnd : '//' {italic.active}? {unsetFormatting(italic);} ;
SEnd : '--' {strike.active}? {unsetFormatting(strike);} ;
NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ;
StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ;
StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ;
StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ;
StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ;
StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ;
/* ***** Links ***** */
LiSt : '[[' -> mode(LINK) ;
ImSt : '{{' -> mode(LINK) ;
/* ***** Breaks ***** */
InlineBrk : '\\\\' ;
ParBreak : LineBreak LineBreak+ {breakOut();} ;
LineBreak : '\r'? '\n' ;
/* ***** Links ***** */
RawUrl : (('http' 's'? | 'ftp') '://' | 'mailto:') (~(' '|'\t'|'\r'|'\n'|'/'|'|'|'['|']')+ '/'?)+ {doUrl();};
WikiWords : ((INTERWIKI UPNUM | UPPER) (ABBR | CAMEL) | INTERWIKI UPNUM+) {checkWW()}? ;
fragment INTERWIKI : ALPHA+ ':' ;
fragment ABBR : UPPER UPPER+ ;
fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ;
/* ***** Macros ***** */
MacroSt : '<<' -> mode(MACRO) ;
/* ***** Miscellaneous ***** */
Any : . ;
WS : (' '|'\t')+ ;
fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ;
fragment START : {start}? | LINE ;
fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*;
fragment LOWNUM : (LOWER | DIGIT) ;
fragment UPNUM : (UPPER | DIGIT) ;
fragment ALNUM : (ALPHA | DIGIT) ;
fragment ALPHA : (UPPER | LOWER) ;
fragment UPPER : ('A'..'Z') ;
fragment LOWER : ('a'..'z') ;
fragment DIGIT : ('0'..'9') ;
/* ***** Contextual stuff ***** */
mode LINK;
LiEnd : ']]' -> mode(DEFAULT_MODE) ;
ImEnd : '}}' -> mode(DEFAULT_MODE) ;
Sep : ' '* '|' ' '*;
InLink : ~(']'|'}'|'|')+ {setText(getText().trim());};
mode MACRO;
MacroName : ~(':'|'>')+ ;
MacroSep : ':' -> mode(MACRO_ARGS) ;
mode MACRO_ARGS;
MacroArgs : . -> more ;
MacroEnd : '>>' -> mode(DEFAULT_MODE) ;
mode CODE_INLINE;
AnyInline : ~('\r'|'\n') -> more;
OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ;
EndNoWikiInline : '}}}' (~'}' {seek(-1);} | EOF) {nowiki}? -> mode(DEFAULT_MODE) ;
EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ;
EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ;
EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ;
EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ;
EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
mode CODE_BLOCK;
AnyText : . -> more ;
EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ;
EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ;
EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ;
EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ;
EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ;
EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
|
Trim off whitespace in link tags
|
Trim off whitespace in link tags
|
ANTLR
|
apache-2.0
|
CoreFiling/reviki,ashirley/reviki,ashirley/reviki,strr/reviki,strr/reviki,strr/reviki,CoreFiling/reviki,ashirley/reviki,strr/reviki,ashirley/reviki,strr/reviki,CoreFiling/reviki,CoreFiling/reviki,ashirley/reviki,CoreFiling/reviki
|
3edc28b7a1f1ff4a40ef1ebb8c14bb28848d34bf
|
xpath/xpath.g4
|
xpath/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]>
*/
/*
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.
*/
main : expr
;
locationPath
: relativeLocationPath
| absoluteLocationPathNoroot
;
absoluteLocationPathNoroot
: '/' relativeLocationPath
| '//' relativeLocationPath
;
relativeLocationPath
: step (('/'|'//') step)*
;
step : axisSpecifier nodeTest predicate*
| abbreviatedStep
;
axisSpecifier
: AxisName '::'
| '@'?
;
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
;
variableReference
: '$' qName
;
nameTest: '*'
| nCName ':' '*'
| qName
;
nCName : NCName
| AxisName
| NodeType
;
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
: '"';
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]>
*/
/*
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.
*/
main : expr
;
locationPath
: relativeLocationPath
| absoluteLocationPathNoroot
;
absoluteLocationPathNoroot
: '/' relativeLocationPath
| '//' relativeLocationPath
;
relativeLocationPath
: step (('/'|'//') step)*
;
step : axisSpecifier nodeTest predicate*
| abbreviatedStep
;
axisSpecifier
: AxisName '::'
| '@'?
;
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
;
variableReference
: '$' qName
;
nameTest: '*'
| nCName ':' '*'
| qName
;
nCName : NCName
| AxisName
| NodeType
;
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
: '"';
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'
;
|
Fix xpath unicode TODO
|
Fix xpath unicode TODO
antlr-4.7 can handle unicode larger than U+FFFF, use the appropriate
syntax to express them -- thus addressing a leftover TODO.
Signed-off-by: Robert Varga <[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
|
ce5cd8e68a9168b66151bf45f368a4d10325bfcf
|
sharding-core/sharding-core-parse/sharding-core-parse-oracle/src/main/antlr4/imports/oracle/DDLStatement.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-oracle/src/main/antlr4/imports/oracle/DDLStatement.g4
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE temporaryClause_ TABLE tableName relationalTable
;
createIndex
: CREATE (UNIQUE | BITMAP)? INDEX indexName ON (tableIndexClause_ | bitmapJoinIndexClause_)
;
alterTable
: ALTER TABLE tableName (alterTableProperties | columnClauses | constraintClauses | alterExternalTable)?
;
// TODO hongjun throw exeption when alter index on oracle
alterIndex
: ALTER INDEX indexName (RENAME TO indexName)?
;
dropTable
: DROP TABLE tableName
;
dropIndex
: DROP INDEX indexName
;
truncateTable
: TRUNCATE TABLE tableName
;
temporaryClause_
: (GLOBAL TEMPORARY)?
;
tablespaceClauseWithParen
: LP_ tablespaceClause RP_
;
tablespaceClause
: TABLESPACE ignoredIdentifier_
;
domainIndexClause
: indexTypeName
;
relationalTable
: (LP_ relationalProperties RP_)? (ON COMMIT (DELETE | PRESERVE) ROWS)?
;
relationalProperties
: relationalProperty (COMMA_ relationalProperty)*
;
relationalProperty
: columnDefinition | virtualColumnDefinition | outOfLineConstraint | outOfLineRefConstraint
;
tableProperties
: columnProperties? (AS unionSelect)?
;
unionSelect
: matchNone
;
alterTableProperties
: renameTableSpecification_ | REKEY encryptionSpec
;
renameTableSpecification_
: RENAME TO newTableName
;
newTableName
: IDENTIFIER_
;
columnClauses
: opColumnClause+ | renameColumnSpecification
;
opColumnClause
: addColumnSpecification | modifyColumnSpecification | dropColumnClause
;
addColumnSpecification
: ADD columnOrVirtualDefinitions columnProperties?
;
columnOrVirtualDefinitions
: LP_ columnOrVirtualDefinition (COMMA_ columnOrVirtualDefinition)* RP_ | columnOrVirtualDefinition
;
columnOrVirtualDefinition
: columnDefinition | virtualColumnDefinition
;
modifyColumnSpecification
: MODIFY (LP_? modifyColProperties (COMMA_ modifyColProperties)* RP_? | modifyColSubstitutable)
;
modifyColProperties
: columnName dataType? (DEFAULT expr)? (ENCRYPT encryptionSpec | DECRYPT)? inlineConstraint*
;
modifyColSubstitutable
: COLUMN columnName NOT? SUBSTITUTABLE AT ALL LEVELS FORCE?
;
dropColumnClause
: SET UNUSED columnOrColumnList cascadeOrInvalidate* | dropColumnSpecification
;
dropColumnSpecification
: DROP columnOrColumnList cascadeOrInvalidate* checkpointNumber?
;
columnOrColumnList
: COLUMN columnName | LP_ columnName (COMMA_ columnName)* RP_
;
cascadeOrInvalidate
: CASCADE CONSTRAINTS | INVALIDATE
;
checkpointNumber
: CHECKPOINT NUMBER_
;
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
constraintClauses
: addConstraintSpecification | modifyConstraintClause | renameConstraintClause | dropConstraintClause+
;
addConstraintSpecification
: ADD (outOfLineConstraint+ | outOfLineRefConstraint)
;
modifyConstraintClause
: MODIFY constraintOption constraintState+ CASCADE?
;
constraintWithName
: CONSTRAINT ignoredIdentifier_
;
constraintOption
: constraintWithName | constraintPrimaryOrUnique
;
constraintPrimaryOrUnique
: primaryKey | UNIQUE columnNames
;
renameConstraintClause
: RENAME constraintWithName TO ignoredIdentifier_
;
dropConstraintClause
: DROP
(
constraintPrimaryOrUnique CASCADE? ((KEEP | DROP) INDEX)? | (CONSTRAINT ignoredIdentifier_ CASCADE?)
)
;
alterExternalTable
: (addColumnSpecification | modifyColumnSpecification | dropColumnSpecification)+
;
columnDefinition
: columnName dataType SORT? (VISIBLE | INVISIBLE)? (DEFAULT (ON NULL)? expr | identityClause)? (ENCRYPT encryptionSpec)? (inlineConstraint+ | inlineRefConstraint)?
;
identityClause
: GENERATED (ALWAYS | BY DEFAULT (ON NULL)?) AS IDENTITY LP_? (identityOptions+)? RP_?
;
identityOptions
: START WITH (NUMBER_ | LIMIT VALUE)
| INCREMENT BY NUMBER_
| MAXVALUE NUMBER_
| NOMAXVALUE
| MINVALUE NUMBER_
| NOMINVALUE
| CYCLE
| NOCYCLE
| CACHE NUMBER_
| NOCACHE
| ORDER
| NOORDER
;
virtualColumnDefinition
: columnName dataType? (GENERATED ALWAYS)? AS LP_ expr RP_ VIRTUAL? inlineConstraint*
;
inlineConstraint
: (CONSTRAINT ignoredIdentifier_)? (NOT? NULL | UNIQUE | primaryKey | referencesClause | CHECK LP_ expr RP_) constraintState*
;
referencesClause
: REFERENCES tableName columnNames? (ON DELETE (CASCADE | SET NULL))?
;
constraintState
: notDeferrable
| initiallyClause
| RELY | NORELY
| usingIndexClause
| ENABLE | DISABLE
| VALIDATE | NOVALIDATE
| exceptionsClause
;
notDeferrable
: NOT? DEFERRABLE
;
initiallyClause
: INITIALLY (IMMEDIATE | DEFERRED)
;
exceptionsClause
: EXCEPTIONS INTO tableName
;
usingIndexClause
: USING INDEX (indexName | LP_ createIndex RP_)?
;
inlineRefConstraint
: SCOPE IS tableName | WITH ROWID | (CONSTRAINT ignoredIdentifier_)? referencesClause constraintState*
;
outOfLineConstraint
: (CONSTRAINT ignoredIdentifier_)?
(UNIQUE columnNames
| primaryKey columnNames
| FOREIGN KEY columnNames referencesClause
| CHECK LP_ expr RP_
) constraintState*
;
outOfLineRefConstraint
: SCOPE FOR LP_ lobItem RP_ IS tableName
| REF LP_ lobItem RP_ WITH ROWID
| (CONSTRAINT ignoredIdentifier_)? FOREIGN KEY lobItemList referencesClause constraintState*
;
encryptionSpec
: (USING STRING_)? (IDENTIFIED BY STRING_)? STRING_? (NO? SALT)?
;
objectProperties
: objectProperty (COMMA_ objectProperty)*
;
objectProperty
: (columnName | attributeName) (DEFAULT expr)? (inlineConstraint* | inlineRefConstraint?) | outOfLineConstraint | outOfLineRefConstraint
;
columnProperties
: columnProperty+
;
columnProperty
: objectTypeColProperties
;
objectTypeColProperties
: COLUMN columnName substitutableColumnClause
;
substitutableColumnClause
: ELEMENT? IS OF TYPE? LP_ ONLY? dataTypeName_ RP_ | NOT? SUBSTITUTABLE AT ALL LEVELS
;
tableIndexClause_
: tableName alias? LP_ indexExpr_ (COMMA_ indexExpr_)* RP_
;
indexExpr_
: (columnName | expr) (ASC | DESC)?
;
bitmapJoinIndexClause_
: tableName LP_ columnSortClause_ (COMMA_ columnSortClause_)* RP_ FROM tableName alias? (COMMA_ tableName alias?)* WHERE expr
;
columnSortClause_
: tableName alias? columnName (ASC | DESC)?
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE temporaryClause_ TABLE tableName createDefinitionClause_
;
createIndex
: CREATE (UNIQUE | BITMAP)? INDEX indexName ON (tableIndexClause_ | bitmapJoinIndexClause_)
;
alterTable
: ALTER TABLE tableName (alterTableProperties | columnClauses | constraintClauses | alterExternalTable)?
;
// TODO hongjun throw exeption when alter index on oracle
alterIndex
: ALTER INDEX indexName (RENAME TO indexName)?
;
dropTable
: DROP TABLE tableName
;
dropIndex
: DROP INDEX indexName
;
truncateTable
: TRUNCATE TABLE tableName
;
temporaryClause_
: (GLOBAL TEMPORARY)?
;
tablespaceClauseWithParen
: LP_ tablespaceClause RP_
;
tablespaceClause
: TABLESPACE ignoredIdentifier_
;
domainIndexClause
: indexTypeName
;
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 encryptionSpec)? (inlineConstraint+ | inlineRefConstraint)?
;
identityClause
: GENERATED (ALWAYS | BY DEFAULT (ON NULL)?) AS IDENTITY LP_? (identityOptions+)? RP_?
;
identityOptions
: START WITH (NUMBER_ | LIMIT VALUE)
| INCREMENT BY NUMBER_
| MAXVALUE NUMBER_
| NOMAXVALUE
| MINVALUE NUMBER_
| NOMINVALUE
| CYCLE
| NOCYCLE
| CACHE NUMBER_
| NOCACHE
| ORDER
| NOORDER
;
encryptionSpec
: (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*
;
tableProperties
: columnProperties? (AS unionSelect)?
;
unionSelect
: matchNone
;
alterTableProperties
: renameTableSpecification_ | REKEY encryptionSpec
;
renameTableSpecification_
: RENAME TO newTableName
;
newTableName
: IDENTIFIER_
;
columnClauses
: opColumnClause+ | renameColumnSpecification
;
opColumnClause
: addColumnSpecification | modifyColumnSpecification | dropColumnClause
;
addColumnSpecification
: ADD columnOrVirtualDefinitions columnProperties?
;
columnOrVirtualDefinitions
: LP_ columnOrVirtualDefinition (COMMA_ columnOrVirtualDefinition)* RP_ | columnOrVirtualDefinition
;
columnOrVirtualDefinition
: columnDefinition | virtualColumnDefinition
;
modifyColumnSpecification
: MODIFY (LP_? modifyColProperties (COMMA_ modifyColProperties)* RP_? | modifyColSubstitutable)
;
modifyColProperties
: columnName dataType? (DEFAULT expr)? (ENCRYPT encryptionSpec | DECRYPT)? inlineConstraint*
;
modifyColSubstitutable
: COLUMN columnName NOT? SUBSTITUTABLE AT ALL LEVELS FORCE?
;
dropColumnClause
: SET UNUSED columnOrColumnList cascadeOrInvalidate* | dropColumnSpecification
;
dropColumnSpecification
: DROP columnOrColumnList cascadeOrInvalidate* checkpointNumber?
;
columnOrColumnList
: COLUMN columnName | LP_ columnName (COMMA_ columnName)* RP_
;
cascadeOrInvalidate
: CASCADE CONSTRAINTS | INVALIDATE
;
checkpointNumber
: CHECKPOINT NUMBER_
;
renameColumnSpecification
: RENAME COLUMN columnName TO columnName
;
constraintClauses
: addConstraintSpecification | modifyConstraintClause | renameConstraintClause | dropConstraintClause+
;
addConstraintSpecification
: ADD (outOfLineConstraint+ | outOfLineRefConstraint)
;
modifyConstraintClause
: MODIFY constraintOption constraintState+ CASCADE?
;
constraintWithName
: CONSTRAINT ignoredIdentifier_
;
constraintOption
: constraintWithName | constraintPrimaryOrUnique
;
constraintPrimaryOrUnique
: primaryKey | UNIQUE columnNames
;
renameConstraintClause
: RENAME constraintWithName TO ignoredIdentifier_
;
dropConstraintClause
: DROP
(
constraintPrimaryOrUnique CASCADE? ((KEEP | DROP) INDEX)? | (CONSTRAINT ignoredIdentifier_ CASCADE?)
)
;
alterExternalTable
: (addColumnSpecification | modifyColumnSpecification | dropColumnSpecification)+
;
objectProperties
: objectProperty (COMMA_ objectProperty)*
;
objectProperty
: (columnName | attributeName) (DEFAULT expr)? (inlineConstraint* | inlineRefConstraint?) | outOfLineConstraint | outOfLineRefConstraint
;
columnProperties
: columnProperty+
;
columnProperty
: objectTypeColProperties
;
objectTypeColProperties
: COLUMN columnName substitutableColumnClause
;
substitutableColumnClause
: ELEMENT? IS OF TYPE? LP_ ONLY? dataTypeName_ RP_ | NOT? SUBSTITUTABLE AT ALL LEVELS
;
tableIndexClause_
: tableName alias? LP_ indexExpr_ (COMMA_ indexExpr_)* RP_
;
indexExpr_
: (columnName | expr) (ASC | DESC)?
;
bitmapJoinIndexClause_
: tableName LP_ columnSortClause_ (COMMA_ columnSortClause_)* RP_ FROM tableName alias? (COMMA_ tableName alias?)* WHERE expr
;
columnSortClause_
: tableName alias? columnName (ASC | DESC)?
;
|
modify sequence of rules
|
modify sequence of rules
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
29e336fb2458e8492038ab42d2ee07ecd041edcd
|
sharding-jdbc-ddl-parser/src/main/resources/io/shardingsphere/parser/antlr/SQLBase.g4
|
sharding-jdbc-ddl-parser/src/main/resources/io/shardingsphere/parser/antlr/SQLBase.g4
|
grammar SQLBase;
import Keyword,Symbol;
expr:
;
itemList:
LEFT_PAREN item (COMMA item)* RIGHT_PAREN
;
item:
;
schemaName: ID;
tableName: ID;
columnName: ID;
STRING:
DOUBLE_QUOTA ('\\"'|.)*? DOUBLE_QUOTA
|SINGLE_QUOTA (SINGLE_QUOTA |.)*? SINGLE_QUOTA
;
INT :
'0' | [1-9] [0-9]*
;
NUMBER:
MINUS? INT DOT [0-9]+ EXP?
|MINUS? INT | EXP
|MINUS? INT
;
EXP :
E [+\-]? INT
;
fragment HEX :
[0-9a-fA-F]
;
HEX_DIGIT:
'0x' HEX+
|'X' SINGLE_QUOTA HEX+ SINGLE_QUOTA
;
BIT_NUM:
('0b' ('0'|'1')+)
|
(B SINGLE_QUOTA ('0'|'1')+ SINGLE_QUOTA)
;
WS:
[ \t\r\n] + ->skip
;
|
grammar SQLBase;
import Keyword,Symbol;
expr:
;
itemList:
LEFT_PAREN item (COMMA item)* RIGHT_PAREN
;
item:
;
idList:
LEFT_PAREN ID (COMMA ID)* RIGHT_PAREN
;
schemaName: ID;
tableName: ID;
columnName: ID;
tablespaceName:ID;
collationName:
ID
;
STRING:
DOUBLE_QUOTA ('\\"'|.)*? DOUBLE_QUOTA
|SINGLE_QUOTA (SINGLE_QUOTA |.)*? SINGLE_QUOTA
;
NUMBER:
MINUS? INT_ DOT [0-9]+ EXP?
|MINUS? INT_ | EXP
|MINUS? INT_
;
INT_ :
'0' | [1-9] [0-9]*
;
EXP :
E [+\-]? INT_
;
fragment HEX :
[0-9a-fA-F]
;
HEX_DIGIT:
'0x' HEX+
|'X' SINGLE_QUOTA HEX+ SINGLE_QUOTA
;
BIT_NUM:
('0b' ('0'|'1')+)
|
(B SINGLE_QUOTA ('0'|'1')+ SINGLE_QUOTA)
;
WS:
[ \t\r\n] + ->skip
;
|
change INT keyword, make it private add common rule
|
change INT keyword, make it private
add common rule
|
ANTLR
|
apache-2.0
|
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
|
4b72e6e2402594a308191bda9dceabdf2693d5df
|
runtime-testsuite/test/org/antlr/v4/test/runtime/java/api/perf/graphemes.g4
|
runtime-testsuite/test/org/antlr/v4/test/runtime/java/api/perf/graphemes.g4
|
grammar graphemes;
Extend: [\p{Grapheme_Cluster_Break=Extend}];
ZWJ: '\u200D';
SpacingMark: [\p{Grapheme_Cluster_Break=SpacingMark}];
fragment VS15: '\uFE0E';
fragment VS16: '\uFE0F';
fragment NonspacingMark: [\p{Nonspacing_Mark}];
fragment TextPresentationCharacter: [\p{EmojiPresentation=TextDefault}];
fragment EmojiPresentationCharacter: [\p{EmojiPresentation=EmojiDefault}];
fragment TextPresentationSequence: EmojiPresentationCharacter VS15;
fragment EmojiPresentationSequence: TextPresentationCharacter VS16;
fragment EmojiModifierSequence:
[\p{Grapheme_Cluster_Break=E_Base}\p{Grapheme_Cluster_Break=E_Base_GAZ}] [\p{Grapheme_Cluster_Break=E_Modifier}];
fragment EmojiFlagSequence:
[\p{Grapheme_Cluster_Break=Regional_Indicator}] [\p{Grapheme_Cluster_Break=Regional_Indicator}];
fragment ExtendedPictographic: [\p{Extended_Pictographic}];
fragment EmojiNRK: [\p{EmojiNRK}];
fragment EmojiCombiningSequence:
( EmojiPresentationSequence
| TextPresentationSequence
| EmojiPresentationCharacter )
NonspacingMark*;
EmojiCoreSequence:
EmojiModifierSequence
| EmojiCombiningSequence
| EmojiFlagSequence;
fragment EmojiZWJElement:
EmojiModifierSequence
| EmojiPresentationSequence
| EmojiPresentationCharacter
| ExtendedPictographic
| EmojiNRK;
EmojiZWJSequence:
EmojiZWJElement (ZWJ EmojiZWJElement)+;
emoji_sequence:
( EmojiZWJSequence
| EmojiCoreSequence )
( Extend | ZWJ | SpacingMark )*;
Prepend: [\p{Grapheme_Cluster_Break=Prepend}];
NonControl: [\P{Grapheme_Cluster_Break=Control}];
CRLF: [\p{Grapheme_Cluster_Break=CR}][\p{Grapheme_Cluster_Break=LF}];
HangulSyllable:
[\p{Grapheme_Cluster_Break=L}]* [\p{Grapheme_Cluster_Break=V}]+ [\p{Grapheme_Cluster_Break=T}]*
| [\p{Grapheme_Cluster_Break=L}]* [\p{Grapheme_Cluster_Break=LV}] [\p{Grapheme_Cluster_Break=V}]* [\p{Grapheme_Cluster_Break=T}]*
| [\p{Grapheme_Cluster_Break=L}]* [\p{Grapheme_Cluster_Break=LVT}] [\p{Grapheme_Cluster_Break=T}]*
| [\p{Grapheme_Cluster_Break=L}]+
| [\p{Grapheme_Cluster_Break=T}]+;
grapheme_cluster:
CRLF
| Prepend* ( emoji_sequence | HangulSyllable | NonControl ) ( Extend | ZWJ | SpacingMark )*;
graphemes: grapheme_cluster* EOF;
|
grammar graphemes;
Extend: [\p{Grapheme_Cluster_Break=Extend}];
ZWJ: '\u200D';
SpacingMark: [\p{Grapheme_Cluster_Break=SpacingMark}];
fragment VS15: '\uFE0E';
fragment VS16: '\uFE0F';
fragment NonspacingMark: [\p{Nonspacing_Mark}];
fragment TextPresentationCharacter: [\p{EmojiPresentation=TextDefault}];
fragment EmojiPresentationCharacter: [\p{EmojiPresentation=EmojiDefault}];
fragment TextPresentationSequence: EmojiPresentationCharacter VS15;
fragment EmojiPresentationSequence: TextPresentationCharacter VS16;
/* No Longer supported; see https://github.com/antlr/antlr4/pull/3261
fragment EmojiModifierSequence:
[\p{Grapheme_Cluster_Break=E_Base}\p{Grapheme_Cluster_Break=E_Base_GAZ}] [\p{Grapheme_Cluster_Break=E_Modifier}];
*/
fragment EmojiFlagSequence:
[\p{Grapheme_Cluster_Break=Regional_Indicator}] [\p{Grapheme_Cluster_Break=Regional_Indicator}];
fragment ExtendedPictographic: [\p{Extended_Pictographic}];
fragment EmojiNRK: [\p{EmojiNRK}];
fragment EmojiCombiningSequence:
( EmojiPresentationSequence
| TextPresentationSequence
| EmojiPresentationCharacter )
NonspacingMark*;
EmojiCoreSequence:
EmojiCombiningSequence
| EmojiFlagSequence;
fragment EmojiZWJElement:
EmojiPresentationSequence
| EmojiPresentationCharacter
| ExtendedPictographic
| EmojiNRK;
EmojiZWJSequence:
EmojiZWJElement (ZWJ EmojiZWJElement)+;
emoji_sequence:
( EmojiZWJSequence
| EmojiCoreSequence )
( Extend | ZWJ | SpacingMark )*;
Prepend: [\p{Grapheme_Cluster_Break=Prepend}];
NonControl: [\P{Grapheme_Cluster_Break=Control}];
CRLF: [\p{Grapheme_Cluster_Break=CR}][\p{Grapheme_Cluster_Break=LF}];
HangulSyllable:
[\p{Grapheme_Cluster_Break=L}]* [\p{Grapheme_Cluster_Break=V}]+ [\p{Grapheme_Cluster_Break=T}]*
| [\p{Grapheme_Cluster_Break=L}]* [\p{Grapheme_Cluster_Break=LV}] [\p{Grapheme_Cluster_Break=V}]* [\p{Grapheme_Cluster_Break=T}]*
| [\p{Grapheme_Cluster_Break=L}]* [\p{Grapheme_Cluster_Break=LVT}] [\p{Grapheme_Cluster_Break=T}]*
| [\p{Grapheme_Cluster_Break=L}]+
| [\p{Grapheme_Cluster_Break=T}]+;
grapheme_cluster:
CRLF
| Prepend* ( emoji_sequence | HangulSyllable | NonControl ) ( Extend | ZWJ | SpacingMark )*;
graphemes: grapheme_cluster* EOF;
|
remove emoji modifiers from graphemes.g4; see https://github.com/antlr/antlr4/pull/3261
|
remove emoji modifiers from graphemes.g4; see https://github.com/antlr/antlr4/pull/3261
|
ANTLR
|
bsd-3-clause
|
antlr/antlr4,ericvergnaud/antlr4,antlr/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,antlr/antlr4,ericvergnaud/antlr4,antlr/antlr4,ericvergnaud/antlr4,antlr/antlr4,parrt/antlr4,antlr/antlr4,antlr/antlr4,antlr/antlr4,parrt/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,parrt/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,antlr/antlr4,parrt/antlr4,parrt/antlr4,parrt/antlr4,antlr/antlr4,parrt/antlr4,parrt/antlr4,parrt/antlr4,ericvergnaud/antlr4,parrt/antlr4
|
57b2b80cc176a09ac204335348a6fb272b3e35f7
|
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*
;
decorator
: AT dotted_name (OPEN_PAREN arglist? CLOSE_PAREN)? NEWLINE
;
decorated
: decorator+ (classdef | funcdef)
;
funcdef
: ASYNC? DEF name parameters (ARROW test)? COLON suite
;
parameters
: OPEN_PAREN typedargslist? CLOSE_PAREN
;
//python 3 paramters
typedargslist
: (def_parameters COMMA)? (args (COMMA def_parameters)? (COMMA kwargs)? | kwargs)
| def_parameters
;
args
: STAR named_parameter
;
kwargs
: POWER named_parameter
;
def_parameters
: def_parameter (COMMA def_parameter)*
;
def_parameter
: named_parameter (ASSIGN test)?
| STAR
;
vardef_parameters
: vardef_parameter (COMMA vardef_parameter)*
;
vardef_parameter
: name (ASSIGN test)?
;
named_parameter
: name (COLON test)?
;
//python 2 paramteters
varargslist
: (vardef_parameters COMMA)? varargs (COMMA vardef_parameters)? (COMMA varkwargs)
| vardef_parameters
;
varargs
: STAR name
;
varkwargs
: POWER name
;
stmt
: simple_stmt
| compound_stmt
;
simple_stmt
: small_stmt (SEMI_COLON small_stmt)* SEMI_COLON? (NEWLINE | EOF)
;
small_stmt
: expr_stmt
| print_stmt
| del_stmt
| pass_stmt
| flow_stmt
| import_stmt
| global_stmt
| exec_stmt
| assert_stmt
| nonlocal_stmt
;
//Python 3
nonlocal_stmt
: NONLOCAL name (COMMA name)*
;
expr_stmt
: testlist_star_expr
| annassign
| augassign
| assign
;
// if left expression in assign is bool literal, it's mean that is Python 2 here
assign
: testlist_star_expr (ASSIGN (yield_expr | testlist_star_expr))*
;
// Python3 rule
annassign
: testlist_star_expr COLON test (ASSIGN (yield_expr | testlist))?
;
testlist_star_expr
: (test | star_expr) (COMMA (test | star_expr))* COMMA?
;
augassign
: testlist_star_expr
op=( ADD_ASSIGN
| SUB_ASSIGN
| MULT_ASSIGN
| AT_ASSIGN
| DIV_ASSIGN
| MOD_ASSIGN
| AND_ASSIGN
| OR_ASSIGN
| XOR_ASSIGN
| LEFT_SHIFT_ASSIGN
| RIGHT_SHIFT_ASSIGN
| POWER_ASSIGN
| IDIV_ASSIGN
)
(yield_expr | testlist)
;
// python 2
print_stmt
: PRINT ((test (COMMA test)* COMMA?) | RIGHT_SHIFT test ((COMMA test)+ COMMA?))
;
del_stmt
: DEL exprlist
;
pass_stmt
: PASS
;
flow_stmt
: break_stmt
| continue_stmt
| return_stmt
| raise_stmt
| yield_stmt
;
break_stmt
: BREAK
;
continue_stmt
: CONTINUE
;
return_stmt
: RETURN testlist?
;
yield_stmt
: yield_expr
;
raise_stmt
: RAISE (test (COMMA test (COMMA test)?)?)? (FROM test)?
;
import_stmt
: import_name
| import_from
;
import_name
: IMPORT dotted_as_names
;
import_from
: (FROM ((DOT | ELLIPSIS)* dotted_name | (DOT | ELLIPSIS)+)
IMPORT (STAR | OPEN_PAREN import_as_names CLOSE_PAREN | import_as_names))
;
import_as_name
: name (AS name)?
;
dotted_as_name
: dotted_name (AS name)?
;
import_as_names
: import_as_name (COMMA import_as_name)* COMMA?
;
dotted_as_names
: dotted_as_name (COMMA dotted_as_name)*
;
dotted_name
: dotted_name DOT name
| name
;
global_stmt
: GLOBAL name (COMMA name)*
;
exec_stmt
: EXEC expr (IN test (COMMA test)?)?
;
assert_stmt
: ASSERT test (COMMA test)?
;
compound_stmt
: if_stmt
| while_stmt
| for_stmt
| try_stmt
| with_stmt
| funcdef
| classdef
| decorated
| async_stmt
;
async_stmt
: ASYNC (funcdef | with_stmt | for_stmt)
;
if_stmt
: IF test COLON suite elif_clause* else_clause?
;
elif_clause
: ELIF test COLON suite
;
else_clause
: ELSE COLON suite
;
while_stmt
: WHILE test COLON suite else_clause?
;
for_stmt
: FOR exprlist IN testlist COLON suite else_clause?
;
try_stmt
: TRY COLON suite (except_clause+ else_clause? finaly_clause? | finaly_clause)
;
finaly_clause
: FINALLY COLON suite
;
with_stmt
: WITH with_item (COMMA with_item)* COLON suite
;
with_item
// NB compile.c makes sure that the default except clause is last
: test (AS expr)?
;
// Python 2 : EXCEPT test COMMA name, Python 3 : EXCEPT test AS name
except_clause
: EXCEPT (test (COMMA name | AS name)?)? COLON suite
;
suite
: simple_stmt
| NEWLINE INDENT stmt+ DEDENT
;
// Backward compatibility cruft to support:
// [ x for x in lambda: True, lambda: False if x() ]
// even while also allowing:
// lambda x: 5 if x else 2
// (But not a mix of the two)
testlist_safe
: old_test ((COMMA old_test)+ COMMA?)?
;
old_test
: logical_test
| old_lambdef
;
old_lambdef
: LAMBDA varargslist? COLON old_test
;
test
: logical_test (IF logical_test ELSE test)?
| lambdef
;
test_nocond
: logical_test
| lambdef_nocond
;
lambdef_nocond
: LAMBDA varargslist? COLON test_nocond
;
logical_test
: logical_test op=OR logical_test
| logical_test op=AND logical_test
| NOT logical_test
| comparison
;
// <> isn't actually a valid comparison operator in Python. It's here for the
// sake of a __future__ import described in PEP 401 (which really works :-)
comparison
: comparison op=(LESS_THAN | GREATER_THAN | EQUALS | GT_EQ | LT_EQ | NOT_EQ_1 | NOT_EQ_2 | IN | IS | NOT) comparison
| comparison (NOT IN | IS NOT) comparison
| expr
;
star_expr
: STAR expr
;
expr
: expr op=OR_OP expr
| expr op=XOR expr
| expr op=AND_OP expr
| expr op=(LEFT_SHIFT | RIGHT_SHIFT) expr
| expr op=(ADD | MINUS) expr
| expr op=(STAR | DIV | MOD | IDIV | AT) expr // @ is multiply operator for numpy arrays
| expr op=(ADD | MINUS) expr
| expr op=POWER expr
| op=(ADD | MINUS | NOT_OP) expr
| AWAIT? atom trailer*
;
atom
: dotted_name
| OPEN_PAREN (yield_expr | testlist_comp)? CLOSE_PAREN
| OPEN_BRACKET testlist_comp? CLOSE_BRACKET
| OPEN_BRACE dictorsetmaker? CLOSE_BRACE
| REVERSE_QUOTE testlist COMMA? REVERSE_QUOTE
| ELLIPSIS
| name
| PRINT
| EXEC
| MINUS? number
| NONE
| STRING+
;
name
: NAME
| TRUE
| FALSE
;
number
: integer
| IMAG_NUMBER
| FLOAT_NUMBER
;
integer
: DECIMAL_INTEGER
| OCT_INTEGER
| HEX_INTEGER
| BIN_INTEGER
;
testlist_comp
: (test | star_expr) (comp_for | (COMMA (test | star_expr))* COMMA?)
;
lambdef
: LAMBDA varargslist? COLON test
;
trailer
: OPEN_PAREN arglist? CLOSE_PAREN
| OPEN_BRACKET subscriptlist CLOSE_BRACKET
| DOT name
;
subscriptlist
: subscript (COMMA subscript)* COMMA?
;
subscript
: ELLIPSIS
| test
| test? COLON test? sliceop?
;
sliceop
: COLON test?
;
exprlist
: expr (COMMA expr)* COMMA?
;
testlist
: test (COMMA test)* COMMA?
;
dictorsetmaker
: (test COLON test | POWER expr) (comp_for | (COMMA (test COLON test | POWER expr))* COMMA?)
| (test | star_expr) (comp_for | (COMMA (test | star_expr))* COMMA?)
;
classdef
: CLASS name (OPEN_PAREN arglist? CLOSE_PAREN)? COLON suite
;
arglist
// The reason that keywords are test nodes instead of name is that using name
// results in an ambiguity. ast.c makes sure it's a name.
: argument (COMMA argument)* COMMA?
;
argument
: test comp_for?
| test ASSIGN test
| POWER test
| STAR test
;
list_iter
: list_for
| list_if
;
list_for
: FOR exprlist IN testlist_safe list_iter?
;
list_if
: IF old_test list_iter?
;
comp_iter
: comp_for
| comp_if
;
comp_for
: FOR exprlist IN logical_test comp_iter?
;
comp_if
: IF old_test comp_iter?
;
// not used in grammar, but may appear in "node" passed from Parser to Compiler
encoding_decl
: name
;
yield_expr
: YIELD yield_arg?
;
yield_arg
: FROM test
| testlist
;
|
// Header included from Python site:
/*
* Grammar for Python
*
* Note: Changing the grammar specified in this file will most likely
* require corresponding changes in the parser module
* (../Modules/parsermodule.c). If you can't make the changes to
* that module yourself, please co-ordinate the required changes
* with someone who can; ask around on python-dev for help. Fred
* Drake <[email protected]> will probably be listening there.
*
* NOTE WELL: You should also follow all the steps listed in PEP 306,
* "How to Change Python's Grammar"
*
* Start symbols for the grammar:
* single_input is a single interactive statement;
* file_input is a module or sequence of commands read from an input file;
* eval_input is the input for the eval() and input() functions.
* NB: compound_stmt in single_input is followed by extra NEWLINE!
*/
parser grammar PythonParser;
options { tokenVocab=PythonLexer; }
root
: (single_input
| file_input
| eval_input)? EOF
;
single_input
: NEWLINE
| simple_stmt
| compound_stmt NEWLINE
;
file_input
: (NEWLINE | stmt)+
;
eval_input
: testlist NEWLINE*
;
decorator
: AT dotted_name (OPEN_PAREN arglist? CLOSE_PAREN)? NEWLINE
;
//python 3 paramters
typedargslist
: (def_parameters COMMA)? (args (COMMA def_parameters)? (COMMA kwargs)? | kwargs)
| def_parameters
;
args
: STAR named_parameter
;
kwargs
: POWER named_parameter
;
def_parameters
: def_parameter (COMMA def_parameter)*
;
def_parameter
: named_parameter (ASSIGN test)?
| STAR
;
named_parameter
: name (COLON test)?
;
//python 2 paramteters
varargslist
: (vardef_parameters COMMA)? varargs (COMMA vardef_parameters)? (COMMA varkwargs)
| vardef_parameters
;
vardef_parameters
: vardef_parameter (COMMA vardef_parameter)*
;
vardef_parameter
: name (ASSIGN test)?
;
varargs
: STAR name
;
varkwargs
: POWER name
;
stmt
: simple_stmt
| compound_stmt
;
simple_stmt
: small_stmt (SEMI_COLON small_stmt)* SEMI_COLON? (NEWLINE | EOF)
;
small_stmt
: 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
| ASSERT test (COMMA test)? #assert_stmt
| NONLOCAL name (COMMA name)* #nonlocal_stmt // Python 3
;
testlist_star_expr
: (test | star_expr) (COMMA (test | star_expr))* COMMA?
;
assign_part
: (ASSIGN (yield_expr | testlist_star_expr))+ // if left expression in assign is bool literal, it's mean that is Python 2 here
| COLON test (ASSIGN (yield_expr | 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)
;
import_as_names
: import_as_name (COMMA import_as_name)* COMMA?
;
import_as_name
: name (AS name)?
;
dotted_as_names
: dotted_as_name (COMMA dotted_as_name)*
;
dotted_as_name
: dotted_name (AS name)?
;
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? finaly_clause? | finaly_clause) #try_stmt
| ASYNC? WITH with_item (COMMA with_item)* COLON suite #with_stmt
| decorator* (classdef | funcdef) #class_or_func_def_stmt
;
elif_clause
: ELIF test COLON suite
;
else_clause
: ELSE COLON suite
;
finaly_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
;
suite
: simple_stmt
| NEWLINE INDENT stmt+ DEDENT
;
old_test
: logical_test
| LAMBDA varargslist? COLON old_test // Old lambda def
;
test
: logical_test (IF logical_test ELSE test)?
| lambdef
;
test_nocond
: logical_test
| LAMBDA varargslist? COLON test_nocond // Lamda def no cond
;
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 (LESS_THAN | GREATER_THAN | EQUALS | GT_EQ | LT_EQ | NOT_EQ_1 | NOT_EQ_2 | IN | IS optional=NOT? | NOT optional=IN?) comparison
| expr
;
expr
: expr op=OR_OP expr
| expr op=XOR expr
| expr op=AND_OP expr
| expr op=(LEFT_SHIFT | RIGHT_SHIFT) expr
| expr op=(ADD | MINUS) expr
| expr op=(STAR | DIV | MOD | IDIV | AT) expr // @ is multiply operator for numpy arrays
| expr op=(ADD | MINUS) expr
| expr op=POWER expr
| op=(ADD | MINUS | NOT_OP) expr
| AWAIT? atom trailer*
;
atom
: dotted_name
| OPEN_PAREN (yield_expr | testlist_comp)? CLOSE_PAREN
| OPEN_BRACKET testlist_comp? CLOSE_BRACKET
| OPEN_BRACE dictorsetmaker? CLOSE_BRACE
| REVERSE_QUOTE testlist COMMA? REVERSE_QUOTE
| ELLIPSIS
| name
| PRINT
| EXEC
| MINUS? number
| NONE
| STRING+
;
dotted_name
: dotted_name DOT name
| name
;
yield_expr
: YIELD yield_arg?
;
testlist_comp
: (test | star_expr) (comp_for | (COMMA (test | star_expr))* COMMA?)
;
name
: NAME
| TRUE
| FALSE
;
number
: integer
| IMAG_NUMBER
| FLOAT_NUMBER
;
integer
: DECIMAL_INTEGER
| OCT_INTEGER
| HEX_INTEGER
| BIN_INTEGER
;
lambdef
: LAMBDA varargslist? COLON test
;
trailer
: OPEN_PAREN arglist? CLOSE_PAREN
| OPEN_BRACKET subscriptlist CLOSE_BRACKET
| DOT name
;
subscriptlist
: subscript (COMMA subscript)* COMMA?
;
subscript
: ELLIPSIS
| test
| test? COLON test? sliceop?
;
sliceop
: COLON test?
;
exprlist
: expr (COMMA expr)* COMMA?
;
testlist
: test (COMMA test)* COMMA?
;
dictorsetmaker
: (test COLON test | POWER expr) (comp_for | (COMMA (test COLON test | POWER expr))* COMMA?)
| (test | star_expr) (comp_for | (COMMA (test | star_expr))* COMMA?)
;
star_expr
: STAR expr
;
classdef
: CLASS name (OPEN_PAREN arglist? CLOSE_PAREN)? COLON suite
;
funcdef
: ASYNC? DEF name OPEN_PAREN typedargslist? CLOSE_PAREN (ARROW test)? COLON suite
;
arglist
// The reason that keywords are test nodes instead of name is that using name
// results in an ambiguity. ast.c makes sure it's a name.
: argument (COMMA argument)* COMMA?
;
argument
: test (comp_for | ASSIGN test)?
| (POWER | STAR) test
;
list_iter
: FOR exprlist IN testlist_safe list_iter?
| IF old_test list_iter?
;
// 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?)?
;
comp_iter
: comp_for
| IF old_test comp_iter?
;
comp_for
: FOR exprlist IN logical_test comp_iter?
;
yield_arg
: FROM test
| testlist
;
|
Simplify PythonParser, make inlined primitive rules that used only one time, use alternative labels for stmt rules, reorder some rules for clarity
|
Simplify PythonParser, make inlined primitive rules that used only one time, use alternative labels for stmt rules, reorder some rules for clarity
|
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
|
fc1a850ecb476d022f32565293a3b8a7d43c6a74
|
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
|
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE createSpecification_ TABLE notExistClause_ tableName createDefinitionClause_ inheritClause_
;
createIndex
: CREATE UNIQUE? INDEX CONCURRENTLY? ((IF NOT EXISTS)? indexName)? ON tableName
;
alterTable
: alterTableNameWithAsterisk (alterTableActions | renameColumnSpecification | renameConstraint) | alterTableNameExists renameTableSpecification_
;
alterIndex
: alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace
;
dropTable
: DROP TABLE (IF EXISTS)? tableNames
;
dropIndex
: DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)*
;
truncateTable
: TRUNCATE TABLE? ONLY? tableNameParts
;
createSpecification_
: ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)?
;
notExistClause_
: (IF NOT EXISTS)?
;
createDefinitionClause_
: LP_ (createDefinition (COMMA_ createDefinition)*)? RP_
;
createDefinition
: columnDefinition | tableConstraint | LIKE tableName likeOption*
;
columnDefinition
: columnName dataType collateClause? columnConstraint*
;
columnConstraint
: constraintClause? columnConstraintOption constraintOptionalParam
;
constraintClause
: CONSTRAINT ignoredIdentifier_
;
columnConstraintOption
: NOT? NULL
| checkOption
| DEFAULT defaultExpr
| GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)?
| UNIQUE indexParameters
| primaryKey indexParameters
| REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)*
;
checkOption
: CHECK expr (NO INHERIT)?
;
defaultExpr
: CURRENT_TIMESTAMP | expr
;
sequenceOptions
: sequenceOption+
;
sequenceOption
: START WITH? NUMBER_
| INCREMENT BY? NUMBER_
| MAXVALUE NUMBER_
| NO MAXVALUE
| MINVALUE NUMBER_
| NO MINVALUE
| CYCLE
| NO CYCLE
| CACHE NUMBER_
| OWNED BY
;
indexParameters
: (USING INDEX TABLESPACE ignoredIdentifier_)?
| INCLUDE columnNames
| WITH
;
action
: NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT)
;
constraintOptionalParam
: (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))?
;
likeOption
: (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL)
;
tableConstraint
: constraintClause? tableConstraintOption constraintOptionalParam
;
tableConstraintOption
: checkOption
| UNIQUE columnNames indexParameters
| primaryKey columnNames indexParameters
| EXCLUDE (USING ignoredIdentifier_)?
| FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)*
;
inheritClause_
: (INHERITS tableNames)?
;
alterIndexName
: ALTER INDEX (IF EXISTS)? indexName
;
renameIndexSpecification
: RENAME TO indexName
;
alterIndexDependsOnExtension
: ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_
;
alterIndexSetTableSpace
: ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)?
;
tableNameParts
: tableNamePart (COMMA_ tableNamePart)*
;
tableNamePart
: tableName ASTERISK_?
;
alterTableNameWithAsterisk
: ALTER TABLE (IF EXISTS)? ONLY? tableName ASTERISK_?
;
alterTableActions
: alterTableAction (COMMA_ alterTableAction)*
;
alterTableAction
: addColumnSpecification
| dropColumnSpecification
| modifyColumnSpecification
| addConstraintSpecification
| ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam
| VALIDATE CONSTRAINT ignoredIdentifier_
| DROP CONSTRAINT (IF EXISTS)? ignoredIdentifier_ (RESTRICT | CASCADE)?
| (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)?
| ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_
| (DISABLE | ENABLE) RULE ignoredIdentifier_
| ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_
| (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY
| CLUSTER ON indexName
| SET WITHOUT CLUSTER
| SET (WITH | WITHOUT) OIDS
| SET TABLESPACE ignoredIdentifier_
| SET (LOGGED | UNLOGGED)
| SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_
| RESET LP_ storageParameter (COMMA_ storageParameter)* RP_
| INHERIT tableName
| NO INHERIT tableName
| OF dataTypeName_
| NOT OF
| OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER)
| REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING)
;
tableConstraintUsingIndex
: (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam
;
addColumnSpecification
: ADD COLUMN? (IF NOT EXISTS)? columnDefinition
;
dropColumnSpecification
: DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)?
;
modifyColumnSpecification
: alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)?
| alterColumn SET DEFAULT expr
| alterColumn DROP DEFAULT
| alterColumn (SET | DROP) NOT NULL
| alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)?
| alterColumn alterColumnSetOption alterColumnSetOption*
| alterColumn DROP IDENTITY (IF EXISTS)?
| alterColumn SET STATISTICS NUMBER_
| alterColumn SET LP_ attributeOptions RP_
| alterColumn RESET LP_ attributeOptions RP_
| alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN)
;
alterColumn
: ALTER COLUMN? columnName
;
alterColumnSetOption
: SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)?
;
attributeOptions
: attributeOption (COMMA_ attributeOption)*
;
attributeOption
: IDENTIFIER_ EQ_ simpleExpr
;
addConstraintSpecification
: ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex)
;
renameColumnSpecification
: RENAME COLUMN? columnName TO columnName
;
renameConstraint
: RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_
;
storageParameterWithValue
: storageParameter EQ_ simpleExpr
;
storageParameter
: IDENTIFIER_
;
alterTableNameExists
: ALTER TABLE (IF EXISTS)? tableName
;
renameTableSpecification_
: RENAME TO newTableName
;
newTableName
: IDENTIFIER_
;
usingIndexType
: USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN)
;
excludeElement
: (columnName | expr) ignoredIdentifier_? (ASC | DESC)? (NULLS (FIRST | LAST))?
;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
grammar DDLStatement;
import Symbol, Keyword, Literals, BaseRule;
createTable
: CREATE createTableSpecification_ TABLE notExistClause_ tableName createDefinitionClause_ inheritClause_
;
createIndex
: CREATE createIndexSpecification_ (indexNotExistClause_ indexName)? ON tableName
;
alterTable
: alterTableNameWithAsterisk (alterTableActions | renameColumnSpecification | renameConstraint) | alterTableNameExists renameTableSpecification_
;
alterIndex
: alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace
;
dropTable
: DROP TABLE (IF EXISTS)? tableNames
;
dropIndex
: DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)*
;
truncateTable
: TRUNCATE TABLE? ONLY? tableNameParts
;
createTableSpecification_
: ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)?
;
notExistClause_
: (IF NOT EXISTS)?
;
createDefinitionClause_
: LP_ (createDefinition (COMMA_ createDefinition)*)? RP_
;
createDefinition
: columnDefinition | tableConstraint | LIKE tableName likeOption*
;
columnDefinition
: columnName dataType collateClause? columnConstraint*
;
columnConstraint
: constraintClause? columnConstraintOption constraintOptionalParam
;
constraintClause
: CONSTRAINT ignoredIdentifier_
;
columnConstraintOption
: NOT? NULL
| checkOption
| DEFAULT defaultExpr
| GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)?
| UNIQUE indexParameters
| primaryKey indexParameters
| REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)*
;
checkOption
: CHECK expr (NO INHERIT)?
;
defaultExpr
: CURRENT_TIMESTAMP | expr
;
sequenceOptions
: sequenceOption+
;
sequenceOption
: START WITH? NUMBER_
| INCREMENT BY? NUMBER_
| MAXVALUE NUMBER_
| NO MAXVALUE
| MINVALUE NUMBER_
| NO MINVALUE
| CYCLE
| NO CYCLE
| CACHE NUMBER_
| OWNED BY
;
indexParameters
: (USING INDEX TABLESPACE ignoredIdentifier_)?
| INCLUDE columnNames
| WITH
;
action
: NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT)
;
constraintOptionalParam
: (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))?
;
likeOption
: (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL)
;
tableConstraint
: constraintClause? tableConstraintOption constraintOptionalParam
;
tableConstraintOption
: checkOption
| UNIQUE columnNames indexParameters
| primaryKey columnNames indexParameters
| EXCLUDE (USING ignoredIdentifier_)?
| FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)*
;
inheritClause_
: (INHERITS tableNames)?
;
createIndexSpecification_
: UNIQUE? INDEX CONCURRENTLY?
;
indexNotExistClause_
: (IF NOT EXISTS)?
;
alterIndexName
: ALTER INDEX (IF EXISTS)? indexName
;
renameIndexSpecification
: RENAME TO indexName
;
alterIndexDependsOnExtension
: ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_
;
alterIndexSetTableSpace
: ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)?
;
tableNameParts
: tableNamePart (COMMA_ tableNamePart)*
;
tableNamePart
: tableName ASTERISK_?
;
alterTableNameWithAsterisk
: ALTER TABLE (IF EXISTS)? ONLY? tableName ASTERISK_?
;
alterTableActions
: alterTableAction (COMMA_ alterTableAction)*
;
alterTableAction
: addColumnSpecification
| dropColumnSpecification
| modifyColumnSpecification
| addConstraintSpecification
| ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam
| VALIDATE CONSTRAINT ignoredIdentifier_
| DROP CONSTRAINT (IF EXISTS)? ignoredIdentifier_ (RESTRICT | CASCADE)?
| (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)?
| ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_
| (DISABLE | ENABLE) RULE ignoredIdentifier_
| ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_
| (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY
| CLUSTER ON indexName
| SET WITHOUT CLUSTER
| SET (WITH | WITHOUT) OIDS
| SET TABLESPACE ignoredIdentifier_
| SET (LOGGED | UNLOGGED)
| SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_
| RESET LP_ storageParameter (COMMA_ storageParameter)* RP_
| INHERIT tableName
| NO INHERIT tableName
| OF dataTypeName_
| NOT OF
| OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER)
| REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING)
;
tableConstraintUsingIndex
: (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam
;
addColumnSpecification
: ADD COLUMN? (IF NOT EXISTS)? columnDefinition
;
dropColumnSpecification
: DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)?
;
modifyColumnSpecification
: alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)?
| alterColumn SET DEFAULT expr
| alterColumn DROP DEFAULT
| alterColumn (SET | DROP) NOT NULL
| alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)?
| alterColumn alterColumnSetOption alterColumnSetOption*
| alterColumn DROP IDENTITY (IF EXISTS)?
| alterColumn SET STATISTICS NUMBER_
| alterColumn SET LP_ attributeOptions RP_
| alterColumn RESET LP_ attributeOptions RP_
| alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN)
;
alterColumn
: ALTER COLUMN? columnName
;
alterColumnSetOption
: SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)?
;
attributeOptions
: attributeOption (COMMA_ attributeOption)*
;
attributeOption
: IDENTIFIER_ EQ_ simpleExpr
;
addConstraintSpecification
: ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex)
;
renameColumnSpecification
: RENAME COLUMN? columnName TO columnName
;
renameConstraint
: RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_
;
storageParameterWithValue
: storageParameter EQ_ simpleExpr
;
storageParameter
: IDENTIFIER_
;
alterTableNameExists
: ALTER TABLE (IF EXISTS)? tableName
;
renameTableSpecification_
: RENAME TO newTableName
;
newTableName
: IDENTIFIER_
;
usingIndexType
: USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN)
;
excludeElement
: (columnName | expr) ignoredIdentifier_? (ASC | DESC)? (NULLS (FIRST | LAST))?
;
|
add indexNotExistClause_
|
add indexNotExistClause_
|
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
|
5d1af7d884ae26660695de7363f6bbce053b66d8
|
client/src/main/antlr4/com/metamx/druid/sql/antlr4/DruidSQL.g4
|
client/src/main/antlr4/com/metamx/druid/sql/antlr4/DruidSQL.g4
|
grammar DruidSQL;
/*
@lexer::header {
package com.metamx.druid.sql.antlr;
}
*/
/*
TODO: handle both multiply / division, addition - subtraction
unary minus
*/
@header {
import com.metamx.druid.aggregation.post.*;
import com.metamx.druid.aggregation.*;
import com.metamx.druid.query.filter.*;
import com.metamx.druid.query.dimension.*;
import com.metamx.druid.*;
import com.google.common.base.*;
import com.google.common.collect.Lists;
import org.joda.time.*;
import java.text.*;
import java.util.*;
}
@parser::members {
public Map<String, AggregatorFactory> aggregators = new LinkedHashMap<String, AggregatorFactory>();
public List<PostAggregator> postAggregators = new LinkedList<PostAggregator>();
public DimFilter filter;
public List<org.joda.time.Interval> intervals;
public QueryGranularity granularity = QueryGranularity.ALL;
public Map<String, DimensionSpec> groupByDimensions = new LinkedHashMap<String, DimensionSpec>();
String dataSourceName = null;
public String getDataSource() {
return dataSourceName;
}
public String unescape(String quoted) {
String unquote = quoted.trim().replaceFirst("^'(.*)'\$", "\$1");
return unquote.replace("''", "'");
}
AggregatorFactory evalAgg(String name, int fn) {
switch (fn) {
case SUM: return new DoubleSumAggregatorFactory("doubleSum:"+name, name);
case MIN: return new MinAggregatorFactory("min:"+name, name);
case MAX: return new MaxAggregatorFactory("max:"+name, name);
case COUNT: return new CountAggregatorFactory(name);
}
throw new IllegalArgumentException("Unknown function [" + fn + "]");
}
PostAggregator evalArithmeticPostAggregator(PostAggregator a, List<Token> ops, List<PostAggregator> b) {
if(b.isEmpty()) return a;
else {
int i = 0;
PostAggregator root = a;
while(i < ops.size()) {
List<PostAggregator> list = new LinkedList<PostAggregator>();
List<String> names = new LinkedList<String>();
names.add(root.getName());
list.add(root);
Token op = ops.get(i);
while(i < ops.size() && ops.get(i).getType() == op.getType()) {
PostAggregator e = b.get(i);
list.add(e);
names.add(e.getName());
i++;
}
root = new ArithmeticPostAggregator("("+Joiner.on(op.getText()).join(names)+")", op.getText(), list);
}
return root;
}
}
}
AND: 'and';
OR: 'or';
SUM: 'sum';
MIN: 'min';
MAX: 'max';
COUNT: 'count';
AS: 'as';
OPEN: '(';
CLOSE: ')';
STAR: '*';
PLUS: '+';
MINUS: '-';
DIV: '/';
COMMA: ',';
GROUP: 'group';
IDENT : (LETTER)(LETTER | DIGIT | '_')* ;
QUOTED_STRING : '\'' ( ESCqs | ~'\'' )* '\'' ;
ESCqs : '\'' '\'';
NUMBER: ('+'|'-')?DIGIT*'.'?DIGIT+(EXPONENT)?;
EXPONENT: ('e') ('+'|'-')? ('0'..'9')+;
fragment DIGIT : '0'..'9';
fragment LETTER : 'a'..'z' | 'A'..'Z';
WS : (' '| '\t' | '\r' '\n' | '\n' | '\r')+ -> skip;
query
: select_stmt where_stmt (groupby_stmt)?
;
select_stmt
: 'select' e+=aliasedExpression (',' e+=aliasedExpression)* 'from' datasource {
for(AliasedExpressionContext a : $e) { postAggregators.add(a.p); }
this.dataSourceName = $datasource.text;
}
;
where_stmt
: 'where' f=timeAndDimFilter {
if($f.filter != null) this.filter = $f.filter;
this.intervals = Lists.newArrayList($f.interval);
}
;
groupby_stmt
: GROUP 'by' groupByExpression ( COMMA! groupByExpression )*
;
groupByExpression
: gran=granularityFn {this.granularity = $gran.granularity;}
| dim=IDENT { this.groupByDimensions.put($dim.text, new DefaultDimensionSpec($dim.text, $dim.text)); }
;
datasource
: IDENT
;
aliasedExpression returns [PostAggregator p]
: expression ( AS^ name=IDENT )? { $p = $expression.p; }
;
expression returns [PostAggregator p]
: additiveExpression { $p = $additiveExpression.p; }
;
additiveExpression returns [PostAggregator p]
: a=multiplyExpression (( ops+=PLUS^ | ops+=MINUS^ ) b+=multiplyExpression)* {
List<PostAggregator> rhs = new LinkedList<PostAggregator>();
for(MultiplyExpressionContext e : $b) rhs.add(e.p);
$p = evalArithmeticPostAggregator($a.p, $ops, rhs);
}
;
multiplyExpression returns [PostAggregator p]
: a=unaryExpression ((ops+= STAR | ops+=DIV ) b+=unaryExpression)* {
List<PostAggregator> rhs = new LinkedList<PostAggregator>();
for(UnaryExpressionContext e : $b) rhs.add(e.p);
$p = evalArithmeticPostAggregator($a.p, $ops, rhs);
}
;
unaryExpression returns [PostAggregator p]
: MINUS e=unaryExpression {
$p = new ArithmeticPostAggregator(
"-"+$e.p.getName(),
"*",
Lists.newArrayList($e.p, new ConstantPostAggregator("-1", -1.0))
);
}
| PLUS e=unaryExpression { $p = $e.p; }
| primaryExpression { $p = $primaryExpression.p; }
;
primaryExpression returns [PostAggregator p]
: constant { $p = $constant.c; }
| aggregate {
aggregators.put($aggregate.agg.getName(), $aggregate.agg);
$p = new FieldAccessPostAggregator($aggregate.agg.getName(), $aggregate.agg.getName());
}
| OPEN! e=expression CLOSE! { $p = $e.p; }
;
aggregate returns [AggregatorFactory agg]
: fn=( SUM^ | MIN^ | MAX^ ) OPEN! name=(IDENT|COUNT) CLOSE! { $agg = evalAgg($name.text, $fn.type); }
| fn=COUNT OPEN! STAR CLOSE! { $agg = evalAgg("count", $fn.type); }
;
constant returns [ConstantPostAggregator c]
: value=NUMBER { double v = Double.parseDouble($value.text); $c = new ConstantPostAggregator(Double.toString(v), v); }
;
/* time filters must be top level filters */
timeAndDimFilter returns [DimFilter filter, org.joda.time.Interval interval]
: t=timeFilter (AND f=dimFilter)? {
if($f.ctx != null) $filter = $f.filter;
$interval = $t.interval;
}
| (f=dimFilter)? AND t=timeFilter {
if($f.ctx != null) $filter = $f.filter;
$interval = $t.interval;
}
;
dimFilter returns [DimFilter filter]
: e=orDimFilter { $filter = $e.filter; }
;
orDimFilter returns [DimFilter filter]
: a=andDimFilter (OR^ b+=andDimFilter)* {
if($b.isEmpty()) $filter = $a.filter;
else {
List<DimFilter> rest = new ArrayList<DimFilter>();
for(AndDimFilterContext e : $b) rest.add(e.filter);
$filter = new OrDimFilter(Lists.asList($a.filter, rest.toArray(new DimFilter[]{})));
}
}
;
andDimFilter returns [DimFilter filter]
: a=primaryDimFilter (AND^ b+=primaryDimFilter)* {
if($b.isEmpty()) $filter = $a.filter;
else {
List<DimFilter> rest = new ArrayList<DimFilter>();
for(PrimaryDimFilterContext e : $b) rest.add(e.filter);
$filter = new AndDimFilter(Lists.asList($a.filter, rest.toArray(new DimFilter[]{})));
}
}
;
primaryDimFilter returns [DimFilter filter]
: e=selectorDimFilter { $filter = $e.filter; }
| OPEN! f=dimFilter CLOSE! { $filter = $f.filter; }
;
selectorDimFilter returns [SelectorDimFilter filter]
: dimension=IDENT '=' value=QUOTED_STRING {
$filter = new SelectorDimFilter($dimension.text, unescape($value.text));
}
;
timeFilter returns [org.joda.time.Interval interval, QueryGranularity granularity]
: 'timestamp' 'between' s=timestamp AND e=timestamp {
$interval = new org.joda.time.Interval($s.t, $e.t);
}
;
granularityFn returns [QueryGranularity granularity]
: 'granularity' OPEN! 'timestamp' ',' str=QUOTED_STRING CLOSE! {
String granStr = unescape($str.text);
try {
$granularity = QueryGranularity.fromString(granStr);
} catch(IllegalArgumentException e) {
$granularity = new PeriodGranularity(new Period(granStr), null, null);
}
}
;
timestamp returns [DateTime t]
: NUMBER {
String str = $NUMBER.text.trim();
try {
$t = new DateTime(NumberFormat.getInstance().parse(str));
}
catch(ParseException e) {
throw new IllegalArgumentException("Unable to parse number [" + str + "]");
}
}
| QUOTED_STRING { $t = new DateTime(unescape($QUOTED_STRING.text)); }
;
|
grammar DruidSQL;
/*
@lexer::header {
package com.metamx.druid.sql.antlr;
}
*/
/*
TODO: handle both multiply / division, addition - subtraction
unary minus
*/
@header {
import com.metamx.druid.aggregation.post.*;
import com.metamx.druid.aggregation.*;
import com.metamx.druid.query.filter.*;
import com.metamx.druid.query.dimension.*;
import com.metamx.druid.*;
import com.google.common.base.*;
import com.google.common.collect.Lists;
import org.joda.time.*;
import java.text.*;
import java.util.*;
}
@parser::members {
public Map<String, AggregatorFactory> aggregators = new LinkedHashMap<String, AggregatorFactory>();
public List<PostAggregator> postAggregators = new LinkedList<PostAggregator>();
public DimFilter filter;
public List<org.joda.time.Interval> intervals;
public QueryGranularity granularity = QueryGranularity.ALL;
public Map<String, DimensionSpec> groupByDimensions = new LinkedHashMap<String, DimensionSpec>();
String dataSourceName = null;
public String getDataSource() {
return dataSourceName;
}
public String unescape(String quoted) {
String unquote = quoted.trim().replaceFirst("^'(.*)'\$", "\$1");
return unquote.replace("''", "'");
}
AggregatorFactory evalAgg(String name, int fn) {
switch (fn) {
case SUM: return new DoubleSumAggregatorFactory("doubleSum:"+name, name);
case MIN: return new MinAggregatorFactory("min:"+name, name);
case MAX: return new MaxAggregatorFactory("max:"+name, name);
case COUNT: return new CountAggregatorFactory(name);
}
throw new IllegalArgumentException("Unknown function [" + fn + "]");
}
PostAggregator evalArithmeticPostAggregator(PostAggregator a, List<Token> ops, List<PostAggregator> b) {
if(b.isEmpty()) return a;
else {
int i = 0;
PostAggregator root = a;
while(i < ops.size()) {
List<PostAggregator> list = new LinkedList<PostAggregator>();
List<String> names = new LinkedList<String>();
names.add(root.getName());
list.add(root);
Token op = ops.get(i);
while(i < ops.size() && ops.get(i).getType() == op.getType()) {
PostAggregator e = b.get(i);
list.add(e);
names.add(e.getName());
i++;
}
root = new ArithmeticPostAggregator("("+Joiner.on(op.getText()).join(names)+")", op.getText(), list);
}
return root;
}
}
}
AND: 'and';
OR: 'or';
SUM: 'sum';
MIN: 'min';
MAX: 'max';
COUNT: 'count';
AS: 'as';
OPEN: '(';
CLOSE: ')';
STAR: '*';
PLUS: '+';
MINUS: '-';
DIV: '/';
COMMA: ',';
GROUP: 'group';
IDENT : (LETTER)(LETTER | DIGIT | '_')* ;
QUOTED_STRING : '\'' ( ESCqs | ~'\'' )* '\'' ;
ESCqs : '\'' '\'';
NUMBER: ('+'|'-')?DIGIT*'.'?DIGIT+(EXPONENT)?;
EXPONENT: ('e') ('+'|'-')? ('0'..'9')+;
fragment DIGIT : '0'..'9';
fragment LETTER : 'a'..'z' | 'A'..'Z';
WS : (' '| '\t' | '\r' '\n' | '\n' | '\r')+ -> skip;
query
: select_stmt where_stmt (groupby_stmt)?
;
select_stmt
: 'select' e+=aliasedExpression (',' e+=aliasedExpression)* 'from' datasource {
for(AliasedExpressionContext a : $e) { postAggregators.add(a.p); }
this.dataSourceName = $datasource.text;
}
;
where_stmt
: 'where' f=timeAndDimFilter {
if($f.filter != null) this.filter = $f.filter;
this.intervals = Lists.newArrayList($f.interval);
}
;
groupby_stmt
: GROUP 'by' groupByExpression ( COMMA! groupByExpression )*
;
groupByExpression
: gran=granularityFn {this.granularity = $gran.granularity;}
| dim=IDENT { this.groupByDimensions.put($dim.text, new DefaultDimensionSpec($dim.text, $dim.text)); }
;
datasource
: IDENT
;
aliasedExpression returns [PostAggregator p]
: expression ( AS^ name=IDENT )? {
if($name != null) {
postAggregators.add($expression.p);
$p = new FieldAccessPostAggregator($name.text, $expression.p.getName());
}
else $p = $expression.p;
}
;
expression returns [PostAggregator p]
: additiveExpression { $p = $additiveExpression.p; }
;
additiveExpression returns [PostAggregator p]
: a=multiplyExpression (( ops+=PLUS^ | ops+=MINUS^ ) b+=multiplyExpression)* {
List<PostAggregator> rhs = new LinkedList<PostAggregator>();
for(MultiplyExpressionContext e : $b) rhs.add(e.p);
$p = evalArithmeticPostAggregator($a.p, $ops, rhs);
}
;
multiplyExpression returns [PostAggregator p]
: a=unaryExpression ((ops+= STAR | ops+=DIV ) b+=unaryExpression)* {
List<PostAggregator> rhs = new LinkedList<PostAggregator>();
for(UnaryExpressionContext e : $b) rhs.add(e.p);
$p = evalArithmeticPostAggregator($a.p, $ops, rhs);
}
;
unaryExpression returns [PostAggregator p]
: MINUS e=unaryExpression {
$p = new ArithmeticPostAggregator(
"-"+$e.p.getName(),
"*",
Lists.newArrayList($e.p, new ConstantPostAggregator("-1", -1.0))
);
}
| PLUS e=unaryExpression { $p = $e.p; }
| primaryExpression { $p = $primaryExpression.p; }
;
primaryExpression returns [PostAggregator p]
: constant { $p = $constant.c; }
| aggregate {
aggregators.put($aggregate.agg.getName(), $aggregate.agg);
$p = new FieldAccessPostAggregator($aggregate.agg.getName(), $aggregate.agg.getName());
}
| OPEN! e=expression CLOSE! { $p = $e.p; }
;
aggregate returns [AggregatorFactory agg]
: fn=( SUM^ | MIN^ | MAX^ ) OPEN! name=(IDENT|COUNT) CLOSE! { $agg = evalAgg($name.text, $fn.type); }
| fn=COUNT OPEN! STAR CLOSE! { $agg = evalAgg("count", $fn.type); }
;
constant returns [ConstantPostAggregator c]
: value=NUMBER { double v = Double.parseDouble($value.text); $c = new ConstantPostAggregator(Double.toString(v), v); }
;
/* time filters must be top level filters */
timeAndDimFilter returns [DimFilter filter, org.joda.time.Interval interval]
: t=timeFilter (AND f=dimFilter)? {
if($f.ctx != null) $filter = $f.filter;
$interval = $t.interval;
}
| (f=dimFilter)? AND t=timeFilter {
if($f.ctx != null) $filter = $f.filter;
$interval = $t.interval;
}
;
dimFilter returns [DimFilter filter]
: e=orDimFilter { $filter = $e.filter; }
;
orDimFilter returns [DimFilter filter]
: a=andDimFilter (OR^ b+=andDimFilter)* {
if($b.isEmpty()) $filter = $a.filter;
else {
List<DimFilter> rest = new ArrayList<DimFilter>();
for(AndDimFilterContext e : $b) rest.add(e.filter);
$filter = new OrDimFilter(Lists.asList($a.filter, rest.toArray(new DimFilter[]{})));
}
}
;
andDimFilter returns [DimFilter filter]
: a=primaryDimFilter (AND^ b+=primaryDimFilter)* {
if($b.isEmpty()) $filter = $a.filter;
else {
List<DimFilter> rest = new ArrayList<DimFilter>();
for(PrimaryDimFilterContext e : $b) rest.add(e.filter);
$filter = new AndDimFilter(Lists.asList($a.filter, rest.toArray(new DimFilter[]{})));
}
}
;
primaryDimFilter returns [DimFilter filter]
: e=selectorDimFilter { $filter = $e.filter; }
| OPEN! f=dimFilter CLOSE! { $filter = $f.filter; }
;
selectorDimFilter returns [SelectorDimFilter filter]
: dimension=IDENT '=' value=QUOTED_STRING {
$filter = new SelectorDimFilter($dimension.text, unescape($value.text));
}
;
timeFilter returns [org.joda.time.Interval interval, QueryGranularity granularity]
: 'timestamp' 'between' s=timestamp AND e=timestamp {
$interval = new org.joda.time.Interval($s.t, $e.t);
}
;
granularityFn returns [QueryGranularity granularity]
: 'granularity' OPEN! 'timestamp' ',' str=QUOTED_STRING CLOSE! {
String granStr = unescape($str.text);
try {
$granularity = QueryGranularity.fromString(granStr);
} catch(IllegalArgumentException e) {
$granularity = new PeriodGranularity(new Period(granStr), null, null);
}
}
;
timestamp returns [DateTime t]
: NUMBER {
String str = $NUMBER.text.trim();
try {
$t = new DateTime(NumberFormat.getInstance().parse(str));
}
catch(ParseException e) {
throw new IllegalArgumentException("Unable to parse number [" + str + "]");
}
}
| QUOTED_STRING { $t = new DateTime(unescape($QUOTED_STRING.text)); }
;
|
support aliasing
|
support aliasing
|
ANTLR
|
apache-2.0
|
Deebs21/druid,gianm/druid,implydata/druid,redBorder/druid,pjain1/druid,michaelschiff/druid,authbox-lib/druid,optimizely/druid,potto007/druid-avro,mrijke/druid,rasahner/druid,liquidm/druid,zhihuij/druid,amikey/druid,du00cs/druid,minewhat/druid,anupkumardixit/druid,authbox-lib/druid,anupkumardixit/druid,zhihuij/druid,b-slim/druid,penuel-leo/druid,mghosh4/druid,optimizely/druid,noddi/druid,knoguchi/druid,Deebs21/druid,OttoOps/druid,potto007/druid-avro,zengzhihai110/druid,andy256/druid,se7entyse7en/druid,rasahner/druid,dclim/druid,deltaprojects/druid,yaochitc/druid-dev,nvoron23/druid,jon-wei/druid,monetate/druid,praveev/druid,haoch/druid,deltaprojects/druid,b-slim/druid,solimant/druid,authbox-lib/druid,cocosli/druid,nishantmonu51/druid,zhihuij/druid,KurtYoung/druid,lizhanhui/data_druid,zhaown/druid,pjain1/druid,implydata/druid,solimant/druid,erikdubbelboer/druid,mangeshpardeshiyahoo/druid,metamx/druid,erikdubbelboer/druid,fjy/druid,friedhardware/druid,gianm/druid,skyportsystems/druid,lizhanhui/data_druid,eshen1991/druid,premc/druid,pdeva/druid,taochaoqiang/druid,guobingkun/druid,noddi/druid,jon-wei/druid,calliope7/druid,yaochitc/druid-dev,taochaoqiang/druid,monetate/druid,premc/druid,zxs/druid,tubemogul/druid,skyportsystems/druid,friedhardware/druid,zhihuij/druid,zxs/druid,zhiqinghuang/druid,KurtYoung/druid,jon-wei/druid,b-slim/druid,calliope7/druid,Fokko/druid,Deebs21/druid,smartpcr/druid,jon-wei/druid,767326791/druid,mghosh4/druid,tubemogul/druid,lizhanhui/data_druid,pjain1/druid,metamx/druid,nishantmonu51/druid,haoch/druid,dkhwangbo/druid,solimant/druid,skyportsystems/druid,kevintvh/druid,guobingkun/druid,mghosh4/druid,penuel-leo/druid,rasahner/druid,KurtYoung/druid,pdeva/druid,redBorder/druid,zhaown/druid,leventov/druid,druid-io/druid,smartpcr/druid,amikey/druid,deltaprojects/druid,andy256/druid,redBorder/druid,zxs/druid,cocosli/druid,praveev/druid,Fokko/druid,solimant/druid,du00cs/druid,pombredanne/druid,haoch/druid,calliope7/druid,elijah513/druid,winval/druid,potto007/druid-avro,jon-wei/druid,himanshug/druid,kevintvh/druid,eshen1991/druid,zhihuij/druid,guobingkun/druid,andy256/druid,zhaown/druid,deltaprojects/druid,nishantmonu51/druid,fjy/druid,zhaown/druid,deltaprojects/druid,mangeshpardeshiyahoo/druid,minewhat/druid,winval/druid,friedhardware/druid,Kleagleguo/druid,zhiqinghuang/druid,milimetric/druid,gianm/druid,guobingkun/druid,druid-io/druid,implydata/druid,eshen1991/druid,zhiqinghuang/druid,dkhwangbo/druid,pjain1/druid,redBorder/druid,leventov/druid,pdeva/druid,nvoron23/druid,erikdubbelboer/druid,optimizely/druid,mrijke/druid,michaelschiff/druid,jon-wei/druid,zengzhihai110/druid,wenjixin/druid,monetate/druid,knoguchi/druid,fjy/druid,authbox-lib/druid,yaochitc/druid-dev,wenjixin/druid,pjain1/druid,solimant/druid,druid-io/druid,knoguchi/druid,friedhardware/druid,nvoron23/druid,mrijke/druid,leventov/druid,rasahner/druid,liquidm/druid,zengzhihai110/druid,dclim/druid,erikdubbelboer/druid,milimetric/druid,qix/druid,metamx/druid,Fokko/druid,pombredanne/druid,wenjixin/druid,knoguchi/druid,gianm/druid,penuel-leo/druid,penuel-leo/druid,nishantmonu51/druid,winval/druid,metamx/druid,mangeshpardeshiyahoo/druid,OttoOps/druid,taochaoqiang/druid,mghosh4/druid,potto007/druid-avro,elijah513/druid,se7entyse7en/druid,b-slim/druid,Kleagleguo/druid,KurtYoung/druid,tubemogul/druid,leventov/druid,himanshug/druid,zxs/druid,noddi/druid,wenjixin/druid,himanshug/druid,noddi/druid,b-slim/druid,haoch/druid,anupkumardixit/druid,andy256/druid,mangeshpardeshiyahoo/druid,amikey/druid,praveev/druid,michaelschiff/druid,dclim/druid,implydata/druid,monetate/druid,fjy/druid,elijah513/druid,zengzhihai110/druid,se7entyse7en/druid,winval/druid,OttoOps/druid,praveev/druid,tubemogul/druid,pdeva/druid,himanshug/druid,potto007/druid-avro,liquidm/druid,yaochitc/druid-dev,minewhat/druid,smartpcr/druid,druid-io/druid,du00cs/druid,elijah513/druid,Fokko/druid,767326791/druid,tubemogul/druid,mghosh4/druid,dkhwangbo/druid,du00cs/druid,lcp0578/druid,qix/druid,optimizely/druid,cocosli/druid,milimetric/druid,smartpcr/druid,authbox-lib/druid,lizhanhui/data_druid,milimetric/druid,mrijke/druid,lcp0578/druid,pdeva/druid,gianm/druid,pombredanne/druid,zhaown/druid,deltaprojects/druid,anupkumardixit/druid,liquidm/druid,andy256/druid,nishantmonu51/druid,anupkumardixit/druid,Deebs21/druid,redBorder/druid,OttoOps/druid,lcp0578/druid,rasahner/druid,monetate/druid,smartpcr/druid,premc/druid,premc/druid,kevintvh/druid,yaochitc/druid-dev,implydata/druid,nishantmonu51/druid,haoch/druid,praveev/druid,cocosli/druid,zengzhihai110/druid,erikdubbelboer/druid,lcp0578/druid,qix/druid,pombredanne/druid,fjy/druid,kevintvh/druid,premc/druid,zhiqinghuang/druid,767326791/druid,Kleagleguo/druid,implydata/druid,wenjixin/druid,deltaprojects/druid,cocosli/druid,dclim/druid,nvoron23/druid,pjain1/druid,Fokko/druid,taochaoqiang/druid,penuel-leo/druid,milimetric/druid,Kleagleguo/druid,Fokko/druid,lizhanhui/data_druid,leventov/druid,mrijke/druid,monetate/druid,kevintvh/druid,guobingkun/druid,michaelschiff/druid,Fokko/druid,noddi/druid,gianm/druid,mghosh4/druid,druid-io/druid,dkhwangbo/druid,liquidm/druid,se7entyse7en/druid,qix/druid,liquidm/druid,monetate/druid,KurtYoung/druid,eshen1991/druid,minewhat/druid,se7entyse7en/druid,dkhwangbo/druid,767326791/druid,pombredanne/druid,taochaoqiang/druid,qix/druid,dclim/druid,zxs/druid,knoguchi/druid,du00cs/druid,calliope7/druid,pjain1/druid,michaelschiff/druid,nishantmonu51/druid,mangeshpardeshiyahoo/druid,himanshug/druid,OttoOps/druid,winval/druid,elijah513/druid,eshen1991/druid,minewhat/druid,lcp0578/druid,metamx/druid,Deebs21/druid,jon-wei/druid,skyportsystems/druid,michaelschiff/druid,amikey/druid,optimizely/druid,767326791/druid,gianm/druid,michaelschiff/druid,amikey/druid,mghosh4/druid,nvoron23/druid,Kleagleguo/druid,friedhardware/druid,zhiqinghuang/druid,calliope7/druid,skyportsystems/druid
|
27362fb77a02b17161c86984283d6fd9cf4bdff0
|
src/main/resources/syntax/LPMLN.g4
|
src/main/resources/syntax/LPMLN.g4
|
/**
* LPMLN 词法语法定义
* 王彬
* 2016-08-30
**/
grammar LPMLN;
/**
* 词法定义
**/
//缺省否定关键字
NAF_NOT : 'not ';
//字符串
STRING : '"' ('\\"'|~('"'))* '"';
//规则终结符
FULLSTOP : '.';
//正整数
POSITIVE_INT : [1-9][0-9]*;
//小数(点表示法)
DECIMAL : MINUS? (POSITIVE_INT* | ZERO ) FULLSTOP [0-9] ZERO* [1-9]*;
//0
ZERO : '0';
//常量
CONSTANT : [a-z][a-zA-Z0-9_]*;
//变量
VAR : [A-Z][a-zA-Z0-9_]*;
//加号
PLUS : '+';
//减号、经典否定关键字
MINUS : '-';
//乘号、 星号
STAR : '*';
//除号、斜线
SLASH : '/';
//左圆括号
LPAREN : '(';
//右圆括号
RPAREN : ')';
//左方括号
LSBRACK : '[';
//右方括号
RSBRACK : ']';
//左花括号
LCBRACK : '{';
//右花括号
RCBRACK : '}';
//范围运算
RANGE : '..';
//逗号
COMMA : ',';
//认知析取符
DISJUNCTION : '|';
//条件限制符
CONDITION : ':';
//推导符号
ASSIGN : ':-';
//弱约束推导符号
WEAK_ASSIGN : ':~';
//分号
SEMICOLON : ';';
//关系运算符
LESS_THAN : '<';
LEQ : '<=';
GREATER_THAN : '>';
GEQ : '>=';
EQUAL : '=';
DOUBLE_EQUAL : '==';
NEQ : '!=';
AGGREGATE_OP : '#count' | '#sum' | '#max' | '#min';
//
META_OP : '#show ';
//单行注释
LINE_COMMENT : ('%' ~('\r' | '\n')* '\r'? '\n') -> skip;
//空白字符或换行符
WS : ( ' ' | '\t' | '\n' | '\r')+ -> skip ;
/**
* 语法规则定义
**/
//负整数
negative_int : MINUS POSITIVE_INT ;
//整数
integer : POSITIVE_INT | negative_int | ZERO;
//自然数
natural_number : POSITIVE_INT | ZERO;
//四则运算符
arithmetic_op : PLUS | MINUS | STAR | SLASH;
//关系运算符(comparison predicates)
relation_op : LESS_THAN | LEQ | GREATER_THAN | GEQ | EQUAL | DOUBLE_EQUAL | NEQ;
//简单四则运算算术表达式,不加括号
simple_arithmetic_expr :
integer |
(MINUS)? VAR |
(integer | (MINUS)? VAR) (arithmetic_op (natural_number | VAR))* ;
//四则运算算术表达式,加括号
simple_arithmetic_expr2 :
simple_arithmetic_expr |
(LPAREN simple_arithmetic_expr2 RPAREN) |
simple_arithmetic_expr2 arithmetic_op simple_arithmetic_expr2;
//四则运算表达式
arithmethic_expr:
simple_arithmetic_expr2 |
MINUS LPAREN simple_arithmetic_expr2 RPAREN;
//函数
function : CONSTANT LPAREN term (COMMA term)* RPAREN;
//项
term : VAR | CONSTANT | integer | arithmethic_expr | function | STRING;
//原子
atom :
CONSTANT |
CONSTANT LPAREN term (COMMA term)* RPAREN;
//范围整数枚举原子
range_atom : CONSTANT LPAREN integer RANGE integer RPAREN;
//文字
literal : atom | MINUS atom | NAF_NOT literal;
//缺省文字
//default_literal : NAF_NOT literal;
//扩展文字,包含查询原子
//extended_literal : literal | default_literal;
//项元组
term_tuple : term (COMMA term)*;
//文字元组
literal_tuple : literal (COMMA literal)*;
//聚合元素
aggregate_elements : (term_tuple CONDITION)? literal_tuple (SEMICOLON (term_tuple CONDITION)? literal_tuple)*;
//带条件的聚合元素
aggregate_elements_condition : (term_tuple CONDITION)? literal_tuple CONDITION literal_tuple (SEMICOLON (term_tuple CONDITION)? literal_tuple CONDITION literal_tuple)*;
//体部聚合原子
body_aggregate : (term relation_op?)? AGGREGATE_OP? LCBRACK aggregate_elements RCBRACK (relation_op? term)?;
//aggregate_atom : AGGREGATE_OP LCBRACK (literal | VAR) CONDITION literal RCBRACK ;
//头部聚合原子
head_aggregate : (term relation_op?)? AGGREGATE_OP? LCBRACK aggregate_elements_condition RCBRACK (relation_op? term)?;
//聚合运算表达式
//aggregate_expr: (VAR | aggregate_atom | integer) relation_op aggregate_atom |
// aggregate_atom relation_op (VAR | integer) |
// VAR EQUAL aggregate_atom;
//关系运算表达式
relation_expr :
(MINUS)? VAR relation_op (MINUS)? VAR |
VAR relation_op STRING |
((MINUS)? VAR | arithmethic_expr) relation_op ((MINUS)? VAR | arithmethic_expr);
//规则头部
head : head_literal (DISJUNCTION head_literal)*;
//头部文字
head_literal : literal | head_aggregate | NAF_NOT head_literal;
//规则体部
body : body_literal (COMMA body_literal)*;
//体部文字
body_literal : literal | relation_expr | body_aggregate | NAF_NOT body_literal;
//事实
fact : (head | range_atom) FULLSTOP;
//约束
constraint : ASSIGN body FULLSTOP;
//基本规则
full_rule : head ASSIGN body FULLSTOP;
//ASP 规则 (hard rule)
hard_rule : fact | constraint | full_rule;
//弱规则 (soft rule)
soft_rule : (DECIMAL | integer ) CONDITION hard_rule;
//
meta_rule : META_OP (MINUS)? CONSTANT SLASH natural_number FULLSTOP;
//ASP4QA程序
lpmln_rule : (hard_rule | soft_rule | meta_rule)*;
|
/**
* LPMLN 词法语法定义
* 王彬
* 2016-08-30
**/
grammar LPMLN;
/**
* 词法定义
**/
//缺省否定关键字
NAF_NOT : 'not ';
//字符串
STRING : '"' ('\\"'|~('"'))* '"';
//规则终结符
FULLSTOP : '.';
//正整数
POSITIVE_INT : [1-9][0-9]*;
//小数(点表示法)
DECIMAL : MINUS? (POSITIVE_INT* | ZERO ) FULLSTOP [0-9] ZERO* [1-9]*;
//0
ZERO : '0';
//常量
CONSTANT : [a-z][a-zA-Z0-9_]*;
//变量
VAR : [A-Z][a-zA-Z0-9_]*;
//加号
PLUS : '+';
//减号、经典否定关键字
MINUS : '-';
//乘号、 星号
STAR : '*';
//除号、斜线
SLASH : '/';
//左圆括号
LPAREN : '(';
//右圆括号
RPAREN : ')';
//左方括号
LSBRACK : '[';
//右方括号
RSBRACK : ']';
//左花括号
LCBRACK : '{';
//右花括号
RCBRACK : '}';
//范围运算
RANGE : '..';
//逗号
COMMA : ',';
//认知析取符
DISJUNCTION : '|';
//条件限制符
CONDITION : ':';
//推导符号
ASSIGN : ':-';
//弱约束推导符号
WEAK_ASSIGN : ':~';
//分号
SEMICOLON : ';';
//关系运算符
LESS_THAN : '<';
LEQ : '<=';
GREATER_THAN : '>';
GEQ : '>=';
EQUAL : '=';
DOUBLE_EQUAL : '==';
NEQ : '!=';
AGGREGATE_OP : '#count' | '#sum' | '#max' | '#min';
//
META_OP : '#show ';
//单行注释
LINE_COMMENT : ('%' ~('\r' | '\n')* '\r'? '\n') -> skip;
//空白字符或换行符
WS : ( ' ' | '\t' | '\n' | '\r')+ -> skip ;
//布尔常量
BOOL_CONSTANTS : '#true' | '#false';
/**
* 语法规则定义
**/
//负整数
negative_int : MINUS POSITIVE_INT ;
//整数
integer : POSITIVE_INT | negative_int | ZERO;
//自然数
natural_number : POSITIVE_INT | ZERO;
//四则运算符
arithmetic_op : PLUS | MINUS | STAR | SLASH;
//关系运算符(comparison predicates)
relation_op : LESS_THAN | LEQ | GREATER_THAN | GEQ | EQUAL | DOUBLE_EQUAL | NEQ;
//简单四则运算算术表达式,不加括号
simple_arithmetic_expr :
integer |
(MINUS)? VAR |
(integer | (MINUS)? VAR) (arithmetic_op (natural_number | VAR))* ;
//四则运算算术表达式,加括号
simple_arithmetic_expr2 :
simple_arithmetic_expr |
(LPAREN simple_arithmetic_expr2 RPAREN) |
simple_arithmetic_expr2 arithmetic_op simple_arithmetic_expr2;
//四则运算表达式
arithmethic_expr:
simple_arithmetic_expr2 |
MINUS LPAREN simple_arithmetic_expr2 RPAREN;
//函数
function : CONSTANT LPAREN term (COMMA term)* RPAREN;
//项
term : VAR | CONSTANT | integer | arithmethic_expr | function | STRING;
//原子
atom :
CONSTANT |
CONSTANT LPAREN term (COMMA term)* RPAREN;
//范围整数枚举原子
range_atom : CONSTANT LPAREN integer RANGE integer RPAREN;
//文字
literal : atom | MINUS atom | NAF_NOT literal;
//缺省文字
//default_literal : NAF_NOT literal;
//扩展文字,包含查询原子
//extended_literal : literal | default_literal;
//项元组
term_tuple : term (COMMA term)*;
//文字元组
literal_tuple : literal (COMMA literal)*;
//聚合元素
aggregate_elements : (term_tuple CONDITION)? literal_tuple (SEMICOLON (term_tuple CONDITION)? literal_tuple)*;
//带条件的聚合元素
aggregate_elements_condition : (term_tuple CONDITION)? literal_tuple CONDITION literal_tuple (SEMICOLON (term_tuple CONDITION)? literal_tuple CONDITION literal_tuple)*;
//体部聚合原子
body_aggregate : (term relation_op?)? AGGREGATE_OP? LCBRACK aggregate_elements RCBRACK (relation_op? term)?;
//aggregate_atom : AGGREGATE_OP LCBRACK (literal | VAR) CONDITION literal RCBRACK ;
//头部聚合原子
head_aggregate : (term relation_op?)? AGGREGATE_OP? LCBRACK aggregate_elements_condition RCBRACK (relation_op? term)?;
//聚合运算表达式
//aggregate_expr: (VAR | aggregate_atom | integer) relation_op aggregate_atom |
// aggregate_atom relation_op (VAR | integer) |
// VAR EQUAL aggregate_atom;
//关系运算表达式
relation_expr :
(MINUS)? VAR relation_op (MINUS)? VAR |
VAR relation_op STRING |
((MINUS)? VAR | arithmethic_expr) relation_op ((MINUS)? VAR | arithmethic_expr);
//规则头部
head : head_literal (DISJUNCTION head_literal)*;
//头部文字
head_literal : literal | head_aggregate | NAF_NOT head_literal;
//规则体部
body : body_literal (COMMA body_literal)*;
//体部文字
body_literal : literal | relation_expr | body_aggregate | NAF_NOT body_literal;
//事实
fact : (head | range_atom) FULLSTOP;
//约束
constraint : ASSIGN body FULLSTOP;
//基本规则
full_rule : head ASSIGN body FULLSTOP;
//ASP 规则 (hard rule)
hard_rule : fact | constraint | full_rule;
//弱规则 (soft rule)
soft_rule : (DECIMAL | integer ) CONDITION hard_rule;
//
meta_rule : META_OP (MINUS)? CONSTANT SLASH natural_number FULLSTOP;
//ASP4QA程序
lpmln_rule : (hard_rule | soft_rule | meta_rule)*;
|
添加布尔常量,暂未使用
|
添加布尔常量,暂未使用
Signed-off-by: 许鸿翔 <[email protected]>
|
ANTLR
|
agpl-3.0
|
wangbiu/lpmlnmodels
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.