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
3d3c7e6a168a6d426ce41dffd8127d09f26a5512
sharding-core/src/main/antlr4/io/shardingsphere/core/parsing/antlr/autogen/OracleStatement.g4
sharding-core/src/main/antlr4/io/shardingsphere/core/parsing/antlr/autogen/OracleStatement.g4
grammar OracleStatement; import OracleKeyword, Keyword, OracleBase, OracleCreateIndex, OracleAlterIndex , OracleDropIndex, OracleCreateTable, OracleAlterTable, OracleDropTable, OracleTruncateTable , OracleTCLStatement, OracleDCLStatement ; execute : createIndex | alterIndex | dropIndex | createTable | alterTable | dropTable | truncateTable | setTransaction | commit | rollback | savepoint | grant | revoke ;
grammar OracleStatement; import OracleKeyword, Keyword, OracleBase, OracleCreateIndex, OracleAlterIndex , OracleDropIndex, OracleCreateTable, OracleAlterTable, OracleDropTable, OracleTruncateTable , OracleTCLStatement, OracleDCLStatement ; execute : createIndex | alterIndex | dropIndex | createTable | alterTable | dropTable | truncateTable | setTransaction | commit | rollback | savepoint | grant | revoke | createUser ;
add create user statement
add create user statement
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
85c83eebb9c8d4ba30678316986976bbc6eeb9b2
sharding-core/sharding-core-parse/sharding-core-parse-oracle/src/main/antlr4/imports/oracle/DDLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-oracle/src/main/antlr4/imports/oracle/DDLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE tableName createDefinitionClause_ ; createIndex : CREATE createIndexSpecification_ INDEX indexName ON (tableIndexClause_ | bitmapJoinIndexClause_) ; alterTable : ALTER TABLE tableName (alterTableProperties | columnClauses | constraintClauses | alterExternalTable)? ; // TODO hongjun throw exeption when alter index on oracle alterIndex : ALTER INDEX indexName (RENAME TO indexName)? ; dropTable : DROP TABLE tableName ; dropIndex : DROP INDEX indexName ; truncateTable : TRUNCATE TABLE tableName ; createTableSpecification_ : (GLOBAL TEMPORARY)? ; tablespaceClauseWithParen : LP_ tablespaceClause RP_ ; tablespaceClause : TABLESPACE ignoredIdentifier_ ; domainIndexClause : indexTypeName ; createDefinitionClause_ : (LP_ relationalProperties RP_)? (ON COMMIT (DELETE | PRESERVE) ROWS)? ; relationalProperties : relationalProperty (COMMA_ relationalProperty)* ; relationalProperty : columnDefinition | virtualColumnDefinition | outOfLineConstraint | outOfLineRefConstraint ; columnDefinition : columnName dataType SORT? (VISIBLE | INVISIBLE)? (DEFAULT (ON NULL)? expr | identityClause)? (ENCRYPT encryptionSpecification_)? (inlineConstraint+ | inlineRefConstraint)? ; identityClause : GENERATED (ALWAYS | BY DEFAULT (ON NULL)?) AS IDENTITY LP_? (identityOptions+)? RP_? ; identityOptions : START WITH (NUMBER_ | LIMIT VALUE) | INCREMENT BY NUMBER_ | MAXVALUE NUMBER_ | NOMAXVALUE | MINVALUE NUMBER_ | NOMINVALUE | CYCLE | NOCYCLE | CACHE NUMBER_ | NOCACHE | ORDER | NOORDER ; encryptionSpecification_ : (USING STRING_)? (IDENTIFIED BY STRING_)? STRING_? (NO? SALT)? ; inlineConstraint : (CONSTRAINT ignoredIdentifier_)? (NOT? NULL | UNIQUE | primaryKey | referencesClause | CHECK LP_ expr RP_) constraintState* ; referencesClause : REFERENCES tableName columnNames? (ON DELETE (CASCADE | SET NULL))? ; constraintState : notDeferrable | initiallyClause | RELY | NORELY | usingIndexClause | ENABLE | DISABLE | VALIDATE | NOVALIDATE | exceptionsClause ; notDeferrable : NOT? DEFERRABLE ; initiallyClause : INITIALLY (IMMEDIATE | DEFERRED) ; exceptionsClause : EXCEPTIONS INTO tableName ; usingIndexClause : USING INDEX (indexName | LP_ createIndex RP_)? ; inlineRefConstraint : SCOPE IS tableName | WITH ROWID | (CONSTRAINT ignoredIdentifier_)? referencesClause constraintState* ; virtualColumnDefinition : columnName dataType? (GENERATED ALWAYS)? AS LP_ expr RP_ VIRTUAL? inlineConstraint* ; outOfLineConstraint : (CONSTRAINT ignoredIdentifier_)? (UNIQUE columnNames | primaryKey columnNames | FOREIGN KEY columnNames referencesClause | CHECK LP_ expr RP_ ) constraintState* ; outOfLineRefConstraint : SCOPE FOR LP_ lobItem RP_ IS tableName | REF LP_ lobItem RP_ WITH ROWID | (CONSTRAINT ignoredIdentifier_)? FOREIGN KEY lobItemList referencesClause constraintState* ; createIndexSpecification_ : (UNIQUE | BITMAP)? ; tableIndexClause_ : tableName alias? indexExpressions_ ; indexExpressions_ : LP_ indexExpression_ (COMMA_ indexExpression_)* RP_ ; indexExpression_ : (columnName | expr) (ASC | DESC)? ; bitmapJoinIndexClause_ : tableName columnSortsClause_ FROM tableAlias WHERE expr ; columnSortsClause_ : LP_ columnSortClause_ (COMMA_ columnSortClause_)* RP_ ; columnSortClause_ : (tableName | alias)? columnName (ASC | DESC)? ; tableAlias : tableName alias? (COMMA_ tableName alias?)* ; tableProperties : columnProperties? (AS unionSelect)? ; unionSelect : matchNone ; alterTableProperties : renameTableSpecification_ | REKEY encryptionSpecification_ ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; columnClauses : opColumnClause+ | renameColumnSpecification ; opColumnClause : addColumnSpecification | modifyColumnSpecification | dropColumnClause ; addColumnSpecification : ADD columnOrVirtualDefinitions columnProperties? ; columnOrVirtualDefinitions : LP_ columnOrVirtualDefinition (COMMA_ columnOrVirtualDefinition)* RP_ | columnOrVirtualDefinition ; columnOrVirtualDefinition : columnDefinition | virtualColumnDefinition ; modifyColumnSpecification : MODIFY (LP_? modifyColProperties (COMMA_ modifyColProperties)* RP_? | modifyColSubstitutable) ; modifyColProperties : columnName dataType? (DEFAULT expr)? (ENCRYPT encryptionSpecification_ | DECRYPT)? inlineConstraint* ; modifyColSubstitutable : COLUMN columnName NOT? SUBSTITUTABLE AT ALL LEVELS FORCE? ; dropColumnClause : SET UNUSED columnOrColumnList cascadeOrInvalidate* | dropColumnSpecification ; dropColumnSpecification : DROP columnOrColumnList cascadeOrInvalidate* checkpointNumber? ; columnOrColumnList : COLUMN columnName | LP_ columnName (COMMA_ columnName)* RP_ ; cascadeOrInvalidate : CASCADE CONSTRAINTS | INVALIDATE ; checkpointNumber : CHECKPOINT NUMBER_ ; renameColumnSpecification : RENAME COLUMN columnName TO columnName ; constraintClauses : addConstraintSpecification | modifyConstraintClause | renameConstraintClause | dropConstraintClause+ ; addConstraintSpecification : ADD (outOfLineConstraint+ | outOfLineRefConstraint) ; modifyConstraintClause : MODIFY constraintOption constraintState+ CASCADE? ; constraintWithName : CONSTRAINT ignoredIdentifier_ ; constraintOption : constraintWithName | constraintPrimaryOrUnique ; constraintPrimaryOrUnique : primaryKey | UNIQUE columnNames ; renameConstraintClause : RENAME constraintWithName TO ignoredIdentifier_ ; dropConstraintClause : DROP ( constraintPrimaryOrUnique CASCADE? ((KEEP | DROP) INDEX)? | (CONSTRAINT ignoredIdentifier_ CASCADE?) ) ; alterExternalTable : (addColumnSpecification | modifyColumnSpecification | dropColumnSpecification)+ ; objectProperties : objectProperty (COMMA_ objectProperty)* ; objectProperty : (columnName | attributeName) (DEFAULT expr)? (inlineConstraint* | inlineRefConstraint?) | outOfLineConstraint | outOfLineRefConstraint ; columnProperties : columnProperty+ ; columnProperty : objectTypeColProperties ; objectTypeColProperties : COLUMN columnName substitutableColumnClause ; substitutableColumnClause : ELEMENT? IS OF TYPE? LP_ ONLY? dataTypeName_ RP_ | NOT? SUBSTITUTABLE AT ALL LEVELS ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE tableName createDefinitionClause_ ; createIndex : CREATE createIndexSpecification_ INDEX indexName ON (tableIndexClause_ | bitmapJoinIndexClause_) ; alterTable : ALTER TABLE tableName alterClause_ ; // TODO hongjun throw exeption when alter index on oracle alterIndex : ALTER INDEX indexName (RENAME TO indexName)? ; dropTable : DROP TABLE tableName ; dropIndex : DROP INDEX indexName ; truncateTable : TRUNCATE TABLE tableName ; createTableSpecification_ : (GLOBAL TEMPORARY)? ; tablespaceClauseWithParen : LP_ tablespaceClause RP_ ; tablespaceClause : TABLESPACE ignoredIdentifier_ ; domainIndexClause : indexTypeName ; createDefinitionClause_ : (LP_ relationalProperties RP_)? (ON COMMIT (DELETE | PRESERVE) ROWS)? ; relationalProperties : relationalProperty (COMMA_ relationalProperty)* ; relationalProperty : columnDefinition | virtualColumnDefinition | outOfLineConstraint | outOfLineRefConstraint ; columnDefinition : columnName dataType SORT? (VISIBLE | INVISIBLE)? (DEFAULT (ON NULL)? expr | identityClause)? (ENCRYPT encryptionSpecification_)? (inlineConstraint+ | inlineRefConstraint)? ; identityClause : GENERATED (ALWAYS | BY DEFAULT (ON NULL)?) AS IDENTITY LP_? (identityOptions+)? RP_? ; identityOptions : START WITH (NUMBER_ | LIMIT VALUE) | INCREMENT BY NUMBER_ | MAXVALUE NUMBER_ | NOMAXVALUE | MINVALUE NUMBER_ | NOMINVALUE | CYCLE | NOCYCLE | CACHE NUMBER_ | NOCACHE | ORDER | NOORDER ; encryptionSpecification_ : (USING STRING_)? (IDENTIFIED BY STRING_)? STRING_? (NO? SALT)? ; inlineConstraint : (CONSTRAINT ignoredIdentifier_)? (NOT? NULL | UNIQUE | primaryKey | referencesClause | CHECK LP_ expr RP_) constraintState* ; referencesClause : REFERENCES tableName columnNames? (ON DELETE (CASCADE | SET NULL))? ; constraintState : notDeferrable | initiallyClause | RELY | NORELY | usingIndexClause | ENABLE | DISABLE | VALIDATE | NOVALIDATE | exceptionsClause ; notDeferrable : NOT? DEFERRABLE ; initiallyClause : INITIALLY (IMMEDIATE | DEFERRED) ; exceptionsClause : EXCEPTIONS INTO tableName ; usingIndexClause : USING INDEX (indexName | LP_ createIndex RP_)? ; inlineRefConstraint : SCOPE IS tableName | WITH ROWID | (CONSTRAINT ignoredIdentifier_)? referencesClause constraintState* ; virtualColumnDefinition : columnName dataType? (GENERATED ALWAYS)? AS LP_ expr RP_ VIRTUAL? inlineConstraint* ; outOfLineConstraint : (CONSTRAINT ignoredIdentifier_)? (UNIQUE columnNames | primaryKey columnNames | FOREIGN KEY columnNames referencesClause | CHECK LP_ expr RP_ ) constraintState* ; outOfLineRefConstraint : SCOPE FOR LP_ lobItem RP_ IS tableName | REF LP_ lobItem RP_ WITH ROWID | (CONSTRAINT ignoredIdentifier_)? FOREIGN KEY lobItemList referencesClause constraintState* ; createIndexSpecification_ : (UNIQUE | BITMAP)? ; tableIndexClause_ : tableName alias? indexExpressions_ ; indexExpressions_ : LP_ indexExpression_ (COMMA_ indexExpression_)* RP_ ; indexExpression_ : (columnName | expr) (ASC | DESC)? ; bitmapJoinIndexClause_ : tableName columnSortsClause_ FROM tableAlias WHERE expr ; columnSortsClause_ : LP_ columnSortClause_ (COMMA_ columnSortClause_)* RP_ ; columnSortClause_ : (tableName | alias)? columnName (ASC | DESC)? ; tableAlias : tableName alias? (COMMA_ tableName alias?)* ; alterClause_ : (alterTableProperties | columnClauses | constraintClauses | alterExternalTable)? ; alterTableProperties : renameTableSpecification_ | REKEY encryptionSpecification_ ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; columnClauses : operateColumnClause+ | renameColumnClause ; operateColumnClause : addColumnSpecification | modifyColumnSpecification | dropColumnClause ; addColumnSpecification : ADD columnOrVirtualDefinitions columnProperties? ; columnOrVirtualDefinitions : LP_ columnOrVirtualDefinition (COMMA_ columnOrVirtualDefinition)* RP_ | columnOrVirtualDefinition ; columnOrVirtualDefinition : columnDefinition | virtualColumnDefinition ; columnProperties : columnProperty+ ; columnProperty : objectTypeColProperties ; objectTypeColProperties : COLUMN columnName substitutableColumnClause ; substitutableColumnClause : ELEMENT? IS OF TYPE? LP_ ONLY? dataTypeName_ RP_ | NOT? SUBSTITUTABLE AT ALL LEVELS ; modifyColumnSpecification : MODIFY (LP_? modifyColProperties (COMMA_ modifyColProperties)* RP_? | modifyColSubstitutable) ; modifyColProperties : columnName dataType? (DEFAULT expr)? (ENCRYPT encryptionSpecification_ | DECRYPT)? inlineConstraint* ; modifyColSubstitutable : COLUMN columnName NOT? SUBSTITUTABLE AT ALL LEVELS FORCE? ; dropColumnClause : SET UNUSED columnOrColumnList cascadeOrInvalidate* | dropColumnSpecification ; dropColumnSpecification : DROP columnOrColumnList cascadeOrInvalidate* checkpointNumber? ; columnOrColumnList : COLUMN columnName | LP_ columnName (COMMA_ columnName)* RP_ ; cascadeOrInvalidate : CASCADE CONSTRAINTS | INVALIDATE ; checkpointNumber : CHECKPOINT NUMBER_ ; renameColumnClause : RENAME COLUMN columnName TO columnName ; constraintClauses : addConstraintSpecification | modifyConstraintClause | renameConstraintClause | dropConstraintClause+ ; addConstraintSpecification : ADD (outOfLineConstraint+ | outOfLineRefConstraint) ; modifyConstraintClause : MODIFY constraintOption constraintState+ CASCADE? ; constraintWithName : CONSTRAINT ignoredIdentifier_ ; constraintOption : constraintWithName | constraintPrimaryOrUnique ; constraintPrimaryOrUnique : primaryKey | UNIQUE columnNames ; renameConstraintClause : RENAME constraintWithName TO ignoredIdentifier_ ; dropConstraintClause : DROP ( constraintPrimaryOrUnique CASCADE? ((KEEP | DROP) INDEX)? | (CONSTRAINT ignoredIdentifier_ CASCADE?) ) ; alterExternalTable : (addColumnSpecification | modifyColumnSpecification | dropColumnSpecification)+ ; objectProperties : objectProperty (COMMA_ objectProperty)* ; objectProperty : (columnName | attributeName) (DEFAULT expr)? (inlineConstraint* | inlineRefConstraint?) | outOfLineConstraint | outOfLineRefConstraint ;
rename to addColumnSpecification
rename to addColumnSpecification
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
694e5be8ea09a8f530c6fa897037f780e5a5ae90
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; grantee : userName | roleName | PUBLIC ; granteeIdentifiedBy : userName (COMMA userName)* IDENTIFIED BY STRING (COMMA STRING)* ; grantObjectPrivileges : objectPrivilege (COMMA objectPrivilege)* ; grantObjectPrivilege : (objectPrivilege | ALL PRIVILEGES?)( LEFT_PAREN columnName (COMMA columnName)* RIGHT_PAREN)? ; objectPrivilege : ID *? ; grantRolesToPrograms : roleName (COMMA roleName)* TO programUnit ( COMMA programUnit )* ; programUnit : (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID ;
grammar OracleDCLStatement; import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol; granteeClause : grantee (COMMA grantee) ; grantee : userName | roleName | PUBLIC ; granteeIdentifiedBy : userName (COMMA userName)* IDENTIFIED BY STRING (COMMA STRING)* ; grantObjectPrivileges : objectPrivilege (COMMA objectPrivilege)* ; grantObjectPrivilege : (objectPrivilege | ALL PRIVILEGES?)( LEFT_PAREN columnName (COMMA columnName)* RIGHT_PAREN)? ; objectPrivilege : ID *? ; grantRolesToPrograms : roleName (COMMA roleName)* TO programUnit ( COMMA programUnit )* ; programUnit : (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID ;
add granteeClause
add granteeClause
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
878d2aae33ffed355d7bfd07d28434ed10d4c4f0
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
grammar OracleDCLStatement; import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol; /** * each statement has a url, * each base url : https://docs.oracle.com/database/121/SQLRF/. * no begin statement in oracle */ //statements_9014.htm#SQLRF01603 grant : GRANT ( (grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))? | grantRolesToPrograms ) ; grantSystemPrivileges : systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)? ; systemObjects : systemObject(COMMA systemObject)* ; systemObject : ALL PRIVILEGES | roleName | ID *? ; grantees : grantee (COMMA grantee)* ; grantee : userName | roleName | PUBLIC ; granteeIdentifiedBy : userNames IDENTIFIED BY STRING (COMMA STRING)* ; grantObjectPrivilegeClause : grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause TO grantees (WITH HIERARCHY OPTION)?(WITH GRANT OPTION)? ; grantObjectPrivilege : objectPrivilege columnList? ; objectPrivilege : ID *? | ALL PRIVILEGES? ; onObjectClause : ON ( schemaName? ID | USER userName ( COMMA userName)* | (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID ) ; grantRolesToPrograms : roleNames TO programUnits ; programUnits : programUnit (COMMA programUnit)* ; programUnit : (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID ; revoke : REVOKE ( (revokeSystemPrivileges | revokeObjectPrivileges) (CONTAINER EQ_ (CURRENT | ALL))? | revokeRolesFromPrograms ) ; revokeSystemPrivileges : systemObjects FROM ; revokeObjectPrivileges : objectPrivilege (COMMA objectPrivilege)* onObjectClause FROM grantees (CASCADE CONSTRAINTS | FORCE)? ; revokeRolesFromPrograms : (roleNames | ALL) FROM programUnits ; createUser : CREATE USER userName IDENTIFIED (BY STRING | (EXTERNALLY | GLOBALLY) ( AS STRING)?) ( DEFAULT TABLESPACE ID | TEMPORARY TABLESPACE ID | (QUOTA (sizeClause | UNLIMITED) ON ID) | PROFILE ID | PASSWORD EXPIRE | ACCOUNT (LOCK | UNLOCK) | ENABLE EDITIONS | CONTAINER EQ_ (CURRENT | ALL) )* ; sizeClause : NUMBER ID? ; alterUser : ALTER USER ( userName ( IDENTIFIED (BY STRING (REPLACE STRING)? | (EXTERNALLY | GLOBALLY) ( AS STRING)?) | DEFAULT TABLESPACE ID | TEMPORARY TABLESPACE ID | (QUOTA (sizeClause | UNLIMITED) ON ID) | PROFILE ID | PASSWORD EXPIRE | ACCOUNT (LOCK | UNLOCK) | ENABLE EDITIONS (FOR ids)? FORCE? | CONTAINER EQ_ (CURRENT | ALL) | DEFAULT ROLE (roleNames| ALL (EXCEPT roleNames)?| NONE) | ID ) * | userNames proxyClause ) ; containerDataClause : ( SET CONTAINER_DATA EQ_ ( ALL | DEFAULT | idList ) |(ADD |REMOVE) CONTAINER_DATA EQ_ idList ) (FOR schemaName? ID)? ; proxyClause : (GRANT | REVOKE) CONNECT THROUGH ( ENTERPRISE USERS | userName dbUserProxyClauses?) ; dbUserProxyClauses : (WITH ( ROLE (ALL EXCEPT)? roleNames | NO ROLES ) )? (AUTHENTICATION REQUIRED )? ;
grammar OracleDCLStatement; import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol; /** * each statement has a url, * each base url : https://docs.oracle.com/database/121/SQLRF/. * no begin statement in oracle */ //statements_9014.htm#SQLRF01603 grant : GRANT ( (grantSystemPrivileges | grantObjectPrivilegeClause) (CONTAINER EQ_ (CURRENT | ALL))? | grantRolesToPrograms ) ; grantSystemPrivileges : systemObjects TO (grantees | granteeIdentifiedBy) (WITH (ADMIN | DELEGATE) OPTION)? ; systemObjects : systemObject(COMMA systemObject)* ; systemObject : ALL PRIVILEGES | roleName | ID *? ; grantees : grantee (COMMA grantee)* ; grantee : userName | roleName | PUBLIC ; granteeIdentifiedBy : userNames IDENTIFIED BY STRING (COMMA STRING)* ; grantObjectPrivilegeClause : grantObjectPrivilege (COMMA grantObjectPrivilege)* onObjectClause TO grantees (WITH HIERARCHY OPTION)?(WITH GRANT OPTION)? ; grantObjectPrivilege : objectPrivilege columnList? ; objectPrivilege : ID *? | ALL PRIVILEGES? ; onObjectClause : ON ( schemaName? ID | USER userName ( COMMA userName)* | (DIRECTORY | EDITION | MINING MODEL | JAVA (SOURCE | RESOURCE) | SQL TRANSLATION PROFILE) schemaName? ID ) ; grantRolesToPrograms : roleNames TO programUnits ; programUnits : programUnit (COMMA programUnit)* ; programUnit : (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID ; revoke : REVOKE ( (revokeSystemPrivileges | revokeObjectPrivileges) (CONTAINER EQ_ (CURRENT | ALL))? | revokeRolesFromPrograms ) ; revokeSystemPrivileges : systemObjects FROM ; revokeObjectPrivileges : objectPrivilege (COMMA objectPrivilege)* onObjectClause FROM grantees (CASCADE CONSTRAINTS | FORCE)? ; revokeRolesFromPrograms : (roleNames | ALL) FROM programUnits ; createUser : CREATE USER userName IDENTIFIED (BY STRING | (EXTERNALLY | GLOBALLY) ( AS STRING)?) ( DEFAULT TABLESPACE ID | TEMPORARY TABLESPACE ID | (QUOTA (sizeClause | UNLIMITED) ON ID) | PROFILE ID | PASSWORD EXPIRE | ACCOUNT (LOCK | UNLOCK) | ENABLE EDITIONS | CONTAINER EQ_ (CURRENT | ALL) )* ; sizeClause : NUMBER ID? ; alterUser : ALTER USER ( userName ( IDENTIFIED (BY STRING (REPLACE STRING)? | (EXTERNALLY | GLOBALLY) ( AS STRING)?) | DEFAULT TABLESPACE ID | TEMPORARY TABLESPACE ID | (QUOTA (sizeClause | UNLIMITED) ON ID) | PROFILE ID | PASSWORD EXPIRE | ACCOUNT (LOCK | UNLOCK) | ENABLE EDITIONS (FOR ids)? FORCE? | CONTAINER EQ_ (CURRENT | ALL) | DEFAULT ROLE (roleNames| ALL (EXCEPT roleNames)?| NONE) | ID ) * | userNames proxyClause ) ; containerDataClause : ( SET CONTAINER_DATA EQ_ ( ALL | DEFAULT | idList ) |(ADD |REMOVE) CONTAINER_DATA EQ_ idList ) (FOR schemaName? ID)? ; proxyClause : (GRANT | REVOKE) CONNECT THROUGH ( ENTERPRISE USERS | userName dbUserProxyClauses?) ; dbUserProxyClauses : (WITH ( ROLE (ALL EXCEPT)? roleNames | NO ROLES ) )? (AUTHENTICATION REQUIRED )? ; dropUser : DROP USER userName CASCADE? ;
add drop user
add drop user
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
7f49b1931f1ea1255b77ad80f7bb33988ab5d075
src/main/antlr4/YokohamaUnitLexer.g4
src/main/antlr4/YokohamaUnitLexer.g4
lexer grammar YokohamaUnitLexer; HASH1: '#' ; HASH2: '##' ; HASH3: '###' ; HASH4: '####' ; HASH5: '#####' ; HASH6: '######' ; TEST: 'Test:' [ \t]* -> mode(TEST_NAME); TABLE_CAPTION: '[' -> skip, mode(TABLE_NAME); SETUP: 'Setup' -> mode(PHASE_LEADING); EXERCISE: 'Exercise' -> mode(PHASE_LEADING); VERIFY: 'Verify' -> mode(PHASE_LEADING); TEARDOWN: 'Teardown' -> mode(PHASE_LEADING); BAR_EOL: '|' [ \t]* '\r'? '\n' ; BAR: '|' ; HBAR: '|' [|\-=\:\.\+ \t]* '|' [ \t]* '\r'? '\n' ; STAR_LBRACKET: '*[' -> skip, mode(ABBREVIATION); ASSERT: 'Assert' ; THAT: 'that' ; STOP: '.' ; AND: 'and' ; IS: 'is' ; NOT: 'not' ; THROWS: 'throws' ; FOR: 'for' ; ALL: 'all' ; COMMA: ',' ; RULES: 'rules' ; IN: 'in' ; UTABLE: 'Table' ; CSV: 'CSV' -> mode(AFTER_CSV) ; TSV: 'TSV' -> mode(AFTER_CSV) ; EXCEL: 'Excel' -> mode(AFTER_EXCEL) ; WHERE: 'where' ; EQ: '=' ; LET: 'Let' ; BE: 'be' ; DO: 'Do' ; A_STUB_OF: 'a' Spaces 'stub' Spaces 'of' -> mode(EXPECT_CLASS) ; SUCH: 'such' ; METHOD: 'method' Spaces? '`' -> mode(METHOD_PATTERN) ; RETURNS: 'returns' ; AN_INSTANCE_OF: 'an' Spaces 'instance' Spaces 'of' -> mode(EXPECT_CLASS) ; AN_INSTANCE: 'an' Spaces 'instance' -> mode(AFTER_AN_INSTANCE) ; AN_INVOCATION_OF: 'an' Spaces 'invocation' Spaces 'of' Spaces? '`' -> mode(METHOD_PATTERN) ; ON: 'on' ; WITH: 'with' ; NULL: 'null' ; NOTHING: 'nothing' ; TRUE: 'true' ; FALSE: 'false' ; Identifier: IdentStart IdentPart* ; Integer: IntegerLiteral ; FloatingPoint: FloatingPointLiteral ; MINUS: '-' ; EMPTY_STRING: '""' ; OPEN_BACK_TICK: '`' -> skip, mode(IN_BACK_TICK) ; OPEN_DOUBLE_QUOTE: '"' -> skip, mode(IN_DOUBLE_QUOTE) ; OPEN_SINGLE_QUOTE: '\'' -> skip, mode(IN_SINGLE_QUOTE) ; WS : Spaces -> skip ; mode TEST_NAME; TestName: ~[\r\n]+ ; NEW_LINE_TEST_NAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode TABLE_NAME; TableName: ~[\]\r\n]+ ; RBRACKET_TABLE_NAME: ']' -> skip, mode(DEFAULT_MODE) ; mode PHASE_LEADING; COLON: ':' [ \t]* -> skip, mode(PHASE_DESCRIPTION) ; NEW_LINE_PHASE_LEADING: [ \t]* '\r'? '\n' -> skip, mode(DEFAULT_MODE) ; mode PHASE_DESCRIPTION; PhaseDescription: ~[\r\n]+ ; NEW_LINE_PHASE_DESCRIPTION: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode IN_DOUBLE_QUOTE; Str: (~["\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_DOUBLE_QUOTE: '"' -> skip, mode(DEFAULT_MODE) ; mode IN_SINGLE_QUOTE; Char: (~['\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_SINGLE_QUOTE: '\'' -> skip, mode(DEFAULT_MODE) ; mode IN_BACK_TICK; Expr: ~[`]+ ; CLOSE_BACK_TICK: '`' -> skip, mode(DEFAULT_MODE) ; mode METHOD_PATTERN; BOOLEAN: 'boolean' ; BYTE: 'byte' ; SHORT: 'short' ; INT: 'int' ; LONG: 'long' ; CHAR: 'char' ; FLOAT: 'float' ; DOUBLE: 'double' ; COMMA3: ',' -> type(COMMA); THREEDOTS: '...' ; DOT: '.' ; LPAREN: '(' ; RPAREN: ')' ; LBRACKET: '[' ; RBRACKET: ']' ; Identifier3 : IdentStart IdentPart* -> type(Identifier); WS_METHOD_PATTERN: Spaces -> skip ; CLOSE_BACK_TICK2: '`' -> skip, mode(DEFAULT_MODE) ; mode EXPECT_CLASS; OPEN_BACK_TICK4: '`' -> skip, mode(CLASS) ; WS_EXPECT_CLASS: Spaces -> skip ; mode CLASS; DOT2: '.' -> type(DOT) ; Identifier4 : IdentStart IdentPart* -> type(Identifier) ; WS_CLASS: Spaces -> skip ; CLOSE_BACK_TICK3: '`' -> skip, mode(DEFAULT_MODE) ; mode AFTER_AN_INSTANCE; OF: 'of' ; Identifier5 : IdentStart IdentPart* -> type(Identifier) ; OPEN_BACK_TICK5: '`' -> skip, mode(CLASS) ; WS_AFTER_AN_INSTANCE: Spaces -> skip ; mode AFTER_CSV; OPEN_SINGLE_QUOTE3: '\'' -> skip, mode(IN_FILE_NAME) ; WS_AFTER_CSV: Spaces -> skip ; mode AFTER_EXCEL; OPEN_SINGLE_QUOTE4: '\'' -> skip, mode(IN_BOOK_NAME) ; WS_AFTER_EXCEL: Spaces -> skip ; mode IN_FILE_NAME; SingleQuoteName: (~['\r\n]|'\'\'')* ; CLOSE_SINGLE_QUOTE2: '\'' -> skip, mode(DEFAULT_MODE) ; mode IN_BOOK_NAME; SingleQuoteName3: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ; CLOSE_SINGLE_QUOTE3: '\'' -> skip, mode(DEFAULT_MODE) ; mode ABBREVIATION; ShortName: ~[\]\r\n]* ; RBRACKET_COLON: ']:' Spaces? -> skip, mode(LONG_NAME) ; mode LONG_NAME; LongName: ~[\r\n]* ; EXIT_LONG_NAME: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; fragment Spaces: [ \t\r\n]+ ; fragment IdentStart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierStart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IdentPart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierPart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IntegerLiteral: DecimalIntegerLiteral | HexIntegerLiteral | OctalIntegerLiteral | BinaryIntegerLiteral ; fragment DecimalIntegerLiteral: DecimalNumeral IntegerTypeSuffix? ; fragment HexIntegerLiteral: HexNumeral IntegerTypeSuffix? ; fragment OctalIntegerLiteral: OctalNumeral IntegerTypeSuffix? ; fragment BinaryIntegerLiteral: BinaryNumeral IntegerTypeSuffix? ; fragment IntegerTypeSuffix: [lL] ; fragment DecimalNumeral: '0' | [1-9] ([_0-9]* [0-9])? ; fragment HexNumeral: '0' [xX] HexDigits ; fragment HexDigits: [0-9a-fA-F] ([_0-9a-fA-F]* [0-9a-fA-F])? ; fragment OctalNumeral: '0' [_0-7]* [0-7] ; fragment BinaryNumeral: '0' [bB] [01] ([_01]* [01])? ; fragment FloatingPointLiteral: DecimalFloatingPointLiteral | HexadecimalFloatingPointLiteral ; fragment DecimalFloatingPointLiteral: Digits '.' Digits ExponentPart? FloatTypeSuffix? | Digits '.' ExponentPart FloatTypeSuffix? | Digits '.' ExponentPart? FloatTypeSuffix /* the above rules differ from the Java spec: fp literals which end with dot are not allowd */ | '.' Digits ExponentPart? FloatTypeSuffix? | Digits ExponentPart FloatTypeSuffix? | Digits ExponentPart? FloatTypeSuffix ; fragment Digits: [0-9] ([_0-9]* [0-9])? ; fragment ExponentPart: [eE] SignedInteger ; fragment SignedInteger: ('+' | '-')? Digits ; fragment FloatTypeSuffix: [fFdD] ; fragment HexadecimalFloatingPointLiteral: HexSignificand BinaryExponent FloatTypeSuffix? ; fragment HexSignificand: HexNumeral '.'? | '0' [xX] HexDigits? . HexDigits ; fragment BinaryExponent: [pP] SignedInteger ; fragment UnicodeEscape: '\\' 'u'+ [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] ; fragment EscapeSequence: '\\b' // (backspace BS, Unicode \u0008) | '\\t' // (horizontal tab HT, Unicode \u0009) | '\\n' // (linefeed LF, Unicode \u000a) | '\\f' // (form feed FF, Unicode \u000c) | '\\r' // (carriage return CR, Unicode \u000d) | '\\"' // (double quote ", Unicode \u0022) | '\\\'' // (single quote ', Unicode \u0027) | '\\\\' // (backslash \, Unicode \u005c) | OctalEscape // (octal value, Unicode \u0000 to \u00ff) ; fragment OctalEscape: '\\' [0-7] | '\\' [0-7] [0-7] | '\\' [0-3] [0-7] [0-7] ;
lexer grammar YokohamaUnitLexer; HASH1: '#' ; HASH2: '##' ; HASH3: '###' ; HASH4: '####' ; HASH5: '#####' ; HASH6: '######' ; TEST: 'Test:' [ \t]* -> mode(TEST_NAME); TABLE_CAPTION: '[' -> skip, mode(TABLE_NAME); SETUP: 'Setup' -> mode(PHASE_LEADING); EXERCISE: 'Exercise' -> mode(PHASE_LEADING); VERIFY: 'Verify' -> mode(PHASE_LEADING); TEARDOWN: 'Teardown' -> mode(PHASE_LEADING); BAR_EOL: '|' [ \t]* '\r'? '\n' ; BAR: '|' ; HBAR: '|' [|\-=\:\.\+ \t]* '|' [ \t]* '\r'? '\n' ; STAR_LBRACKET: '*[' -> skip, mode(ABBREVIATION); ASSERT: 'Assert' ; THAT: 'that' ; STOP: '.' ; AND: 'and' ; IS: 'is' ; NOT: 'not' ; THROWS: 'throws' ; FOR: 'for' ; ALL: 'all' ; COMMA: ',' ; RULES: 'rules' ; IN: 'in' ; UTABLE: 'Table' ; CSV: 'CSV' -> mode(AFTER_CSV) ; TSV: 'TSV' -> mode(AFTER_CSV) ; EXCEL: 'Excel' -> mode(AFTER_EXCEL) ; WHERE: 'where' ; EQ: '=' ; LET: 'Let' ; BE: 'be' ; DO: 'Do' ; A_STUB_OF: 'a' Spaces 'stub' Spaces 'of' Spaces? '`' -> mode(CLASS) ; SUCH: 'such' ; METHOD: 'method' Spaces? '`' -> mode(METHOD_PATTERN) ; RETURNS: 'returns' ; AN_INSTANCE_OF: 'an' Spaces 'instance' Spaces 'of' Spaces? '`' -> mode(CLASS) ; AN_INSTANCE: 'an' Spaces 'instance' -> mode(AFTER_AN_INSTANCE) ; AN_INVOCATION_OF: 'an' Spaces 'invocation' Spaces 'of' Spaces? '`' -> mode(METHOD_PATTERN) ; ON: 'on' ; WITH: 'with' ; NULL: 'null' ; NOTHING: 'nothing' ; TRUE: 'true' ; FALSE: 'false' ; Identifier: IdentStart IdentPart* ; Integer: IntegerLiteral ; FloatingPoint: FloatingPointLiteral ; MINUS: '-' ; EMPTY_STRING: '""' ; OPEN_BACK_TICK: '`' -> skip, mode(IN_BACK_TICK) ; OPEN_DOUBLE_QUOTE: '"' -> skip, mode(IN_DOUBLE_QUOTE) ; OPEN_SINGLE_QUOTE: '\'' -> skip, mode(IN_SINGLE_QUOTE) ; WS : Spaces -> skip ; mode TEST_NAME; TestName: ~[\r\n]+ ; NEW_LINE_TEST_NAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode TABLE_NAME; TableName: ~[\]\r\n]+ ; RBRACKET_TABLE_NAME: ']' -> skip, mode(DEFAULT_MODE) ; mode PHASE_LEADING; COLON: ':' [ \t]* -> skip, mode(PHASE_DESCRIPTION) ; NEW_LINE_PHASE_LEADING: [ \t]* '\r'? '\n' -> skip, mode(DEFAULT_MODE) ; mode PHASE_DESCRIPTION; PhaseDescription: ~[\r\n]+ ; NEW_LINE_PHASE_DESCRIPTION: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode IN_DOUBLE_QUOTE; Str: (~["\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_DOUBLE_QUOTE: '"' -> skip, mode(DEFAULT_MODE) ; mode IN_SINGLE_QUOTE; Char: (~['\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_SINGLE_QUOTE: '\'' -> skip, mode(DEFAULT_MODE) ; mode IN_BACK_TICK; Expr: ~[`]+ ; CLOSE_BACK_TICK: '`' -> skip, mode(DEFAULT_MODE) ; mode METHOD_PATTERN; BOOLEAN: 'boolean' ; BYTE: 'byte' ; SHORT: 'short' ; INT: 'int' ; LONG: 'long' ; CHAR: 'char' ; FLOAT: 'float' ; DOUBLE: 'double' ; COMMA3: ',' -> type(COMMA); THREEDOTS: '...' ; DOT: '.' ; LPAREN: '(' ; RPAREN: ')' ; LBRACKET: '[' ; RBRACKET: ']' ; Identifier3 : IdentStart IdentPart* -> type(Identifier); WS_METHOD_PATTERN: Spaces -> skip ; CLOSE_BACK_TICK2: '`' -> skip, mode(DEFAULT_MODE) ; mode CLASS; DOT2: '.' -> type(DOT) ; Identifier4 : IdentStart IdentPart* -> type(Identifier) ; WS_CLASS: Spaces -> skip ; CLOSE_BACK_TICK3: '`' -> skip, mode(DEFAULT_MODE) ; mode AFTER_AN_INSTANCE; OF: 'of' ; Identifier5 : IdentStart IdentPart* -> type(Identifier) ; OPEN_BACK_TICK5: '`' -> skip, mode(CLASS) ; WS_AFTER_AN_INSTANCE: Spaces -> skip ; mode AFTER_CSV; OPEN_SINGLE_QUOTE3: '\'' -> skip, mode(IN_FILE_NAME) ; WS_AFTER_CSV: Spaces -> skip ; mode AFTER_EXCEL; OPEN_SINGLE_QUOTE4: '\'' -> skip, mode(IN_BOOK_NAME) ; WS_AFTER_EXCEL: Spaces -> skip ; mode IN_FILE_NAME; SingleQuoteName: (~['\r\n]|'\'\'')* ; CLOSE_SINGLE_QUOTE2: '\'' -> skip, mode(DEFAULT_MODE) ; mode IN_BOOK_NAME; SingleQuoteName3: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ; CLOSE_SINGLE_QUOTE3: '\'' -> skip, mode(DEFAULT_MODE) ; mode ABBREVIATION; ShortName: ~[\]\r\n]* ; RBRACKET_COLON: ']:' Spaces? -> skip, mode(LONG_NAME) ; mode LONG_NAME; LongName: ~[\r\n]* ; EXIT_LONG_NAME: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; fragment Spaces: [ \t\r\n]+ ; fragment IdentStart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierStart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IdentPart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierPart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IntegerLiteral: DecimalIntegerLiteral | HexIntegerLiteral | OctalIntegerLiteral | BinaryIntegerLiteral ; fragment DecimalIntegerLiteral: DecimalNumeral IntegerTypeSuffix? ; fragment HexIntegerLiteral: HexNumeral IntegerTypeSuffix? ; fragment OctalIntegerLiteral: OctalNumeral IntegerTypeSuffix? ; fragment BinaryIntegerLiteral: BinaryNumeral IntegerTypeSuffix? ; fragment IntegerTypeSuffix: [lL] ; fragment DecimalNumeral: '0' | [1-9] ([_0-9]* [0-9])? ; fragment HexNumeral: '0' [xX] HexDigits ; fragment HexDigits: [0-9a-fA-F] ([_0-9a-fA-F]* [0-9a-fA-F])? ; fragment OctalNumeral: '0' [_0-7]* [0-7] ; fragment BinaryNumeral: '0' [bB] [01] ([_01]* [01])? ; fragment FloatingPointLiteral: DecimalFloatingPointLiteral | HexadecimalFloatingPointLiteral ; fragment DecimalFloatingPointLiteral: Digits '.' Digits ExponentPart? FloatTypeSuffix? | Digits '.' ExponentPart FloatTypeSuffix? | Digits '.' ExponentPart? FloatTypeSuffix /* the above rules differ from the Java spec: fp literals which end with dot are not allowd */ | '.' Digits ExponentPart? FloatTypeSuffix? | Digits ExponentPart FloatTypeSuffix? | Digits ExponentPart? FloatTypeSuffix ; fragment Digits: [0-9] ([_0-9]* [0-9])? ; fragment ExponentPart: [eE] SignedInteger ; fragment SignedInteger: ('+' | '-')? Digits ; fragment FloatTypeSuffix: [fFdD] ; fragment HexadecimalFloatingPointLiteral: HexSignificand BinaryExponent FloatTypeSuffix? ; fragment HexSignificand: HexNumeral '.'? | '0' [xX] HexDigits? . HexDigits ; fragment BinaryExponent: [pP] SignedInteger ; fragment UnicodeEscape: '\\' 'u'+ [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] ; fragment EscapeSequence: '\\b' // (backspace BS, Unicode \u0008) | '\\t' // (horizontal tab HT, Unicode \u0009) | '\\n' // (linefeed LF, Unicode \u000a) | '\\f' // (form feed FF, Unicode \u000c) | '\\r' // (carriage return CR, Unicode \u000d) | '\\"' // (double quote ", Unicode \u0022) | '\\\'' // (single quote ', Unicode \u0027) | '\\\\' // (backslash \, Unicode \u005c) | OctalEscape // (octal value, Unicode \u0000 to \u00ff) ; fragment OctalEscape: '\\' [0-7] | '\\' [0-7] [0-7] | '\\' [0-3] [0-7] [0-7] ;
Remove EXPECT_CLASS state from the lexer
Remove EXPECT_CLASS state from the lexer
ANTLR
mit
tkob/yokohamaunit,tkob/yokohamaunit
9bba885cd8a35f21cea2ab443dee8c2b656558bc
turing/turing.g4
turing/turing.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 turing; program : declarationOrStatementInMainProgram+ ; declarationOrStatementInMainProgram : declaration | statement | subprogramDeclaration ; declaration : constantDeclaration | variableDeclaration | typeDeclaration ; constantDeclaration : ('const' id_ ':=' expn) | ('const' id_ (':' typeSpec)? ':=' initializingValue) ; initializingValue : expn '(' 'init' (initializingValue (',' initializingValue)* ')') ; variableDeclaration : ('var' id_ (',' id_)* ':=' expn) | ('var' id_ (',' id_)* ':' typeSpec (':=' initializingValue)?) ; typeDeclaration : 'type' id_ ':' typeSpec ; typeSpec : standardType | subrangeType | arrayType | recordType | namedType ; standardType : 'int' | 'real' | 'boolean' | 'string' ('(' compileTimeExpn ')')? ; subrangeType : compileTimeExpn '..' expn ; arrayType : 'array' indexType (',' indexType)* 'of' typeSpec ; indexType : subrangeType | namedType ; recordType : 'record' id_ (',' id_)* ':' typeSpec (id_ (',' id_)* ':' typeSpec)* 'end' 'record' ; namedType : id_ ; subprogramDeclaration : subprogramHeader subprogramBody ; subprogramHeader : 'procedure' id_ ('(' parameterDeclaration (',' parameterDeclaration)* ')')? 'function' id_ ('(' parameterDeclaration (',' parameterDeclaration)* ')')? ':' typeSpec ; parameterDeclaration : 'var'? id_ (',' id_)* ':' parameterType ; parameterType : ':' typeSpec | 'string' '(' '*' ')' | 'array' compileTimeExpn '..' '*' (',' compileTimeExpn '..' '*')* 'of' typeSpec | 'array' compileTimeExpn '..' '*' (',' compileTimeExpn '..' '*')* 'of' string '(' '*' ')' ; subprogramBody : declarationsAndStatements 'end' id_ ; declarationsAndStatements : declarationOrStatement* ; declarationOrStatement : declaration | statement ; statement : (variableReference ':=' expn) | procedureCall | ('assert' booleanExpn) | 'result' expn | ifStatement | loopStatement | 'exit' ('when' booleanExpn)? | caseStatement | forStatement | putStatement | getStatement | openStatement | closeStatement ; procedureCall : reference ; ifStatement : 'if' booleanExpn 'then' declarationsAndStatements ('elsif' booleanExpn 'then' declarationsAndStatements)* ('else' declarationsAndStatements)? 'end' 'if' ; loopStatement : 'loop' declarationsAndStatements 'end' 'loop' ; caseStatement : 'case' expn 'of' 'label' compileTimeExpn (',' compileTimeExpn)* ':' declarationsAndStatements ('label' compileTimeExpn (',' compileTimeExpn)* ':' declarationsAndStatements)* ('label' ':' declarationsAndStatements)? 'end' 'case' ; forStatement : ('for' id_ ':' expn '..' expn ('by' expn)? declarationsAndStatements 'end' 'for') | ('for' 'decreasing' id_ ':' expn '..' expn ('by' expn)? declarationsAndStatements 'end' 'for') ; putStatement : 'put' (':' streamNumber ',')? putItem (',' putItem)? ('..')? ; putItem : expn (':' widthExpn (':' fractionWidth (':' exponentWidth)?)?)? | 'skip' ; getStatement : 'get' (':' streamNumber ',')? getItem (',' getItem)* ; getItem : variableReference | 'skip' variableReference ':' '*' | variableReference ':' widthExpn ; openStatement : 'open' ':' fileNumber ',' string ',' capability (',' capability)* ; capability : 'get' | 'put' ; closeStatement : 'close' ':' fileNumber ; streamNumber : expn ; widthExpn : expn ; fractionWidth : expn ; exponentWidth : expn ; fileNumber : expn ; variableReference : reference ; reference : id_ reference_2 ; reference_2 : (componentSelector reference_2)? ; componentSelector : '(' expn (',' expn)* ')' | '.' id_ ; booleanExpn : expn ; compileTimeExpn : expn ; expn : reference | explicitConstant | substring | expn infixOperator expn | prefixOperator expn | '(' expn ')' ; string : ExplicitStringConstant ; explicitConstant : ExplicitUnsignedIntegerConstant | ExplicitUnsignedRealConstant | ExplicitStringConstant | 'true' | 'false' ; infixOperator : '+' | '–' | '*' | '/' 'div' | 'mod' | '**' | '<' | '>' | '=' | '<=' | '>=' | 'not=' | 'and' | 'or' ; prefixOperator : '+' | '–' | 'not' ; substring : reference '(' substringPosition ('..' substringPosition)? ')' ; substringPosition : expn ('*' ('–' expn)) ; id_ : IDENTIFIER ; ExplicitUnsignedIntegerConstant : ('+' | '-')? [0-9]+ ; ExplicitUnsignedRealConstant : ('+' | '-')? ([0-9]+ '.')? [0-9]+ ('e' [0-9]+) ; ExplicitStringConstant : '"' ~ '"'* '"' ; IDENTIFIER : [a-zA-Z] [a-zA-Z_0-9]* ; COMMENT : '%' ~ [\r\n]* -> channel (HIDDEN) ; WS : [ \r\n\t]+ -> channel (HIDDEN) ;
/* 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 turing; program : declarationOrStatementInMainProgram+ EOF ; declarationOrStatementInMainProgram : declaration | statement | subprogramDeclaration ; declaration : constantDeclaration | variableDeclaration | typeDeclaration ; constantDeclaration : ('const' id_ ':=' expn) | ('const' id_ (':' typeSpec)? ':=' initializingValue) ; initializingValue : expn '(' 'init' (initializingValue (',' initializingValue)* ')') ; variableDeclaration : ('var' id_ (',' id_)* ':=' expn) | ('var' id_ (',' id_)* ':' typeSpec (':=' initializingValue)?) ; typeDeclaration : 'type' id_ ':' typeSpec ; typeSpec : standardType | subrangeType | arrayType | recordType | namedType ; standardType : 'int' | 'real' | 'boolean' | 'string' ('(' compileTimeExpn ')')? ; subrangeType : compileTimeExpn '..' expn ; arrayType : 'array' indexType (',' indexType)* 'of' typeSpec ; indexType : subrangeType | namedType ; recordType : 'record' id_ (',' id_)* ':' typeSpec (id_ (',' id_)* ':' typeSpec)* 'end' 'record' ; namedType : id_ ; subprogramDeclaration : subprogramHeader subprogramBody ; subprogramHeader : 'procedure' id_ ('(' parameterDeclaration (',' parameterDeclaration)* ')')? 'function' id_ ('(' parameterDeclaration (',' parameterDeclaration)* ')')? ':' typeSpec ; parameterDeclaration : 'var'? id_ (',' id_)* ':' parameterType ; parameterType : ':' typeSpec | 'string' '(' '*' ')' | 'array' compileTimeExpn '..' '*' (',' compileTimeExpn '..' '*')* 'of' typeSpec | 'array' compileTimeExpn '..' '*' (',' compileTimeExpn '..' '*')* 'of' string '(' '*' ')' ; subprogramBody : declarationsAndStatements 'end' id_ ; declarationsAndStatements : declarationOrStatement* ; declarationOrStatement : declaration | statement ; statement : (variableReference ':=' expn) | procedureCall | ('assert' booleanExpn) | 'result' expn | ifStatement | loopStatement | 'exit' ('when' booleanExpn)? | caseStatement | forStatement | putStatement | getStatement | openStatement | closeStatement ; procedureCall : reference ; ifStatement : 'if' booleanExpn 'then' declarationsAndStatements ('elsif' booleanExpn 'then' declarationsAndStatements)* ('else' declarationsAndStatements)? 'end' 'if' ; loopStatement : 'loop' declarationsAndStatements 'end' 'loop' ; caseStatement : 'case' expn 'of' 'label' compileTimeExpn (',' compileTimeExpn)* ':' declarationsAndStatements ('label' compileTimeExpn (',' compileTimeExpn)* ':' declarationsAndStatements)* ('label' ':' declarationsAndStatements)? 'end' 'case' ; forStatement : ('for' id_ ':' expn '..' expn ('by' expn)? declarationsAndStatements 'end' 'for') | ('for' 'decreasing' id_ ':' expn '..' expn ('by' expn)? declarationsAndStatements 'end' 'for') ; putStatement : 'put' (':' streamNumber ',')? putItem (',' putItem)* ('..')? ; putItem : expn (':' widthExpn (':' fractionWidth (':' exponentWidth)?)?)? | 'skip' ; getStatement : 'get' (':' streamNumber ',')? getItem (',' getItem)* ; getItem : variableReference | 'skip' variableReference ':' '*' | variableReference ':' widthExpn ; openStatement : 'open' ':' fileNumber ',' string ',' capability (',' capability)* ; capability : 'get' | 'put' ; closeStatement : 'close' ':' fileNumber ; streamNumber : expn ; widthExpn : expn ; fractionWidth : expn ; exponentWidth : expn ; fileNumber : expn ; variableReference : reference ; reference : id_ reference_2 ; reference_2 : (componentSelector reference_2)? ; componentSelector : '(' expn (',' expn)* ')' | '.' id_ ; booleanExpn : expn ; compileTimeExpn : expn ; expn : reference | explicitConstant | substring | expn infixOperator expn | prefixOperator expn | '(' expn ')' ; string : ExplicitStringConstant ; explicitConstant : ExplicitUnsignedIntegerConstant | ExplicitUnsignedRealConstant | ExplicitStringConstant | 'true' | 'false' ; infixOperator : '+' | '–' | '*' | '/' 'div' | 'mod' | '**' | '<' | '>' | '=' | '<=' | '>=' | 'not=' | 'and' | 'or' ; prefixOperator : '+' | '–' | 'not' ; substring : reference '(' substringPosition ('..' substringPosition)? ')' ; substringPosition : expn ('*' ('–' expn)) ; id_ : IDENTIFIER ; ExplicitUnsignedIntegerConstant : ('+' | '-')? [0-9]+ ; ExplicitUnsignedRealConstant : ('+' | '-')? ([0-9]+ '.')? [0-9]+ ('e' [0-9]+) ; ExplicitStringConstant : '"' ~ '"'* '"' ; IDENTIFIER : [a-zA-Z] [a-zA-Z_0-9]* ; COMMENT : '%' ~ [\r\n]* -> channel (HIDDEN) ; WS : [ \r\n\t]+ -> channel (HIDDEN) ;
Add EOF to start rule for turing/. Corrected grammar -- '{}' means 0 or more, not 0 or 1.
Add EOF to start rule for turing/. Corrected grammar -- '{}' means 0 or more, not 0 or 1.
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
3e3723c7f53bb0f63792a3726f6a06d5b3f2e2c1
RustLexer/RustLexer.g4
RustLexer/RustLexer.g4
lexer grammar RustLexer; tokens { EQ, LT, LE, EQEQ, NE, GE, GT, ANDAND, OROR, NOT, TILDE, PLUT, MINUS, STAR, SLASH, PERCENT, CARET, AND, OR, SHL, SHR, BINOP, BINOPEQ, AT, DOT, DOTDOT, DOTDOTDOT, COMMA, SEMI, COLON, MOD_SEP, RARROW, FAT_ARROW, LPAREN, RPAREN, LBRACKET, RBRACKET, LBRACE, RBRACE, POUND, DOLLAR, UNDERSCORE, LIT_CHAR, LIT_INTEGER, LIT_FLOAT, LIT_STR, LIT_STR_RAW, LIT_BINARY, LIT_BINARY_RAW, IDENT, LIFETIME, WHITESPACE, DOC_COMMENT, COMMENT } /* Note: due to antlr limitations, we can't represent XID_start and * XID_continue properly. ASCII-only substitute. */ fragment XID_start : [_a-zA-Z] ; fragment XID_continue : [_a-zA-Z0-9] ; /* Expression-operator symbols */ EQ : '=' ; LT : '<' ; LE : '<=' ; EQEQ : '==' ; NE : '!=' ; GE : '>=' ; GT : '>' ; ANDAND : '&&' ; OROR : '||' ; NOT : '!' ; TILDE : '~' ; PLUS : '+' ; MINUS : '-' ; STAR : '*' ; SLASH : '/' ; PERCENT : '%' ; CARET : '^' ; AND : '&' ; OR : '|' ; SHL : '<<' ; SHR : '>>' ; BINOP : PLUS | SLASH | MINUS | STAR | PERCENT | CARET | AND | OR | SHL | SHR ; BINOPEQ : BINOP EQ ; /* "Structural symbols" */ AT : '@' ; DOT : '.' ; DOTDOT : '..' ; DOTDOTDOT : '...' ; COMMA : ',' ; SEMI : ';' ; COLON : ':' ; MOD_SEP : '::' ; RARROW : '->' ; FAT_ARROW : '=>' ; LPAREN : '(' ; RPAREN : ')' ; LBRACKET : '[' ; RBRACKET : ']' ; LBRACE : '{' ; RBRACE : '}' ; POUND : '#'; DOLLAR : '$' ; UNDERSCORE : '_' ; // Literals fragment HEXIT : [0-9a-fA-F] ; fragment CHAR_ESCAPE : [nrt\\'"0] | [xX] HEXIT HEXIT | 'u' HEXIT HEXIT HEXIT HEXIT | 'U' HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT ; LIT_CHAR : '\'' ( '\\' CHAR_ESCAPE | ~[\\'\n\t\r] ) '\'' ; LIT_BYTE : 'b\'' ( '\\' ( [xX] HEXIT HEXIT | [nrt\\'"0] ) | ~[\\'\n\t\r] ) '\'' ; fragment INT_SUFFIX : 'i' | 'i8' | 'i16' | 'i32' | 'i64' | 'u' | 'u8' | 'u16' | 'u32' | 'u64' ; LIT_INTEGER : [0-9][0-9_]* INT_SUFFIX? | '0b' [01][01_]* INT_SUFFIX? | '0o' [0-7][0-7_]* INT_SUFFIX? | '0x' [0-9a-fA-F][0-9a-fA-F_]* INT_SUFFIX? ; fragment FLOAT_SUFFIX : 'f32' | 'f64' ; LIT_FLOAT : [0-9][0-9_]* ('.' | ('.' [0-9][0-9_]*)? ([eE] [-+]? [0-9][0-9_]*)? FLOAT_SUFFIX?) ; LIT_STR : '"' ('\\\n' | '\\\r\n' | '\\' CHAR_ESCAPE | .)*? '"' ; LIT_BINARY : 'b' LIT_STR ; LIT_BINARY_RAW : 'rb' LIT_STR_RAW ; /* this is a bit messy */ fragment LIT_STR_RAW_INNER : '"' .*? '"' | LIT_STR_RAW_INNER2 ; fragment LIT_STR_RAW_INNER2 : POUND LIT_STR_RAW_INNER POUND ; LIT_STR_RAW : 'r' LIT_STR_RAW_INNER ; IDENT : XID_start XID_continue* ; LIFETIME : '\'' IDENT ; WHITESPACE : [ \r\n\t]+ ; UNDOC_COMMENT : '////' ~[\r\n]* -> type(COMMENT) ; YESDOC_COMMENT : '///' ~[\r\n]* -> type(DOC_COMMENT) ; OUTER_DOC_COMMENT : '//!' ~[\r\n]* -> type(DOC_COMMENT) ; LINE_COMMENT : '//' ~[\r\n]* -> type(COMMENT) ; DOC_BLOCK_COMMENT : ('/**' ~[*] | '/*!') (DOC_BLOCK_COMMENT | .)*? '*/' -> type(DOC_COMMENT) ; BLOCK_COMMENT : '/*' (BLOCK_COMMENT | .)*? '*/' -> type(COMMENT) ;
lexer grammar RustLexer; tokens { EQ, LT, LE, EQEQ, NE, GE, GT, ANDAND, OROR, NOT, TILDE, PLUT, MINUS, STAR, SLASH, PERCENT, CARET, AND, OR, SHL, SHR, BINOP, BINOPEQ, AT, DOT, DOTDOT, DOTDOTDOT, COMMA, SEMI, COLON, MOD_SEP, RARROW, FAT_ARROW, LPAREN, RPAREN, LBRACKET, RBRACKET, LBRACE, RBRACE, POUND, DOLLAR, UNDERSCORE, LIT_CHAR, LIT_INTEGER, LIT_FLOAT, LIT_STR, LIT_STR_RAW, LIT_BINARY, LIT_BINARY_RAW, IDENT, LIFETIME, WHITESPACE, DOC_COMMENT, COMMENT } /* Note: due to antlr limitations, we can't represent XID_start and * XID_continue properly. ASCII-only substitute. */ fragment XID_start : [_a-zA-Z] ; fragment XID_continue : [_a-zA-Z0-9] ; /* Expression-operator symbols */ EQ : '=' ; LT : '<' ; LE : '<=' ; EQEQ : '==' ; NE : '!=' ; GE : '>=' ; GT : '>' ; ANDAND : '&&' ; OROR : '||' ; NOT : '!' ; TILDE : '~' ; PLUS : '+' ; MINUS : '-' ; STAR : '*' ; SLASH : '/' ; PERCENT : '%' ; CARET : '^' ; AND : '&' ; OR : '|' ; SHL : '<<' ; SHR : '>>' ; BINOP : PLUS | SLASH | MINUS | STAR | PERCENT | CARET | AND | OR | SHL | SHR ; BINOPEQ : BINOP EQ ; /* "Structural symbols" */ AT : '@' ; DOT : '.' ; DOTDOT : '..' ; DOTDOTDOT : '...' ; COMMA : ',' ; SEMI : ';' ; COLON : ':' ; MOD_SEP : '::' ; RARROW : '->' ; FAT_ARROW : '=>' ; LPAREN : '(' ; RPAREN : ')' ; LBRACKET : '[' ; RBRACKET : ']' ; LBRACE : '{' ; RBRACE : '}' ; POUND : '#'; DOLLAR : '$' ; UNDERSCORE : '_' ; // Literals fragment HEXIT : [0-9a-fA-F] ; fragment CHAR_ESCAPE : [nrt\\'"0] | [xX] HEXIT HEXIT | 'u' HEXIT HEXIT HEXIT HEXIT | 'U' HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT HEXIT ; LIT_CHAR : '\'' ( '\\' CHAR_ESCAPE | ~[\\'\n\t\r] ) ('\'' | '\r\n' | EOF) ; LIT_BYTE : 'b\'' ( '\\' ( [xX] HEXIT HEXIT | [nrt\\'"0] ) | ~[\\'\n\t\r] ) ('\'' | '\r\n' | EOF) ; fragment INT_SUFFIX : 'i' | 'i8' | 'i16' | 'i32' | 'i64' | 'u' | 'u8' | 'u16' | 'u32' | 'u64' ; LIT_INTEGER : [0-9][0-9_]* INT_SUFFIX? | '0b' [01][01_]* INT_SUFFIX? | '0o' [0-7][0-7_]* INT_SUFFIX? | '0x' [0-9a-fA-F][0-9a-fA-F_]* INT_SUFFIX? ; fragment FLOAT_SUFFIX : 'f32' | 'f64' ; LIT_FLOAT : [0-9][0-9_]* ('.' | ('.' [0-9][0-9_]*)? ([eE] [-+]? [0-9][0-9_]*)? FLOAT_SUFFIX?) ; LIT_STR : '"' ('\\\n' | '\\\r\n' | '\\' CHAR_ESCAPE | .)*? ('"' | EOF) ; LIT_BINARY : 'b' LIT_STR ; LIT_BINARY_RAW : 'rb' LIT_STR_RAW ; /* this is a bit messy */ fragment LIT_STR_RAW_INNER : '"' .*? '"' | LIT_STR_RAW_INNER2 ; fragment LIT_STR_RAW_INNER2 : POUND LIT_STR_RAW_INNER POUND ; LIT_STR_RAW : 'r' LIT_STR_RAW_INNER ; IDENT : XID_start XID_continue* ; LIFETIME : '\'' IDENT ; WHITESPACE : [ \r\n\t]+ ; UNDOC_COMMENT : '////' ~[\r\n]* -> type(COMMENT) ; YESDOC_COMMENT : '///' ~[\r\n]* -> type(DOC_COMMENT) ; OUTER_DOC_COMMENT : '//!' ~[\r\n]* -> type(DOC_COMMENT) ; LINE_COMMENT : '//' ~[\r\n]* -> type(COMMENT) ; DOC_BLOCK_COMMENT : ('/**' ~[*] | '/*!') (DOC_BLOCK_COMMENT | .)*? ('*/' | EOF) -> type(DOC_COMMENT) ; BLOCK_COMMENT : '/*' (BLOCK_COMMENT | .)*? ('*/' | EOF) -> type(COMMENT) ;
Make the grammar rules for multiline (and possibly multiline) characters more resilient
Make the grammar rules for multiline (and possibly multiline) characters more resilient
ANTLR
mit
Boddlnagg/VisualRust,Vbif/VisualRust,Muraad/VisualRust,drewet/VisualRust,xilec/VisualRust,dlsteuer/VisualRust,xilec/VisualRust,yacoder/VisualRust,vadimcn/VisualRust,Connorcpu/VisualRust,Stitchous/VisualRust,tempbottle/VisualRust,cmr/VisualRust,dlsteuer/VisualRust,Vbif/VisualRust,vadimcn/VisualRust,vosen/VisualRust,Connorcpu/VisualRust,yacoder/VisualRust,drewet/VisualRust,PistonDevelopers/VisualRust,Boddlnagg/VisualRust,cmr/VisualRust,Stitchous/VisualRust,tempbottle/VisualRust,PistonDevelopers/VisualRust,vosen/VisualRust,Muraad/VisualRust
f9e7077f3d18aa0c02020df5e4df2b97fb0500cf
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 ; 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 ; IF : I F ; 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 if to mysql keyword
add if to mysql keyword
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
edce5c44d2d681e32bb23034d822bf0fcf1cb43e
Solidity.g4
Solidity.g4
// Copyright 2016-2019 Federico Bond <[email protected]> // Licensed under the MIT license. See LICENSE file in the project root for details. grammar Solidity; sourceUnit : (pragmaDirective | importDirective | contractDefinition)* EOF ; pragmaDirective : 'pragma' pragmaName pragmaValue ';' ; pragmaName : identifier ; pragmaValue : version | expression ; version : versionConstraint versionConstraint? ; versionOperator : '^' | '~' | '>=' | '>' | '<' | '<=' | '=' ; versionConstraint : versionOperator? VersionLiteral ; importDeclaration : identifier ('as' identifier)? ; importDirective : 'import' StringLiteral ('as' identifier)? ';' | 'import' ('*' | identifier) ('as' identifier)? 'from' StringLiteral ';' | 'import' '{' importDeclaration ( ',' importDeclaration )* '}' 'from' StringLiteral ';' ; contractDefinition : ( 'contract' | 'interface' | 'library' ) identifier ( 'is' inheritanceSpecifier (',' inheritanceSpecifier )* )? '{' contractPart* '}' ; inheritanceSpecifier : userDefinedTypeName ( '(' expression ( ',' expression )* ')' )? ; contractPart : stateVariableDeclaration | usingForDeclaration | structDefinition | constructorDefinition | modifierDefinition | functionDefinition | eventDefinition | enumDefinition ; stateVariableDeclaration : typeName ( PublicKeyword | InternalKeyword | PrivateKeyword | ConstantKeyword )* identifier ('=' expression)? ';' ; usingForDeclaration : 'using' identifier 'for' ('*' | typeName) ';' ; structDefinition : 'struct' identifier '{' ( variableDeclaration ';' (variableDeclaration ';')* )? '}' ; constructorDefinition : 'constructor' parameterList modifierList block ; modifierDefinition : 'modifier' identifier parameterList? block ; modifierInvocation : identifier ( '(' expressionList? ')' )? ; functionDefinition : 'function' identifier? parameterList modifierList returnParameters? ( ';' | block ) ; returnParameters : 'returns' parameterList ; modifierList : ( modifierInvocation | stateMutability | ExternalKeyword | PublicKeyword | InternalKeyword | PrivateKeyword )* ; eventDefinition : 'event' identifier eventParameterList AnonymousKeyword? ';' ; enumValue : identifier ; enumDefinition : 'enum' identifier '{' enumValue? (',' enumValue)* '}' ; parameterList : '(' ( parameter (',' parameter)* )? ')' ; parameter : typeName storageLocation? identifier? ; eventParameterList : '(' ( eventParameter (',' eventParameter)* )? ')' ; eventParameter : typeName IndexedKeyword? identifier? ; functionTypeParameterList : '(' ( functionTypeParameter (',' functionTypeParameter)* )? ')' ; functionTypeParameter : typeName storageLocation? ; variableDeclaration : typeName storageLocation? identifier ; typeName : elementaryTypeName | userDefinedTypeName | mapping | typeName '[' expression? ']' | functionTypeName | 'address' 'payable' ; userDefinedTypeName : identifier ( '.' identifier )* ; mapping : 'mapping' '(' elementaryTypeName '=>' typeName ')' ; functionTypeName : 'function' functionTypeParameterList ( InternalKeyword | ExternalKeyword | stateMutability )* ( 'returns' functionTypeParameterList )? ; storageLocation : 'memory' | 'storage' | 'calldata'; stateMutability : PureKeyword | ConstantKeyword | ViewKeyword | PayableKeyword ; block : '{' statement* '}' ; statement : ifStatement | whileStatement | forStatement | block | inlineAssemblyStatement | doWhileStatement | continueStatement | breakStatement | returnStatement | throwStatement | emitStatement | simpleStatement ; expressionStatement : expression ';' ; ifStatement : 'if' '(' expression ')' statement ( 'else' statement )? ; whileStatement : 'while' '(' expression ')' statement ; simpleStatement : ( variableDeclarationStatement | expressionStatement ) ; forStatement : 'for' '(' ( simpleStatement | ';' ) ( expressionStatement | ';' ) expression? ')' statement ; inlineAssemblyStatement : 'assembly' StringLiteral? assemblyBlock ; doWhileStatement : 'do' statement 'while' '(' expression ')' ';' ; continueStatement : 'continue' ';' ; breakStatement : 'break' ';' ; returnStatement : 'return' expression? ';' ; throwStatement : 'throw' ';' ; emitStatement : 'emit' functionCall ';' ; variableDeclarationStatement : ( 'var' identifierList | variableDeclaration | '(' variableDeclarationList ')' ) ( '=' expression )? ';'; variableDeclarationList : variableDeclaration? (',' variableDeclaration? )* ; identifierList : '(' ( identifier? ',' )* identifier? ')' ; elementaryTypeName : 'address' | 'bool' | 'string' | 'var' | Int | Uint | 'byte' | Byte | Fixed | Ufixed ; Int : 'int' | 'int8' | 'int16' | 'int24' | 'int32' | 'int40' | 'int48' | 'int56' | 'int64' | 'int72' | 'int80' | 'int88' | 'int96' | 'int104' | 'int112' | 'int120' | 'int128' | 'int136' | 'int144' | 'int152' | 'int160' | 'int168' | 'int176' | 'int184' | 'int192' | 'int200' | 'int208' | 'int216' | 'int224' | 'int232' | 'int240' | 'int248' | 'int256' ; Uint : 'uint' | 'uint8' | 'uint16' | 'uint24' | 'uint32' | 'uint40' | 'uint48' | 'uint56' | 'uint64' | 'uint72' | 'uint80' | 'uint88' | 'uint96' | 'uint104' | 'uint112' | 'uint120' | 'uint128' | 'uint136' | 'uint144' | 'uint152' | 'uint160' | 'uint168' | 'uint176' | 'uint184' | 'uint192' | 'uint200' | 'uint208' | 'uint216' | 'uint224' | 'uint232' | 'uint240' | 'uint248' | 'uint256' ; Byte : 'bytes' | 'bytes1' | 'bytes2' | 'bytes3' | 'bytes4' | 'bytes5' | 'bytes6' | 'bytes7' | 'bytes8' | 'bytes9' | 'bytes10' | 'bytes11' | 'bytes12' | 'bytes13' | 'bytes14' | 'bytes15' | 'bytes16' | 'bytes17' | 'bytes18' | 'bytes19' | 'bytes20' | 'bytes21' | 'bytes22' | 'bytes23' | 'bytes24' | 'bytes25' | 'bytes26' | 'bytes27' | 'bytes28' | 'bytes29' | 'bytes30' | 'bytes31' | 'bytes32' ; Fixed : 'fixed' | ( 'fixed' [0-9]+ 'x' [0-9]+ ) ; Ufixed : 'ufixed' | ( 'ufixed' [0-9]+ 'x' [0-9]+ ) ; expression : expression ('++' | '--') | 'new' typeName | expression '[' expression ']' | expression '(' functionCallArguments ')' | expression '.' identifier | '(' expression ')' | ('++' | '--') expression | ('+' | '-') expression | ('after' | 'delete') expression | '!' expression | '~' expression | expression '**' expression | expression ('*' | '/' | '%') expression | expression ('+' | '-') expression | expression ('<<' | '>>') expression | expression '&' expression | expression '^' expression | expression '|' expression | expression ('<' | '>' | '<=' | '>=') expression | expression ('==' | '!=') expression | expression '&&' expression | expression '||' expression | expression '?' expression ':' expression | expression ('=' | '|=' | '^=' | '&=' | '<<=' | '>>=' | '+=' | '-=' | '*=' | '/=' | '%=') expression | primaryExpression ; primaryExpression : BooleanLiteral | numberLiteral | HexLiteral | StringLiteral | identifier | tupleExpression | elementaryTypeNameExpression ; expressionList : expression (',' expression)* ; nameValueList : nameValue (',' nameValue)* ','? ; nameValue : identifier ':' expression ; functionCallArguments : '{' nameValueList? '}' | expressionList? ; functionCall : expression '(' functionCallArguments ')' ; assemblyBlock : '{' assemblyItem* '}' ; assemblyItem : identifier | assemblyBlock | assemblyExpression | assemblyLocalDefinition | assemblyAssignment | assemblyStackAssignment | labelDefinition | assemblySwitch | assemblyFunctionDefinition | assemblyFor | assemblyIf | BreakKeyword | ContinueKeyword | subAssembly | numberLiteral | StringLiteral | HexLiteral ; assemblyExpression : assemblyCall | assemblyLiteral ; assemblyCall : ( 'return' | 'address' | 'byte' | identifier ) ( '(' assemblyExpression? ( ',' assemblyExpression )* ')' )? ; assemblyLocalDefinition : 'let' assemblyIdentifierOrList ( ':=' assemblyExpression )? ; assemblyAssignment : assemblyIdentifierOrList ':=' assemblyExpression ; assemblyIdentifierOrList : identifier | '(' assemblyIdentifierList ')' ; assemblyIdentifierList : identifier ( ',' identifier )* ; assemblyStackAssignment : '=:' identifier ; labelDefinition : identifier ':' ; assemblySwitch : 'switch' assemblyExpression assemblyCase* ; assemblyCase : 'case' assemblyLiteral assemblyBlock | 'default' assemblyBlock ; assemblyFunctionDefinition : 'function' identifier '(' assemblyIdentifierList? ')' assemblyFunctionReturns? assemblyBlock ; assemblyFunctionReturns : ( '->' assemblyIdentifierList ) ; assemblyFor : 'for' ( assemblyBlock | assemblyExpression ) assemblyExpression ( assemblyBlock | assemblyExpression ) assemblyBlock ; assemblyIf : 'if' assemblyExpression assemblyBlock ; assemblyLiteral : StringLiteral | DecimalNumber | HexNumber | HexLiteral ; subAssembly : 'assembly' identifier assemblyBlock ; tupleExpression : '(' ( expression? ( ',' expression? )* ) ')' | '[' ( expression ( ',' expression )* )? ']' ; elementaryTypeNameExpression : elementaryTypeName ; numberLiteral : (DecimalNumber | HexNumber) NumberUnit? ; identifier : ('from' | 'calldata' | Identifier) ; VersionLiteral : [0-9]+ '.' [0-9]+ '.' [0-9]+ ; BooleanLiteral : 'true' | 'false' ; DecimalNumber : ([0-9]+ | ([0-9]* '.' [0-9]+) ) ( [eE] [0-9]+ )? ; HexNumber : '0' [xX] HexCharacter+ ; NumberUnit : 'wei' | 'szabo' | 'finney' | 'ether' | 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'years' ; HexLiteral : 'hex' ('"' HexPair* '"' | '\'' HexPair* '\'') ; fragment HexPair : HexCharacter HexCharacter ; fragment HexCharacter : [0-9A-Fa-f] ; ReservedKeyword : 'abstract' | 'after' | 'case' | 'catch' | 'default' | 'final' | 'in' | 'inline' | 'let' | 'match' | 'null' | 'of' | 'relocatable' | 'static' | 'switch' | 'try' | 'type' | 'typeof' ; AnonymousKeyword : 'anonymous' ; BreakKeyword : 'break' ; ConstantKeyword : 'constant' ; ContinueKeyword : 'continue' ; ExternalKeyword : 'external' ; IndexedKeyword : 'indexed' ; InternalKeyword : 'internal' ; PayableKeyword : 'payable' ; PrivateKeyword : 'private' ; PublicKeyword : 'public' ; PureKeyword : 'pure' ; ViewKeyword : 'view' ; Identifier : IdentifierStart IdentifierPart* ; fragment IdentifierStart : [a-zA-Z$_] ; fragment IdentifierPart : [a-zA-Z0-9$_] ; StringLiteral : '"' DoubleQuotedStringCharacter* '"' | '\'' SingleQuotedStringCharacter* '\'' ; fragment DoubleQuotedStringCharacter : ~["\r\n\\] | ('\\' .) ; fragment SingleQuotedStringCharacter : ~['\r\n\\] | ('\\' .) ; WS : [ \t\r\n\u000C]+ -> skip ; COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ;
// Copyright 2016-2019 Federico Bond <[email protected]> // Licensed under the MIT license. See LICENSE file in the project root for details. grammar Solidity; sourceUnit : (pragmaDirective | importDirective | contractDefinition)* EOF ; pragmaDirective : 'pragma' pragmaName pragmaValue ';' ; pragmaName : identifier ; pragmaValue : version | expression ; version : versionConstraint versionConstraint? ; versionOperator : '^' | '~' | '>=' | '>' | '<' | '<=' | '=' ; versionConstraint : versionOperator? VersionLiteral ; importDeclaration : identifier ('as' identifier)? ; importDirective : 'import' StringLiteral ('as' identifier)? ';' | 'import' ('*' | identifier) ('as' identifier)? 'from' StringLiteral ';' | 'import' '{' importDeclaration ( ',' importDeclaration )* '}' 'from' StringLiteral ';' ; contractDefinition : ( 'contract' | 'interface' | 'library' ) identifier ( 'is' inheritanceSpecifier (',' inheritanceSpecifier )* )? '{' contractPart* '}' ; inheritanceSpecifier : userDefinedTypeName ( '(' expression ( ',' expression )* ')' )? ; contractPart : stateVariableDeclaration | usingForDeclaration | structDefinition | constructorDefinition | modifierDefinition | functionDefinition | eventDefinition | enumDefinition ; stateVariableDeclaration : typeName ( PublicKeyword | InternalKeyword | PrivateKeyword | ConstantKeyword )* identifier ('=' expression)? ';' ; usingForDeclaration : 'using' identifier 'for' ('*' | typeName) ';' ; structDefinition : 'struct' identifier '{' ( variableDeclaration ';' (variableDeclaration ';')* )? '}' ; constructorDefinition : 'constructor' parameterList modifierList block ; modifierDefinition : 'modifier' identifier parameterList? block ; modifierInvocation : identifier ( '(' expressionList? ')' )? ; functionDefinition : 'function' identifier? parameterList modifierList returnParameters? ( ';' | block ) ; returnParameters : 'returns' parameterList ; modifierList : ( modifierInvocation | stateMutability | ExternalKeyword | PublicKeyword | InternalKeyword | PrivateKeyword )* ; eventDefinition : 'event' identifier eventParameterList AnonymousKeyword? ';' ; enumValue : identifier ; enumDefinition : 'enum' identifier '{' enumValue? (',' enumValue)* '}' ; parameterList : '(' ( parameter (',' parameter)* )? ')' ; parameter : typeName storageLocation? identifier? ; eventParameterList : '(' ( eventParameter (',' eventParameter)* )? ')' ; eventParameter : typeName IndexedKeyword? identifier? ; functionTypeParameterList : '(' ( functionTypeParameter (',' functionTypeParameter)* )? ')' ; functionTypeParameter : typeName storageLocation? ; variableDeclaration : typeName storageLocation? identifier ; typeName : elementaryTypeName | userDefinedTypeName | mapping | typeName '[' expression? ']' | functionTypeName | 'address' 'payable' ; userDefinedTypeName : identifier ( '.' identifier )* ; mapping : 'mapping' '(' elementaryTypeName '=>' typeName ')' ; functionTypeName : 'function' functionTypeParameterList ( InternalKeyword | ExternalKeyword | stateMutability )* ( 'returns' functionTypeParameterList )? ; storageLocation : 'memory' | 'storage' | 'calldata'; stateMutability : PureKeyword | ConstantKeyword | ViewKeyword | PayableKeyword ; block : '{' statement* '}' ; statement : ifStatement | whileStatement | forStatement | block | inlineAssemblyStatement | doWhileStatement | continueStatement | breakStatement | returnStatement | throwStatement | emitStatement | simpleStatement ; expressionStatement : expression ';' ; ifStatement : 'if' '(' expression ')' statement ( 'else' statement )? ; whileStatement : 'while' '(' expression ')' statement ; simpleStatement : ( variableDeclarationStatement | expressionStatement ) ; forStatement : 'for' '(' ( simpleStatement | ';' ) ( expressionStatement | ';' ) expression? ')' statement ; inlineAssemblyStatement : 'assembly' StringLiteral? assemblyBlock ; doWhileStatement : 'do' statement 'while' '(' expression ')' ';' ; continueStatement : 'continue' ';' ; breakStatement : 'break' ';' ; returnStatement : 'return' expression? ';' ; throwStatement : 'throw' ';' ; emitStatement : 'emit' functionCall ';' ; variableDeclarationStatement : ( 'var' identifierList | variableDeclaration | '(' variableDeclarationList ')' ) ( '=' expression )? ';'; variableDeclarationList : variableDeclaration? (',' variableDeclaration? )* ; identifierList : '(' ( identifier? ',' )* identifier? ')' ; elementaryTypeName : 'address' | 'bool' | 'string' | 'var' | Int | Uint | 'byte' | Byte | Fixed | Ufixed ; Int : 'int' | 'int8' | 'int16' | 'int24' | 'int32' | 'int40' | 'int48' | 'int56' | 'int64' | 'int72' | 'int80' | 'int88' | 'int96' | 'int104' | 'int112' | 'int120' | 'int128' | 'int136' | 'int144' | 'int152' | 'int160' | 'int168' | 'int176' | 'int184' | 'int192' | 'int200' | 'int208' | 'int216' | 'int224' | 'int232' | 'int240' | 'int248' | 'int256' ; Uint : 'uint' | 'uint8' | 'uint16' | 'uint24' | 'uint32' | 'uint40' | 'uint48' | 'uint56' | 'uint64' | 'uint72' | 'uint80' | 'uint88' | 'uint96' | 'uint104' | 'uint112' | 'uint120' | 'uint128' | 'uint136' | 'uint144' | 'uint152' | 'uint160' | 'uint168' | 'uint176' | 'uint184' | 'uint192' | 'uint200' | 'uint208' | 'uint216' | 'uint224' | 'uint232' | 'uint240' | 'uint248' | 'uint256' ; Byte : 'bytes' | 'bytes1' | 'bytes2' | 'bytes3' | 'bytes4' | 'bytes5' | 'bytes6' | 'bytes7' | 'bytes8' | 'bytes9' | 'bytes10' | 'bytes11' | 'bytes12' | 'bytes13' | 'bytes14' | 'bytes15' | 'bytes16' | 'bytes17' | 'bytes18' | 'bytes19' | 'bytes20' | 'bytes21' | 'bytes22' | 'bytes23' | 'bytes24' | 'bytes25' | 'bytes26' | 'bytes27' | 'bytes28' | 'bytes29' | 'bytes30' | 'bytes31' | 'bytes32' ; Fixed : 'fixed' | ( 'fixed' [0-9]+ 'x' [0-9]+ ) ; Ufixed : 'ufixed' | ( 'ufixed' [0-9]+ 'x' [0-9]+ ) ; expression : expression ('++' | '--') | 'new' typeName | expression '[' expression ']' | expression '(' functionCallArguments ')' | expression '.' identifier | '(' expression ')' | ('++' | '--') expression | ('+' | '-') expression | ('after' | 'delete') expression | '!' expression | '~' expression | expression '**' expression | expression ('*' | '/' | '%') expression | expression ('+' | '-') expression | expression ('<<' | '>>') expression | expression '&' expression | expression '^' expression | expression '|' expression | expression ('<' | '>' | '<=' | '>=') expression | expression ('==' | '!=') expression | expression '&&' expression | expression '||' expression | expression '?' expression ':' expression | expression ('=' | '|=' | '^=' | '&=' | '<<=' | '>>=' | '+=' | '-=' | '*=' | '/=' | '%=') expression | primaryExpression ; primaryExpression : BooleanLiteral | numberLiteral | HexLiteral | StringLiteral | identifier ('[' ']')? | tupleExpression | elementaryTypeNameExpression ('[' ']')? ; expressionList : expression (',' expression)* ; nameValueList : nameValue (',' nameValue)* ','? ; nameValue : identifier ':' expression ; functionCallArguments : '{' nameValueList? '}' | expressionList? ; functionCall : expression '(' functionCallArguments ')' ; assemblyBlock : '{' assemblyItem* '}' ; assemblyItem : identifier | assemblyBlock | assemblyExpression | assemblyLocalDefinition | assemblyAssignment | assemblyStackAssignment | labelDefinition | assemblySwitch | assemblyFunctionDefinition | assemblyFor | assemblyIf | BreakKeyword | ContinueKeyword | subAssembly | numberLiteral | StringLiteral | HexLiteral ; assemblyExpression : assemblyCall | assemblyLiteral ; assemblyCall : ( 'return' | 'address' | 'byte' | identifier ) ( '(' assemblyExpression? ( ',' assemblyExpression )* ')' )? ; assemblyLocalDefinition : 'let' assemblyIdentifierOrList ( ':=' assemblyExpression )? ; assemblyAssignment : assemblyIdentifierOrList ':=' assemblyExpression ; assemblyIdentifierOrList : identifier | '(' assemblyIdentifierList ')' ; assemblyIdentifierList : identifier ( ',' identifier )* ; assemblyStackAssignment : '=:' identifier ; labelDefinition : identifier ':' ; assemblySwitch : 'switch' assemblyExpression assemblyCase* ; assemblyCase : 'case' assemblyLiteral assemblyBlock | 'default' assemblyBlock ; assemblyFunctionDefinition : 'function' identifier '(' assemblyIdentifierList? ')' assemblyFunctionReturns? assemblyBlock ; assemblyFunctionReturns : ( '->' assemblyIdentifierList ) ; assemblyFor : 'for' ( assemblyBlock | assemblyExpression ) assemblyExpression ( assemblyBlock | assemblyExpression ) assemblyBlock ; assemblyIf : 'if' assemblyExpression assemblyBlock ; assemblyLiteral : StringLiteral | DecimalNumber | HexNumber | HexLiteral ; subAssembly : 'assembly' identifier assemblyBlock ; tupleExpression : '(' ( expression? ( ',' expression? )* ) ')' | '[' ( expression ( ',' expression )* )? ']' ; elementaryTypeNameExpression : elementaryTypeName ; numberLiteral : (DecimalNumber | HexNumber) NumberUnit? ; identifier : ('from' | 'calldata' | Identifier) ; VersionLiteral : [0-9]+ '.' [0-9]+ '.' [0-9]+ ; BooleanLiteral : 'true' | 'false' ; DecimalNumber : ([0-9]+ | ([0-9]* '.' [0-9]+) ) ( [eE] [0-9]+ )? ; HexNumber : '0' [xX] HexCharacter+ ; NumberUnit : 'wei' | 'szabo' | 'finney' | 'ether' | 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'years' ; HexLiteral : 'hex' ('"' HexPair* '"' | '\'' HexPair* '\'') ; fragment HexPair : HexCharacter HexCharacter ; fragment HexCharacter : [0-9A-Fa-f] ; ReservedKeyword : 'abstract' | 'after' | 'case' | 'catch' | 'default' | 'final' | 'in' | 'inline' | 'let' | 'match' | 'null' | 'of' | 'relocatable' | 'static' | 'switch' | 'try' | 'type' | 'typeof' ; AnonymousKeyword : 'anonymous' ; BreakKeyword : 'break' ; ConstantKeyword : 'constant' ; ContinueKeyword : 'continue' ; ExternalKeyword : 'external' ; IndexedKeyword : 'indexed' ; InternalKeyword : 'internal' ; PayableKeyword : 'payable' ; PrivateKeyword : 'private' ; PublicKeyword : 'public' ; PureKeyword : 'pure' ; ViewKeyword : 'view' ; Identifier : IdentifierStart IdentifierPart* ; fragment IdentifierStart : [a-zA-Z$_] ; fragment IdentifierPart : [a-zA-Z0-9$_] ; StringLiteral : '"' DoubleQuotedStringCharacter* '"' | '\'' SingleQuotedStringCharacter* '\'' ; fragment DoubleQuotedStringCharacter : ~["\r\n\\] | ('\\' .) ; fragment SingleQuotedStringCharacter : ~['\r\n\\] | ('\\' .) ; WS : [ \t\r\n\u000C]+ -> skip ; COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ;
Add support for array typenames as expressions
Add support for array typenames as expressions
ANTLR
mit
solidityj/solidity-antlr4,federicobond/solidity-antlr4
a6c9d0eacde8bc7ca2439cd599c2f11aa2812a84
Protogen.g4
Protogen.g4
grammar Protogen; ATTR : 'auth' | 'unauth' | 'admin' | 'global' | 'map' ; NEWTYPE : 'newtype' ; CATEGORY : 'category' ; INCLUDE : 'include' ; METHOD : 'method' ; PRIM : 'i8' | 'u8' | 'i16' | 'u16' | 'i32' | 'u32' | 'f32' | 'i64' | 'u64' | 'f64' | 'array' '<' IDENT '>' ; SEMI : ';' ; LBRACE : '{' ; RBRACE : '}' ; COMMA : ',' ; EQ : '=' ; IN : 'in' ; OUT : 'out' ; STRING : '"' ~["]* '"' ; IDENT : [a-zA-Z_][a-zA-Z_0-9]* ; WS : [ \t]+ -> skip; NL : '\n' | '\r\n' ; EXTRA : . ; newtype : NEWTYPE IDENT EQ (PRIM SEMI | object) ; category : CATEGORY IDENT LBRACE NL? (include | method)* RBRACE NL? ; include : INCLUDE STRING SEMI NL? ; property : (IN | OUT) '=' (object | PRIM) SEMI NL ?; comment : .*? NL ; method : METHOD IDENT LBRACE ATTR* RBRACE LBRACE NL? comment* property* RBRACE NL ?; object : LBRACE NL? (field COMMA NL?)* (field COMMA? NL?)? NL? RBRACE ; field : IDENT ':' IDENT ; prog : (newtype | category | NL)* ;
grammar Protogen; ATTR : 'auth' | 'unauth' | 'admin' | 'global' | 'map' ; NEWTYPE : 'newtype' ; CATEGORY : 'category' ; INCLUDE : 'include' ; METHOD : 'method' ; PRIM : 'i8' | 'u8' | 'i16' | 'u16' | 'i32' | 'u32' | 'f32' | 'i64' | 'u64' | 'f64' | 'array' '<' IDENT '>' ; SEMI : ';' ; LBRACE : '{' ; RBRACE : '}' ; COMMA : ',' ; EQ : '=' ; IN : 'in' ; OUT : 'out' ; STRING : '"' ~["]* '"' ; IDENT : [a-zA-Z_][a-zA-Z_0-9]* ; WS : [ \t]+ -> skip; NL : '\n' | '\r\n' ; EXTRA : . ; newtype : NEWTYPE IDENT EQ (PRIM SEMI | object) ; category : CATEGORY IDENT LBRACE NL? (include | method)* RBRACE NL? ; include : INCLUDE STRING SEMI NL? ; property : (IN | OUT) '=' (object | PRIM) SEMI NL ?; comment : .*? NL ; method : METHOD IDENT LBRACE ATTR* RBRACE LBRACE NL? comment* property* RBRACE NL ?; object : LBRACE NL? (field COMMA NL?)* (field COMMA? NL?)? NL? RBRACE ; field : IDENT ':' IDENT ; protocol : (newtype | category | NL)* ;
Rename prog nonterminal to protocol
Rename prog nonterminal to protocol
ANTLR
mit
cmr/Protogen,arke-industries/Protogen
8a2b7a38fab20a2e1065307ac32c00cb0e5fb3aa
src/queryparser/postgresql/PostgreSQLParser.g4
src/queryparser/postgresql/PostgreSQLParser.g4
parser grammar PostgreSQLParser; options { tokenVocab = PostgreSQLLexer; } ////////////////////////////////////////////////////////////////////////////// relational_op: EQ | LTH | GTH | NOT_EQ | LET | GET; cast_data_type: BINARY (LPAREN INTEGER_NUM RPAREN)? | CHAR (LPAREN INTEGER_NUM RPAREN)? | DATE_SYM | DATETIME | TIME_SYM | TIMESTAMP | INTERVAL_SYM | DECIMAL_SYM (LPAREN INTEGER_NUM (COMMA INTEGER_NUM)? RPAREN)? | INTEGER_SYM | BIGINT | FLOAT | REAL | DOUBLE_PRECISION_SYM; interval_unit: SECOND | MINUTE | HOUR | DAY_SYM | 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 ; //transcoding_name: // LATIN1 | UTF8 ; ////////////////////////////////////////////////////////////////////////////// // LITERALS bit_literal: BIT_NUM ; boolean_literal: TRUE_SYM | FALSE_SYM ; hex_literal: HEX_DIGIT ; number_literal: ( PLUS | MINUS )? ( INTEGER_NUM | REAL_NUMBER ) ; string_literal: TEXT_STRING ; ////////////////////////////////////////////////////////////////////////////// // FUNCTIONS char_functions: ASCII_SYM | BIT_LENGTH | CHAR_LENGTH | CHR | CONCAT_WS | CONCAT | LEFT | LENGTH | LOWER | LPAD | LTRIM | REPEAT | REPLACE | REVERSE | RIGHT | RPAD | RTRIM | SUBSTRING | TRIM | UPPER ; group_functions: AVG | COUNT | MAX_SYM | MIN_SYM | SUM | BIT_AND | BIT_OR | BIT_XOR | BIT_COUNT | STDDEV | STDDEV_POP | STDDEV_SAMP | VAR_POP | VAR_SAMP | VARIANCE ; number_functions: ABS | ACOS | ASIN | ATAN2 | ATAN | CBRT | CEIL | CEILING | COS | COT | DEGREES | DIV | EXP | FLOOR | LN | LOG | MOD | PI | POW | POWER | RADIANS | RANDOM | ROUND | SIGN | SIN | SQRT | TAN | TRUNCATE | GREATEST ; other_functions: ENCODE | MD5 | VALUES ; time_functions: CONVERT_TZ | CURDATE | CURTIME | DATE_ADD | DATE_FORMAT | DATE_PART | DATE_SYM | DAYNAME | DAYOFMONTH | DAYOFWEEK | DAYOFYEAR | EXTRACT | FROM_DAYS | FROM_UNIXTIME | GET_FORMAT | HOUR | LAST_DAY | MAKEDATE | MAKETIME | MICROSECOND | MINUTE | MONTH | MONTHNAME | NOW | PERIOD_ADD | PERIOD_DIFF | QUARTER | SEC_TO_TIME | SECOND | STR_TO_DATE | SUBTIME | SYSDATE | TIME_FORMAT | TIME_TO_SEC | TIME_SYM | TIMEDIFF | TIMESTAMP | TIMESTAMPADD | TIMESTAMPDIFF | TO_DAYS | TO_SECONDS | UNIX_TIMESTAMP | UTC_DATE | UTC_TIME | UTC_TIMESTAMP | WEEK | WEEKDAY | WEEKOFYEAR | YEAR | YEARWEEK ; array_functions: ARRAY_LENGTH ; pg_sphere_functions: AREA ; functionList: number_functions | char_functions | time_functions | other_functions | pg_sphere_functions | array_functions ; literal_value: string_literal | number_literal | hex_literal | boolean_literal | bit_literal | NULL_SYM ; ////////////////////////////////////////////////////////////////////////////// // MAIN select_expression: SELECT ( ALL | DISTINCT )? select_list ( FROM table_references ( partition_clause )? ( where_clause )? ( groupby_clause )? ( having_clause )? ) ? ( orderby_clause )? ( limit_clause )? ( offset_clause )? ( FOR_SYM UPDATE )? SEMI? ; ////////////////////////////////////////////////////////////////////////////// // TOKENS alias: ( AS_SYM )? ID ; bit_expr: factor1 ( VERTBAR factor1 )? ; bool_primary: predicate ( relational_op ( ANY )? predicate )? | ( ( NOT_SYM )? EXISTS subquery); case_when_statement: CASE_SYM ( case_when_statement1 | case_when_statement2 ) ( ELSE_SYM bit_expr )? END_SYM; case_when_statement1: ( WHEN_SYM expression THEN_SYM bit_expr )+ ; case_when_statement2: bit_expr ( WHEN_SYM bit_expr THEN_SYM bit_expr )+ ; column_list: LPAREN column_spec ( COMMA column_spec )* RPAREN ; column_name: ID; column_spec: ( ( schema_name DOT )? table_name DOT )? column_name ( slice_spec )?; displayed_column : ( table_spec DOT ASTERISK ) | ( ( bit_expr | sbit_expr ) ( LIKE_SYM TEXT_STRING )? ( alias )? ) ; exp_factor1: exp_factor2 ( AND_SYM exp_factor2 )* ; exp_factor2: ( NOT_SYM )? exp_factor3 ; exp_factor3: bool_primary ( ( IS_SYM ( NOT_SYM )? (boolean_literal | NULL_SYM | ( DISTINCT FROM ) ) )? | ( ISNULL | NOTNULL )? ); expression: ( exp_factor1 ( OR_SYM exp_factor1 )* ) ; expression_list: LPAREN expression ( COMMA expression )* RPAREN ; factor1: factor2 ( BITAND factor2 )? ; factor2: factor3 ( ( SHIFT_LEFT | SHIFT_RIGHT ) factor3 )? ; factor3: factor4 ( ( PLUS | MINUS ) factor4 )* ; factor4: factor5 ( ( ASTERISK | DIVIDE | MOD_SYM | POWER_OP) factor5 )* ; factor5: ( PLUS | MINUS | NEGATION | BINARY | ABS_VAL_OR_SCONTAINS | DFACTORIAL )? simple_expr ( NOT_SYM )? ( ( PLUS | MINUS ) interval_expr )? ; function_call: ( functionList ( LPAREN ( expression ( COMMA expression )* )? RPAREN ) ? ) | ( CAST_SYM LPAREN expression AS_SYM cast_data_type RPAREN ) | ( CONVERT_SYM LPAREN TEXT_STRING COMMA TEXT_STRING COMMA TEXT_STRING RPAREN ) | ( POSITION_SYM LPAREN expression IN_SYM expression RPAREN ) | ( group_functions LPAREN ( ASTERISK | ALL | DISTINCT )? ( ( bit_expr | sbit_expr ) )? RPAREN ) ; groupby_clause: GROUP_SYM BY_SYM groupby_item ( COMMA groupby_item )* ( WITH ROLLUP_SYM )? ; groupby_item: (column_spec | INTEGER_NUM | bit_expr ) ( ASC | DESC )?; having_clause: HAVING expression ; index_hint: USE_SYM index_options LPAREN ( index_list )? RPAREN | IGNORE_SYM index_options LPAREN index_list RPAREN | FORCE_SYM index_options LPAREN index_list RPAREN ; index_hint_list: index_hint ( COMMA index_hint )* ; index_name: ID ; index_list: index_name ( COMMA index_name )* ; index_options: ( INDEX_SYM | KEY_SYM ) ( FOR_SYM (( JOIN_SYM ) | ( ORDER_SYM BY_SYM ) | ( GROUP_SYM BY_SYM )) )? ; interval_expr: INTERVAL_SYM expression interval_unit ; join_condition: ( ON expression ) | ( USING_SYM column_list ) ; limit_clause: LIMIT (( offset COMMA )? row_count) | ( row_count OFFSET_SYM offset ) ; offset: INTEGER_NUM ; offset_clause: OFFSET_SYM offset ; row_count: INTEGER_NUM ; orderby_clause: ORDER_SYM BY_SYM orderby_item ( COMMA orderby_item )* ; orderby_item: groupby_item ( ( ASC | DESC )? | ( NULLS_SYM ( FIRST_SYM | LAST_SYM ) )? ) | groupby_item USING_SYM ( GTH | LTH ); partition_clause: PARTITION_SYM LPAREN partition_names RPAREN ; partition_name: ID ; partition_names: partition_name ( COMMA partition_name )* ; bit_fac1: ( NOT_SYM )? ( (IN_SYM ( subquery | expression_list )) | (LIKE_SYM simple_expr ( ESCAPE_SYM simple_expr )?) | (REGEXP ( bit_expr | sbit_expr )) | (BETWEEN ( SYMMETRIC )? ( bit_expr | sbit_expr ) AND_SYM predicate) ) ; bit_fac2: SOUNDS_SYM LIKE_SYM ( bit_expr | sbit_expr ); predicate: ( bit_expr | sbit_expr ) (( bit_fac1 | bit_fac2)?) ; query: select_statement SEMI; schema_name: ID ; select_list: ( displayed_column ( COMMA displayed_column )* ) | ( ASTERISK ( COMMA displayed_column ( COMMA displayed_column )* )? ) ; select_statement: select_expression ( (UNION_SYM ( ALL )? ) select_expression )* ; simple_expr: literal_value | expression_list | column_spec | function_call //| USER_VAR | (ROW_SYM expression_list) | subquery | EXISTS subquery | interval_expr | case_when_statement ; slice_spec: ( LBRACK INTEGER_NUM ( COLON INTEGER_NUM )? RBRACK )+; subquery: LPAREN select_statement RPAREN ; table_atom: ( table_spec ( partition_clause )? ( alias )? ( index_hint_list )? ) | ( subquery alias ) | ( LPAREN table_references RPAREN ) | ( OJ_SYM table_reference LEFT OUTER JOIN_SYM table_reference ON expression ) ; table_name: ID ; table_factor1: table_factor2 ( (INNER_SYM | CROSS | LEFT | RIGHT)? JOIN_SYM table_atom ( join_condition )? )* ; table_factor2: table_factor3 ( STRAIGHT_JOIN table_atom ( ON expression )? )? ; table_factor3: table_factor4 ( ( LEFT | RIGHT ) ( OUTER )? JOIN_SYM table_factor4 join_condition )* ; table_factor4: table_atom ( NATURAL ( ( LEFT | RIGHT ) ( OUTER )? )? JOIN_SYM table_atom )? ; table_reference: table_factor1 | ( LPAREN values_list RPAREN ) alias ( column_list )? ; table_references: table_reference ( COMMA table_reference )* ; table_spec: ( schema_name DOT )? table_name ; values_list: VALUES ( expression_list ( COMMA expression_list )* ); where_clause: WHERE expression ; pg_sphere_op: ABS_VAL_OR_SCONTAINS | SCONTAINS2 | NEGATION | SLEFTCONTAINS2 | SNOTCONTAINS | SNOTCONTAINS2 | SLEFTNOTCONTAINS | SLEFTNOTCONTAINS2 | AND_SYM | SNOTOVERLAP ; sbit_expr: ( pg_sphere_object | spoint ) | ( ( spoint | simple_expr ) pg_sphere_op pg_sphere_object) | ( pg_sphere_object EQ pg_sphere_object ) | ( pg_sphere_object pg_sphere_op pg_sphere_object ) | ( sline | simple_expr SCROSS sline | simple_expr ) | ( ( spoint | scircle | simple_expr ) SDISTANCE ( spoint | scircle | simple_expr ) ) | ( SLENGTH ( scircle | sbox | spoly | simple_expr ) ) | ( SCENTER ( scircle | sellipse | simple_expr ) ) | ( MINUS ( sline | spath | simple_expr ) ) | ( ( spoint | scircle | sline | sellipse | spoly | spath | simple_expr )? ( ( PLUS | MINUS )? strans )+ ) ; spoint: SPOINT LPAREN bit_expr COMMA bit_expr RPAREN ; scircle: SCIRCLE LPAREN spoint COMMA bit_expr RPAREN ; sline: ( SLINE LPAREN spoint COMMA spoint RPAREN ) | ( SLINE LPAREN strans COMMA bit_expr RPAREN ); sellipse: SELLIPSE LPAREN spoint COMMA bit_expr COMMA bit_expr COMMA bit_expr RPAREN ; sbox: SBOX LPAREN spoint COMMA spoint RPAREN ; spoly: SPOLY TEXT_STRING| SPOLY LPAREN column_spec RPAREN | SPOLY LPAREN TEXT_STRING RPAREN; spath: SPATH TEXT_STRING | SPATH LPAREN column_spec RPAREN ; strans: STRANS LPAREN bit_expr COMMA bit_expr COMMA bit_expr COMMA TRANS RPAREN ; pg_sphere_object: scircle | sline | sellipse | sbox | spoly | spath | simple_expr;
parser grammar PostgreSQLParser; options { tokenVocab = PostgreSQLLexer; } ////////////////////////////////////////////////////////////////////////////// relational_op: EQ | LTH | GTH | NOT_EQ | LET | GET; cast_data_type: BINARY (LPAREN INTEGER_NUM RPAREN)? | CHAR (LPAREN INTEGER_NUM RPAREN)? | DATE_SYM | DATETIME | TIME_SYM | TIMESTAMP | INTERVAL_SYM | DECIMAL_SYM (LPAREN INTEGER_NUM (COMMA INTEGER_NUM)? RPAREN)? | INTEGER_SYM | BIGINT | FLOAT | REAL | DOUBLE_PRECISION_SYM; interval_unit: SECOND | MINUTE | HOUR | DAY_SYM | 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 ; //transcoding_name: // LATIN1 | UTF8 ; ////////////////////////////////////////////////////////////////////////////// // LITERALS bit_literal: BIT_NUM ; boolean_literal: TRUE_SYM | FALSE_SYM ; hex_literal: HEX_DIGIT ; number_literal: ( PLUS | MINUS )? ( INTEGER_NUM | REAL_NUMBER ) ; string_literal: TEXT_STRING ; ////////////////////////////////////////////////////////////////////////////// // FUNCTIONS char_functions: ASCII_SYM | BIT_LENGTH | CHAR_LENGTH | CHR | CONCAT_WS | CONCAT | LEFT | LENGTH | LOWER | LPAD | LTRIM | REPEAT | REPLACE | REVERSE | RIGHT | RPAD | RTRIM | SUBSTRING | TRIM | UPPER ; group_functions: AVG | COUNT | MAX_SYM | MIN_SYM | SUM | BIT_AND | BIT_OR | BIT_XOR | BIT_COUNT | STDDEV | STDDEV_POP | STDDEV_SAMP | VAR_POP | VAR_SAMP | VARIANCE ; number_functions: ABS | ACOS | ASIN | ATAN2 | ATAN | CBRT | CEIL | CEILING | COS | COT | DEGREES | DIV | EXP | FLOOR | LN | LOG | MOD | PI | POW | POWER | RADIANS | RANDOM | ROUND | SIGN | SIN | SQRT | TAN | TRUNCATE | GREATEST ; other_functions: ENCODE | MD5 | VALUES ; time_functions: CONVERT_TZ | CURDATE | CURTIME | DATE_ADD | DATE_FORMAT | DATE_PART | DATE_SYM | DAYNAME | DAYOFMONTH | DAYOFWEEK | DAYOFYEAR | EXTRACT | FROM_DAYS | FROM_UNIXTIME | GET_FORMAT | HOUR | LAST_DAY | MAKEDATE | MAKETIME | MICROSECOND | MINUTE | MONTH | MONTHNAME | NOW | PERIOD_ADD | PERIOD_DIFF | QUARTER | SEC_TO_TIME | SECOND | STR_TO_DATE | SUBTIME | SYSDATE | TIME_FORMAT | TIME_TO_SEC | TIME_SYM | TIMEDIFF | TIMESTAMP | TIMESTAMPADD | TIMESTAMPDIFF | TO_DAYS | TO_SECONDS | UNIX_TIMESTAMP | UTC_DATE | UTC_TIME | UTC_TIMESTAMP | WEEK | WEEKDAY | WEEKOFYEAR | YEAR | YEARWEEK ; array_functions: ARRAY_LENGTH ; pg_sphere_functions: AREA ; functionList: number_functions | char_functions | time_functions | other_functions | pg_sphere_functions | array_functions ; literal_value: string_literal | number_literal | hex_literal | boolean_literal | bit_literal | NULL_SYM ; ////////////////////////////////////////////////////////////////////////////// // MAIN select_expression: SELECT ( ALL | DISTINCT )? select_list ( FROM table_references ( partition_clause )? ( where_clause )? ( groupby_clause )? ( having_clause )? ) ? ( orderby_clause )? ( limit_clause )? ( offset_clause )? ( FOR_SYM UPDATE )? SEMI? ; ////////////////////////////////////////////////////////////////////////////// // TOKENS alias: ( AS_SYM )? ID ; bit_expr: factor1 ( VERTBAR factor1 )? ; bool_primary: predicate ( relational_op ( ANY )? predicate )? | ( ( NOT_SYM )? EXISTS subquery); case_when_statement: CASE_SYM ( case_when_statement1 | case_when_statement2 ) ( ELSE_SYM bit_expr )? END_SYM; case_when_statement1: ( WHEN_SYM expression THEN_SYM bit_expr )+ ; case_when_statement2: bit_expr ( WHEN_SYM bit_expr THEN_SYM bit_expr )+ ; column_list: LPAREN column_spec ( COMMA column_spec )* RPAREN ; column_name: ID; column_spec: ( ( schema_name DOT )? table_name DOT )? column_name ( slice_spec )?; displayed_column : ( table_spec DOT ASTERISK ) | ( ( bit_expr | sbit_expr ) ( LIKE_SYM TEXT_STRING )? ( alias )? ) ; exp_factor1: exp_factor2 ( AND_SYM exp_factor2 )* ; exp_factor2: ( NOT_SYM )? exp_factor3 ; exp_factor3: bool_primary ( ( IS_SYM ( NOT_SYM )? (boolean_literal | NULL_SYM | ( DISTINCT FROM ) ) )? | ( ISNULL | NOTNULL )? ); expression: ( exp_factor1 ( OR_SYM exp_factor1 )* ) ; expression_list: LPAREN expression ( COMMA expression )* RPAREN ; factor1: factor2 ( BITAND factor2 )? ; factor2: factor3 ( ( SHIFT_LEFT | SHIFT_RIGHT ) factor3 )? ; factor3: factor4 ( ( PLUS | MINUS ) factor4 )* ; factor4: factor5 ( ( ASTERISK | DIVIDE | MOD_SYM | POWER_OP) factor5 )* ; factor5: ( PLUS | MINUS | NEGATION | BINARY | ABS_VAL_OR_SCONTAINS | DFACTORIAL )? simple_expr ( NOT_SYM )? ( ( PLUS | MINUS ) interval_expr )? ; function_call: ( functionList ( LPAREN ( expression ( COMMA expression )* )? RPAREN ) ? ) | ( CAST_SYM LPAREN expression AS_SYM cast_data_type RPAREN ) | ( CONVERT_SYM LPAREN TEXT_STRING COMMA TEXT_STRING COMMA TEXT_STRING RPAREN ) | ( POSITION_SYM LPAREN expression IN_SYM expression RPAREN ) | ( group_functions LPAREN ( ASTERISK | ALL | DISTINCT )? ( ( bit_expr | sbit_expr ) )? RPAREN ) ; groupby_clause: GROUP_SYM BY_SYM groupby_item ( COMMA groupby_item )* ( WITH ROLLUP_SYM )? ; groupby_item: (column_spec | INTEGER_NUM | bit_expr ) ( ASC | DESC )?; having_clause: HAVING expression ; index_hint: USE_SYM index_options LPAREN ( index_list )? RPAREN | IGNORE_SYM index_options LPAREN index_list RPAREN | FORCE_SYM index_options LPAREN index_list RPAREN ; index_hint_list: index_hint ( COMMA index_hint )* ; index_name: ID ; index_list: index_name ( COMMA index_name )* ; index_options: ( INDEX_SYM | KEY_SYM ) ( FOR_SYM (( JOIN_SYM ) | ( ORDER_SYM BY_SYM ) | ( GROUP_SYM BY_SYM )) )? ; interval_expr: INTERVAL_SYM expression interval_unit ; join_condition: ( ON expression ) | ( USING_SYM column_list ) ; limit_clause: ( LIMIT row_count ( OFFSET_SYM offset )? ) | ( OFFSET_SYM offset LIMIT row_count ); offset: INTEGER_NUM ; offset_clause: OFFSET_SYM offset ; row_count: INTEGER_NUM ; orderby_clause: ORDER_SYM BY_SYM orderby_item ( COMMA orderby_item )* ; orderby_item: groupby_item ( ( ASC | DESC )? | ( NULLS_SYM ( FIRST_SYM | LAST_SYM ) )? ) | groupby_item USING_SYM ( GTH | LTH ); partition_clause: PARTITION_SYM LPAREN partition_names RPAREN ; partition_name: ID ; partition_names: partition_name ( COMMA partition_name )* ; bit_fac1: ( NOT_SYM )? ( (IN_SYM ( subquery | expression_list )) | (LIKE_SYM simple_expr ( ESCAPE_SYM simple_expr )?) | (REGEXP ( bit_expr | sbit_expr )) | (BETWEEN ( SYMMETRIC )? ( bit_expr | sbit_expr ) AND_SYM predicate) ) ; bit_fac2: SOUNDS_SYM LIKE_SYM ( bit_expr | sbit_expr ); predicate: ( bit_expr | sbit_expr ) (( bit_fac1 | bit_fac2)?) ; query: select_statement SEMI; schema_name: ID ; select_list: ( displayed_column ( COMMA displayed_column )* ) | ( ASTERISK ( COMMA displayed_column ( COMMA displayed_column )* )? ) ; select_statement: select_expression ( (UNION_SYM ( ALL )? ) select_expression )* ; simple_expr: literal_value | expression_list | column_spec | function_call //| USER_VAR | (ROW_SYM expression_list) | subquery | EXISTS subquery | interval_expr | case_when_statement ; slice_spec: ( LBRACK INTEGER_NUM ( COLON INTEGER_NUM )? RBRACK )+; subquery: LPAREN select_statement RPAREN ; table_atom: ( table_spec ( partition_clause )? ( alias )? ( index_hint_list )? ) | ( subquery alias ) | ( LPAREN table_references RPAREN ) | ( OJ_SYM table_reference LEFT OUTER JOIN_SYM table_reference ON expression ) ; table_name: ID ; table_factor1: table_factor2 ( (INNER_SYM | CROSS | LEFT | RIGHT)? JOIN_SYM table_atom ( join_condition )? )* ; table_factor2: table_factor3 ( STRAIGHT_JOIN table_atom ( ON expression )? )? ; table_factor3: table_factor4 ( ( LEFT | RIGHT ) ( OUTER )? JOIN_SYM table_factor4 join_condition )* ; table_factor4: table_atom ( NATURAL ( ( LEFT | RIGHT ) ( OUTER )? )? JOIN_SYM table_atom )? ; table_reference: table_factor1 | ( LPAREN values_list RPAREN ) alias ( column_list )? ; table_references: table_reference ( COMMA table_reference )* ; table_spec: ( schema_name DOT )? table_name ; values_list: VALUES ( expression_list ( COMMA expression_list )* ); where_clause: WHERE expression ; pg_sphere_op: ABS_VAL_OR_SCONTAINS | SCONTAINS2 | NEGATION | SLEFTCONTAINS2 | SNOTCONTAINS | SNOTCONTAINS2 | SLEFTNOTCONTAINS | SLEFTNOTCONTAINS2 | AND_SYM | SNOTOVERLAP ; sbit_expr: ( pg_sphere_object | spoint ) | ( ( spoint | simple_expr ) pg_sphere_op pg_sphere_object) | ( pg_sphere_object EQ pg_sphere_object ) | ( pg_sphere_object pg_sphere_op pg_sphere_object ) | ( sline | simple_expr SCROSS sline | simple_expr ) | ( ( spoint | scircle | simple_expr ) SDISTANCE ( spoint | scircle | simple_expr ) ) | ( SLENGTH ( scircle | sbox | spoly | simple_expr ) ) | ( SCENTER ( scircle | sellipse | simple_expr ) ) | ( MINUS ( sline | spath | simple_expr ) ) | ( ( spoint | scircle | sline | sellipse | spoly | spath | simple_expr )? ( ( PLUS | MINUS )? strans )+ ) ; spoint: SPOINT LPAREN bit_expr COMMA bit_expr RPAREN ; scircle: SCIRCLE LPAREN spoint COMMA bit_expr RPAREN ; sline: ( SLINE LPAREN spoint COMMA spoint RPAREN ) | ( SLINE LPAREN strans COMMA bit_expr RPAREN ); sellipse: SELLIPSE LPAREN spoint COMMA bit_expr COMMA bit_expr COMMA bit_expr RPAREN ; sbox: SBOX LPAREN spoint COMMA spoint RPAREN ; spoly: SPOLY TEXT_STRING| SPOLY LPAREN column_spec RPAREN | SPOLY LPAREN TEXT_STRING RPAREN; spath: SPATH TEXT_STRING | SPATH LPAREN column_spec RPAREN ; strans: STRANS LPAREN bit_expr COMMA bit_expr COMMA bit_expr COMMA TRANS RPAREN ; pg_sphere_object: scircle | sline | sellipse | sbox | spoly | spath | simple_expr;
Fix OFFSET postgres bug
Fix OFFSET postgres bug
ANTLR
apache-2.0
aipescience/queryparser
e79d5a8a0c5290edc468c826b2f5b241a914bb57
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'; // // Operators // 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) { 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 (); } ;
Remove extraneous comment.
Remove extraneous comment.
ANTLR
mit
Collap/bryg
9d7bb7f3d23ac86e73aadbe89743d6285ae07c4d
prolog.g4
prolog.g4
/* BSD License Copyright (c) 2013, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar prolog; // Prolog text and data formed from terms (6.2) p_text: (directive | clause) * EOF ; directive: ':-' term '.' ; // also 3.58 clause: term '.' ; // also 3.33 // Abstract Syntax (6.3): terms formed from tokens termlist : term ( ',' term )* ; term : VARIABLE # variable | '(' term ')' # braced_term | '-'? integer # integer_term | '-'? FLOAT # float // structure / compound term | atom '(' termlist ')' # compound_term |<assoc=right> term operator term # binary_operator | operator term # unary_operator | '[' termlist ( '|' term )? ']' # list_term //TODO: find out what [|] list syntax means | '{' termlist '}' # curly_bracketed_term | atom # atom_term ; //TODO: operator priority, associativity, arity. valid priority ranges for e.g. [list] syntax //TODO: modifying operator table operator : ':-' | '-->' | '?-' | 'dynamic' | 'multifile' | 'discontiguous' | 'public' | ';' | '->' | ',' | '\\+' | '=' | '\\=' | '==' | '\\==' | '@<' | '@=<' | '@>' | '@>=' | '=..' | 'is' | '=:=' | '=\\=' | '<' | '=<' | '>' | '>=' | '+' | '-' | '/\\' | '\\/' | '*' | '/' | '//' | 'rem' | 'mod' | '<<' | '>>' //TODO: '/' cannot be used as atom because token here not in GRAPHIC. only works because , is operator too. example: swipl/filesex.pl:177 | '**' | '^' | '\\' ; atom // 6.4.2 and 6.1.2 : '[' ']' # empty_list | '{' '}' # empty_braces | LETTER_DIGIT # name | GRAPHIC_TOKEN # graphic | QUOTED # quoted_string | DOUBLE_QUOTED_LIST# dq_string | BACK_QUOTED_STRING# backq_string | ';' # semicolon | '!' # cut ; integer // 6.4.4 : DECIMAL | CHARACTER_CODE_CONSTANT | BINARY | OCTAL | HEX ; // Lexer (6.4 & 6.5): Tokens formed from Characters LETTER_DIGIT // 6.4.2 : SMALL_LETTER ALPHANUMERIC* ; VARIABLE // 6.4.3 : CAPITAL_LETTER ALPHANUMERIC* | '_' ALPHANUMERIC+ | '_' ; // 6.4.4 DECIMAL: DIGIT+ ; BINARY: '0b' [01]+ ; OCTAL: '0o' [0-7]+ ; HEX: '0x' HEX_DIGIT+ ; CHARACTER_CODE_CONSTANT: '0' '\'' SINGLE_QUOTED_CHARACTER ; FLOAT: DECIMAL '.' [0-9]+ ( [eE] [+-] DECIMAL )? ; GRAPHIC_TOKEN: (GRAPHIC | '\\')+ ; // 6.4.2 fragment GRAPHIC: [#$&*+./:<=>?@^~] | '-' ; // 6.5.1 graphic char // 6.4.2.1 fragment SINGLE_QUOTED_CHARACTER: NON_QUOTE_CHAR | '\'\'' | '"' | '`' ; fragment DOUBLE_QUOTED_CHARACTER: NON_QUOTE_CHAR | '\'' | '""' | '`' ; fragment BACK_QUOTED_CHARACTER: NON_QUOTE_CHAR | '\'' | '"' | '``' ; fragment NON_QUOTE_CHAR : GRAPHIC | ALPHANUMERIC | SOLO | ' ' // space char | META_ESCAPE | CONTROL_ESCAPE | OCTAL_ESCAPE | HEX_ESCAPE ; META_ESCAPE: '\\' [\\'"`] ; // meta char CONTROL_ESCAPE: '\\' [abrftnv] ; OCTAL_ESCAPE: '\\' [0-7]+ '\\' ; HEX_ESCAPE: '\\x' HEX_DIGIT+ '\\' ; QUOTED: '\'' (CONTINUATION_ESCAPE | SINGLE_QUOTED_CHARACTER )*? '\'' ; // 6.4.2 DOUBLE_QUOTED_LIST: '"' (CONTINUATION_ESCAPE | DOUBLE_QUOTED_CHARACTER )*? '"'; // 6.4.6 BACK_QUOTED_STRING: '`' (CONTINUATION_ESCAPE | BACK_QUOTED_CHARACTER )*? '`'; // 6.4.7 fragment CONTINUATION_ESCAPE: '\\\n' ; // 6.5.2 fragment ALPHANUMERIC: ALPHA | DIGIT ; fragment ALPHA: '_' | SMALL_LETTER | CAPITAL_LETTER ; fragment SMALL_LETTER: [a-z_]; fragment CAPITAL_LETTER: [A-Z]; fragment DIGIT: [0-9] ; fragment HEX_DIGIT: [0-9a-fA-F] ; // 6.5.3 fragment SOLO: [!(),;[{}|%] | ']' ; WS : [ \t\r\n]+ -> skip ; COMMENT: '%' ~[\n\r]* ( [\n\r] | EOF) -> channel(HIDDEN) ; MULTILINE_COMMENT: '/*' ( MULTILINE_COMMENT | . )*? ('*/' | EOF) -> channel(HIDDEN);
/* BSD License Copyright (c) 2013, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar prolog; // Prolog text and data formed from terms (6.2) p_text: (directive | clause) * EOF ; directive: ':-' term '.' ; // also 3.58 clause: term '.' ; // also 3.33 // Abstract Syntax (6.3): terms formed from tokens termlist : term ( ',' term )* ; term : VARIABLE # variable | '(' term ')' # braced_term | '-'? integer # integer_term | '-'? FLOAT # float // structure / compound term | atom '(' termlist ')' # compound_term |<assoc=right> term operator term # binary_operator | operator term # unary_operator | '[' termlist ( '|' term )? ']' # list_term //TODO: find out what [|] list syntax means | '{' termlist '}' # curly_bracketed_term | atom # atom_term ; //TODO: operator priority, associativity, arity. valid priority ranges for e.g. [list] syntax //TODO: modifying operator table operator : ':-' | '-->' | '?-' | 'dynamic' | 'multifile' | 'discontiguous' | 'public' | ';' | '->' | ',' | '\\+' | '=' | '\\=' | '==' | '\\==' | '@<' | '@=<' | '@>' | '@>=' | '=..' | 'is' | '=:=' | '=\\=' | '<' | '=<' | '>' | '>=' | ':' // modules: 5.2.1 | '+' | '-' | '/\\' | '\\/' | '*' | '/' | '//' | 'rem' | 'mod' | '<<' | '>>' //TODO: '/' cannot be used as atom because token here not in GRAPHIC. only works because , is operator too. example: swipl/filesex.pl:177 | '**' | '^' | '\\' ; atom // 6.4.2 and 6.1.2 : '[' ']' # empty_list | '{' '}' # empty_braces | LETTER_DIGIT # name | GRAPHIC_TOKEN # graphic | QUOTED # quoted_string | DOUBLE_QUOTED_LIST# dq_string | BACK_QUOTED_STRING# backq_string | ';' # semicolon | '!' # cut ; integer // 6.4.4 : DECIMAL | CHARACTER_CODE_CONSTANT | BINARY | OCTAL | HEX ; // Lexer (6.4 & 6.5): Tokens formed from Characters LETTER_DIGIT // 6.4.2 : SMALL_LETTER ALPHANUMERIC* ; VARIABLE // 6.4.3 : CAPITAL_LETTER ALPHANUMERIC* | '_' ALPHANUMERIC+ | '_' ; // 6.4.4 DECIMAL: DIGIT+ ; BINARY: '0b' [01]+ ; OCTAL: '0o' [0-7]+ ; HEX: '0x' HEX_DIGIT+ ; CHARACTER_CODE_CONSTANT: '0' '\'' SINGLE_QUOTED_CHARACTER ; FLOAT: DECIMAL '.' [0-9]+ ( [eE] [+-] DECIMAL )? ; GRAPHIC_TOKEN: (GRAPHIC | '\\')+ ; // 6.4.2 fragment GRAPHIC: [#$&*+./:<=>?@^~] | '-' ; // 6.5.1 graphic char // 6.4.2.1 fragment SINGLE_QUOTED_CHARACTER: NON_QUOTE_CHAR | '\'\'' | '"' | '`' ; fragment DOUBLE_QUOTED_CHARACTER: NON_QUOTE_CHAR | '\'' | '""' | '`' ; fragment BACK_QUOTED_CHARACTER: NON_QUOTE_CHAR | '\'' | '"' | '``' ; fragment NON_QUOTE_CHAR : GRAPHIC | ALPHANUMERIC | SOLO | ' ' // space char | META_ESCAPE | CONTROL_ESCAPE | OCTAL_ESCAPE | HEX_ESCAPE ; META_ESCAPE: '\\' [\\'"`] ; // meta char CONTROL_ESCAPE: '\\' [abrftnv] ; OCTAL_ESCAPE: '\\' [0-7]+ '\\' ; HEX_ESCAPE: '\\x' HEX_DIGIT+ '\\' ; QUOTED: '\'' (CONTINUATION_ESCAPE | SINGLE_QUOTED_CHARACTER )*? '\'' ; // 6.4.2 DOUBLE_QUOTED_LIST: '"' (CONTINUATION_ESCAPE | DOUBLE_QUOTED_CHARACTER )*? '"'; // 6.4.6 BACK_QUOTED_STRING: '`' (CONTINUATION_ESCAPE | BACK_QUOTED_CHARACTER )*? '`'; // 6.4.7 fragment CONTINUATION_ESCAPE: '\\\n' ; // 6.5.2 fragment ALPHANUMERIC: ALPHA | DIGIT ; fragment ALPHA: '_' | SMALL_LETTER | CAPITAL_LETTER ; fragment SMALL_LETTER: [a-z_]; fragment CAPITAL_LETTER: [A-Z]; fragment DIGIT: [0-9] ; fragment HEX_DIGIT: [0-9a-fA-F] ; // 6.5.3 fragment SOLO: [!(),;[{}|%] | ']' ; WS : [ \t\r\n]+ -> skip ; COMMENT: '%' ~[\n\r]* ( [\n\r] | EOF) -> channel(HIDDEN) ; MULTILINE_COMMENT: '/*' ( MULTILINE_COMMENT | . )*? ('*/' | EOF) -> channel(HIDDEN);
implement module operator : (from second ISO standard)
implement module operator : (from second ISO standard)
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
046307485fdf39c0650075a687f55feda80808db
graphene/parser/GQL.g4
graphene/parser/GQL.g4
grammar GQL; @header { from graphene.commands import * from graphene.expressions import * } // General parsing, including statement lists parse : stmt_list EOF; stmt_list returns [stmts] : s1=stmt {$stmts = [$s1.ctx]} (';' (si=stmt {$stmts.append($si.ctx)})? )* ; stmt : ( c=match_stmt | c=create_stmt | c=exit_stmt ) ; // EXIT command exit_stmt returns [cmd] : (K_EXIT | K_QUIT) {$cmd = ExitCommand()} ; // MATCH command match_stmt returns [cmd] @init {$cmd = None} : K_MATCH (nc=node_chain) {$cmd = MatchCommand($nc.ctx)} ; node_chain returns [chain] @init {$chain = []} : (n1=node {$chain.append($n1.ctx)}) (ri=relation {$chain.append($ri.ctx)} ni=node {$chain.append($ni.ctx)})* {return $chain} ; node : '(' (nn=I_NAME ':')? (nt=I_TYPE) ')' {return MatchNode($nn.text, $nt.text)} ; /* * I_RELATION matches all totally uppercase strings, and I_TYPE matches all * strings that start with a capital letter... but if the string is one * character long, this is ambiguous. Hence we allow both identifier * possibilities, but ensure they pass the fully uppercase predicate. */ relation : '-' '[' (rn=I_NAME ':')? (rel=(I_RELATION|I_TYPE) {$rel.text.isupper()}?) ']' '->' {return MatchRelation($rn.text, $rel.text)} ; // CREATE command create_stmt returns [cmd] @init {$cmd = None} : K_CREATE ( ct=create_type | cr=create_relation ) { if $ct.ctx is not None: $cmd = CreateTypeCommand($ct.ctx) else: $cmd = CreateRelationCommand($cr.ctx) } ; create_type : K_TYPE (t=I_TYPE {$t=$t.text}) '(' (tl=type_list) ')' ; type_list returns [tds] : td1=type_decl {$tds = [$td1.ctx]} (',' (tdi=type_decl {$tds.append($tdi.ctx)}))* {return $tds} ; type_decl : (n=I_NAME) ':' (t=( T_INT | T_STR )) {return ($n.text, $t.text)} ; create_relation : K_RELATION (r=(I_RELATION|I_TYPE) {$r.text.isupper()}? {$r=$r.text}) (t1=I_TYPE {$t1=$t1.text}) (t2=I_TYPE {$t2=$t2.text}); // Keywords K_MATCH : M A T C H ; K_CREATE : C R E A T E ; K_TYPE : T Y P E ; K_RELATION : R E L A T I O N ; K_EXIT : E X I T ; K_QUIT : Q U I T ; // Types T_INT : I N T ; T_STR : S T R ; // Identifiers I_NAME : LCASE (LCASE | DIGIT | OTHER_VALID)* ; I_TYPE : UCASE LETTER*; I_RELATION : UCASE+ {self.text.isupper()}?; // Other tokens SPACES : [ \u000B\u000C\t\r\n] -> channel(HIDDEN) ; BLOCK_COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ; fragment OTHER_VALID : [_\-]; fragment DIGIT : [0-9]; fragment LETTER : [A-Za-z]; fragment UCASE : [A-Z]; fragment LCASE : [a-z]; fragment A : [aA]; fragment B : [bB]; fragment C : [cC]; fragment D : [dD]; fragment E : [eE]; fragment F : [fF]; fragment G : [gG]; fragment H : [hH]; fragment I : [iI]; fragment J : [jJ]; fragment K : [kK]; fragment L : [lL]; fragment M : [mM]; fragment N : [nN]; fragment O : [oO]; fragment P : [pP]; fragment Q : [qQ]; fragment R : [rR]; fragment S : [sS]; fragment T : [tT]; fragment U : [uU]; fragment V : [vV]; fragment W : [wW]; fragment X : [xX]; fragment Y : [yY]; fragment Z : [zZ];
grammar GQL; @header { from graphene.commands import * from graphene.expressions import * } // General parsing, including statement lists parse : stmt_list EOF; stmt_list returns [stmts] : s1=stmt {$stmts = [$s1.ctx]} (';' (si=stmt {$stmts.append($si.ctx)})? )* ; stmt : ( c=match_stmt | c=create_stmt | c=exit_stmt ) ; // EXIT command exit_stmt returns [cmd] : (K_EXIT | K_QUIT) {$cmd = ExitCommand()} ; // MATCH command match_stmt returns [cmd] @init {$cmd = None} : K_MATCH (nc=node_chain) {$cmd = MatchCommand($nc.ctx)} ; node_chain returns [chain] @init {$chain = []} : (n1=node {$chain.append($n1.ctx)}) (ri=relation {$chain.append($ri.ctx)} ni=node {$chain.append($ni.ctx)})* {return $chain} ; node : '(' (nn=I_NAME ':')? (nt=I_TYPE) ')' {return MatchNode($nn.text, $nt.text)} ; /* * I_RELATION matches all totally uppercase strings, and I_TYPE matches all * strings that start with a capital letter... but if the string is one * character long, this is ambiguous. Hence we allow both identifier * possibilities, but ensure they pass the fully uppercase predicate. */ relation : '-' '[' (rn=I_NAME ':')? (rel=(I_RELATION|I_TYPE) {$rel.text.isupper()}?) ']' '->' {return MatchRelation($rn.text, $rel.text)} ; // CREATE command create_stmt returns [cmd] @init {$cmd = None} : K_CREATE ( ct=create_type | cr=create_relation ) { if $ct.ctx is not None: $cmd = CreateTypeCommand($ct.ctx) else: $cmd = CreateRelationCommand($cr.ctx) } ; create_type : K_TYPE (t=I_TYPE {$t=$t.text}) '(' (tl=type_list) ')' ; type_list returns [tds] : td1=type_decl {$tds = [$td1.ctx]} (',' (tdi=type_decl {$tds.append($tdi.ctx)}))* {return $tds} ; type_decl : (n=I_NAME) ':' (t=( T_INT | T_STR )) {return ($n.text, $t.text)} ; create_relation : K_RELATION (r=(I_RELATION|I_TYPE) {$r.text.isupper()}? {$r=$r.text}) (t1=I_TYPE {$t1=$t1.text}) (t2=I_TYPE {$t2=$t2.text}); // Keywords K_MATCH : M A T C H ; K_CREATE : C R E A T E ; K_TYPE : T Y P E ; K_RELATION : R E L A T I O N ; K_EXIT : E X I T ; K_QUIT : Q U I T ; // Types T_INT : I N T ; T_STR : S T R ; // Identifiers I_NAME : LCASE (LCASE | DIGIT | OTHER_VALID)* ; I_TYPE : UCASE LETTER*; I_RELATION : UCASE (UCASE | OTHER_VALID)+ {self.text.isupper()}?; // Other tokens SPACES : [ \u000B\u000C\t\r\n] -> channel(HIDDEN) ; BLOCK_COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ; fragment OTHER_VALID : [_\-]; fragment DIGIT : [0-9]; fragment LETTER : [A-Za-z]; fragment UCASE : [A-Z]; fragment LCASE : [a-z]; fragment A : [aA]; fragment B : [bB]; fragment C : [cC]; fragment D : [dD]; fragment E : [eE]; fragment F : [fF]; fragment G : [gG]; fragment H : [hH]; fragment I : [iI]; fragment J : [jJ]; fragment K : [kK]; fragment L : [lL]; fragment M : [mM]; fragment N : [nN]; fragment O : [oO]; fragment P : [pP]; fragment Q : [qQ]; fragment R : [rR]; fragment S : [sS]; fragment T : [tT]; fragment U : [uU]; fragment V : [vV]; fragment W : [wW]; fragment X : [xX]; fragment Y : [yY]; fragment Z : [zZ];
Allow underscores/hyphens in relation names
Allow underscores/hyphens in relation names
ANTLR
apache-2.0
PHB-CS123/graphene,PHB-CS123/graphene,PHB-CS123/graphene
85b7e11fc4a86cd7bdc7878f86b597657b543bbd
src/antlr/PTP.g4
src/antlr/PTP.g4
grammar PTP; @header { package pt.up.fe.iart.proj1.parser; } map : stmt+ ; stmt : node_stmt #node | edge_stmt #edge ; edge_stmt : 'Edge' '(' from=node_stmt ',' to=node_stmt ',' weight=(INT|REAL) ')'; node_stmt : 'GasStation' '(' position ')' #GasStation | 'GenericLocation' '(' position ')' #GenericLocation | 'PatientLocation' '(' position ')' #PatientLocation | 'Filiation' '(' position ',' bool ')' #Filiation ; position : '(' x=INT ',' y=INT ')' ; bool : 'true' | 'false' ; INT: [0-9]+ ; REAL: [0-9]+ '.' [0-9]* ; WS : [ \t\r\n]+ -> skip;
grammar PTP; @header { package pt.up.fe.iart.proj1.parser; } map : stmt+ ; stmt : node_stmt #node | edge_stmt #edge ; edge_stmt : 'Edge' '(' from=node_stmt ',' to=node_stmt ',' weight=(INT|REAL) ')'; node_stmt : 'GasStation' '(' position ')' #GasStation | 'GenericLocation' '(' position ')' #GenericLocation | 'PatientLocation' '(' position ')' #PatientLocation | 'Filiation' '(' position ',' bool ')' #Filiation ; position : '(' x=INT ',' y=INT ')' ; bool : 'true' | 'false' ; INT: [0-9]+ ; REAL: [0-9]+ '.' [0-9]* ; WS : [ \t\r\n]+ -> skip; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '//' .*? '\r'? '\n' -> skip ;
Add comments to input grammar.
Add comments to input grammar.
ANTLR
mit
migulorama/feup-iart-2014,migulorama/feup-iart-2014
f09a753e73d7b5eff486edc95d54c51bc383e009
sharding-core/src/main/antlr4/io/shardingsphere/core/parsing/antlr/autogen/OracleStatement.g4
sharding-core/src/main/antlr4/io/shardingsphere/core/parsing/antlr/autogen/OracleStatement.g4
grammar OracleStatement; import OracleKeyword, Keyword, OracleBase, OracleCreateIndex, OracleAlterIndex , OracleDropIndex, OracleCreateTable, OracleAlterTable, OracleDropTable, OracleTruncateTable , OracleTCLStatement, OracleDCLStatement ; execute : createIndex | alterIndex | dropIndex | createTable | alterTable | dropTable | truncateTable | setTransaction | commit | rollback | savepoint | grant | revoke | createUser ;
grammar OracleStatement; import OracleKeyword, Keyword, OracleBase, OracleCreateIndex, OracleAlterIndex , OracleDropIndex, OracleCreateTable, OracleAlterTable, OracleDropTable, OracleTruncateTable , OracleTCLStatement, OracleDCLStatement ; execute : createIndex | alterIndex | dropIndex | createTable | alterTable | dropTable | truncateTable | setTransaction | commit | rollback | savepoint | grant | revoke | createUser | alterUser ;
add alter user statement
add alter user statement
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
8df7263b96161687b99fc88e1b67d2b4710d459a
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE tableNotExistClause_ tableName createDefinitionClause_ inheritClause_ ; createIndex : CREATE createIndexSpecification_ INDEX concurrentlyClause_ (indexNotExistClause_ indexName)? ON onlyClause_ tableName ; alterTable : ALTER TABLE tableExistClause_ onlyClause_ tableName asteriskClause_ alterDefinitionClause_ ; alterIndex : ALTER INDEX indexExistClause_ indexName alterIndexDefinitionClause_ ; dropTable : DROP TABLE tableExistClause_ tableNames ; dropIndex : DROP INDEX concurrentlyClause_ indexExistClause_ indexNames ; truncateTable : TRUNCATE TABLE? onlyClause_ tableNamesClause ; createTableSpecification_ : ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? ; tableNotExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ (createDefinition (COMMA_ createDefinition)*)? RP_ ; createDefinition : columnDefinition | tableConstraint | LIKE tableName likeOption* ; columnDefinition : columnName dataType collateClause? columnConstraint* ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT ignoredIdentifier_ ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; checkOption : CHECK expr (NO INHERIT)? ; defaultExpr : CURRENT_TIMESTAMP | expr ; sequenceOptions : sequenceOption+ ; sequenceOption : START WITH? NUMBER_ | INCREMENT BY? NUMBER_ | MAXVALUE NUMBER_ | NO MAXVALUE | MINVALUE NUMBER_ | NO MINVALUE | CYCLE | NO CYCLE | CACHE NUMBER_ | OWNED BY ; indexParameters : (USING INDEX TABLESPACE ignoredIdentifier_)? | INCLUDE columnNames | WITH ; action : NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT) ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))? ; likeOption : (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnNames indexParameters | primaryKey columnNames indexParameters | EXCLUDE (USING ignoredIdentifier_)? | FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; inheritClause_ : (INHERITS tableNames)? ; createIndexSpecification_ : UNIQUE? ; concurrentlyClause_ : CONCURRENTLY? ; indexNotExistClause_ : (IF NOT EXISTS)? ; onlyClause_ : ONLY? ; tableExistClause_ : (IF EXISTS)? ; asteriskClause_ : ASTERISK_? ; alterDefinitionClause_ : alterTableActions | renameColumnSpecification | renameConstraint | renameTableSpecification_ ; alterIndexDefinitionClause_ : renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace ; renameIndexSpecification : RENAME TO indexName ; alterIndexDependsOnExtension : ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_ ; alterIndexSetTableSpace : ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)? ; tableNamesClause : tableNameClause (COMMA_ tableNameClause)* ; tableNameClause : tableName ASTERISK_? ; alterTableActions : alterTableAction (COMMA_ alterTableAction)* ; alterTableAction : addColumnSpecification | dropColumnSpecification | modifyColumnSpecification | addConstraintSpecification | ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam | VALIDATE CONSTRAINT ignoredIdentifier_ | DROP CONSTRAINT indexExistClause_ ignoredIdentifier_ (RESTRICT | CASCADE)? | (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)? | ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_ | (DISABLE | ENABLE) RULE ignoredIdentifier_ | ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_ | (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY | CLUSTER ON indexName | SET WITHOUT CLUSTER | SET (WITH | WITHOUT) OIDS | SET TABLESPACE ignoredIdentifier_ | SET (LOGGED | UNLOGGED) | SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_ | RESET LP_ storageParameter (COMMA_ storageParameter)* RP_ | INHERIT tableName | NO INHERIT tableName | OF dataTypeName_ | NOT OF | OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER) | REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING) ; addColumnSpecification : ADD COLUMN? (IF NOT EXISTS)? columnDefinition ; dropColumnSpecification : DROP COLUMN? columnExistClause_ columnName (RESTRICT | CASCADE)? ; columnExistClause_ : (IF EXISTS)? ; modifyColumnSpecification : modifyColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)? | modifyColumn SET DEFAULT expr | modifyColumn DROP DEFAULT | modifyColumn (SET | DROP) NOT NULL | modifyColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)? | modifyColumn alterColumnSetOption alterColumnSetOption* | modifyColumn DROP IDENTITY columnExistClause_ | modifyColumn SET STATISTICS NUMBER_ | modifyColumn SET LP_ attributeOptions RP_ | modifyColumn RESET LP_ attributeOptions RP_ | modifyColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN) ; modifyColumn : ALTER COLUMN? columnName ; alterColumnSetOption : SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)? ; attributeOptions : attributeOption (COMMA_ attributeOption)* ; attributeOption : IDENTIFIER_ EQ_ simpleExpr ; addConstraintSpecification : ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex) ; tableConstraintUsingIndex : (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam ; storageParameterWithValue : storageParameter EQ_ simpleExpr ; storageParameter : IDENTIFIER_ ; renameColumnSpecification : RENAME COLUMN? columnName TO columnName ; renameConstraint : RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_ ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; indexExistClause_ : (IF EXISTS)? ; indexNames : indexName (COMMA_ indexName)* ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE tableNotExistClause_ tableName createDefinitionClause_ inheritClause_ ; createIndex : CREATE createIndexSpecification_ INDEX concurrentlyClause_ (indexNotExistClause_ indexName)? ON onlyClause_ tableName ; alterTable : ALTER TABLE tableExistClause_ onlyClause_ tableNameClause alterDefinitionClause_ ; alterIndex : ALTER INDEX indexExistClause_ indexName alterIndexDefinitionClause_ ; dropTable : DROP TABLE tableExistClause_ tableNames ; dropIndex : DROP INDEX concurrentlyClause_ indexExistClause_ indexNames ; truncateTable : TRUNCATE TABLE? onlyClause_ tableNamesClause ; createTableSpecification_ : ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? ; tableNotExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ (createDefinition (COMMA_ createDefinition)*)? RP_ ; createDefinition : columnDefinition | tableConstraint | LIKE tableName likeOption* ; columnDefinition : columnName dataType collateClause? columnConstraint* ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT ignoredIdentifier_ ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; checkOption : CHECK expr (NO INHERIT)? ; defaultExpr : CURRENT_TIMESTAMP | expr ; sequenceOptions : sequenceOption+ ; sequenceOption : START WITH? NUMBER_ | INCREMENT BY? NUMBER_ | MAXVALUE NUMBER_ | NO MAXVALUE | MINVALUE NUMBER_ | NO MINVALUE | CYCLE | NO CYCLE | CACHE NUMBER_ | OWNED BY ; indexParameters : (USING INDEX TABLESPACE ignoredIdentifier_)? | INCLUDE columnNames | WITH ; action : NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT) ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))? ; likeOption : (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnNames indexParameters | primaryKey columnNames indexParameters | EXCLUDE (USING ignoredIdentifier_)? | FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; inheritClause_ : (INHERITS tableNames)? ; createIndexSpecification_ : UNIQUE? ; concurrentlyClause_ : CONCURRENTLY? ; indexNotExistClause_ : (IF NOT EXISTS)? ; onlyClause_ : ONLY? ; tableExistClause_ : (IF EXISTS)? ; asteriskClause_ : ASTERISK_? ; alterDefinitionClause_ : alterTableActions | renameColumnSpecification | renameConstraint | renameTableSpecification_ ; alterIndexDefinitionClause_ : renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace ; renameIndexSpecification : RENAME TO indexName ; alterIndexDependsOnExtension : ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_ ; alterIndexSetTableSpace : ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)? ; tableNamesClause : tableNameClause (COMMA_ tableNameClause)* ; tableNameClause : tableName ASTERISK_? ; alterTableActions : alterTableAction (COMMA_ alterTableAction)* ; alterTableAction : addColumnSpecification | dropColumnSpecification | modifyColumnSpecification | addConstraintSpecification | ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam | VALIDATE CONSTRAINT ignoredIdentifier_ | DROP CONSTRAINT indexExistClause_ ignoredIdentifier_ (RESTRICT | CASCADE)? | (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)? | ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_ | (DISABLE | ENABLE) RULE ignoredIdentifier_ | ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_ | (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY | CLUSTER ON indexName | SET WITHOUT CLUSTER | SET (WITH | WITHOUT) OIDS | SET TABLESPACE ignoredIdentifier_ | SET (LOGGED | UNLOGGED) | SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_ | RESET LP_ storageParameter (COMMA_ storageParameter)* RP_ | INHERIT tableName | NO INHERIT tableName | OF dataTypeName_ | NOT OF | OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER) | REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING) ; addColumnSpecification : ADD COLUMN? (IF NOT EXISTS)? columnDefinition ; dropColumnSpecification : DROP COLUMN? columnExistClause_ columnName (RESTRICT | CASCADE)? ; columnExistClause_ : (IF EXISTS)? ; modifyColumnSpecification : modifyColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)? | modifyColumn SET DEFAULT expr | modifyColumn DROP DEFAULT | modifyColumn (SET | DROP) NOT NULL | modifyColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)? | modifyColumn alterColumnSetOption alterColumnSetOption* | modifyColumn DROP IDENTITY columnExistClause_ | modifyColumn SET STATISTICS NUMBER_ | modifyColumn SET LP_ attributeOptions RP_ | modifyColumn RESET LP_ attributeOptions RP_ | modifyColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN) ; modifyColumn : ALTER COLUMN? columnName ; alterColumnSetOption : SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)? ; attributeOptions : attributeOption (COMMA_ attributeOption)* ; attributeOption : IDENTIFIER_ EQ_ simpleExpr ; addConstraintSpecification : ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex) ; tableConstraintUsingIndex : (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam ; storageParameterWithValue : storageParameter EQ_ simpleExpr ; storageParameter : IDENTIFIER_ ; renameColumnSpecification : RENAME COLUMN? columnName TO columnName ; renameConstraint : RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_ ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; indexExistClause_ : (IF EXISTS)? ; indexNames : indexName (COMMA_ indexName)* ;
use tableNameClause
use tableNameClause
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
6fb348a3113c8a60c4fbdee63198f7f67019c1e3
Krypton.LibProtocol/Grammars/KryptonParser.g4
Krypton.LibProtocol/Grammars/KryptonParser.g4
parser grammar KryptonParser; options { tokenVocab=KryptonTokens; } // Root members init : import_statement* library_declaration* ; import_statement : IMPORT (directory)? IDENTIFIER '.' KPDL ';' ; group_definition : GROUP IDENTIFIER ';' ; protocol_definition : PROTOCOL IDENTIFIER '{' message_definition? packet_definition* '}' ; message_definition : IDENTIFIER (',' message_definition)? ; packet_definition : PACKET IDENTIFIER (':' packet_parent)? '{' operation_statement+ '}' ; packet_parent : (namespace_reference '::')? IDENTIFIER (',' packet_parent)? ; library_declaration : LIBRARY IDENTIFIER '{' member_options? library_member* '}' ; library_member : group_definition | library_declaration | protocol_definition | type_declaration | packet_definition ; // Types type_name : IDENTIFIER | BUILTIN_TYPE ; type_reference : generic_attribute_reference | (namespace_reference '::')? type_name generic_types? ; generic_attribute_reference : IDENTIFIER ; generic_types : '<' type_reference (',' type_reference)* '>' ; // Type declaration type_declaration : DECLARE IDENTIFIER generic_type_attributes? '{' operation_statement+ '}' ; generic_type_attributes : '<' IDENTIFIER (',' IDENTIFIER)* '>' ; // Operation statements if_statement : '(' expression ')' '=>' '{' operation_statement+ '}' ';' ; conditional_statement : if_statement ; data_statement : type_reference IDENTIFIER ';' ; operation_statement : conditional_statement | data_statement ; // Expressions // see https://github.com/antlr/grammars-v4/blob/master/csharp/CSharpParser.g4 line 83 expression // alias : conditional_or_expression ; conditional_or_expression : conditional_and_expression ('||' conditional_and_expression)* ; conditional_and_expression : inclusive_or_expression ('&&' inclusive_or_expression)* ; inclusive_or_expression : exclusive_or_expression ('|' exclusive_or_expression)* ; exclusive_or_expression : and_expression ('^' and_expression)* ; and_expression : equality_expression ('&' equality_expression)* ; equality_expression : relational_expression (('==' | '!=') relational_expression)* ; relational_expression : shift_expression (('<' | '>' | '<=' | '>=') shift_expression)* ; shift_expression : additive_expression (('<<' | '>>') additive_expression)* ; additive_expression : multiplicative_expression (('+' | '-') multiplicative_expression)* ; multiplicative_expression : unary_expression (('*' | '/' | '%') unary_expression)* ; // https://msdn.microsoft.com/library/6a71f45d(v=vs.110).aspx unary_expression : expr_type | '+' unary_expression | '-' unary_expression | '!' unary_expression | '~' unary_expression | '(' expr_type ')' unary_expression | '&' unary_expression | '*' unary_expression ; expr_type : TRUE | FALSE | INTEGER | FLOAT | IDENTIFIER ; // Member option parsing member_options : OPTIONS OPTIONS_ENTER member_option* OPTIONS_EXIT ; member_option : OPTION_KEY OPTION_SET option_value OPTION_END ; // tood: support more than just string values option_value : STRING_VAL ; // Utility namespace_reference : IDENTIFIER ('::' IDENTIFIER)* | THIS ('::' IDENTIFIER)* ; directory : IDENTIFIER ('/' IDENTIFIER)* '/' ;
parser grammar KryptonParser; options { tokenVocab=KryptonTokens; } // Root members init : import_statement* library_declaration* ; import_statement : IMPORT (directory)? IDENTIFIER '.' KPDL ';' ; group_definition : GROUP IDENTIFIER ';' ; protocol_definition : PROTOCOL IDENTIFIER '{' message_definition? packet_definition* '}' ; message_definition : IDENTIFIER (',' message_definition)? ; packet_definition : PACKET IDENTIFIER (':' packet_parent)? '{' operation_statement+ '}' ; packet_parent : (namespace_reference '::')? IDENTIFIER (',' packet_parent)? ; library_declaration : LIBRARY IDENTIFIER '{' member_options? library_member* '}' ; library_member : group_definition | library_declaration | protocol_definition | type_declaration | packet_definition ; // Types type_name : IDENTIFIER | BUILTIN_TYPE ; type_reference : generic_attribute_reference | (namespace_reference '::')? type_name generic_types? ; generic_attribute_reference : IDENTIFIER ; generic_types : '<' type_reference (',' type_reference)* '>' ; // Type declaration type_declaration : DECLARE IDENTIFIER generic_type_attributes? '{' operation_statement+ '}' ; generic_type_attributes : '<' IDENTIFIER (',' IDENTIFIER)* '>' ; // Operation statements if_statement : '(' boolean_expression_tree ')' '=>' '{' operation_statement+ '}' ';' ; conditional_statement : if_statement ; data_statement : type_reference IDENTIFIER ';' ; operation_statement : conditional_statement | data_statement ; // Expressions boolean_expression_tree : expression_tree relational_operator expression_tree | TRUE | FALSE ; expression_tree : unary_expression (expression_operator unary_expression)* ; // https://msdn.microsoft.com/library/6a71f45d(v=vs.110).aspx unary_expression : op='+' expression_tree | op='-' expression_tree | op='!' expression_tree | op='~' expression_tree | op='&' expression_tree | op='*' expression_tree | '(' expression_tree ')' unary_expression* | literal_expression ; expression_operator : relational_operator |'||' | '&&' | '|' | '&' | '^' | '<<' | '>>' | '+' | '-' | '*' | '/' | '%' ; relational_operator : '==' | '!=' | '<' | '<=' | '>' | '>=' ; literal_expression : TRUE | FALSE | INTEGER | FLOAT | IDENTIFIER ; // Member option parsing member_options : OPTIONS OPTIONS_ENTER member_option* OPTIONS_EXIT ; member_option : OPTION_KEY OPTION_SET option_value OPTION_END ; // tood: support more than just string values option_value : STRING_VAL ; // Utility namespace_reference : IDENTIFIER ('::' IDENTIFIER)* | THIS ('::' IDENTIFIER)* ; directory : IDENTIFIER ('/' IDENTIFIER)* '/' ;
simplify the expression tree
parser: simplify the expression tree
ANTLR
mit
toontown-archive/Krypton.LibProtocol
e380f5a3d9555ac9d11d0cb13925d78cef9011c2
fortran77/Fortran77Lexer.g4
fortran77/Fortran77Lexer.g4
/* * Fortran 77 grammar for ANTLR 2.7.5 * Adadpted from Fortran 77 PCCTS grammar by Olivier Dragon * Original PCCTS grammar by Terence Parr * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA * */ /** * ported to Antlr4 by Tom Everett */ /* * Updated by Tom Everett, 2018 */ lexer grammar Fortran77Lexer; PROGRAM : 'program' | 'PROGRAM' ; ENTRY : 'entry' | 'ENTRY' ; FUNCTION : 'function' | 'FUNCTION' ; BLOCK : 'block' | 'BLOCK' ; SUBROUTINE : 'subroutine' | 'SUBROUTINE' ; END : 'END' | 'end' ; DIMENSION : 'dimension' | 'DIMENSION' ; REAL : 'REAL' | 'real' ; EQUIVALENCE : 'EQUIVALENCE' | 'equivalence' ; COMMON : 'common' | 'COMMON' ; POINTER : 'pointer' | 'POINTER' ; IMPLICIT : 'implicit' | 'IMPLICIT' ; NONE : 'none' | 'NONE' ; CHARACTER : 'character' | 'CHARACTER' ; PARAMETER : 'parameter' | 'PARAMETER' ; EXTERNAL : 'external' | 'EXTERNAL' ; INTRINSIC : 'intrinsic' | 'INTRINSIC' ; SAVE : 'save' | 'SAVE' ; DATA : 'data' | 'DATA' ; GO : 'GO' | 'go' ; GOTO : 'GOTO' | 'goto' ; IF : 'IF' | 'if' ; THEN : 'THEN' | 'then' ; ELSE : 'ELSE' | 'else' ; ENDIF : 'ENDIF' | 'endif' ; ELSEIF : 'ELSEIF' | 'elseif' ; DO : 'DO' | 'do' ; CONTINUE : 'CONTINUE' | 'continue' ; STOP : 'STOP' | 'stop' ; ENDDO : 'ENDDO' | 'enddo' ; PAUSE : 'pause' | 'PAUSE' ; WRITE : 'WRITE' | 'write' ; READ : 'READ' | 'read' ; PRINT : 'PRINT' | 'print' ; OPEN : 'OPEN' | 'open' ; FMT : 'FMT' | 'fmt' ; UNIT : 'UNIT' | 'unit' ; ERR : 'err' | 'ERR' ; IOSTAT : 'IOSTAT' | 'iostat' ; FORMAT : 'FORMAT' | 'format' ; LET : 'LET' | 'let' ; CALL : 'CALL' | 'call' ; RETURN : 'RETURN' | 'return' ; CLOSE : 'CLOSE' | 'close' ; DOUBLE : 'DOUBLE' | 'double' ; IOSTART : 'IOSTART' | 'iostart' ; SEQUENTIAL : 'SEQUENTIAL' | 'sequential' ; // ICON // : 'ICON' | 'icon' // ; LABEL : 'LABEL' | 'label' ; FILE : 'file' | 'FILE' ; STATUS : 'STATUS' | 'status' ; ACCESS : 'ACCESS' | 'access' ; POSITION : 'POSITION' | 'position' ; FORM : 'FORM' | 'form' ; RECL : 'RECL' | 'recl' ; BLANK : 'BLANK' | 'blank' ; EXIST : 'EXIST' | 'exist' ; OPENED : 'OPENED' | 'opened' ; NUMBER : 'NUMBER' | 'number' ; NAMED : 'NAMED' | 'named' ; NAME_ : 'NAME' | 'name' ; FORMATTED : 'FORMATTED' | 'formatted' ; UNFORMATTED : 'UNFORMATTED' | 'unformatted' ; NEXTREC : 'NEXTREC' | 'nextrec' ; INQUIRE : 'INQUIRE' | 'inquire' ; BACKSPACE : 'BACKSPACE' | 'backspace' ; ENDFILE : 'ENDFILE' | 'endfile' ; REWIND : 'REWIND' | 'rewind' ; DOLLAR : '$' ; COMMA : ',' ; LPAREN : '(' ; RPAREN : ')' ; COLON : ':' ; ASSIGN : '=' ; MINUS : '-' ; PLUS : '+' ; DIV : '/' ; fragment STARCHAR : '*' ; POWER : '**' ; LNOT : '.not.' | '.NOT.' ; LAND : '.and.' | '.AND.' ; LOR : '.or.' | '.OR.' ; EQV : '.eqv.' | '.EQV.' ; NEQV : '.neqv.' | '.NEQV.' ; XOR : '.xor.' | '.XOR.' ; EOR : '.eor.' | '.EOR.' ; LT : '.lt.' | '.LT.' ; LE : '.le.' | '.LE.' ; GT : '.gt.' | '.GT.' ; GE : '.ge.' | '.GE.' ; NE : '.ne.' | '.NE.' ; EQ : '.eq.' | '.EQ.' ; TRUE : '.true.' | '.TRUE.' ; FALSE : '.false.' | '.FALSE.' ; XCON : 'XCON' ; PCON : 'PCON' ; FCON : 'FCON' ; CCON : 'CCON' ; HOLLERITH : 'HOLLERITH' ; CONCATOP : 'CONCATOP' ; CTRLDIRECT : 'CTRLDIRECT' ; CTRLREC : 'CTRLREC' ; TO : 'TO' ; SUBPROGRAMBLOCK : 'SUBPROGRAMBLOCK' ; DOBLOCK : 'DOBLOCK' ; AIF : 'AIF' ; THENBLOCK : 'THENBLOCK' ; ELSEBLOCK : 'ELSEBLOCK' ; CODEROOT : 'CODEROOT' ; COMPLEX : 'COMPLEX' | 'complex' ; PRECISION : 'PRECISION' | 'precision' ; INTEGER : 'INTEGER' | 'integer' ; LOGICAL : 'LOGICAL' | 'logical' ; fragment CONTINUATION : ~ ('0' | ' ') ; fragment ALNUM : (ALPHA | NUM) ; fragment HEX : (NUM | 'a' .. 'f') ; fragment SIGN : ('+' | '-') ; fragment FDESC : ('i' | 'f' | 'd') (NUM) + '.' (NUM) + | ('e' | 'g') (NUM) + '.' (NUM) + ('e' (NUM) +)? ; fragment EXPON : ('e' | 'E' | 'd' | 'D') (SIGN)? (NUM) + ; fragment ALPHA : ('a' .. 'z') | ('A' .. 'Z') ; fragment NUM : ('0' .. '9') ; // '' is used to drop the charater when forming the lexical token // Strings are assumed to start with a single quote (') and two // single quotes is meant as a literal single quote SCON : '\'' ('\'' '\'' | ~ ('\'' | '\n' | '\r') | (('\n' | '\r' ('\n')?) ' ' CONTINUATION) ('\n' | '\r' ('\n')?) ' ' CONTINUATION)* '\'' ; RCON : NUM+ '.' NUM* EXPON? ; ICON : NUM+ ; NAME : (('i' | 'f' | 'd' | 'g' | 'e') (NUM) + '.') FDESC | (ALNUM +) (ALNUM)* ; COMMENT : {getCharPositionInLine() == 0}? ('c' | STARCHAR) (~ [\r\n])* EOL ; STAR : STARCHAR ; STRINGLITERAL : '"' ~ ["\r\n]* '"' ; EOL : [\r\n] + ; LINECONT : ((EOL ' $') | (EOL ' +')) -> skip ; WS : [\t ] + -> skip ;
/* * Fortran 77 grammar for ANTLR 2.7.5 * Adadpted from Fortran 77 PCCTS grammar by Olivier Dragon * Original PCCTS grammar by Terence Parr * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA * */ /** * ported to Antlr4 by Tom Everett */ /* * Updated by Tom Everett, 2018 */ lexer grammar Fortran77Lexer; PROGRAM : 'program' | 'PROGRAM' ; ENTRY : 'entry' | 'ENTRY' ; FUNCTION : 'function' | 'FUNCTION' ; BLOCK : 'block' | 'BLOCK' ; SUBROUTINE : 'subroutine' | 'SUBROUTINE' ; END : 'END' | 'end' ; DIMENSION : 'dimension' | 'DIMENSION' ; REAL : 'REAL' | 'real' ; EQUIVALENCE : 'EQUIVALENCE' | 'equivalence' ; COMMON : 'common' | 'COMMON' ; POINTER : 'pointer' | 'POINTER' ; IMPLICIT : 'implicit' | 'IMPLICIT' ; NONE : 'none' | 'NONE' ; CHARACTER : 'character' | 'CHARACTER' ; PARAMETER : 'parameter' | 'PARAMETER' ; EXTERNAL : 'external' | 'EXTERNAL' ; INTRINSIC : 'intrinsic' | 'INTRINSIC' ; SAVE : 'save' | 'SAVE' ; DATA : 'data' | 'DATA' ; GO : 'GO' | 'go' ; GOTO : 'GOTO' | 'goto' ; IF : 'IF' | 'if' ; THEN : 'THEN' | 'then' ; ELSE : 'ELSE' | 'else' ; ENDIF : 'ENDIF' | 'endif' ; ELSEIF : 'ELSEIF' | 'elseif' ; DO : 'DO' | 'do' ; CONTINUE : 'CONTINUE' | 'continue' ; STOP : 'STOP' | 'stop' ; ENDDO : 'ENDDO' | 'enddo' ; PAUSE : 'pause' | 'PAUSE' ; WRITE : 'WRITE' | 'write' ; READ : 'READ' | 'read' ; PRINT : 'PRINT' | 'print' ; OPEN : 'OPEN' | 'open' ; FMT : 'FMT' | 'fmt' ; UNIT : 'UNIT' | 'unit' ; ERR : 'err' | 'ERR' ; IOSTAT : 'IOSTAT' | 'iostat' ; FORMAT : 'FORMAT' | 'format' ; LET : 'LET' | 'let' ; CALL : 'CALL' | 'call' ; RETURN : 'RETURN' | 'return' ; CLOSE : 'CLOSE' | 'close' ; DOUBLE : 'DOUBLE' | 'double' ; IOSTART : 'IOSTART' | 'iostart' ; SEQUENTIAL : 'SEQUENTIAL' | 'sequential' ; LABEL : 'LABEL' | 'label' ; FILE : 'file' | 'FILE' ; STATUS : 'STATUS' | 'status' ; ACCESS : 'ACCESS' | 'access' ; POSITION : 'POSITION' | 'position' ; FORM : 'FORM' | 'form' ; RECL : 'RECL' | 'recl' ; BLANK : 'BLANK' | 'blank' ; EXIST : 'EXIST' | 'exist' ; OPENED : 'OPENED' | 'opened' ; NUMBER : 'NUMBER' | 'number' ; NAMED : 'NAMED' | 'named' ; NAME_ : 'NAME' | 'name' ; FORMATTED : 'FORMATTED' | 'formatted' ; UNFORMATTED : 'UNFORMATTED' | 'unformatted' ; NEXTREC : 'NEXTREC' | 'nextrec' ; INQUIRE : 'INQUIRE' | 'inquire' ; BACKSPACE : 'BACKSPACE' | 'backspace' ; ENDFILE : 'ENDFILE' | 'endfile' ; REWIND : 'REWIND' | 'rewind' ; DOLLAR : '$' ; COMMA : ',' ; LPAREN : '(' ; RPAREN : ')' ; COLON : ':' ; ASSIGN : '=' ; MINUS : '-' ; PLUS : '+' ; DIV : '/' ; fragment STARCHAR : '*' ; POWER : '**' ; LNOT : '.not.' | '.NOT.' ; LAND : '.and.' | '.AND.' ; LOR : '.or.' | '.OR.' ; EQV : '.eqv.' | '.EQV.' ; NEQV : '.neqv.' | '.NEQV.' ; XOR : '.xor.' | '.XOR.' ; EOR : '.eor.' | '.EOR.' ; LT : '.lt.' | '.LT.' ; LE : '.le.' | '.LE.' ; GT : '.gt.' | '.GT.' ; GE : '.ge.' | '.GE.' ; NE : '.ne.' | '.NE.' ; EQ : '.eq.' | '.EQ.' ; TRUE : '.true.' | '.TRUE.' ; FALSE : '.false.' | '.FALSE.' ; XCON : 'XCON' ; PCON : 'PCON' ; FCON : 'FCON' ; CCON : 'CCON' ; HOLLERITH : 'HOLLERITH' ; CONCATOP : 'CONCATOP' ; CTRLDIRECT : 'CTRLDIRECT' ; CTRLREC : 'CTRLREC' ; TO : 'TO' ; SUBPROGRAMBLOCK : 'SUBPROGRAMBLOCK' ; DOBLOCK : 'DOBLOCK' ; AIF : 'AIF' ; THENBLOCK : 'THENBLOCK' ; ELSEBLOCK : 'ELSEBLOCK' ; CODEROOT : 'CODEROOT' ; COMPLEX : 'COMPLEX' | 'complex' ; PRECISION : 'PRECISION' | 'precision' ; INTEGER : 'INTEGER' | 'integer' ; LOGICAL : 'LOGICAL' | 'logical' ; fragment CONTINUATION : ~ ('0' | ' ') ; fragment ALNUM : (ALPHA | NUM) ; fragment HEX : (NUM | 'a' .. 'f') ; fragment SIGN : ('+' | '-') ; fragment FDESC : ('i' | 'f' | 'd') (NUM) + '.' (NUM) + | ('e' | 'g') (NUM) + '.' (NUM) + ('e' (NUM) +)? ; fragment EXPON : ('e' | 'E' | 'd' | 'D') (SIGN)? (NUM) + ; fragment ALPHA : ('a' .. 'z') | ('A' .. 'Z') ; fragment NUM : ('0' .. '9') ; // '' is used to drop the charater when forming the lexical token // Strings are assumed to start with a single quote (') and two // single quotes is meant as a literal single quote SCON : '\'' ('\'' '\'' | ~ ('\'' | '\n' | '\r') | (('\n' | '\r' ('\n')?) ' ' CONTINUATION) ('\n' | '\r' ('\n')?) ' ' CONTINUATION)* '\'' ; RCON : NUM+ '.' NUM* EXPON? ; ICON : NUM+ ; NAME : (('i' | 'f' | 'd' | 'g' | 'e') (NUM) + '.') FDESC | (ALNUM +) (ALNUM)* ; COMMENT : {getCharPositionInLine() == 0}? ('c' | STARCHAR) (~ [\r\n])* EOL ; STAR : STARCHAR ; STRINGLITERAL : '"' ~ ["\r\n]* '"' ; EOL : [\r\n] + ; LINECONT : ((EOL ' $') | (EOL ' +')) -> skip ; WS : [\t ] + -> skip ;
remove commented old code
remove commented old code
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
660b4d515f118c7aacaf2af7c2c86d33df7b0d42
terraform/terraform.g4
terraform/terraform.g4
/* BSD License Copyright (c) 2020, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar terraform; file : (local | module | output | provider | variable | data | resource)+ ; resource : 'resource' label* blockbody ; data : 'data' label* blockbody ; provider : 'provider' STRING blockbody ; output : 'output' STRING blockbody ; local : 'locals' blockbody ; module : 'module' STRING blockbody ; variable : 'variable' STRING blockbody ; block : blocktype label* blockbody ; blocktype : IDENTIFIER ; label : STRING ; blockbody : '{' (argument | block)* '}' ; argument : identifier '=' expression ; identifier : IDENTIFIER ; expression : section ('.' section)* ; section : list | map | val ; val : NULL | NUMBER | string | BOOL | IDENTIFIER index? | DESCRIPTION | filedecl | functioncall | EOF_ ; functioncall : functionname '(' functionarguments ')' ; functionname : IDENTIFIER ; functionarguments : //no arguments | expression (',' expression)* ; index : '[' expression ']' ; filedecl : 'file' '(' expression ')' ; list : '[' expression (',' expression)* ','? ']' ; map : '{' argument* '}' ; string : STRING | MULTILINESTRING ; fragment DIGIT : [0-9] ; EOF_ : '<<EOF' .*? 'EOF' ; NULL : 'nul' ; NUMBER : DIGIT+ ('.' DIGIT+)? ; BOOL : 'true' | 'false' ; DESCRIPTION : '<<DESCRIPTION' .*? 'DESCRIPTION' ; MULTILINESTRING : '<<-EOF' .*? 'EOF' ; STRING : '"' (~ [\r\n"] | '""')* '"' ; IDENTIFIER : [a-zA-Z] ([a-zA-Z0-9_-])* ; COMMENT : ('#' | '//') ~ [\r\n]* -> channel(HIDDEN) ; BLOCKCOMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; WS : [ \r\n\t]+ -> skip ;
/* BSD License Copyright (c) 2020, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar terraform; file : (local | module | output | provider | variable | data | resource)+ ; resource : 'resource' 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 ;
Add resourcetype and name instead of using the generic 'label'
Add resourcetype and name instead of using the generic 'label'
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
f4d7a33bfb9c407e3cb60dbce8bc304e676a299e
src/main/antlr/SHRParser.g4
src/main/antlr/SHRParser.g4
parser grammar SHRParser; options { tokenVocab=SHRLexer; } shr: dataDefsDoc | valuesetDefsDoc /* | contentProfiles*/; // DATA DEFINITIONS (Vocabularies, Entries, Elements) dataDefsDoc: dataDefsHeader usesStatement? pathDefs? vocabularyDefs? dataDefs; dataDefsHeader: KW_DATA_DEFINITIONS namespace; usesStatement: KW_USES namespace (COMMA namespace)*; pathDefs: (defaultPathDef pathDef*) | (defaultPathDef? pathDef+); defaultPathDef: KW_PATH URL; pathDef: KW_PATH ALL_CAPS EQUAL URL; vocabularyDefs: vocabularyDef+; vocabularyDef: KW_VOCABULARY ALL_CAPS EQUAL (URL | URN_OID); dataDefs: dataDef*; dataDef: elementDef | entryDef; elementDef: elementHeader elementProps? values; elementHeader: KW_ELEMENT simpleName; entryDef: entryHeader elementProps? values; entryHeader: KW_ENTRY_ELEMENT simpleName; elementProps: elementProp+; elementProp: basedOnProp | conceptProp | descriptionProp; values: (value supportingValue*) | (value? supportingValue+); value: KW_VALUE (uncountedValue | countedValue); uncountedValue: (valueType (KW_OR valueType)*) | (OPEN_PAREN valueType (KW_OR valueType)* CLOSE_PAREN); countedValue: count valueType | count OPEN_PAREN valueType (KW_OR valueType)* CLOSE_PAREN; valueType: simpleOrFQName | ref | primitive | codeFromVS | quantityWithUnits | KW_TBD; supportingValue: countedSupportingValue (KW_OR countedSupportingValue)*; countedSupportingValue: count (supportingValueType | OPEN_PAREN supportingValueType (KW_OR supportingValueType)* CLOSE_PAREN); supportingValueType: simpleOrFQName | ref | elementWithConstraint; basedOnProp: KW_BASED_ON simpleOrFQName; conceptProp: KW_CONCEPT (KW_TBD | concepts); concepts: fullyQualifiedCode (COMMA fullyQualifiedCode)*; descriptionProp: KW_DESCRIPTION STRING; // VALUESET DEFINITIONS valuesetDefsDoc: valuesetDefsHeader usesStatement? pathDefs? vocabularyDefs? valuesetDefs; valuesetDefsHeader: KW_VALUESET_DEFINITIONS namespace; valuesetDefs: valuesetDef*; valuesetDef: valuesetHeader valuesetProps? valuesetValues?; valuesetHeader: KW_VALUESET (URL | URN_OID| simpleName); valuesetValues: valuesetValue+; valuesetValue: fullyQualifiedCode | valuesetInlineValue | valuesetDescendingFrom | valuesetFrom; valuesetInlineValue: CODE STRING?; valuesetDescendingFrom: KW_INCLUDES_CODES_DESCENDING_FROM fullyQualifiedCode (KW_AND_NOT_DESCENDING_FROM fullyQualifiedCode)*; valuesetFrom: KW_INCLUDES_CODES_FROM fullyQualifiedCode; valuesetProps: valuesetProp+; valuesetProp: conceptProp | descriptionProp; // CONTENT PROFILES: TODO -- May Be a Separate Grammar // COMMON BITS namespace: LOWER_WORD | DOT_SEPARATED_LW; simpleName: UPPER_WORD | ALL_CAPS; fullyQualifiedName: DOT_SEPARATED_UW; simpleOrFQName: simpleName | fullyQualifiedName; ref: KW_REF OPEN_PAREN simpleOrFQName CLOSE_PAREN; code: CODE STRING?; fullyQualifiedCode: ALL_CAPS code; codeFromVS: (KW_CODE_FROM | KW_CODING_FROM) valueset; elementWithConstraint: simpleOrFQName (DOT simpleName)* elementConstraint; elementConstraint: elementCodeVSConstraint | elementCodeValueConstraint | elementTypeConstraint; elementCodeVSConstraint: KW_WITH codeFromVS; elementCodeValueConstraint: KW_IS fullyQualifiedCode; elementTypeConstraint: KW_IS simpleOrFQName; quantityWithUnits: KW_QUANTITY_WITH_UNITS fullyQualifiedCode; valueset: URL | PATH_URL | URN_OID | simpleName; primitive: KW_BOOLEAN | KW_INTEGER | KW_STRING | KW_DECIMAL | KW_URI | KW_BASE64_BINARY | KW_INSTANT | KW_DATE | KW_DATE_TIME | KW_TIME | KW_CODE | KW_OID | KW_ID | KW_MARKDOWN | KW_UNSIGNED_INT | KW_POSITIVE_INT; count: WHOLE_NUMBER RANGE (WHOLE_NUMBER | STAR);
parser grammar SHRParser; options { tokenVocab=SHRLexer; } shr: dataDefsDoc | valuesetDefsDoc /* | contentProfiles*/; // DATA DEFINITIONS (Vocabularies, Entries, Elements) dataDefsDoc: dataDefsHeader usesStatement? pathDefs? vocabularyDefs? dataDefs; dataDefsHeader: KW_DATA_DEFINITIONS namespace; usesStatement: KW_USES namespace (COMMA namespace)*; pathDefs: (defaultPathDef pathDef*) | (defaultPathDef? pathDef+); defaultPathDef: KW_PATH URL; pathDef: KW_PATH ALL_CAPS EQUAL URL; vocabularyDefs: vocabularyDef+; vocabularyDef: KW_VOCABULARY ALL_CAPS EQUAL (URL | URN_OID); dataDefs: dataDef*; dataDef: elementDef | entryDef; elementDef: elementHeader elementProps? values; elementHeader: KW_ELEMENT simpleName; entryDef: entryHeader elementProps? values; entryHeader: KW_ENTRY_ELEMENT simpleName; elementProps: elementProp+; elementProp: basedOnProp | conceptProp | descriptionProp; values: (value supportingValue*) | (value? supportingValue+); value: KW_VALUE (uncountedValue | countedValue); uncountedValue: (valueType (KW_OR valueType)*) | (OPEN_PAREN valueType (KW_OR valueType)* CLOSE_PAREN); countedValue: count valueType | count OPEN_PAREN valueType (KW_OR valueType)* CLOSE_PAREN; valueType: simpleOrFQName | ref | primitive | codeFromVS | elementWithConstraint | quantityWithUnits | KW_TBD; supportingValue: countedSupportingValue (KW_OR countedSupportingValue)*; countedSupportingValue: count (supportingValueType | OPEN_PAREN supportingValueType (KW_OR supportingValueType)* CLOSE_PAREN); supportingValueType: simpleOrFQName | ref | elementWithConstraint; basedOnProp: KW_BASED_ON simpleOrFQName; conceptProp: KW_CONCEPT (KW_TBD | concepts); concepts: fullyQualifiedCode (COMMA fullyQualifiedCode)*; descriptionProp: KW_DESCRIPTION STRING; // VALUESET DEFINITIONS valuesetDefsDoc: valuesetDefsHeader usesStatement? pathDefs? vocabularyDefs? valuesetDefs; valuesetDefsHeader: KW_VALUESET_DEFINITIONS namespace; valuesetDefs: valuesetDef*; valuesetDef: valuesetHeader valuesetProps? valuesetValues?; valuesetHeader: KW_VALUESET (URL | URN_OID| simpleName); valuesetValues: valuesetValue+; valuesetValue: fullyQualifiedCode | valuesetInlineValue | valuesetDescendingFrom | valuesetFrom; valuesetInlineValue: CODE STRING?; valuesetDescendingFrom: KW_INCLUDES_CODES_DESCENDING_FROM fullyQualifiedCode (KW_AND_NOT_DESCENDING_FROM fullyQualifiedCode)*; valuesetFrom: KW_INCLUDES_CODES_FROM fullyQualifiedCode; valuesetProps: valuesetProp+; valuesetProp: conceptProp | descriptionProp; // CONTENT PROFILES: TODO -- May Be a Separate Grammar // COMMON BITS namespace: LOWER_WORD | DOT_SEPARATED_LW; simpleName: UPPER_WORD | ALL_CAPS; fullyQualifiedName: DOT_SEPARATED_UW; simpleOrFQName: simpleName | fullyQualifiedName; ref: KW_REF OPEN_PAREN simpleOrFQName CLOSE_PAREN; code: CODE STRING?; fullyQualifiedCode: ALL_CAPS code; codeFromVS: (KW_CODE_FROM | KW_CODING_FROM) valueset; elementWithConstraint: simpleOrFQName (DOT simpleName)* elementConstraint; elementConstraint: elementCodeVSConstraint | elementCodeValueConstraint | elementTypeConstraint; elementCodeVSConstraint: KW_WITH codeFromVS; elementCodeValueConstraint: KW_IS fullyQualifiedCode; elementTypeConstraint: KW_IS simpleOrFQName; quantityWithUnits: KW_QUANTITY_WITH_UNITS fullyQualifiedCode; valueset: URL | PATH_URL | URN_OID | simpleName; primitive: KW_BOOLEAN | KW_INTEGER | KW_STRING | KW_DECIMAL | KW_URI | KW_BASE64_BINARY | KW_INSTANT | KW_DATE | KW_DATE_TIME | KW_TIME | KW_CODE | KW_OID | KW_ID | KW_MARKDOWN | KW_UNSIGNED_INT | KW_POSITIVE_INT; count: WHOLE_NUMBER RANGE (WHOLE_NUMBER | STAR);
Update grammar to allow constraints on value
Update grammar to allow constraints on value
ANTLR
apache-2.0
standardhealth/shr_spec
17ff134db7ffa379d226a58f8b6cc9af382f8ae2
kotlin/kotlin/KotlinParser.g4
kotlin/kotlin/KotlinParser.g4
/** * Kotlin Grammar for ANTLR v4 * * Based on: * http://jetbrains.github.io/kotlin-spec/#_grammars_and_parsing * and * http://kotlinlang.org/docs/reference/grammar.html * * Tested on * https://github.com/JetBrains/kotlin/tree/master/compiler/testData/psi */ parser grammar KotlinParser; options { tokenVocab = KotlinLexer; } kotlinFile : NL* preamble anysemi* (topLevelObject (anysemi+ topLevelObject?)*)? EOF ; script : NL* preamble anysemi* (expression (anysemi+ expression?)*)? EOF ; preamble : fileAnnotations? packageHeader importList ; fileAnnotations : fileAnnotation+ ; fileAnnotation : (FILE COLON (LSQUARE unescapedAnnotation+ RSQUARE | unescapedAnnotation) semi?)+ ; packageHeader : (modifierList? PACKAGE identifier semi?)? ; importList : importHeader* ; importHeader : IMPORT identifier (DOT MULT | importAlias)? semi? ; importAlias : AS simpleIdentifier ; topLevelObject : classDeclaration | objectDeclaration | functionDeclaration | propertyDeclaration | typeAlias ; classDeclaration : modifierList? (CLASS | INTERFACE) NL* simpleIdentifier (NL* typeParameters)? (NL* primaryConstructor)? (NL* COLON NL* delegationSpecifiers)? (NL* typeConstraints)? (NL* classBody | NL* enumClassBody)? ; primaryConstructor : modifierList? (CONSTRUCTOR NL*)? classParameters ; classParameters : LPAREN (classParameter (COMMA classParameter)*)? RPAREN ; classParameter : modifierList? (VAL | VAR)? simpleIdentifier COLON type (ASSIGNMENT expression)? ; delegationSpecifiers : annotations* delegationSpecifier (NL* COMMA NL* delegationSpecifier)* ; delegationSpecifier : constructorInvocation | userType | explicitDelegation ; constructorInvocation : userType callSuffix ; explicitDelegation : userType NL* BY NL* expression ; classBody : LCURL NL* classMemberDeclaration* NL* RCURL ; classMemberDeclaration : (classDeclaration | functionDeclaration | objectDeclaration | companionObject | propertyDeclaration | anonymousInitializer | secondaryConstructor | typeAlias) anysemi* ; anonymousInitializer : INIT NL* block ; secondaryConstructor : modifierList? CONSTRUCTOR NL* functionValueParameters (NL* COLON NL* constructorDelegationCall)? NL* block ; constructorDelegationCall : THIS NL* valueArguments | SUPER NL* valueArguments ; enumClassBody : LCURL NL* enumEntries? (NL* SEMICOLON NL* classMemberDeclaration*)? NL* RCURL ; enumEntries : (enumEntry NL*)+ SEMICOLON? ; enumEntry : simpleIdentifier (NL* valueArguments)? (NL* classBody)? (NL* COMMA)? ; functionDeclaration : modifierList? FUN (NL* type NL* DOT)? (NL* typeParameters)? (NL* identifier)? NL* functionValueParameters (NL* COLON NL* type)? (NL* typeConstraints)? (NL* functionBody)? ; functionValueParameters : LPAREN (functionValueParameter (COMMA functionValueParameter)*)? RPAREN ; functionValueParameter : modifierList? parameter (ASSIGNMENT expression)? ; parameter : simpleIdentifier COLON type ; functionBody : block | ASSIGNMENT NL* expression ; objectDeclaration : modifierList? OBJECT NL* simpleIdentifier (NL* primaryConstructor)? (NL* COLON NL* delegationSpecifiers)? (NL* classBody)? ; companionObject : modifierList? COMPANION NL* modifierList? OBJECT (NL* simpleIdentifier)? (NL* COLON NL* delegationSpecifiers)? (NL* classBody)? ; propertyDeclaration : modifierList? (VAL | VAR) (NL* typeParameters)? (NL* type NL* DOT)? (NL* (multiVariableDeclaration | variableDeclaration)) (NL* typeConstraints)? (NL* (BY | ASSIGNMENT) NL* expression)? (getter (semi setter)? | setter (semi getter)?)? ; multiVariableDeclaration : LPAREN variableDeclaration (COMMA variableDeclaration)* RPAREN ; variableDeclaration : simpleIdentifier (COLON type)? ; getter : modifierList? GETTER | modifierList? GETTER NL* LPAREN RPAREN (NL* COLON NL* type)? NL* (block | ASSIGNMENT NL* expression) ; setter : modifierList? SETTER | modifierList? SETTER NL* LPAREN (annotations | parameterModifier)* (simpleIdentifier | parameter) RPAREN NL* functionBody ; typeAlias : modifierList? TYPE_ALIAS NL* simpleIdentifier (NL* typeParameters)? NL* ASSIGNMENT NL* type ; typeParameters : LANGLE NL* typeParameter (NL* COMMA NL* typeParameter)* NL* RANGLE ; typeParameter : modifierList? NL* simpleIdentifier (NL* COLON NL* type)? ; type : typeModifierList? ( functionType | parenthesizedType | nullableType | typeReference) ; typeModifierList : (annotations | SUSPEND NL*)+ ; parenthesizedType : LPAREN type RPAREN ; nullableType : (typeReference | parenthesizedType) NL* QUEST+ ; typeReference : LPAREN typeReference RPAREN | userType | DYNAMIC ; functionType : (functionTypeReceiver NL* DOT NL*)? functionTypeParameters NL* ARROW (NL* type) ; functionTypeReceiver : parenthesizedType | nullableType | typeReference ; userType : simpleUserType (NL* DOT NL* simpleUserType)* ; simpleUserType : simpleIdentifier (NL* typeArguments)? ; //parameters for functionType functionTypeParameters : LPAREN (parameter | type)? (COMMA (parameter | type))* RPAREN ; typeConstraints : WHERE NL* typeConstraint (NL* COMMA NL* typeConstraint)* ; typeConstraint : annotations* simpleIdentifier NL* COLON NL* type ; block : LCURL statements RCURL ; statements : anysemi* (statement (anysemi+ statement?)*)? ; statement : declaration | blockLevelExpression ; blockLevelExpression : annotations* NL* expression ; declaration : labelDefinition* ( classDeclaration | functionDeclaration | propertyDeclaration | typeAlias) ; expression : disjunction (assignmentOperator disjunction)* ; disjunction : conjunction (NL* DISJ NL* conjunction)* ; conjunction : equalityComparison (NL* CONJ NL* equalityComparison)* ; equalityComparison : comparison (equalityOperation NL* comparison)* ; comparison : namedInfix (comparisonOperator NL* namedInfix)? ; namedInfix : elvisExpression ((inOperator NL* elvisExpression)+ | (isOperator NL* type))? ; elvisExpression : infixFunctionCall (NL* ELVIS NL* infixFunctionCall)* ; infixFunctionCall : rangeExpression (simpleIdentifier NL* rangeExpression)* ; rangeExpression : additiveExpression (RANGE NL* additiveExpression)* ; additiveExpression : multiplicativeExpression (additiveOperator NL* multiplicativeExpression)* ; multiplicativeExpression : typeRHS (multiplicativeOperation NL* typeRHS)* ; typeRHS : prefixUnaryExpression (NL* typeOperation prefixUnaryExpression)* ; prefixUnaryExpression : prefixUnaryOperation* postfixUnaryExpression ; postfixUnaryExpression : (atomicExpression | callableReference) postfixUnaryOperation* ; atomicExpression : parenthesizedExpression | literalConstant | functionLiteral | thisExpression // THIS labelReference? | superExpression // SUPER (LANGLE type RANGLE)? labelReference? | conditionalExpression // ifExpression, whenExpression | tryExpression | objectLiteral | jumpExpression | loopExpression | collectionLiteral | simpleIdentifier ; parenthesizedExpression : LPAREN expression RPAREN ; callSuffix : typeArguments valueArguments? annotatedLambda* | valueArguments annotatedLambda* | annotatedLambda+ ; annotatedLambda : unescapedAnnotation* LabelDefinition? NL* functionLiteral ; arrayAccess : LSQUARE (expression (COMMA expression)*)? RSQUARE ; valueArguments : LPAREN (valueArgument (COMMA valueArgument)*)? RPAREN ; typeArguments : LANGLE NL* typeProjection (NL* COMMA typeProjection)* NL* RANGLE ; typeProjection : typeProjectionModifierList? type | MULT ; typeProjectionModifierList : varianceAnnotation+ ; valueArgument : (simpleIdentifier NL* ASSIGNMENT NL*)? MULT? NL* expression ; literalConstant : BooleanLiteral | IntegerLiteral | stringLiteral | HexLiteral | BinLiteral | CharacterLiteral | RealLiteral | NullLiteral | LongLiteral ; stringLiteral : lineStringLiteral | multiLineStringLiteral ; lineStringLiteral : QUOTE_OPEN (lineStringContent | lineStringExpression)* QUOTE_CLOSE ; multiLineStringLiteral : TRIPLE_QUOTE_OPEN (multiLineStringContent | multiLineStringExpression | lineStringLiteral | MultiLineStringQuote)* TRIPLE_QUOTE_CLOSE ; lineStringContent : LineStrText | LineStrEscapedChar | LineStrRef ; lineStringExpression : LineStrExprStart expression RCURL ; multiLineStringContent : MultiLineStrText | MultiLineStrEscapedChar | MultiLineStrRef ; multiLineStringExpression : MultiLineStrExprStart expression RCURL ; functionLiteral : annotations* ( LCURL NL* statements NL* RCURL | LCURL NL* lambdaParameters NL* ARROW NL* statements NL* RCURL ) ; lambdaParameters : lambdaParameter? (NL* COMMA NL* lambdaParameter)* ; lambdaParameter : variableDeclaration | multiVariableDeclaration (NL* COLON NL* type)? ; objectLiteral : OBJECT (NL* COLON NL* delegationSpecifiers)? NL* classBody ; collectionLiteral : LSQUARE expression? (COMMA expression)* RSQUARE ; thisExpression : THIS LabelReference? ; superExpression : SUPER (LANGLE NL* type NL* RANGLE)? LabelReference? ; conditionalExpression : ifExpression | whenExpression ; ifExpression : IF NL* LPAREN expression RPAREN NL* controlStructureBody? SEMICOLON? (NL* ELSE NL* controlStructureBody?)? ; controlStructureBody : block | expression ; whenExpression : WHEN NL* (LPAREN expression RPAREN)? NL* LCURL NL* (whenEntry NL*)* NL* RCURL ; whenEntry : whenCondition (NL* COMMA NL* whenCondition)* NL* ARROW NL* controlStructureBody semi? | ELSE NL* ARROW NL* controlStructureBody ; whenCondition : expression | rangeTest | typeTest ; rangeTest : inOperator NL* expression ; typeTest : isOperator NL* type ; tryExpression : TRY NL* block (NL* catchBlock)* (NL* finallyBlock)? ; catchBlock : CATCH NL* LPAREN annotations* simpleIdentifier COLON userType RPAREN NL* block ; finallyBlock : FINALLY NL* block ; loopExpression : forExpression | whileExpression | doWhileExpression ; forExpression : FOR NL* LPAREN annotations* (variableDeclaration | multiVariableDeclaration) IN expression RPAREN NL* controlStructureBody? ; whileExpression : WHILE NL* LPAREN expression RPAREN NL* controlStructureBody? ; doWhileExpression : DO NL* controlStructureBody? NL* WHILE NL* LPAREN expression RPAREN ; jumpExpression : THROW NL* expression | (RETURN | RETURN_AT) expression? | CONTINUE | CONTINUE_AT | BREAK | BREAK_AT ; callableReference : (userType (QUEST NL*)*)? NL* (COLONCOLON | Q_COLONCOLON) NL* (identifier | CLASS) ; assignmentOperator : ASSIGNMENT | ADD_ASSIGNMENT | SUB_ASSIGNMENT | MULT_ASSIGNMENT | DIV_ASSIGNMENT | MOD_ASSIGNMENT ; equalityOperation : EXCL_EQ | EXCL_EQEQ | EQEQ | EQEQEQ ; comparisonOperator : LANGLE | RANGLE | LE | GE ; inOperator : IN | NOT_IN ; isOperator : IS | NOT_IS ; additiveOperator : ADD | SUB ; multiplicativeOperation : MULT | DIV | MOD ; typeOperation : AS | AS_SAFE | COLON ; prefixUnaryOperation : INCR | DECR | ADD | SUB | EXCL | annotations | labelDefinition ; postfixUnaryOperation : INCR | DECR | EXCL EXCL | callSuffix | arrayAccess | NL* memberAccessOperator postfixUnaryExpression ; memberAccessOperator : DOT | QUEST DOT ; modifierList : (annotations | modifier)+ ; modifier : (classModifier | memberModifier | visibilityModifier | varianceAnnotation | functionModifier | propertyModifier | inheritanceModifier | parameterModifier | typeParameterModifier) NL* ; classModifier : ENUM | SEALED | ANNOTATION | DATA | INNER ; memberModifier : OVERRIDE | LATEINIT ; visibilityModifier : PUBLIC | PRIVATE | INTERNAL | PROTECTED ; varianceAnnotation : IN | OUT ; functionModifier : TAILREC | OPERATOR | INFIX | INLINE | EXTERNAL | SUSPEND ; propertyModifier : CONST ; inheritanceModifier : ABSTRACT | FINAL | OPEN ; parameterModifier : VARARG | NOINLINE | CROSSINLINE ; typeParameterModifier : REIFIED ; labelDefinition : LabelDefinition NL* ; annotations : (annotation | annotationList) NL* ; annotation : annotationUseSiteTarget NL* COLON NL* unescapedAnnotation | LabelReference (NL* typeArguments)? (NL* valueArguments)? ; annotationList : annotationUseSiteTarget COLON LSQUARE unescapedAnnotation+ RSQUARE | AT LSQUARE unescapedAnnotation+ RSQUARE ; annotationUseSiteTarget : FIELD | FILE | PROPERTY | GET | SET | RECEIVER | PARAM | SETPARAM | DELEGATE ; unescapedAnnotation : identifier typeArguments? valueArguments? ; identifier : simpleIdentifier (NL* DOT simpleIdentifier)* ; simpleIdentifier : Identifier //soft keywords: | ABSTRACT | ANNOTATION | BY | CATCH | COMPANION | CONSTRUCTOR | CROSSINLINE | DATA | DYNAMIC | ENUM | EXTERNAL | FINAL | FINALLY | GETTER | IMPORT | INFIX | INIT | INLINE | INNER | INTERNAL | LATEINIT | NOINLINE | OPEN | OPERATOR | OUT | OVERRIDE | PRIVATE | PROTECTED | PUBLIC | REIFIED | SEALED | TAILREC | SETTER | VARARG | WHERE //strong keywords | CONST | SUSPEND ; semi: NL+ | NL* SEMICOLON NL*; anysemi: NL | SEMICOLON;
/** * Kotlin Grammar for ANTLR v4 * * Based on: * http://jetbrains.github.io/kotlin-spec/#_grammars_and_parsing * and * http://kotlinlang.org/docs/reference/grammar.html * * Tested on * https://github.com/JetBrains/kotlin/tree/master/compiler/testData/psi */ parser grammar KotlinParser; options { tokenVocab = KotlinLexer; } kotlinFile : NL* preamble anysemi* (topLevelObject (anysemi+ topLevelObject?)*)? EOF ; script : NL* preamble anysemi* (expression (anysemi+ expression?)*)? EOF ; preamble : fileAnnotations? packageHeader importList ; fileAnnotations : fileAnnotation+ ; fileAnnotation : (FILE COLON (LSQUARE unescapedAnnotation+ RSQUARE | unescapedAnnotation) semi?)+ ; packageHeader : (modifierList? PACKAGE identifier semi?)? ; importList : importHeader* ; importHeader : IMPORT identifier (DOT MULT | importAlias)? semi? ; importAlias : AS simpleIdentifier ; topLevelObject : classDeclaration | objectDeclaration | functionDeclaration | propertyDeclaration | typeAlias ; classDeclaration : modifierList? (CLASS | INTERFACE) NL* simpleIdentifier (NL* typeParameters)? (NL* primaryConstructor)? (NL* COLON NL* delegationSpecifiers)? (NL* typeConstraints)? (NL* classBody | NL* enumClassBody)? ; primaryConstructor : modifierList? (CONSTRUCTOR NL*)? classParameters ; classParameters : LPAREN (classParameter (COMMA classParameter)*)? RPAREN ; classParameter : modifierList? (VAL | VAR)? simpleIdentifier COLON type (ASSIGNMENT expression)? ; delegationSpecifiers : annotations* delegationSpecifier (NL* COMMA NL* delegationSpecifier)* ; delegationSpecifier : constructorInvocation | userType | explicitDelegation ; constructorInvocation : userType callSuffix ; explicitDelegation : userType NL* BY NL* expression ; classBody : LCURL NL* classMemberDeclaration* NL* RCURL ; classMemberDeclaration : (classDeclaration | functionDeclaration | objectDeclaration | companionObject | propertyDeclaration | anonymousInitializer | secondaryConstructor | typeAlias) anysemi+ ; anonymousInitializer : INIT NL* block ; secondaryConstructor : modifierList? CONSTRUCTOR NL* functionValueParameters (NL* COLON NL* constructorDelegationCall)? NL* block? ; constructorDelegationCall : THIS NL* valueArguments | SUPER NL* valueArguments ; enumClassBody : LCURL NL* enumEntries? (NL* SEMICOLON NL* classMemberDeclaration*)? NL* RCURL ; enumEntries : (enumEntry NL*)+ SEMICOLON? ; enumEntry : simpleIdentifier (NL* valueArguments)? (NL* classBody)? (NL* COMMA)? ; functionDeclaration : modifierList? FUN (NL* type NL* DOT)? (NL* typeParameters)? (NL* identifier)? NL* functionValueParameters (NL* COLON NL* type)? (NL* typeConstraints)? (NL* functionBody)? ; functionValueParameters : LPAREN (functionValueParameter (COMMA functionValueParameter)*)? RPAREN ; functionValueParameter : modifierList? parameter (ASSIGNMENT expression)? ; parameter : simpleIdentifier COLON type ; functionBody : block | ASSIGNMENT NL* expression ; objectDeclaration : modifierList? OBJECT NL* simpleIdentifier (NL* primaryConstructor)? (NL* COLON NL* delegationSpecifiers)? (NL* classBody)? ; companionObject : modifierList? COMPANION NL* modifierList? OBJECT (NL* simpleIdentifier)? (NL* COLON NL* delegationSpecifiers)? (NL* classBody)? ; propertyDeclaration : modifierList? (VAL | VAR) (NL* typeParameters)? (NL* type NL* DOT)? (NL* (multiVariableDeclaration | variableDeclaration)) (NL* typeConstraints)? (NL* (BY | ASSIGNMENT) NL* expression)? (getter (semi setter)? | setter (semi getter)?)? ; multiVariableDeclaration : LPAREN variableDeclaration (COMMA variableDeclaration)* RPAREN ; variableDeclaration : simpleIdentifier (COLON type)? ; getter : modifierList? GETTER | modifierList? GETTER NL* LPAREN RPAREN (NL* COLON NL* type)? NL* (block | ASSIGNMENT NL* expression) ; setter : modifierList? SETTER | modifierList? SETTER NL* LPAREN (annotations | parameterModifier)* (simpleIdentifier | parameter) RPAREN NL* functionBody ; typeAlias : modifierList? TYPE_ALIAS NL* simpleIdentifier (NL* typeParameters)? NL* ASSIGNMENT NL* type ; typeParameters : LANGLE NL* typeParameter (NL* COMMA NL* typeParameter)* NL* RANGLE ; typeParameter : modifierList? NL* simpleIdentifier (NL* COLON NL* type)? ; type : typeModifierList? ( functionType | parenthesizedType | nullableType | typeReference) ; typeModifierList : (annotations | SUSPEND NL*)+ ; parenthesizedType : LPAREN type RPAREN ; nullableType : (typeReference | parenthesizedType) NL* QUEST+ ; typeReference : LPAREN typeReference RPAREN | userType | DYNAMIC ; functionType : (functionTypeReceiver NL* DOT NL*)? functionTypeParameters NL* ARROW (NL* type) ; functionTypeReceiver : parenthesizedType | nullableType | typeReference ; userType : simpleUserType (NL* DOT NL* simpleUserType)* ; simpleUserType : simpleIdentifier (NL* typeArguments)? ; //parameters for functionType functionTypeParameters : LPAREN (parameter | type)? (COMMA (parameter | type))* RPAREN ; typeConstraints : WHERE NL* typeConstraint (NL* COMMA NL* typeConstraint)* ; typeConstraint : annotations* simpleIdentifier NL* COLON NL* type ; block : LCURL statements RCURL ; statements : anysemi* (statement (anysemi+ statement?)*)? ; statement : declaration | blockLevelExpression ; blockLevelExpression : annotations* NL* expression ; declaration : labelDefinition* ( classDeclaration | functionDeclaration | propertyDeclaration | typeAlias) ; expression : disjunction (assignmentOperator disjunction)* ; disjunction : conjunction (NL* DISJ NL* conjunction)* ; conjunction : equalityComparison (NL* CONJ NL* equalityComparison)* ; equalityComparison : comparison (equalityOperation NL* comparison)* ; comparison : namedInfix (comparisonOperator NL* namedInfix)? ; namedInfix : elvisExpression ((inOperator NL* elvisExpression)+ | (isOperator NL* type))? ; elvisExpression : infixFunctionCall (NL* ELVIS NL* infixFunctionCall)* ; infixFunctionCall : rangeExpression (simpleIdentifier NL* rangeExpression)* ; rangeExpression : additiveExpression (RANGE NL* additiveExpression)* ; additiveExpression : multiplicativeExpression (additiveOperator NL* multiplicativeExpression)* ; multiplicativeExpression : typeRHS (multiplicativeOperation NL* typeRHS)* ; typeRHS : prefixUnaryExpression (NL* typeOperation prefixUnaryExpression)* ; prefixUnaryExpression : prefixUnaryOperation* postfixUnaryExpression ; postfixUnaryExpression : (atomicExpression | callableReference) postfixUnaryOperation* ; atomicExpression : parenthesizedExpression | literalConstant | functionLiteral | thisExpression // THIS labelReference? | superExpression // SUPER (LANGLE type RANGLE)? labelReference? | conditionalExpression // ifExpression, whenExpression | tryExpression | objectLiteral | jumpExpression | loopExpression | collectionLiteral | simpleIdentifier ; parenthesizedExpression : LPAREN expression RPAREN ; callSuffix : typeArguments valueArguments? annotatedLambda* | valueArguments annotatedLambda* | annotatedLambda+ ; annotatedLambda : unescapedAnnotation* LabelDefinition? NL* functionLiteral ; arrayAccess : LSQUARE (expression (COMMA expression)*)? RSQUARE ; valueArguments : LPAREN (valueArgument (COMMA valueArgument)*)? RPAREN ; typeArguments : LANGLE NL* typeProjection (NL* COMMA typeProjection)* NL* RANGLE ; typeProjection : typeProjectionModifierList? type | MULT ; typeProjectionModifierList : varianceAnnotation+ ; valueArgument : (simpleIdentifier NL* ASSIGNMENT NL*)? MULT? NL* expression ; literalConstant : BooleanLiteral | IntegerLiteral | stringLiteral | HexLiteral | BinLiteral | CharacterLiteral | RealLiteral | NullLiteral | LongLiteral ; stringLiteral : lineStringLiteral | multiLineStringLiteral ; lineStringLiteral : QUOTE_OPEN (lineStringContent | lineStringExpression)* QUOTE_CLOSE ; multiLineStringLiteral : TRIPLE_QUOTE_OPEN (multiLineStringContent | multiLineStringExpression | lineStringLiteral | MultiLineStringQuote)* TRIPLE_QUOTE_CLOSE ; lineStringContent : LineStrText | LineStrEscapedChar | LineStrRef ; lineStringExpression : LineStrExprStart expression RCURL ; multiLineStringContent : MultiLineStrText | MultiLineStrEscapedChar | MultiLineStrRef ; multiLineStringExpression : MultiLineStrExprStart expression RCURL ; functionLiteral : annotations* ( LCURL NL* statements NL* RCURL | LCURL NL* lambdaParameters NL* ARROW NL* statements NL* RCURL ) ; lambdaParameters : lambdaParameter? (NL* COMMA NL* lambdaParameter)* ; lambdaParameter : variableDeclaration | multiVariableDeclaration (NL* COLON NL* type)? ; objectLiteral : OBJECT (NL* COLON NL* delegationSpecifiers)? NL* classBody ; collectionLiteral : LSQUARE expression? (COMMA expression)* RSQUARE ; thisExpression : THIS LabelReference? ; superExpression : SUPER (LANGLE NL* type NL* RANGLE)? LabelReference? ; conditionalExpression : ifExpression | whenExpression ; ifExpression : IF NL* LPAREN expression RPAREN NL* controlStructureBody? SEMICOLON? (NL* ELSE NL* controlStructureBody?)? ; controlStructureBody : block | expression ; whenExpression : WHEN NL* (LPAREN expression RPAREN)? NL* LCURL NL* (whenEntry NL*)* NL* RCURL ; whenEntry : whenCondition (NL* COMMA NL* whenCondition)* NL* ARROW NL* controlStructureBody semi? | ELSE NL* ARROW NL* controlStructureBody ; whenCondition : expression | rangeTest | typeTest ; rangeTest : inOperator NL* expression ; typeTest : isOperator NL* type ; tryExpression : TRY NL* block (NL* catchBlock)* (NL* finallyBlock)? ; catchBlock : CATCH NL* LPAREN annotations* simpleIdentifier COLON userType RPAREN NL* block ; finallyBlock : FINALLY NL* block ; loopExpression : forExpression | whileExpression | doWhileExpression ; forExpression : FOR NL* LPAREN annotations* (variableDeclaration | multiVariableDeclaration) IN expression RPAREN NL* controlStructureBody? ; whileExpression : WHILE NL* LPAREN expression RPAREN NL* controlStructureBody? ; doWhileExpression : DO NL* controlStructureBody? NL* WHILE NL* LPAREN expression RPAREN ; jumpExpression : THROW NL* expression | (RETURN | RETURN_AT) expression? | CONTINUE | CONTINUE_AT | BREAK | BREAK_AT ; callableReference : (userType (QUEST NL*)*)? NL* (COLONCOLON | Q_COLONCOLON) NL* (identifier | CLASS) ; assignmentOperator : ASSIGNMENT | ADD_ASSIGNMENT | SUB_ASSIGNMENT | MULT_ASSIGNMENT | DIV_ASSIGNMENT | MOD_ASSIGNMENT ; equalityOperation : EXCL_EQ | EXCL_EQEQ | EQEQ | EQEQEQ ; comparisonOperator : LANGLE | RANGLE | LE | GE ; inOperator : IN | NOT_IN ; isOperator : IS | NOT_IS ; additiveOperator : ADD | SUB ; multiplicativeOperation : MULT | DIV | MOD ; typeOperation : AS | AS_SAFE | COLON ; prefixUnaryOperation : INCR | DECR | ADD | SUB | EXCL | annotations | labelDefinition ; postfixUnaryOperation : INCR | DECR | EXCL EXCL | callSuffix | arrayAccess | NL* memberAccessOperator postfixUnaryExpression ; memberAccessOperator : DOT | QUEST DOT ; modifierList : (annotations | modifier)+ ; modifier : (classModifier | memberModifier | visibilityModifier | varianceAnnotation | functionModifier | propertyModifier | inheritanceModifier | parameterModifier | typeParameterModifier) NL* ; classModifier : ENUM | SEALED | ANNOTATION | DATA | INNER ; memberModifier : OVERRIDE | LATEINIT ; visibilityModifier : PUBLIC | PRIVATE | INTERNAL | PROTECTED ; varianceAnnotation : IN | OUT ; functionModifier : TAILREC | OPERATOR | INFIX | INLINE | EXTERNAL | SUSPEND ; propertyModifier : CONST ; inheritanceModifier : ABSTRACT | FINAL | OPEN ; parameterModifier : VARARG | NOINLINE | CROSSINLINE ; typeParameterModifier : REIFIED ; labelDefinition : LabelDefinition NL* ; annotations : (annotation | annotationList) NL* ; annotation : annotationUseSiteTarget NL* COLON NL* unescapedAnnotation | LabelReference (NL* typeArguments)? (NL* valueArguments)? ; annotationList : annotationUseSiteTarget COLON LSQUARE unescapedAnnotation+ RSQUARE | AT LSQUARE unescapedAnnotation+ RSQUARE ; annotationUseSiteTarget : FIELD | FILE | PROPERTY | GET | SET | RECEIVER | PARAM | SETPARAM | DELEGATE ; unescapedAnnotation : identifier typeArguments? valueArguments? ; identifier : simpleIdentifier (NL* DOT simpleIdentifier)* ; simpleIdentifier : Identifier //soft keywords: | ABSTRACT | ANNOTATION | BY | CATCH | COMPANION | CONSTRUCTOR | CROSSINLINE | DATA | DYNAMIC | ENUM | EXTERNAL | FINAL | FINALLY | GETTER | IMPORT | INFIX | INIT | INLINE | INNER | INTERNAL | LATEINIT | NOINLINE | OPEN | OPERATOR | OUT | OVERRIDE | PRIVATE | PROTECTED | PUBLIC | REIFIED | SEALED | TAILREC | SETTER | VARARG | WHERE //strong keywords | CONST | SUSPEND ; semi: NL+ | NL* SEMICOLON NL*; anysemi: NL | SEMICOLON;
Fix parsing classes with constructor without block statement
Fix parsing classes with constructor without block statement
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
b892695315eabea975337aa233e89449adfaee17
pike/pike.g4
pike/pike.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. */ /* * http://www.mit.edu/afs.new/sipb/project/pike/tutorial/tutorial_onepage.html#D */ grammar pike; program : definition* ; definition : impo | inheritance | function_declaration | function_definition | variables | constant | class_def ; impo : modifiers? 'import' constant_identifier ';' ; inheritance : modifiers? 'inherit' program_specifier (':' IDENTIFIER)? ';' ; function_declaration : modifiers? type_ IDENTIFIER '(' arguments ')' ';' ; function_definition : modifiers? type_ IDENTIFIER '(' arguments ')' block ; variables : modifiers? type_ variable_names ';' ; variable_names : variable_name (',' variable_name)* ; variable_name : '*'* IDENTIFIER ('=' expression2)? ; constant : modifiers? 'constant' constant_names ';' ; constant_names : constant_name (',' constant_name)* ; constant_name : IDENTIFIER '=' expression2 ; class_def : modifiers? 'class' ';'? ; class_implementation : 'class' IDENTIFIER? '{' program '}' ; modifiers : 'static' | 'private' | 'nomask' | 'public' | 'protected' | 'inline' ; block : '{' statement* '}' ; statement : expression2 ';' | cond | while_stmt | do_while_stmt | for_stmt | switch_stmt | case_stmt | default_stmt | block | foreach_stmt | break_stmt | continue_stmt | ';' ; cond : 'if' statement ('else' statement)? ; while_stmt : 'while''(' expression ')' statement ; do_while_stmt : 'do' statement while_stmt '(' expression ')' ';' ; for_stmt : 'for' '(' expression? ';' expression? ';' expression? ')' statement ; switch_stmt : 'switch' '(' expression ')' block ; case_stmt : 'case' expression ('..' expression)? ':' ; default_stmt : 'default' ':' ; foreach_stmt : 'foreach' '(' expression ':' expression6 ')' statement ; break_stmt : 'break' ';' ; continue_stmt : 'continue' ';' ; expression : expression2 (',' expression2)* ; expression2 : (lvalue ('=' | '+=' | '*=' | '/=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '%='))* expression3 ; expression3 : expression4 '?' expression3 ':' expression3 ; expression4 : (expression5 ('||' | '&&' | '|' | '^' | '&' | '==' | '!=' | '>' | '<' | '>=' | '<=' | '<<' | '>>' | '+' | '*' | '/' | '%'))* expression5 ; expression5 : expression6 | '(' type_ ')' expression5 | '--' expression6 | '++' expression6 | expression6 '--' | expression6 '++' | '~' expression5 | '-' expression5 ; expression6 : ( STRING | NUMBER | FLOAT | catch_ | gauge | sscanf | lambda | class_implementation | constant_identifier | mapping | multiset | array | parenthesis ) extension* ; extension : '(' expression_list ')' | '->' IDENTIFIER | '[' expression ('..' expression)? ']' ; catch_ : 'catch' ('(' expression ')' | block) ; gauge : 'gauge' ('(' expression ')' | block) ; sscanf : 'sscanf' '(' expression2 ',' expression2 (',' lvalue)* ')' ; lvalue : 'lambda' expression6 | type_ IDENTIFIER ; lambda : 'lambda' '(' arguments ')' block ; constant_identifier : IDENTIFIER ('.' IDENTIFIER)* ; array : '({' expression_list '})' ; multiset : '(<' expression_list '>)' ; mapping : '([' (expression ':' expression (',' expression ':' expression)*)? ','? '])' ; program_specifier : /*string_constant |*/ constant_identifier ; parenthesis : '(' expression ')' ; expression_list : (splice_expression (',' splice_expression)*)? ','? ; splice_expression : '@'? expression2 ; argument : type_ ('...')? (IDENTIFIER)? ; arguments : (argument (',' argument)*)? (',')? ; type_ : ('int' | 'string' | 'float' | 'program' | ('object' ('(' program_specifier ')')?) | ('mapping' ('(' type_ ':' type_ ')')?) | ('array' ('(' type_ ')')?) | ('multiset' ('(' type_ ')')?) | ('function' function_type?)) ('*')* ; function_type : '(' type_ (',' type_)* ('...')? ')' ; IDENTIFIER : LETTER (LETTER | DIGIT)* | '+' | '/' | '%' | '*' | '&' | '|' | '^' | '~' | '<' | '<<' | '<=' | '>' | '>>' | '>=' | '==' | '!=' | '!' | '()' | '-' | '->' | '->=' | '[]' | '[]=' ; LETTER : 'a' .. 'z' | 'A' .. 'Z' | '_' ; DIGIT : '0' .. '9' ; FLOAT : DIGIT DIGIT* '.' DIGIT* ; NUMBER : DIGIT DIGIT* | '0x' DIGIT* ; STRING : '"' ~ '"'* '"' ; WS : [ \t\r\n] -> skip ;
/* BSD License Copyright (c) 2018, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * http://www.mit.edu/afs.new/sipb/project/pike/tutorial/tutorial_onepage.html#D */ grammar pike; program : definition* ; definition : impo | inheritance | function_declaration | function_definition | variables | constant | class_def ; impo : modifiers? 'import' constant_identifier ';' ; inheritance : modifiers? 'inherit' program_specifier (':' IDENTIFIER)? ';' ; function_declaration : modifiers? type_ IDENTIFIER '(' arguments ')' ';' ; function_definition : modifiers? type_ IDENTIFIER '(' arguments ')' block ; variables : modifiers? type_ variable_names ';' ; variable_names : variable_name (',' variable_name)* ; variable_name : '*'* IDENTIFIER ('=' expression2)? ; constant : modifiers? 'constant' constant_names ';' ; constant_names : constant_name (',' constant_name)* ; constant_name : IDENTIFIER '=' expression2 ; class_def : modifiers? 'class' ';'? ; class_implementation : 'class' IDENTIFIER? '{' program '}' ; modifiers : 'static' | 'private' | 'nomask' | 'public' | 'protected' | 'inline' ; block : '{' statement* '}' ; statement : expression2 ';' | cond | while_stmt | do_while_stmt | for_stmt | switch_stmt | case_stmt | default_stmt | block | foreach_stmt | break_stmt | continue_stmt | ';' ; cond : 'if' statement ('else' statement)? ; while_stmt : 'while''(' expression ')' statement ; do_while_stmt : 'do' statement while_stmt '(' expression ')' ';' ; for_stmt : 'for' '(' expression? ';' expression? ';' expression? ')' statement ; switch_stmt : 'switch' '(' expression ')' block ; case_stmt : 'case' expression ('..' expression)? ':' ; default_stmt : 'default' ':' ; foreach_stmt : 'foreach' '(' expression ':' expression6 ')' statement ; break_stmt : 'break' ';' ; continue_stmt : 'continue' ';' ; expression : expression2 (',' expression2)* ; expression2 : (lvalue ('=' | '+=' | '*=' | '/=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '%='))* expression3 ; expression3 : expression4 ('?' expression3 ':' expression3)? ; expression4 : (expression5 ('||' | '&&' | '|' | '^' | '&' | '==' | '!=' | '>' | '<' | '>=' | '<=' | '<<' | '>>' | '+' | '*' | '/' | '%'))* expression5 ; expression5 : expression6 | '(' type_ ')' expression5 | '--' expression6 | '++' expression6 | expression6 '--' | expression6 '++' | '~' expression5 | '-' expression5 ; expression6 : ( STRING | NUMBER | FLOAT | catch_ | gauge | sscanf | lambda | class_implementation | constant_identifier | mapping | multiset | array | parenthesis ) extension* ; extension : '(' expression_list ')' | '->' IDENTIFIER | '[' expression ('..' expression)? ']' ; catch_ : 'catch' ('(' expression ')' | block) ; gauge : 'gauge' ('(' expression ')' | block) ; sscanf : 'sscanf' '(' expression2 ',' expression2 (',' lvalue)* ')' ; lvalue : 'lambda' expression6 | type_ IDENTIFIER ; lambda : 'lambda' '(' arguments ')' block ; constant_identifier : IDENTIFIER ('.' IDENTIFIER)* ; array : '({' expression_list '})' ; multiset : '(<' expression_list '>)' ; mapping : '([' (expression ':' expression (',' expression ':' expression)*)? ','? '])' ; program_specifier : /*string_constant |*/ constant_identifier ; parenthesis : '(' expression ')' ; expression_list : (splice_expression (',' splice_expression)*)? ','? ; splice_expression : '@'? expression2 ; argument : type_ ('...')? (IDENTIFIER)? ; arguments : (argument (',' argument)*)? (',')? ; type_ : ('int' | 'string' | 'float' | 'program' | ('object' ('(' program_specifier ')')?) | ('mapping' ('(' type_ ':' type_ ')')?) | ('array' ('(' type_ ')')?) | ('multiset' ('(' type_ ')')?) | ('function' function_type?)) ('*')* ; function_type : '(' type_ (',' type_)* ('...')? ')' ; IDENTIFIER : LETTER (LETTER | DIGIT)* | '+' | '/' | '%' | '*' | '&' | '|' | '^' | '~' | '<' | '<<' | '<=' | '>' | '>>' | '>=' | '==' | '!=' | '!' | '()' | '-' | '->' | '->=' | '[]' | '[]=' ; LETTER : 'a' .. 'z' | 'A' .. 'Z' | '_' ; DIGIT : '0' .. '9' ; FLOAT : DIGIT DIGIT* '.' DIGIT* ; NUMBER : DIGIT DIGIT* | '0x' DIGIT* ; STRING : '"' ~ '"'* '"' ; WS : [ \t\r\n] -> skip ;
Make pike have a non-infinite rule
Make pike have a non-infinite 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
73fa6acb3fc2537efc6e670a6774a8785ec493ed
src/Composer.g4
src/Composer.g4
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ grammar Composer; stat: assign NEWLINE {console.log("create new");} | connect NEWLINE {console.log("connect new");} ; assign: ID '=' expr {console.log("assign expr is" + $expr.text);}; connect: expr CONNECT expr {console.log("connect expr is" + $expr.text);}; expr:; CONNECT : '->'; ID : [a-zA-Z_] [a-zA-Z_0-9]* ; // match identifiers <label id="code.tour.expr.3"/> INT : [0-9]+ ; // match integers /** Newline ends a statement */ NEWLINE :'\r'? '\n' ; // return newlines to parser (is end-statement signal) /** Warning: doesn't handle INDENT/DEDENT Python rules */ WS : [ \t]+ -> skip ; // toss out whitespace /** Match comments. Don't match \n here; we'll send NEWLINE to the parser. */ COMMENT : '#' ~[\r\n]* -> skip ;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ grammar Composer; prog: (stat)+; stat: declare NEWLINE {System.out.println("create expression");} | connect NEWLINE {System.out.println("connect expression");} | NEWLINE {System.out.println("empty or comment line");} ; declare: ID '=' function {System.out.println("assign expr is " + $text);}; function: ID '(' parameter? ')'; parameter: INT | STRING; connect: port CONNECT port {System.out.println("connect expr is " + $text);}; port: ID '.' ID; CONNECT : '->'; ID : [a-zA-Z_] [a-zA-Z_0-9]* ; // match identifiers <label id="code.tour.expr.3"/> INT : [0-9]+ ; // match integers /** Newline ends a statement */ NEWLINE :'\r'? '\n' ; // return newlines to parser (is end-statement signal) /** Warning: doesn't handle INDENT/DEDENT Python rules */ WS : [ \t]+ -> skip ; // toss out whitespace /** Match comments. Don't match \n here; we'll send NEWLINE to the parser. */ COMMENT : '#' ~[\r\n]* -> skip ; /** Match strings, not match escape chars */ STRING: '"' (ESC|.)*? '"'; fragment ESC : '\\"' | '\\\\'; // 2-char sequences \" and \\
Update Composer.g4
Update Composer.g4
ANTLR
mit
hanwencheng/ConnectLang
6720c4c4e2276056247462f44cbc5edd09a9e94f
sharding-core/src/main/antlr4/imports/SQLServerKeyword.g4
sharding-core/src/main/antlr4/imports/SQLServerKeyword.g4
lexer grammar SQLServerKeyword; import Symbol; ABORT_AFTER_WAIT : A B O R T UL_ A F T E R UL_ W A I T ; ACTION : A C T I O N ; 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 ; ASYMMETRIC : A S Y M M E T R I C ; AUTO : A U T O ; BACKSLASH : B A C K S L A S H ; BEGIN : B E G I N ; BLOCKERS : B L O C K E R S ; BUCKET_COUNT : B U C K E T UL_ C O U N T ; CAST : C A S T ; CERTIFICATE : C E R T I F I C A T E ; CLUSTERED : C L U S T E R E D ; COLLATE : C O L L A T E ; 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 ; CONVERT : C O N V E R T ; DATABASE : D A T A B A S E ; DATABASE_DEAULT : D A T A B A S E UL_ D E A U L 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 ; DAYS : D A Y S ; DELAYED_DURABILITY : D E L A Y E D UL_ D U R A B I L I T Y ; DENY : D E N Y ; DETERMINISTIC : D E T E R M I N I S T I C ; DISTRIBUTION : D I S T R I B U T I O N ; DOCUMENT : D O C U M E N T ; DROP_EXISTING : D R O P UL_ E X I S T I N G ; DURABILITY : D U R A B I L I T Y ; DW : D W ; 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 ; END : E N D ; EXTERNAL : E X T E R N A L ; 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 : F I L E T A B L E ; 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 ; FILLFACTOR : F I L L F A C T O R ; FILTER_PREDICATE : F I L T E R UL_ P R E D I C A T E ; FOLLOWING : F O L L O W I N G ; FOR : F O R ; FUNCTION : F U N C T I O N ; GRANT : G R A N T ; HASH : H A S H ; HASHED : H A S H E D ; HEAP : H E A P ; HIDDEN_ : H I D D E N UL_ ; 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 ; HISTORY_TABLE : H I S T O R Y UL_ T A B L E ; IDENTITY : I D E N T I T Y ; 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 ; INFINITE : I N F I N I T E ; LEFT : L E F T ; LEFT_BRACKET : L E F T UL_ B R A C K E T ; LOCK_ESCALATION : L O C K UL_ E S C A L A T I O N ; LOGIN : L O G I N ; MARK : M A R K ; MASKED : M A S K E D ; MAX : M A X ; MAXDOP : M A X D O P ; MAX_DURATION : M A X UL_ D U R A T I O N ; 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 ; MINUTES : M I N U T E S ; MONTH : M O N T H ; MONTHS : M O N T H S ; MOVE : M O V E ; MUST_CHANGE : M U S T UL_ C H A N G E ; NOCHECK : N O C H E C K ; NONCLUSTERED : N O N C L U S T E R E D ; NONE : N O N E ; OBJECT : O B J E C T ; OFF : O F F ; ONLINE : O N L I N E ; OPTION : O P T I O N ; OUTBOUND : O U T B O U N D ; OVER : O V E R ; 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 ; PASSWORD : P A S S W O R D ; PAUSED : P A U S E D ; PERIOD : P E R I O D ; PERSISTED : P E R S I S T E D ; PRECEDING : P R E C E D I N G ; PRIVILEGES : P R I V I L E G E S ; PROVIDER : P R O V I D E R ; RANDOMIZED : R A N D O M I Z E D ; RANGE : R A N G E ; REBUILD : R E B U I L D ; REMOTE_DATA_ARCHIVE : R E M O T E UL_ D A T A UL_ A R C H I V E ; REPEATABLE : R E P E A T A B L E ; REPLICATE : R E P L I C A T E ; REPLICATION : R E P L I C A T I O N ; RESUMABLE : R E S U M A B L E ; REVOKE : R E V O K E ; RIGHT : R I G H T ; RIGHT_BRACKET : R I G H T UL_ B R A C K E T ; ROLE : R O L E ; ROUND_ROBIN : R O U N D UL_ R O B I N ; ROWGUIDCOL : R O W G U I D C O L ; ROWS : R O W S ; SAVE : S A V E ; SCHEMA : S C H E M A ; 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 ; SELF : S E L F ; SNAPSHOT : S N A P S H O T ; SORT_IN_TEMPDB : S O R T UL_ I N UL_ T E M P D B ; SPARSE : S P A R S E ; 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 ; SWITCH : S W I T C H ; 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 ; TRAN : T R A N ; TRIGGER : T R I G G E R ; UNBOUNDED : U N B O U N D E D ; UNCOMMITTED : U N C O M M I T T E D ; UPDATE : U P D A T E ; VALUES : V A L U E S ; 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 ; WINDOWS : W I N D O W S ; WITHOUT : W I T H O U T ; YEARS : Y E A R S ; ZONE : Z O N E ;
lexer grammar SQLServerKeyword; import Symbol; ABORT_AFTER_WAIT : A B O R T UL_ A F T E R UL_ W A I T ; ACTION : A C T I O N ; 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 ; ASYMMETRIC : A S Y M M E T R I C ; AUTHORIZATION : A U T H O R I Z A T I O N ; AUTO : A U T O ; BACKSLASH : B A C K S L A S H ; BEGIN : B E G I N ; BLOCKERS : B L O C K E R S ; BUCKET_COUNT : B U C K E T UL_ C O U N T ; CAST : C A S T ; CERTIFICATE : C E R T I F I C A T E ; CLUSTERED : C L U S T E R E D ; COLLATE : C O L L A T E ; 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 ; CONVERT : C O N V E R T ; CREDENTIAL : C R E D E N T I A L ; DATABASE : D A T A B A S E ; DATABASE_DEAULT : D A T A B A S E UL_ D E A U L 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 ; DAYS : D A Y S ; DEFAULT_DATABASE : D E F A U L T UL_ D A T A B A S E ; DELAYED_DURABILITY : D E L A Y E D UL_ D U R A B I L I T Y ; DENY : D E N Y ; DETERMINISTIC : D E T E R M I N I S T I C ; DISTRIBUTION : D I S T R I B U T I O N ; DOCUMENT : D O C U M E N T ; DROP_EXISTING : D R O P UL_ E X I S T I N G ; DURABILITY : D U R A B I L I T Y ; DW : D W ; 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 ; END : E N D ; EXTERNAL : E X T E R N A L ; 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 : F I L E T A B L E ; 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 ; FILLFACTOR : F I L L F A C T O R ; FILTER_PREDICATE : F I L T E R UL_ P R E D I C A T E ; FOLLOWING : F O L L O W I N G ; FOR : F O R ; FUNCTION : F U N C T I O N ; GRANT : G R A N T ; HASH : H A S H ; HASHED : H A S H E D ; HEAP : H E A P ; HIDDEN_ : H I D D E N UL_ ; 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 ; HISTORY_TABLE : H I S T O R Y UL_ T A B L E ; IDENTITY : I D E N T I T Y ; 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 ; INFINITE : I N F I N I T E ; LEFT : L E F T ; LEFT_BRACKET : L E F T UL_ B R A C K E T ; LOCK_ESCALATION : L O C K UL_ E S C A L A T I O N ; LOGIN : L O G I N ; MARK : M A R K ; MASKED : M A S K E D ; MAX : M A X ; MAXDOP : M A X D O P ; MAX_DURATION : M A X UL_ D U R A T I O N ; MEMBER : M E M B E R ; 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 ; MINUTES : M I N U T E S ; MONTH : M O N T H ; MONTHS : M O N T H S ; MOVE : M O V E ; MUST_CHANGE : M U S T UL_ C H A N G E ; NAME : N A M E ; NOCHECK : N O C H E C K ; NONCLUSTERED : N O N C L U S T E R E D ; NONE : N O N E ; OBJECT : O B J E C T ; OFF : O F F ; OLD_PASSWORD : O L D UL_ P A S S W O R D ; ONLINE : O N L I N E ; OPTION : O P T I O N ; OUTBOUND : O U T B O U N D ; OVER : O V E R ; 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 ; PASSWORD : P A S S W O R D ; PAUSED : P A U S E D ; PERIOD : P E R I O D ; PERSISTED : P E R S I S T E D ; PRECEDING : P R E C E D I N G ; PRIVILEGES : P R I V I L E G E S ; PROVIDER : P R O V I D E R ; RANDOMIZED : R A N D O M I Z E D ; RANGE : R A N G E ; REBUILD : R E B U I L D ; REMOTE_DATA_ARCHIVE : R E M O T E UL_ D A T A UL_ A R C H I V E ; REPEATABLE : R E P E A T A B L E ; REPLICATE : R E P L I C A T E ; REPLICATION : R E P L I C A T I O N ; RESUMABLE : R E S U M A B L E ; REVOKE : R E V O K E ; RIGHT : R I G H T ; RIGHT_BRACKET : R I G H T UL_ B R A C K E T ; ROLE : R O L E ; ROUND_ROBIN : R O U N D UL_ R O B I N ; ROWGUIDCOL : R O W G U I D C O L ; ROWS : R O W S ; SAVE : S A V E ; SCHEMA : S C H E M A ; 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 ; SELF : S E L F ; SNAPSHOT : S N A P S H O T ; SORT_IN_TEMPDB : S O R T UL_ I N UL_ T E M P D B ; SPARSE : S P A R S E ; 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 ; SWITCH : S W I T C H ; 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 ; TRAN : T R A N ; TRIGGER : T R I G G E R ; UNBOUNDED : U N B O U N D E D ; UNCOMMITTED : U N C O M M I T T E D ; UNLOCK : U N L O C K ; UPDATE : U P D A T E ; VALUES : V A L U E S ; 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 ; WINDOWS : W I N D O W S ; WITHOUT : W I T H O U T ; YEARS : Y E A R S ; ZONE : Z O N E ;
add keyword
add keyword
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
fe4c9c6e0a69889a179f4cf82019989848463d02
antlr3/ANTLRv3.g4
antlr3/ANTLRv3.g4
/* [The "BSD licence"] Copyright (c) 2005-2007 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. */ grammar ANTLRv3; grammarDef : DOC_COMMENT? ('lexer' | 'parser' | 'tree')? 'grammar' id ';' optionsSpec? tokensSpec? attrScope* action* rule_ + ; tokensSpec : TOKENS tokenSpec + '}' ; tokenSpec : TOKEN_REF ('=' (STRING_LITERAL | CHAR_LITERAL) |) ';' ; attrScope : 'scope' id ACTION ; action : '@' (actionScopeName '::')? id ACTION ; actionScopeName : id | 'lexer' | 'parser' ; optionsSpec : OPTIONS (option ';') + '}' ; option : id '=' optionValue ; optionValue : id | STRING_LITERAL | CHAR_LITERAL | INT | '*' ; rule_ : DOC_COMMENT? (('protected' | 'public' | 'private' | 'fragment'))? id '!'? (ARG_ACTION)? ('returns' ARG_ACTION)? throwsSpec? optionsSpec? ruleScopeSpec? ruleAction* ':' altList? ';' exceptionGroup? ; ruleAction : '@' id ACTION ; throwsSpec : 'throws' id (',' id)* ; ruleScopeSpec : 'scope' ACTION | 'scope' id (',' id)* ';' | 'scope' ACTION 'scope' id (',' id)* ';' ; block : '(' ((optionsSpec)? ':')? alternative? rewrite? ('|' (alternative rewrite?)?)* ')' ; altList : alternative rewrite? ('|' (alternative rewrite?)?)* ; alternative : element + ; exceptionGroup : (exceptionHandler) + (finallyClause)? | finallyClause ; exceptionHandler : 'catch' ARG_ACTION ACTION ; finallyClause : 'finally' ACTION ; element : elementNoOptionSpec ; elementNoOptionSpec : id ('=' | '+=') atom (ebnfSuffix?) | id ('=' | '+=') block (ebnfSuffix?) | atom (ebnfSuffix?) | ebnf | ACTION | SEMPRED ('=>') | treeSpec (ebnfSuffix) ; atom : range | terminal_ | notSet | RULE_REF (ARG_ACTION)? ; notSet : '~' (notTerminal | block) ; treeSpec : '^(' element (element) + ')' ; ebnf : block ('?' | '*' | '+' | '=>')? ; range : CHAR_LITERAL RANGE CHAR_LITERAL ; terminal_ : (CHAR_LITERAL | TOKEN_REF (ARG_ACTION?) | STRING_LITERAL | '.') ('^' | '!')? ; notTerminal : CHAR_LITERAL | TOKEN_REF | STRING_LITERAL ; ebnfSuffix : '?' | '*' | '+' ; rewrite : ('->' SEMPREDrewrite_alternative)* '->' rewrite_alternative ; rewrite_alternative : rewrite_template | rewrite_tree_alternative ; rewrite_tree_block : '(' rewrite_tree_alternative ')' ; rewrite_tree_alternative : rewrite_tree_element + ; rewrite_tree_element : rewrite_tree_atom | rewrite_tree_atom ebnfSuffix | rewrite_tree (ebnfSuffix) | rewrite_tree_ebnf ; rewrite_tree_atom : CHAR_LITERAL | TOKEN_REF ARG_ACTION? | RULE_REF | STRING_LITERAL | '$' id | ACTION ; rewrite_tree_ebnf : rewrite_tree_block ebnfSuffix ; rewrite_tree : '^(' rewrite_tree_atom rewrite_tree_element* ')' ; rewrite_template : ; rewrite_template_ref : id '(' rewrite_template_args ')' ; rewrite_indirect_template_head : '(' ACTION ')' '(' rewrite_template_args ')' ; rewrite_template_args : rewrite_template_arg (',' rewrite_template_arg)* ; rewrite_template_arg : id '=' ACTION ; id : TOKEN_REF | RULE_REF ; CHAR_LITERAL : '\'' LITERAL_CHAR '\'' ; STRING_LITERAL : '\'' LITERAL_CHAR LITERAL_CHAR* '\'' ; fragment LITERAL_CHAR : ESC | ~ ('\'' | '\\') ; DOUBLE_QUOTE_STRING_LITERAL : '"' (ESC | ~ ('\\' | '"'))* '"' ; DOUBLE_ANGLE_STRING_LITERAL : '<<' ()*? '>>' ; fragment ESC : '\\' ('n' | 'r' | 't' | 'b' | 'f' | '"' | '\'' | '\\' | '>' | 'u' XDIGIT XDIGIT XDIGIT XDIGIT | .) ; fragment XDIGIT : '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' ; INT : '0' .. '9' + ; ARG_ACTION : NESTED_ARG_ACTION ; fragment NESTED_ARG_ACTION : '[' (NESTED_ARG_ACTION | ACTION_STRING_LITERAL | ACTION_CHAR_LITERAL | .)*? ']' ; ACTION : NESTED_ACTION ('?')? ; fragment NESTED_ACTION : '{' (NESTED_ACTION | SL_COMMENT | ML_COMMENT | ACTION_STRING_LITERAL | ACTION_CHAR_LITERAL | .)*? '}' ; fragment ACTION_CHAR_LITERAL : '\'' (ACTION_ESC | ~ ('\\' | '\'')) '\'' ; fragment ACTION_STRING_LITERAL : '"' (ACTION_ESC | ~ ('\\' | '"'))* '"' ; fragment ACTION_ESC : '\\\'' | '\\' '"' | '\\' ~ ('\'' | '"') ; OPTIONS : 'options' WS_LOOP '{' ; TOKENS : 'tokens' WS_LOOP '{' ; fragment SRC : 'src' ' ' ACTION_STRING_LITERAL ' ' INT ; fragment WS_LOOP : (WS | SL_COMMENT | ML_COMMENT)* ; DOC_COMMENT : 'DOC_COMMENT' ; PARSER : 'PARSER' ; LEXER : 'LEXER' ; RULE : 'RULE' ; BLOCK : 'BLOCK' ; OPTIONAL : 'OPTIONAL' ; CLOSURE : 'CLOSURE' ; POSITIVE_CLOSURE : 'POSITIVE_CLOSURE' ; SYNPRED : 'SYNPRED' ; CHAR_RANGE : 'CHAR_RANGE' ; EPSILON : 'EPSILON' ; ALT : 'ALT' ; EOR : 'EOR' ; EOB : 'EOB' ; EOA : 'EOA' ; // end of alt ID : 'ID' ; ARG : 'ARG' ; ARGLIST : 'ARGLIST' ; RET : 'RET' ; LEXER_GRAMMAR : 'LEXER_GRAMMAR' ; PARSER_GRAMMAR : 'PARSER_GRAMMAR' ; TREE_GRAMMAR : 'TREE_GRAMMAR' ; COMBINED_GRAMMAR : 'COMBINED_GRAMMAR' ; INITACTION : 'INITACTION' ; LABEL : 'LABEL' ; TEMPLATE : 'TEMPLATE' ; SCOPE : 'scope' ; SEMPRED : 'SEMPRED' ; GATED_SEMPRED : 'GATED_SEMPRED' ; SYN_SEMPRED : 'SYN_SEMPRED' ; BACKTRACK_SEMPRED : 'BACKTRACK_SEMPRED' ; FRAGMENT : 'fragment' ; TREE_BEGIN : '^(' ; ROOT : '^' ; BANG : '!' ; RANGE : '..' ; REWRITE : '->' ; SL_COMMENT : '//' ~ [\r\n]* -> skip ; ML_COMMENT : '/*' .*? '*/' -> skip ; WS : (' ' | '\t' | '\r'? '\n') + -> skip ; TOKEN_REF : 'A' .. 'Z' ('a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9')* ; RULE_REF : 'a' .. 'z' ('a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9')* ;
/* [The "BSD licence"] Copyright (c) 2005-2007 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. */ grammar ANTLRv3; grammarDef : DOC_COMMENT? ('lexer' | 'parser' | 'tree')? 'grammar' id ';' optionsSpec? tokensSpec? attrScope* action* rule_+ ; tokensSpec : TOKENS tokenSpec+ '}' ; tokenSpec : TOKEN_REF ('=' (STRING_LITERAL | CHAR_LITERAL) |) ';' ; attrScope : 'scope' id ACTION ; action : '@' (actionScopeName '::')? id ACTION ; actionScopeName : id | 'lexer' | 'parser' ; optionsSpec : OPTIONS (option ';')+ '}' ; option : id '=' optionValue ; optionValue : id | STRING_LITERAL | CHAR_LITERAL | INT | '*' ; rule_ : DOC_COMMENT? (('protected' | 'public' | 'private' | 'fragment'))? id '!'? (ARG_ACTION)? ('returns' ARG_ACTION)? throwsSpec? optionsSpec? ruleScopeSpec? ruleAction* ':' altList? ';' exceptionGroup? ; ruleAction : '@' id ACTION ; throwsSpec : 'throws' id (',' id)* ; ruleScopeSpec : 'scope' ACTION | 'scope' id (',' id)* ';' | 'scope' ACTION 'scope' id (',' id)* ';' ; block : '(' ((optionsSpec)? ':')? alternative? rewrite? ('|' (alternative rewrite?)?)* ')' ; altList : alternative rewrite? ('|' (alternative rewrite?)?)* ; alternative : element+ ; exceptionGroup : (exceptionHandler)+ (finallyClause)? | finallyClause ; exceptionHandler : 'catch' ARG_ACTION ACTION ; finallyClause : 'finally' ACTION ; element : elementNoOptionSpec ; elementNoOptionSpec : id ('=' | '+=') atom (ebnfSuffix?) | id ('=' | '+=') block (ebnfSuffix?) | atom (ebnfSuffix?) | ebnf | ACTION | SEMPRED ('=>') | treeSpec (ebnfSuffix) ; atom : range | terminal_ | notSet | RULE_REF (ARG_ACTION)? ; notSet : '~' (notTerminal | block) ; treeSpec : '^(' element (element)+ ')' ; ebnf : block ('?' | '*' | '+' | '=>')? ; range : CHAR_LITERAL RANGE CHAR_LITERAL ; terminal_ : (CHAR_LITERAL | TOKEN_REF (ARG_ACTION?) | STRING_LITERAL | '.') ('^' | '!')? ; notTerminal : CHAR_LITERAL | TOKEN_REF | STRING_LITERAL ; ebnfSuffix : '?' | '*' | '+' ; rewrite : ('->' SEMPREDrewrite_alternative)* '->' rewrite_alternative ; rewrite_alternative : rewrite_template | rewrite_tree_alternative ; rewrite_tree_block : '(' rewrite_tree_alternative ')' ; rewrite_tree_alternative : rewrite_tree_element+ ; rewrite_tree_element : rewrite_tree_atom | rewrite_tree_atom ebnfSuffix | rewrite_tree (ebnfSuffix) | rewrite_tree_ebnf ; rewrite_tree_atom : CHAR_LITERAL | TOKEN_REF ARG_ACTION? | RULE_REF | STRING_LITERAL | '$' id | ACTION ; rewrite_tree_ebnf : rewrite_tree_block ebnfSuffix ; rewrite_tree : '^(' rewrite_tree_atom rewrite_tree_element* ')' ; rewrite_template : ; rewrite_template_ref : id '(' rewrite_template_args ')' ; rewrite_indirect_template_head : '(' ACTION ')' '(' rewrite_template_args ')' ; rewrite_template_args : rewrite_template_arg (',' rewrite_template_arg)* ; rewrite_template_arg : id '=' ACTION ; id : TOKEN_REF | RULE_REF ; CHAR_LITERAL : '\'' LITERAL_CHAR '\'' ; STRING_LITERAL : '\'' LITERAL_CHAR LITERAL_CHAR* '\'' ; fragment LITERAL_CHAR : ESC | ~ ('\'' | '\\') ; DOUBLE_QUOTE_STRING_LITERAL : '"' (ESC | ~ ('\\' | '"'))* '"' ; DOUBLE_ANGLE_STRING_LITERAL : '<<' ()*? '>>' ; fragment ESC : '\\' ('n' | 'r' | 't' | 'b' | 'f' | '"' | '\'' | '\\' | '>' | 'u' XDIGIT XDIGIT XDIGIT XDIGIT | .) ; fragment XDIGIT : '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' ; INT : '0' .. '9'+ ; ARG_ACTION : NESTED_ARG_ACTION ; fragment NESTED_ARG_ACTION : '[' (NESTED_ARG_ACTION | ACTION_STRING_LITERAL | ACTION_CHAR_LITERAL | .)*? ']' ; ACTION : NESTED_ACTION ('?')? ; fragment NESTED_ACTION : '{' (NESTED_ACTION | SL_COMMENT | ML_COMMENT | ACTION_STRING_LITERAL | ACTION_CHAR_LITERAL | .)*? '}' ; fragment ACTION_CHAR_LITERAL : '\'' (ACTION_ESC | ~ ('\\' | '\'')) '\'' ; fragment ACTION_STRING_LITERAL : '"' (ACTION_ESC | ~ ('\\' | '"'))* '"' ; fragment ACTION_ESC : '\\\'' | '\\' '"' | '\\' ~ ('\'' | '"') ; OPTIONS : 'options' WS_LOOP '{' ; TOKENS : 'tokens' WS_LOOP '{' ; fragment SRC : 'src' ' ' ACTION_STRING_LITERAL ' ' INT ; fragment WS_LOOP : (WS | SL_COMMENT | ML_COMMENT)* ; DOC_COMMENT : 'DOC_COMMENT' ; PARSER : 'PARSER' ; LEXER : 'LEXER' ; RULE : 'RULE' ; BLOCK : 'BLOCK' ; OPTIONAL : 'OPTIONAL' ; CLOSURE : 'CLOSURE' ; POSITIVE_CLOSURE : 'POSITIVE_CLOSURE' ; SYNPRED : 'SYNPRED' ; CHAR_RANGE : 'CHAR_RANGE' ; EPSILON : 'EPSILON' ; ALT : 'ALT' ; EOR : 'EOR' ; EOB : 'EOB' ; EOA : 'EOA' ; // end of alt ID : 'ID' ; ARG : 'ARG' ; ARGLIST : 'ARGLIST' ; RET : 'RET' ; LEXER_GRAMMAR : 'LEXER_GRAMMAR' ; PARSER_GRAMMAR : 'PARSER_GRAMMAR' ; TREE_GRAMMAR : 'TREE_GRAMMAR' ; COMBINED_GRAMMAR : 'COMBINED_GRAMMAR' ; INITACTION : 'INITACTION' ; LABEL : 'LABEL' ; TEMPLATE : 'TEMPLATE' ; SCOPE : 'scope' ; SEMPRED : 'SEMPRED' ; GATED_SEMPRED : 'GATED_SEMPRED' ; SYN_SEMPRED : 'SYN_SEMPRED' ; BACKTRACK_SEMPRED : 'BACKTRACK_SEMPRED' ; FRAGMENT : 'fragment' ; TREE_BEGIN : '^(' ; ROOT : '^' ; BANG : '!' ; RANGE : '..' ; REWRITE : '->' ; SL_COMMENT : '//' ~ [\r\n]* -> skip ; ML_COMMENT : '/*' .*? '*/' -> skip ; WS : (' ' | '\t' | '\r'? '\n')+ -> skip ; TOKEN_REF : 'A' .. 'Z' ('a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9')* ; RULE_REF : 'a' .. 'z' ('a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9')* ;
format Antlr3
format Antlr3
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
9fa3b66c5caa0e937ea69f6f76bdb0b87845b989
pattern_grammar/STIXPattern.g4
pattern_grammar/STIXPattern.g4
// This is an ANTLR4 grammar for the STIX Patterning Language. // // http://docs.oasis-open.org/cti/stix/v2.0/stix-v2.0-part5-stix-patterning.html grammar STIXPattern; pattern : observationExpressions ; observationExpressions : <assoc=left> observationExpressions FOLLOWEDBY observationExpressions | observationExpressionOr ; observationExpressionOr : <assoc=left> observationExpressionOr OR observationExpressionOr | observationExpressionAnd ; observationExpressionAnd : <assoc=left> observationExpressionAnd AND observationExpressionAnd | observationExpression ; observationExpression : LBRACK comparisonExpression RBRACK # observationExpressionSimple | LPAREN observationExpressions RPAREN # observationExpressionCompound | observationExpression startStopQualifier # observationExpressionStartStop | observationExpression withinQualifier # observationExpressionWithin | observationExpression repeatedQualifier # observationExpressionRepeated ; comparisonExpression : <assoc=left> comparisonExpression OR comparisonExpression | comparisonExpressionAnd ; comparisonExpressionAnd : <assoc=left> comparisonExpressionAnd AND comparisonExpressionAnd | propTest ; propTest : objectPath NOT? (EQ|NEQ) primitiveLiteral # propTestEqual | objectPath NOT? (GT|LT|GE|LE) orderableLiteral # propTestOrder | objectPath NOT? IN setLiteral # propTestSet | objectPath NOT? LIKE StringLiteral # propTestLike | objectPath NOT? MATCHES StringLiteral # propTestRegex | objectPath NOT? ISSUBSET StringLiteral # propTestIsSubset | objectPath NOT? ISSUPERSET StringLiteral # propTestIsSuperset | LPAREN comparisonExpression RPAREN # propTestParen ; startStopQualifier : START StringLiteral STOP StringLiteral ; withinQualifier : WITHIN (IntPosLiteral|FloatPosLiteral) SECONDS ; repeatedQualifier : REPEATS IntPosLiteral TIMES ; objectPath : objectType COLON firstPathComponent objectPathComponent? ; objectType : IdentifierWithoutHyphen | IdentifierWithHyphen ; firstPathComponent : IdentifierWithoutHyphen | StringLiteral ; objectPathComponent : <assoc=left> objectPathComponent objectPathComponent # pathStep | '.' (IdentifierWithoutHyphen | StringLiteral) # keyPathStep | LBRACK (IntPosLiteral|IntNegLiteral|ASTERISK) RBRACK # indexPathStep ; setLiteral : LPAREN RPAREN | LPAREN primitiveLiteral (COMMA primitiveLiteral)* RPAREN ; primitiveLiteral : orderableLiteral | BoolLiteral ; orderableLiteral : IntPosLiteral | IntNegLiteral | FloatPosLiteral | FloatNegLiteral | StringLiteral | BinaryLiteral | HexLiteral | TimestampLiteral ; IntNegLiteral : '-' ('0' | [1-7] [0-9]*) ; IntPosLiteral : '+'? ('0' | [1-8] [0-9]*) ; FloatNegLiteral : '-' [0-9]* '.' [0-9]+ ; FloatPosLiteral : '+'? [0-9]* '.' [0-9]+ ; HexLiteral : 'h' QUOTE TwoHexDigits* QUOTE ; BinaryLiteral : 'b' QUOTE Base64Char* QUOTE ; StringLiteral : QUOTE ( ~['\\] | '\\\'' | '\\\\' )* QUOTE ; BoolLiteral : TRUE | FALSE ; TimestampLiteral : 't' QUOTE [0-9] [0-9] [0-9] [0-9] HYPHEN ( ('0' [1-9]) | ('1' [012]) ) HYPHEN ( ('0' [1-9]) | ([12] [0-9]) | ('3' [01]) ) 'T' ( ([01] [0-9]) | ('2' [0-3]) ) COLON [0-5] [0-9] COLON ([0-5] [0-9] | '60') (DOT [0-9]+)? 'Z' QUOTE ; ////////////////////////////////////////////// // Keywords AND: A N D; OR: O R; NOT: N O T; FOLLOWEDBY: F O L L O W E D B Y; LIKE: L I K E ; MATCHES: M A T C H E S ; ISSUPERSET: I S S U P E R S E T ; ISSUBSET: I S S U B S E T ; LAST: L A S T ; IN: I N; START: S T A R T ; STOP: S T O P ; SECONDS: S E C O N D S; TRUE: T R U E; FALSE: F A L S E; WITHIN: W I T H I N; REPEATS: R E P E A T S; TIMES: T I M E S; // After keywords, so the lexer doesn't tokenize them as identifiers. // Object types may have unquoted hyphens, but property names // (in object paths) cannot. IdentifierWithoutHyphen : [a-zA-Z_] [a-zA-Z0-9_]* ; IdentifierWithHyphen : [a-zA-Z_] [a-zA-Z0-9_-]* ; EQ : '=' | '=='; NEQ : '!=' | '<>'; LT : '<'; LE : '<='; GT : '>'; GE : '>='; QUOTE : '\''; COLON : ':' ; DOT : '.' ; COMMA : ',' ; RPAREN : ')' ; LPAREN : '(' ; RBRACK : ']' ; LBRACK : '[' ; PLUS : '+' ; HYPHEN : MINUS ; MINUS : '-' ; POWER_OP : '^' ; DIVIDE : '/' ; ASTERISK : '*'; fragment A: [aA]; fragment B: [bB]; fragment C: [cC]; fragment D: [dD]; fragment E: [eE]; fragment F: [fF]; fragment G: [gG]; fragment H: [hH]; fragment I: [iI]; fragment J: [jJ]; fragment K: [kK]; fragment L: [lL]; fragment M: [mM]; fragment N: [nN]; fragment O: [oO]; fragment P: [pP]; fragment Q: [qQ]; fragment R: [rR]; fragment S: [sS]; fragment T: [tT]; fragment U: [uU]; fragment V: [vV]; fragment W: [wW]; fragment X: [xX]; fragment Y: [yY]; fragment Z: [zZ]; fragment HexDigit: [A-Fa-f0-9]; fragment TwoHexDigits: HexDigit HexDigit; fragment Base64Char: [A-Za-z0-9+/=]; // Whitespace and comments // WS : [ \t\r\n\u000B\u000C\u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+ -> skip ; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '//' ~[\r\n]* -> skip ; // Catch-all to prevent lexer from silently eating unusable characters. InvalidCharacter : . ;
// This is an ANTLR4 grammar for the STIX Patterning Language. // // http://docs.oasis-open.org/cti/stix/v2.0/stix-v2.0-part5-stix-patterning.html grammar STIXPattern; pattern : observationExpressions ; observationExpressions : <assoc=left> observationExpressions FOLLOWEDBY observationExpressions | observationExpressionOr ; observationExpressionOr : <assoc=left> observationExpressionOr OR observationExpressionOr | observationExpressionAnd ; observationExpressionAnd : <assoc=left> observationExpressionAnd AND observationExpressionAnd | observationExpression ; observationExpression : LBRACK comparisonExpression RBRACK # observationExpressionSimple | LPAREN observationExpressions RPAREN # observationExpressionCompound | observationExpression startStopQualifier # observationExpressionStartStop | observationExpression withinQualifier # observationExpressionWithin | observationExpression repeatedQualifier # observationExpressionRepeated ; comparisonExpression : <assoc=left> comparisonExpression OR comparisonExpression | comparisonExpressionAnd ; comparisonExpressionAnd : <assoc=left> comparisonExpressionAnd AND comparisonExpressionAnd | propTest ; propTest : objectPath NOT? (EQ|NEQ) primitiveLiteral # propTestEqual | objectPath NOT? (GT|LT|GE|LE) orderableLiteral # propTestOrder | objectPath NOT? IN setLiteral # propTestSet | objectPath NOT? LIKE StringLiteral # propTestLike | objectPath NOT? MATCHES StringLiteral # propTestRegex | objectPath NOT? ISSUBSET StringLiteral # propTestIsSubset | objectPath NOT? ISSUPERSET StringLiteral # propTestIsSuperset | LPAREN comparisonExpression RPAREN # propTestParen ; startStopQualifier : START StringLiteral STOP StringLiteral ; withinQualifier : WITHIN (IntPosLiteral|FloatPosLiteral) SECONDS ; repeatedQualifier : REPEATS IntPosLiteral TIMES ; objectPath : objectType COLON firstPathComponent objectPathComponent? ; objectType : IdentifierWithoutHyphen | IdentifierWithHyphen ; firstPathComponent : IdentifierWithoutHyphen | StringLiteral ; objectPathComponent : <assoc=left> objectPathComponent objectPathComponent # pathStep | '.' (IdentifierWithoutHyphen | StringLiteral) # keyPathStep | LBRACK (IntPosLiteral|IntNegLiteral|ASTERISK) RBRACK # indexPathStep ; setLiteral : LPAREN RPAREN | LPAREN primitiveLiteral (COMMA primitiveLiteral)* RPAREN ; primitiveLiteral : orderableLiteral | BoolLiteral ; orderableLiteral : IntPosLiteral | IntNegLiteral | FloatPosLiteral | FloatNegLiteral | StringLiteral | BinaryLiteral | HexLiteral | TimestampLiteral ; IntNegLiteral : '-' ('0' | [1-7] [0-9]*) ; IntPosLiteral : '+'? ('0' | [1-8] [0-9]*) ; FloatNegLiteral : '-' [0-9]* '.' [0-9]+ ; FloatPosLiteral : '+'? [0-9]* '.' [0-9]+ ; HexLiteral : 'h' QUOTE TwoHexDigits* QUOTE ; BinaryLiteral : 'b' QUOTE ( Base64Char Base64Char Base64Char Base64Char )* ( (Base64Char Base64Char Base64Char Base64Char ) | (Base64Char Base64Char Base64Char ) '=' | (Base64Char Base64Char ) '==' ) QUOTE ; StringLiteral : QUOTE ( ~['\\] | '\\\'' | '\\\\' )* QUOTE ; BoolLiteral : TRUE | FALSE ; TimestampLiteral : 't' QUOTE [0-9] [0-9] [0-9] [0-9] HYPHEN ( ('0' [1-9]) | ('1' [012]) ) HYPHEN ( ('0' [1-9]) | ([12] [0-9]) | ('3' [01]) ) 'T' ( ([01] [0-9]) | ('2' [0-3]) ) COLON [0-5] [0-9] COLON ([0-5] [0-9] | '60') (DOT [0-9]+)? 'Z' QUOTE ; ////////////////////////////////////////////// // Keywords AND: A N D; OR: O R; NOT: N O T; FOLLOWEDBY: F O L L O W E D B Y; LIKE: L I K E ; MATCHES: M A T C H E S ; ISSUPERSET: I S S U P E R S E T ; ISSUBSET: I S S U B S E T ; LAST: L A S T ; IN: I N; START: S T A R T ; STOP: S T O P ; SECONDS: S E C O N D S; TRUE: T R U E; FALSE: F A L S E; WITHIN: W I T H I N; REPEATS: R E P E A T S; TIMES: T I M E S; // After keywords, so the lexer doesn't tokenize them as identifiers. // Object types may have unquoted hyphens, but property names // (in object paths) cannot. IdentifierWithoutHyphen : [a-zA-Z_] [a-zA-Z0-9_]* ; IdentifierWithHyphen : [a-zA-Z_] [a-zA-Z0-9_-]* ; EQ : '=' | '=='; NEQ : '!=' | '<>'; LT : '<'; LE : '<='; GT : '>'; GE : '>='; QUOTE : '\''; COLON : ':' ; DOT : '.' ; COMMA : ',' ; RPAREN : ')' ; LPAREN : '(' ; RBRACK : ']' ; LBRACK : '[' ; PLUS : '+' ; HYPHEN : MINUS ; MINUS : '-' ; POWER_OP : '^' ; DIVIDE : '/' ; ASTERISK : '*'; fragment A: [aA]; fragment B: [bB]; fragment C: [cC]; fragment D: [dD]; fragment E: [eE]; fragment F: [fF]; fragment G: [gG]; fragment H: [hH]; fragment I: [iI]; fragment J: [jJ]; fragment K: [kK]; fragment L: [lL]; fragment M: [mM]; fragment N: [nN]; fragment O: [oO]; fragment P: [pP]; fragment Q: [qQ]; fragment R: [rR]; fragment S: [sS]; fragment T: [tT]; fragment U: [uU]; fragment V: [vV]; fragment W: [wW]; fragment X: [xX]; fragment Y: [yY]; fragment Z: [zZ]; fragment HexDigit: [A-Fa-f0-9]; fragment TwoHexDigits: HexDigit HexDigit; fragment Base64Char: [A-Za-z0-9+/]; // Whitespace and comments // WS : [ \t\r\n\u000B\u000C\u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+ -> skip ; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '//' ~[\r\n]* -> skip ; // Catch-all to prevent lexer from silently eating unusable characters. InvalidCharacter : . ;
Update patterning grammar definition for Base64
Update patterning grammar definition for Base64
ANTLR
bsd-3-clause
oasis-open/cti-stix2-json-schemas
55c42c5963fbfa5ad3631cedca7882d3e0ea3a50
sql/hive/v3/IdentifiersParser.g4
sql/hive/v3/IdentifiersParser.g4
/** Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @author Canwei He */ parser grammar IdentifiersParser; //----------------------------------------------------------------------------------- // group by a,b groupByClause : KW_GROUP KW_BY groupby_expression ; // support for new and old rollup/cube syntax groupby_expression : rollupStandard | rollupOldSyntax | groupByEmpty ; groupByEmpty : LPAREN RPAREN ; // standard rollup syntax rollupStandard : (KW_ROLLUP | KW_CUBE) LPAREN expression ( COMMA expression)* RPAREN ; // old hive rollup syntax rollupOldSyntax : expressionsNotInParenthesis (KW_WITH KW_ROLLUP | KW_WITH KW_CUBE) ? (KW_GROUPING KW_SETS LPAREN groupingSetExpression ( COMMA groupingSetExpression)* RPAREN ) ? ; groupingSetExpression : groupingSetExpressionMultiple | groupingExpressionSingle ; groupingSetExpressionMultiple : LPAREN expression? (COMMA expression)* RPAREN ; groupingExpressionSingle : expression ; havingClause : KW_HAVING havingCondition ; havingCondition : expression ; expressionsInParenthesis : LPAREN expressionsNotInParenthesis RPAREN ; expressionsNotInParenthesis : expression expressionPart? ; expressionPart : (COMMA expression)+ ; expressions : expressionsInParenthesis | expressionsNotInParenthesis ; columnRefOrderInParenthesis : LPAREN columnRefOrder (COMMA columnRefOrder)* RPAREN ; columnRefOrderNotInParenthesis : columnRefOrder (COMMA columnRefOrder)* ; // order by a,b orderByClause : KW_ORDER KW_BY columnRefOrder ( COMMA columnRefOrder)* ; clusterByClause : KW_CLUSTER KW_BY expressions ; partitionByClause : KW_PARTITION KW_BY expressions ; distributeByClause : KW_DISTRIBUTE KW_BY expressions ; sortByClause : KW_SORT KW_BY ( columnRefOrderInParenthesis | columnRefOrderNotInParenthesis ) ; // fun(par1, par2, par3) function_ : functionName LPAREN ( STAR | (KW_DISTINCT | KW_ALL)? (selectExpression (COMMA selectExpression)*)? ) RPAREN (KW_OVER window_specification)? ; functionName : // Keyword IF is also a function name functionIdentifier | sql11ReservedKeywordsUsedAsFunctionName ; castExpression : KW_CAST LPAREN expression KW_AS primitiveType RPAREN ; caseExpression : KW_CASE expression (KW_WHEN expression KW_THEN expression)+ (KW_ELSE expression)? KW_END ; whenExpression : KW_CASE ( KW_WHEN expression KW_THEN expression)+ (KW_ELSE expression)? KW_END ; floorExpression : KW_FLOOR LPAREN expression (KW_TO floorDateQualifiers)? RPAREN ; floorDateQualifiers : KW_YEAR | KW_QUARTER | KW_MONTH | KW_WEEK | KW_DAY | KW_HOUR | KW_MINUTE | KW_SECOND ; extractExpression : KW_EXTRACT LPAREN timeQualifiers KW_FROM expression RPAREN ; timeQualifiers : KW_YEAR | KW_QUARTER | KW_MONTH | KW_WEEK | KW_DAY | KW_DOW | KW_HOUR | KW_MINUTE | KW_SECOND ; constant : intervalLiteral | Number | dateLiteral | timestampLiteral | timestampLocalTZLiteral | StringLiteral | stringLiteralSequence | IntegralLiteral | NumberLiteral | charSetStringLiteral | booleanValue | KW_NULL ; stringLiteralSequence : StringLiteral StringLiteral+ ; charSetStringLiteral : CharSetName CharSetLiteral ; dateLiteral : KW_DATE StringLiteral | KW_CURRENT_DATE ; timestampLiteral : KW_TIMESTAMP StringLiteral | KW_CURRENT_TIMESTAMP ; timestampLocalTZLiteral : KW_TIMESTAMPLOCALTZ StringLiteral ; intervalValue : StringLiteral | Number ; intervalLiteral : intervalValue intervalQualifiers ; intervalExpression : LPAREN intervalValue RPAREN intervalQualifiers | KW_INTERVAL intervalValue intervalQualifiers | KW_INTERVAL LPAREN expression RPAREN intervalQualifiers ; intervalQualifiers : KW_YEAR KW_TO KW_MONTH | KW_DAY KW_TO KW_SECOND | KW_YEAR | KW_MONTH | KW_DAY | KW_HOUR | KW_MINUTE | KW_SECOND ; atomExpression : constant | intervalExpression | castExpression | extractExpression | floorExpression | caseExpression | whenExpression | subQueryExpression | function_ | tableOrColumn | expressionsInParenthesis ; precedenceUnaryOperator : PLUS | MINUS | TILDE ; isCondition : KW_NOT? (KW_NULL | KW_TRUE | KW_FALSE | KW_DISTINCT KW_FROM) ; precedenceBitwiseXorOperator : BITWISEXOR ; precedenceStarOperator : STAR | DIVIDE | MOD | DIV ; precedencePlusOperator : PLUS | MINUS ; precedenceConcatenateOperator : CONCATENATE ; precedenceAmpersandOperator : AMPERSAND ; precedenceBitwiseOrOperator : BITWISEOR ; precedenceRegexpOperator : KW_LIKE | KW_RLIKE | KW_REGEXP ; precedenceComparisonOperator : LESSTHANOREQUALTO | LESSTHAN | GREATERTHANOREQUALTO | GREATERTHAN | EQUAL | EQUAL_NS | NOTEQUAL ; precedenceNotOperator : KW_NOT ; precedenceLogicOperator : KW_AND | KW_OR ; //precedenceFieldExpression //precedenceUnaryPrefixExpression //precedenceUnarySuffixExpression //precedenceBitwiseXorExpression //precedenceStarExpression //precedencePlusExpression //precedenceConcatenateExpression //precedenceAmpersandExpression //precedenceBitwiseOrExpression //precedenceSimilarExpressionMain //precedenceSimilarExpression //precedenceEqualExpression //precedenceNotExpression //precedenceAndExpression //precedenceOrExpression expression : atomExpression ((LSQUARE expression RSQUARE) | (DOT identifier))* | precedenceUnaryOperator expression | expression KW_IS isCondition | expression precedenceBitwiseXorOperator expression | expression precedenceStarOperator expression | expression precedencePlusOperator expression | expression precedenceConcatenateOperator expression | expression precedenceAmpersandOperator expression | expression precedenceBitwiseOrOperator expression | expression precedenceComparisonOperator expression | expression KW_NOT? precedenceRegexpOperator expression | expression KW_NOT? KW_LIKE (KW_ANY | KW_ALL) expressionsInParenthesis | expression KW_NOT? KW_IN precedenceSimilarExpressionIn | expression KW_NOT? KW_BETWEEN expression KW_AND expression | KW_EXISTS subQueryExpression | precedenceNotOperator expression | expression precedenceLogicOperator expression | LPAREN expression RPAREN ; precedenceSimilarExpressionIn : subQueryExpression | expressionsInParenthesis ; subQueryExpression : LPAREN selectStatement RPAREN ; booleanValue : KW_TRUE | KW_FALSE ; booleanValueTok : KW_TRUE | KW_FALSE ; tableOrPartition : tableName partitionSpec? ; partitionSpec : KW_PARTITION LPAREN partitionVal (COMMA partitionVal)* RPAREN ; partitionVal : identifier (EQUAL constant)? ; dropPartitionSpec : KW_PARTITION LPAREN dropPartitionVal (COMMA dropPartitionVal )* RPAREN ; dropPartitionVal : identifier dropPartitionOperator constant ; dropPartitionOperator : EQUAL | NOTEQUAL | LESSTHANOREQUALTO | LESSTHAN | GREATERTHANOREQUALTO | GREATERTHAN ; sysFuncNames : KW_AND | KW_OR | KW_NOT | KW_LIKE | KW_IF | KW_CASE | KW_WHEN | KW_FLOOR | KW_TINYINT | KW_SMALLINT | KW_INT | KW_BIGINT | KW_FLOAT | KW_DOUBLE | KW_BOOLEAN | KW_STRING | KW_BINARY | KW_ARRAY | KW_MAP | KW_STRUCT | KW_UNIONTYPE | EQUAL | EQUAL_NS | NOTEQUAL | LESSTHANOREQUALTO | LESSTHAN | GREATERTHANOREQUALTO | GREATERTHAN | DIVIDE | PLUS | MINUS | STAR | MOD | DIV | AMPERSAND | TILDE | BITWISEOR | BITWISEXOR | KW_RLIKE | KW_REGEXP | KW_IN | KW_BETWEEN ; descFuncNames : sysFuncNames | StringLiteral | functionIdentifier ; identifier : Identifier | nonReserved ; functionIdentifier : identifier DOT identifier | identifier ; principalIdentifier : identifier | QuotedIdentifier ; // Here is what you have to do if you would like to add a new keyword. // Note that non reserved keywords are basically the keywords that can be used as identifiers. // (1) Add a new entry to HiveLexer, e.g., KW_TRUE : 'TRUE'; // (2) If it is reserved, you do NOT need to change IdentifiersParser.g // because all the KW_* are automatically not only keywords, but also reserved keywords. // However, you need to add a test to TestSQL11ReservedKeyWordsNegative.java. // Otherwise it is non-reserved, you need to put them in the nonReserved list below. //If you are not sure, please refer to the SQL2011 column in //http://www.postgresql.org/docs/9.5/static/sql-keywords-appendix.html nonReserved : KW_ABORT | KW_ADD | KW_ADMIN | KW_AFTER | KW_ANALYZE | KW_ARCHIVE | KW_ASC | KW_BEFORE | KW_BUCKET | KW_BUCKETS | KW_CASCADE | KW_CHANGE | KW_CHECK | KW_CLUSTER | KW_CLUSTERED | KW_CLUSTERSTATUS | KW_COLLECTION | KW_COLUMNS | KW_COMMENT | KW_COMPACT | KW_COMPACTIONS | KW_COMPUTE | KW_CONCATENATE | KW_CONTINUE | KW_DATA | KW_DAY | KW_DATABASES | KW_DATETIME | KW_DBPROPERTIES | KW_DEFERRED | KW_DEFINED | KW_DELIMITED | KW_DEPENDENCY | KW_DESC | KW_DIRECTORIES | KW_DIRECTORY | KW_DISABLE | KW_DISTRIBUTE | KW_DOW | KW_ELEM_TYPE | KW_ENABLE | KW_ENFORCED | KW_ESCAPED | KW_EXCLUSIVE | KW_EXPLAIN | KW_EXPORT | KW_FIELDS | KW_FILE | KW_FILEFORMAT | KW_FIRST | KW_FORMAT | KW_FORMATTED | KW_FUNCTIONS | KW_HOUR | KW_IDXPROPERTIES | KW_INDEX | KW_INDEXES | KW_INPATH | KW_INPUTDRIVER | KW_INPUTFORMAT | KW_ITEMS | KW_JAR | KW_KILL | KW_KEYS | KW_KEY_TYPE | KW_LAST | KW_LIMIT | KW_OFFSET | KW_LINES | KW_LOAD | KW_LOCATION | KW_LOCK | KW_LOCKS | KW_LOGICAL | KW_LONG | KW_MAPJOIN | KW_MATERIALIZED | KW_METADATA | KW_MINUTE | KW_MONTH | KW_MSCK | KW_NOSCAN | KW_NULLS | KW_OPTION | KW_OUTPUTDRIVER | KW_OUTPUTFORMAT | KW_OVERWRITE | KW_OWNER | KW_PARTITIONED | KW_PARTITIONS | KW_PLUS | KW_PRINCIPALS | KW_PURGE | KW_QUERY | KW_QUARTER | KW_READ | KW_REBUILD | KW_RECORDREADER | KW_RECORDWRITER | KW_RELOAD | KW_RENAME | KW_REPAIR | KW_REPLACE | KW_REPLICATION | KW_RESTRICT | KW_REWRITE | KW_ROLE | KW_ROLES | KW_SCHEMA | KW_SCHEMAS | KW_SECOND | KW_SEMI | KW_SERDE | KW_SERDEPROPERTIES | KW_SERVER | KW_SETS | KW_SHARED | KW_SHOW | KW_SHOW_DATABASE | KW_SKEWED | KW_SORT | KW_SORTED | KW_SSL | KW_STATISTICS | KW_STORED | KW_STREAMTABLE | KW_STRING | KW_STRUCT | KW_TABLES | KW_TBLPROPERTIES | KW_TEMPORARY | KW_TERMINATED | KW_TINYINT | KW_TOUCH | KW_TRANSACTIONS | KW_UNARCHIVE | KW_UNDO | KW_UNIONTYPE | KW_UNLOCK | KW_UNSET | KW_UNSIGNED | KW_URI | KW_USE | KW_UTC | KW_UTCTIMESTAMP | KW_VALUE_TYPE | KW_VIEW | KW_WEEK | KW_WHILE | KW_YEAR | KW_WORK | KW_TRANSACTION | KW_WRITE | KW_ISOLATION | KW_LEVEL | KW_SNAPSHOT | KW_AUTOCOMMIT | KW_RELY | KW_NORELY | KW_VALIDATE | KW_NOVALIDATE | KW_KEY | KW_MATCHED | KW_REPL | KW_DUMP | KW_STATUS | KW_CACHE | KW_VIEWS | KW_VECTORIZATION | KW_SUMMARY | KW_OPERATOR | KW_EXPRESSION | KW_DETAIL | KW_WAIT | KW_ZONE | KW_DEFAULT | KW_REOPTIMIZATION | KW_RESOURCE | KW_PLAN | KW_PLANS | KW_QUERY_PARALLELISM | KW_ACTIVATE | KW_MOVE | KW_DO | KW_POOL | KW_ALLOC_FRACTION | KW_SCHEDULING_POLICY | KW_PATH | KW_MAPPING | KW_WORKLOAD | KW_MANAGEMENT | KW_ACTIVE | KW_UNMANAGED ; //The following SQL2011 reserved keywords are used as function name only, but not as identifiers. sql11ReservedKeywordsUsedAsFunctionName : KW_IF | KW_ARRAY | KW_MAP | KW_BIGINT | KW_BINARY | KW_BOOLEAN | KW_CURRENT_DATE | KW_CURRENT_TIMESTAMP | KW_DATE | KW_DOUBLE | KW_FLOAT | KW_GROUPING | KW_INT | KW_SMALLINT | KW_TIMESTAMP ;
/** Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @author Canwei He */ parser grammar IdentifiersParser; //----------------------------------------------------------------------------------- // group by a,b groupByClause : KW_GROUP KW_BY groupby_expression ; // support for new and old rollup/cube syntax groupby_expression : rollupStandard | rollupOldSyntax | groupByEmpty ; groupByEmpty : LPAREN RPAREN ; // standard rollup syntax rollupStandard : (KW_ROLLUP | KW_CUBE) LPAREN expression ( COMMA expression)* RPAREN ; // old hive rollup syntax rollupOldSyntax : expressionsNotInParenthesis (KW_WITH KW_ROLLUP | KW_WITH KW_CUBE) ? (KW_GROUPING KW_SETS LPAREN groupingSetExpression ( COMMA groupingSetExpression)* RPAREN ) ? ; groupingSetExpression : groupingSetExpressionMultiple | groupingExpressionSingle ; groupingSetExpressionMultiple : LPAREN expression? (COMMA expression)* RPAREN ; groupingExpressionSingle : expression ; havingClause : KW_HAVING havingCondition ; havingCondition : expression ; expressionsInParenthesis : LPAREN expressionsNotInParenthesis RPAREN ; expressionsNotInParenthesis : expression expressionPart? ; expressionPart : (COMMA expression)+ ; expressions : expressionsInParenthesis | expressionsNotInParenthesis ; columnRefOrderInParenthesis : LPAREN columnRefOrder (COMMA columnRefOrder)* RPAREN ; columnRefOrderNotInParenthesis : columnRefOrder (COMMA columnRefOrder)* ; // order by a,b orderByClause : KW_ORDER KW_BY columnRefOrder ( COMMA columnRefOrder)* ; clusterByClause : KW_CLUSTER KW_BY expressions ; partitionByClause : KW_PARTITION KW_BY expressions ; distributeByClause : KW_DISTRIBUTE KW_BY expressions ; sortByClause : KW_SORT KW_BY ( columnRefOrderInParenthesis | columnRefOrderNotInParenthesis ) ; // fun(par1, par2, par3) function_ : functionName LPAREN ( STAR | (KW_DISTINCT | KW_ALL)? (selectExpression (COMMA selectExpression)*)? ) RPAREN (KW_OVER window_specification)? ; functionName : // Keyword IF is also a function name functionIdentifier | sql11ReservedKeywordsUsedAsFunctionName ; castExpression : KW_CAST LPAREN expression KW_AS primitiveType RPAREN ; caseExpression : KW_CASE expression (KW_WHEN expression KW_THEN expression)+ (KW_ELSE expression)? KW_END ; whenExpression : KW_CASE ( KW_WHEN expression KW_THEN expression)+ (KW_ELSE expression)? KW_END ; floorExpression : KW_FLOOR LPAREN expression (KW_TO floorDateQualifiers)? RPAREN ; floorDateQualifiers : KW_YEAR | KW_QUARTER | KW_MONTH | KW_WEEK | KW_DAY | KW_HOUR | KW_MINUTE | KW_SECOND ; extractExpression : KW_EXTRACT LPAREN timeQualifiers KW_FROM expression RPAREN ; timeQualifiers : KW_YEAR | KW_QUARTER | KW_MONTH | KW_WEEK | KW_DAY | KW_DOW | KW_HOUR | KW_MINUTE | KW_SECOND ; constant : intervalLiteral | Number | dateLiteral | timestampLiteral | timestampLocalTZLiteral | StringLiteral | stringLiteralSequence | IntegralLiteral | NumberLiteral | charSetStringLiteral | booleanValue | KW_NULL ; stringLiteralSequence : StringLiteral StringLiteral+ ; charSetStringLiteral : CharSetName CharSetLiteral ; dateLiteral : KW_DATE StringLiteral | KW_CURRENT_DATE ; timestampLiteral : KW_TIMESTAMP StringLiteral | KW_CURRENT_TIMESTAMP ; timestampLocalTZLiteral : KW_TIMESTAMPLOCALTZ StringLiteral ; intervalValue : StringLiteral | Number ; intervalLiteral : intervalValue intervalQualifiers ; intervalExpression : LPAREN intervalValue RPAREN intervalQualifiers | KW_INTERVAL intervalValue intervalQualifiers | KW_INTERVAL LPAREN expression RPAREN intervalQualifiers ; intervalQualifiers : KW_YEAR KW_TO KW_MONTH | KW_DAY KW_TO KW_SECOND | KW_YEAR | KW_MONTH | KW_DAY | KW_HOUR | KW_MINUTE | KW_SECOND ; atomExpression : constant | intervalExpression | castExpression | extractExpression | floorExpression | caseExpression | whenExpression | subQueryExpression | function_ | tableOrColumn | expressionsInParenthesis ; precedenceUnaryOperator : PLUS | MINUS | TILDE ; isCondition : KW_NOT? (KW_NULL | KW_TRUE | KW_FALSE | KW_DISTINCT KW_FROM) ; precedenceBitwiseXorOperator : BITWISEXOR ; precedenceStarOperator : STAR | DIVIDE | MOD | DIV ; precedencePlusOperator : PLUS | MINUS ; precedenceConcatenateOperator : CONCATENATE ; precedenceAmpersandOperator : AMPERSAND ; precedenceBitwiseOrOperator : BITWISEOR ; precedenceRegexpOperator : KW_LIKE | KW_RLIKE | KW_REGEXP ; precedenceComparisonOperator : LESSTHANOREQUALTO | LESSTHAN | GREATERTHANOREQUALTO | GREATERTHAN | EQUAL | EQUAL_NS | NOTEQUAL ; precedenceNotOperator : KW_NOT ; precedenceLogicOperator : KW_AND | KW_OR ; //precedenceFieldExpression //precedenceUnaryPrefixExpression //precedenceUnarySuffixExpression //precedenceBitwiseXorExpression //precedenceStarExpression //precedencePlusExpression //precedenceConcatenateExpression //precedenceAmpersandExpression //precedenceBitwiseOrExpression //precedenceSimilarExpressionMain //precedenceSimilarExpression //precedenceEqualExpression //precedenceNotExpression //precedenceAndExpression //precedenceOrExpression expression : expression precedenceLogicOperator expression | LPAREN expression RPAREN | precedenceExpression ; precedenceExpression : atomExpression ((LSQUARE expression RSQUARE) | (DOT identifier))* | precedenceUnaryOperator precedenceExpression | precedenceExpression KW_IS isCondition | precedenceExpression precedenceBitwiseXorOperator precedenceExpression | precedenceExpression precedenceStarOperator precedenceExpression | precedenceExpression precedencePlusOperator precedenceExpression | precedenceExpression precedenceConcatenateOperator precedenceExpression | precedenceExpression precedenceAmpersandOperator precedenceExpression | precedenceExpression precedenceBitwiseOrOperator precedenceExpression | precedenceExpression precedenceComparisonOperator precedenceExpression | precedenceExpression KW_NOT? precedenceRegexpOperator precedenceExpression | precedenceExpression KW_NOT? KW_LIKE (KW_ANY | KW_ALL) expressionsInParenthesis | precedenceExpression KW_NOT? KW_IN precedenceSimilarExpressionIn | precedenceExpression KW_NOT? KW_BETWEEN precedenceExpression KW_AND precedenceExpression | KW_EXISTS subQueryExpression | precedenceNotOperator precedenceExpression ; precedenceSimilarExpressionIn : subQueryExpression | expressionsInParenthesis ; subQueryExpression : LPAREN selectStatement RPAREN ; booleanValue : KW_TRUE | KW_FALSE ; booleanValueTok : KW_TRUE | KW_FALSE ; tableOrPartition : tableName partitionSpec? ; partitionSpec : KW_PARTITION LPAREN partitionVal (COMMA partitionVal)* RPAREN ; partitionVal : identifier (EQUAL constant)? ; dropPartitionSpec : KW_PARTITION LPAREN dropPartitionVal (COMMA dropPartitionVal )* RPAREN ; dropPartitionVal : identifier dropPartitionOperator constant ; dropPartitionOperator : EQUAL | NOTEQUAL | LESSTHANOREQUALTO | LESSTHAN | GREATERTHANOREQUALTO | GREATERTHAN ; sysFuncNames : KW_AND | KW_OR | KW_NOT | KW_LIKE | KW_IF | KW_CASE | KW_WHEN | KW_FLOOR | KW_TINYINT | KW_SMALLINT | KW_INT | KW_BIGINT | KW_FLOAT | KW_DOUBLE | KW_BOOLEAN | KW_STRING | KW_BINARY | KW_ARRAY | KW_MAP | KW_STRUCT | KW_UNIONTYPE | EQUAL | EQUAL_NS | NOTEQUAL | LESSTHANOREQUALTO | LESSTHAN | GREATERTHANOREQUALTO | GREATERTHAN | DIVIDE | PLUS | MINUS | STAR | MOD | DIV | AMPERSAND | TILDE | BITWISEOR | BITWISEXOR | KW_RLIKE | KW_REGEXP | KW_IN | KW_BETWEEN ; descFuncNames : sysFuncNames | StringLiteral | functionIdentifier ; identifier : Identifier | nonReserved ; functionIdentifier : identifier DOT identifier | identifier ; principalIdentifier : identifier | QuotedIdentifier ; // Here is what you have to do if you would like to add a new keyword. // Note that non reserved keywords are basically the keywords that can be used as identifiers. // (1) Add a new entry to HiveLexer, e.g., KW_TRUE : 'TRUE'; // (2) If it is reserved, you do NOT need to change IdentifiersParser.g // because all the KW_* are automatically not only keywords, but also reserved keywords. // However, you need to add a test to TestSQL11ReservedKeyWordsNegative.java. // Otherwise it is non-reserved, you need to put them in the nonReserved list below. //If you are not sure, please refer to the SQL2011 column in //http://www.postgresql.org/docs/9.5/static/sql-keywords-appendix.html nonReserved : KW_ABORT | KW_ADD | KW_ADMIN | KW_AFTER | KW_ANALYZE | KW_ARCHIVE | KW_ASC | KW_BEFORE | KW_BUCKET | KW_BUCKETS | KW_CASCADE | KW_CHANGE | KW_CHECK | KW_CLUSTER | KW_CLUSTERED | KW_CLUSTERSTATUS | KW_COLLECTION | KW_COLUMNS | KW_COMMENT | KW_COMPACT | KW_COMPACTIONS | KW_COMPUTE | KW_CONCATENATE | KW_CONTINUE | KW_DATA | KW_DAY | KW_DATABASES | KW_DATETIME | KW_DBPROPERTIES | KW_DEFERRED | KW_DEFINED | KW_DELIMITED | KW_DEPENDENCY | KW_DESC | KW_DIRECTORIES | KW_DIRECTORY | KW_DISABLE | KW_DISTRIBUTE | KW_DOW | KW_ELEM_TYPE | KW_ENABLE | KW_ENFORCED | KW_ESCAPED | KW_EXCLUSIVE | KW_EXPLAIN | KW_EXPORT | KW_FIELDS | KW_FILE | KW_FILEFORMAT | KW_FIRST | KW_FORMAT | KW_FORMATTED | KW_FUNCTIONS | KW_HOUR | KW_IDXPROPERTIES | KW_INDEX | KW_INDEXES | KW_INPATH | KW_INPUTDRIVER | KW_INPUTFORMAT | KW_ITEMS | KW_JAR | KW_KILL | KW_KEYS | KW_KEY_TYPE | KW_LAST | KW_LIMIT | KW_OFFSET | KW_LINES | KW_LOAD | KW_LOCATION | KW_LOCK | KW_LOCKS | KW_LOGICAL | KW_LONG | KW_MAPJOIN | KW_MATERIALIZED | KW_METADATA | KW_MINUTE | KW_MONTH | KW_MSCK | KW_NOSCAN | KW_NULLS | KW_OPTION | KW_OUTPUTDRIVER | KW_OUTPUTFORMAT | KW_OVERWRITE | KW_OWNER | KW_PARTITIONED | KW_PARTITIONS | KW_PLUS | KW_PRINCIPALS | KW_PURGE | KW_QUERY | KW_QUARTER | KW_READ | KW_REBUILD | KW_RECORDREADER | KW_RECORDWRITER | KW_RELOAD | KW_RENAME | KW_REPAIR | KW_REPLACE | KW_REPLICATION | KW_RESTRICT | KW_REWRITE | KW_ROLE | KW_ROLES | KW_SCHEMA | KW_SCHEMAS | KW_SECOND | KW_SEMI | KW_SERDE | KW_SERDEPROPERTIES | KW_SERVER | KW_SETS | KW_SHARED | KW_SHOW | KW_SHOW_DATABASE | KW_SKEWED | KW_SORT | KW_SORTED | KW_SSL | KW_STATISTICS | KW_STORED | KW_STREAMTABLE | KW_STRING | KW_STRUCT | KW_TABLES | KW_TBLPROPERTIES | KW_TEMPORARY | KW_TERMINATED | KW_TINYINT | KW_TOUCH | KW_TRANSACTIONS | KW_UNARCHIVE | KW_UNDO | KW_UNIONTYPE | KW_UNLOCK | KW_UNSET | KW_UNSIGNED | KW_URI | KW_USE | KW_UTC | KW_UTCTIMESTAMP | KW_VALUE_TYPE | KW_VIEW | KW_WEEK | KW_WHILE | KW_YEAR | KW_WORK | KW_TRANSACTION | KW_WRITE | KW_ISOLATION | KW_LEVEL | KW_SNAPSHOT | KW_AUTOCOMMIT | KW_RELY | KW_NORELY | KW_VALIDATE | KW_NOVALIDATE | KW_KEY | KW_MATCHED | KW_REPL | KW_DUMP | KW_STATUS | KW_CACHE | KW_VIEWS | KW_VECTORIZATION | KW_SUMMARY | KW_OPERATOR | KW_EXPRESSION | KW_DETAIL | KW_WAIT | KW_ZONE | KW_DEFAULT | KW_REOPTIMIZATION | KW_RESOURCE | KW_PLAN | KW_PLANS | KW_QUERY_PARALLELISM | KW_ACTIVATE | KW_MOVE | KW_DO | KW_POOL | KW_ALLOC_FRACTION | KW_SCHEDULING_POLICY | KW_PATH | KW_MAPPING | KW_WORKLOAD | KW_MANAGEMENT | KW_ACTIVE | KW_UNMANAGED ; //The following SQL2011 reserved keywords are used as function name only, but not as identifiers. sql11ReservedKeywordsUsedAsFunctionName : KW_IF | KW_ARRAY | KW_MAP | KW_BIGINT | KW_BINARY | KW_BOOLEAN | KW_CURRENT_DATE | KW_CURRENT_TIMESTAMP | KW_DATE | KW_DOUBLE | KW_FLOAT | KW_GROUPING | KW_INT | KW_SMALLINT | KW_TIMESTAMP ;
Fix the priority problem of 'BETWEEN AND' expression and 'AND' logical operator
Fix the priority problem of 'BETWEEN AND' expression and 'AND' logical operator
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
b38e4695c529a36d3f25b82f6a013710ce10e1e9
sharding-core/sharding-core-parse/sharding-core-parse-sqlserver/src/main/antlr4/imports/sqlserver/DDLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-sqlserver/src/main/antlr4/imports/sqlserver/DDLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE TABLE tableName fileTableClause_ createDefinitionClause_ ; createIndex : CREATE createIndexSpecification_ INDEX indexName ON tableName columnNames ; alterTable : ALTER TABLE tableName alterClause_ ; alterIndex : ALTER INDEX (indexName | ALL) ON tableName ; dropTable : DROP TABLE (IF EXISTS)? tableName (COMMA_ tableName)* ; dropIndex : DROP INDEX (IF EXISTS)? indexName ON tableName ; truncateTable : TRUNCATE TABLE tableName ; fileTableClause_ : (AS FILETABLE)? ; createDefinitionClause_ : createTableDefinitions_ partitionScheme_ fileGroup_ ; createTableDefinitions_ : LP_ createTableDefinition_ (COMMA_ createTableDefinition_)* (COMMA_ periodClause)? RP_ ; createTableDefinition_ : columnDefinition | computedColumnDefinition | columnSetDefinition | tableConstraint | tableIndex ; columnDefinition : columnName dataType columnDefinitionOption* columnConstraints columnIndex? ; columnDefinitionOption : FILESTREAM | COLLATE collationName | SPARSE | MASKED WITH LP_ FUNCTION EQ_ STRING_ RP_ | (CONSTRAINT ignoredIdentifier_)? DEFAULT expr | IDENTITY (LP_ NUMBER_ COMMA_ NUMBER_ RP_)? | NOT FOR REPLICATION | GENERATED ALWAYS AS ROW (START | END) HIDDEN_? | NOT? NULL | ROWGUIDCOL | ENCRYPTED WITH LP_ COLUMN_ENCRYPTION_KEY EQ_ ignoredIdentifier_ COMMA_ ENCRYPTION_TYPE EQ_ (DETERMINISTIC | RANDOMIZED) COMMA_ ALGORITHM EQ_ STRING_ RP_ | columnConstraint (COMMA_ columnConstraint)* | columnIndex ; columnConstraint : (CONSTRAINT ignoredIdentifier_)? (primaryKeyConstraint | columnForeignKeyConstraint | checkConstraint) ; primaryKeyConstraint : (primaryKey | UNIQUE) (diskTablePrimaryKeyConstraintOption | memoryTablePrimaryKeyConstraintOption) ; diskTablePrimaryKeyConstraintOption : (CLUSTERED | NONCLUSTERED)? primaryKeyWithClause? primaryKeyOnClause? ; primaryKeyWithClause : WITH (FILLFACTOR EQ_ NUMBER_ | LP_ indexOption (COMMA_ indexOption)* RP_) ; primaryKeyOnClause : onSchemaColumn | onFileGroup | onString ; onSchemaColumn : ON schemaName LP_ columnName RP_ ; onFileGroup : ON ignoredIdentifier_ ; onString : ON STRING_ ; memoryTablePrimaryKeyConstraintOption : CLUSTERED withBucket? ; withBucket : WITH LP_ BUCKET_COUNT EQ_ NUMBER_ RP_ ; columnForeignKeyConstraint : (FOREIGN KEY)? REFERENCES tableName LP_ columnName RP_ foreignKeyOnAction* ; foreignKeyOnAction : ON (DELETE | UPDATE) foreignKeyOn | NOT FOR REPLICATION ; foreignKeyOn : NO ACTION | CASCADE | SET (NULL | DEFAULT) ; checkConstraint : CHECK(NOT FOR REPLICATION)? LP_ expr RP_ ; columnIndex : INDEX indexName (CLUSTERED | NONCLUSTERED)? (WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause? (FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))? ; indexOnClause : onSchemaColumn | onFileGroup | onDefault ; onDefault : ON DEFAULT ; columnConstraints : (columnConstraint(COMMA_ columnConstraint)*)? ; computedColumnDefinition : columnName AS expr (PERSISTED(NOT NULL)?)? columnConstraint? ; columnSetDefinition : ignoredIdentifier_ IDENTIFIER_ COLUMN_SET FOR ALL_SPARSE_COLUMNS ; tableConstraint : (CONSTRAINT ignoredIdentifier_)? (tablePrimaryConstraint | tableForeignKeyConstraint | checkConstraint) ; tablePrimaryConstraint : primaryKeyUnique (diskTablePrimaryConstraintOption | memoryTablePrimaryConstraintOption) ; primaryKeyUnique : primaryKey | UNIQUE ; diskTablePrimaryConstraintOption : (CLUSTERED | NONCLUSTERED)? columnNames primaryKeyWithClause? primaryKeyOnClause? ; memoryTablePrimaryConstraintOption : NONCLUSTERED (columnNames | hashWithBucket) ; hashWithBucket : HASH columnNames withBucket ; tableForeignKeyConstraint : (FOREIGN KEY)? columnNames REFERENCES tableName columnNames foreignKeyOnAction* ; tableIndex : INDEX indexName ((CLUSTERED | NONCLUSTERED)? columnNames | CLUSTERED COLUMNSTORE | NONCLUSTERED? (COLUMNSTORE columnNames | hashWithBucket) | CLUSTERED COLUMNSTORE (WITH LP_ COMPRESSION_DELAY EQ_ (NUMBER_ MINUTES?) RP_)?) (WHERE expr)? (WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause? (FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))? ; createIndexSpecification_ : UNIQUE? (CLUSTERED | NONCLUSTERED)? ; alterClause_ : modifyColumnSpecification | addColumnSpecification | alterDrop | alterCheckConstraint | alterTrigger | alterSwitch | alterSet | alterTableOption | REBUILD ; modifyColumnSpecification : alterColumnOperation dataType (COLLATE collationName)? (NULL | NOT NULL)? SPARSE? ; alterColumnOperation : ALTER COLUMN columnName ; addColumnSpecification : (WITH (CHECK | NOCHECK))? ADD (alterColumnAddOptions | generatedColumnNamesClause) ; alterColumnAddOptions : alterColumnAddOption (COMMA_ alterColumnAddOption)* ; alterColumnAddOption : columnDefinition | computedColumnDefinition | columnSetDefinition | tableConstraint | alterTableTableIndex | constraintForColumn ; constraintForColumn : (CONSTRAINT ignoredIdentifier_)? DEFAULT simpleExpr FOR columnName ; columnNameWithSortsWithParen : LP_ columnNameWithSort (COMMA_ columnNameWithSort)* RP_ ; columnNameWithSort : columnName (ASC | DESC)? ; generatedColumnNamesClause : generatedColumnNameClause COMMA_ periodClause | periodClause COMMA_ generatedColumnNameClause ; generatedColumnNameClause : generatedColumnName DEFAULT simpleExpr (WITH VALUES)? COMMA_ generatedColumnName ; generatedColumnName : columnName dataTypeName_ GENERATED ALWAYS AS ROW (START | END)? HIDDEN_? (NOT NULL)? (CONSTRAINT ignoredIdentifier_)? ; alterDrop : DROP (alterTableDropConstraint | dropColumnSpecification | dropIndexSpecification | PERIOD FOR SYSTEM_TIME) ; alterTableDropConstraint : CONSTRAINT? (IF EXISTS)? dropConstraintName (COMMA_ dropConstraintName)* ; dropConstraintName : ignoredIdentifier_ dropConstraintWithClause? ; dropConstraintWithClause : WITH LP_ dropConstraintOption (COMMA_ dropConstraintOption)* RP_ ; dropConstraintOption : (MAXDOP EQ_ NUMBER_ | ONLINE EQ_ (ON | OFF) | MOVE TO (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_)) ; dropColumnSpecification : COLUMN (IF EXISTS)? columnName (COMMA_ columnName)* ; dropIndexSpecification : INDEX (IF EXISTS)? indexName (COMMA_ indexName)* ; alterCheckConstraint : WITH? (CHECK | NOCHECK) CONSTRAINT (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*)) ; alterTrigger : (ENABLE| DISABLE) TRIGGER (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*)) ; alterSwitch : SWITCH (PARTITION expr)? TO tableName (PARTITION expr)? (WITH LP_ lowPriorityLockWait RP_)? ; alterSet : SET LP_ (setFileStreamClause | setSystemVersionClause) RP_ ; setFileStreamClause : FILESTREAM_ON EQ_ (schemaName | ignoredIdentifier_ | STRING_) ; setSystemVersionClause : SYSTEM_VERSIONING EQ_ (OFF | ON alterSetOnClause?) ; alterSetOnClause : LP_ (HISTORY_TABLE EQ_ tableName)? dataConsistencyCheckClause_? historyRetentionPeriodClause_? RP_ ; dataConsistencyCheckClause_ : COMMA_? DATA_CONSISTENCY_CHECK EQ_ (ON | OFF) ; historyRetentionPeriodClause_ : COMMA_? HISTORY_RETENTION_PERIOD EQ_ historyRetentionPeriod ; historyRetentionPeriod : INFINITE | (NUMBER_ (DAY | DAYS | WEEK | WEEKS | MONTH | MONTHS | YEAR | YEARS)) ; alterTableTableIndex : indexWithName (indexNonClusterClause | indexClusterClause) ; indexWithName : INDEX indexName ; indexNonClusterClause : NONCLUSTERED (hashWithBucket | (columnNameWithSortsWithParen alterTableIndexOnClause?)) ; alterTableIndexOnClause : ON ignoredIdentifier_ | DEFAULT ; indexClusterClause : CLUSTERED COLUMNSTORE (WITH COMPRESSION_DELAY EQ_ NUMBER_ MINUTES?)? indexOnClause? ; alterTableOption : SET LP_ LOCK_ESCALATION EQ_ (AUTO | TABLE | DISABLE) RP_ | MEMORY_OPTIMIZED EQ_ ON | DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA) | SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)? ; tableOption : DATA_COMPRESSION EQ_ (NONE | ROW | PAGE) (ON PARTITIONS LP_ partitionExpressions RP_)? | FILETABLE_DIRECTORY EQ_ ignoredIdentifier_ | FILETABLE_COLLATE_FILENAME EQ_ (collationName | DATABASE_DEAULT) | FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME EQ_ ignoredIdentifier_ | FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME EQ_ ignoredIdentifier_ | FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME EQ_ ignoredIdentifier_ | SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)? | REMOTE_DATA_ARCHIVE EQ_ (ON (LP_ tableStretchOptions (COMMA_ tableStretchOptions)* RP_)? | OFF LP_ MIGRATION_STATE EQ_ PAUSED RP_) | tableOptOption | distributionOption | dataWareHouseTableOption ; tableOptOption : (MEMORY_OPTIMIZED EQ_ ON) | (DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA)) | (SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?) ; distributionOption : DISTRIBUTION EQ_ (HASH LP_ columnName RP_ | ROUND_ROBIN | REPLICATE) ; dataWareHouseTableOption : CLUSTERED COLUMNSTORE INDEX | HEAP | dataWareHousePartitionOption ; dataWareHousePartitionOption : (PARTITION LP_ columnName RANGE (LEFT | RIGHT)? FOR VALUES LP_ simpleExpr (COMMA_ simpleExpr)* RP_ RP_) ; tableStretchOptions : (FILTER_PREDICATE EQ_ (NULL | functionCall) COMMA_)? MIGRATION_STATE EQ_ (OUTBOUND | INBOUND | PAUSED) ; partitionScheme_ : (ON (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_))? ; fileGroup_ : (TEXTIMAGE_ON (ignoredIdentifier_ | STRING_))? ((FILESTREAM_ON (schemaName) | ignoredIdentifier_ STRING_))? (WITH LP_ tableOption (COMMA_ tableOption)* RP_)? ; periodClause : PERIOD FOR SYSTEM_TIME LP_ columnName COMMA_ columnName RP_ ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE TABLE tableName fileTableClause_ createDefinitionClause_ ; createIndex : CREATE createIndexSpecification_ INDEX indexName ON tableName columnNames ; alterTable : ALTER TABLE tableName alterDefinitionClause_ ; alterIndex : ALTER INDEX (indexName | ALL) ON tableName ; dropTable : DROP TABLE tableExistClause_ tableNames ; dropIndex : DROP INDEX indexExistClause_ indexName ON tableName ; truncateTable : TRUNCATE TABLE tableName ; fileTableClause_ : (AS FILETABLE)? ; createDefinitionClause_ : createTableDefinitions_ partitionScheme_ fileGroup_ ; createTableDefinitions_ : LP_ createTableDefinition_ (COMMA_ createTableDefinition_)* (COMMA_ periodClause)? RP_ ; createTableDefinition_ : columnDefinition | computedColumnDefinition | columnSetDefinition | tableConstraint | tableIndex ; columnDefinition : columnName dataType columnDefinitionOption* columnConstraints columnIndex? ; columnDefinitionOption : FILESTREAM | COLLATE collationName | SPARSE | MASKED WITH LP_ FUNCTION EQ_ STRING_ RP_ | (CONSTRAINT ignoredIdentifier_)? DEFAULT expr | IDENTITY (LP_ NUMBER_ COMMA_ NUMBER_ RP_)? | NOT FOR REPLICATION | GENERATED ALWAYS AS ROW (START | END) HIDDEN_? | NOT? NULL | ROWGUIDCOL | ENCRYPTED WITH LP_ COLUMN_ENCRYPTION_KEY EQ_ ignoredIdentifier_ COMMA_ ENCRYPTION_TYPE EQ_ (DETERMINISTIC | RANDOMIZED) COMMA_ ALGORITHM EQ_ STRING_ RP_ | columnConstraint (COMMA_ columnConstraint)* | columnIndex ; columnConstraint : (CONSTRAINT ignoredIdentifier_)? (primaryKeyConstraint | columnForeignKeyConstraint | checkConstraint) ; primaryKeyConstraint : (primaryKey | UNIQUE) (diskTablePrimaryKeyConstraintOption | memoryTablePrimaryKeyConstraintOption) ; diskTablePrimaryKeyConstraintOption : (CLUSTERED | NONCLUSTERED)? primaryKeyWithClause? primaryKeyOnClause? ; primaryKeyWithClause : WITH (FILLFACTOR EQ_ NUMBER_ | LP_ indexOption (COMMA_ indexOption)* RP_) ; primaryKeyOnClause : onSchemaColumn | onFileGroup | onString ; onSchemaColumn : ON schemaName LP_ columnName RP_ ; onFileGroup : ON ignoredIdentifier_ ; onString : ON STRING_ ; memoryTablePrimaryKeyConstraintOption : CLUSTERED withBucket? ; withBucket : WITH LP_ BUCKET_COUNT EQ_ NUMBER_ RP_ ; columnForeignKeyConstraint : (FOREIGN KEY)? REFERENCES tableName LP_ columnName RP_ foreignKeyOnAction* ; foreignKeyOnAction : ON (DELETE | UPDATE) foreignKeyOn | NOT FOR REPLICATION ; foreignKeyOn : NO ACTION | CASCADE | SET (NULL | DEFAULT) ; checkConstraint : CHECK(NOT FOR REPLICATION)? LP_ expr RP_ ; columnIndex : INDEX indexName (CLUSTERED | NONCLUSTERED)? (WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause? (FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))? ; indexOnClause : onSchemaColumn | onFileGroup | onDefault ; onDefault : ON DEFAULT ; columnConstraints : (columnConstraint(COMMA_ columnConstraint)*)? ; computedColumnDefinition : columnName AS expr (PERSISTED(NOT NULL)?)? columnConstraint? ; columnSetDefinition : ignoredIdentifier_ IDENTIFIER_ COLUMN_SET FOR ALL_SPARSE_COLUMNS ; tableConstraint : (CONSTRAINT ignoredIdentifier_)? (tablePrimaryConstraint | tableForeignKeyConstraint | checkConstraint) ; tablePrimaryConstraint : primaryKeyUnique (diskTablePrimaryConstraintOption | memoryTablePrimaryConstraintOption) ; primaryKeyUnique : primaryKey | UNIQUE ; diskTablePrimaryConstraintOption : (CLUSTERED | NONCLUSTERED)? columnNames primaryKeyWithClause? primaryKeyOnClause? ; memoryTablePrimaryConstraintOption : NONCLUSTERED (columnNames | hashWithBucket) ; hashWithBucket : HASH columnNames withBucket ; tableForeignKeyConstraint : (FOREIGN KEY)? columnNames REFERENCES tableName columnNames foreignKeyOnAction* ; tableIndex : INDEX indexName ((CLUSTERED | NONCLUSTERED)? columnNames | CLUSTERED COLUMNSTORE | NONCLUSTERED? (COLUMNSTORE columnNames | hashWithBucket) | CLUSTERED COLUMNSTORE (WITH LP_ COMPRESSION_DELAY EQ_ (NUMBER_ MINUTES?) RP_)?) (WHERE expr)? (WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause? (FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))? ; createIndexSpecification_ : UNIQUE? (CLUSTERED | NONCLUSTERED)? ; alterDefinitionClause_ : modifyColumnSpecification | addColumnSpecification | alterDrop | alterCheckConstraint | alterTrigger | alterSwitch | alterSet | alterTableOption | REBUILD ; modifyColumnSpecification : alterColumnOperation dataType (COLLATE collationName)? (NULL | NOT NULL)? SPARSE? ; alterColumnOperation : ALTER COLUMN columnName ; addColumnSpecification : (WITH (CHECK | NOCHECK))? ADD (alterColumnAddOptions | generatedColumnNamesClause) ; alterColumnAddOptions : alterColumnAddOption (COMMA_ alterColumnAddOption)* ; alterColumnAddOption : columnDefinition | computedColumnDefinition | columnSetDefinition | tableConstraint | alterTableTableIndex | constraintForColumn ; constraintForColumn : (CONSTRAINT ignoredIdentifier_)? DEFAULT simpleExpr FOR columnName ; columnNameWithSortsWithParen : LP_ columnNameWithSort (COMMA_ columnNameWithSort)* RP_ ; columnNameWithSort : columnName (ASC | DESC)? ; generatedColumnNamesClause : generatedColumnNameClause COMMA_ periodClause | periodClause COMMA_ generatedColumnNameClause ; generatedColumnNameClause : generatedColumnName DEFAULT simpleExpr (WITH VALUES)? COMMA_ generatedColumnName ; generatedColumnName : columnName dataTypeName_ GENERATED ALWAYS AS ROW (START | END)? HIDDEN_? (NOT NULL)? (CONSTRAINT ignoredIdentifier_)? ; alterDrop : DROP (alterTableDropConstraint | dropColumnSpecification | dropIndexSpecification | PERIOD FOR SYSTEM_TIME) ; alterTableDropConstraint : CONSTRAINT? (IF EXISTS)? dropConstraintName (COMMA_ dropConstraintName)* ; dropConstraintName : ignoredIdentifier_ dropConstraintWithClause? ; dropConstraintWithClause : WITH LP_ dropConstraintOption (COMMA_ dropConstraintOption)* RP_ ; dropConstraintOption : (MAXDOP EQ_ NUMBER_ | ONLINE EQ_ (ON | OFF) | MOVE TO (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_)) ; dropColumnSpecification : COLUMN (IF EXISTS)? columnName (COMMA_ columnName)* ; dropIndexSpecification : INDEX (IF EXISTS)? indexName (COMMA_ indexName)* ; alterCheckConstraint : WITH? (CHECK | NOCHECK) CONSTRAINT (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*)) ; alterTrigger : (ENABLE| DISABLE) TRIGGER (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*)) ; alterSwitch : SWITCH (PARTITION expr)? TO tableName (PARTITION expr)? (WITH LP_ lowPriorityLockWait RP_)? ; alterSet : SET LP_ (setFileStreamClause | setSystemVersionClause) RP_ ; setFileStreamClause : FILESTREAM_ON EQ_ (schemaName | ignoredIdentifier_ | STRING_) ; setSystemVersionClause : SYSTEM_VERSIONING EQ_ (OFF | ON alterSetOnClause?) ; alterSetOnClause : LP_ (HISTORY_TABLE EQ_ tableName)? dataConsistencyCheckClause_? historyRetentionPeriodClause_? RP_ ; dataConsistencyCheckClause_ : COMMA_? DATA_CONSISTENCY_CHECK EQ_ (ON | OFF) ; historyRetentionPeriodClause_ : COMMA_? HISTORY_RETENTION_PERIOD EQ_ historyRetentionPeriod ; historyRetentionPeriod : INFINITE | (NUMBER_ (DAY | DAYS | WEEK | WEEKS | MONTH | MONTHS | YEAR | YEARS)) ; alterTableTableIndex : indexWithName (indexNonClusterClause | indexClusterClause) ; indexWithName : INDEX indexName ; indexNonClusterClause : NONCLUSTERED (hashWithBucket | (columnNameWithSortsWithParen alterTableIndexOnClause?)) ; alterTableIndexOnClause : ON ignoredIdentifier_ | DEFAULT ; indexClusterClause : CLUSTERED COLUMNSTORE (WITH COMPRESSION_DELAY EQ_ NUMBER_ MINUTES?)? indexOnClause? ; alterTableOption : SET LP_ LOCK_ESCALATION EQ_ (AUTO | TABLE | DISABLE) RP_ | MEMORY_OPTIMIZED EQ_ ON | DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA) | SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)? ; tableExistClause_ : (IF EXISTS)? ; indexExistClause_ : (IF EXISTS)? ; tableOption : DATA_COMPRESSION EQ_ (NONE | ROW | PAGE) (ON PARTITIONS LP_ partitionExpressions RP_)? | FILETABLE_DIRECTORY EQ_ ignoredIdentifier_ | FILETABLE_COLLATE_FILENAME EQ_ (collationName | DATABASE_DEAULT) | FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME EQ_ ignoredIdentifier_ | FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME EQ_ ignoredIdentifier_ | FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME EQ_ ignoredIdentifier_ | SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)? | REMOTE_DATA_ARCHIVE EQ_ (ON (LP_ tableStretchOptions (COMMA_ tableStretchOptions)* RP_)? | OFF LP_ MIGRATION_STATE EQ_ PAUSED RP_) | tableOptOption | distributionOption | dataWareHouseTableOption ; tableOptOption : (MEMORY_OPTIMIZED EQ_ ON) | (DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA)) | (SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)?) ; distributionOption : DISTRIBUTION EQ_ (HASH LP_ columnName RP_ | ROUND_ROBIN | REPLICATE) ; dataWareHouseTableOption : CLUSTERED COLUMNSTORE INDEX | HEAP | dataWareHousePartitionOption ; dataWareHousePartitionOption : (PARTITION LP_ columnName RANGE (LEFT | RIGHT)? FOR VALUES LP_ simpleExpr (COMMA_ simpleExpr)* RP_ RP_) ; tableStretchOptions : (FILTER_PREDICATE EQ_ (NULL | functionCall) COMMA_)? MIGRATION_STATE EQ_ (OUTBOUND | INBOUND | PAUSED) ; partitionScheme_ : (ON (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_))? ; fileGroup_ : (TEXTIMAGE_ON (ignoredIdentifier_ | STRING_))? ((FILESTREAM_ON (schemaName) | ignoredIdentifier_ STRING_))? (WITH LP_ tableOption (COMMA_ tableOption)* RP_)? ; periodClause : PERIOD FOR SYSTEM_TIME LP_ columnName COMMA_ columnName RP_ ;
rename to alterDefinitionClause_
rename to alterDefinitionClause_
ANTLR
apache-2.0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
c336040b2aa001179e1cbf546f8df9359f27248a
reo-compiler/src/main/antlr4/nl/cwi/reo/parse/Reo.g4
reo-compiler/src/main/antlr4/nl/cwi/reo/parse/Reo.g4
grammar Reo; /** * Generic structure */ file : body EOF ; body : (comp | defn)* ; defn : 'define' ID params? portset '{' atom '}' # defnAtomic | 'define' ID params? nodeset '{' body '}' # defnComposed | nodes '=' nodes # defnJoin ; comp : ID assign? nodeset # compReference | 'for' ID '=' expr '...' expr '{' body '}' # compForLoop ; atom : java # atomJava | c # atomC | pa # atomPA | cam # atomCAM | wa # atomWA ; params : '<' ID (',' ID)* '>' ; assign : '<' value (',' value)* '>' ; value : ID | INT | STRING ; nodeset : '(' ')' | '(' nodes (',' nodes)* ')' ; nodes : ID indices* ; indices : '[' expr ']' | '[' expr '...' expr ']' ; portset : '(' port (',' port)* ')' ; port : ID '?' # portInput | ID '!' # portOutput ; expr : ID # exprParameter | INT # exprInteger | '-' expr # exprUnaryMin | expr '+' expr # exprAddition | expr '-' expr # exprDifference | expr '*' expr # exprProduct | expr '\' expr # exprDivision | expr '%' expr # exprRemainder ; /** * Java */ java : '#Java' FUNC ; /** * C */ c : '#C' FUNC ; /** * Port Automata */ pa : '#PA' pa_stmt* ; pa_stmt : ID '*'? '--' sync_const '->' ID ; sync_const : '{' '}' | '{' ID (',' ID)* '}' ; /** * Constraint Automata with State Memory */ cam : '#CAM' cam_stmt* ; cam_stmt : ID '*'? '--' sync_const ',' e '->' ID ; e : t OP e # cam_dcBinRel | t ; t : STRING # cam_termString | INT # cam_termInteger | ID # cam_termPortOrMem | ID '\'' # cam_termMemoryNext | ID '(' t (',' t )* ')' # cam_termFunc | '(' e ')' ; /** * Work Automata */ wa : '#WA' wa_stmt* ; wa_stmt : ID '*'? ':' wa_jc # wa_stmtInvar | ID '*'? '--' sync_const ',' wa_jc '->' ID # wa_stmtTrans ; wa_jc : 'true' # wa_jcTrue | ID '==' INT # wa_jcEql | ID '<=' INT # wa_jcLeq | wa_jc '&' wa_jc # wa_jcAnd ; /** * Tokens */ ID : [a-zA-Z] [a-zA-Z0-9]* ; OP : ('=' | '!' | '<' | '>')+ INT : ( '0' | [1-9] [0-9]* ) ; STRING : '\'' .*? '\'' ; FUNC : [a-zA-Z] [a-zA-Z0-9_-.:]* ; SPACES : [ \t\r\n]+ -> skip ; SL_COMM : '//' .*? ('\n'|EOF) -> skip ; ML_COMM : '/*' .*? '*/' -> skip ;
grammar Reo; /** * Generic structure */ file : includes body EOF ; incl : 'include' body : (comp | defn)* ; defn : 'define' ID params? portset '{' atom '}' # defnAtomic | 'define' ID params? nodeset '{' body '}' # defnComposed | nodes '=' nodes # defnJoin ; comp : ID assign? nodeset # compReference | 'for' ID '=' expr '...' expr '{' body '}' # compForLoop ; atom : java # atomJava | c # atomC | pa # atomPA | cam # atomCAM | wa # atomWA ; params : '<' ID (',' ID)* '>' ; assign : '<' value (',' value)* '>' ; value : ID | INT | STRING ; nodeset : '(' ')' | '(' nodes (',' nodes)* ')' ; nodes : ID indices* ; indices : '[' expr ']' | '[' expr '...' expr ']' ; portset : '(' port (',' port)* ')' ; port : ID '?' # portInput | ID '!' # portOutput ; expr : ID # exprParameter | INT # exprInteger | '-' expr # exprUnaryMin | expr '+' expr # exprAddition | expr '-' expr # exprDifference | expr '*' expr # exprProduct | expr '\' expr # exprDivision | expr '%' expr # exprRemainder ; /** * Java */ java : '#Java' FUNC ; /** * C */ c : '#C' FUNC ; /** * Port Automata */ pa : '#PA' pa_stmt* ; pa_stmt : ID '*'? '--' sync_const '->' ID ; sync_const : '{' '}' | '{' ID (',' ID)* '}' ; /** * Constraint Automata with State Memory */ cam : '#CAM' cam_stmt* ; cam_stmt : ID '*'? '--' sync_const ',' e '->' ID ; e : t OP e # cam_exInfix | PO t # cam_exInfix | t ; t : STRING # cam_termString | INT # cam_termInteger | ID # cam_termPortOrMem | ID '\'' # cam_termMemoryNext | ID '(' t (',' t )* ')' # cam_termFunc | '(' e ')' ; /** * Work Automata */ wa : '#WA' wa_stmt* ; wa_stmt : ID '*'? ':' wa_jc # wa_stmtInvar | ID '*'? '--' sync_const ',' wa_jc '->' ID # wa_stmtTrans ; wa_jc : 'true' # wa_jcTrue | ID '==' INT # wa_jcEql | ID '<=' INT # wa_jcLeq | wa_jc '&' wa_jc # wa_jcAnd ; /** * Tokens */ ID : [a-zA-Z] [a-zA-Z0-9]* ; OP : ('=' | '!' | '<' | '>' | '-')+ PO : ('-' | '~') INT : ( '0' | [1-9] [0-9]* ) ; STRING : '\'' .*? '\'' ; FUNC : [a-zA-Z] [a-zA-Z0-9_-.:]* ; SPACES : [ \t\r\n]+ -> skip ; SL_COMM : '//' .*? ('\n'|EOF) -> skip ; ML_COMM : '/*' .*? '*/' -> skip ;
Update Reo.g4
Update Reo.g4
ANTLR
mit
kasperdokter/Reo,kasperdokter/Reo,kasperdokter/Reo-compiler,kasperdokter/Reo-compiler,kasperdokter/Reo,kasperdokter/Reo,kasperdokter/Reo-compiler,kasperdokter/Reo-compiler,kasperdokter/Reo-compiler
3c8a2acea59482d1362d8be4062b4a0bca381639
grammars/cs652/cdecl/CDecl.g4
grammars/cs652/cdecl/CDecl.g4
grammar CDecl; declaration : typename declarator ';' ; typename : 'void' | 'float' | 'int' | ID ; declarator : declarator '[' ']' # Array // right operators have highest precedence | declarator '(' ')' # Func | '*' declarator # Pointer | '(' declarator ')' # Grouping | ID # Var ; // the following also would work but with less cool trees declaration2 : typename declarator2 ';' ; declarator2 : ( '*' declarator2 | '(' declarator2 ')' | ID ) ( '[' ']' | '(' ')' )* ; ID : [a-zA-Z_]* [a-zA-Z0-9_]+ ; WS : [ \t\n\r]+ -> skip ;
grammar CDecl; declaration : typename declarator ';' ; typename : 'void' | 'float' | 'int' | ID ; declarator : declarator '[' ']' # Array // right operators have highest precedence | declarator '(' ')' # Func | '*' declarator # Pointer | '(' declarator ')' # Grouping | ID # Var ; // the following also would work but with less cool trees declaration2 : typename declarator2 ';' ; declarator2 : ( '*' declarator2 | '(' declarator2 ')' | ID ) ( '[' ']' | '(' ')' )* ; ID : [a-zA-Z_] [a-zA-Z0-9_]+ ; WS : [ \t\n\r]+ -> skip ;
Update CDecl.g4
Update CDecl.g4
ANTLR
bsd-2-clause
USF-CS652-starterkits/parrt-cdecl
e7500982e67cd47ab85ea325da0d376ad53521fe
omni-cx2x/src/cx2x/translator/language/Claw.g4
omni-cx2x/src/cx2x/translator/language/Claw.g4
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import java.util.List; import java.util.ArrayList; import cx2x.translator.common.Constant; import cx2x.translator.pragma.*; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage language] @init{ $language = new ClawLanguage(); } : CLAW directive[$language] ; ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; directive[ClawLanguage language]: // loop-fusion directive LFUSION { $language.setDirective(ClawDirective.LOOP_FUSION); } group_option[$language] EOF // loop-interchange directive | LINTERCHANGE { $language.setDirective(ClawDirective.LOOP_INTERCHANGE); } indexes_option[$language] EOF // loop-extract directive | LEXTRACT range_option mapping_option EOF { $language.setDirective(ClawDirective.LOOP_EXTRACT); $language.setRange($range_option.r); } // remove directive | REMOVE { $language.setDirective(ClawDirective.REMOVE); } EOF | END REMOVE { $language.setDirective(ClawDirective.END_REMOVE); } EOF ; group_option[ClawLanguage language]: GROUP '(' group_name=IDENTIFIER ')' { $language.setGroupOption($group_name.text); } | /* empty */ ; indexes_option[ClawLanguage language] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $language.setIndexes(indexes); } | /* empty */ ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(Constant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ',' step=IDENTIFIER ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; mapping_var_list[List<ClawMappingVar> vars]: mv=mapping_var { $vars.add($mv.mappingVar); } | mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars] ; mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>(); List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>(); $mapping.setMappedVariables(listMapped); $mapping.setMappingVariables(listMapping); } : MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')' ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // Directives LFUSION : 'loop-fusion'; LINTERCHANGE : 'loop-interchange'; LEXTRACT : 'loop-extract'; REMOVE : 'remove'; END : 'end'; // Options GROUP : 'group'; RANGE : 'range'; MAP : 'map'; // Special elements IDENTIFIER : [a-zA-Z_$0-9] [a-zA-Z_$0-9]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : '0'..'9' ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import java.util.List; import java.util.ArrayList; import cx2x.translator.common.Constant; import cx2x.translator.pragma.*; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage language] @init{ $language = new ClawLanguage(); } : CLAW directive[$language] ; ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; directive[ClawLanguage language] @init{ List<ClawMapping> mappings = new ArrayList<ClawMapping>(); } : // loop-fusion directive LFUSION { $language.setDirective(ClawDirective.LOOP_FUSION); } group_option[$language] EOF // loop-interchange directive | LINTERCHANGE { $language.setDirective(ClawDirective.LOOP_INTERCHANGE); } indexes_option[$language] EOF // loop-extract directive | LEXTRACT range_option mapping_option_list[mappings] EOF { $language.setDirective(ClawDirective.LOOP_EXTRACT); $language.setRange($range_option.r); $language.setMappings(mappings); } // remove directive | REMOVE { $language.setDirective(ClawDirective.REMOVE); } EOF | END REMOVE { $language.setDirective(ClawDirective.END_REMOVE); } EOF ; group_option[ClawLanguage language]: GROUP '(' group_name=IDENTIFIER ')' { $language.setGroupOption($group_name.text); } | /* empty */ ; indexes_option[ClawLanguage language] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $language.setIndexes(indexes); } | /* empty */ ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(Constant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=IDENTIFIER ',' upper=IDENTIFIER ',' step=IDENTIFIER ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; mapping_var_list[List<ClawMappingVar> vars]: mv=mapping_var { $vars.add($mv.mappingVar); } | mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars] ; mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>(); List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>(); $mapping.setMappedVariables(listMapped); $mapping.setMappingVariables(listMapping); } : MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')' ; 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 LFUSION : 'loop-fusion'; LINTERCHANGE : 'loop-interchange'; LEXTRACT : 'loop-extract'; REMOVE : 'remove'; END : 'end'; // Options GROUP : 'group'; RANGE : 'range'; MAP : 'map'; // Special elements IDENTIFIER : [a-zA-Z_$0-9] [a-zA-Z_$0-9]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : '0'..'9' ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
Add mapping_option_list
Add mapping_option_list
ANTLR
bsd-2-clause
clementval/claw-compiler,clementval/claw-compiler
523c6a4d5f0d454499551501db6c0e9a284771e3
src/main/antlr/WorkflowCatalogQueryLanguage.g4
src/main/antlr/WorkflowCatalogQueryLanguage.g4
grammar WorkflowCatalogQueryLanguage; @header { package org.ow2.proactive.workflow_catalog.rest.query.parser; } // PARSER start // start rule, begin parsing here : expression ; expression // ANTLR resolves ambiguities in favor of the alternative given first : expression AND expression #andExpression // match subexpressions joined with AND | expression OR expression #orExpression // match subexpressions joined with OR | clause #clauseExpression // | LPAREN expression RPAREN #parenthesedExpression ; clause : AttributeLiteral COMPARE_OPERATOR StringLiteral #atomicClause | AttributeLiteral LPAREN StringLiteral PAIR_SEPARATOR StringLiteral RPAREN #keyValueClause ; // LEXER AND : 'AND' ; OR : 'OR' ; COMPARE_OPERATOR : '!=' | '=' ; LPAREN : '(' ; RPAREN : ')' ; PAIR_SEPARATOR : ',' ; AttributeLiteral : ID_LETTER (ID_LETTER | DIGIT)* ; StringLiteral : '"' ( ESC | . )*? '"' ; WS : [ \t\r\n]+ -> skip ; fragment ID_LETTER : [a-z]|[A-Z]|'_' ; fragment DIGIT : [0-9]; fragment ESC : '\\"' | '\\\\' | '\\%'; // 2-char sequences \" and \\ fragment LETTER : LOWERCASE | UPPERCASE; fragment LOWERCASE : [a-z]; fragment UPPERCASE : [A-Z];
grammar WorkflowCatalogQueryLanguage; @header { package org.ow2.proactive.workflow_catalog.rest.query.parser; } // PARSER start // start rule, begin parsing here : expression ; expression // ANTLR resolves ambiguities in favor of the alternative given first : expression AND expression #andExpression // match subexpressions joined with AND | expression OR expression #orExpression // match subexpressions joined with OR | clause #clauseExpression // | LPAREN expression RPAREN #parenthesedExpression ; clause : AttributeLiteral COMPARE_OPERATOR StringLiteral #atomicClause | AttributeLiteral LPAREN StringLiteral PAIR_SEPARATOR StringLiteral RPAREN #keyValueClause ; // LEXER AND : 'AND' ; OR : 'OR' ; COMPARE_OPERATOR : '!=' | '=' ; LPAREN : '(' ; RPAREN : ')' ; PAIR_SEPARATOR : ',' ; AttributeLiteral : ID_LETTER (ID_LETTER | DIGIT)* ; StringLiteral : '"' ( ESC | . )*? '"' ; WS : [ \t\r\n]+ -> skip ; fragment DIGIT : [0-9]; fragment ESC : '\\"' | '\\\\' | '\\%'; fragment ID_LETTER : [a-z]|[A-Z]|'_' ; fragment LETTER : LOWERCASE | UPPERCASE; fragment LOWERCASE : [a-z]; fragment UPPERCASE : [A-Z];
Clean up grammar
Clean up grammar
ANTLR
agpl-3.0
paraita/workflow-catalog,laurianed/workflow-catalog,gparanthoen/workflow-catalog,ow2-proactive/workflow-catalog,yinan-liu/workflow-catalog,ShatalovYaroslav/catalog,ow2-proactive/catalog,ShatalovYaroslav/catalog,ow2-proactive/catalog,laurianed/catalog,laurianed/catalog,ow2-proactive/catalog,ShatalovYaroslav/catalog,laurianed/catalog
9776dff4dbcafe4ee9b13d52fde5fbbdc2a0f6f2
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 : typeClasses ? innerType ; innerType : functionType | compoundType ; // function type functionType : compoundType '->' innerType ; compoundType : constantType | variableType | tupleType | listType | parenType ; tupleType : '(' innerType (',' innerType)+ ')' ; // tuple type, k>=2 listType : '[' innerType ']' ; // list type parenType : '(' innerType ')' ; // type with parentheses constantType : typeConstructor (WS* innerType)* ; typeConstructor : CT ; variableType : VT ; typeClasses : '(' typeWithClass (',' typeWithClass)* ')' '=>' ; typeWithClass : typeClass WS* classedType ; classedType : VT ; typeClass : CT ;
grammar Type; CT : [A-Z][a-z]+ ; VT : [a-z]+ ; WS : [ \t\r\n]+ -> skip ; type : typeClasses ? innerType ; innerType : functionType | compoundType ; // function type functionType : compoundType '->' innerType ; compoundType : constantType | variableType | tupleType | listType | parenType ; tupleType : '(' innerType (',' innerType)+ ')' ; // tuple type, k>=2 listType : '[' innerType ']' ; // list type parenType : '(' innerType ')' ; // type with parentheses constantType : typeConstructor (WS* innerType)* ; typeConstructor : CT ; variableType : VT ; typeClasses : '(' typeWithClass (',' typeWithClass)* ')' '=>' | typeWithClass '=>' ; typeWithClass : typeClass WS* classedType ; classedType : VT ; typeClass : CT ;
Add single type class notation to type parser
Add single type class notation to type parser
ANTLR
mit
viskell/viskell,wandernauta/viskell,andrewdavidmackenzie/viskell
72ab15ab002a010ec7d6f76f5ad107a60aa5da37
sharding-core/src/main/antlr4/imports/MySQLDCLStatement.g4
sharding-core/src/main/antlr4/imports/MySQLDCLStatement.g4
grammar MySQLDCLStatement; import MySQLKeyword, Keyword, BaseRule, DataType, Symbol; /** * each statement has a url, * each base url : https://dev.mysql.com/doc/refman/8.0/en/. */ //grant.html grantPriveleges : GRANT privType columnList? (COMMA privType columnList?)* ON objectType? privLevel TO userOrRoles (WITH GRANT OPTION)? ; privType : ALL PRIVILEGES? | ALTER ROUTINE? | CREATE (ROUTINE | TEMPORARY TABLES? | USER | VIEW)? | DELETE | DROP | EVENT | EXECUTE | FILE | GRANT OPTION | INDEX | INSERT | LOCK TABLES | PROCESS | PROXY | REFERENCES | RELOAD | REPLICATION CLIENT | REPLICATION SLAVE | SELECT | SHOW DATABASES | SHOW VIEW | SHUTDOWN | SUPER | TRIGGER | UPDATE | USAGE | AUDIT_ADMIN | BINLOG_ADMIN | CONNECTION_ADMIN | ENCRYPTION_KEY_ADMIN | FIREWALL_ADMIN | FIREWALL_USER | GROUP_REPLICATION_ADMIN | REPLICATION_SLAVE_ADMIN | ROLE_ADMIN | SET_USER_ID | SYSTEM_VARIABLES_ADMIN | VERSION_TOKEN_ADMIN ; objectType : TABLE | FUNCTION | PROCEDURE ; privLevel : ASTERISK | ASTERISK DOT ASTERISK | schemaName DOT ASTERISK | schemaName DOT tableName | tableName | schemaName DOT routineName ; user : ID | STRING | STRING AT_ STRING ; users : user (COMMA user)* ; role : ID | STRING | STRING AT_ STRING ; roles : role (COMMA role)* ; userOrRole : user | role ; userOrRoles : userOrRole (COMMA userOrRole)* ; //grant.html grantProxy : GRANT PROXY ON userOrRole TO userOrRoles (WITH GRANT OPTION)? ; //grant.html grantRoles : GRANT roleNames TO userOrRoles (WITH ADMIN OPTION)? ; //revoke.html revokePriveleges : REVOKE privType columnList? (COMMA privType columnList?)* ON objectType? privLevel FROM userOrRoles ; //revoke.html revokeAllPriveleges : REVOKE ALL PRIVILEGES? COMMA GRANT OPTION FROM userOrRoles ; //revoke.html revokeProxy : REVOKE PROXY ON userOrRole FROM userOrRoles ; //revoke.html revokeRoles : REVOKE roleNames FROM userOrRoles ; //create-user.html createUser : CREATE USER (IF NOT EXISTS)? user authOptions DEFAULT ROLE roles (REQUIRE (NONE | tlsOption (COMMA AND? tlsOption)*))? (WITH resourceOption (COMMA resourceOption)*)? (passwordOption | lockOption)* ; authOption : IDENTIFIED BY STRING (REPLACE STRING)? (RETAIN CURRENT PASSWORD)? | IDENTIFIED WITH authPlugin | IDENTIFIED WITH authPlugin BY STRING (REPLACE STRING)? (RETAIN CURRENT PASSWORD)? | IDENTIFIED WITH authPlugin AS STRING | DISCARD OLD PASSWORD ; authOptions : authOption (COMMA authOption)* ; authPlugin : ID ; tlsOption : SSL | X509 | CIPHER STRING | ISSUER STRING | SUBJECT STRING ; resourceOption : MAX_QUERIES_PER_HOUR NUMBER MAX_UPDATES_PER_HOUR NUMBER MAX_CONNECTIONS_PER_HOUR NUMBER MAX_USER_CONNECTIONS NUMBER ; passwordOption : PASSWORD EXPIRE (DEFAULT | NEVER | INTERVAL NUMBER DAY)? | PASSWORD HISTORY (DEFAULT | NUMBER) | PASSWORD REUSE INTERVAL (DEFAULT | NUMBER DAY) | PASSWORD REQUIRE CURRENT (DEFAULT | OPTIONAL)? ; lockOption : ACCOUNT LOCK | ACCOUNT UNLOCK ; //alter-user.html alterUser : ALTER USER (IF EXISTS)? user authOptions (REQUIRE (NONE | tlsOption (COMMA AND? tlsOption)*))? (WITH resourceOption (COMMA resourceOption)*)? (passwordOption | lockOption)* ; //alter-user.html alterCurrentUser : ALTER USER (IF EXISTS)? USER() userFuncAuthOption ; userFuncAuthOption : IDENTIFIED BY STRING (REPLACE STRING)? (RETAIN CURRENT PASSWORD)? | DISCARD OLD PASSWORD ; //alter-user.html alterUserRole : ALTER USER (IF EXISTS)? user DEFAULT ROLE (NONE | ALL | roles) ; //drop-user.html dropUser : DROP USER (IF EXISTS)? users ; //rename-user.html renameUser : RENAME USER user TO user (user TO user)* ; //create-role.html createRole : CREATE ROLE (IF NOT EXISTS)? roles ; //drop-role.html dropRole : DROP ROLE (IF EXISTS)? roles ; //set-password.html setPassword : SET PASSWORD (FOR user)? EQ STRING (REPLACE STRING)? (RETAIN CURRENT PASSWORD)? ; //set-default-role.html setDefaultRole : SET DEFAULT ROLE (NONE | ALL | roles) TO users ; //set-role.html setRole : SET ROLE ( DEFAULT | NONE | ALL | ALL EXCEPT roles | roles ) ;
grammar MySQLDCLStatement; import MySQLKeyword, Keyword, BaseRule, DataType, Symbol; /** * each statement has a url, * each base url : https://dev.mysql.com/doc/refman/8.0/en/. */ //grant.html grantPriveleges : GRANT privType columnList? (COMMA privType columnList?)* ON objectType? privLevel TO userOrRoles (WITH GRANT OPTION)? ; privType : ALL PRIVILEGES? | ALTER ROUTINE? | CREATE (ROUTINE | TEMPORARY TABLES? | USER | VIEW)? | DELETE | DROP | EVENT | EXECUTE | FILE | GRANT OPTION | INDEX | INSERT | LOCK TABLES | PROCESS | PROXY | REFERENCES | RELOAD | REPLICATION CLIENT | REPLICATION SLAVE | SELECT | SHOW DATABASES | SHOW VIEW | SHUTDOWN | SUPER | TRIGGER | UPDATE | USAGE | AUDIT_ADMIN | BINLOG_ADMIN | CONNECTION_ADMIN | ENCRYPTION_KEY_ADMIN | FIREWALL_ADMIN | FIREWALL_USER | GROUP_REPLICATION_ADMIN | REPLICATION_SLAVE_ADMIN | ROLE_ADMIN | SET_USER_ID | SYSTEM_VARIABLES_ADMIN | VERSION_TOKEN_ADMIN ; objectType : TABLE | FUNCTION | PROCEDURE ; privLevel : ASTERISK | ASTERISK DOT ASTERISK | schemaName DOT ASTERISK | schemaName DOT tableName | tableName | schemaName DOT routineName ; user : STRING AT_ STRING | STRING | ID ; users : user (COMMA user)* ; role : STRING AT_ STRING | STRING | ID ; roles : role (COMMA role)* ; userOrRole : user | role ; userOrRoles : userOrRole (COMMA userOrRole)* ; //grant.html grantProxy : GRANT PROXY ON userOrRole TO userOrRoles (WITH GRANT OPTION)? ; //grant.html grantRoles : GRANT roleNames TO userOrRoles (WITH ADMIN OPTION)? ; //revoke.html revokePriveleges : REVOKE privType columnList? (COMMA privType columnList?)* ON objectType? privLevel FROM userOrRoles ; //revoke.html revokeAllPriveleges : REVOKE ALL PRIVILEGES? COMMA GRANT OPTION FROM userOrRoles ; //revoke.html revokeProxy : REVOKE PROXY ON userOrRole FROM userOrRoles ; //revoke.html revokeRoles : REVOKE roleNames FROM userOrRoles ; //create-user.html createUser : CREATE USER (IF NOT EXISTS)? user authOptions? DEFAULT ROLE roles (REQUIRE (NONE | tlsOption (COMMA AND? tlsOption)*))? (WITH resourceOption (COMMA resourceOption)*)? (passwordOption | lockOption)* ; authOption : IDENTIFIED BY STRING (REPLACE STRING)? (RETAIN CURRENT PASSWORD)? | IDENTIFIED WITH authPlugin | IDENTIFIED WITH authPlugin BY STRING (REPLACE STRING)? (RETAIN CURRENT PASSWORD)? | IDENTIFIED WITH authPlugin AS STRING | DISCARD OLD PASSWORD ; authOptions : authOption (COMMA authOption)* ; authPlugin : ID ; tlsOption : SSL | X509 | CIPHER STRING | ISSUER STRING | SUBJECT STRING ; resourceOption : MAX_QUERIES_PER_HOUR NUMBER MAX_UPDATES_PER_HOUR NUMBER MAX_CONNECTIONS_PER_HOUR NUMBER MAX_USER_CONNECTIONS NUMBER ; passwordOption : PASSWORD EXPIRE (DEFAULT | NEVER | INTERVAL NUMBER DAY)? | PASSWORD HISTORY (DEFAULT | NUMBER) | PASSWORD REUSE INTERVAL (DEFAULT | NUMBER DAY) | PASSWORD REQUIRE CURRENT (DEFAULT | OPTIONAL)? ; lockOption : ACCOUNT LOCK | ACCOUNT UNLOCK ; //alter-user.html alterUser : ALTER USER (IF EXISTS)? user authOptions (REQUIRE (NONE | tlsOption (COMMA AND? tlsOption)*))? (WITH resourceOption (COMMA resourceOption)*)? (passwordOption | lockOption)* ; //alter-user.html alterCurrentUser : ALTER USER (IF EXISTS)? USER() userFuncAuthOption ; userFuncAuthOption : IDENTIFIED BY STRING (REPLACE STRING)? (RETAIN CURRENT PASSWORD)? | DISCARD OLD PASSWORD ; //alter-user.html alterUserRole : ALTER USER (IF EXISTS)? user DEFAULT ROLE (NONE | ALL | roles) ; //drop-user.html dropUser : DROP USER (IF EXISTS)? users ; //rename-user.html renameUser : RENAME USER user TO user (user TO user)* ; //create-role.html createRole : CREATE ROLE (IF NOT EXISTS)? roles ; //drop-role.html dropRole : DROP ROLE (IF EXISTS)? roles ; //set-password.html setPassword : SET PASSWORD (FOR user)? EQ STRING (REPLACE STRING)? (RETAIN CURRENT PASSWORD)? ; //set-default-role.html setDefaultRole : SET DEFAULT ROLE (NONE | ALL | roles) TO users ; //set-role.html setRole : SET ROLE ( DEFAULT | NONE | ALL | ALL EXCEPT roles | roles ) ;
fix user rule, role rule and create user rule
fix user rule, role rule and create user rule
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
79042a9695fc552319c7edfa5a463d2a41056693
terraform/terraform.g4
terraform/terraform.g4
/* BSD License Copyright (c) 2020, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar terraform; file : (local | module | output | provider | variable | block)+ ; provider : 'provider' blockbody ; output : 'output' STRING blockbody ; local : 'locals' blockbody ; module : 'module' STRING blockbody ; variable : 'variable' STRING blockbody ; block : blocktype label* blockbody ; blocktype : IDENTIFIER ; label : STRING ; blockbody : '{' (argument | block)* '}' ; argument : identifier '=' expression ; identifier : IDENTIFIER ; expression : section ('.' section)* ; section : list | map | val ; val : NULL | NUMBER | string | BOOL | IDENTIFIER index? | DESCRIPTION | filedecl | functioncall | EOF_ ; functioncall : functionname '(' functionarguments ')' ; functionname : IDENTIFIER ; functionarguments : //no arguments | expression (',' expression)* ; index : '[' expression ']' ; filedecl : 'file' '(' expression ')' ; list : '[' expression (',' expression)* ','? ']' ; map : '{' argument* '}' ; string : STRING | MULTILINESTRING ; fragment DIGIT : [0-9] ; EOF_ : '<<EOF' .*? 'EOF' ; NULL : 'nul' ; NUMBER : DIGIT+ ('.' DIGIT+)? ; BOOL : 'true' | 'false' ; DESCRIPTION : '<<DESCRIPTION' .*? 'DESCRIPTION' ; MULTILINESTRING : '<<-EOF' .*? 'EOF' ; STRING : '"' (~ [\r\n"] | '""')* '"' ; IDENTIFIER : [a-zA-Z] ([a-zA-Z0-9_-])* ; COMMENT : ('#' | '//') ~ [\r\n]* -> channel(HIDDEN) ; BLOCKCOMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; WS : [ \r\n\t]+ -> skip ;
/* BSD License Copyright (c) 2020, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar terraform; file : (local | module | output | provider | variable | block)+ ; provider : 'provider' STRING blockbody ; output : 'output' STRING blockbody ; local : 'locals' blockbody ; module : 'module' STRING blockbody ; variable : 'variable' STRING blockbody ; block : blocktype label* blockbody ; blocktype : IDENTIFIER ; label : STRING ; blockbody : '{' (argument | block)* '}' ; argument : identifier '=' expression ; identifier : IDENTIFIER ; expression : section ('.' section)* ; 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 ;
Add a STRING which follows "provider" (the provider name)
Add a STRING which follows "provider" (the provider name)
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
927179e199b9e7cdd48c56b9ec15d71de7eed438
sharding-jdbc-ddl-parser/src/main/antlr4/imports/PostgreBase.g4
sharding-jdbc-ddl-parser/src/main/antlr4/imports/PostgreBase.g4
grammar PostgreBase; import PostgreKeyword, DataType, Keyword, Symbol, BaseRule; columnDefinition : columnName dataType collateClause? columnConstraint* ; dataType : typeName intervalFields? dataTypeLength? (WITHOUT TIME ZONE | WITH TIME ZONE)? (LEFT_BRACKET RIGHT_BRACKET)* | ID ; typeName : DOUBLE PRECISION | CHARACTER VARYING? | BIT VARYING? | ID ; intervalFields : intervalField (TO intervalField)? ; intervalField : YEAR | MONTH | DAY | HOUR | MINUTE | SECOND ; collateClause : COLLATE collationName ; usingIndexType: USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN) ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT constraintName ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LEFT_PAREN sequenceOptions RIGHT_PAREN)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName (LEFT_PAREN columnName RIGHT_PAREN)? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)?(ON DELETE action)? (ON UPDATE action)? ; checkOption : CHECK expr (NO INHERIT )? ; defaultExpr : CURRENT_TIMESTAMP | expr; sequenceOptions: sequenceOption (START WITH? NUMBER)? (CACHE NUMBER)? (NO? CYCLE)? ; sequenceOption : (INCREMENT BY? NUMBER)? (MINVALUE NUMBER | NO MINVALUE)? (MAXVALUE NUMBER | NO MAXVALUE)? ; indexParameters : (USING INDEX TABLESPACE tablespaceName)? ; action : NO ACTION | RESTRICT | CASCADE | SET NULL | SET DEFAULT ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED |IMMEDIATE))? ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnList indexParameters | primaryKey columnList indexParameters | FOREIGN KEY columnList REFERENCES tableName columnList ; excludeElement : (columnName | expr) opclass? (ASC | DESC)? (NULLS (FIRST | LAST))? ; privateExprOfDb: aggregateExpression |windowFunction |arrayConstructorWithCast |(TIMESTAMP (WITH TIME ZONE)? STRING) |extractFromFunction ; pgExpr : castExpr | collateExpr | expr ; aggregateExpression : ID (LEFT_PAREN (ALL | DISTINCT)? exprs orderByClause? RIGHT_PAREN) asteriskWithParen (LEFT_PAREN exprs RIGHT_PAREN WITHIN GROUP LEFT_PAREN orderByClause RIGHT_PAREN) filterClause? ; filterClause : FILTER LEFT_PAREN WHERE booleanPrimary RIGHT_PAREN ; asteriskWithParen : LEFT_PAREN ASTERISK RIGHT_PAREN ; windowFunction : ID (exprsWithParen | asteriskWithParen) filterClause? windowFunctionWithClause ; windowFunctionWithClause : OVER (ID | LEFT_PAREN windowDefinition RIGHT_PAREN ) ; windowDefinition : ID? (PARTITION BY exprs)? (orderByExpr (COMMA orderByExpr)*)? frameClause? ; orderByExpr : ORDER BY expr (ASC | DESC | USING operator)? (NULLS (FIRST | LAST ))? ; operator : SAFE_EQ | EQ_OR_ASSIGN | NEQ | NEQ_SYM | GT | GTE | LT | LTE | AND_SYM | OR_SYM | NOT_SYM ; frameClause : (RANGE | ROWS) frameStart | (RANGE | ROWS ) BETWEEN frameStart AND frameEnd ; frameStart : UNBOUNDED PRECEDING | NUMBER PRECEDING | CURRENT ROW | NUMBER FOLLOWING | UNBOUNDED FOLLOWING ; frameEnd : frameStart ; castExpr : CAST LEFT_PAREN expr AS dataType RIGHT_PAREN | expr COLON COLON dataType ; castExprWithColon : COLON COLON dataType(LEFT_BRACKET RIGHT_BRACKET)* ; collateExpr : expr COLLATE expr ; arrayConstructorWithCast : arrayConstructor castExprWithColon? | ARRAY LEFT_BRACKET RIGHT_BRACKET castExprWithColon ; arrayConstructor : ARRAY LEFT_BRACKET exprs RIGHT_BRACKET | ARRAY LEFT_BRACKET arrayConstructor (COMMA arrayConstructor)* RIGHT_BRACKET ; extractFromFunction : EXTRACT LEFT_PAREN ID FROM ID RIGHT_PAREN ;
grammar PostgreBase; import PostgreKeyword, DataType, Keyword, Symbol, BaseRule; columnDefinition : columnName dataType collateClause? columnConstraint* ; dataType : typeName intervalFields? dataTypeLength? (WITHOUT TIME ZONE | WITH TIME ZONE)? (LEFT_BRACKET RIGHT_BRACKET)* | ID ; typeName : DOUBLE PRECISION | CHARACTER VARYING? | BIT VARYING? | ID ; intervalFields : intervalField (TO intervalField)? ; intervalField : YEAR | MONTH | DAY | HOUR | MINUTE | SECOND ; collateClause : COLLATE collationName ; usingIndexType: USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN) ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT constraintName ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LEFT_PAREN sequenceOptions RIGHT_PAREN)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName (LEFT_PAREN columnName RIGHT_PAREN)? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)?(ON DELETE action)? (ON UPDATE action)? ; checkOption : CHECK expr (NO INHERIT )? ; defaultExpr : CURRENT_TIMESTAMP | expr; sequenceOptions: sequenceOption (START WITH? NUMBER)? (CACHE NUMBER)? (NO? CYCLE)? ; sequenceOption : (INCREMENT BY? NUMBER)? (MINVALUE NUMBER | NO MINVALUE)? (MAXVALUE NUMBER | NO MAXVALUE)? ; indexParameters : (USING INDEX TABLESPACE tablespaceName)? ; action : NO ACTION | RESTRICT | CASCADE | SET NULL | SET DEFAULT ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED |IMMEDIATE))? ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnList indexParameters | primaryKey columnList indexParameters | FOREIGN KEY columnList REFERENCES tableName columnList (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? foreignKeyOnAction* ; foreignKeyOnAction : ON UPDATE foreignKeyOn | ON DELETE foreignKeyOn ; foreignKeyOn : RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT ; excludeElement : (columnName | expr) opclass? (ASC | DESC)? (NULLS (FIRST | LAST))? ; privateExprOfDb: aggregateExpression |windowFunction |arrayConstructorWithCast |(TIMESTAMP (WITH TIME ZONE)? STRING) |extractFromFunction ; pgExpr : castExpr | collateExpr | expr ; aggregateExpression : ID (LEFT_PAREN (ALL | DISTINCT)? exprs orderByClause? RIGHT_PAREN) asteriskWithParen (LEFT_PAREN exprs RIGHT_PAREN WITHIN GROUP LEFT_PAREN orderByClause RIGHT_PAREN) filterClause? ; filterClause : FILTER LEFT_PAREN WHERE booleanPrimary RIGHT_PAREN ; asteriskWithParen : LEFT_PAREN ASTERISK RIGHT_PAREN ; windowFunction : ID (exprsWithParen | asteriskWithParen) filterClause? windowFunctionWithClause ; windowFunctionWithClause : OVER (ID | LEFT_PAREN windowDefinition RIGHT_PAREN ) ; windowDefinition : ID? (PARTITION BY exprs)? (orderByExpr (COMMA orderByExpr)*)? frameClause? ; orderByExpr : ORDER BY expr (ASC | DESC | USING operator)? (NULLS (FIRST | LAST ))? ; operator : SAFE_EQ | EQ_OR_ASSIGN | NEQ | NEQ_SYM | GT | GTE | LT | LTE | AND_SYM | OR_SYM | NOT_SYM ; frameClause : (RANGE | ROWS) frameStart | (RANGE | ROWS ) BETWEEN frameStart AND frameEnd ; frameStart : UNBOUNDED PRECEDING | NUMBER PRECEDING | CURRENT ROW | NUMBER FOLLOWING | UNBOUNDED FOLLOWING ; frameEnd : frameStart ; castExpr : CAST LEFT_PAREN expr AS dataType RIGHT_PAREN | expr COLON COLON dataType ; castExprWithColon : COLON COLON dataType(LEFT_BRACKET RIGHT_BRACKET)* ; collateExpr : expr COLLATE expr ; arrayConstructorWithCast : arrayConstructor castExprWithColon? | ARRAY LEFT_BRACKET RIGHT_BRACKET castExprWithColon ; arrayConstructor : ARRAY LEFT_BRACKET exprs RIGHT_BRACKET | ARRAY LEFT_BRACKET arrayConstructor (COMMA arrayConstructor)* RIGHT_BRACKET ; extractFromFunction : EXTRACT LEFT_PAREN ID FROM ID RIGHT_PAREN ;
fix foreign key bug
fix foreign key bug
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
0a7278a2668cad3321624ad1068b62bb5cc6540f
omni-cx2x/src/cx2x/translator/language/Claw.g4
omni-cx2x/src/cx2x/translator/language/Claw.g4
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import cx2x.translator.common.ClawConstant; import cx2x.translator.misc.Utility; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage l] @init{ $l = new ClawLanguage(); } : CLAW directive[$l] ; directive[ClawLanguage l] @init{ List<ClawMapping> m = new ArrayList<>(); List<String> o = new ArrayList<>(); List<String> s = new ArrayList<>(); List<Integer> i = new ArrayList<>(); } : // loop-fusion directive LFUSION group_clause_optional[$l] collapse_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_FUSION); } // loop-interchange directive | LINTERCHANGE indexes_option[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } // loop-extract directive | LEXTRACT range_option mapping_option_list[m] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_EXTRACT); $l.setRange($range_option.r); $l.setMappings(m); } // remove directive | REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); } | END REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); $l.setEndPragma(); } // Kcache directive | KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); } | KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); $l.setInitClause(); } // Array notation transformation directive | ARRAY_TRANS induction_optional[$l] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); } | END ARRAY_TRANS { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); $l.setEndPragma(); } // loop-hoist directive | LHOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF { $l.setHoistInductionVars(o); $l.setDirective(ClawDirective.LOOP_HOIST); } | END LHOIST EOF { $l.setDirective(ClawDirective.LOOP_HOIST); $l.setEndPragma(); } // on the fly directive | ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')' { $l.setDirective(ClawDirective.ARRAY_TO_CALL); $l.setFctParams(o); $l.setFctName($fct_name.text); $l.setArrayName($array_name.text); } // parallelize directive | define_option[$l]* PARALLELIZE data_clause_optional[$l] over_clause_optional[$l] { $l.setDirective(ClawDirective.PARALLELIZE); } | PARALLELIZE FORWARD { $l.setDirective(ClawDirective.PARALLELIZE); $l.setForwardClause(); } | END PARALLELIZE { $l.setDirective(ClawDirective.PARALLELIZE); $l.setEndPragma(); } | 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] ; // over clause over_clause_optional[ClawLanguage l] @init{ List<String> s = new ArrayList<>(); } : OVER '(' ids_or_colon_list[s] ')' { $l.setOverClause(s); } | /* empty */ ; // group clause group_clause_optional[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupClause($group_name.text); } | /* empty */ ; // collapse clause collapse_optional[ClawLanguage l]: COLLAPSE '(' n=NUMBER ')' { $l.setCollapseClause($n.text); } | /* empty */ ; // fusion clause fusion_optional[ClawLanguage l]: FUSION group_clause_optional[$l] { $l.setFusionClause(); } | /* empty */ ; // parallel clause parallel_optional[ClawLanguage l]: PARALLEL { $l.setParallelClause(); } | /* empty */ ; // acc clause acc_optional[ClawLanguage l] @init{ List<String> tempAcc = new ArrayList<>(); } : ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); } | /* empty */ ; // interchange clause interchange_optional[ClawLanguage l]: INTERCHANGE indexes_option[$l] { $l.setInterchangeClause(); } | /* empty */ ; // induction clause induction_optional[ClawLanguage l] @init{ List<String> temp = new ArrayList<>(); } : INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); } | /* empty */ ; // data clause data_clause[ClawLanguage l] @init { List<String> temp = new ArrayList<>(); } : DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); } ; // data clause or empty data_clause_optional[ClawLanguage l]: data_clause[$l] | /* empty */ ; // private clause private_optional[ClawLanguage l]: PRIVATE { $l.setPrivateClause(); } | /* empty */ ; // reshape clause reshape_optional[ClawLanguage l] @init{ List<ClawReshapeInfo> r = new ArrayList(); } : RESHAPE '(' reshape_list[r] ')' { $l.setReshapeClauseValues(r); } | /* empty */ ; // reshape clause reshape_element returns [ClawReshapeInfo i] @init{ List<Integer> temp = new ArrayList(); } : array_name=IDENTIFIER '(' target_dim=NUMBER ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } | array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } ; reshape_list[List<ClawReshapeInfo> r]: info=reshape_element { $r.add($info.i); } ',' reshape_list[$r] | info=reshape_element { $r.add($info.i); } ; identifiers[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids] ; identifiers_list[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids] ; integers[List<Integer> ints]: ; integers_list[List<Integer> ints]: i=NUMBER { $ints.add(Integer.parseInt($i.text)); } | i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints] ; indexes_option[ClawLanguage l] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $l.setIndexes(indexes); } | /* empty */ ; offset_list_optional[List<Integer> offsets]: OFFSET '(' offset_list[$offsets] ')' | /* empty */ ; offset_list[List<Integer> offsets]: offset[$offsets] | offset[$offsets] ',' offset_list[$offsets] ; offset[List<Integer> offsets]: n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } | '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); } | '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(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'; // Clauses ACC : 'acc'; COLLAPSE : 'collapse'; DATA : 'data'; DIMENSION : 'dimension'; FORWARD : 'forward'; FUSION : 'fusion'; GROUP : 'group'; INDUCTION : 'induction'; INIT : 'init'; INTERCHANGE : 'interchange'; MAP : 'map'; OFFSET : 'offset'; OVER : 'over'; PARALLEL : 'parallel'; PRIVATE : 'private'; RANGE : 'range'; RESHAPE : 'reshape'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : [0-9] ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import cx2x.translator.common.ClawConstant; import cx2x.translator.misc.Utility; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage l] @init{ $l = new ClawLanguage(); } : CLAW directive[$l] ; directive[ClawLanguage l] @init{ List<ClawMapping> m = new ArrayList<>(); List<String> o = new ArrayList<>(); List<String> s = new ArrayList<>(); List<Integer> i = new ArrayList<>(); } : // loop-fusion directive LFUSION group_clause_optional[$l] collapse_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_FUSION); } // loop-interchange directive | LINTERCHANGE indexes_option[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } // loop-extract directive | LEXTRACT range_option mapping_option_list[m] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_EXTRACT); $l.setRange($range_option.r); $l.setMappings(m); } // remove directive | REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); } | END REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); $l.setEndPragma(); } // Kcache directive | KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); } | KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); $l.setInitClause(); } // Array notation transformation directive | ARRAY_TRANS induction_optional[$l] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); } | END ARRAY_TRANS { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); $l.setEndPragma(); } // loop-hoist directive | LHOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF { $l.setHoistInductionVars(o); $l.setDirective(ClawDirective.LOOP_HOIST); } | END LHOIST EOF { $l.setDirective(ClawDirective.LOOP_HOIST); $l.setEndPragma(); } // on the fly directive | ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')' { $l.setDirective(ClawDirective.ARRAY_TO_CALL); $l.setFctParams(o); $l.setFctName($fct_name.text); $l.setArrayName($array_name.text); } // parallelize directive | define_option[$l]* PARALLELIZE data_clause_optional[$l] over_clause_optional[$l] { $l.setDirective(ClawDirective.PARALLELIZE); } | PARALLELIZE FORWARD { $l.setDirective(ClawDirective.PARALLELIZE); $l.setForwardClause(); } | END PARALLELIZE { $l.setDirective(ClawDirective.PARALLELIZE); $l.setEndPragma(); } | 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] ; // over clause over_clause_optional[ClawLanguage l] @init{ List<String> s = new ArrayList<>(); } : OVER '(' ids_or_colon_list[s] ')' { $l.setOverClause(s); } | /* empty */ ; // group clause group_clause_optional[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupClause($group_name.text); } | /* empty */ ; // collapse clause collapse_optional[ClawLanguage l]: COLLAPSE '(' n=NUMBER ')' { $l.setCollapseClause($n.text); } | /* empty */ ; // fusion clause fusion_optional[ClawLanguage l]: FUSION group_clause_optional[$l] { $l.setFusionClause(); } | /* empty */ ; // parallel clause parallel_optional[ClawLanguage l]: PARALLEL { $l.setParallelClause(); } | /* empty */ ; // acc clause acc_optional[ClawLanguage l] @init{ List<String> tempAcc = new ArrayList<>(); } : ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); } | /* empty */ ; // interchange clause interchange_optional[ClawLanguage l]: INTERCHANGE indexes_option[$l] { $l.setInterchangeClause(); } | /* empty */ ; // induction clause induction_optional[ClawLanguage l] @init{ List<String> temp = new ArrayList<>(); } : INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); } | /* empty */ ; // data clause data_clause[ClawLanguage l] @init { List<String> temp = new ArrayList<>(); } : DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); } ; // data clause or empty data_clause_optional[ClawLanguage l]: data_clause[$l] | /* empty */ ; // private clause private_optional[ClawLanguage l]: PRIVATE { $l.setPrivateClause(); } | /* empty */ ; // reshape clause reshape_optional[ClawLanguage l] @init{ List<ClawReshapeInfo> r = new ArrayList(); } : RESHAPE '(' reshape_list[r] ')' { $l.setReshapeClauseValues(r); } | /* empty */ ; // reshape clause reshape_element returns [ClawReshapeInfo i] @init{ List<Integer> temp = new ArrayList(); } : array_name=IDENTIFIER '(' target_dim=NUMBER ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } | array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } ; reshape_list[List<ClawReshapeInfo> r]: info=reshape_element { $r.add($info.i); } ',' reshape_list[$r] | info=reshape_element { $r.add($info.i); } ; identifiers[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids] ; identifiers_list[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids] ; integers[List<Integer> ints]: ; integers_list[List<Integer> ints]: i=NUMBER { $ints.add(Integer.parseInt($i.text)); } | i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints] ; indexes_option[ClawLanguage l] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $l.setIndexes(indexes); } | /* empty */ ; offset_list_optional[List<Integer> offsets]: OFFSET '(' offset_list[$offsets] ')' | /* empty */ ; offset_list[List<Integer> offsets]: offset[$offsets] | offset[$offsets] ',' offset_list[$offsets] ; offset[List<Integer> offsets]: n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } | '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); } | '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(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'; // Clauses ACC : 'acc'; COLLAPSE : 'collapse'; DATA : 'data'; DIMENSION : 'dimension'; FORWARD : 'forward'; FUSION : 'fusion'; GROUP : 'group'; INDUCTION : 'induction'; INIT : 'init'; INTERCHANGE : 'interchange'; MAP : 'map'; OFFSET : 'offset'; OVER : 'over'; PARALLEL : 'parallel'; PRIVATE : 'private'; RANGE : 'range'; RESHAPE : 'reshape'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : [0-9] ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
Change dimension grammar definition
Change dimension grammar definition
ANTLR
bsd-2-clause
clementval/claw-compiler,clementval/claw-compiler
9731faa7302014400c00028ec0708b76a5907711
antlr4/ANTLRv4Lexer.g4
antlr4/ANTLRv4Lexer.g4
/* * [The "BSD license"] * Copyright (c) 2012 Terence Parr * Copyright (c) 2012 Sam Harwell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** A grammar for ANTLR v4 tokens */ lexer grammar ANTLRv4Lexer; tokens { TOKEN_REF, RULE_REF, LEXER_CHAR_SET } @members { /** Track whether we are inside of a rule and whether it is lexical parser. * _currentRuleType==Token.INVALID_TYPE means that we are outside of a rule. * At the first sign of a rule name reference and _currentRuleType==invalid, * we can assume that we are starting a parser rule. Similarly, seeing * a token reference when not already in rule means starting a token * rule. The terminating ';' of a rule, flips this back to invalid type. * * This is not perfect logic but works. For example, "grammar T;" means * that we start and stop a lexical rule for the "T;". Dangerous but works. * * The whole point of this state information is to distinguish * between [..arg actions..] and [charsets]. Char sets can only occur in * lexical rules and arg actions cannot occur. */ private int _currentRuleType = Token.INVALID_TYPE; public int getCurrentRuleType() { return _currentRuleType; } public void setCurrentRuleType(int ruleType) { this._currentRuleType = ruleType; } protected void handleBeginArgAction() { if (inLexerRule()) { pushMode(LexerCharSet); more(); } else { pushMode(ArgAction); more(); } } @Override public Token emit() { if (_type == ID) { String firstChar = _input.getText(Interval.of(_tokenStartCharIndex, _tokenStartCharIndex)); if (Character.isUpperCase(firstChar.charAt(0))) { _type = TOKEN_REF; } else { _type = RULE_REF; } if (_currentRuleType == Token.INVALID_TYPE) { // if outside of rule def _currentRuleType = _type; // set to inside lexer or parser rule } } else if (_type == SEMI) { // exit rule def _currentRuleType = Token.INVALID_TYPE; } return super.emit(); } private boolean inLexerRule() { return _currentRuleType == TOKEN_REF; } private boolean inParserRule() { // not used, but added for clarity return _currentRuleType == RULE_REF; } } DOC_COMMENT : '/**' .*? ('*/' | EOF) ; BLOCK_COMMENT : '/*' .*? ('*/' | EOF) -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ; BEGIN_ARG_ACTION : '[' {handleBeginArgAction();} ; BEGIN_ACTION : '{' -> more, pushMode(Action) ; // OPTIONS and TOKENS must also consume the opening brace that captures // their option block, as this is teh easiest way to parse it separate // to an ACTION block, despite it usingthe same {} delimiters. // OPTIONS : 'options' [ \t\f\n\r]* '{' ; TOKENS : 'tokens' [ \t\f\n\r]* '{' ; IMPORT : 'import' ; FRAGMENT : 'fragment' ; LEXER : 'lexer' ; PARSER : 'parser' ; GRAMMAR : 'grammar' ; PROTECTED : 'protected' ; PUBLIC : 'public' ; PRIVATE : 'private' ; RETURNS : 'returns' ; LOCALS : 'locals' ; THROWS : 'throws' ; CATCH : 'catch' ; FINALLY : 'finally' ; MODE : 'mode' ; COLON : ':' ; COLONCOLON : '::' ; COMMA : ',' ; SEMI : ';' ; LPAREN : '(' ; RPAREN : ')' ; RARROW : '->' ; LT : '<' ; GT : '>' ; ASSIGN : '=' ; QUESTION : '?' ; STAR : '*' ; PLUS : '+' ; PLUS_ASSIGN : '+=' ; OR : '|' ; DOLLAR : '$' ; DOT : '.' ; RANGE : '..' ; AT : '@' ; POUND : '#' ; NOT : '~' ; RBRACE : '}' ; /** Allow unicode rule/token names */ ID : NameStartChar NameChar*; fragment NameChar : NameStartChar | '0'..'9' | '_' | '\u00B7' | '\u0300'..'\u036F' | '\u203F'..'\u2040' ; fragment NameStartChar : 'A'..'Z' | 'a'..'z' | '\u00C0'..'\u00D6' | '\u00D8'..'\u00F6' | '\u00F8'..'\u02FF' | '\u0370'..'\u037D' | '\u037F'..'\u1FFF' | '\u200C'..'\u200D' | '\u2070'..'\u218F' | '\u2C00'..'\u2FEF' | '\u3001'..'\uD7FF' | '\uF900'..'\uFDCF' | '\uFDF0'..'\uFFFD' ; // ignores | ['\u10000-'\uEFFFF] ; INT : [0-9]+ ; // ANTLR makes no distinction between a single character literal and a // multi-character string. All literals are single quote delimited and // may contain unicode escape sequences of the form \uxxxx, where x // is a valid hexadecimal number (as per Java basically). STRING_LITERAL : '\'' (ESC_SEQ | ~['\r\n\\])* '\'' ; UNTERMINATED_STRING_LITERAL : '\'' (ESC_SEQ | ~['\r\n\\])* ; // Any kind of escaped character that we can embed within ANTLR // literal strings. fragment ESC_SEQ : '\\' ( // The standard escaped character set such as tab, newline, etc. [btnfr"'\\] | // A Java style Unicode escape sequence UNICODE_ESC | // Invalid escape . | // Invalid escape at end of file EOF ) ; fragment UNICODE_ESC : 'u' (HEX_DIGIT (HEX_DIGIT (HEX_DIGIT HEX_DIGIT?)?)?)? ; fragment HEX_DIGIT : [0-9a-fA-F] ; WS : [ \t\r\n\f]+ -> channel(HIDDEN) ; // ----------------- // Illegal Character // // This is an illegal character trap which is always the last rule in the // lexer specification. It matches a single character of any value and being // the last rule in the file will match when no other rule knows what to do // about the character. It is reported as an error but is not passed on to the // parser. This means that the parser to deal with the gramamr file anyway // but we will not try to analyse or code generate from a file with lexical // errors. // ERRCHAR : . -> channel(HIDDEN) ; mode ArgAction; // E.g., [int x, List<String> a[]] NESTED_ARG_ACTION : '[' -> more, pushMode(ArgAction) ; ARG_ACTION_ESCAPE : '\\' . -> more ; ARG_ACTION_STRING_LITERAL : ('"' ('\\' . | ~["\\])* '"')-> more ; ARG_ACTION_CHAR_LITERAL : ('"' '\\' . | ~["\\] '"') -> more ; ARG_ACTION : ']' -> popMode ; UNTERMINATED_ARG_ACTION // added this to return non-EOF token type here. EOF did something weird : EOF -> popMode ; ARG_ACTION_CHAR // must be last : . -> more ; // ---------------- // Action structure // // Many language targets use {} as block delimiters and so we // must recursively match {} delimited blocks to balance the // braces. Additionally, we must make some assumptions about // literal string representation in the target language. We assume // that they are delimited by ' or " and so consume these // in their own alts so as not to inadvertantly match {}. // This mode is recursive on matching a { mode Action; NESTED_ACTION : '{' -> more, pushMode(Action) ; ACTION_ESCAPE : '\\' . -> more ; ACTION_STRING_LITERAL : '"' ('\\' . | ~["\\])* '"' -> more ; ACTION_CHAR_LITERAL : ('"' '\\' . | ~["\\] '"') -> more ; ACTION_COMMENT : (BLOCK_COMMENT |LINE_COMMENT ) -> more ; ACTION : '}' { popMode(); if ( _modeStack.size()>0 ) more(); // keep scarfing until outermost } } ; UNTERMINATED_ACTION : EOF -> popMode ; ACTION_CHAR : . -> more ; mode LexerCharSet; LEXER_CHAR_SET_BODY : ( ~[\]\\] | '\\' . )+ -> more ; LEXER_CHAR_SET : ']' -> popMode ; UNTERMINATED_CHAR_SET : EOF -> popMode ;
/* * [The "BSD license"] * Copyright (c) 2014 Terence Parr * Copyright (c) 2014 Sam Harwell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** A grammar for ANTLR v4 tokens */ lexer grammar ANTLRv4Lexer; tokens { TOKEN_REF, RULE_REF, LEXER_CHAR_SET } @members { /** Track whether we are inside of a rule and whether it is lexical parser. * _currentRuleType==Token.INVALID_TYPE means that we are outside of a rule. * At the first sign of a rule name reference and _currentRuleType==invalid, * we can assume that we are starting a parser rule. Similarly, seeing * a token reference when not already in rule means starting a token * rule. The terminating ';' of a rule, flips this back to invalid type. * * This is not perfect logic but works. For example, "grammar T;" means * that we start and stop a lexical rule for the "T;". Dangerous but works. * * The whole point of this state information is to distinguish * between [..arg actions..] and [charsets]. Char sets can only occur in * lexical rules and arg actions cannot occur. */ private int _currentRuleType = Token.INVALID_TYPE; public int getCurrentRuleType() { return _currentRuleType; } public void setCurrentRuleType(int ruleType) { this._currentRuleType = ruleType; } protected void handleBeginArgAction() { if (inLexerRule()) { pushMode(LexerCharSet); more(); } else { pushMode(ArgAction); more(); } } @Override public Token emit() { if (_type == ID) { String firstChar = _input.getText(Interval.of(_tokenStartCharIndex, _tokenStartCharIndex)); if (Character.isUpperCase(firstChar.charAt(0))) { _type = TOKEN_REF; } else { _type = RULE_REF; } if (_currentRuleType == Token.INVALID_TYPE) { // if outside of rule def _currentRuleType = _type; // set to inside lexer or parser rule } } else if (_type == SEMI) { // exit rule def _currentRuleType = Token.INVALID_TYPE; } return super.emit(); } private boolean inLexerRule() { return _currentRuleType == TOKEN_REF; } private boolean inParserRule() { // not used, but added for clarity return _currentRuleType == RULE_REF; } } DOC_COMMENT : '/**' .*? ('*/' | EOF) ; BLOCK_COMMENT : '/*' .*? ('*/' | EOF) -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ; BEGIN_ARG_ACTION : '[' {handleBeginArgAction();} ; // OPTIONS and TOKENS must also consume the opening brace that captures // their option block, as this is teh easiest way to parse it separate // to an ACTION block, despite it usingthe same {} delimiters. // OPTIONS : 'options' [ \t\f\n\r]* '{' ; TOKENS : 'tokens' [ \t\f\n\r]* '{' ; IMPORT : 'import' ; FRAGMENT : 'fragment' ; LEXER : 'lexer' ; PARSER : 'parser' ; GRAMMAR : 'grammar' ; PROTECTED : 'protected' ; PUBLIC : 'public' ; PRIVATE : 'private' ; RETURNS : 'returns' ; LOCALS : 'locals' ; THROWS : 'throws' ; CATCH : 'catch' ; FINALLY : 'finally' ; MODE : 'mode' ; COLON : ':' ; COLONCOLON : '::' ; COMMA : ',' ; SEMI : ';' ; LPAREN : '(' ; RPAREN : ')' ; RARROW : '->' ; LT : '<' ; GT : '>' ; ASSIGN : '=' ; QUESTION : '?' ; STAR : '*' ; PLUS : '+' ; PLUS_ASSIGN : '+=' ; OR : '|' ; DOLLAR : '$' ; DOT : '.' ; RANGE : '..' ; AT : '@' ; POUND : '#' ; NOT : '~' ; RBRACE : '}' ; /** Allow unicode rule/token names */ ID : NameStartChar NameChar*; fragment NameChar : NameStartChar | '0'..'9' | '_' | '\u00B7' | '\u0300'..'\u036F' | '\u203F'..'\u2040' ; fragment NameStartChar : 'A'..'Z' | 'a'..'z' | '\u00C0'..'\u00D6' | '\u00D8'..'\u00F6' | '\u00F8'..'\u02FF' | '\u0370'..'\u037D' | '\u037F'..'\u1FFF' | '\u200C'..'\u200D' | '\u2070'..'\u218F' | '\u2C00'..'\u2FEF' | '\u3001'..'\uD7FF' | '\uF900'..'\uFDCF' | '\uFDF0'..'\uFFFD' ; // ignores | ['\u10000-'\uEFFFF] ; INT : [0-9]+ ; // ANTLR makes no distinction between a single character literal and a // multi-character string. All literals are single quote delimited and // may contain unicode escape sequences of the form \uxxxx, where x // is a valid hexadecimal number (as per Java basically). STRING_LITERAL : '\'' (ESC_SEQ | ~['\r\n\\])* '\'' ; UNTERMINATED_STRING_LITERAL : '\'' (ESC_SEQ | ~['\r\n\\])* ; // Any kind of escaped character that we can embed within ANTLR // literal strings. fragment ESC_SEQ : '\\' ( // The standard escaped character set such as tab, newline, etc. [btnfr"'\\] | // A Java style Unicode escape sequence UNICODE_ESC | // Invalid escape . | // Invalid escape at end of file EOF ) ; fragment UNICODE_ESC : 'u' (HEX_DIGIT (HEX_DIGIT (HEX_DIGIT HEX_DIGIT?)?)?)? ; fragment HEX_DIGIT : [0-9a-fA-F] ; WS : [ \t\r\n\f]+ -> channel(HIDDEN) ; // 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 {}. ACTION : '{' ( ACTION | ACTION_ESCAPE | ACTION_STRING_LITERAL | ACTION_CHAR_LITERAL | '/*' .*? '*/' // ('*/' | EOF) | '//' ~[\r\n]* | . )*? ('}'|EOF) ; fragment ACTION_ESCAPE : '\\' . ; fragment ACTION_STRING_LITERAL : '"' (ACTION_ESCAPE | ~["\\])* '"' ; fragment ACTION_CHAR_LITERAL : '\'' (ACTION_ESCAPE | ~['\\])* '\'' ; // ----------------- // Illegal Character // // This is an illegal character trap which is always the last rule in the // lexer specification. It matches a single character of any value and being // the last rule in the file will match when no other rule knows what to do // about the character. It is reported as an error but is not passed on to the // parser. This means that the parser to deal with the gramamr file anyway // but we will not try to analyse or code generate from a file with lexical // errors. // ERRCHAR : . -> channel(HIDDEN) ; mode ArgAction; // E.g., [int x, List<String> a[]] NESTED_ARG_ACTION : '[' -> more, pushMode(ArgAction) ; ARG_ACTION_ESCAPE : '\\' . -> more ; ARG_ACTION_STRING_LITERAL : ('"' ('\\' . | ~["\\])* '"')-> more ; ARG_ACTION_CHAR_LITERAL : ('"' '\\' . | ~["\\] '"') -> more ; ARG_ACTION : ']' -> popMode ; UNTERMINATED_ARG_ACTION // added this to return non-EOF token type here. EOF did something weird : EOF -> popMode ; ARG_ACTION_CHAR // must be last : . -> more ; mode LexerCharSet; LEXER_CHAR_SET_BODY : ( ~[\]\\] | '\\' . )+ -> more ; LEXER_CHAR_SET : ']' -> popMode ; UNTERMINATED_CHAR_SET : EOF -> popMode ;
read actions more accurately
read actions more accurately
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
4f7cce6b7c725226bd044163a5adec98f6800962
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
/* Todo: * - Comments justifying and explaining every rule. */ lexer grammar CreoleTokens; options { superClass=ContextSensitiveLexer; } @members { Formatting bold; Formatting italic; Formatting strike; public void setupFormatting() { bold = new Formatting("**"); italic = new Formatting("//"); strike = new Formatting("--"); inlineFormatting.add(bold); inlineFormatting.add(italic); inlineFormatting.add(strike); } public boolean inHeader = false; public boolean start = false; public int listLevel = 0; boolean nowiki = false; boolean cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = false; boolean intr = false; public void doHdr() { String prefix = getText().trim(); boolean seekback = false; if(!prefix.substring(prefix.length() - 1).equals("=")) { prefix = prefix.substring(0, prefix.length() - 1); seekback = true; } if(prefix.length() <= 6) { if(seekback) { seek(-1); } setText(prefix); inHeader = true; } else { setType(Any); } } public void setStart() { String next1 = next(); String next2 = get(1); start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#")); } public void doList(int level) { listLevel = level; seek(-1); setStart(); resetFormatting(); } public void doUrl() { String url = getText(); String last = url.substring(url.length()-1); String next = next(); if(url.endsWith("://") || url.endsWith("mailto:")) { setType(Any); } while((last + next).equals("//") || last.matches("[\\.,)\"]")) { seek(-1); url = url.substring(0, url.length() - 1); last = url.substring(url.length()-1); next = next(); } setText(url); } public void breakOut() { resetFormatting(); listLevel = 0; inHeader = false; intr = false; nowiki = false; cpp = false; html = false; java = false; xhtml = false; xml = false; } public String[] thisKillsTheFormatting() { String[] ends = new String[7]; if(inHeader || intr) { ends[0] = "\n"; ends[1] = "\r\n"; } else { ends[0] = null; ends[1] = null; } if(intr) { ends[2] = "|"; } else { ends[2] = null; } ends[3] = "\n\n"; ends[4] = "\r\n\r\n"; if(listLevel > 0) { ends[5] = "\n*"; ends[6] = "\n#"; } else { ends[5] = null; ends[6] = null; } return ends; } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' WS? {doHdr();} ; HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ; /* ***** Lists ***** */ U1 : START '*' ~'*' {doList(1);} ; U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ; U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ; U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ; U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ; U6 : START '******' ~'*' {listLevel >= 5}? {doList(6);} ; U7 : START '*******' ~'*' {listLevel >= 6}? {doList(7);} ; U8 : START '********' ~'*' {listLevel >= 7}? {doList(8);} ; U9 : START '*********' ~'*' {listLevel >= 8}? {doList(9);} ; U10 : START '**********' ~'*' {listLevel >= 9}? {doList(10);} ; O1 : START '#' ~'#' {doList(1);} ; O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ; O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ; O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ; O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ; O6 : START '######' ~'#' {listLevel >= 5}? {doList(6);} ; O7 : START '#######' ~'#' {listLevel >= 6}? {doList(7);} ; O8 : START '########' ~'#' {listLevel >= 7}? {doList(8);} ; O9 : START '#########' ~'#' {listLevel >= 8}? {doList(9);} ; O10 : START '##########' ~'#' {listLevel >= 9}? {doList(10);} ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+? {breakOut();} ; /* ***** Tables ***** */ TdStartLn : LINE '|'+ {intr=true; setType(TdStart);} ; ThStartLn : LINE '|'+ '=' {intr=true; setType(ThStart);} ; RowEnd : '|'+ WS? LineBreak {intr}? {breakOut();} ; TdStart : '|'+ {intr}? {breakOut(); intr=true;} ; ThStart : '|'+ '=' {intr}? {breakOut(); intr=true;} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active && !prior().equals(":")}? {setFormatting(italic, Any);} ; SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ; BEnd : '**' {bold.active}? {unsetFormatting(bold);} ; IEnd : '//' {italic.active && !prior().equals(":")}? {unsetFormatting(italic);} ; SEnd : '--' {strike.active}? {unsetFormatting(strike);} ; NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ; StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ; StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ; StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ; StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ; StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ; /* ***** Links ***** */ LiSt : '[[' -> mode(LINK) ; ImSt : '{{' -> mode(LINK) ; /* ***** Breaks ***** */ InlineBrk : '\\\\' ; ParBreak : LineBreak LineBreak+ {breakOut();} ; LineBreak : '\r'? '\n' ; /* ***** Links ***** */ RawUrl : PROTOCOL (~(' '|'\t'|'\r'|'\n'|'|'|'['|']')+ '/'?)+ {doUrl();} ; fragment PROTOCOL : ('http' 's'? | 'file' | 'ftp') '://' | 'mailto:' ; Attachment : UPPER ALNUM* ALPHA ALNUM+ '.' LOWNUM+ {checkBounds("[a-zA-Z0-9@\\./=-]", "[a-zA-Z0-9@/=-]")}? ; WikiWords : (UPPER (ABBR | CAMEL) | INTERWIKI ALNUM+) {checkBounds("[\\.\\w]", "\\w")}? ; fragment INTERWIKI : ALPHA ALNUM+ ':' ; fragment ABBR : UPPER UPPER+ ; fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ; /* ***** Macros ***** */ MacroSt : '<<' -> mode(MACRO) ; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t')+ ; fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ; fragment START : {start}? | LINE ; fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*; fragment LOWNUM : (LOWER | DIGIT) ; fragment UPNUM : (UPPER | DIGIT) ; fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ; ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ; Sep : ' '* '|' ' '*; InLink : ~(']'|'}'|'|'|'\r'|'\n')+ {setText(getText().trim());}; mode MACRO; MacroName : ~(':'|'>')+ ; MacroSep : ':' -> mode(MACRO_ARGS) ; mode MACRO_ARGS; MacroArgs : . -> more ; MacroEnd : '>>' -> mode(DEFAULT_MODE) ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' ~'}' {nowiki}? {nowiki=false; seek(-1);} -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
/* Todo: * - Comments justifying and explaining every rule. */ lexer grammar CreoleTokens; options { superClass=ContextSensitiveLexer; } @members { Formatting bold; Formatting italic; Formatting strike; public void setupFormatting() { bold = new Formatting("**"); italic = new Formatting("//"); strike = new Formatting("--"); inlineFormatting.add(bold); inlineFormatting.add(italic); inlineFormatting.add(strike); } public boolean inHeader = false; public boolean start = false; public int listLevel = 0; boolean nowiki = false; boolean cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = false; boolean intr = false; public void doHdr() { String prefix = getText().trim(); boolean seekback = false; if(!prefix.substring(prefix.length() - 1).equals("=")) { prefix = prefix.substring(0, prefix.length() - 1); seekback = true; } if(prefix.length() <= 6) { if(seekback) { seek(-1); } setText(prefix); inHeader = true; } else { setType(Any); } } public void setStart() { String next1 = next(); String next2 = get(1); start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#")); } public void doList(int level) { listLevel = level; seek(-1); setStart(); resetFormatting(); } public void doUrl() { String url = getText(); String last = url.substring(url.length()-1); String next = next(); if(url.endsWith("://") || url.endsWith("mailto:")) { setType(Any); } while((last + next).equals("//") || last.matches("[\\.,)\"]")) { seek(-1); url = url.substring(0, url.length() - 1); last = url.substring(url.length()-1); next = next(); } setText(url); } public void breakOut() { resetFormatting(); listLevel = 0; inHeader = false; intr = false; nowiki = false; cpp = false; html = false; java = false; xhtml = false; xml = false; } public String[] thisKillsTheFormatting() { String[] ends = new String[7]; if(inHeader || intr) { ends[0] = "\n"; ends[1] = "\r\n"; } else { ends[0] = null; ends[1] = null; } if(intr) { ends[2] = "|"; } else { ends[2] = null; } ends[3] = "\n\n"; ends[4] = "\r\n\r\n"; if(listLevel > 0) { ends[5] = "\n*"; ends[6] = "\n#"; } else { ends[5] = null; ends[6] = null; } return ends; } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' WS? {doHdr();} ; HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ; /* ***** Lists ***** */ U1 : START '*' ~'*' {doList(1);} ; U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ; U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ; U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ; U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ; U6 : START '******' ~'*' {listLevel >= 5}? {doList(6);} ; U7 : START '*******' ~'*' {listLevel >= 6}? {doList(7);} ; U8 : START '********' ~'*' {listLevel >= 7}? {doList(8);} ; U9 : START '*********' ~'*' {listLevel >= 8}? {doList(9);} ; U10 : START '**********' ~'*' {listLevel >= 9}? {doList(10);} ; O1 : START '#' ~'#' {doList(1);} ; O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ; O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ; O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ; O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ; O6 : START '######' ~'#' {listLevel >= 5}? {doList(6);} ; O7 : START '#######' ~'#' {listLevel >= 6}? {doList(7);} ; O8 : START '########' ~'#' {listLevel >= 7}? {doList(8);} ; O9 : START '#########' ~'#' {listLevel >= 8}? {doList(9);} ; O10 : START '##########' ~'#' {listLevel >= 9}? {doList(10);} ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+? {breakOut();} ; /* ***** Tables ***** */ TdStartLn : LINE '|'+ {intr=true; setType(TdStart);} ; ThStartLn : LINE '|'+ '=' {intr=true; setType(ThStart);} ; RowEnd : '|'+ WS? LineBreak {intr}? {breakOut();} ; TdStart : '|'+ {intr}? {breakOut(); intr=true;} ; ThStart : '|'+ '=' {intr}? {breakOut(); intr=true;} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active && !prior().equals(":")}? {setFormatting(italic, Any);} ; SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ; BEnd : '**' {bold.active}? {unsetFormatting(bold);} ; IEnd : '//' {italic.active && !prior().equals(":")}? {unsetFormatting(italic);} ; SEnd : '--' {strike.active}? {unsetFormatting(strike);} ; NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ; StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ; StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ; StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ; StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ; StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ; /* ***** Links ***** */ LiSt : '[[' -> mode(LINK) ; ImSt : '{{' -> mode(LINK) ; /* ***** Breaks ***** */ InlineBrk : '\\\\' ; ParBreak : LineBreak WS? LineBreak+ {breakOut();} ; LineBreak : '\r'? '\n' ; /* ***** Links ***** */ RawUrl : PROTOCOL (~(' '|'\t'|'\r'|'\n'|'|'|'['|']')+ '/'?)+ {doUrl();} ; fragment PROTOCOL : ('http' 's'? | 'file' | 'ftp') '://' | 'mailto:' ; Attachment : UPPER ALNUM* ALPHA ALNUM+ '.' LOWNUM+ {checkBounds("[a-zA-Z0-9@\\./=-]", "[a-zA-Z0-9@/=-]")}? ; WikiWords : (UPPER (ABBR | CAMEL) | INTERWIKI ALNUM+) {checkBounds("[\\.\\w]", "\\w")}? ; fragment INTERWIKI : ALPHA ALNUM+ ':' ; fragment ABBR : UPPER UPPER+ ; fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ; /* ***** Macros ***** */ MacroSt : '<<' -> mode(MACRO) ; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t')+ ; fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ; fragment START : {start}? | LINE ; fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*; fragment LOWNUM : (LOWER | DIGIT) ; fragment UPNUM : (UPPER | DIGIT) ; fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ; ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ; Sep : ' '* '|' ' '*; InLink : ~(']'|'}'|'|'|'\r'|'\n')+ {setText(getText().trim());}; mode MACRO; MacroName : ~(':'|'>')+ ; MacroSep : ':' -> mode(MACRO_ARGS) ; mode MACRO_ARGS; MacroArgs : . -> more ; MacroEnd : '>>' -> mode(DEFAULT_MODE) ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' ~'}' {nowiki}? {nowiki=false; seek(-1);} -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
Allow inline whitespace to appear in the middle of a parbreak
Allow inline whitespace to appear in the middle of a parbreak
ANTLR
apache-2.0
strr/reviki,ashirley/reviki,strr/reviki,CoreFiling/reviki,ashirley/reviki,ashirley/reviki,CoreFiling/reviki,strr/reviki,CoreFiling/reviki,ashirley/reviki,ashirley/reviki,CoreFiling/reviki,strr/reviki,strr/reviki,CoreFiling/reviki
65655b895f6424de9d222613ac37d2152f794f44
watertemplate-engine/grammar.g4
watertemplate-engine/grammar.g4
prop_name_head : Upper- or lowercase letter A through Z ; prop_name_body : '_' | prop_name_head ; prop_name : prop_name_head | prop_name_head prop_name_body ; id : prop_name | prop_name '.' id ; // --------------------------------------------- prop_eval : ~id~ ; if : '~if' id ':' statements ':~' | '~if' id ':' statements ':else:' statements ':~' ; for : '~for' prop_name 'in' id ':' statements ':~' | '~for' prop_name 'in' id ':' statements ':else:' statements ':~' ; text : Any string ; // --------------------------------------------- statement : prop_eval | if | for | text | ε ; statements : statement | statement statements ;
prop_name_head : [a-zA-Z] ; prop_name_body : '_' | [0-9] | prop_name_head ; prop_name : prop_name_head | prop_name_head prop_name_body ; id : prop_name | prop_name '.' id ; // --------------------------------------------- prop_eval : '~' id '~' ; if : '~if' id ':' statements ':~' | '~if' id ':' statements ':else:' statements ':~' ; for : '~for' prop_name 'in' id ':' statements ':~' | '~for' prop_name 'in' id ':' statements ':else:' statements ':~' ; text : Any string ; // --------------------------------------------- statement : prop_eval | if | for | text | ε ; statements : statement | statement statements ;
Update grammar.g4
Update grammar.g4
ANTLR
apache-2.0
tiagobento/watertemplate-engine,codefacts/watertemplate-engine,codefacts/watertemplate-engine,tiagobento/watertemplate-engine
c881b853c2a70c7460d0bcd798cfaf5aae0f4c0e
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 | hierarchyExpression #withHierarchy | relationalExpression #withRelational | function #withFunction | exprAtom #withAtom ; hierarchyExpression : HIERARCHY_FUNC '(' datasetRef ',' componentRef ',' hierarchyReference ',' BOOLEAN_CONSTANT ( ',' HIERARCHY_FLAGS )? ')' ; hierarchyReference : datasetRef ; HIERARCHY_FUNC : 'hierarchy' ; HIERARCHY_FLAGS : 'sum' | 'prod'; function : getFunction #withGet | putFunction #withPut | checkFunction #withCheck | aggregationFunction #withAggregation ; getFunction : 'get' '(' datasetId ')'; putFunction : 'put(todo)'; aggregationFunction : 'sum' '(' (datasetRef|componentRef) ')' aggregationParms #aggregateSum | 'avg' '(' (datasetRef|componentRef) ')' aggregationParms #aggregateAvg ; aggregationParms: aggregationClause=(GROUP_BY|ALONG) componentRef (',' componentRef)*; ALONG : 'along' ; GROUP_BY : 'group by' ; 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 | hierarchyExpression #withHierarchy | relationalExpression #withRelational | function #withFunction | exprAtom #withAtom ; hierarchyExpression : 'hierarchy' '(' datasetRef ',' componentRef ',' hierarchyReference ',' BOOLEAN_CONSTANT ( ',' ('sum' | 'prod') )? ')' ; hierarchyReference : datasetRef ; function : getFunction #withGet | putFunction #withPut | checkFunction #withCheck | aggregationFunction #withAggregation ; getFunction : 'get' '(' datasetId ')'; putFunction : 'put(todo)'; aggregationFunction : 'sum' '(' (datasetRef|componentRef) ')' aggregationParms #aggregateSum | 'avg' '(' (datasetRef|componentRef) ')' aggregationParms #aggregateAvg ; aggregationParms: aggregationClause=(GROUP_BY|ALONG) componentRef (',' componentRef)*; ALONG : 'along' ; GROUP_BY : 'group by' ; 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;
Adjust the grammar to support sum both in hierarchy and aggregation
Adjust the grammar to support sum both in hierarchy and aggregation
ANTLR
apache-2.0
statisticsnorway/java-vtl,hadrienk/java-vtl,statisticsnorway/java-vtl,statisticsnorway/java-vtl,hadrienk/java-vtl,statisticsnorway/java-vtl,hadrienk/java-vtl
7d39a4accfa99dc8e72482a8181c62018d696bd7
tinybasic/tinybasic.g4
tinybasic/tinybasic.g4
/* BSD License Copyright (c) 2017, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar tinybasic; program : line* ; line : number statement CR | statement CR ; statement : 'PRINT' exprlist | 'IF' expression relop expression 'THEN'? statement | 'GOTO' number | 'INPUT' varlist | 'LET'? vara '=' expression | 'GOSUB' expression | 'RETURN' | 'CLEAR' | 'LIST' | 'RUN' | 'END' ; exprlist : (STRING | expression) (',' (STRING | expression))* ; varlist : vara (',' vara)* ; expression : ('+' | '-' | 'ε')? term (('+' | '-') term)* ; term : factor (('*' | '/') factor)* ; factor : vara | number ; vara : VAR | STRING ; number : DIGIT + ; relop : ('<' ('>' | '=' | 'ε')?) | ('>' ('<' | '=' | 'ε')?) | '=' | '+' | '-' ; STRING : '"' ~ ["\r\n]* '"' ; DIGIT : '0' .. '9' ; VAR : 'A' .. 'Z' ; CR : [\r\n]+ ; WS : [ \t] -> skip ;
/* BSD License Copyright (c) 2017, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar tinybasic; program : line* ; line : number statement CR | statement CR ; statement : 'PRINT' exprlist | 'IF' expression relop expression 'THEN'? statement | 'GOTO' number | 'INPUT' varlist | 'LET'? vara '=' expression | 'GOSUB' expression | 'RETURN' | 'CLEAR' | 'LIST' | 'RUN' | 'END' ; exprlist : (STRING | expression) (',' (STRING | expression))* ; varlist : vara (',' vara)* ; expression : ('+' | '-' )? term (('+' | '-') term)* ; term : factor (('*' | '/') factor)* ; factor : vara | number ; vara : VAR | STRING ; number : DIGIT + ; relop : ('<' ('>' | '=' )?) | ('>' ('<' | '=' )?) | '=' | '+' | '-' ; STRING : '"' ~ ["\r\n]* '"' ; DIGIT : '0' .. '9' ; VAR : 'A' .. 'Z' ; CR : [\r\n]+ ; WS : [ \t] -> skip ;
Remove empty set symbol
Remove empty set symbol
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
7544ddbdf3bfd166d9513ba352a322af861f4dfd
annis-service/src/main/antlr4/annis/ql/AqlLexer.g4
annis-service/src/main/antlr4/annis/ql/AqlLexer.g4
/* * Copyright 2013 SFB 632. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ lexer grammar AqlLexer; // additional tokens tokens { RANGE, ANNO, FROM_TO, DOM } TOK:'tok'; NODE:'node'; META:'meta'; AND:'&'; OR:'|'; EQ_VAL:'=='; EQ: '='; NEQ:'!='; DOMINANCE:'>'; POINTING:'->'; PRECEDENCE:'.'; NEAR:'^'; TEST:'%'; IDENT_COV:'_=_'; INCLUSION:'_i_'; OVERLAP:'_o_'; LEFT_ALIGN:'_l_'; RIGHT_ALIGN:'_r_'; LEFT_OVERLAP:'_ol_'; RIGHT_OVERLAP:'_or_'; LEFT_CHILD:'@l'; RIGHT_CHILD:'@r'; COMMON_PARENT:'$'; IDENTITY:'_ident_'; ROOT:':root'; ARITY:':arity'; TOKEN_ARITY:':tokenarity'; COMMA:','; STAR:'*'; BRACE_OPEN:'('; BRACE_CLOSE:')'; BRACKET_OPEN:'['; BRACKET_CLOSE:']'; COLON:':'; DOUBLECOLON:'::'; WS : ( ' ' | '\t' | '\r' | '\n' )+ -> skip ; VAR_DEF : ('a'..'z'|'A'..'Z') ( '0' .. '9'|'a'..'z'|'A'..'Z')* '#' ; REF : '#' ( '0' .. '9'|'a'..'z'|'A'..'Z')+ ; ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_'|'-')* ; DIGITS : ('0'..'9')+; START_TEXT_REGEX : '/' -> pushMode(IN_REGEX); START_TEXT_PLAIN:'"' -> pushMode(IN_TEXT); mode IN_REGEX; END_TEXT_REGEX : '/' -> popMode; TEXT_REGEX : (~'/')+; mode IN_TEXT; END_TEXT_PLAIN : '"' -> popMode; TEXT_PLAIN : (~'"')+;
/* * Copyright 2013 SFB 632. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ lexer grammar AqlLexer; // additional tokens tokens { RANGE, ANNO, FROM_TO, DOM } TOK:'tok'; NODE:'node'; META:'meta'; AND:'&'; OR:'|'; EQ_VAL:'=='; EQ: '='; NEQ:'!='; DOMINANCE:'>'; POINTING:'->'; PRECEDENCE:'.'; NEAR:'^'; TEST:'%'; IDENT_COV:'_=_'; INCLUSION:'_i_'; OVERLAP:'_o_'; LEFT_ALIGN:'_l_'; RIGHT_ALIGN:'_r_'; LEFT_OVERLAP:'_ol_'; RIGHT_OVERLAP:'_or_'; LEFT_CHILD:'@l'; RIGHT_CHILD:'@r'; COMMON_PARENT:'$'; IDENTITY:'_ident_'; ROOT:':root'; ARITY:':arity'; TOKEN_ARITY:':tokenarity'; COMMA:','; STAR:'*'; BRACE_OPEN:'('; BRACE_CLOSE:')'; BRACKET_OPEN:'['; BRACKET_CLOSE:']'; COLON:':'; DOUBLECOLON:'::'; WS : [ \t\r\n]+ -> skip ; VAR_DEF : [a-zA-Z] [0-9a-zA-Z]* '#' ; REF : '#' [0-9a-zA-Z]+ ; ID : [a-zA-Z_] [a-zA-Z0-9_-]* ; DIGITS : [0-9]+; START_TEXT_REGEX : '/' -> pushMode(IN_REGEX); START_TEXT_PLAIN:'"' -> pushMode(IN_TEXT); mode IN_REGEX; END_TEXT_REGEX : '/' -> popMode; TEXT_REGEX : (~'/')+; mode IN_TEXT; END_TEXT_PLAIN : '"' -> popMode; TEXT_PLAIN : (~'"')+;
use regex style character classes
use regex style character classes
ANTLR
apache-2.0
pixeldrama/ANNIS,amir-zeldes/ANNIS,amir-zeldes/ANNIS,zangsir/ANNIS,korpling/ANNIS,zangsir/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS,pixeldrama/ANNIS,pixeldrama/ANNIS,zangsir/ANNIS,amir-zeldes/ANNIS,korpling/ANNIS,zangsir/ANNIS,pixeldrama/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,zangsir/ANNIS,zangsir/ANNIS,korpling/ANNIS,korpling/ANNIS,korpling/ANNIS,amir-zeldes/ANNIS
f70e40f74099d3c9ed4c46a84d58cb41d4639147
refal/refal.g4
refal/refal.g4
/* BSD License Copyright (c) 2021, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar refal; program : f_definition (';'? program)? | external_decl ';' program | program external_decl ';' ; f_definition : f_name '{' block_ '}' | '$ENTRY' f_name '{' block_ '}' ; external_decl : ('$EXTERNAL' | '$EXTERN' | '$EXTRN') f_name_list ; f_name_list : f_name (',' f_name_list ';')? ; f_name : identifier ; block_ : sentence | sentence ';' | sentence ';' block_ ; sentence : left_side conditions '=' right_side | left_side conditions ',' block_ending ; left_side : pattern ; conditions : (',' arg_ ':' pattern conditions)? ; pattern : expression_ ; arg_ : expression_ ; right_side : expression_ ; expression_ : (term_ expression_)? ; term_ : symbol | variable | '<' expression_ '>' ; block_ending : arg_ ':' '{' block_ '}' ; symbol : identifier | DIGITS | STRING | STRING2 | CHAR ; identifier : IDENTIFER | STRING ; variable : svar | tvar | evar ; svar : 's' '.' index ; tvar : 't' '.' index ; evar : 'e' '.' index ; index : identifier | DIGITS ; DIGITS : [0-9]+ ; IDENTIFER : [a-zA-Z] [a-zA-Z0-9_-]* ; STRING : '"' ~ '"'* '"' ; STRING2 : '\'' ~ '\''* '\'' ; CHAR : '\\\'' | '\\"' | '\\\\' | '\\n' | '\\r' | '\\t' | ('\\x' [0-9] [0-9]) ; WS : [ \r\n\t]+ -> skip ;
/* BSD License Copyright (c) 2021, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar refal; program : f_definition (';'? program)? | external_decl ';' program | program external_decl ';' ; f_definition : f_name '{' block_ '}' | '$ENTRY' f_name '{' block_ '}' ; external_decl : ('$EXTERNAL' | '$EXTERN' | '$EXTRN') f_name_list ; f_name_list : f_name (',' f_name_list ';')? ; f_name : identifier ; block_ : sentence | sentence ';' | sentence ';' block_ ; sentence : left_side conditions ('=' right_side | ',' block_ending) ; left_side : pattern ; conditions : (',' arg_ ':' pattern conditions)? ; pattern : expression_ ; arg_ : expression_ ; right_side : expression_ ; expression_ : (term_ expression_)? ; term_ : symbol | variable | '<' expression_ '>' ; block_ending : arg_ ':' '{' block_ '}' ; symbol : identifier | DIGITS | STRING | STRING2 | CHAR ; identifier : IDENTIFER | STRING ; variable : svar | tvar | evar ; svar : 's' '.' index ; tvar : 't' '.' index ; evar : 'e' '.' index ; index : identifier | DIGITS ; DIGITS : [0-9]+ ; IDENTIFER : [a-zA-Z] [a-zA-Z0-9_-]* ; STRING : '"' ~ '"'* '"' ; STRING2 : '\'' ~ '\''* '\'' ; CHAR : '\\\'' | '\\"' | '\\\\' | '\\n' | '\\r' | '\\t' | ('\\x' [0-9] [0-9]) ; WS : [ \r\n\t]+ -> skip ;
Update refal/refal.g4
Update refal/refal.g4 Co-authored-by: Ivan Kochurkin <[email protected]>
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
4f95ea7c09f479c4e6057bf30402fe2bdd054934
java/grammars/org/antlr/codebuff/ANTLRv4Lexer.g4
java/grammars/org/antlr/codebuff/ANTLRv4Lexer.g4
/* * [The "BSD license"] * Copyright (c) 2014 Terence Parr * Copyright (c) 2014 Sam Harwell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** A grammar for ANTLR v4 tokens */ lexer grammar ANTLRv4Lexer; tokens { TOKEN_REF, RULE_REF, LEXER_CHAR_SET } @members { /** Track whether we are inside of a rule and whether it is lexical parser. * _currentRuleType==Token.INVALID_TYPE means that we are outside of a rule. * At the first sign of a rule name reference and _currentRuleType==invalid, * we can assume that we are starting a parser rule. Similarly, seeing * a token reference when not already in rule means starting a token * rule. The terminating ';' of a rule, flips this back to invalid type. * * This is not perfect logic but works. For example, "grammar T;" means * that we start and stop a lexical rule for the "T;". Dangerous but works. * * The whole point of this state information is to distinguish * between [..arg actions..] and [charsets]. Char sets can only occur in * lexical rules and arg actions cannot occur. */ private int _currentRuleType = Token.INVALID_TYPE; public int getCurrentRuleType() { return _currentRuleType; } public void setCurrentRuleType(int ruleType) { this._currentRuleType = ruleType; } protected void handleBeginArgAction() { if (inLexerRule()) { pushMode(LexerCharSet); more(); } else { pushMode(ArgAction); more(); } } @Override public Token emit() { if (_type == ID) { String firstChar = _input.getText(Interval.of(_tokenStartCharIndex, _tokenStartCharIndex)); if (Character.isUpperCase(firstChar.charAt(0))) { _type = TOKEN_REF; } else { _type = RULE_REF; } if (_currentRuleType == Token.INVALID_TYPE) { // if outside of rule def _currentRuleType = _type; // set to inside lexer or parser rule } } else if (_type == SEMI) { // exit rule def _currentRuleType = Token.INVALID_TYPE; } return super.emit(); } private boolean inLexerRule() { return _currentRuleType == TOKEN_REF; } private boolean inParserRule() { // not used, but added for clarity return _currentRuleType == RULE_REF; } } DOC_COMMENT : '/**' .*? ('*/' | EOF) ; BLOCK_COMMENT : '/*' .*? ('*/' | EOF) -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ; BEGIN_ARG_ACTION : '[' {handleBeginArgAction();} ; // OPTIONS and TOKENS must also consume the opening brace that captures // their option block, as this is the easiest way to parse it separate // to an ACTION block, despite it using the same {} delimiters. // OPTIONS : 'options' [ \t\f\n\r]* '{' ; TOKENS : 'tokens' [ \t\f\n\r]* '{' ; CHANNELS : 'channels' [ \t\f\n\r]* '{' ; IMPORT : 'import' ; FRAGMENT : 'fragment' ; LEXER : 'lexer' ; PARSER : 'parser' ; GRAMMAR : 'grammar' ; PROTECTED : 'protected' ; PUBLIC : 'public' ; PRIVATE : 'private' ; RETURNS : 'returns' ; LOCALS : 'locals' ; THROWS : 'throws' ; CATCH : 'catch' ; FINALLY : 'finally' ; MODE : 'mode' ; COLON : ':' ; COLONCOLON : '::' ; COMMA : ',' ; SEMI : ';' ; LPAREN : '(' ; RPAREN : ')' ; RARROW : '->' ; LT : '<' ; GT : '>' ; ASSIGN : '=' ; QUESTION : '?' ; STAR : '*' ; PLUS : '+' ; PLUS_ASSIGN : '+=' ; OR : '|' ; DOLLAR : '$' ; DOT : '.' ; RANGE : '..' ; AT : '@' ; POUND : '#' ; NOT : '~' ; RBRACE : '}' ; /** Allow unicode rule/token names */ //ID : NameStartChar NameChar*; // ##################### to allow testing ANTLR grammars in intellij preview RULE_REF : [a-z][a-zA-Z_0-9]* ; TOKEN_REF : [A-Z][a-zA-Z_0-9]* ; fragment NameChar : NameStartChar | '0'..'9' | '_' | '\u00B7' | '\u0300'..'\u036F' | '\u203F'..'\u2040' ; fragment NameStartChar : 'A'..'Z' | 'a'..'z' | '\u00C0'..'\u00D6' | '\u00D8'..'\u00F6' | '\u00F8'..'\u02FF' | '\u0370'..'\u037D' | '\u037F'..'\u1FFF' | '\u200C'..'\u200D' | '\u2070'..'\u218F' | '\u2C00'..'\u2FEF' | '\u3001'..'\uD7FF' | '\uF900'..'\uFDCF' | '\uFDF0'..'\uFFFD' ; // ignores | ['\u10000-'\uEFFFF] ; INT : [0-9]+ ; // ANTLR makes no distinction between a single character literal and a // multi-character string. All literals are single quote delimited and // may contain unicode escape sequences of the form \uxxxx, where x // is a valid hexadecimal number (as per Java basically). STRING_LITERAL : '\'' (ESC_SEQ | ~['\r\n\\])* '\'' ; UNTERMINATED_STRING_LITERAL : '\'' (ESC_SEQ | ~['\r\n\\])* ; // Any kind of escaped character that we can embed within ANTLR // literal strings. fragment ESC_SEQ : '\\' ( // The standard escaped character set such as tab, newline, etc. [btnfr"'\\] | // A Java style Unicode escape sequence UNICODE_ESC | // Invalid escape . | // Invalid escape at end of file EOF ) ; fragment UNICODE_ESC : 'u' (HEX_DIGIT (HEX_DIGIT (HEX_DIGIT HEX_DIGIT?)?)?)? ; fragment HEX_DIGIT : [0-9a-fA-F] ; WS : [ \t\r\n\f]+ -> channel(HIDDEN) ; // 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 {}. ACTION : '{' ( ACTION | ACTION_ESCAPE | ACTION_STRING_LITERAL | ACTION_CHAR_LITERAL | '/*' .*? '*/' // ('*/' | EOF) | '//' ~[\r\n]* | . )*? ('}'|EOF) ; fragment ACTION_ESCAPE : '\\' . ; fragment ACTION_STRING_LITERAL : '"' (ACTION_ESCAPE | ~["\\])* '"' ; fragment ACTION_CHAR_LITERAL : '\'' (ACTION_ESCAPE | ~['\\])* '\'' ; // ----------------- // Illegal Character // // This is an illegal character trap which is always the last rule in the // lexer specification. It matches a single character of any value and being // the last rule in the file will match when no other rule knows what to do // about the character. It is reported as an error but is not passed on to the // parser. This means that the parser to deal with the gramamr file anyway // but we will not try to analyse or code generate from a file with lexical // errors. // ERRCHAR : . -> channel(HIDDEN) ; mode ArgAction; // E.g., [int x, List<String> a[]] NESTED_ARG_ACTION : '[' -> more, pushMode(ArgAction) ; ARG_ACTION_ESCAPE : '\\' . -> more ; ARG_ACTION_STRING_LITERAL : ('"' ('\\' . | ~["\\])* '"')-> more ; ARG_ACTION_CHAR_LITERAL : ('"' '\\' . | ~["\\] '"') -> more ; ARG_ACTION : ']' -> popMode ; UNTERMINATED_ARG_ACTION // added this to return non-EOF token type here. EOF did something weird : EOF -> popMode ; ARG_ACTION_CHAR // must be last : . -> more ; mode LexerCharSet; LEXER_CHAR_SET_BODY : ( ~[\]\\] | '\\' . ) -> more ; LEXER_CHAR_SET : ']' -> popMode ; UNTERMINATED_CHAR_SET : EOF -> popMode ;
/* * [The "BSD license"] * Copyright (c) 2014 Terence Parr * Copyright (c) 2014 Sam Harwell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** A grammar for ANTLR v4 tokens */ lexer grammar ANTLRv4Lexer; tokens { TOKEN_REF, RULE_REF, LEXER_CHAR_SET } @members { /** Track whether we are inside of a rule and whether it is lexical parser. * _currentRuleType==Token.INVALID_TYPE means that we are outside of a rule. * At the first sign of a rule name reference and _currentRuleType==invalid, * we can assume that we are starting a parser rule. Similarly, seeing * a token reference when not already in rule means starting a token * rule. The terminating ';' of a rule, flips this back to invalid type. * * This is not perfect logic but works. For example, "grammar T;" means * that we start and stop a lexical rule for the "T;". Dangerous but works. * * The whole point of this state information is to distinguish * between [..arg actions..] and [charsets]. Char sets can only occur in * lexical rules and arg actions cannot occur. */ private int _currentRuleType = Token.INVALID_TYPE; public int getCurrentRuleType() { return _currentRuleType; } public void setCurrentRuleType(int ruleType) { this._currentRuleType = ruleType; } protected void handleBeginArgAction() { if (inLexerRule()) { pushMode(LexerCharSet); more(); } else { pushMode(ArgAction); more(); } } @Override public Token emit() { if (_type == TOKEN_REF || _type==RULE_REF ) { if (_currentRuleType == Token.INVALID_TYPE) { // if outside of rule def _currentRuleType = _type; // set to inside lexer or parser rule } } else if (_type == SEMI) { // exit rule def _currentRuleType = Token.INVALID_TYPE; } return super.emit(); } private boolean inLexerRule() { return _currentRuleType == TOKEN_REF; } private boolean inParserRule() { // not used, but added for clarity return _currentRuleType == RULE_REF; } } DOC_COMMENT : '/**' .*? ('*/' | EOF) ; BLOCK_COMMENT : '/*' .*? ('*/' | EOF) -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ; BEGIN_ARG_ACTION : '[' {handleBeginArgAction();} ; // OPTIONS and TOKENS must also consume the opening brace that captures // their option block, as this is the easiest way to parse it separate // to an ACTION block, despite it using the same {} delimiters. // OPTIONS : 'options' [ \t\f\n\r]* '{' ; TOKENS : 'tokens' [ \t\f\n\r]* '{' ; CHANNELS : 'channels' [ \t\f\n\r]* '{' ; IMPORT : 'import' ; FRAGMENT : 'fragment' ; LEXER : 'lexer' ; PARSER : 'parser' ; GRAMMAR : 'grammar' ; PROTECTED : 'protected' ; PUBLIC : 'public' ; PRIVATE : 'private' ; RETURNS : 'returns' ; LOCALS : 'locals' ; THROWS : 'throws' ; CATCH : 'catch' ; FINALLY : 'finally' ; MODE : 'mode' ; COLON : ':' ; COLONCOLON : '::' ; COMMA : ',' ; SEMI : ';' ; LPAREN : '(' ; RPAREN : ')' ; RARROW : '->' ; LT : '<' ; GT : '>' ; ASSIGN : '=' ; QUESTION : '?' ; STAR : '*' ; PLUS : '+' ; PLUS_ASSIGN : '+=' ; OR : '|' ; DOLLAR : '$' ; DOT : '.' ; RANGE : '..' ; AT : '@' ; POUND : '#' ; NOT : '~' ; RBRACE : '}' ; /** Allow unicode rule/token names */ //ID : NameStartChar NameChar*; // ##################### to allow testing ANTLR grammars in intellij preview RULE_REF : [a-z][a-zA-Z_0-9]* ; TOKEN_REF : [A-Z][a-zA-Z_0-9]* ; fragment NameChar : NameStartChar | '0'..'9' | '_' | '\u00B7' | '\u0300'..'\u036F' | '\u203F'..'\u2040' ; fragment NameStartChar : 'A'..'Z' | 'a'..'z' | '\u00C0'..'\u00D6' | '\u00D8'..'\u00F6' | '\u00F8'..'\u02FF' | '\u0370'..'\u037D' | '\u037F'..'\u1FFF' | '\u200C'..'\u200D' | '\u2070'..'\u218F' | '\u2C00'..'\u2FEF' | '\u3001'..'\uD7FF' | '\uF900'..'\uFDCF' | '\uFDF0'..'\uFFFD' ; // ignores | ['\u10000-'\uEFFFF] ; INT : [0-9]+ ; // ANTLR makes no distinction between a single character literal and a // multi-character string. All literals are single quote delimited and // may contain unicode escape sequences of the form \uxxxx, where x // is a valid hexadecimal number (as per Java basically). STRING_LITERAL : '\'' (ESC_SEQ | ~['\r\n\\])* '\'' ; UNTERMINATED_STRING_LITERAL : '\'' (ESC_SEQ | ~['\r\n\\])* ; // Any kind of escaped character that we can embed within ANTLR // literal strings. fragment ESC_SEQ : '\\' ( // The standard escaped character set such as tab, newline, etc. [btnfr"'\\] | // A Java style Unicode escape sequence UNICODE_ESC | // Invalid escape . | // Invalid escape at end of file EOF ) ; fragment UNICODE_ESC : 'u' (HEX_DIGIT (HEX_DIGIT (HEX_DIGIT HEX_DIGIT?)?)?)? ; fragment HEX_DIGIT : [0-9a-fA-F] ; WS : [ \t\r\n\f]+ -> channel(HIDDEN) ; // 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 {}. ACTION : '{' ( ACTION | ACTION_ESCAPE | ACTION_STRING_LITERAL | ACTION_CHAR_LITERAL | '/*' .*? '*/' // ('*/' | EOF) | '//' ~[\r\n]* | . )*? ('}'|EOF) ; fragment ACTION_ESCAPE : '\\' . ; fragment ACTION_STRING_LITERAL : '"' (ACTION_ESCAPE | ~["\\])* '"' ; fragment ACTION_CHAR_LITERAL : '\'' (ACTION_ESCAPE | ~['\\])* '\'' ; // ----------------- // Illegal Character // // This is an illegal character trap which is always the last rule in the // lexer specification. It matches a single character of any value and being // the last rule in the file will match when no other rule knows what to do // about the character. It is reported as an error but is not passed on to the // parser. This means that the parser to deal with the gramamr file anyway // but we will not try to analyse or code generate from a file with lexical // errors. // ERRCHAR : . -> channel(HIDDEN) ; mode ArgAction; // E.g., [int x, List<String> a[]] NESTED_ARG_ACTION : '[' -> more, pushMode(ArgAction) ; ARG_ACTION_ESCAPE : '\\' . -> more ; ARG_ACTION_STRING_LITERAL : ('"' ('\\' . | ~["\\])* '"')-> more ; ARG_ACTION_CHAR_LITERAL : ('"' '\\' . | ~["\\] '"') -> more ; ARG_ACTION : ']' -> popMode ; UNTERMINATED_ARG_ACTION // added this to return non-EOF token type here. EOF did something weird : EOF -> popMode ; ARG_ACTION_CHAR // must be last : . -> more ; mode LexerCharSet; LEXER_CHAR_SET_BODY : ( ~[\]\\] | '\\' . ) -> more ; LEXER_CHAR_SET : ']' -> popMode ; UNTERMINATED_CHAR_SET : EOF -> popMode ;
fix antlr lexer
fix antlr lexer
ANTLR
bsd-2-clause
antlr/codebuff,antlr/codebuff,MorganZhang100/codebuff,antlr/codebuff,MorganZhang100/codebuff
96d8285f3c6b35b7492756733a3f54af248db958
sharding-core/src/main/antlr4/imports/BaseRule.g4
sharding-core/src/main/antlr4/imports/BaseRule.g4
grammar BaseRule; import DataType, Keyword, Symbol; ID: (BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_? DOT)? (BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_?) | [a-zA-Z_$0-9]+ DOT ASTERISK ; schemaName : ID ; databaseName : ID ; domainName : ID ; tableName : ID ; columnName : ID ; sequenceName : ID ; tablespaceName : ID ; collationName : STRING | ID ; indexName : ID ; alias : ID ; cteName : ID ; parserName : ID ; extensionName : ID ; rowName : ID ; opclass : ID ; fileGroup : ID ; groupName : ID ; constraintName : ID ; keyName : ID ; typeName : ID ; xmlSchemaCollection : ID ; columnSetName : ID ; directoryName : ID ; triggerName : ID ; routineName : ID ; roleName : STRING | ID ; partitionName : ID ; rewriteRuleName : ID ; ownerName : ID ; userName : STRING | ID ; serverName : ID ; dataTypeLength : LP_ (NUMBER (COMMA NUMBER)?)? RP_ ; primaryKey : PRIMARY? KEY ; matchNone : 'Default does not match anything' ; ids : ID (COMMA ID)* ; idList : LP_ ids RP_ ; rangeClause : NUMBER (COMMA NUMBER)* | NUMBER OFFSET NUMBER ; schemaNames : schemaName (COMMA schemaName)* ; databaseNames : databaseName (COMMA databaseName)* ; domainNames : domainName (COMMA domainName)* ; tableNamesWithParen : LP_ tableNames RP_ ; tableNames : tableName (COMMA tableName)* ; columnNamesWithParen : LP_ columnNames RP_ ; columnNames : columnName (COMMA columnName)* ; columnList : LP_ columnNames RP_ ; sequenceNames : sequenceName (COMMA sequenceName)* ; tablespaceNames : tablespaceName (COMMA tablespaceName)* ; indexNames : indexName (COMMA indexName)* ; typeNames : typeName (COMMA typeName)* ; rowNames : rowName (COMMA rowName)* ; roleNames : roleName (COMMA roleName)* ; userNames : userName (COMMA userName)* ; serverNames : serverName (COMMA serverName)* ; bitExprs: bitExpr (COMMA bitExpr)* ; exprs : expr (COMMA expr)* ; exprsWithParen : LP_ exprs RP_ ; expr : expr AND expr | expr AND_ expr | expr XOR expr | LP_ expr RP_ | NOT expr | NOT_ expr | expr OR expr | expr OR_ expr | booleanPrimary | exprRecursive ; exprRecursive : matchNone ; booleanPrimary : booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL) | booleanPrimary SAFE_EQ predicate | booleanPrimary comparisonOperator predicate | booleanPrimary comparisonOperator (ALL | ANY) subquery | predicate ; comparisonOperator : EQ_ | GTE | GT | LTE | LT | NEQ_ | NEQ ; predicate : bitExpr NOT? IN subquery | bitExpr NOT? IN LP_ simpleExpr ( COMMA simpleExpr)* RP_ | bitExpr NOT? BETWEEN simpleExpr AND predicate | bitExpr SOUNDS LIKE simpleExpr | bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)* | bitExpr NOT? REGEXP simpleExpr | bitExpr ; bitExpr : bitExpr BIT_INCLUSIVE_OR bitExpr | bitExpr BIT_AND bitExpr | bitExpr SIGNED_LEFT_SHIFT bitExpr | bitExpr SIGNED_RIGHT_SHIFT bitExpr | bitExpr PLUS bitExpr | bitExpr MINUS bitExpr | bitExpr ASTERISK bitExpr | bitExpr SLASH bitExpr | bitExpr MOD bitExpr | bitExpr MOD_ bitExpr | bitExpr BIT_EXCLUSIVE_OR bitExpr //| bitExpr '+' interval_expr //| bitExpr '-' interval_expr | simpleExpr ; simpleExpr : functionCall | liter | 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 orderByItem (COMMA orderByItem)* ; orderByItem : (columnName | NUMBER |expr) (ASC|DESC)? ;
grammar BaseRule; import DataType, Keyword, Symbol; ID: (BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_? DOT)? (BQ_?[a-zA-Z_$][a-zA-Z0-9_$]* BQ_?) | [a-zA-Z_$0-9]+ DOT ASTERISK ; schemaName : ID ; databaseName : ID ; domainName : ID ; tableName : ID ; columnName : ID ; sequenceName : ID ; tablespaceName : ID ; collationName : STRING | ID ; indexName : ID ; alias : ID ; cteName : ID ; parserName : ID ; extensionName : ID ; rowName : ID ; opclass : ID ; fileGroup : ID ; groupName : ID ; constraintName : ID ; keyName : ID ; typeName : ID ; xmlSchemaCollection : ID ; columnSetName : ID ; directoryName : ID ; triggerName : ID ; routineName : ID ; roleName : STRING | ID ; partitionName : ID ; rewriteRuleName : ID ; ownerName : ID ; userName : STRING | ID ; serverName : ID ; dataTypeLength : LP_ (NUMBER (COMMA NUMBER)?)? RP_ ; primaryKey : PRIMARY? KEY ; matchNone : 'Default does not match anything' ; ids : ID (COMMA ID)* ; idList : LP_ ids RP_ ; rangeClause : NUMBER (COMMA NUMBER)* | NUMBER OFFSET NUMBER ; schemaNames : schemaName (COMMA schemaName)* ; databaseNames : databaseName (COMMA databaseName)* ; domainNames : domainName (COMMA domainName)* ; tableNamesWithParen : LP_ tableNames RP_ ; tableNames : tableName (COMMA tableName)* ; columnNamesWithParen : LP_ columnNames RP_ ; columnNames : columnName (COMMA columnName)* ; columnList : LP_ columnNames RP_ ; sequenceNames : sequenceName (COMMA sequenceName)* ; tablespaceNames : tablespaceName (COMMA tablespaceName)* ; indexNames : indexName (COMMA indexName)* ; typeNames : typeName (COMMA typeName)* ; rowNames : rowName (COMMA rowName)* ; roleNames : roleName (COMMA roleName)* ; userNames : userName (COMMA userName)* ; serverNames : serverName (COMMA serverName)* ; bitExprs: bitExpr (COMMA bitExpr)* ; exprs : expr (COMMA expr)* ; exprsWithParen : LP_ exprs RP_ ; expr : expr AND expr | expr AND_ expr | expr XOR expr | LP_ expr RP_ | NOT expr | NOT_ expr | expr OR expr | expr OR_ expr | booleanPrimary | exprRecursive ; exprRecursive : matchNone ; booleanPrimary : booleanPrimary IS NOT? (TRUE | FALSE | UNKNOWN |NULL) | booleanPrimary SAFE_EQ predicate | booleanPrimary comparsionOperator predicate | booleanPrimary comparsionOperator (ALL | ANY) subquery | predicate ; comparsionOperator : EQ_ | GTE | GT | LTE | LT | NEQ_ | NEQ ; predicate : bitExpr NOT? IN subquery | bitExpr NOT? IN LP_ simpleExpr (COMMA simpleExpr)* RP_ | bitExpr NOT? BETWEEN simpleExpr AND predicate | bitExpr SOUNDS LIKE simpleExpr | bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)* | bitExpr NOT? REGEXP simpleExpr | bitExpr ; bitExpr : bitExpr BIT_INCLUSIVE_OR bitExpr | bitExpr BIT_AND bitExpr | bitExpr SIGNED_LEFT_SHIFT bitExpr | bitExpr SIGNED_RIGHT_SHIFT bitExpr | bitExpr PLUS bitExpr | bitExpr MINUS bitExpr | bitExpr ASTERISK bitExpr | bitExpr SLASH bitExpr | bitExpr MOD bitExpr | bitExpr MOD_ bitExpr | bitExpr BIT_EXCLUSIVE_OR bitExpr //| bitExpr '+' interval_expr //| bitExpr '-' interval_expr | simpleExpr ; simpleExpr : functionCall | liter | columnName | simpleExpr collateClause //| param_marker //| variable | simpleExpr AND_ simpleExpr | PLUS simpleExpr | MINUS simpleExpr | UNARY_BIT_COMPLEMENT simpleExpr | NOT_ simpleExpr | BINARY simpleExpr | 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 | string | ID STRING collateClause? | (DATE | TIME |TIMESTAMP) STRING | ID? BIT_NUM collateClause? ; question : QUESTION ; number : NUMBER ; string : STRING ; subquery : matchNone ; collateClause : matchNone ; orderByClause : ORDER BY orderByItem (COMMA orderByItem)* ; orderByItem : (columnName | NUMBER |expr) (ASC|DESC)? ;
add question number string rule
add question number string rule
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
57ee378563ffd78267d32ec4e18437c4cb962389
projects/batfish/src/main/antlr4/org/batfish/grammar/palo_alto_nested/PaloAltoNestedLexer.g4
projects/batfish/src/main/antlr4/org/batfish/grammar/palo_alto_nested/PaloAltoNestedLexer.g4
lexer grammar PaloAltoNestedLexer; options { superClass = 'org.batfish.grammar.palo_alto_nested.parsing.PaloAltoNestedBaseLexer'; } @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(); } } CLOSE_BRACE : '}' ; CLOSE_BRACKET : ']' ; CLOSE_PAREN : ')' ; // Handle developer and RANCID-header-style line comments COMMENT_LINE : F_WhitespaceChar* [!#] {lastTokenType() == -1 || lastTokenType() == NEWLINE || lastTokenType() == SHOW_CONFIG_LINE}? F_NonNewlineChar* (F_NewlineChar+ | EOF) -> skip // so not counted as last token ; OPEN_BRACE : '{' ; OPEN_BRACKET : '[' ; OPEN_PAREN : '(' ; SEMICOLON : ';' ; // Allow initial garbage for prompt, etc. SHOW_CONFIG_LINE : F_NonNewlineChar* 'show' F_WhitespaceChar+ 'config' F_NonNewlineChar* F_NewlineChar+ -> channel(HIDDEN) ; WORD : F_QuotedString | F_Word ; NEWLINE: F_NewlineChar+ -> channel(HIDDEN); WS : F_WhitespaceChar+ -> skip // so not counted as last token ; fragment F_NewlineChar : [\r\n] ; fragment F_NonNewlineChar : ~[\r\n] ; fragment F_QuotedString : '"' ~'"'* '"' ; fragment F_WhitespaceChar : [ \t\u000C] ; fragment F_Word : F_WordStart (F_WordInteriorChar* F_WordFinalChar)? ; F_WordFinalChar : // Not whitespace, not ; or } or ] as those are nested syntax. ~[ \t\u000C\r\n;}\]] ; F_WordInteriorChar : ~[ \t\u000C\r\n] ; fragment F_WordStart : ~[ \t\u000C\r\n[\](){};] ;
lexer grammar PaloAltoNestedLexer; options { superClass = 'org.batfish.grammar.palo_alto_nested.parsing.PaloAltoNestedBaseLexer'; } CLOSE_BRACE : '}' ; CLOSE_BRACKET : ']' ; CLOSE_PAREN : ')' ; // Handle developer and RANCID-header-style line comments COMMENT_LINE : F_WhitespaceChar* [!#] {lastTokenType() == -1 || lastTokenType() == NEWLINE || lastTokenType() == SHOW_CONFIG_LINE}? F_NonNewlineChar* (F_NewlineChar+ | EOF) -> skip // so not counted as last token ; OPEN_BRACE : '{' ; OPEN_BRACKET : '[' ; OPEN_PAREN : '(' ; SEMICOLON : ';' ; // Allow initial garbage for prompt, etc. SHOW_CONFIG_LINE : F_NonNewlineChar* 'show' F_WhitespaceChar+ 'config' F_NonNewlineChar* F_NewlineChar+ -> channel(HIDDEN) ; WORD : F_QuotedString | F_Word ; NEWLINE: F_NewlineChar+ -> channel(HIDDEN); WS : F_WhitespaceChar+ -> skip // so not counted as last token ; fragment F_NewlineChar : [\r\n] ; fragment F_NonNewlineChar : ~[\r\n] ; fragment F_QuotedString : '"' ~'"'* '"' ; fragment F_WhitespaceChar : [ \t\u000C] ; fragment F_Word : F_WordStart (F_WordInteriorChar* F_WordFinalChar)? ; F_WordFinalChar : // Not whitespace, not ; or } or ] as those are nested syntax. ~[ \t\u000C\r\n;}\]] ; F_WordInteriorChar : ~[ \t\u000C\r\n] ; fragment F_WordStart : ~[ \t\u000C\r\n[\](){};] ;
delete unused members (#6786)
PAN: delete unused members (#6786)
ANTLR
apache-2.0
batfish/batfish,intentionet/batfish,dhalperi/batfish,intentionet/batfish,arifogel/batfish,intentionet/batfish,intentionet/batfish,arifogel/batfish,intentionet/batfish,batfish/batfish,arifogel/batfish,dhalperi/batfish,dhalperi/batfish,batfish/batfish
99dcd2d03ebb1983c4d3d8746d5e6a7a21d55139
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DMLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DMLStatement.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 DMLStatement; import Symbol, Keyword, Literals, BaseRule; insert : INSERT insertSpecification_ INTO? tableName partitionNames_? (insertValuesClause | setAssignmentsClause | insertSelectClause) onDuplicateKeyClause? ; insertSpecification_ : (LOW_PRIORITY | DELAYED | HIGH_PRIORITY)? IGNORE? ; partitionNames_ : PARTITION identifier_ (COMMA_ identifier_)* ; insertValuesClause : columnNames? (VALUES | VALUE) assignmentValues (COMMA_ assignmentValues)* ; insertSelectClause : columnNames? select ; onDuplicateKeyClause : ON DUPLICATE KEY UPDATE assignment (COMMA_ assignment)* ; assignment : columnName EQ_ assignmentValue ; assignmentValues : LP_ assignmentValue (COMMA_ assignmentValue)* RP_ | LP_ RP_ ; assignmentValue : expr | DEFAULT ; setAssignmentsClause : SET assignment (COMMA_ assignment)* ; update : updateClause setAssignmentsClause whereClause? ; updateClause : UPDATE LOW_PRIORITY? IGNORE? tableReferences ; delete : deleteClause whereClause? ; deleteClause : DELETE LOW_PRIORITY? QUICK? IGNORE? (fromMulti | fromSingle) ; fromSingle : FROM tableName (PARTITION ignoredIdentifiers_)? ; fromMulti : fromMultiTables FROM tableReferences | FROM fromMultiTables USING tableReferences ; fromMultiTables : fromMultiTable (COMMA_ fromMultiTable)* ; fromMultiTable : tableName DOT_ASTERISK_? ; select : unionSelect | withClause_ ; unionSelect : selectExpression (UNION (ALL | DISTINCT)? selectExpression)* ; selectExpression : selectClause fromClause? whereClause? groupByClause? havingClause? windowClause_? orderByClause? limitClause? ; selectClause : SELECT selectSpecification selectExprs ; selectSpecification : (ALL | distinct | DISTINCTROW)? HIGH_PRIORITY? STRAIGHT_JOIN? SQL_SMALL_RESULT? SQL_BIG_RESULT? SQL_BUFFER_RESULT? (SQL_CACHE | SQL_NO_CACHE)? SQL_CALC_FOUND_ROWS? ; selectExprs : (unqualifiedShorthand | selectExpr) (COMMA_ selectExpr)* ; selectExpr : (columnName | expr) AS? alias? | qualifiedShorthand ; alias : identifier_ | STRING_ ; unqualifiedShorthand : ASTERISK_ ; qualifiedShorthand : identifier_ DOT_ASTERISK_ ; fromClause : FROM tableReferences ; tableReferences : tableReference (COMMA_ tableReference)* ; tableReference : (tableFactor joinTable)+ | tableFactor joinTable+ | tableFactor ; tableFactor : tableName (PARTITION ignoredIdentifiers_)? (AS? alias)? indexHintList_? | subquery AS? alias | LP_ tableReferences RP_ ; indexHintList_ : indexHint_(COMMA_ indexHint_)* ; indexHint_ : (USE | IGNORE | FORCE) (INDEX | KEY) (FOR (JOIN | ORDER BY | GROUP BY))* LP_ indexName (COMMA_ indexName)* RP_ ; joinTable : (INNER | CROSS)? JOIN tableFactor joinCondition? | STRAIGHT_JOIN tableFactor | STRAIGHT_JOIN tableFactor joinCondition | (LEFT | RIGHT) OUTER? JOIN tableFactor joinCondition | NATURAL (INNER | (LEFT | RIGHT) (OUTER))? JOIN tableFactor ; joinCondition : ON expr | USING columnNames ; whereClause : WHERE expr ; groupByClause : GROUP BY orderByItem (COMMA_ orderByItem)* (WITH ROLLUP)? ; havingClause : HAVING expr ; limitClause : LIMIT (rangeItem_ (COMMA_ rangeItem_)? | rangeItem_ OFFSET rangeItem_) ; rangeItem_ : number | question ; windowClause_ : WINDOW windowItem_ (COMMA_ windowItem_)* ; windowItem_ : ignoredIdentifier_ AS LP_ windowSpec RP_ ; subquery : LP_ unionSelect RP_ ; caseExpress : caseCond | caseComp ; caseComp : CASE simpleExpr caseWhenComp+ elseResult? END ; caseWhenComp : WHEN simpleExpr THEN caseResult ; caseCond : CASE whenResult+ elseResult? END ; whenResult : WHEN expr THEN caseResult ; elseResult : ELSE caseResult ; caseResult : expr ; intervalExpr : INTERVAL expr ignoredIdentifier_ ; withClause_ : WITH RECURSIVE? cteClause_ (COMMA_ cteClause_)* unionSelect ; cteClause_ : ignoredIdentifier_ columnNames? AS subquery ;
/* * 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 DMLStatement; import Symbol, Keyword, Literals, BaseRule; insert : INSERT insertSpecification_ INTO? tableName partitionNames_? (insertValuesClause | setAssignmentsClause | insertSelectClause) onDuplicateKeyClause? ; insertSpecification_ : (LOW_PRIORITY | DELAYED | HIGH_PRIORITY)? IGNORE? ; partitionNames_ : PARTITION identifier_ (COMMA_ identifier_)* ; insertValuesClause : columnNames? (VALUES | VALUE) assignmentValues (COMMA_ assignmentValues)* ; insertSelectClause : columnNames? select ; onDuplicateKeyClause : ON DUPLICATE KEY UPDATE assignment (COMMA_ assignment)* ; assignment : columnName EQ_ assignmentValue ; assignmentValues : LP_ assignmentValue (COMMA_ assignmentValue)* RP_ | LP_ RP_ ; assignmentValue : expr | DEFAULT ; setAssignmentsClause : SET assignment (COMMA_ assignment)* ; update : updateClause setAssignmentsClause whereClause? ; updateClause : UPDATE LOW_PRIORITY? IGNORE? tableReferences ; delete : deleteClause whereClause? ; deleteClause : DELETE LOW_PRIORITY? QUICK? IGNORE? (fromMulti | fromSingle) ; fromSingle : FROM tableName (PARTITION ignoredIdentifiers_)? ; fromMulti : fromMultiTables FROM tableReferences | FROM fromMultiTables USING tableReferences ; fromMultiTables : fromMultiTable (COMMA_ fromMultiTable)* ; fromMultiTable : tableName DOT_ASTERISK_? ; select : unionSelect | withClause_ ; unionSelect : selectExpression (UNION (ALL | DISTINCT)? selectExpression)* ; selectExpression : selectClause fromClause? whereClause? groupByClause? havingClause? windowClause_? orderByClause? limitClause? ; selectClause : SELECT selectSpecification selectExprs ; selectSpecification : (ALL | distinct | DISTINCTROW)? HIGH_PRIORITY? STRAIGHT_JOIN? SQL_SMALL_RESULT? SQL_BIG_RESULT? SQL_BUFFER_RESULT? (SQL_CACHE | SQL_NO_CACHE)? SQL_CALC_FOUND_ROWS? ; selectExprs : (unqualifiedShorthand | selectExpr) (COMMA_ selectExpr)* ; selectExpr : (columnName | expr) AS? alias? | qualifiedShorthand ; alias : identifier_ | STRING_ ; unqualifiedShorthand : ASTERISK_ ; qualifiedShorthand : identifier_ DOT_ASTERISK_ ; fromClause : FROM tableReferences ; tableReferences : tableReference (COMMA_ tableReference)* ; tableReference : (tableFactor joinTable)+ | tableFactor joinTable+ | tableFactor ; tableFactor : tableName (PARTITION ignoredIdentifiers_)? (AS? alias)? indexHintList_? | subquery AS? alias | LP_ tableReferences RP_ ; indexHintList_ : indexHint_(COMMA_ indexHint_)* ; indexHint_ : (USE | IGNORE | FORCE) (INDEX | KEY) (FOR (JOIN | ORDER BY | GROUP BY))* LP_ indexName (COMMA_ indexName)* RP_ ; joinTable : (INNER | CROSS)? JOIN tableFactor joinCondition? | STRAIGHT_JOIN tableFactor | STRAIGHT_JOIN tableFactor joinCondition | (LEFT | RIGHT) OUTER? JOIN tableFactor joinCondition | NATURAL (INNER | (LEFT | RIGHT) (OUTER))? JOIN tableFactor ; joinCondition : ON expr | USING columnNames ; whereClause : WHERE expr ; groupByClause : GROUP BY orderByItem (COMMA_ orderByItem)* (WITH ROLLUP)? ; havingClause : HAVING expr ; limitClause : LIMIT (rangeItem_ (COMMA_ rangeItem_)? | rangeItem_ OFFSET rangeItem_) ; rangeItem_ : number | question ; windowClause_ : WINDOW windowItem_ (COMMA_ windowItem_)* ; windowItem_ : ignoredIdentifier_ AS LP_ windowSpec RP_ ; subquery : LP_ unionSelect RP_ ; withClause_ : WITH RECURSIVE? cteClause_ (COMMA_ cteClause_)* unionSelect ; cteClause_ : ignoredIdentifier_ columnNames? AS subquery ;
delete some expr
delete some expr
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
8538aacb6ba4b047989c12620dea91eedfb7ea93
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/BaseRule.g4
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/BaseRule.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar BaseRule; import Symbol, Keyword, Literals; parameterMarker : QUESTION_ ; number : NUMBER_ ; string : STRING_ ; dateTimeLiterals : (DATE | TIME | TIMESTAMP) STRING_ ; hexadecimalLiterals : HEX_DIGIT_ ; literals_ : number | string | TRUE | FALSE | NULL | BIT_NUM_ | hexadecimalLiterals | dateTimeLiterals | LBE_ identifier_ STRING_ RBE_ | IDENTIFIER_ STRING_ COLLATE (STRING_ | IDENTIFIER_)? | characterSet_? BIT_NUM_ collateClause_? ; identifier_ : IDENTIFIER_ | unreservedWord_ ; variable_ : (AT_ AT_)? (GLOBAL | PERSIST | PERSIST_ONLY | SESSION)? DOT_? identifier_ ; unreservedWord_ : ACCOUNT | ACTION | AFTER | ALGORITHM | ALWAYS | ANY | AUTO_INCREMENT | AVG_ROW_LENGTH | BEGIN | BTREE | CHAIN | CHARSET | CHECKSUM | CIPHER | CLIENT | COALESCE | COLUMNS | COLUMN_FORMAT | COMMENT | COMMIT | COMMITTED | COMPACT | COMPRESSED | COMPRESSION | CONNECTION | CONSISTENT | CURRENT | DATA | DATE | DELAY_KEY_WRITE | DISABLE | DISCARD | DISK | DUPLICATE | ENABLE | ENCRYPTION | ENFORCED | END | ENGINE | ESCAPE | EVENT | EXCHANGE | EXECUTE | FILE | FIRST | FIXED | FOLLOWING | GLOBAL | HASH | IMPORT_ | INSERT_METHOD | INVISIBLE | KEY_BLOCK_SIZE | LAST | LESS | LEVEL | MAX_ROWS | MEMORY | MIN_ROWS | MODIFY | NO | NONE | OFFSET | PACK_KEYS | PARSER | PARTIAL | PARTITIONING | PASSWORD | PERSIST | PERSIST_ONLY | PRECEDING | PRIVILEGES | PROCESS | PROXY | QUICK | REBUILD | REDUNDANT | RELOAD | REMOVE | REORGANIZE | REPAIR | REVERSE | ROLLBACK | ROLLUP | ROW_FORMAT | SAVEPOINT | SESSION | SHUTDOWN | SIMPLE | SLAVE | SOUNDS | SQL_BIG_RESULT | SQL_BUFFER_RESULT | SQL_CACHE | SQL_NO_CACHE | START | STATS_AUTO_RECALC | STATS_PERSISTENT | STATS_SAMPLE_PAGES | STORAGE | SUBPARTITION | SUPER | TABLES | TABLESPACE | TEMPORARY | THAN | TIME | TIMESTAMP | TRANSACTION | TRUNCATE | UNBOUNDED | UNKNOWN | UPGRADE | VALIDATION | VALUE | VIEW | VISIBLE | WEIGHT_STRING | WITHOUT | MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH | QUARTER | YEAR | AGAINST | LANGUAGE | MODE | QUERY | EXPANSION | BOOLEAN | MAX | MIN | SUM | COUNT | AVG | BIT_AND | BIT_OR | BIT_XOR | GROUP_CONCAT | JSON_ARRAYAGG | JSON_OBJECTAGG | STD | STDDEV | STDDEV_POP | STDDEV_SAMP | VAR_POP | VAR_SAMP | VARIANCE ; tableName : (identifier_ DOT_)? identifier_ ; columnName : (identifier_ DOT_)? identifier_ ; columnNames : LP_ columnName (COMMA_ columnName)* RP_ ; indexName : identifier_ ; expr : expr logicalOperator_ expr | notOperator_ expr | LP_ expr RP_ | booleanPrimary_ ; notOperator_ : NOT | NOT_ ; logicalOperator_ : OR | OR_ | XOR | AND | AND_ ; booleanPrimary_ : booleanPrimary_ IS NOT? (TRUE | FALSE | UNKNOWN | NULL) | booleanPrimary_ SAFE_EQ_ predicate | booleanPrimary_ comparisonOperator predicate | booleanPrimary_ comparisonOperator (ALL | ANY) subquery | predicate ; comparisonOperator : EQ_ | GTE_ | GT_ | LTE_ | LT_ | NEQ_ ; predicate : bitExpr NOT? IN subquery | bitExpr NOT? IN LP_ expr (COMMA_ expr)* RP_ | bitExpr NOT? BETWEEN bitExpr AND predicate | bitExpr SOUNDS LIKE bitExpr | bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)? | bitExpr NOT? (REGEXP | RLIKE) bitExpr | bitExpr ; bitExpr : bitExpr VERTICAL_BAR_ bitExpr | bitExpr AMPERSAND_ bitExpr | bitExpr SIGNED_LEFT_SHIFT_ bitExpr | bitExpr SIGNED_RIGHT_SHIFT_ bitExpr | bitExpr PLUS_ bitExpr | bitExpr MINUS_ bitExpr | bitExpr ASTERISK_ bitExpr | bitExpr SLASH_ bitExpr | bitExpr DIV bitExpr | bitExpr MOD bitExpr | bitExpr MOD_ bitExpr | bitExpr CARET_ bitExpr | bitExpr PLUS_ intervalExpression_ | bitExpr MINUS_ intervalExpression_ | simpleExpr ; simpleExpr : functionCall | parameterMarker | literals_ | columnName | simpleExpr COLLATE (STRING_ | identifier_) | variable_ | simpleExpr OR_ simpleExpr | (PLUS_ | MINUS_ | TILDE_ | NOT_ | BINARY) simpleExpr | ROW? LP_ expr (COMMA_ expr)* RP_ | EXISTS? subquery | LBE_ identifier_ expr RBE_ | matchExpression_ | caseExpression_ | intervalExpression_ ; functionCall : aggregationFunction | specialFunction_ | regularFunction_ ; aggregationFunction : aggregationFunctionName_ LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? RP_ overClause_? ; aggregationFunctionName_ : MAX | MIN | SUM | COUNT | AVG | BIT_AND | BIT_OR | BIT_XOR | JSON_ARRAYAGG | JSON_OBJECTAGG | STD | STDDEV | STDDEV_POP | STDDEV_SAMP | VAR_POP | VAR_SAMP | VARIANCE ; distinct : DISTINCT ; overClause_ : OVER (LP_ windowSpecification_ RP_ | identifier_) ; windowSpecification_ : identifier_? partitionClause_? orderByClause? frameClause_? ; partitionClause_ : PARTITION BY expr (COMMA_ expr)* ; frameClause_ : (ROWS | RANGE) (frameStart_ | frameBetween_) ; frameStart_ : CURRENT ROW | UNBOUNDED PRECEDING | UNBOUNDED FOLLOWING | expr PRECEDING | expr FOLLOWING ; frameEnd_ : frameStart_ ; frameBetween_ : BETWEEN frameStart_ AND frameEnd_ ; specialFunction_ : groupConcatFunction_ | windowFunction_ | castFunction_ | convertFunction_ | positionFunction_ | substringFunction_ | extractFunction_ | charFunction_ | trimFunction_ | weightStringFunction_ ; groupConcatFunction_ : GROUP_CONCAT LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? (orderByClause (SEPARATOR expr)?)? RP_ ; windowFunction_ : identifier_ LP_ expr (COMMA_ expr)* RP_ overClause_ ; castFunction_ : CAST LP_ expr AS dataType RP_ ; convertFunction_ : CONVERT LP_ expr COMMA_ dataType RP_ | CONVERT LP_ expr USING identifier_ RP_ ; positionFunction_ : POSITION LP_ expr IN expr RP_ ; substringFunction_ : (SUBSTRING | SUBSTR) LP_ expr FROM NUMBER_ (FOR NUMBER_)? RP_ ; extractFunction_ : EXTRACT LP_ identifier_ FROM expr RP_ ; charFunction_ : CHAR LP_ expr (COMMA_ expr)* (USING ignoredIdentifier_)? RP_ ; trimFunction_ : TRIM LP_ (LEADING | BOTH | TRAILING) STRING_ FROM STRING_ RP_ ; weightStringFunction_ : WEIGHT_STRING LP_ expr (AS dataType)? levelClause_? RP_ ; levelClause_ : LEVEL (levelInWeightListElement_ (COMMA_ levelInWeightListElement_)* | NUMBER_ MINUS_ NUMBER_) ; levelInWeightListElement_ : NUMBER_ (ASC | DESC)? REVERSE? ; regularFunction_ : regularFunctionName_ LP_ (expr (COMMA_ expr)* | ASTERISK_)? RP_ ; regularFunctionName_ : identifier_ | IF | CURRENT_TIMESTAMP | LOCALTIME | LOCALTIMESTAMP | NOW | REPLACE ; matchExpression_ : MATCH columnNames AGAINST (expr matchSearchModifier_?) ; matchSearchModifier_ : IN NATURAL LANGUAGE MODE | IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION | IN BOOLEAN MODE | WITH QUERY EXPANSION ; caseExpression_ : CASE simpleExpr? caseWhen_+ caseElse_? END ; caseWhen_ : WHEN expr THEN expr ; caseElse_ : ELSE expr ; intervalExpression_ : INTERVAL expr intervalUnit_ ; intervalUnit_ : MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH | QUARTER | YEAR | SECOND_MICROSECOND | MINUTE_MICROSECOND | MINUTE_SECOND | HOUR_MICROSECOND | HOUR_SECOND | HOUR_MINUTE | DAY_MICROSECOND | DAY_SECOND | DAY_MINUTE | DAY_HOUR | YEAR_MONTH ; subquery : 'Default does not match anything' ; orderByClause : ORDER BY orderByItem (COMMA_ orderByItem)* ; orderByItem : (columnName | number | expr) (ASC | DESC)? ; dataType : dataTypeName_ dataTypeLength? characterSet_? collateClause_? UNSIGNED? ZEROFILL? | dataTypeName_ LP_ STRING_ (COMMA_ STRING_)* RP_ characterSet_? collateClause_? ; dataTypeName_ : identifier_ identifier_? ; dataTypeLength : LP_ NUMBER_ (COMMA_ NUMBER_)? RP_ ; characterSet_ : (CHARACTER | CHAR) SET EQ_? ignoredIdentifier_ | CHARSET EQ_? ignoredIdentifier_ ; collateClause_ : COLLATE EQ_? (STRING_ | ignoredIdentifier_) ; ignoredIdentifier_ : identifier_ (DOT_ identifier_)? ; ignoredIdentifiers_ : ignoredIdentifier_ (COMMA_ ignoredIdentifier_)* ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar BaseRule; import Symbol, Keyword, Literals; parameterMarker : QUESTION_ ; number : NUMBER_ ; string : STRING_ | characterSet_? STRING_ collateClause_? | IDENTIFIER_ STRING_ COLLATE (STRING_ | IDENTIFIER_)? ; dateTimeLiterals : (DATE | TIME | TIMESTAMP) STRING_ | LBE_ identifier_ STRING_ RBE_ ; hexadecimalLiterals : HEX_DIGIT_ | characterSet_? HEX_DIGIT_ collateClause_? ; bitValueLiterals : BIT_NUM_ | characterSet_? BIT_NUM_ collateClause_? ; booleanLiterals : TRUE | FALSE ; nullValueLiterals : NULL ; literals_ : number | string | booleanLiterals | nullValueLiterals | bitValueLiterals | hexadecimalLiterals | dateTimeLiterals ; identifier_ : IDENTIFIER_ | unreservedWord_ ; variable_ : (AT_ AT_)? (GLOBAL | PERSIST | PERSIST_ONLY | SESSION)? DOT_? identifier_ ; unreservedWord_ : ACCOUNT | ACTION | AFTER | ALGORITHM | ALWAYS | ANY | AUTO_INCREMENT | AVG_ROW_LENGTH | BEGIN | BTREE | CHAIN | CHARSET | CHECKSUM | CIPHER | CLIENT | COALESCE | COLUMNS | COLUMN_FORMAT | COMMENT | COMMIT | COMMITTED | COMPACT | COMPRESSED | COMPRESSION | CONNECTION | CONSISTENT | CURRENT | DATA | DATE | DELAY_KEY_WRITE | DISABLE | DISCARD | DISK | DUPLICATE | ENABLE | ENCRYPTION | ENFORCED | END | ENGINE | ESCAPE | EVENT | EXCHANGE | EXECUTE | FILE | FIRST | FIXED | FOLLOWING | GLOBAL | HASH | IMPORT_ | INSERT_METHOD | INVISIBLE | KEY_BLOCK_SIZE | LAST | LESS | LEVEL | MAX_ROWS | MEMORY | MIN_ROWS | MODIFY | NO | NONE | OFFSET | PACK_KEYS | PARSER | PARTIAL | PARTITIONING | PASSWORD | PERSIST | PERSIST_ONLY | PRECEDING | PRIVILEGES | PROCESS | PROXY | QUICK | REBUILD | REDUNDANT | RELOAD | REMOVE | REORGANIZE | REPAIR | REVERSE | ROLLBACK | ROLLUP | ROW_FORMAT | SAVEPOINT | SESSION | SHUTDOWN | SIMPLE | SLAVE | SOUNDS | SQL_BIG_RESULT | SQL_BUFFER_RESULT | SQL_CACHE | SQL_NO_CACHE | START | STATS_AUTO_RECALC | STATS_PERSISTENT | STATS_SAMPLE_PAGES | STORAGE | SUBPARTITION | SUPER | TABLES | TABLESPACE | TEMPORARY | THAN | TIME | TIMESTAMP | TRANSACTION | TRUNCATE | UNBOUNDED | UNKNOWN | UPGRADE | VALIDATION | VALUE | VIEW | VISIBLE | WEIGHT_STRING | WITHOUT | MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH | QUARTER | YEAR | AGAINST | LANGUAGE | MODE | QUERY | EXPANSION | BOOLEAN | MAX | MIN | SUM | COUNT | AVG | BIT_AND | BIT_OR | BIT_XOR | GROUP_CONCAT | JSON_ARRAYAGG | JSON_OBJECTAGG | STD | STDDEV | STDDEV_POP | STDDEV_SAMP | VAR_POP | VAR_SAMP | VARIANCE ; tableName : (identifier_ DOT_)? identifier_ ; columnName : (identifier_ DOT_)? identifier_ ; columnNames : LP_ columnName (COMMA_ columnName)* RP_ ; indexName : identifier_ ; expr : expr logicalOperator_ expr | notOperator_ expr | LP_ expr RP_ | booleanPrimary_ ; notOperator_ : NOT | NOT_ ; logicalOperator_ : OR | OR_ | XOR | AND | AND_ ; booleanPrimary_ : booleanPrimary_ IS NOT? (TRUE | FALSE | UNKNOWN | NULL) | booleanPrimary_ SAFE_EQ_ predicate | booleanPrimary_ comparisonOperator predicate | booleanPrimary_ comparisonOperator (ALL | ANY) subquery | predicate ; comparisonOperator : EQ_ | GTE_ | GT_ | LTE_ | LT_ | NEQ_ ; predicate : bitExpr NOT? IN subquery | bitExpr NOT? IN LP_ expr (COMMA_ expr)* RP_ | bitExpr NOT? BETWEEN bitExpr AND predicate | bitExpr SOUNDS LIKE bitExpr | bitExpr NOT? LIKE simpleExpr (ESCAPE simpleExpr)? | bitExpr NOT? (REGEXP | RLIKE) bitExpr | bitExpr ; bitExpr : bitExpr VERTICAL_BAR_ bitExpr | bitExpr AMPERSAND_ bitExpr | bitExpr SIGNED_LEFT_SHIFT_ bitExpr | bitExpr SIGNED_RIGHT_SHIFT_ bitExpr | bitExpr PLUS_ bitExpr | bitExpr MINUS_ bitExpr | bitExpr ASTERISK_ bitExpr | bitExpr SLASH_ bitExpr | bitExpr DIV bitExpr | bitExpr MOD bitExpr | bitExpr MOD_ bitExpr | bitExpr CARET_ bitExpr | bitExpr PLUS_ intervalExpression_ | bitExpr MINUS_ intervalExpression_ | simpleExpr ; simpleExpr : functionCall | parameterMarker | literals_ | columnName | simpleExpr COLLATE (STRING_ | identifier_) | variable_ | simpleExpr OR_ simpleExpr | (PLUS_ | MINUS_ | TILDE_ | NOT_ | BINARY) simpleExpr | ROW? LP_ expr (COMMA_ expr)* RP_ | EXISTS? subquery | LBE_ identifier_ expr RBE_ | matchExpression_ | caseExpression_ | intervalExpression_ ; functionCall : aggregationFunction | specialFunction_ | regularFunction_ ; aggregationFunction : aggregationFunctionName_ LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? RP_ overClause_? ; aggregationFunctionName_ : MAX | MIN | SUM | COUNT | AVG | BIT_AND | BIT_OR | BIT_XOR | JSON_ARRAYAGG | JSON_OBJECTAGG | STD | STDDEV | STDDEV_POP | STDDEV_SAMP | VAR_POP | VAR_SAMP | VARIANCE ; distinct : DISTINCT ; overClause_ : OVER (LP_ windowSpecification_ RP_ | identifier_) ; windowSpecification_ : identifier_? partitionClause_? orderByClause? frameClause_? ; partitionClause_ : PARTITION BY expr (COMMA_ expr)* ; frameClause_ : (ROWS | RANGE) (frameStart_ | frameBetween_) ; frameStart_ : CURRENT ROW | UNBOUNDED PRECEDING | UNBOUNDED FOLLOWING | expr PRECEDING | expr FOLLOWING ; frameEnd_ : frameStart_ ; frameBetween_ : BETWEEN frameStart_ AND frameEnd_ ; specialFunction_ : groupConcatFunction_ | windowFunction_ | castFunction_ | convertFunction_ | positionFunction_ | substringFunction_ | extractFunction_ | charFunction_ | trimFunction_ | weightStringFunction_ ; groupConcatFunction_ : GROUP_CONCAT LP_ distinct? (expr (COMMA_ expr)* | ASTERISK_)? (orderByClause (SEPARATOR expr)?)? RP_ ; windowFunction_ : identifier_ LP_ expr (COMMA_ expr)* RP_ overClause_ ; castFunction_ : CAST LP_ expr AS dataType RP_ ; convertFunction_ : CONVERT LP_ expr COMMA_ dataType RP_ | CONVERT LP_ expr USING identifier_ RP_ ; positionFunction_ : POSITION LP_ expr IN expr RP_ ; substringFunction_ : (SUBSTRING | SUBSTR) LP_ expr FROM NUMBER_ (FOR NUMBER_)? RP_ ; extractFunction_ : EXTRACT LP_ identifier_ FROM expr RP_ ; charFunction_ : CHAR LP_ expr (COMMA_ expr)* (USING ignoredIdentifier_)? RP_ ; trimFunction_ : TRIM LP_ (LEADING | BOTH | TRAILING) STRING_ FROM STRING_ RP_ ; weightStringFunction_ : WEIGHT_STRING LP_ expr (AS dataType)? levelClause_? RP_ ; levelClause_ : LEVEL (levelInWeightListElement_ (COMMA_ levelInWeightListElement_)* | NUMBER_ MINUS_ NUMBER_) ; levelInWeightListElement_ : NUMBER_ (ASC | DESC)? REVERSE? ; regularFunction_ : regularFunctionName_ LP_ (expr (COMMA_ expr)* | ASTERISK_)? RP_ ; regularFunctionName_ : identifier_ | IF | CURRENT_TIMESTAMP | LOCALTIME | LOCALTIMESTAMP | NOW | REPLACE ; matchExpression_ : MATCH columnNames AGAINST (expr matchSearchModifier_?) ; matchSearchModifier_ : IN NATURAL LANGUAGE MODE | IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION | IN BOOLEAN MODE | WITH QUERY EXPANSION ; caseExpression_ : CASE simpleExpr? caseWhen_+ caseElse_? END ; caseWhen_ : WHEN expr THEN expr ; caseElse_ : ELSE expr ; intervalExpression_ : INTERVAL expr intervalUnit_ ; intervalUnit_ : MICROSECOND | SECOND | MINUTE | HOUR | DAY | WEEK | MONTH | QUARTER | YEAR | SECOND_MICROSECOND | MINUTE_MICROSECOND | MINUTE_SECOND | HOUR_MICROSECOND | HOUR_SECOND | HOUR_MINUTE | DAY_MICROSECOND | DAY_SECOND | DAY_MINUTE | DAY_HOUR | YEAR_MONTH ; subquery : 'Default does not match anything' ; orderByClause : ORDER BY orderByItem (COMMA_ orderByItem)* ; orderByItem : (columnName | number | expr) (ASC | DESC)? ; dataType : dataTypeName_ dataTypeLength? characterSet_? collateClause_? UNSIGNED? ZEROFILL? | dataTypeName_ LP_ STRING_ (COMMA_ STRING_)* RP_ characterSet_? collateClause_? ; dataTypeName_ : identifier_ identifier_? ; dataTypeLength : LP_ NUMBER_ (COMMA_ NUMBER_)? RP_ ; characterSet_ : (CHARACTER | CHAR) SET EQ_? ignoredIdentifier_ | CHARSET EQ_? ignoredIdentifier_ ; collateClause_ : COLLATE EQ_? (STRING_ | ignoredIdentifier_) ; ignoredIdentifier_ : identifier_ (DOT_ identifier_)? ; ignoredIdentifiers_ : ignoredIdentifier_ (COMMA_ ignoredIdentifier_)* ;
add hexadecimalLiterals
add hexadecimalLiterals
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
e9367896ec9b25230c6dc8d2be91bf94cfe00707
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE tableNotExistClause_ tableName createDefinitionClause_ inheritClause_ ; createIndex : CREATE createIndexSpecification_ INDEX concurrentlyClause_ (indexNotExistClause_ indexName)? ON onlyClause_ tableName ; alterTable : ALTER TABLE tableExistClause_ onlyClause_ tableName asteriskClause_ alterDefinitionClause_ ; alterIndex : ALTER INDEX indexExistClause_ indexName alterIndexDefinitionClause_ ; dropTable : DROP TABLE tableExistClause_ tableNames ; dropIndex : DROP INDEX concurrentlyClause_ indexExistClause_ indexNames ; truncateTable : TRUNCATE TABLE? onlyClause_ tableNamesClause ; createTableSpecification_ : ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? ; tableNotExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ (createDefinition (COMMA_ createDefinition)*)? RP_ ; createDefinition : columnDefinition | tableConstraint | LIKE tableName likeOption* ; columnDefinition : columnName dataType collateClause? columnConstraint* ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT ignoredIdentifier_ ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; checkOption : CHECK expr (NO INHERIT)? ; defaultExpr : CURRENT_TIMESTAMP | expr ; sequenceOptions : sequenceOption+ ; sequenceOption : START WITH? NUMBER_ | INCREMENT BY? NUMBER_ | MAXVALUE NUMBER_ | NO MAXVALUE | MINVALUE NUMBER_ | NO MINVALUE | CYCLE | NO CYCLE | CACHE NUMBER_ | OWNED BY ; indexParameters : (USING INDEX TABLESPACE ignoredIdentifier_)? | INCLUDE columnNames | WITH ; action : NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT) ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))? ; likeOption : (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnNames indexParameters | primaryKey columnNames indexParameters | EXCLUDE (USING ignoredIdentifier_)? | FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; inheritClause_ : (INHERITS tableNames)? ; createIndexSpecification_ : UNIQUE? ; concurrentlyClause_ : CONCURRENTLY? ; indexNotExistClause_ : (IF NOT EXISTS)? ; onlyClause_ : ONLY? ; tableExistClause_ : (IF EXISTS)? ; asteriskClause_ : ASTERISK_? ; alterDefinitionClause_ : alterTableActions | renameColumnSpecification | renameConstraint | renameTableSpecification_ ; alterIndexDefinitionClause_ : renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace ; renameIndexSpecification : RENAME TO indexName ; alterIndexDependsOnExtension : ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_ ; alterIndexSetTableSpace : ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)? ; tableNamesClause : tableNameClause (COMMA_ tableNameClause)* ; tableNameClause : tableName ASTERISK_? ; alterTableActions : alterTableAction (COMMA_ alterTableAction)* ; alterTableAction : addColumnSpecification | dropColumnSpecification | modifyColumnSpecification | addConstraintSpecification | ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam | VALIDATE CONSTRAINT ignoredIdentifier_ | DROP CONSTRAINT indexExistClause_ ignoredIdentifier_ (RESTRICT | CASCADE)? | (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)? | ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_ | (DISABLE | ENABLE) RULE ignoredIdentifier_ | ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_ | (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY | CLUSTER ON indexName | SET WITHOUT CLUSTER | SET (WITH | WITHOUT) OIDS | SET TABLESPACE ignoredIdentifier_ | SET (LOGGED | UNLOGGED) | SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_ | RESET LP_ storageParameter (COMMA_ storageParameter)* RP_ | INHERIT tableName | NO INHERIT tableName | OF dataTypeName_ | NOT OF | OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER) | REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING) ; addColumnSpecification : ADD COLUMN? (IF NOT EXISTS)? columnDefinition ; dropColumnSpecification : DROP COLUMN? columnExistClause_ columnName (RESTRICT | CASCADE)? ; columnExistClause_ : (IF EXISTS)? ; modifyColumnSpecification : alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)? | alterColumn SET DEFAULT expr | alterColumn DROP DEFAULT | alterColumn (SET | DROP) NOT NULL | alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)? | alterColumn alterColumnSetOption alterColumnSetOption* | alterColumn DROP IDENTITY columnExistClause_ | alterColumn SET STATISTICS NUMBER_ | alterColumn SET LP_ attributeOptions RP_ | alterColumn RESET LP_ attributeOptions RP_ | alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN) ; alterColumn : ALTER COLUMN? columnName ; alterColumnSetOption : SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)? ; attributeOptions : attributeOption (COMMA_ attributeOption)* ; attributeOption : IDENTIFIER_ EQ_ simpleExpr ; addConstraintSpecification : ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex) ; tableConstraintUsingIndex : (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam ; storageParameterWithValue : storageParameter EQ_ simpleExpr ; storageParameter : IDENTIFIER_ ; renameColumnSpecification : RENAME COLUMN? columnName TO columnName ; renameConstraint : RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_ ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; indexExistClause_ : (IF EXISTS)? ; indexNames : indexName (COMMA_ indexName)* ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE tableNotExistClause_ tableName createDefinitionClause_ inheritClause_ ; createIndex : CREATE createIndexSpecification_ INDEX concurrentlyClause_ (indexNotExistClause_ indexName)? ON onlyClause_ tableName ; alterTable : ALTER TABLE tableExistClause_ onlyClause_ tableName asteriskClause_ alterDefinitionClause_ ; alterIndex : ALTER INDEX indexExistClause_ indexName alterIndexDefinitionClause_ ; dropTable : DROP TABLE tableExistClause_ tableNames ; dropIndex : DROP INDEX concurrentlyClause_ indexExistClause_ indexNames ; truncateTable : TRUNCATE TABLE? onlyClause_ tableNamesClause ; createTableSpecification_ : ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? ; tableNotExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ (createDefinition (COMMA_ createDefinition)*)? RP_ ; createDefinition : columnDefinition | tableConstraint | LIKE tableName likeOption* ; columnDefinition : columnName dataType collateClause? columnConstraint* ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT ignoredIdentifier_ ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; checkOption : CHECK expr (NO INHERIT)? ; defaultExpr : CURRENT_TIMESTAMP | expr ; sequenceOptions : sequenceOption+ ; sequenceOption : START WITH? NUMBER_ | INCREMENT BY? NUMBER_ | MAXVALUE NUMBER_ | NO MAXVALUE | MINVALUE NUMBER_ | NO MINVALUE | CYCLE | NO CYCLE | CACHE NUMBER_ | OWNED BY ; indexParameters : (USING INDEX TABLESPACE ignoredIdentifier_)? | INCLUDE columnNames | WITH ; action : NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT) ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))? ; likeOption : (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnNames indexParameters | primaryKey columnNames indexParameters | EXCLUDE (USING ignoredIdentifier_)? | FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; inheritClause_ : (INHERITS tableNames)? ; createIndexSpecification_ : UNIQUE? ; concurrentlyClause_ : CONCURRENTLY? ; indexNotExistClause_ : (IF NOT EXISTS)? ; onlyClause_ : ONLY? ; tableExistClause_ : (IF EXISTS)? ; asteriskClause_ : ASTERISK_? ; alterDefinitionClause_ : alterTableActions | renameColumnSpecification | renameConstraint | renameTableSpecification_ ; alterIndexDefinitionClause_ : renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace ; renameIndexSpecification : RENAME TO indexName ; alterIndexDependsOnExtension : ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_ ; alterIndexSetTableSpace : ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)? ; tableNamesClause : tableNameClause (COMMA_ tableNameClause)* ; tableNameClause : tableName ASTERISK_? ; alterTableActions : alterTableAction (COMMA_ alterTableAction)* ; alterTableAction : addColumnSpecification | dropColumnSpecification | modifyColumnSpecification | addConstraintSpecification | ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam | VALIDATE CONSTRAINT ignoredIdentifier_ | DROP CONSTRAINT indexExistClause_ ignoredIdentifier_ (RESTRICT | CASCADE)? | (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)? | ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_ | (DISABLE | ENABLE) RULE ignoredIdentifier_ | ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_ | (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY | CLUSTER ON indexName | SET WITHOUT CLUSTER | SET (WITH | WITHOUT) OIDS | SET TABLESPACE ignoredIdentifier_ | SET (LOGGED | UNLOGGED) | SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_ | RESET LP_ storageParameter (COMMA_ storageParameter)* RP_ | INHERIT tableName | NO INHERIT tableName | OF dataTypeName_ | NOT OF | OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER) | REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING) ; addColumnSpecification : ADD COLUMN? (IF NOT EXISTS)? columnDefinition ; dropColumnSpecification : DROP COLUMN? columnExistClause_ columnName (RESTRICT | CASCADE)? ; columnExistClause_ : (IF EXISTS)? ; modifyColumnSpecification : modifyColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)? | modifyColumn SET DEFAULT expr | modifyColumn DROP DEFAULT | modifyColumn (SET | DROP) NOT NULL | modifyColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)? | modifyColumn alterColumnSetOption alterColumnSetOption* | modifyColumn DROP IDENTITY columnExistClause_ | modifyColumn SET STATISTICS NUMBER_ | modifyColumn SET LP_ attributeOptions RP_ | modifyColumn RESET LP_ attributeOptions RP_ | modifyColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN) ; modifyColumn : ALTER COLUMN? columnName ; alterColumnSetOption : SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)? ; attributeOptions : attributeOption (COMMA_ attributeOption)* ; attributeOption : IDENTIFIER_ EQ_ simpleExpr ; addConstraintSpecification : ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex) ; tableConstraintUsingIndex : (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam ; storageParameterWithValue : storageParameter EQ_ simpleExpr ; storageParameter : IDENTIFIER_ ; renameColumnSpecification : RENAME COLUMN? columnName TO columnName ; renameConstraint : RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_ ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; indexExistClause_ : (IF EXISTS)? ; indexNames : indexName (COMMA_ indexName)* ;
rename to modifyColumn
rename to modifyColumn
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
cad3eff27639f0477042019c1bd01ae062620023
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE temporaryClause_ TABLE existClause_ tableName createDefinitions inheritClause? ; createIndex : CREATE UNIQUE? INDEX CONCURRENTLY? ((IF NOT EXISTS)? indexName)? ON tableName ; alterTable : alterTableNameWithAsterisk (alterTableActions | renameColumnSpecification | renameConstraint) | alterTableNameExists renameTableSpecification_ ; alterIndex : alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace ; dropTable : DROP TABLE (IF EXISTS)? tableNames ; dropIndex : DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)* ; truncateTable : TRUNCATE TABLE? ONLY? tableNameParts ; 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_? ; temporaryClause_ : ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? ; existClause_ : (IF NOT EXISTS)? ; 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 tableNames ; 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 ; 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))? ; 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))? ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE temporaryClause_ TABLE existClause_ tableName createDefinitions inheritClause? ; createIndex : CREATE UNIQUE? INDEX CONCURRENTLY? ((IF NOT EXISTS)? indexName)? ON tableName ; alterTable : alterTableNameWithAsterisk (alterTableActions | renameColumnSpecification | renameConstraint) | alterTableNameExists renameTableSpecification_ ; alterIndex : alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace ; dropTable : DROP TABLE (IF EXISTS)? tableNames ; dropIndex : DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)* ; truncateTable : TRUNCATE TABLE? ONLY? tableNameParts ; temporaryClause_ : ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? ; existClause_ : (IF NOT EXISTS)? ; createDefinitions : LP_ (createDefinition (COMMA_ createDefinition)*)? RP_ ; createDefinition : columnDefinition | tableConstraint | LIKE tableName likeOption* ; columnDefinition : columnName dataType collateClause? columnConstraint* ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT ignoredIdentifier_ ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; checkOption : CHECK expr (NO INHERIT)? ; defaultExpr : CURRENT_TIMESTAMP | expr ; sequenceOptions : sequenceOption+ ; sequenceOption : START WITH? NUMBER_ | INCREMENT BY? NUMBER_ | MAXVALUE NUMBER_ | NO MAXVALUE | MINVALUE NUMBER_ | NO MINVALUE | CYCLE | NO CYCLE | CACHE NUMBER_ | OWNED BY ; indexParameters : (USING INDEX TABLESPACE ignoredIdentifier_)? | INCLUDE columnNames | WITH ; action : NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT) ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))? ; likeOption : (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnNames indexParameters | primaryKey columnNames indexParameters | EXCLUDE (USING ignoredIdentifier_)? | FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; inheritClause : INHERITS tableNames ; alterIndexName : ALTER INDEX (IF EXISTS)? indexName ; renameIndexSpecification : RENAME TO indexName ; alterIndexDependsOnExtension : ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_ ; alterIndexSetTableSpace : ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)? ; tableNameParts : tableNamePart (COMMA_ tableNamePart)* ; tableNamePart : tableName ASTERISK_? ; alterTableNameWithAsterisk : ALTER TABLE (IF EXISTS)? ONLY? tableName ASTERISK_? ; alterTableActions : alterTableAction (COMMA_ alterTableAction)* ; alterTableAction : addColumnSpecification | dropColumnSpecification | modifyColumnSpecification | addConstraintSpecification | ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam | VALIDATE CONSTRAINT ignoredIdentifier_ | DROP CONSTRAINT (IF EXISTS)? ignoredIdentifier_ (RESTRICT | CASCADE)? | (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)? | ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_ | (DISABLE | ENABLE) RULE ignoredIdentifier_ | ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_ | (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY | CLUSTER ON indexName | SET WITHOUT CLUSTER | SET (WITH | WITHOUT) OIDS | SET TABLESPACE ignoredIdentifier_ | SET (LOGGED | UNLOGGED) | SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_ | RESET LP_ storageParameter (COMMA_ storageParameter)* RP_ | INHERIT tableName | NO INHERIT tableName | OF dataTypeName_ | NOT OF | OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER) | REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING) ; tableConstraintUsingIndex : (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam ; addColumnSpecification : ADD COLUMN? (IF NOT EXISTS)? columnDefinition ; dropColumnSpecification : DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)? ; modifyColumnSpecification : alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)? | alterColumn SET DEFAULT expr | alterColumn DROP DEFAULT | alterColumn (SET | DROP) NOT NULL | alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)? | alterColumn alterColumnSetOption alterColumnSetOption* | alterColumn DROP IDENTITY (IF EXISTS)? | alterColumn SET STATISTICS NUMBER_ | alterColumn SET LP_ attributeOptions RP_ | alterColumn RESET LP_ attributeOptions RP_ | alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN) ; alterColumn : ALTER COLUMN? columnName ; alterColumnSetOption : SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)? ; attributeOptions : attributeOption (COMMA_ attributeOption)* ; attributeOption : IDENTIFIER_ EQ_ simpleExpr ; addConstraintSpecification : ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex) ; renameColumnSpecification : RENAME COLUMN? columnName TO columnName ; renameConstraint : RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_ ; storageParameterWithValue : storageParameter EQ_ simpleExpr ; storageParameter : IDENTIFIER_ ; alterTableNameExists : ALTER TABLE (IF EXISTS)? tableName ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; usingIndexType : USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN) ; excludeElement : (columnName | expr) ignoredIdentifier_? (ASC | DESC)? (NULLS (FIRST | LAST))? ;
adjust sequence of rules
adjust sequence of rules
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
7830568a8ed115f42546d69d0409dbf3aad6a56f
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; createIndex : CREATE UNIQUE? INDEX CONCURRENTLY? ((IF NOT EXISTS)? indexName)? ON tableName ; dropIndex : DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)* ; alterIndex : alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace ; createTable : createTableHeader createDefinitions inheritClause? ; alterTable : alterTableNameWithAsterisk (alterTableActions | renameColumnSpecification | renameConstraint) | alterTableNameExists renameTableSpecification_ ; truncateTable : TRUNCATE TABLE? ONLY? tableNameParts ; dropTable : DROP TABLE (IF EXISTS)? tableName (COMMA_ tableName)* ; 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 | FOREIGN KEY columnNames REFERENCES tableName columnNames (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? foreignKeyOnAction* ; excludeElement : (columnName | expr) ignoredIdentifier_? (ASC | DESC)? (NULLS (FIRST | LAST))? ;
adjust the sequences of statements for pg
adjust the sequences of statements for pg
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
bb2cd3086abd3af927c1931e81901d4a4a3755d8
src/main/antlr/mrtim/sasscompiler/grammar/Sass.g4
src/main/antlr/mrtim/sasscompiler/grammar/Sass.g4
grammar Sass; NL : '\r'? '\n' -> skip; WS : (' ' | '\t' | NL) -> skip; COMMENT_START: '/*'; COMMENT_END: '*/'; COMMENT: COMMENT_START .*? COMMENT_END; LINE_COMMENT : '//' ~[\r\n]* NL? -> skip; DSTRING : '"' ('\\"' | ~'"')* '"'; SSTRING : '\'' ('\\\'' | ~'\'')* '\''; URL : 'url' LPAREN ~[)]* RPAREN; COMMA : ','; SEMICOLON: ';'; LPAREN: '('; RPAREN: ')'; LBRACE: '{'; RBRACE: '}'; LSQBRACKET: '['; RSQBRACKET: ']'; DOLLAR: '$'; EQUALS: '='; COLON: ':'; STAR: '*'; BAR: '|'; DOT: '.'; AMPERSAND: '&'; IMPORT_KW : '@import'; MIXIN_KW: '@mixin'; FUNCTION_KW: '@function'; INCLUDE_KW: '@include'; //CSS constants EVEN_KW: 'even'; ODD_KW: 'odd'; PSEUDO_NOT_KW: ':not'; fragment PX : 'px'; fragment PT : 'pt'; fragment EM : 'em'; fragment EN : 'en'; fragment EX : 'ex'; fragment DIGITS: [0-9]+; PLUS: '+'; MINUS: '-'; DIVIDE: '/'; fragment ID_CHARS: [a-zA-Z0-9_-]; IDENTIFIER: [a-zA-Z] ID_CHARS*; VARIABLE: '$' IDENTIFIER; TILDE: '~'; RARROW: '>'; PIPE: '|'; CARET: '^'; PERCENT: '%'; HASH_ID: '#' ID_CHARS+; CLASS_NAME: DOT IDENTIFIER; string: DSTRING | SSTRING; import_target: URL | string; import_statement : IMPORT_KW import_target ( ',' import_target )* SEMICOLON; definition : ( MIXIN_KW | FUNCTION_KW) IDENTIFIER parameter_def_list block_body ; include_statement : INCLUDE_KW IDENTIFIER parameter_list? SEMICOLON; parameter_def_list: LPAREN ( COMMENT? variable_def COMMENT? (COMMA COMMENT? variable_def COMMENT?)* )? RPAREN; parameter_list: '(' ( parameter (COMMA parameter)* )? ')'; parameter: (IDENTIFIER | named_parameter | value); named_parameter: VARIABLE COMMENT? COLON COMMENT? expression_list; variable_def: VARIABLE (COMMENT? COLON COMMENT? expression_list)?; //selectors: L309-532 //selector_schema: parser.cpp:309 //selector_group: parser.cpp:336 selector_list: selector_combination (COMMA selector_combination)*; //selector_combination: parser.cpp:362 selector_combination: simple_selector (selector_combinator selector_combination)* | non_blank_combinator simple_selector (selector_combinator selector_combination)*; non_blank_combinator : (PLUS | TILDE | RARROW); selector_combinator : (non_blank_combinator | ); //simple_selector_sequence: parser.cpp:399 //simple_selector_sequence: simple_selector+; //simple_selector: parser.cpp:426 simple_selector: tag (simple_selector_element)* | simple_selector_element+; tag: IDENTIFIER; simple_selector_element: (HASH_ID | CLASS_NAME | AMPERSAND) | negated_selector | pseudo_selector | attribute_selector | placeholder_selector; placeholder_selector: PERCENT IDENTIFIER; //negated_selector: parser.cpp:453 negated_selector: PSEUDO_NOT_KW LPAREN selector_list RPAREN; //pseudo_selector: parser.cpp:464 pseudo_selector: ((pseudo_prefix)? functional ((EVEN_KW | ODD_KW) | binomial | IDENTIFIER | string )? RPAREN ) | pseudo_prefix IDENTIFIER; pseudo_prefix: COLON COLON?; functional: IDENTIFIER LPAREN; binomial: NUMBER IDENTIFIER (PLUS NUMBER)?; //attribute_selector: parser.cpp:517 attribute_selector: LSQBRACKET type_selector ((TILDE | PIPE | STAR | CARET | DOLLAR)? EQUALS (string | IDENTIFIER))? RSQBRACKET; type_selector: namespace_prefix? IDENTIFIER; namespace_prefix: (IDENTIFIER | STAR) BAR; variable: variable_def SEMICOLON; //parser.cpp:534 block_body: LBRACE ( COMMENT | import_statement // not allowed inside mixins and functions | assignment | ruleset | include_statement | variable )* RBRACE; variable_assignment: VARIABLE COLON expression_list SEMICOLON; css_identifier: MINUS? IDENTIFIER; assignment: css_identifier COLON expression_list SEMICOLON; expression_list: expression ( expression )* # ExpressionList | expression_list COMMA expression_list # MultiExpressionList; expression: expression STAR expression # MultiplyExpression | expression DIVIDE expression # DivideExpression | expression PLUS expression # PlusExpression | expression MINUS expression # MinusExpression | value # ValueExpression | LPAREN expression RPAREN # ParenExpression | LPAREN expression_list RPAREN # ListExpression; value : builtin_call | (VARIABLE | IDENTIFIER | DIMENSION | PERCENTAGE | NUMBER | URL ) | string | colour; colour: HASH_ID; NUMBER : MINUS? DIGITS+ ('.' DIGITS+)? | '.' DIGITS+; DIMENSION: NUMBER (PX | PT | EM | EN | EX ); PERCENTAGE: NUMBER '%'; builtin_call: IDENTIFIER parameter_list; ruleset: selector_list block_body; top_level: ( COMMENT | import_statement | definition | ruleset | variable | include_statement ); sass_file : top_level*;
grammar Sass; NL : '\r'? '\n' -> skip; WS : (' ' | '\t' | NL) -> skip; COMMENT_START: '/*'; COMMENT_END: '*/'; COMMENT: COMMENT_START .*? COMMENT_END; LINE_COMMENT : '//' ~[\r\n]* NL? -> skip; DSTRING : '"' ('\\"' | ~'"')* '"'; SSTRING : '\'' ('\\\'' | ~'\'')* '\''; URL : 'url' LPAREN ~[)]* RPAREN; COMMA : ','; SEMICOLON: ';'; LPAREN: '('; RPAREN: ')'; LBRACE: '{'; RBRACE: '}'; LSQBRACKET: '['; RSQBRACKET: ']'; DOLLAR: '$'; EQUALS: '='; COLON: ':'; STAR: '*'; BAR: '|'; DOT: '.'; AMPERSAND: '&'; IMPORT_KW : '@import'; MIXIN_KW: '@mixin'; FUNCTION_KW: '@function'; INCLUDE_KW: '@include'; //CSS constants EVEN_KW: 'even'; ODD_KW: 'odd'; PSEUDO_NOT_KW: ':not'; fragment PX : 'px'; fragment PT : 'pt'; fragment EM : 'em'; fragment EN : 'en'; fragment EX : 'ex'; fragment DIGITS: [0-9]+; PLUS: '+'; MINUS: '-'; DIVIDE: '/'; fragment ID_CHARS: [a-zA-Z0-9_-]; IDENTIFIER: [a-zA-Z] ID_CHARS*; VARIABLE: '$' IDENTIFIER; TILDE: '~'; RARROW: '>'; PIPE: '|'; CARET: '^'; PERCENT: '%'; HASH_ID: '#' ID_CHARS+; CLASS_NAME: DOT IDENTIFIER; string: DSTRING | SSTRING; import_target: URL | string; import_statement : IMPORT_KW import_target ( ',' import_target )* SEMICOLON; definition : ( MIXIN_KW | FUNCTION_KW) IDENTIFIER parameter_def_list block_body ; include_statement : INCLUDE_KW IDENTIFIER parameter_list? SEMICOLON; parameter_def_list: LPAREN ( COMMENT? variable_def COMMENT? (COMMA COMMENT? variable_def COMMENT?)* )? RPAREN; parameter_list: '(' ( parameter (COMMA parameter)* )? ')'; parameter: (IDENTIFIER | named_parameter | value); named_parameter: VARIABLE COMMENT? COLON COMMENT? expression_list; variable_def: VARIABLE (COMMENT? COLON COMMENT? expression_list)?; //selectors: L309-532 //selector_schema: parser.cpp:309 //selector_group: parser.cpp:336 selector_list: selector_combination (COMMA COMMA* selector_combination)* COMMA*; //selector_combination: parser.cpp:362 selector_combination: simple_selector (selector_combinator selector_combination)* | non_blank_combinator simple_selector (selector_combinator selector_combination)*; non_blank_combinator : (PLUS | TILDE | RARROW); selector_combinator : (non_blank_combinator | ); //simple_selector_sequence: parser.cpp:399 //simple_selector_sequence: simple_selector+; //simple_selector: parser.cpp:426 simple_selector: tag (simple_selector_element)* | simple_selector_element+; tag: IDENTIFIER; simple_selector_element: (HASH_ID | CLASS_NAME | AMPERSAND) | negated_selector | pseudo_selector | attribute_selector | placeholder_selector; placeholder_selector: PERCENT IDENTIFIER; //negated_selector: parser.cpp:453 negated_selector: PSEUDO_NOT_KW LPAREN selector_list RPAREN; //pseudo_selector: parser.cpp:464 pseudo_selector: ((pseudo_prefix)? functional ((EVEN_KW | ODD_KW) | binomial | IDENTIFIER | string )? RPAREN ) | pseudo_prefix IDENTIFIER; pseudo_prefix: COLON COLON?; functional: IDENTIFIER LPAREN; binomial: NUMBER IDENTIFIER (PLUS NUMBER)?; //attribute_selector: parser.cpp:517 attribute_selector: LSQBRACKET type_selector ((TILDE | PIPE | STAR | CARET | DOLLAR)? EQUALS (string | IDENTIFIER))? RSQBRACKET; type_selector: namespace_prefix? IDENTIFIER; namespace_prefix: (IDENTIFIER | STAR) BAR; variable: variable_def SEMICOLON; //parser.cpp:534 block_body: LBRACE ( COMMENT | import_statement // not allowed inside mixins and functions | assignment | ruleset | include_statement | variable )* RBRACE; variable_assignment: VARIABLE COLON expression_list SEMICOLON; css_identifier: MINUS? IDENTIFIER; assignment: css_identifier COLON expression_list SEMICOLON; expression_list: expression ( expression )* # ExpressionList | expression_list COMMA expression_list # MultiExpressionList; expression: expression STAR expression # MultiplyExpression | expression DIVIDE expression # DivideExpression | expression PLUS expression # PlusExpression | expression MINUS expression # MinusExpression | value # ValueExpression | LPAREN expression RPAREN # ParenExpression | LPAREN expression_list RPAREN # ListExpression; value : builtin_call | (VARIABLE | IDENTIFIER | DIMENSION | PERCENTAGE | NUMBER | URL ) | string | colour; colour: HASH_ID; NUMBER : MINUS? DIGITS+ ('.' DIGITS+)? | '.' DIGITS+; DIMENSION: NUMBER (PX | PT | EM | EN | EX ); PERCENTAGE: NUMBER '%'; builtin_call: IDENTIFIER parameter_list; ruleset: selector_list block_body; top_level: ( COMMENT | import_statement | definition | ruleset | variable | include_statement ); sass_file : top_level*;
Handle extra commas in selectors
Handle extra commas in selectors
ANTLR
mit
mr-tim/sass-compiler,mr-tim/sass-compiler
c74f54c0893fa81c18ca9085034287d9aa9f2d93
javascript/javascript/JavaScriptLexer.g4
javascript/javascript/JavaScriptLexer.g4
/* * The MIT License (MIT) * * Copyright (c) 2014 by Bart Kiers (original author) and Alexandre Vitorelli (contributor -> ported to CSharp) * Copyright (c) 2017-2020 by Ivan Kochurkin (Positive Technologies): added ECMAScript 6 support, cleared and transformed to the universal grammar. * Copyright (c) 2018 by Juan Alvarez (contributor -> ported to Go) * Copyright (c) 2019 by Student Main (contributor -> ES2020) * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ lexer grammar JavaScriptLexer; channels { ERROR } options { superClass=JavaScriptLexerBase; } HashBangLine: { this.IsStartOfFile()}? '#!' ~[\r\n\u2028\u2029]*; // only allowed at start MultiLineComment: '/*' .*? '*/' -> channel(HIDDEN); SingleLineComment: '//' ~[\r\n\u2028\u2029]* -> channel(HIDDEN); RegularExpressionLiteral: '/' RegularExpressionFirstChar RegularExpressionChar* {this.IsRegexPossible()}? '/' IdentifierPart*; OpenBracket: '['; CloseBracket: ']'; OpenParen: '('; CloseParen: ')'; OpenBrace: '{' {this.ProcessOpenBrace();}; TemplateCloseBrace: {this.IsInTemplateString()}? '}' -> popMode; CloseBrace: '}' {this.ProcessCloseBrace();}; SemiColon: ';'; Comma: ','; Assign: '='; QuestionMark: '?'; Colon: ':'; Ellipsis: '...'; Dot: '.'; PlusPlus: '++'; MinusMinus: '--'; Plus: '+'; Minus: '-'; BitNot: '~'; Not: '!'; Multiply: '*'; Divide: '/'; Modulus: '%'; Power: '**'; NullCoalesce: '??'; Hashtag: '#'; RightShiftArithmetic: '>>'; LeftShiftArithmetic: '<<'; RightShiftLogical: '>>>'; LessThan: '<'; MoreThan: '>'; LessThanEquals: '<='; GreaterThanEquals: '>='; Equals_: '=='; NotEquals: '!='; IdentityEquals: '==='; IdentityNotEquals: '!=='; BitAnd: '&'; BitXOr: '^'; BitOr: '|'; And: '&&'; Or: '||'; MultiplyAssign: '*='; DivideAssign: '/='; ModulusAssign: '%='; PlusAssign: '+='; MinusAssign: '-='; LeftShiftArithmeticAssign: '<<='; RightShiftArithmeticAssign: '>>='; RightShiftLogicalAssign: '>>>='; BitAndAssign: '&='; BitXorAssign: '^='; BitOrAssign: '|='; PowerAssign: '**='; ARROW: '=>'; /// Null Literals NullLiteral: 'null'; /// Boolean Literals BooleanLiteral: 'true' | 'false'; /// Numeric Literals DecimalLiteral: DecimalIntegerLiteral '.' [0-9] [0-9_]* ExponentPart? | '.' [0-9] [0-9_]* ExponentPart? | DecimalIntegerLiteral ExponentPart? ; /// Numeric Literals HexIntegerLiteral: '0' [xX] [0-9a-fA-F] HexDigit*; OctalIntegerLiteral: '0' [0-7]+ {!this.IsStrictMode()}?; OctalIntegerLiteral2: '0' [oO] [0-7] [_0-7]*; BinaryIntegerLiteral: '0' [bB] [01] [_01]*; BigHexIntegerLiteral: '0' [xX] [0-9a-fA-F] HexDigit* 'n'; BigOctalIntegerLiteral: '0' [oO] [0-7] [_0-7]* 'n'; BigBinaryIntegerLiteral: '0' [bB] [01] [_01]* 'n'; BigDecimalIntegerLiteral: DecimalIntegerLiteral 'n'; /// Keywords Break: 'break'; Do: 'do'; Instanceof: 'instanceof'; Typeof: 'typeof'; Case: 'case'; Else: 'else'; New: 'new'; Var: 'var'; Catch: 'catch'; Finally: 'finally'; Return: 'return'; Void: 'void'; Continue: 'continue'; For: 'for'; Switch: 'switch'; While: 'while'; Debugger: 'debugger'; Function_: 'function'; This: 'this'; With: 'with'; Default: 'default'; If: 'if'; Throw: 'throw'; Delete: 'delete'; In: 'in'; Try: 'try'; As: 'as'; From: 'from'; /// Future Reserved Words Class: 'class'; Enum: 'enum'; Extends: 'extends'; Super: 'super'; Const: 'const'; Export: 'export'; Import: 'import'; Async: 'async'; Await: 'await'; /// The following tokens are also considered to be FutureReservedWords /// when parsing strict mode Implements: 'implements' {this.IsStrictMode()}?; StrictLet: 'let' {this.IsStrictMode()}?; NonStrictLet: 'let' {!this.IsStrictMode()}?; Private: 'private' {this.IsStrictMode()}?; Public: 'public' {this.IsStrictMode()}?; Interface: 'interface' {this.IsStrictMode()}?; Package: 'package' {this.IsStrictMode()}?; Protected: 'protected' {this.IsStrictMode()}?; Static: 'static' {this.IsStrictMode()}?; Yield: 'yield' {this.IsStrictMode()}?; /// Identifier Names and Identifiers Identifier: IdentifierStart IdentifierPart*; /// String Literals StringLiteral: ('"' DoubleStringCharacter* '"' | '\'' SingleStringCharacter* '\'') {this.ProcessStringLiteral();} ; BackTick: '`' {this.IncreaseTemplateDepth();} -> pushMode(TEMPLATE); WhiteSpaces: [\t\u000B\u000C\u0020\u00A0]+ -> channel(HIDDEN); LineTerminator: [\r\n\u2028\u2029] -> channel(HIDDEN); /// Comments HtmlComment: '<!--' .*? '-->' -> channel(HIDDEN); CDataComment: '<![CDATA[' .*? ']]>' -> channel(HIDDEN); UnexpectedCharacter: . -> channel(ERROR); mode TEMPLATE; BackTickInside: '`' {this.DecreaseTemplateDepth();} -> type(BackTick), popMode; TemplateStringStartExpression: '${' -> pushMode(DEFAULT_MODE); TemplateStringAtom: ~[`]; // Fragment rules fragment DoubleStringCharacter : ~["\\\r\n] | '\\' EscapeSequence | LineContinuation ; fragment SingleStringCharacter : ~['\\\r\n] | '\\' EscapeSequence | LineContinuation ; fragment EscapeSequence : CharacterEscapeSequence | '0' // no digit ahead! TODO | HexEscapeSequence | UnicodeEscapeSequence | ExtendedUnicodeEscapeSequence ; fragment CharacterEscapeSequence : SingleEscapeCharacter | NonEscapeCharacter ; fragment HexEscapeSequence : 'x' HexDigit HexDigit ; fragment UnicodeEscapeSequence : 'u' HexDigit HexDigit HexDigit HexDigit | 'u' '{' HexDigit HexDigit+ '}' ; fragment ExtendedUnicodeEscapeSequence : 'u' '{' HexDigit+ '}' ; fragment SingleEscapeCharacter : ['"\\bfnrtv] ; fragment NonEscapeCharacter : ~['"\\bfnrtv0-9xu\r\n] ; fragment EscapeCharacter : SingleEscapeCharacter | [0-9] | [xu] ; fragment LineContinuation : '\\' [\r\n\u2028\u2029] ; fragment HexDigit : [_0-9a-fA-F] ; fragment DecimalIntegerLiteral : '0' | [1-9] [0-9_]* ; fragment ExponentPart : [eE] [+-]? [0-9_]+ ; fragment IdentifierPart : IdentifierStart | [\p{Mn}] | [\p{Nd}] | [\p{Pc}] | '\u200C' | '\u200D' ; fragment IdentifierStart : [\p{L}] | [$_] | '\\' UnicodeEscapeSequence ; fragment RegularExpressionFirstChar : ~[*\r\n\u2028\u2029\\/[] | RegularExpressionBackslashSequence | '[' RegularExpressionClassChar* ']' ; fragment RegularExpressionChar : ~[\r\n\u2028\u2029\\/[] | RegularExpressionBackslashSequence | '[' RegularExpressionClassChar* ']' ; fragment RegularExpressionClassChar : ~[\r\n\u2028\u2029\]\\] | RegularExpressionBackslashSequence ; fragment RegularExpressionBackslashSequence : '\\' ~[\r\n\u2028\u2029] ;
/* * The MIT License (MIT) * * Copyright (c) 2014 by Bart Kiers (original author) and Alexandre Vitorelli (contributor -> ported to CSharp) * Copyright (c) 2017-2020 by Ivan Kochurkin (Positive Technologies): added ECMAScript 6 support, cleared and transformed to the universal grammar. * Copyright (c) 2018 by Juan Alvarez (contributor -> ported to Go) * Copyright (c) 2019 by Student Main (contributor -> ES2020) * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ lexer grammar JavaScriptLexer; channels { ERROR } options { superClass=JavaScriptLexerBase; } HashBangLine: { this.IsStartOfFile()}? '#!' ~[\r\n\u2028\u2029]*; // only allowed at start MultiLineComment: '/*' .*? '*/' -> channel(HIDDEN); SingleLineComment: '//' ~[\r\n\u2028\u2029]* -> channel(HIDDEN); RegularExpressionLiteral: '/' RegularExpressionFirstChar RegularExpressionChar* {this.IsRegexPossible()}? '/' IdentifierPart*; OpenBracket: '['; CloseBracket: ']'; OpenParen: '('; CloseParen: ')'; OpenBrace: '{' {this.ProcessOpenBrace();}; TemplateCloseBrace: {this.IsInTemplateString()}? '}' -> popMode; CloseBrace: '}' {this.ProcessCloseBrace();}; SemiColon: ';'; Comma: ','; Assign: '='; QuestionMark: '?'; Colon: ':'; Ellipsis: '...'; Dot: '.'; PlusPlus: '++'; MinusMinus: '--'; Plus: '+'; Minus: '-'; BitNot: '~'; Not: '!'; Multiply: '*'; Divide: '/'; Modulus: '%'; Power: '**'; NullCoalesce: '??'; Hashtag: '#'; RightShiftArithmetic: '>>'; LeftShiftArithmetic: '<<'; RightShiftLogical: '>>>'; LessThan: '<'; MoreThan: '>'; LessThanEquals: '<='; GreaterThanEquals: '>='; Equals_: '=='; NotEquals: '!='; IdentityEquals: '==='; IdentityNotEquals: '!=='; BitAnd: '&'; BitXOr: '^'; BitOr: '|'; And: '&&'; Or: '||'; MultiplyAssign: '*='; DivideAssign: '/='; ModulusAssign: '%='; PlusAssign: '+='; MinusAssign: '-='; LeftShiftArithmeticAssign: '<<='; RightShiftArithmeticAssign: '>>='; RightShiftLogicalAssign: '>>>='; BitAndAssign: '&='; BitXorAssign: '^='; BitOrAssign: '|='; PowerAssign: '**='; ARROW: '=>'; /// Null Literals NullLiteral: 'null'; /// Boolean Literals BooleanLiteral: 'true' | 'false'; /// Numeric Literals DecimalLiteral: DecimalIntegerLiteral '.' [0-9] [0-9_]* ExponentPart? | '.' [0-9] [0-9_]* ExponentPart? | DecimalIntegerLiteral ExponentPart? ; /// Numeric Literals HexIntegerLiteral: '0' [xX] [0-9a-fA-F] HexDigit*; OctalIntegerLiteral: '0' [0-7]+ {!this.IsStrictMode()}?; OctalIntegerLiteral2: '0' [oO] [0-7] [_0-7]*; BinaryIntegerLiteral: '0' [bB] [01] [_01]*; BigHexIntegerLiteral: '0' [xX] [0-9a-fA-F] HexDigit* 'n'; BigOctalIntegerLiteral: '0' [oO] [0-7] [_0-7]* 'n'; BigBinaryIntegerLiteral: '0' [bB] [01] [_01]* 'n'; BigDecimalIntegerLiteral: DecimalIntegerLiteral 'n'; /// Keywords Break: 'break'; Do: 'do'; Instanceof: 'instanceof'; Typeof: 'typeof'; Case: 'case'; Else: 'else'; New: 'new'; Var: 'var'; Catch: 'catch'; Finally: 'finally'; Return: 'return'; Void: 'void'; Continue: 'continue'; For: 'for'; Switch: 'switch'; While: 'while'; Debugger: 'debugger'; Function_: 'function'; This: 'this'; With: 'with'; Default: 'default'; If: 'if'; Throw: 'throw'; Delete: 'delete'; In: 'in'; Try: 'try'; As: 'as'; From: 'from'; /// Future Reserved Words Class: 'class'; Enum: 'enum'; Extends: 'extends'; Super: 'super'; Const: 'const'; Export: 'export'; Import: 'import'; Async: 'async'; Await: 'await'; Yield: 'yield'; /// The following tokens are also considered to be FutureReservedWords /// when parsing strict mode Implements: 'implements' {this.IsStrictMode()}?; StrictLet: 'let' {this.IsStrictMode()}?; NonStrictLet: 'let' {!this.IsStrictMode()}?; Private: 'private' {this.IsStrictMode()}?; Public: 'public' {this.IsStrictMode()}?; Interface: 'interface' {this.IsStrictMode()}?; Package: 'package' {this.IsStrictMode()}?; Protected: 'protected' {this.IsStrictMode()}?; Static: 'static' {this.IsStrictMode()}?; /// Identifier Names and Identifiers Identifier: IdentifierStart IdentifierPart*; /// String Literals StringLiteral: ('"' DoubleStringCharacter* '"' | '\'' SingleStringCharacter* '\'') {this.ProcessStringLiteral();} ; BackTick: '`' {this.IncreaseTemplateDepth();} -> pushMode(TEMPLATE); WhiteSpaces: [\t\u000B\u000C\u0020\u00A0]+ -> channel(HIDDEN); LineTerminator: [\r\n\u2028\u2029] -> channel(HIDDEN); /// Comments HtmlComment: '<!--' .*? '-->' -> channel(HIDDEN); CDataComment: '<![CDATA[' .*? ']]>' -> channel(HIDDEN); UnexpectedCharacter: . -> channel(ERROR); mode TEMPLATE; BackTickInside: '`' {this.DecreaseTemplateDepth();} -> type(BackTick), popMode; TemplateStringStartExpression: '${' -> pushMode(DEFAULT_MODE); TemplateStringAtom: ~[`]; // Fragment rules fragment DoubleStringCharacter : ~["\\\r\n] | '\\' EscapeSequence | LineContinuation ; fragment SingleStringCharacter : ~['\\\r\n] | '\\' EscapeSequence | LineContinuation ; fragment EscapeSequence : CharacterEscapeSequence | '0' // no digit ahead! TODO | HexEscapeSequence | UnicodeEscapeSequence | ExtendedUnicodeEscapeSequence ; fragment CharacterEscapeSequence : SingleEscapeCharacter | NonEscapeCharacter ; fragment HexEscapeSequence : 'x' HexDigit HexDigit ; fragment UnicodeEscapeSequence : 'u' HexDigit HexDigit HexDigit HexDigit | 'u' '{' HexDigit HexDigit+ '}' ; fragment ExtendedUnicodeEscapeSequence : 'u' '{' HexDigit+ '}' ; fragment SingleEscapeCharacter : ['"\\bfnrtv] ; fragment NonEscapeCharacter : ~['"\\bfnrtv0-9xu\r\n] ; fragment EscapeCharacter : SingleEscapeCharacter | [0-9] | [xu] ; fragment LineContinuation : '\\' [\r\n\u2028\u2029] ; fragment HexDigit : [_0-9a-fA-F] ; fragment DecimalIntegerLiteral : '0' | [1-9] [0-9_]* ; fragment ExponentPart : [eE] [+-]? [0-9_]+ ; fragment IdentifierPart : IdentifierStart | [\p{Mn}] | [\p{Nd}] | [\p{Pc}] | '\u200C' | '\u200D' ; fragment IdentifierStart : [\p{L}] | [$_] | '\\' UnicodeEscapeSequence ; fragment RegularExpressionFirstChar : ~[*\r\n\u2028\u2029\\/[] | RegularExpressionBackslashSequence | '[' RegularExpressionClassChar* ']' ; fragment RegularExpressionChar : ~[\r\n\u2028\u2029\\/[] | RegularExpressionBackslashSequence | '[' RegularExpressionClassChar* ']' ; fragment RegularExpressionClassChar : ~[\r\n\u2028\u2029\]\\] | RegularExpressionBackslashSequence ; fragment RegularExpressionBackslashSequence : '\\' ~[\r\n\u2028\u2029] ;
enable yield in non strict mode
javascript: enable yield in non strict mode
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
3e60f7d0271458ea492b4fff2ce5684571578e37
omni-cx2x/src/cx2x/translator/language/parser/Claw.g4
omni-cx2x/src/cx2x/translator/language/parser/Claw.g4
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import cx2x.translator.common.ClawConstant; import cx2x.translator.language.base.ClawDirective; import cx2x.translator.language.base.ClawLanguage; import cx2x.translator.language.common.*; import cx2x.translator.common.Utility; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage l] @init{ $l = new ClawLanguage(); } : CLAW directive[$l] EOF | CLAW VERBATIM // this directive accept anything after the verbatim { $l.setDirective(ClawDirective.VERBATIM); } | CLAW ACC // this directive accept anything after the acc { $l.setDirective(ClawDirective.PRIMITIVE); } | CLAW OMP // this directive accept anything after the omp { $l.setDirective(ClawDirective.PRIMITIVE); } ; directive[ClawLanguage l] @init{ List<ClawMapping> m = new ArrayList<>(); List<String> o = new ArrayList<>(); List<String> s = new ArrayList<>(); List<Integer> i = new ArrayList<>(); } : // loop-fusion directive LOOPFUSION group_clause_optional[$l] collapse_clause_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_FUSION); } // loop-interchange directive | LOOPINTERCHANGE indexes_option[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } // loop-extract directive | LOOPEXTRACT range_option mapping_option_list[m] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_EXTRACT); $l.setRange($range_option.r); $l.setMappings(m); } // remove directive | REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); } | END REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); $l.setEndPragma(); } // Kcache directive | KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); } | KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); $l.setInitClause(); } // Array notation transformation directive | ARRAY_TRANS induction_optional[$l] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); } | END ARRAY_TRANS { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); $l.setEndPragma(); } // loop-hoist directive | LOOPHOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF { $l.setHoistInductionVars(o); $l.setDirective(ClawDirective.LOOP_HOIST); } | END LOOPHOIST EOF { $l.setDirective(ClawDirective.LOOP_HOIST); $l.setEndPragma(); } // on the fly directive | ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')' { $l.setDirective(ClawDirective.ARRAY_TO_CALL); $l.setFctParams(o); $l.setFctName($fct_name.text); $l.setArrayName($array_name.text); } // parallelize directive | define_option[$l]* PARALLELIZE data_over_clause[$l]* { $l.setDirective(ClawDirective.PARALLELIZE); } | PARALLELIZE FORWARD { $l.setDirective(ClawDirective.PARALLELIZE); $l.setForwardClause(); } | END PARALLELIZE { $l.setDirective(ClawDirective.PARALLELIZE); $l.setEndPragma(); } // ignore directive | IGNORE { $l.setDirective(ClawDirective.IGNORE); } | END IGNORE { $l.setDirective(ClawDirective.IGNORE); $l.setEndPragma(); } ; // Comma-separated identifiers list ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; // Comma-separated identifiers or colon symbol list ids_or_colon_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | ':' { $ids.add(":"); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_or_colon_list[$ids] | ':' { $ids.add(":"); } ',' ids_or_colon_list[$ids] ; // data over clause used in parallelize directive data_over_clause[ClawLanguage l] @init{ List<String> overLst = new ArrayList<>(); List<String> dataLst = new ArrayList<>(); } : DATA '(' ids_list[dataLst] ')' OVER '(' ids_or_colon_list[overLst] ')' { $l.setOverDataClause(dataLst); $l.setOverClause(overLst); } ; // group clause group_clause_optional[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupClause($group_name.text); } | /* empty */ ; // collapse clause collapse_clause_optional[ClawLanguage l]: COLLAPSE '(' n=NUMBER ')' { $l.setCollapseClause($n.text); } | /* empty */ ; // fusion clause fusion_clause_optional[ClawLanguage l]: FUSION group_clause_optional[$l] { $l.setFusionClause(); } | /* empty */ ; // parallel clause parallel_clause_optional[ClawLanguage l]: PARALLEL { $l.setParallelClause(); } | /* empty */ ; // acc clause acc_optional[ClawLanguage l] @init{ List<String> tempAcc = new ArrayList<>(); } : ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); } | /* empty */ ; // interchange clause interchange_optional[ClawLanguage l]: INTERCHANGE indexes_option[$l] { $l.setInterchangeClause(); } | /* empty */ ; // induction clause induction_optional[ClawLanguage l] @init{ List<String> temp = new ArrayList<>(); } : INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); } | /* empty */ ; // data clause data_clause[ClawLanguage l] @init { List<String> temp = new ArrayList<>(); } : DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); } ; // private clause private_optional[ClawLanguage l]: PRIVATE { $l.setPrivateClause(); } | /* empty */ ; // reshape clause reshape_optional[ClawLanguage l] @init{ List<ClawReshapeInfo> r = new ArrayList(); } : RESHAPE '(' reshape_list[r] ')' { $l.setReshapeClauseValues(r); } | /* empty */ ; // reshape clause reshape_element returns [ClawReshapeInfo i] @init{ List<Integer> temp = new ArrayList(); } : array_name=IDENTIFIER '(' target_dim=NUMBER ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } | array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } ; reshape_list[List<ClawReshapeInfo> r]: info=reshape_element { $r.add($info.i); } ',' reshape_list[$r] | info=reshape_element { $r.add($info.i); } ; identifiers[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids] ; identifiers_list[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids] ; integers[List<Integer> ints]: ; integers_list[List<Integer> ints]: i=NUMBER { $ints.add(Integer.parseInt($i.text)); } | i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints] ; indexes_option[ClawLanguage l] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $l.setIndexes(indexes); } | /* empty */ ; offset_list_optional[List<Integer> offsets]: OFFSET '(' offset_list[$offsets] ')' | /* empty */ ; offset_list[List<Integer> offsets]: offset[$offsets] | offset[$offsets] ',' offset_list[$offsets] ; offset[List<Integer> offsets]: n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } | '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); } | '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(ClawConstant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; range_id returns [String text]: n=NUMBER { $text = $n.text; } | i=IDENTIFIER { $text = $i.text; } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; mapping_var_list[List<ClawMappingVar> vars]: mv=mapping_var { $vars.add($mv.mappingVar); } | mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars] ; mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>(); List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>(); $mapping.setMappedVariables(listMapped); $mapping.setMappingVariables(listMapping); } : MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')' ; mapping_option_list[List<ClawMapping> mappings]: m=mapping_option { $mappings.add($m.mapping); } | m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings] ; define_option[ClawLanguage l]: DEFINE DIMENSION id=IDENTIFIER '(' lower=range_id ':' upper=range_id ')' { ClawDimension cd = new ClawDimension($id.text, $lower.text, $upper.text); $l.addDimension(cd); } ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // CLAW Directives ARRAY_TRANS : 'array-transform'; ARRAY_TO_CALL : 'call'; DEFINE : 'define'; END : 'end'; KCACHE : 'kcache'; LOOPEXTRACT : 'loop-extract'; LOOPFUSION : 'loop-fusion'; LOOPHOIST : 'loop-hoist'; LOOPINTERCHANGE : 'loop-interchange'; PARALLELIZE : 'parallelize'; REMOVE : 'remove'; IGNORE : 'ignore'; VERBATIM : 'verbatim'; // CLAW Clauses COLLAPSE : 'collapse'; DATA : 'data'; DIMENSION : 'dimension'; FORWARD : 'forward'; FUSION : 'fusion'; GROUP : 'group'; INDUCTION : 'induction'; INIT : 'init'; INTERCHANGE : 'interchange'; MAP : 'map'; OFFSET : 'offset'; OVER : 'over'; PARALLEL : 'parallel'; PRIVATE : 'private'; RANGE : 'range'; RESHAPE : 'reshape'; // Directive primitive clause ACC : 'acc'; OMP : 'omp'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : [0-9] ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import cx2x.translator.common.ClawConstant; import cx2x.translator.language.base.ClawDirective; import cx2x.translator.language.base.ClawLanguage; import cx2x.translator.language.common.*; import cx2x.translator.common.Utility; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage l] @init{ $l = new ClawLanguage(); } : CLAW directive[$l] EOF | CLAW VERBATIM // this directive accept anything after the verbatim { $l.setDirective(ClawDirective.VERBATIM); } | CLAW ACC // this directive accept anything after the acc { $l.setDirective(ClawDirective.PRIMITIVE); } | CLAW OMP // this directive accept anything after the omp { $l.setDirective(ClawDirective.PRIMITIVE); } ; directive[ClawLanguage l] @init{ List<ClawMapping> m = new ArrayList<>(); List<String> o = new ArrayList<>(); List<String> s = new ArrayList<>(); List<Integer> i = new ArrayList<>(); } : // loop-fusion directive LOOPFUSION group_clause_optional[$l] collapse_clause_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_FUSION); } // loop-interchange directive | LOOPINTERCHANGE indexes_option[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } // loop-extract directive | LOOPEXTRACT range_option mapping_option_list[m] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_EXTRACT); $l.setRange($range_option.r); $l.setMappings(m); } // remove directive | REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); } | END REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); $l.setEndPragma(); } // Kcache directive | KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); } | KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); $l.setInitClause(); } // Array notation transformation directive | ARRAY_TRANS induction_optional[$l] fusion_clause_optional[$l] parallel_clause_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); } | END ARRAY_TRANS { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); $l.setEndPragma(); } // loop-hoist directive | LOOPHOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF { $l.setHoistInductionVars(o); $l.setDirective(ClawDirective.LOOP_HOIST); } | END LOOPHOIST EOF { $l.setDirective(ClawDirective.LOOP_HOIST); $l.setEndPragma(); } // on the fly directive | ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')' { $l.setDirective(ClawDirective.ARRAY_TO_CALL); $l.setFctParams(o); $l.setFctName($fct_name.text); $l.setArrayName($array_name.text); } // parallelize directive | define_option[$l]* PARALLELIZE data_over_clause[$l]* { $l.setDirective(ClawDirective.PARALLELIZE); } | PARALLELIZE FORWARD { $l.setDirective(ClawDirective.PARALLELIZE); $l.setForwardClause(); } | END PARALLELIZE { $l.setDirective(ClawDirective.PARALLELIZE); $l.setEndPragma(); } // ignore directive | IGNORE { $l.setDirective(ClawDirective.IGNORE); } | END IGNORE { $l.setDirective(ClawDirective.IGNORE); $l.setEndPragma(); } ; // Comma-separated identifiers list ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; // Comma-separated identifiers or colon symbol list ids_or_colon_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | ':' { $ids.add(":"); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_or_colon_list[$ids] | ':' { $ids.add(":"); } ',' ids_or_colon_list[$ids] ; // data over clause used in parallelize directive data_over_clause[ClawLanguage l] @init{ List<String> overLst = new ArrayList<>(); List<String> dataLst = new ArrayList<>(); } : DATA '(' ids_list[dataLst] ')' OVER '(' ids_or_colon_list[overLst] ')' { $l.setOverDataClause(dataLst); $l.setOverClause(overLst); } ; // group clause group_clause_optional[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupClause($group_name.text); } | /* empty */ ; // collapse clause collapse_clause_optional[ClawLanguage l]: COLLAPSE '(' n=NUMBER ')' { $l.setCollapseClause($n.text); } | /* empty */ ; // fusion clause fusion_clause_optional[ClawLanguage l]: FUSION group_clause_optional[$l] { $l.setFusionClause(); } | /* empty */ ; // parallel clause parallel_clause_optional[ClawLanguage l]: PARALLEL { $l.setParallelClause(); } | /* empty */ ; // acc clause acc_optional[ClawLanguage l] @init{ List<String> tempAcc = new ArrayList<>(); } : ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); } | /* empty */ ; // interchange clause interchange_optional[ClawLanguage l]: INTERCHANGE indexes_option[$l] { $l.setInterchangeClause(); } | /* empty */ ; // induction clause induction_optional[ClawLanguage l] @init{ List<String> temp = new ArrayList<>(); } : INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); } | /* empty */ ; // data clause data_clause[ClawLanguage l] @init { List<String> temp = new ArrayList<>(); } : DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); } ; // private clause private_optional[ClawLanguage l]: PRIVATE { $l.setPrivateClause(); } | /* empty */ ; // reshape clause reshape_optional[ClawLanguage l] @init{ List<ClawReshapeInfo> r = new ArrayList(); } : RESHAPE '(' reshape_list[r] ')' { $l.setReshapeClauseValues(r); } | /* empty */ ; // reshape clause reshape_element returns [ClawReshapeInfo i] @init{ List<Integer> temp = new ArrayList(); } : array_name=IDENTIFIER '(' target_dim=NUMBER ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } | array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } ; reshape_list[List<ClawReshapeInfo> r]: info=reshape_element { $r.add($info.i); } ',' reshape_list[$r] | info=reshape_element { $r.add($info.i); } ; identifiers[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids] ; identifiers_list[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids] ; integers[List<Integer> ints]: ; integers_list[List<Integer> ints]: i=NUMBER { $ints.add(Integer.parseInt($i.text)); } | i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints] ; indexes_option[ClawLanguage l] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $l.setIndexes(indexes); } | /* empty */ ; offset_list_optional[List<Integer> offsets]: OFFSET '(' offset_list[$offsets] ')' | /* empty */ ; offset_list[List<Integer> offsets]: offset[$offsets] | offset[$offsets] ',' offset_list[$offsets] ; offset[List<Integer> offsets]: n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } | '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); } | '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(ClawConstant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; range_id returns [String text]: n=NUMBER { $text = $n.text; } | i=IDENTIFIER { $text = $i.text; } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; mapping_var_list[List<ClawMappingVar> vars]: mv=mapping_var { $vars.add($mv.mappingVar); } | mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars] ; mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>(); List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>(); $mapping.setMappedVariables(listMapped); $mapping.setMappingVariables(listMapping); } : MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')' ; mapping_option_list[List<ClawMapping> mappings]: m=mapping_option { $mappings.add($m.mapping); } | m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings] ; define_option[ClawLanguage l]: DEFINE DIMENSION id=IDENTIFIER '(' lower=range_id ':' upper=range_id ')' { ClawDimension cd = new ClawDimension($id.text, $lower.text, $upper.text); $l.addDimension(cd); } ; copy_clause_optional[ClawLanguage l]: /* empty */ | COPY //{ $l.setCopyClause(BOTH); } | COPY '(' IN ')' //{ $l.setCopyClause(IN); } | COPY '(' OUT ')' //{ $l.setCopyClause(OUT); } ; update_clause_optional[ClawLanguage l]: /* empty */ | UPDATE //{ $l.setUpdateClause(BOTH); } | UPDATE '(' IN ')' //{ $l.setUpdateClause(IN); } | UPDATE '(' OUT ')' //{ $l.setUpdateClause(OUT); } ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // CLAW Directives ARRAY_TRANS : 'array-transform'; ARRAY_TO_CALL : 'call'; DEFINE : 'define'; END : 'end'; KCACHE : 'kcache'; LOOPEXTRACT : 'loop-extract'; LOOPFUSION : 'loop-fusion'; LOOPHOIST : 'loop-hoist'; LOOPINTERCHANGE : 'loop-interchange'; PARALLELIZE : 'parallelize'; REMOVE : 'remove'; IGNORE : 'ignore'; VERBATIM : 'verbatim'; // CLAW Clauses COLLAPSE : 'collapse'; COPY : 'copy'; DATA : 'data'; DIMENSION : 'dimension'; FORWARD : 'forward'; FUSION : 'fusion'; GROUP : 'group'; INDUCTION : 'induction'; INIT : 'init'; INTERCHANGE : 'interchange'; MAP : 'map'; OFFSET : 'offset'; OVER : 'over'; PARALLEL : 'parallel'; PRIVATE : 'private'; RANGE : 'range'; RESHAPE : 'reshape'; UPDATE : 'update'; // data copy/update clause keywords IN : 'in'; OUT : 'out'; // Directive primitive clause ACC : 'acc'; OMP : 'omp'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : [0-9] ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
Add lexer rules + simple grammar for copx/update
Add lexer rules + simple grammar for copx/update
ANTLR
bsd-2-clause
clementval/claw-compiler,clementval/claw-compiler
e1e23f70cbd78d2addc0b35312a5d0bc3eb004d0
sharding-jdbc-ddl-parser/src/main/antlr4/io/shardingsphere/parser/antlr/postgre/PostgreDDL.g4
sharding-jdbc-ddl-parser/src/main/antlr4/io/shardingsphere/parser/antlr/postgre/PostgreDDL.g4
grammar PostgreDDL; import PostgreKeyword, DataType, Keyword, BaseRule,DDLBase,MySQLDQL,DQLBase,Symbol; createTable: createBasicTable |createTypeTable |createTableForPartition ; createBasicTable: createTableHeader createDefinitions inheritClause? partitionClause? tableWithClause? commitClause? tableSpaceClause? ; createTableHeader: CREATE ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? TABLE (IF NOT EXISTS)? tableName ; createDefinitions: LEFT_PAREN (createDefinition (COMMA createDefinition)*)? RIGHT_PAREN ; createDefinition: (columnName dataType collateClause? columnConstraint*) | tableConstraint | LIKE tableName likeOption* ; inheritClause: INHERITS LEFT_PAREN tableName (COMMA tableName)* RIGHT_PAREN ; partitionClause: PARTITION BY (RANGE | LIST) LEFT_PAREN partitionClauseParam (COMMA partitionClauseParam)* RIGHT_PAREN ; partitionClauseParam: (columnName | expr) collateClause? opclass? ; tableWithClause: withStorageParameters |(WITH OIDS) |(WITHOUT OIDS) ; commitClause: ON COMMIT (PRESERVE ROWS | DELETE ROWS | DROP) ; tableSpaceClause: TABLESPACE tablespaceName ; createTypeTable: createTableHeader typeNameClause createDefinition1s? partitionClause? tableWithClause? commitClause? tableSpaceClause? ; typeNameClause: OF typeName ; createDefinition1s: LEFT_PAREN createDefinition1 (COMMA createDefinition1)* RIGHT_PAREN ; createDefinition1: (columnName (WITH OPTIONS )? columnConstraint*) | tableConstraint ; createTableForPartition: createTableHeader partitionOfParent createDefinition1s? forValuesParition partitionClause? tableWithClause? commitClause? tableSpaceClause? ; partitionOfParent: PARTITION OF tableName ; forValuesParition: FOR VALUES partitionBoundSpec ; partitionBoundSpec: (IN inValueOption) |(FROM fromValueOption TO fromValueOption) ; inValueOption: LEFT_PAREN inValue (COMMA inValue)* RIGHT_PAREN ; inValue: NUMBER |STRING |TRUE |FALSE |NULL ; fromValue: inValue |MINVALUE |MAXVALUE ; fromValueOption: LEFT_PAREN fromValue (COMMA fromValue)* RIGHT_PAREN ; createTableOptions: ; dataType: basicDataType (LEFT_BRACKET RIGHT_BRACKET)* ; basicDataType: BIGINT |INT8 |BIGSERIAL |SERIAL8 |BIT VARYING? numericPrecision? |VARBIT numericPrecision? |BOOLEAN |BOOL |BOX |BYTEA |((CHARACTER VARYING?) | CHAR | VARCHAR) numericPrecision? |CIDR |CIRCLE |DATE |DOUBLE PRECISION |FLOAT8 |(INTEGER | INT4 | INT) |intervalType |JSON |JSONB |LINE |LSEG |MACADDR |MACADDR8 |MONEY |NUMERIC numericPrecision |DECIMAL numericPrecision? |PATH |PG_LSN |POINT |POLYGON |REAL |FLOAT4 |SMALLINT |INT2 |SERIAL |SERIAL4 |FLOAT numericPrecision? |TEXT |(TIME | TIMESTAMP) numericPrecision?((WITHOUT TIME ZONE)? | (WITH TIME ZONE)) |TSQUERY |TSVECTOR |TXID_SNAPSHOT |UUID |XML ; intervalType: INTERVAL intervalFields? numericPrecision? ; intervalFields: intervalField (TO intervalField)? ; intervalField: YEAR |MONTH |DAY |HOUR |MINUTE |SECOND ; numericPrecision: LEFT_PAREN NUMBER (COMMA NUMBER)? RIGHT_PAREN ; defaultExpr: CURRENT_TIMESTAMP |expr; exprsWithParen: LEFT_PAREN exprs RIGHT_PAREN ; exprWithParen: LEFT_PAREN expr RIGHT_PAREN ; collateClause: COLLATE collationName ; columnConstraint: constraintClause? columnConstraintOption constraintOptionalParam ; columnConstraintOption: (NOT NULL) |NULL |checkOption |(DEFAULT defaultExpr) |(GENERATED ( ALWAYS | BY DEFAULT ) AS IDENTITY ( LEFT_PAREN sequenceOptions RIGHT_PAREN )?) |(UNIQUE indexParameters) |(PRIMARY KEY indexParameters) |(REFERENCES tableName (LEFT_PAREN columnName RIGHT_PAREN)? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)?(ON DELETE action )? (ON UPDATE action )?) ; checkOption: CHECK exprWithParen (NO INHERIT )? ; action: (NO ACTION) |RESTRICT |CASCADE |(SET NULL) |(SET DEFAULT) ; sequenceOptions: sequenceOption (START WITH? NUMBER)? (CACHE NUMBER)? (NO? CYCLE)? ; sequenceOption: (INCREMENT BY? NUMBER)? (MINVALUE NUMBER | NO MINVALUE)? (MAXVALUE NUMBER | NO MAXVALUE)? ; likeOption: (INCLUDING | EXCLUDING ) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint: constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption: checkOption |(UNIQUE columnList indexParameters) |(PRIMARY KEY columnList indexParameters) |(EXCLUDE (USING extensionName)? LEFT_PAREN excludeParam (COMMA excludeParam)* RIGHT_PAREN indexParameters (WHERE ( predicate ))?) |(FOREIGN KEY columnList REFERENCES tableName columnList (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON DELETE action )? (ON UPDATE action)?) ; indexParameters: withStorageParameters? (USING INDEX TABLESPACE tablespaceName)? ; extensionName: ID ; excludeParam: excludeElement WITH operator ; excludeElement: (columnName | exprWithParen) opclass? (ASC | DESC)? (NULLS (FIRST | LAST))? ; operator: SAFE_EQ |EQ_OR_ASSIGN |NEQ |NEQ_SYM |GT |GTE |LT |LTE |AND_SYM |OR_SYM |NOT_SYM ; typeName:ID; constraintName:ID; constraintClause: CONSTRAINT constraintName ; withStorageParameters: WITH LEFT_PAREN storageParameters RIGHT_PAREN ; storageParameters: storageParameterWithValue (COMMA storageParameterWithValue)* ; storageParameterWithValue: storageParameter (EQ_OR_ASSIGN NUMBER)? ; storageParameter: ID ; opclass: ID ; alterTable: (alterTableNameWithAsterisk(alterTableActions| renameColumn | renameConstraint)) |(alterTableNameExists(renameTable | setSchema |attachTableSpace |detachTableSpace)) |alterTableSetTableSpace ; alterTableOp: ALTER TABLE ; alterTableActions: alterTableAction (COMMA alterTableAction)* ; renameColumn: RENAME COLUMN? columnName TO columnName ; renameConstraint: RENAME CONSTRAINT constraintName TO constraintName ; renameTable: RENAME TO tableName ; setSchema: SET SCHEMA schemaName ; alterTableSetTableSpace: alterTableOp ALL IN TABLESPACE tablespaceName (OWNED BY roleName (COMMA roleName)* )? SET TABLESPACE tablespaceName NOWAIT? ; attachTableSpace: ATTACH PARTITION partitionName forValuesParition ; detachTableSpace: DETACH PARTITION partitionName ; alterTableNameWithAsterisk: alterTableOp (IF EXISTS)? ONLY? tableName ASTERISK? ; alterTableNameExists: alterTableOp (IF EXISTS)? tableName ; roleName: ID ; partitionName: ID ; triggerName: ID ; rewriteRuleName: ID ; ownerName: ID ; alterTableAction: (ADD COLUMN? (IF NOT EXISTS )? columnName dataType collateClause? (columnConstraint columnConstraint*)?) |(DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)?) |(alterColumnOp columnName (SET DATA)? TYPE dataType collateClause? (USING expr)?) |(alterColumnOp columnName SET DEFAULT expr) |(alterColumnOp columnName DROP DEFAULT) |(alterColumnOp columnName (SET | DROP) NOT NULL) |(alterColumnOp columnName ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LEFT_PAREN sequenceOptions RIGHT_PAREN)?) |(alterColumnOp columnName alterColumnSetOption alterColumnSetOption*) |(alterColumnOp columnName DROP IDENTITY (IF EXISTS)?) |(alterColumnOp columnName SET STATISTICS NUMBER) |(alterColumnOp columnName SET LEFT_PAREN attributeOptions RIGHT_PAREN) |(alterColumnOp columnName RESET LEFT_PAREN attributeOptions RIGHT_PAREN) |(alterColumnOp columnName SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN)) |(ADD tableConstraint (NOT VALID)?) |(ADD tableConstraintUsingIndex) |(ALTER CONSTRAINT constraintName constraintOptionalParam) |(VALIDATE CONSTRAINT constraintName) |(DROP CONSTRAINT (IF EXISTS)? constraintName (RESTRICT | CASCADE)?) |((DISABLE |ENABLE) TRIGGER (triggerName | ALL | USER )?) |(ENABLE (REPLICA | ALWAYS) TRIGGER triggerName) |((DISABLE | ENABLE) RULE rewriteRuleName) |(ENABLE (REPLICA | ALWAYS) RULE rewriteRuleName) |((DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY) |(CLUSTER ON indexName) |(SET WITHOUT CLUSTER) |(SET (WITH | WITHOUT) OIDS) |(SET TABLESPACE tablespaceName) |(SET (LOGGED | UNLOGGED)) |(SET LEFT_PAREN storageParameterWithValue (COMMA storageParameterWithValue)* RIGHT_PAREN) |(RESET LEFT_PAREN storageParameter (COMMA storageParameter)* RIGHT_PAREN) |(INHERIT tableName) |(NO INHERIT tableName) |(OF typeName) |(NOT OF) |(OWNER TO (ownerName | CURRENT_USER | SESSION_USER)) |(REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING)) ; alterColumnOp: ALTER COLUMN? ; alterColumnSetOption: (SET GENERATED (ALWAYS | BY DEFAULT)) |SET sequenceOption |(RESTART (WITH? NUMBER)?) ; attributeOptions: attributeOption (COMMA attributeOption)* ; //options:n_distinct and n_distinct_inherited, loosen match attributeOption: ID EQ_OR_ASSIGN simpleExpr ; tableConstraintUsingIndex: (CONSTRAINT constraintName)? (UNIQUE | PRIMARY KEY) USING INDEX indexName constraintOptionalParam ; constraintOptionalParam: (NOT? DEFERRABLE)? (INITIALLY (DEFERRED |IMMEDIATE))? ; privateExprOfDb: aggregateExpression |windowFunction |arrayConstructorWithCast |(TIMESTAMP (WITH TIME ZONE)? STRING) ; pgExpr: |castExpr |collateExpr |expr ; aggregateExpression: ID ( (LEFT_PAREN (ALL | DISTINCT)? exprs orderByClause? RIGHT_PAREN) |asteriskWithParen | (LEFT_PAREN exprs RIGHT_PAREN WITHIN GROUP LEFT_PAREN orderByClause RIGHT_PAREN) ) filterClause ? ; filterClause: FILTER LEFT_PAREN WHERE booleanPrimary RIGHT_PAREN ; asteriskWithParen: LEFT_PAREN ASTERISK RIGHT_PAREN ; windowFunction: ID (exprsWithParen | asteriskWithParen) filterClause? windowFunctionWithClause ; windowFunctionWithClause: OVER (ID | LEFT_PAREN windowDefinition RIGHT_PAREN ) ; windowDefinition: ID? (PARTITION BY exprs)? (orderByExpr (COMMA orderByExpr)*)? frameClause? ; orderByExpr: ORDER BY expr (ASC | DESC | USING operator)? (NULLS (FIRST | LAST ))? ; frameClause: ((RANGE | ROWS) frameStart) |(RANGE | ROWS ) BETWEEN frameStart AND frameEnd ; frameStart: (UNBOUNDED PRECEDING) |(NUMBER PRECEDING) |(CURRENT ROW) |(NUMBER FOLLOWING) |(UNBOUNDED FOLLOWING) ; frameEnd: frameStart ; castExpr: (CAST LEFT_PAREN expr AS dataType RIGHT_PAREN) |(expr COLON COLON dataType) ; castExprWithColon: COLON COLON dataType(LEFT_BRACKET RIGHT_BRACKET)* ; collateExpr: expr COLLATE expr ; arrayConstructorWithCast: arrayConstructor castExprWithColon? |(ARRAY LEFT_BRACKET RIGHT_BRACKET castExprWithColon) ; arrayConstructor: | ARRAY LEFT_BRACKET exprs RIGHT_BRACKET | ARRAY LEFT_BRACKET arrayConstructor (COMMA arrayConstructor)* RIGHT_BRACKET ;
grammar PostgreDDL; import PostgreKeyword, DataType, Keyword, BaseRule,DDLBase,MySQLDQL,DQLBase,Symbol; createIndex: CREATE UNIQUE? INDEX CONCURRENTLY? ((IF NOT EXISTS)? indexName)? ON tableName indexType? keyParts withStorageParameters? tableSpaceClause? whereClause? ; alterIndex: (alterIndexName(renameIndex | setTableSpace | setStorageParameter | resetStorageParameter)) | alterIndexDependsOnExtension | alterIndexSetTableSpace ; dropIndex: DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA indexName)* (CASCADE | RESTRICT) ; indexType: USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN) ; keyParts: LEFT_PAREN keyPart (COMMA keyPart)* RIGHT_PAREN ; keyPart: (columnName | simpleExpr | LEFT_PAREN simpleExpr RIGHT_PAREN) collateClause? opclass? (ASC | DESC)? (NULLS (FIRST | LAST))? ; simpleExpr: | functionCall | liter | ID ; alterIndexName: ALTER INDEX (IF EXISTS)? indexName ; renameIndex: RENAME TO indexName ; setTableSpace: SET TABLESPACE tablespaceName ; setStorageParameter: SET LEFT_PAREN storageParameters RIGHT_PAREN ; resetStorageParameter: RESET LEFT_PAREN storageParameters RIGHT_PAREN ; alterIndexDependsOnExtension: ALTER INDEX indexName DEPENDS ON EXTENSION extensionName ; alterIndexSetTableSpace: ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY rowNames)? SET TABLESPACE tablespaceName (NOWAIT)? ; rowNames: rowName (COMMA rowName)* ; rowName: ID ; whereClause: WHERE expr ; createTable: createBasicTable |createTypeTable |createTableForPartition ; createBasicTable: createTableHeader createDefinitions inheritClause? partitionClause? tableWithClause? commitClause? tableSpaceClause? ; createTableHeader: CREATE ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? TABLE (IF NOT EXISTS)? tableName ; createDefinitions: LEFT_PAREN (createDefinition (COMMA createDefinition)*)? RIGHT_PAREN ; createDefinition: (columnName dataType collateClause? columnConstraint*) | tableConstraint | LIKE tableName likeOption* ; inheritClause: INHERITS LEFT_PAREN tableName (COMMA tableName)* RIGHT_PAREN ; partitionClause: PARTITION BY (RANGE | LIST) LEFT_PAREN partitionClauseParam (COMMA partitionClauseParam)* RIGHT_PAREN ; partitionClauseParam: (columnName | LEFT_PAREN simpleExpr RIGHT_PAREN) collateClause? opclass? ; tableWithClause: withStorageParameters |(WITH OIDS) |(WITHOUT OIDS) ; commitClause: ON COMMIT (PRESERVE ROWS | DELETE ROWS | DROP) ; tableSpaceClause: TABLESPACE tablespaceName ; createTypeTable: createTableHeader typeNameClause createDefinition1s? partitionClause? tableWithClause? commitClause? tableSpaceClause? ; typeNameClause: OF typeName ; createDefinition1s: LEFT_PAREN createDefinition1 (COMMA createDefinition1)* RIGHT_PAREN ; createDefinition1: (columnName (WITH OPTIONS )? columnConstraint*) | tableConstraint ; createTableForPartition: createTableHeader partitionOfParent createDefinition1s? forValuesParition partitionClause? tableWithClause? commitClause? tableSpaceClause? ; partitionOfParent: PARTITION OF tableName ; forValuesParition: FOR VALUES partitionBoundSpec ; partitionBoundSpec: (IN inValueOption) |(FROM fromValueOption TO fromValueOption) ; inValueOption: LEFT_PAREN inValue (COMMA inValue)* RIGHT_PAREN ; inValue: NUMBER |STRING |TRUE |FALSE |NULL ; fromValue: inValue |MINVALUE |MAXVALUE ; fromValueOption: LEFT_PAREN fromValue (COMMA fromValue)* RIGHT_PAREN ; createTableOptions: ; dataType: basicDataType (LEFT_BRACKET RIGHT_BRACKET)* ; basicDataType: BIGINT |INT8 |BIGSERIAL |SERIAL8 |BIT VARYING? numericPrecision? |VARBIT numericPrecision? |BOOLEAN |BOOL // |BOX |BYTEA |((CHARACTER VARYING?) | CHAR | VARCHAR) numericPrecision? |CIDR |CIRCLE |DATE |DOUBLE PRECISION |FLOAT8 |(INTEGER | INT4 | INT) |intervalType |JSON |JSONB |LINE |LSEG |MACADDR |MACADDR8 |MONEY |NUMERIC numericPrecision |DECIMAL numericPrecision? |PATH |PG_LSN |POINT |POLYGON |REAL |FLOAT4 |SMALLINT |INT2 |SERIAL |SERIAL4 |FLOAT numericPrecision? |TEXT |(TIME | TIMESTAMP) numericPrecision?((WITHOUT TIME ZONE)? | (WITH TIME ZONE)) |TSQUERY |TSVECTOR |TXID_SNAPSHOT |UUID |XML ; intervalType: INTERVAL intervalFields? numericPrecision? ; intervalFields: intervalField (TO intervalField)? ; intervalField: YEAR |MONTH |DAY |HOUR |MINUTE |SECOND ; numericPrecision: LEFT_PAREN NUMBER (COMMA NUMBER)? RIGHT_PAREN ; defaultExpr: CURRENT_TIMESTAMP |expr; exprsWithParen: LEFT_PAREN exprs RIGHT_PAREN ; exprWithParen: LEFT_PAREN expr RIGHT_PAREN ; collateClause: COLLATE collationName ; columnConstraint: constraintClause? columnConstraintOption constraintOptionalParam ; columnConstraintOption: (NOT NULL) |NULL |checkOption |(DEFAULT defaultExpr) |(GENERATED ( ALWAYS | BY DEFAULT ) AS IDENTITY ( LEFT_PAREN sequenceOptions RIGHT_PAREN )?) |(UNIQUE indexParameters) |(PRIMARY KEY indexParameters) |(REFERENCES tableName (LEFT_PAREN columnName RIGHT_PAREN)? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)?(ON DELETE action )? (ON UPDATE action )?) ; checkOption: CHECK exprWithParen (NO INHERIT )? ; action: (NO ACTION) |RESTRICT |CASCADE |(SET NULL) |(SET DEFAULT) ; sequenceOptions: sequenceOption (START WITH? NUMBER)? (CACHE NUMBER)? (NO? CYCLE)? ; sequenceOption: (INCREMENT BY? NUMBER)? (MINVALUE NUMBER | NO MINVALUE)? (MAXVALUE NUMBER | NO MAXVALUE)? ; likeOption: (INCLUDING | EXCLUDING ) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint: constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption: checkOption |(UNIQUE columnList indexParameters) |(PRIMARY KEY columnList indexParameters) |(EXCLUDE (USING extensionName)? LEFT_PAREN excludeParam (COMMA excludeParam)* RIGHT_PAREN indexParameters (WHERE ( predicate ))?) |(FOREIGN KEY columnList REFERENCES tableName columnList (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON DELETE action )? (ON UPDATE action)?) ; indexParameters: withStorageParameters? (USING INDEX TABLESPACE tablespaceName)? ; extensionName: ID ; excludeParam: excludeElement WITH operator ; excludeElement: (columnName | exprWithParen) opclass? (ASC | DESC)? (NULLS (FIRST | LAST))? ; operator: SAFE_EQ |EQ_OR_ASSIGN |NEQ |NEQ_SYM |GT |GTE |LT |LTE |AND_SYM |OR_SYM |NOT_SYM ; typeName:ID; constraintName:ID; constraintClause: CONSTRAINT constraintName ; withStorageParameters: WITH LEFT_PAREN storageParameters RIGHT_PAREN ; storageParameters: storageParameterWithValue (COMMA storageParameterWithValue)* ; storageParameterWithValue: storageParameter EQ_OR_ASSIGN simpleExpr ; storageParameter: ID ; opclass: ID ; alterTable: (alterTableNameWithAsterisk(alterTableActions| renameColumn | renameConstraint)) |(alterTableNameExists(renameTable | setSchema |attachTableSpace |detachTableSpace)) |alterTableSetTableSpace ; alterTableOp: ALTER TABLE ; alterTableActions: alterTableAction (COMMA alterTableAction)* ; renameColumn: RENAME COLUMN? columnName TO columnName ; renameConstraint: RENAME CONSTRAINT constraintName TO constraintName ; renameTable: RENAME TO tableName ; setSchema: SET SCHEMA schemaName ; alterTableSetTableSpace: alterTableOp ALL IN TABLESPACE tablespaceName (OWNED BY roleName (COMMA roleName)* )? SET TABLESPACE tablespaceName NOWAIT? ; attachTableSpace: ATTACH PARTITION partitionName forValuesParition ; detachTableSpace: DETACH PARTITION partitionName ; alterTableNameWithAsterisk: alterTableOp (IF EXISTS)? ONLY? tableName ASTERISK? ; alterTableNameExists: alterTableOp (IF EXISTS)? tableName ; roleName: ID ; partitionName: ID ; triggerName: ID ; rewriteRuleName: ID ; ownerName: ID ; alterTableAction: (ADD COLUMN? (IF NOT EXISTS )? columnName dataType collateClause? (columnConstraint columnConstraint*)?) |(DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)?) |(alterColumnOp columnName (SET DATA)? TYPE dataType collateClause? (USING expr)?) |(alterColumnOp columnName SET DEFAULT expr) |(alterColumnOp columnName DROP DEFAULT) |(alterColumnOp columnName (SET | DROP) NOT NULL) |(alterColumnOp columnName ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LEFT_PAREN sequenceOptions RIGHT_PAREN)?) |(alterColumnOp columnName alterColumnSetOption alterColumnSetOption*) |(alterColumnOp columnName DROP IDENTITY (IF EXISTS)?) |(alterColumnOp columnName SET STATISTICS NUMBER) |(alterColumnOp columnName SET LEFT_PAREN attributeOptions RIGHT_PAREN) |(alterColumnOp columnName RESET LEFT_PAREN attributeOptions RIGHT_PAREN) |(alterColumnOp columnName SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN)) |(ADD tableConstraint (NOT VALID)?) |(ADD tableConstraintUsingIndex) |(ALTER CONSTRAINT constraintName constraintOptionalParam) |(VALIDATE CONSTRAINT constraintName) |(DROP CONSTRAINT (IF EXISTS)? constraintName (RESTRICT | CASCADE)?) |((DISABLE |ENABLE) TRIGGER (triggerName | ALL | USER )?) |(ENABLE (REPLICA | ALWAYS) TRIGGER triggerName) |((DISABLE | ENABLE) RULE rewriteRuleName) |(ENABLE (REPLICA | ALWAYS) RULE rewriteRuleName) |((DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY) |(CLUSTER ON indexName) |(SET WITHOUT CLUSTER) |(SET (WITH | WITHOUT) OIDS) |(SET TABLESPACE tablespaceName) |(SET (LOGGED | UNLOGGED)) |(SET LEFT_PAREN storageParameterWithValue (COMMA storageParameterWithValue)* RIGHT_PAREN) |(RESET LEFT_PAREN storageParameter (COMMA storageParameter)* RIGHT_PAREN) |(INHERIT tableName) |(NO INHERIT tableName) |(OF typeName) |(NOT OF) |(OWNER TO (ownerName | CURRENT_USER | SESSION_USER)) |(REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING)) ; alterColumnOp: ALTER COLUMN? ; alterColumnSetOption: (SET GENERATED (ALWAYS | BY DEFAULT)) |SET sequenceOption |(RESTART (WITH? NUMBER)?) ; attributeOptions: attributeOption (COMMA attributeOption)* ; //options:n_distinct and n_distinct_inherited, loosen match attributeOption: ID EQ_OR_ASSIGN simpleExpr ; tableConstraintUsingIndex: (CONSTRAINT constraintName)? (UNIQUE | PRIMARY KEY) USING INDEX indexName constraintOptionalParam ; constraintOptionalParam: (NOT? DEFERRABLE)? (INITIALLY (DEFERRED |IMMEDIATE))? ; privateExprOfDb: aggregateExpression |windowFunction |arrayConstructorWithCast |(TIMESTAMP (WITH TIME ZONE)? STRING) ; pgExpr: |castExpr |collateExpr |expr ; aggregateExpression: ID ( (LEFT_PAREN (ALL | DISTINCT)? exprs orderByClause? RIGHT_PAREN) |asteriskWithParen | (LEFT_PAREN exprs RIGHT_PAREN WITHIN GROUP LEFT_PAREN orderByClause RIGHT_PAREN) ) filterClause ? ; filterClause: FILTER LEFT_PAREN WHERE booleanPrimary RIGHT_PAREN ; asteriskWithParen: LEFT_PAREN ASTERISK RIGHT_PAREN ; windowFunction: ID (exprsWithParen | asteriskWithParen) filterClause? windowFunctionWithClause ; windowFunctionWithClause: OVER (ID | LEFT_PAREN windowDefinition RIGHT_PAREN ) ; windowDefinition: ID? (PARTITION BY exprs)? (orderByExpr (COMMA orderByExpr)*)? frameClause? ; orderByExpr: ORDER BY expr (ASC | DESC | USING operator)? (NULLS (FIRST | LAST ))? ; frameClause: ((RANGE | ROWS) frameStart) |(RANGE | ROWS ) BETWEEN frameStart AND frameEnd ; frameStart: (UNBOUNDED PRECEDING) |(NUMBER PRECEDING) |(CURRENT ROW) |(NUMBER FOLLOWING) |(UNBOUNDED FOLLOWING) ; frameEnd: frameStart ; castExpr: (CAST LEFT_PAREN expr AS dataType RIGHT_PAREN) |(expr COLON COLON dataType) ; castExprWithColon: COLON COLON dataType(LEFT_BRACKET RIGHT_BRACKET)* ; collateExpr: expr COLLATE expr ; arrayConstructorWithCast: arrayConstructor castExprWithColon? |(ARRAY LEFT_BRACKET RIGHT_BRACKET castExprWithColon) ; arrayConstructor: | ARRAY LEFT_BRACKET exprs RIGHT_BRACKET | ARRAY LEFT_BRACKET arrayConstructor (COMMA arrayConstructor)* RIGHT_BRACKET ;
add index regular
add index regular
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
fa96367cfa6fd68452d70751ae91b8adf28a87ad
src/main/antlr/BMoThParser.g4
src/main/antlr/BMoThParser.g4
parser grammar BMoThParser; options { tokenVocab=BMoThLexer; } @header { package de.bmoth.antlr; } start : parse_unit EOF # ParseUnit ; parse_unit : MACHINE IDENTIFIER (clauses+=machine_clause)* END # MachineParseUnit ; machine_clause : clauseName=(PROPERTIES|INVARIANT) pred=predicate # PredicateClause | clauseName=(CONSTANTS|VARIABLES) identifier_list # DeclarationClause | INITIALISATION substitution # InitialisationClause | OPERATIONS ops+=single_operation (SEMICOLON ops+=single_operation)* # OperationsClause ; single_operation : IDENTIFIER EQUAL substitution # Operation ; quantified_variables_list : identifier_list | LEFT_PAR identifier_list RIGHT_PAR ; identifier_list : identifiers+=IDENTIFIER (',' identifiers+=IDENTIFIER)* ; substitution : BEGIN substitution END # BlockSubstitution | SKIP_SUB # SkipSubstitution | SELECT condition=predicate THEN sub=substitution END # SelectSubstitution | ANY identifier_list WHERE predicate THEN substitution END # AnySubstitution | identifier_list ':=' expression_list # AssignSubstitution | substitution DOUBLE_VERTICAL_BAR substitution # ParallelSubstitution ; expression_list : exprs+=expression (',' exprs+=expression)* ; predicate : '(' predicate ')' # ParenthesisPredicate | operator=(TRUE|FALSE) # PredicateOperator | operator=NOT '(' predicate ')' # PredicateOperator | operator=(FOR_ANY|EXITS) quantified_variables_list DOT LEFT_PAR predicate RIGHT_PAR # QuantificationPredicate | expression operator=(EQUAL|NOT_EQUAL|COLON|ELEMENT_OF |LESS_EQUAL|LESS|GREATER_EQUAL|GREATER) expression # PredicateOperatorWithExprArgs | predicate operator=EQUIVALENCE predicate # PredicateOperator //p60 | predicate operator=(AND|OR) predicate # PredicateOperator //p40 | predicate operator=IMPLIES predicate # PredicateOperator //p30 ; expression : Number # NumberExpression | LEFT_PAR expression RIGHT_PAR # ParenthesesExpression | IDENTIFIER # IdentifierExpression | BOOl_CAST '(' predicate ')' # CastPredicateExpression | operator=(NATURAL|NATURAL1|INTEGER|BOOL|TRUE|FALSE) # ExpressionOperator // operators with precedences | operator=MINUS expression # ExpressionOperator //P210 | <assoc=right> expression operator=POWER_OF expression # ExpressionOperator //p200 | expression operator=(MULT|DIVIDE|MOD) expression # ExpressionOperator //p190 | expression operator=(PLUS|MINUS|SET_SUBTRACTION) expression # ExpressionOperator //p180 | expression operator=INTERVAL expression # ExpressionOperator //p170 | expression operator=(UNION) expression # ExpressionOperator //p160 ;
parser grammar BMoThParser; options { tokenVocab=BMoThLexer; } @header { package de.bmoth.antlr; } start : parse_unit EOF # ParseUnit ; parse_unit : MACHINE IDENTIFIER (clauses+=machine_clause)* END # MachineParseUnit ; machine_clause : clauseName=(PROPERTIES|INVARIANT) pred=predicate # PredicateClause | clauseName=(CONSTANTS|VARIABLES) identifier_list # DeclarationClause | INITIALISATION substitution # InitialisationClause | OPERATIONS ops+=single_operation (SEMICOLON ops+=single_operation)* # OperationsClause ; single_operation : IDENTIFIER EQUAL substitution # Operation ; quantified_variables_list : identifier_list | LEFT_PAR identifier_list RIGHT_PAR ; identifier_list : identifiers+=IDENTIFIER (',' identifiers+=IDENTIFIER)* ; substitution : BEGIN substitution END # BlockSubstitution | SKIP_SUB # SkipSubstitution | SELECT condition=predicate THEN sub=substitution END # SelectSubstitution | ANY identifier_list WHERE predicate THEN substitution END # AnySubstitution | identifier_list ':=' expression_list # AssignSubstitution | substitution DOUBLE_VERTICAL_BAR substitution # ParallelSubstitution ; expression_list : exprs+=expression (',' exprs+=expression)* ; predicate : '(' predicate ')' # ParenthesisPredicate | operator=(TRUE|FALSE) # PredicateOperator | operator=NOT '(' predicate ')' # PredicateOperator | operator=(FOR_ANY|EXITS) quantified_variables_list DOT LEFT_PAR predicate RIGHT_PAR # QuantificationPredicate | expression operator=(EQUAL|NOT_EQUAL|COLON|ELEMENT_OF |LESS_EQUAL|LESS|GREATER_EQUAL|GREATER) expression # PredicateOperatorWithExprArgs | predicate operator=EQUIVALENCE predicate # PredicateOperator //p60 | predicate operator=(AND|OR) predicate # PredicateOperator //p40 | predicate operator=IMPLIES predicate # PredicateOperator //p30 ; expression : Number # NumberExpression | LEFT_PAR expression RIGHT_PAR # ParenthesesExpression | IDENTIFIER # IdentifierExpression | BOOl_CAST '(' predicate ')' # CastPredicateExpression | operator=(NATURAL|NATURAL1|INTEGER|BOOL|TRUE|FALSE) # ExpressionOperator // operators with precedences | operator=MINUS expression # ExpressionOperator //P210 | <assoc=right> expression operator=POWER_OF expression # ExpressionOperator //p200 | expression operator=(MULT|DIVIDE|MOD) expression # ExpressionOperator //p190 | expression operator=(PLUS|MINUS|SET_SUBTRACTION) expression # ExpressionOperator //p180 | expression operator=INTERVAL expression # ExpressionOperator //p170 | expression operator=UNION expression # ExpressionOperator //p160 ;
update grammar
update grammar
ANTLR
mit
hhu-stups/bmoth
7ffe3ad24a4d28e6d2a6e1e539bc281f2fdd29f1
core/src/main/antlr4/nl/eernie/jmoribus/Gherkins.g4
core/src/main/antlr4/nl/eernie/jmoribus/Gherkins.g4
grammar Gherkins; story : feature? prologue? scenario*; feature : feature_keyword feature_title feature_content ; feature_content : (NEWLINE SPACE SPACE line)* ; feature_title : line ; prologue : NEWLINE*? prologue_keyword (NEWLINE step)+; scenario : NEWLINE*? scenario_keyword scenario_title (NEWLINE step)+ NEWLINE* examples*; scenario_title : line ; examples : examples_keyword NEWLINE+ SPACE SPACE examples_table ; examples_table : table ; table : table_row+; table_row : (SPACE SPACE)? '|' cell+ NEWLINE?; cell : (SPACE|TEXT)*? '|'; step : step_keyword step_line (NEWLINE SPACE SPACE step_line)*; step_line : (step_text_line|step_table_line) ; step_text_line : line ; step_table_line : table ; line : (SPACE|TEXT)*; feature_keyword : 'Feature:'; prologue_keyword : 'Prologue:'; scenario_keyword : 'Scenario:'; examples_keyword : 'Examples:'; step_keyword : 'Given' | 'When' | 'Then' | 'And' | 'Referring'; SPACE : ' ' | '\t'; NEWLINE : '\r'? '\n'; TEXT : (UPPERCASE_LETTER | LOWERCASE_LETTER | DIGIT| SYMBOL ) ; fragment UPPERCASE_LETTER : 'A'..'Z' ; fragment LOWERCASE_LETTER : 'a'..'z' ; fragment DIGIT : '0'..'9' ; fragment SYMBOL : '\u0021'..'\u0027' | '\u002a'..'\u002f' | '\u003a'..'\u0040' | '\u005e'..'\u0060' | '\u00a1'..'\u00FF' | '\u0152'..'\u0192' | '\u2013'..'\u2122' | '\u2190'..'\u21FF' | '\u2200'..'\u22FF' | '('..')' | '['..']' | '{'..'}' ; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '#-- ' .*? [\r\n] -> skip ;
grammar Gherkins; story : feature? prologue? scenario*; feature : feature_keyword feature_title feature_content ; feature_content : (NEWLINE SPACE SPACE line)* ; feature_title : line ; prologue : NEWLINE*? prologue_keyword (NEWLINE step)+; scenario : NEWLINE*? scenario_keyword scenario_title (NEWLINE step)+ NEWLINE* examples*; scenario_title : line ; examples : examples_keyword NEWLINE+ SPACE SPACE examples_table ; examples_table : table ; table : table_row+; table_row : (SPACE SPACE)? '|' cell+ NEWLINE?; cell : (SPACE|TEXT)*? '|'; step : NEWLINE*? step_keyword step_line (NEWLINE SPACE SPACE step_line)*; step_line : (step_text_line|step_table_line) ; step_text_line : line ; step_table_line : table ; line : (SPACE|TEXT)*; feature_keyword : 'Feature:'; prologue_keyword : 'Prologue:'; scenario_keyword : 'Scenario:'; examples_keyword : 'Examples:'; step_keyword : 'Given' | 'When' | 'Then' | 'And' | 'Referring'; SPACE : ' ' | '\t'; NEWLINE : '\r'? '\n'; TEXT : (UPPERCASE_LETTER | LOWERCASE_LETTER | DIGIT| SYMBOL ) ; fragment UPPERCASE_LETTER : 'A'..'Z' ; fragment LOWERCASE_LETTER : 'a'..'z' ; fragment DIGIT : '0'..'9' ; fragment SYMBOL : '\u0021'..'\u0027' | '\u002a'..'\u002f' | '\u003a'..'\u0040' | '\u005e'..'\u0060' | '\u00a1'..'\u00FF' | '\u0152'..'\u0192' | '\u2013'..'\u2122' | '\u2190'..'\u21FF' | '\u2200'..'\u22FF' | '('..')' | '['..']' | '{'..'}' ; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '#-- ' .*? [\r\n] -> skip ;
make it possible to have whitelines between steps
make it possible to have whitelines between steps
ANTLR
mit
Eernie/JMoribus
f05d7d207be707c296aa9bb62530c3f793238e36
src/net/hillsdon/reviki/wiki/renderer/creole/Creole.g4
src/net/hillsdon/reviki/wiki/renderer/creole/Creole.g4
/* Todo: * - Comments justifying and explaining every rule. * - Allow arbitrarily-nested lists (see actions/attributes) */ parser grammar Creole; options { tokenVocab=CreoleTokens; superClass=ContextSensitiveParser; } /* ***** Top level elements ***** */ creole : (block (LineBreak | ParBreak)*)* EOF ; block : heading | ulist | olist | hrule | table | code | nowiki | paragraph ; /* ***** Block Elements ***** */ heading : HSt WS? {noBreak();} inline {unsetBreaks();} HEnd; paragraph : inline ; ulist : {yesBreak();} (ulist1 LineBreak?)* {unsetBreaks();} {noBreak();} ulist1 LineBreak? {unsetBreaks();}; ulist1 : U1 inList LineBreak? ({yesBreak();} list2* {unsetBreaks();} {noBreak();} list2 {unsetBreaks();})? ; ulist2 : U2 inList LineBreak? ({yesBreak();} list3* {unsetBreaks();} {noBreak();} list3 {unsetBreaks();})? ; ulist3 : U3 inList LineBreak? ({yesBreak();} list4* {unsetBreaks();} {noBreak();} list4 {unsetBreaks();})? ; ulist4 : U4 inList LineBreak? ({yesBreak();} list5* {unsetBreaks();} {noBreak();} list5 {unsetBreaks();})? ; ulist5 : U5 inList LineBreak? ({yesBreak();} list6* {unsetBreaks();} {noBreak();} list6 {unsetBreaks();})? ; ulist6 : U6 inList LineBreak? ({yesBreak();} list7* {unsetBreaks();} {noBreak();} list7 {unsetBreaks();})? ; ulist7 : U7 inList LineBreak? ({yesBreak();} list8* {unsetBreaks();} {noBreak();} list8 {unsetBreaks();})? ; ulist8 : U8 inList LineBreak? ({yesBreak();} list9* {unsetBreaks();} {noBreak();} list9 {unsetBreaks();})? ; ulist9 : U9 inList LineBreak? ({yesBreak();} list10* {unsetBreaks();} {noBreak();} list10 {unsetBreaks();})? ; ulist10 : U10 inList ; olist : {yesBreak();} (olist1 LineBreak?)* {unsetBreaks();} {noBreak();} olist1 LineBreak? {unsetBreaks();}; olist1 : O1 inList LineBreak? ({yesBreak();} list2* {unsetBreaks();} {noBreak();} list2 {unsetBreaks();})? ; olist2 : O2 inList LineBreak? ({yesBreak();} list3* {unsetBreaks();} {noBreak();} list3 {unsetBreaks();})? ; olist3 : O3 inList LineBreak? ({yesBreak();} list4* {unsetBreaks();} {noBreak();} list4 {unsetBreaks();})? ; olist4 : O4 inList LineBreak? ({yesBreak();} list5* {unsetBreaks();} {noBreak();} list5 {unsetBreaks();})? ; olist5 : O5 inList LineBreak? ({yesBreak();} list6* {unsetBreaks();} {noBreak();} list6 {unsetBreaks();})? ; olist6 : O6 inList LineBreak? ({yesBreak();} list7* {unsetBreaks();} {noBreak();} list7 {unsetBreaks();})? ; olist7 : O7 inList LineBreak? ({yesBreak();} list8* {unsetBreaks();} {noBreak();} list8 {unsetBreaks();})? ; olist8 : O8 inList LineBreak? ({yesBreak();} list9* {unsetBreaks();} {noBreak();} list9 {unsetBreaks();})? ; olist9 : O9 inList LineBreak? ({yesBreak();} list10* {unsetBreaks();} {noBreak();} list10 {unsetBreaks();})? ; olist10 : O10 inList ; list2 : (olist2 | ulist2) LineBreak? ; list3 : (olist3 | ulist3) LineBreak? ; list4 : (olist4 | ulist4) LineBreak? ; list5 : (olist5 | ulist5) LineBreak? ; list6 : (olist6 | ulist6) LineBreak? ; list7 : (olist7 | ulist7) LineBreak? ; list8 : (olist8 | ulist8) LineBreak? ; list9 : (olist9 | ulist9) LineBreak? ; list10 : (olist10 | ulist10) LineBreak? ; inList : WS? (ulist | olist | inline) ; hrule : Rule ; table : {noBreak();} (trow (RowEnd | LineBreak))* trow (RowEnd | LineBreak)? {unsetBreaks();}; trow : tcell+ ; tcell : th | td ; th : ThStart inline? ; td : TdStart inline? ; nowiki : NoWiki EndNoWikiBlock ; /* ***** Inline Elements ***** */ inline : inlinestep+ ; inlinestep : bold | italic | sthrough | link | titlelink | simpleimg | imglink | wikiwlink | attachment | rawlink | inlinecode | preformat | linebreak | macro | any ; bold : BSt inline? BEnd ; italic : ISt inline? IEnd ; sthrough : SSt inline? SEnd ; link : LiSt InLink LiEnd ; titlelink : LiSt InLink? Sep InLinkEnd LiEnd2 ; imglink : ImSt InLink? Sep InLinkEnd ImEnd2 ; simpleimg : ImSt InLink ImEnd ; wikiwlink : WikiWords ; attachment : Attachment ; rawlink : RawUrl ; preformat : NoWiki EndNoWikiInline ; linebreak : InlineBrk ({canBreak()}? LineBreak)? ; macro : MacroSt MacroName (MacroSep MacroEnd | MacroEndNoArgs) ; any : Any | WS | {canBreak()}? LineBreak ; /* ***** Syntax Highlighting ***** */ code : cpp | html | java | xhtml | xml ; inlinecode : inlinecpp | inlinehtml | inlinejava | inlinexhtml | inlinexml ; cpp : StartCpp EndCppBlock ; inlinecpp : StartCpp EndCppInline ; html : StartHtml EndHtmlBlock ; inlinehtml : StartHtml EndHtmlInline ; java : StartJava EndJavaBlock ; inlinejava : StartJava EndJavaInline ; xhtml : StartXhtml EndXhtmlBlock ; inlinexhtml : StartXhtml EndXhtmlInline ; xml : StartXml EndXmlBlock ; inlinexml : StartXml EndXmlInline ;
/* Todo: * - Comments justifying and explaining every rule. * - Allow arbitrarily-nested lists (see actions/attributes) */ parser grammar Creole; options { tokenVocab=CreoleTokens; superClass=ContextSensitiveParser; } /* ***** Top level elements ***** */ creole : (block (LineBreak | ParBreak)*)* EOF ; block : heading | ulist | olist | hrule | table | code | nowiki | paragraph ; /* ***** Block Elements ***** */ heading : HSt WS? {noBreak();} inline {unsetBreaks();} HEnd; paragraph : inline ; ulist : {yesBreak();} (ulist1 LineBreak?)* {unsetBreaks();} {noBreak();} ulist1 LineBreak? {unsetBreaks();}; ulist1 : U1 inList LineBreak? ({yesBreak();} list2* {unsetBreaks();} {noBreak();} list2 {unsetBreaks();})? ; ulist2 : U2 inList LineBreak? ({yesBreak();} list3* {unsetBreaks();} {noBreak();} list3 {unsetBreaks();})? ; ulist3 : U3 inList LineBreak? ({yesBreak();} list4* {unsetBreaks();} {noBreak();} list4 {unsetBreaks();})? ; ulist4 : U4 inList LineBreak? ({yesBreak();} list5* {unsetBreaks();} {noBreak();} list5 {unsetBreaks();})? ; ulist5 : U5 inList LineBreak? ({yesBreak();} list6* {unsetBreaks();} {noBreak();} list6 {unsetBreaks();})? ; ulist6 : U6 inList LineBreak? ({yesBreak();} list7* {unsetBreaks();} {noBreak();} list7 {unsetBreaks();})? ; ulist7 : U7 inList LineBreak? ({yesBreak();} list8* {unsetBreaks();} {noBreak();} list8 {unsetBreaks();})? ; ulist8 : U8 inList LineBreak? ({yesBreak();} list9* {unsetBreaks();} {noBreak();} list9 {unsetBreaks();})? ; ulist9 : U9 inList LineBreak? ({yesBreak();} list10* {unsetBreaks();} {noBreak();} list10 {unsetBreaks();})? ; ulist10 : U10 inList ; olist : {yesBreak();} (olist1 LineBreak?)* {unsetBreaks();} {noBreak();} olist1 LineBreak? {unsetBreaks();}; olist1 : O1 inList LineBreak? ({yesBreak();} list2* {unsetBreaks();} {noBreak();} list2 {unsetBreaks();})? ; olist2 : O2 inList LineBreak? ({yesBreak();} list3* {unsetBreaks();} {noBreak();} list3 {unsetBreaks();})? ; olist3 : O3 inList LineBreak? ({yesBreak();} list4* {unsetBreaks();} {noBreak();} list4 {unsetBreaks();})? ; olist4 : O4 inList LineBreak? ({yesBreak();} list5* {unsetBreaks();} {noBreak();} list5 {unsetBreaks();})? ; olist5 : O5 inList LineBreak? ({yesBreak();} list6* {unsetBreaks();} {noBreak();} list6 {unsetBreaks();})? ; olist6 : O6 inList LineBreak? ({yesBreak();} list7* {unsetBreaks();} {noBreak();} list7 {unsetBreaks();})? ; olist7 : O7 inList LineBreak? ({yesBreak();} list8* {unsetBreaks();} {noBreak();} list8 {unsetBreaks();})? ; olist8 : O8 inList LineBreak? ({yesBreak();} list9* {unsetBreaks();} {noBreak();} list9 {unsetBreaks();})? ; olist9 : O9 inList LineBreak? ({yesBreak();} list10* {unsetBreaks();} {noBreak();} list10 {unsetBreaks();})? ; olist10 : O10 inList ; list2 : (olist2 | ulist2) LineBreak? ; list3 : (olist3 | ulist3) LineBreak? ; list4 : (olist4 | ulist4) LineBreak? ; list5 : (olist5 | ulist5) LineBreak? ; list6 : (olist6 | ulist6) LineBreak? ; list7 : (olist7 | ulist7) LineBreak? ; list8 : (olist8 | ulist8) LineBreak? ; list9 : (olist9 | ulist9) LineBreak? ; list10 : (olist10 | ulist10) LineBreak? ; inList : WS? (ulist | olist | inline) ; hrule : Rule ; table : {noBreak();} (trow (RowEnd | LineBreak))* trow (RowEnd | LineBreak)? {unsetBreaks();}; trow : tcell+ ; tcell : th | td ; th : ThStart inline? ; td : TdStart inline? ; nowiki : NoWiki EndNoWikiBlock ; /* ***** Inline Elements ***** */ inline : inlinestep+ ; inlinestep : bold | italic | sthrough | link | titlelink | simpleimg | imglink | wikiwlink | attachment | rawlink | inlinecode | preformat | linebreak | macro | any ; bold : BSt inline? BEnd ; italic : ISt inline? IEnd ; sthrough : SSt inline? SEnd ; link : LiSt InLink LiEnd ; titlelink : LiSt InLink? Sep InLinkEnd LiEnd2 ; imglink : ImSt InLink? Sep InLinkEnd ImEnd2 ; simpleimg : ImSt InLink ImEnd ; wikiwlink : WikiWords ; attachment : Attachment ; rawlink : RawUrl ; preformat : NoWiki EndNoWikiInline ; linebreak : ({canBreak()}? LineBreak)? InlineBrk ({canBreak()}? LineBreak)? ; macro : MacroSt MacroName (MacroSep MacroEnd | MacroEndNoArgs) ; any : Any | WS | {canBreak()}? LineBreak ; /* ***** Syntax Highlighting ***** */ code : cpp | html | java | xhtml | xml ; inlinecode : inlinecpp | inlinehtml | inlinejava | inlinexhtml | inlinexml ; cpp : StartCpp EndCppBlock ; inlinecpp : StartCpp EndCppInline ; html : StartHtml EndHtmlBlock ; inlinehtml : StartHtml EndHtmlInline ; java : StartJava EndJavaBlock ; inlinejava : StartJava EndJavaInline ; xhtml : StartXhtml EndXhtmlBlock ; inlinexhtml : StartXhtml EndXhtmlInline ; xml : StartXml EndXmlBlock ; inlinexml : StartXml EndXmlInline ;
Allow linebreaks before an escaped break when inline
Allow linebreaks before an escaped break when inline
ANTLR
apache-2.0
strr/reviki,ashirley/reviki,strr/reviki,CoreFiling/reviki,CoreFiling/reviki,strr/reviki,ashirley/reviki,CoreFiling/reviki,CoreFiling/reviki,strr/reviki,strr/reviki,ashirley/reviki,ashirley/reviki,CoreFiling/reviki,ashirley/reviki
fd63360a9cafffc9f1a591deddd51096dd350ce3
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
/* Todo: * - Comments justifying and explaining every rule. */ lexer grammar CreoleTokens; options { superClass=ContextSensitiveLexer; } @members { Formatting bold; Formatting italic; Formatting strike; public void setupFormatting() { bold = new Formatting("**"); italic = new Formatting("//"); strike = new Formatting("--"); inlineFormatting.add(bold); inlineFormatting.add(italic); inlineFormatting.add(strike); } public boolean inHeader = false; public boolean start = false; public int listLevel = 0; boolean nowiki = false; boolean cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = false; boolean intr = false; public void doHdr() { String prefix = getText().trim(); boolean seekback = false; if(!prefix.substring(prefix.length() - 1).equals("=")) { prefix = prefix.substring(0, prefix.length() - 1); seekback = true; } if(prefix.length() <= 6) { if(seekback) { seek(-1); } setText(prefix); inHeader = true; } else { setType(Any); } } public void setStart() { String next1 = next(); String next2 = get(1); start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#")); } public void doList(int level) { listLevel = level; seek(-1); setStart(); resetFormatting(); } public void doUrl() { String url = getText(); String last = url.substring(url.length()-1); String next = next(); if(url.endsWith("://") || url.endsWith("mailto:")) { setType(Any); } String badEnds = inHeader ? "[\\.,)\"';:\\\\=-]" : "[\\.,)\"';:\\\\-]"; while((last + next).equals("//") || last.matches(badEnds)) { seek(-1); url = url.substring(0, url.length() - 1); last = url.substring(url.length()-1); next = next(); } setText(url); } public void breakOut() { resetFormatting(); listLevel = 0; inHeader = false; intr = false; nowiki = false; cpp = false; html = false; java = false; xhtml = false; xml = false; } public String[] thisKillsTheFormatting() { String[] ends = new String[7]; if(inHeader || intr) { ends[0] = "\n"; ends[1] = "\r\n"; } else { ends[0] = null; ends[1] = null; } if(intr) { ends[2] = "|"; } else { ends[2] = null; } ends[3] = "\n\n"; ends[4] = "\r\n\r\n"; if(listLevel > 0) { // \L (when at the start) matches the start of a line. ends[5] = "\\L*"; ends[6] = "\\L#"; } else { ends[5] = null; ends[6] = null; } return ends; } public void doInLink() { String txt = getText().trim(); int len = txt.length(); if(len > 2) { String lastButTwo = txt.substring(len - 3, len - 2); if(lastButTwo.equals("]") || lastButTwo.equals("}")) { txt = txt.substring(0, len - 2); seek(-2); } } setText(txt); } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' {doHdr();} ; HEnd : WS? '='* WS? (LineBreak | ParBreak) {inHeader}? {breakOut();} ; /* ***** Lists ***** */ U1 : START U {doList(1);} ; U2 : START L U {listLevel >= 1 && occurrencesBefore("**", "\n") % 2 == 0}? {doList(2);} ; U3 : START L L U {listLevel >= 2}? {doList(3);} ; U4 : START L L L U {listLevel >= 3}? {doList(4);} ; U5 : START L L L L U {listLevel >= 4}? {doList(5);} ; U6 : START L L L L L U {listLevel >= 5}? {doList(6);} ; U7 : START L L L L L L U {listLevel >= 6}? {doList(7);} ; U8 : START L L L L L L L U {listLevel >= 7}? {doList(8);} ; U9 : START L L L L L L L L U {listLevel >= 8}? {doList(9);} ; U10 : START L L L L L L L L L U {listLevel >= 9}? {doList(10);} ; O1 : START O {doList(1);} ; O2 : START L O {listLevel >= 1}? {doList(2);} ; O3 : START L L O {listLevel >= 2}? {doList(3);} ; O4 : START L L L O {listLevel >= 3}? {doList(4);} ; O5 : START L L L L O {listLevel >= 4}? {doList(5);} ; O6 : START L L L L L O {listLevel >= 5}? {doList(6);} ; O7 : START L L L L L L O {listLevel >= 6}? {doList(7);} ; O8 : START L L L L L L L O {listLevel >= 7}? {doList(8);} ; O9 : START L L L L L L L L O {listLevel >= 8}? {doList(9);} ; O10 : START L L L L L L L L L O {listLevel >= 9}? {doList(10);} ; fragment U : '*' ~'*' ; fragment O : '#' ~'#' ; fragment L : '*' | '#' ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+ {breakOut();} ; /* ***** Tables ***** */ TdStartLn : LINE '|'+ {intr=true; setType(TdStart);} ; ThStartLn : LINE '|'+ '=' {intr=true; setType(ThStart);} ; RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ; TdStart : '|'+ {intr}? {breakOut(); intr=true;} ; ThStart : '|'+ '=' {intr}? {breakOut(); intr=true;} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active && !prior().matches("[a-zA-Z0-9]:")}? {setFormatting(italic, Any);} ; SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ; BEnd : '**' {bold.active}? {unsetFormatting(bold);} ; IEnd : '//' {italic.active && !prior().matches("[a-zA-Z0-9]:")}? {unsetFormatting(italic);} ; SEnd : '--' {strike.active}? {unsetFormatting(strike);} ; NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ; StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ; StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ; StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ; StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ; StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ; /* ***** Links ***** */ LiSt : '[[' -> mode(LINK) ; ImSt : '{{' -> mode(LINK) ; /* ***** Breaks ***** */ InlineBrk : '\\\\' ; ParBreak : LineBreak WS? LineBreak+ {breakOut();} ; LineBreak : '\r'? '\n' ; /* ***** Links ***** */ RawUrl : PROTOCOL (~(' '|'\t'|'\r'|'\n'|'|'|'['|']')+ '/'?)+ {doUrl();} ; fragment PROTOCOL : ('http' 's'? | 'file' | 'ftp') '://' | 'file:/' | 'mailto:' ; Attachment : ALNUM+ '.' ALNUM+ ; WikiWords : (UPPER (ABBR | CAMEL) | INTERWIKI ALNUM+) {checkBounds("[\\.\\w:]", "\\w")}? ; fragment INTERWIKI : ALPHA ALNUM+ ':' ; fragment ABBR : UPPER UPPER+ ; fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ; /* ***** Macros ***** */ MacroSt : '<<' -> mode(MACRO) ; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t')+ ; EmptyLink : ('[[' WS? ']]' | '{{' WS? '}}' |'[[' WS? '|' WS? ']]' | '{{' WS? '|' WS? '}}') -> skip ; fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ; fragment START : {start}? | LINE ; fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*; fragment LOWNUM : (LOWER | DIGIT) ; fragment UPNUM : (UPPER | DIGIT) ; fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ; ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ; Sep : ' '* '|' ' '*; InLink : (~('|'|'\r'|'\n'|']'|'}') | (']' ~']' | '}' ~'}'))+ {doInLink();}; mode MACRO; MacroName : ~(':'|'>')+ ; MacroEndNoArgs : '>>' -> mode(DEFAULT_MODE) ; MacroSep : ':' -> mode(MACRO_ARGS) ; mode MACRO_ARGS; MacroArgs : . -> more ; MacroEnd : '>>' -> mode(DEFAULT_MODE) ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') {seek(-1);} -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' ~'}' {nowiki}? {nowiki=false; seek(-1);} -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : (~' ' '}}}' | ' }}}' '\r'? '\n' {seek(-1);}) {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
/* Todo: * - Comments justifying and explaining every rule. */ lexer grammar CreoleTokens; options { superClass=ContextSensitiveLexer; } @members { Formatting bold; Formatting italic; Formatting strike; public void setupFormatting() { bold = new Formatting("**"); italic = new Formatting("//"); strike = new Formatting("--"); inlineFormatting.add(bold); inlineFormatting.add(italic); inlineFormatting.add(strike); } public boolean inHeader = false; public boolean start = false; public int listLevel = 0; boolean nowiki = false; boolean cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = false; boolean intr = false; public void doHdr() { String prefix = getText().trim(); boolean seekback = false; if(!prefix.substring(prefix.length() - 1).equals("=")) { prefix = prefix.substring(0, prefix.length() - 1); seekback = true; } if(prefix.length() <= 6) { if(seekback) { seek(-1); } setText(prefix); inHeader = true; } else { setType(Any); } } public void setStart() { String next1 = next(); String next2 = get(1); start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#")); } public void doList(int level) { listLevel = level; seek(-1); setStart(); resetFormatting(); } public void doUrl() { String url = getText(); String last = url.substring(url.length()-1); String next = next(); if(url.endsWith("://") || url.endsWith("mailto:")) { setType(Any); } String badEnds = inHeader ? "[\\.,)\"';:\\\\=-]" : "[\\.,)\"';:\\\\-]"; while((last + next).equals("//") || last.matches(badEnds)) { seek(-1); url = url.substring(0, url.length() - 1); last = url.substring(url.length()-1); next = next(); } setText(url); } public void breakOut() { resetFormatting(); listLevel = 0; inHeader = false; intr = false; nowiki = false; cpp = false; html = false; java = false; xhtml = false; xml = false; } public String[] thisKillsTheFormatting() { String[] ends = new String[7]; if(inHeader || intr) { ends[0] = "\n"; ends[1] = "\r\n"; } else { ends[0] = null; ends[1] = null; } if(intr) { ends[2] = "|"; } else { ends[2] = null; } ends[3] = "\n\n"; ends[4] = "\r\n\r\n"; if(listLevel > 0) { // \L (when at the start) matches the start of a line. ends[5] = "\\L*"; ends[6] = "\\L#"; } else { ends[5] = null; ends[6] = null; } return ends; } public void doInLink() { String txt = getText().trim(); int len = txt.length(); if(len > 2) { String lastButTwo = txt.substring(len - 3, len - 2); if(lastButTwo.equals("]") || lastButTwo.equals("}")) { txt = txt.substring(0, len - 2); seek(-2); } } setText(txt); } public void doAny() { String txt = getText(); // Avoid eating the start of a URL if(txt.length() > 1 && next().equals(":")) { int idx = txt.lastIndexOf(" "); seek(-(txt.length() - idx)); setText(txt.substring(0, idx)); } } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' {doHdr();} ; HEnd : WS? '='* WS? (LineBreak | ParBreak) {inHeader}? {breakOut();} ; /* ***** Lists ***** */ U1 : START U {doList(1);} ; U2 : START L U {listLevel >= 1 && occurrencesBefore("**", "\n") % 2 == 0}? {doList(2);} ; U3 : START L L U {listLevel >= 2}? {doList(3);} ; U4 : START L L L U {listLevel >= 3}? {doList(4);} ; U5 : START L L L L U {listLevel >= 4}? {doList(5);} ; U6 : START L L L L L U {listLevel >= 5}? {doList(6);} ; U7 : START L L L L L L U {listLevel >= 6}? {doList(7);} ; U8 : START L L L L L L L U {listLevel >= 7}? {doList(8);} ; U9 : START L L L L L L L L U {listLevel >= 8}? {doList(9);} ; U10 : START L L L L L L L L L U {listLevel >= 9}? {doList(10);} ; O1 : START O {doList(1);} ; O2 : START L O {listLevel >= 1}? {doList(2);} ; O3 : START L L O {listLevel >= 2}? {doList(3);} ; O4 : START L L L O {listLevel >= 3}? {doList(4);} ; O5 : START L L L L O {listLevel >= 4}? {doList(5);} ; O6 : START L L L L L O {listLevel >= 5}? {doList(6);} ; O7 : START L L L L L L O {listLevel >= 6}? {doList(7);} ; O8 : START L L L L L L L O {listLevel >= 7}? {doList(8);} ; O9 : START L L L L L L L L O {listLevel >= 8}? {doList(9);} ; O10 : START L L L L L L L L L O {listLevel >= 9}? {doList(10);} ; fragment U : '*' ~'*' ; fragment O : '#' ~'#' ; fragment L : '*' | '#' ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+ {breakOut();} ; /* ***** Tables ***** */ TdStartLn : LINE '|'+ {intr=true; setType(TdStart);} ; ThStartLn : LINE '|'+ '=' {intr=true; setType(ThStart);} ; RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ; TdStart : '|'+ {intr}? {breakOut(); intr=true;} ; ThStart : '|'+ '=' {intr}? {breakOut(); intr=true;} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active && !prior().matches("[a-zA-Z0-9]:")}? {setFormatting(italic, Any);} ; SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ; BEnd : '**' {bold.active}? {unsetFormatting(bold);} ; IEnd : '//' {italic.active && !prior().matches("[a-zA-Z0-9]:")}? {unsetFormatting(italic);} ; SEnd : '--' {strike.active}? {unsetFormatting(strike);} ; NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ; StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ; StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ; StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ; StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ; StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ; /* ***** Links ***** */ LiSt : '[[' -> mode(LINK) ; ImSt : '{{' -> mode(LINK) ; /* ***** Breaks ***** */ InlineBrk : '\\\\' ; ParBreak : LineBreak WS? LineBreak+ {breakOut();} ; LineBreak : '\r'? '\n' ; /* ***** Links ***** */ RawUrl : PROTOCOL (~(' '|'\t'|'\r'|'\n'|'|'|'['|']')+ '/'?)+ {doUrl();} ; fragment PROTOCOL : ('http' 's'? | 'file' | 'ftp') '://' | 'file:/' | 'mailto:' ; Attachment : ALNUM+ '.' ALNUM+ ; WikiWords : (UPPER (ABBR | CAMEL) | INTERWIKI ALNUM+) {checkBounds("[\\.\\w:]", "\\w")}? ; fragment INTERWIKI : ALPHA ALNUM+ ':' ; fragment ABBR : UPPER UPPER+ ; fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ; /* ***** Macros ***** */ MacroSt : '<<' -> mode(MACRO) ; /* ***** Miscellaneous ***** */ Any : LOWER+ ' ' | . {doAny();} ; WS : (' '|'\t')+ ; EmptyLink : ('[[' WS? ']]' | '{{' WS? '}}' |'[[' WS? '|' WS? ']]' | '{{' WS? '|' WS? '}}') -> skip ; fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ; fragment START : {start}? | LINE ; fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*; fragment LOWNUM : (LOWER | DIGIT) ; fragment UPNUM : (UPPER | DIGIT) ; fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ; ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ; Sep : ' '* '|' ' '*; InLink : (~('|'|'\r'|'\n'|']'|'}') | (']' ~']' | '}' ~'}'))+ {doInLink();}; mode MACRO; MacroName : ~(':'|'>')+ ; MacroEndNoArgs : '>>' -> mode(DEFAULT_MODE) ; MacroSep : ':' -> mode(MACRO_ARGS) ; mode MACRO_ARGS; MacroArgs : . -> more ; MacroEnd : '>>' -> mode(DEFAULT_MODE) ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') {seek(-1);} -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' ~'}' {nowiki}? {nowiki=false; seek(-1);} -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : (~' ' '}}}' | ' }}}' '\r'? '\n' {seek(-1);}) {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
Make matching 'Any' tokens much more memory efficient, by considering the common case
Make matching 'Any' tokens much more memory efficient, by considering the common case
ANTLR
apache-2.0
strr/reviki,CoreFiling/reviki,ashirley/reviki,ashirley/reviki,strr/reviki,CoreFiling/reviki,strr/reviki,ashirley/reviki,strr/reviki,CoreFiling/reviki,CoreFiling/reviki,ashirley/reviki,CoreFiling/reviki,ashirley/reviki,strr/reviki
6f5aee9ec79b5cc7e153a2d30fc9f935f39e9286
src/main/java/org/shirolang/interpreter/Shiro.g4
src/main/java/org/shirolang/interpreter/Shiro.g4
grammar Shiro; shiro : includeStmt* shiroStmt* EOF ; includeStmt: INCLUDE STRING_LITERAL NEWLINE; shiroStmt : anonymousGraphStmt | nodeDecl | graphDecl | stateDecl | NEWLINE ; stateDecl : STATE stateName BEGIN NEWLINE stateGraphSelection NEWLINE stateStmt* END ; stateName : IDENT ; stateStmt : stateActivation NEWLINE | NEWLINE ; stateGraphSelection : GRAPH (IDENT | DEFAULT) ; stateActivation : optionSelection | nestedOptionSelection ; nestedOptionSelection : nodeName=IDENT LSQUARE activeObject=IDENT RSQUARE BEGIN NEWLINE (stateActivation NEWLINE | NEWLINE)* END ; optionSelection : nodeName=IDENT LSQUARE activeObject=IDENT RSQUARE ; graphDecl : GRAPH IDENT BEGIN NEWLINE graphStmt+ END ; graphStmt : portAssignment | funcDeclInit | funcDecl | NEWLINE ; nodeDecl : NODE MFNAME ('[' optionSelector ']')? BEGIN NEWLINE nodeStmt END ; funcDeclInit : name=IDENT fullyQualifiedType ( LSQUARE activeObject=IDENT RSQUARE )? ('(' arguments ')') ; funcCall : fullyQualifiedType ( LSQUARE activeObject=IDENT RSQUARE )? ('(' arguments ')')?; funcDecl : name=IDENT fullyQualifiedType ( LSQUARE activeObject=IDENT RSQUARE )? ; arguments : argMap | argList ; argMap : (keys+=IDENT ':' values+=arg)(',' keys+=IDENT ':' values+=arg)* ; argList : arg(',' arg)* ; arg: expr; optionSelector : IDENT ; nodeStmt : (portstmt | portAssignment | nodeDecl | NEWLINE)* ; portDecl : OPTION? accessModifier? funcDecl ; portDeclInit : OPTION? accessModifier? funcDeclInit ; portstmt : ( portDeclInit | portDecl ) NEWLINE ; portName : IDENT ; accessModifier : INPUT | OUTPUT ; fullyQualifiedType : types+=MFNAME ('.' types+=MFNAME)* ; path : (REF| SELECT)? segments+=pathSegment ('.' segments+=pathSegment)* ; pathSegment : IDENT | (INPUTS| OUTPUTS) LSQUARE pathIndex RSQUARE ; pathIndex : index=(NUMBER | IDENT) ; portAssignment : path '(' arguments ')' NEWLINE ; anonExpr : expr NEWLINE ; anonymousGraphStmt : portAssignment | funcDeclInit NEWLINE | funcDecl NEWLINE | anonExpr ; expr : '(' expr ')' #parensExpr | NOT_OP expr #notExpr | MINUS_OP expr #negExpr | expr AND_OP expr #andExpr | expr OR_OP expr #orExpr | expr (DIV_OP | MULT_OP | MOD_OP) expr #multExpr | expr (PLUS_OP | MINUS_OP ) expr #addExpr | expr (GT | GTE | LT | LTE) expr #comparisonExpr | expr ( EQ | NEQ ) expr #equalityExpr | fullyQualifiedType #typeExpr | funcCall #inlineFuncCall | path #pathExpr | NUMBER #numExpr | BOOLEAN_LITERAL #boolExpr | STRING_LITERAL #stringExpr ; SELECT : '@'; REF : '~'; DEFAULT : '^'; PORT : 'port'; INPUT : 'input'; OUTPUT : 'output'; EVAL : 'eval'; THIS : 'this'; NOT_OP : '!'; AND_OP : '&&'; OR_OP : '||'; PLUS_OP : '+'; MINUS_OP : '-'; MULT_OP : '*'; DIV_OP : '/'; MOD_OP : '%'; LSQUARE : '['; RSQUARE : ']'; GT : '>'; GTE : '>='; LT : '<'; LTE : '<='; EQ : '=='; NEQ : '!='; INCLUDE: 'include'; STATE: 'state'; NODE: 'node'; GRAPH: 'graph'; BEGIN: 'begin'; END: 'end'; INPUTS: 'inputs'; OUTPUTS: 'outputs'; OPTION : 'option'; BOOLEAN_LITERAL : 'true' | 'false' ; STRING_LITERAL : '"' (~'"'|'\\"')* '"' ; NUMBER : DIGIT+ ('.'DIGIT+)? ; IDENT : LCLETTER (LCLETTER | UCLETTER | DIGIT|'_')* ; MFNAME : UCLETTER (LCLETTER | UCLETTER | DIGIT|'_')* ; WS : (' '|'\t'|'\f')+ -> channel(HIDDEN) ; COMMENT : '//' ~('\n'|'\r')* -> channel(HIDDEN) ; LINE_COMMENT : '/*' .*? '*/' NEWLINE? -> channel(HIDDEN) ; NEWLINE : '\r'?'\n' ; fragment LCLETTER : 'a'..'z'; fragment UCLETTER : 'A'..'Z'; fragment DIGIT : '0'..'9';
grammar Shiro; shiro : includeStmt* shiroStmt* EOF ; includeStmt: INCLUDE STRING_LITERAL NEWLINE; shiroStmt : anonymousGraphStmt | nodeDecl | graphDecl | stateDecl | NEWLINE ; stateDecl : STATE stateName BEGIN NEWLINE stateGraphSelection NEWLINE stateStmt* END ; stateName : IDENT ; stateStmt : stateActivation NEWLINE | NEWLINE ; stateGraphSelection : GRAPH (IDENT | DEFAULT) ; stateActivation : optionSelection | nestedOptionSelection ; nestedOptionSelection : nodeName=IDENT LSQUARE activeObject=IDENT RSQUARE BEGIN NEWLINE (stateActivation NEWLINE | NEWLINE)* END ; optionSelection : nodeName=IDENT LSQUARE activeObject=IDENT RSQUARE ; graphDecl : GRAPH IDENT BEGIN NEWLINE graphStmt+ END ; graphStmt : portAssignment | funcDeclInit | funcDecl | namedRef |NEWLINE ; nodeDecl : NODE MFNAME ('[' optionSelector ']')? BEGIN NEWLINE nodeStmt END ; namedRef : name=IDENT reference ; anonymousRef : reference ; reference : REF funcCall outputSelector ; outputSelector : (LSQUARE selectedOutput=IDENT RSQUARE)? ; funcDeclInit : name=IDENT fullyQualifiedType ( LSQUARE activeObject=IDENT RSQUARE )? ('(' arguments? ')') ; funcCall : fullyQualifiedType ( LSQUARE activeObject=IDENT RSQUARE )? ('(' arguments? ')')?; funcDecl : name=IDENT fullyQualifiedType ( LSQUARE activeObject=IDENT RSQUARE )? ; arguments : argMap | argList ; argMap : (keys+=IDENT ':' values+=arg)(',' keys+=IDENT ':' values+=arg)* ; argList : arg(',' arg)* ; arg: expr; optionSelector : IDENT ; nodeStmt : (portstmt | portAssignment | nodeDecl | NEWLINE)* ; portDecl : OPTION? accessModifier? funcDecl ; portDeclInit : OPTION? accessModifier? funcDeclInit ; portstmt : ( portDeclInit | portDecl | namedRef ) NEWLINE ; portName : IDENT ; accessModifier : INPUT | OUTPUT ; fullyQualifiedType : types+=MFNAME ('.' types+=MFNAME)* ; path : (REF| SELECT)? segments+=pathSegment ('.' segments+=pathSegment)* ; pathSegment : IDENT | (INPUTS| OUTPUTS) LSQUARE pathIndex RSQUARE ; pathIndex : index=(NUMBER | IDENT) ; portAssignment : path '(' arguments ')' NEWLINE ; anonExpr : expr NEWLINE ; anonymousGraphStmt : portAssignment | funcDeclInit NEWLINE | funcDecl NEWLINE | anonExpr | namedRef NEWLINE ; listLiteral : LSQUARE argList? RSQUARE ; expr : '(' expr ')' #parensExpr | NOT_OP expr #notExpr | MINUS_OP expr #negExpr | expr AND_OP expr #andExpr | expr OR_OP expr #orExpr | expr (DIV_OP | MULT_OP | MOD_OP) expr #multExpr | expr (PLUS_OP | MINUS_OP ) expr #addExpr | expr (GT | GTE | LT | LTE) expr #comparisonExpr | expr ( EQ | NEQ ) expr #equalityExpr | fullyQualifiedType #typeExpr | anonymousRef #anonRefExpr | funcCall #inlineFuncCall | path #pathExpr | listLiteral #listExpr | NUMBER #numExpr | BOOLEAN_LITERAL #boolExpr | STRING_LITERAL #stringExpr ; SELECT : '@'; REF : '~'; DEFAULT : '^'; PORT : 'port'; INPUT : 'input'; OUTPUT : 'output'; EVAL : 'eval'; THIS : 'this'; NOT_OP : '!'; AND_OP : '&&'; OR_OP : '||'; PLUS_OP : '+'; MINUS_OP : '-'; MULT_OP : '*'; DIV_OP : '/'; MOD_OP : '%'; LSQUARE : '['; RSQUARE : ']'; GT : '>'; GTE : '>='; LT : '<'; LTE : '<='; EQ : '=='; NEQ : '!='; INCLUDE: 'include'; STATE: 'state'; NODE: 'node'; GRAPH: 'graph'; BEGIN: 'begin'; END: 'end'; INPUTS: 'inputs'; OUTPUTS: 'outputs'; OPTION : 'option'; BOOLEAN_LITERAL : 'true' | 'false' ; STRING_LITERAL : '"' (~'"'|'\\"')* '"' ; NUMBER : DIGIT+ ('.'DIGIT+)? ; IDENT : LCLETTER (LCLETTER | UCLETTER | DIGIT|'_')* ; MFNAME : UCLETTER (LCLETTER | UCLETTER | DIGIT|'_')* ; WS : (' '|'\t'|'\f')+ -> channel(HIDDEN) ; COMMENT : '//' ~('\n'|'\r')* -> channel(HIDDEN) ; LINE_COMMENT : '/*' .*? '*/' NEWLINE? -> channel(HIDDEN) ; NEWLINE : '\r'?'\n' ; fragment LCLETTER : 'a'..'z'; fragment UCLETTER : 'A'..'Z'; fragment DIGIT : '0'..'9';
Add function references
Add function references
ANTLR
mit
jrguenther/shiro
2cdbe83f9c03aac6f8c085c687ac24184dff2366
oap-server/generate-tool-grammar/src/main/antlr4/org/apache/skywalking/oal/tool/grammar/OALParser.g4
oap-server/generate-tool-grammar/src/main/antlr4/org/apache/skywalking/oal/tool/grammar/OALParser.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. * */ parser grammar OALParser; @Header {package org.apache.skywalking.oal.tool.grammar;} options { tokenVocab=OALLexer; } // Top Level Description root : (aggregationStatement | disableStatement)* ; aggregationStatement : variable (SPACE)? EQUAL (SPACE)? metricStatement DelimitedComment? LineComment? (SEMI|EOF) ; disableStatement : DISABLE LR_BRACKET disableSource RR_BRACKET DelimitedComment? LineComment? (SEMI|EOF) ; metricStatement : FROM LR_BRACKET source DOT sourceAttribute RR_BRACKET (filterStatement+)? DOT aggregateFunction ; filterStatement : DOT FILTER LR_BRACKET filterExpression RR_BRACKET ; filterExpression : expression ; source : SRC_ALL | SRC_SERVICE | SRC_DATABASE_ACCESS | SRC_SERVICE_INSTANCE | SRC_ENDPOINT | SRC_SERVICE_RELATION | SRC_SERVICE_INSTANCE_RELATION | SRC_ENDPOINT_RELATION | SRC_SERVICE_INSTANCE_JVM_CPU | SRC_SERVICE_INSTANCE_JVM_MEMORY | SRC_SERVICE_INSTANCE_JVM_MEMORY_POOL | SRC_SERVICE_INSTANCE_JVM_GC |// JVM source of service instance SRC_SERVICE_INSTANCE_CLR_CPU | SRC_SERVICE_INSTANCE_CLR_GC | SRC_SERVICE_INSTANCE_CLR_THREAD | SRC_ENVOY_INSTANCE_METRIC | SRC_ZIPKIN_SPAN | SRC_JAEGER_SPAN ; disableSource : SRC_SEGMENT | SRC_TOP_N_DB_STATEMENT | SRC_ENDPOINT_RELATION_SERVER_SIDE | SRC_SERVICE_RELATION_SERVER_SIDE | SRC_SERVICE_RELATION_CLIENT_SIDE | SRC_ALARM_RECORD | SRC_HTTP_ACCESS_LOG ; sourceAttribute : IDENTIFIER | ALL ; variable : IDENTIFIER ; aggregateFunction : functionName LR_BRACKET (funcParamExpression | (literalExpression (COMMA literalExpression)?))? RR_BRACKET ; functionName : IDENTIFIER ; funcParamExpression : expression ; literalExpression : BOOL_LITERAL | NUMBER_LITERAL ; expression : booleanMatch | stringMatch | greaterMatch | lessMatch | greaterEqualMatch | lessEqualMatch ; booleanMatch : conditionAttribute DUALEQUALS booleanConditionValue ; stringMatch : conditionAttribute DUALEQUALS (stringConditionValue | enumConditionValue) ; greaterMatch : conditionAttribute GREATER numberConditionValue ; lessMatch : conditionAttribute LESS numberConditionValue ; greaterEqualMatch : conditionAttribute GREATER_EQUAL numberConditionValue ; lessEqualMatch : conditionAttribute LESS_EQUAL numberConditionValue ; conditionAttribute : IDENTIFIER ; booleanConditionValue : BOOL_LITERAL ; stringConditionValue : STRING_LITERAL ; enumConditionValue : IDENTIFIER DOT IDENTIFIER ; numberConditionValue : NUMBER_LITERAL ;
/* * 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. * */ parser grammar OALParser; @Header {package org.apache.skywalking.oal.tool.grammar;} options { tokenVocab=OALLexer; } // Top Level Description root : (aggregationStatement | disableStatement)* ; aggregationStatement : variable (SPACE)? EQUAL (SPACE)? metricStatement DelimitedComment? LineComment? (SEMI|EOF) ; disableStatement : DISABLE LR_BRACKET disableSource RR_BRACKET DelimitedComment? LineComment? (SEMI|EOF) ; metricStatement : FROM LR_BRACKET source DOT sourceAttribute RR_BRACKET (filterStatement+)? DOT aggregateFunction ; filterStatement : DOT FILTER LR_BRACKET filterExpression RR_BRACKET ; filterExpression : expression ; source : SRC_ALL | SRC_SERVICE | SRC_DATABASE_ACCESS | SRC_SERVICE_INSTANCE | SRC_ENDPOINT | SRC_SERVICE_RELATION | SRC_SERVICE_INSTANCE_RELATION | SRC_ENDPOINT_RELATION | SRC_SERVICE_INSTANCE_JVM_CPU | SRC_SERVICE_INSTANCE_JVM_MEMORY | SRC_SERVICE_INSTANCE_JVM_MEMORY_POOL | SRC_SERVICE_INSTANCE_JVM_GC |// JVM source of service instance SRC_SERVICE_INSTANCE_CLR_CPU | SRC_SERVICE_INSTANCE_CLR_GC | SRC_SERVICE_INSTANCE_CLR_THREAD | SRC_ENVOY_INSTANCE_METRIC ; disableSource : SRC_SEGMENT | SRC_TOP_N_DB_STATEMENT | SRC_ENDPOINT_RELATION_SERVER_SIDE | SRC_SERVICE_RELATION_SERVER_SIDE | SRC_SERVICE_RELATION_CLIENT_SIDE | SRC_ALARM_RECORD | SRC_HTTP_ACCESS_LOG | SRC_ZIPKIN_SPAN | SRC_JAEGER_SPAN ; sourceAttribute : IDENTIFIER | ALL ; variable : IDENTIFIER ; aggregateFunction : functionName LR_BRACKET (funcParamExpression | (literalExpression (COMMA literalExpression)?))? RR_BRACKET ; functionName : IDENTIFIER ; funcParamExpression : expression ; literalExpression : BOOL_LITERAL | NUMBER_LITERAL ; expression : booleanMatch | stringMatch | greaterMatch | lessMatch | greaterEqualMatch | lessEqualMatch ; booleanMatch : conditionAttribute DUALEQUALS booleanConditionValue ; stringMatch : conditionAttribute DUALEQUALS (stringConditionValue | enumConditionValue) ; greaterMatch : conditionAttribute GREATER numberConditionValue ; lessMatch : conditionAttribute LESS numberConditionValue ; greaterEqualMatch : conditionAttribute GREATER_EQUAL numberConditionValue ; lessEqualMatch : conditionAttribute LESS_EQUAL numberConditionValue ; conditionAttribute : IDENTIFIER ; booleanConditionValue : BOOL_LITERAL ; stringConditionValue : STRING_LITERAL ; enumConditionValue : IDENTIFIER DOT IDENTIFIER ; numberConditionValue : NUMBER_LITERAL ;
Move zipkin and jaeger span source to disable from metrics. (#2842)
Move zipkin and jaeger span source to disable from metrics. (#2842)
ANTLR
apache-2.0
ascrutae/sky-walking,apache/skywalking,ascrutae/sky-walking,apache/skywalking,OpenSkywalking/skywalking,apache/skywalking,apache/skywalking,ascrutae/sky-walking,OpenSkywalking/skywalking,apache/skywalking,ascrutae/sky-walking,apache/skywalking,apache/skywalking
d3d0fbf0fd4cc70ba3ee6456f3526b1c391137ea
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-postgresql/src/main/antlr4/imports/postgresql/DDLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE tableNotExistClause_ tableName createDefinitionClause_ inheritClause_ ; createIndex : CREATE createIndexSpecification_ INDEX concurrentlyClause_ (indexNotExistClause_ indexName)? ON onlyClause_ tableName ; alterTable : ALTER TABLE tableExistClause_ onlyClause_ tableName asteriskClause_ (alterTableActions | renameColumnSpecification | renameConstraint | renameTableSpecification_) ; alterIndex : alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace ; dropTable : DROP TABLE (IF EXISTS)? tableNames ; dropIndex : DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)* ; truncateTable : TRUNCATE TABLE? ONLY? tableNameParts ; createTableSpecification_ : ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? ; tableNotExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ (createDefinition (COMMA_ createDefinition)*)? RP_ ; createDefinition : columnDefinition | tableConstraint | LIKE tableName likeOption* ; columnDefinition : columnName dataType collateClause? columnConstraint* ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT ignoredIdentifier_ ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; checkOption : CHECK expr (NO INHERIT)? ; defaultExpr : CURRENT_TIMESTAMP | expr ; sequenceOptions : sequenceOption+ ; sequenceOption : START WITH? NUMBER_ | INCREMENT BY? NUMBER_ | MAXVALUE NUMBER_ | NO MAXVALUE | MINVALUE NUMBER_ | NO MINVALUE | CYCLE | NO CYCLE | CACHE NUMBER_ | OWNED BY ; indexParameters : (USING INDEX TABLESPACE ignoredIdentifier_)? | INCLUDE columnNames | WITH ; action : NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT) ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))? ; likeOption : (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnNames indexParameters | primaryKey columnNames indexParameters | EXCLUDE (USING ignoredIdentifier_)? | FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; inheritClause_ : (INHERITS tableNames)? ; createIndexSpecification_ : UNIQUE? ; concurrentlyClause_ : CONCURRENTLY? ; indexNotExistClause_ : (IF NOT EXISTS)? ; onlyClause_ : ONLY? ; tableExistClause_ : (IF EXISTS)? ; asteriskClause_ : ASTERISK_? ; alterIndexName : ALTER INDEX (IF EXISTS)? indexName ; renameIndexSpecification : RENAME TO indexName ; alterIndexDependsOnExtension : ALTER INDEX indexName DEPENDS ON EXTENSION ignoredIdentifier_ ; alterIndexSetTableSpace : ALTER INDEX ALL IN TABLESPACE indexName (OWNED BY ignoredIdentifiers_)? ; tableNameParts : tableNamePart (COMMA_ tableNamePart)* ; tableNamePart : tableName ASTERISK_? ; alterTableNameWithAsterisk : ALTER TABLE (IF EXISTS)? ONLY? tableName ASTERISK_? ; alterTableActions : alterTableAction (COMMA_ alterTableAction)* ; alterTableAction : addColumnSpecification | dropColumnSpecification | modifyColumnSpecification | addConstraintSpecification | ALTER CONSTRAINT ignoredIdentifier_ constraintOptionalParam | VALIDATE CONSTRAINT ignoredIdentifier_ | DROP CONSTRAINT (IF EXISTS)? ignoredIdentifier_ (RESTRICT | CASCADE)? | (DISABLE | ENABLE) TRIGGER (ignoredIdentifier_ | ALL | USER)? | ENABLE (REPLICA | ALWAYS) TRIGGER ignoredIdentifier_ | (DISABLE | ENABLE) RULE ignoredIdentifier_ | ENABLE (REPLICA | ALWAYS) RULE ignoredIdentifier_ | (DISABLE | ENABLE | (NO? FORCE)) ROW LEVEL SECURITY | CLUSTER ON indexName | SET WITHOUT CLUSTER | SET (WITH | WITHOUT) OIDS | SET TABLESPACE ignoredIdentifier_ | SET (LOGGED | UNLOGGED) | SET LP_ storageParameterWithValue (COMMA_ storageParameterWithValue)* RP_ | RESET LP_ storageParameter (COMMA_ storageParameter)* RP_ | INHERIT tableName | NO INHERIT tableName | OF dataTypeName_ | NOT OF | OWNER TO (ignoredIdentifier_ | CURRENT_USER | SESSION_USER) | REPLICA IDENTITY (DEFAULT | (USING INDEX indexName) | FULL | NOTHING) ; tableConstraintUsingIndex : (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam ; addColumnSpecification : ADD COLUMN? (IF NOT EXISTS)? columnDefinition ; dropColumnSpecification : DROP COLUMN? (IF EXISTS)? columnName (RESTRICT | CASCADE)? ; modifyColumnSpecification : alterColumn (SET DATA)? TYPE dataType collateClause? (USING simpleExpr)? | alterColumn SET DEFAULT expr | alterColumn DROP DEFAULT | alterColumn (SET | DROP) NOT NULL | alterColumn ADD GENERATED (ALWAYS | (BY DEFAULT)) AS IDENTITY (LP_ sequenceOptions RP_)? | alterColumn alterColumnSetOption alterColumnSetOption* | alterColumn DROP IDENTITY (IF EXISTS)? | alterColumn SET STATISTICS NUMBER_ | alterColumn SET LP_ attributeOptions RP_ | alterColumn RESET LP_ attributeOptions RP_ | alterColumn SET STORAGE (PLAIN | EXTERNAL | EXTENDED | MAIN) ; alterColumn : ALTER COLUMN? columnName ; alterColumnSetOption : SET (GENERATED (ALWAYS | BY DEFAULT) | sequenceOption) | RESTART (WITH? NUMBER_)? ; attributeOptions : attributeOption (COMMA_ attributeOption)* ; attributeOption : IDENTIFIER_ EQ_ simpleExpr ; addConstraintSpecification : ADD (tableConstraint (NOT VALID)? | tableConstraintUsingIndex) ; renameColumnSpecification : RENAME COLUMN? columnName TO columnName ; renameConstraint : RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_ ; storageParameterWithValue : storageParameter EQ_ simpleExpr ; storageParameter : IDENTIFIER_ ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; usingIndexType : USING (BTREE | HASH | GIST | SPGIST | GIN | BRIN) ; excludeElement : (columnName | expr) ignoredIdentifier_? (ASC | DESC)? (NULLS (FIRST | LAST))? ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE tableNotExistClause_ tableName createDefinitionClause_ inheritClause_ ; createIndex : CREATE createIndexSpecification_ INDEX concurrentlyClause_ (indexNotExistClause_ indexName)? ON onlyClause_ tableName ; alterTable : ALTER TABLE tableExistClause_ onlyClause_ tableName asteriskClause_ alterClause_ ; alterIndex : alterIndexName renameIndexSpecification | alterIndexDependsOnExtension | alterIndexSetTableSpace ; dropTable : DROP TABLE (IF EXISTS)? tableNames ; dropIndex : DROP INDEX (CONCURRENTLY)? (IF EXISTS)? indexName (COMMA_ indexName)* ; truncateTable : TRUNCATE TABLE? ONLY? tableNameParts ; createTableSpecification_ : ((GLOBAL | LOCAL)? (TEMPORARY | TEMP) | UNLOGGED)? ; tableNotExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ (createDefinition (COMMA_ createDefinition)*)? RP_ ; createDefinition : columnDefinition | tableConstraint | LIKE tableName likeOption* ; columnDefinition : columnName dataType collateClause? columnConstraint* ; columnConstraint : constraintClause? columnConstraintOption constraintOptionalParam ; constraintClause : CONSTRAINT ignoredIdentifier_ ; columnConstraintOption : NOT? NULL | checkOption | DEFAULT defaultExpr | GENERATED (ALWAYS | BY DEFAULT) AS IDENTITY (LP_ sequenceOptions RP_)? | UNIQUE indexParameters | primaryKey indexParameters | REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; checkOption : CHECK expr (NO INHERIT)? ; defaultExpr : CURRENT_TIMESTAMP | expr ; sequenceOptions : sequenceOption+ ; sequenceOption : START WITH? NUMBER_ | INCREMENT BY? NUMBER_ | MAXVALUE NUMBER_ | NO MAXVALUE | MINVALUE NUMBER_ | NO MINVALUE | CYCLE | NO CYCLE | CACHE NUMBER_ | OWNED BY ; indexParameters : (USING INDEX TABLESPACE ignoredIdentifier_)? | INCLUDE columnNames | WITH ; action : NO ACTION | RESTRICT | CASCADE | SET (NULL | DEFAULT) ; constraintOptionalParam : (NOT? DEFERRABLE)? (INITIALLY (DEFERRED | IMMEDIATE))? ; likeOption : (INCLUDING | EXCLUDING) (COMMENTS | CONSTRAINTS | DEFAULTS | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL) ; tableConstraint : constraintClause? tableConstraintOption constraintOptionalParam ; tableConstraintOption : checkOption | UNIQUE columnNames indexParameters | primaryKey columnNames indexParameters | EXCLUDE (USING ignoredIdentifier_)? | FOREIGN KEY columnNames REFERENCES tableName columnNames? (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (DELETE | UPDATE) action)* ; inheritClause_ : (INHERITS tableNames)? ; createIndexSpecification_ : UNIQUE? ; concurrentlyClause_ : CONCURRENTLY? ; indexNotExistClause_ : (IF NOT EXISTS)? ; onlyClause_ : ONLY? ; tableExistClause_ : (IF EXISTS)? ; asteriskClause_ : ASTERISK_? ; alterClause_ : alterTableActions | renameColumnSpecification | renameConstraint | renameTableSpecification_ ; 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_? ; 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) ; 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) ; tableConstraintUsingIndex : (CONSTRAINT ignoredIdentifier_)? (UNIQUE | primaryKey) USING INDEX indexName constraintOptionalParam ; storageParameterWithValue : storageParameter EQ_ simpleExpr ; storageParameter : IDENTIFIER_ ; renameColumnSpecification : RENAME COLUMN? columnName TO columnName ; renameConstraint : RENAME CONSTRAINT ignoredIdentifier_ TO ignoredIdentifier_ ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ;
modify alterClause_ rule
modify alterClause_ rule
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
a79c9ec18327bda3bd97f776639fdf1dc9dfdffb
client/src/main/antlr4/com/metamx/druid/sql/antlr4/DruidSQL.g4
client/src/main/antlr4/com/metamx/druid/sql/antlr4/DruidSQL.g4
grammar DruidSQL; @header { import com.metamx.druid.aggregation.post.*; import com.metamx.druid.aggregation.*; import com.metamx.druid.query.filter.*; import com.metamx.druid.query.dimension.*; import com.metamx.druid.*; import com.google.common.base.*; import com.google.common.collect.Lists; import org.joda.time.*; import java.text.*; import java.util.*; } @parser::members { public Map<String, AggregatorFactory> aggregators = new LinkedHashMap<String, AggregatorFactory>(); public List<PostAggregator> postAggregators = new LinkedList<PostAggregator>(); public DimFilter filter; public List<org.joda.time.Interval> intervals; public List<String> fields = new LinkedList<String>(); public QueryGranularity granularity = QueryGranularity.ALL; public Map<String, DimensionSpec> groupByDimensions = new LinkedHashMap<String, DimensionSpec>(); String dataSourceName = null; public String getDataSource() { return dataSourceName; } public String unescape(String quoted) { String unquote = quoted.trim().replaceFirst("^'(.*)'\$", "\$1"); return unquote.replace("''", "'"); } AggregatorFactory evalAgg(String name, int fn) { switch (fn) { case SUM: return new DoubleSumAggregatorFactory("sum("+name+")", name); case MIN: return new MinAggregatorFactory("min("+name+")", name); case MAX: return new MaxAggregatorFactory("max("+name+")", name); case COUNT: return new CountAggregatorFactory(name); } throw new IllegalArgumentException("Unknown function [" + fn + "]"); } PostAggregator evalArithmeticPostAggregator(PostAggregator a, List<Token> ops, List<PostAggregator> b) { if(b.isEmpty()) return a; else { int i = 0; PostAggregator root = a; while(i < ops.size()) { List<PostAggregator> list = new LinkedList<PostAggregator>(); List<String> names = new LinkedList<String>(); names.add(root.getName()); list.add(root); Token op = ops.get(i); while(i < ops.size() && ops.get(i).getType() == op.getType()) { PostAggregator e = b.get(i); list.add(e); names.add(e.getName()); i++; } root = new ArithmeticPostAggregator("("+Joiner.on(op.getText()).join(names)+")", op.getText(), list); } return root; } } } AND: 'and'; OR: 'or'; SUM: 'sum'; MIN: 'min'; MAX: 'max'; COUNT: 'count'; AS: 'as'; OPEN: '('; CLOSE: ')'; STAR: '*'; NOT: '!' ; PLUS: '+'; MINUS: '-'; DIV: '/'; COMMA: ','; EQ: '='; NEQ: '!='; MATCH: '~'; 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); fields.add(a.p.getName()); } 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] : (f1=dimFilter AND)? t=timeFilter (AND f2=dimFilter)? { if($f1.ctx != null || $f2.ctx != null) { if($f1.ctx != null && $f2.ctx != null) { $filter = new AndDimFilter(Lists.newArrayList($f1.filter, $f2.filter)); } else if($f1.ctx != null) { $filter = $f1.filter; } else { $filter = $f2.filter; } } $interval = $t.interval; } ; dimFilter returns [DimFilter filter] : e=orDimFilter { $filter = $e.filter; } ; orDimFilter returns [DimFilter filter] : a=andDimFilter (OR^ b+=andDimFilter)* { if($b.isEmpty()) $filter = $a.filter; else { List<DimFilter> rest = new ArrayList<DimFilter>(); for(AndDimFilterContext e : $b) rest.add(e.filter); $filter = new OrDimFilter(Lists.asList($a.filter, rest.toArray(new DimFilter[]{}))); } } ; andDimFilter returns [DimFilter filter] : a=primaryDimFilter (AND^ b+=primaryDimFilter)* { if($b.isEmpty()) $filter = $a.filter; else { List<DimFilter> rest = new ArrayList<DimFilter>(); for(PrimaryDimFilterContext e : $b) rest.add(e.filter); $filter = new AndDimFilter(Lists.asList($a.filter, rest.toArray(new DimFilter[]{}))); } } ; primaryDimFilter returns [DimFilter filter] : e=selectorDimFilter { $filter = $e.filter; } | l=inListDimFilter { $filter = $l.filter; } | NOT f=dimFilter { $filter = new NotDimFilter($f.filter); } | OPEN! f=dimFilter CLOSE! { $filter = $f.filter; } ; selectorDimFilter returns [DimFilter filter] : dimension=IDENT op=(EQ|NEQ|MATCH) value=QUOTED_STRING { String dim = $dimension.text; String val = unescape($value.text); switch($op.type) { case(EQ): $filter = new SelectorDimFilter(dim, val); break; case(NEQ): $filter = new NotDimFilter(new SelectorDimFilter(dim, val)); break; case(MATCH): $filter = new RegexDimFilter(dim, val); break; } } ; inListDimFilter returns [DimFilter filter] : dimension=IDENT 'in' (OPEN! ( (list+=QUOTED_STRING (COMMA! list+=QUOTED_STRING)*) ) CLOSE!) { List<DimFilter> filterList = new LinkedList<DimFilter>(); for(Token e : $list) filterList.add(new SelectorDimFilter($dimension.text, unescape(e.getText()))); $filter = new OrDimFilter(filterList); } ; timeFilter returns [org.joda.time.Interval interval, QueryGranularity granularity] : 'timestamp' 'between' s=timestamp AND e=timestamp { $interval = new org.joda.time.Interval($s.t, $e.t); } ; granularityFn returns [QueryGranularity granularity] : 'granularity' OPEN! 'timestamp' ',' str=QUOTED_STRING CLOSE! { String granStr = unescape($str.text); try { $granularity = QueryGranularity.fromString(granStr); } catch(IllegalArgumentException e) { $granularity = new PeriodGranularity(new Period(granStr), null, null); } } ; timestamp returns [DateTime t] : NUMBER { String str = $NUMBER.text.trim(); try { $t = new DateTime(NumberFormat.getInstance().parse(str)); } catch(ParseException e) { throw new IllegalArgumentException("Unable to parse number [" + str + "]"); } } | QUOTED_STRING { $t = new DateTime(unescape($QUOTED_STRING.text)); } ;
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 List<String> fields = new LinkedList<String>(); public QueryGranularity granularity = QueryGranularity.ALL; public Map<String, DimensionSpec> groupByDimensions = new LinkedHashMap<String, DimensionSpec>(); String dataSourceName = null; public String getDataSource() { return dataSourceName; } public String unescape(String quoted) { String unquote = quoted.trim().replaceFirst("^'(.*)'\$", "\$1"); return unquote.replace("''", "'"); } AggregatorFactory evalAgg(String name, int fn) { switch (fn) { case SUM: return new DoubleSumAggregatorFactory("sum("+name+")", name); case MIN: return new MinAggregatorFactory("min("+name+")", name); case MAX: return new MaxAggregatorFactory("max("+name+")", name); case COUNT: return new CountAggregatorFactory(name); } throw new IllegalArgumentException("Unknown function [" + fn + "]"); } PostAggregator evalArithmeticPostAggregator(PostAggregator a, List<Token> ops, List<PostAggregator> b) { if(b.isEmpty()) return a; else { int i = 0; PostAggregator root = a; while(i < ops.size()) { List<PostAggregator> list = new LinkedList<PostAggregator>(); List<String> names = new LinkedList<String>(); names.add(root.getName()); list.add(root); Token op = ops.get(i); while(i < ops.size() && ops.get(i).getType() == op.getType()) { PostAggregator e = b.get(i); list.add(e); names.add(e.getName()); i++; } root = new ArithmeticPostAggregator("("+Joiner.on(op.getText()).join(names)+")", op.getText(), list); } return root; } } } AND: 'and'; OR: 'or'; SUM: 'sum'; MIN: 'min'; MAX: 'max'; COUNT: 'count'; AS: 'as'; OPEN: '('; CLOSE: ')'; STAR: '*'; NOT: '!' ; PLUS: '+'; MINUS: '-'; DIV: '/'; COMMA: ','; EQ: '='; NEQ: '!='; MATCH: '~'; 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); fields.add(a.p.getName()); } 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 { if($e.p instanceof ConstantPostAggregator) { ConstantPostAggregator c = (ConstantPostAggregator)$e.p; double v = c.getConstantValue().doubleValue() * -1; $p = new ConstantPostAggregator(Double.toString(v), v); } else { $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] : (f1=dimFilter AND)? t=timeFilter (AND f2=dimFilter)? { if($f1.ctx != null || $f2.ctx != null) { if($f1.ctx != null && $f2.ctx != null) { $filter = new AndDimFilter(Lists.newArrayList($f1.filter, $f2.filter)); } else if($f1.ctx != null) { $filter = $f1.filter; } else { $filter = $f2.filter; } } $interval = $t.interval; } ; dimFilter returns [DimFilter filter] : e=orDimFilter { $filter = $e.filter; } ; orDimFilter returns [DimFilter filter] : a=andDimFilter (OR^ b+=andDimFilter)* { if($b.isEmpty()) $filter = $a.filter; else { List<DimFilter> rest = new ArrayList<DimFilter>(); for(AndDimFilterContext e : $b) rest.add(e.filter); $filter = new OrDimFilter(Lists.asList($a.filter, rest.toArray(new DimFilter[]{}))); } } ; andDimFilter returns [DimFilter filter] : a=primaryDimFilter (AND^ b+=primaryDimFilter)* { if($b.isEmpty()) $filter = $a.filter; else { List<DimFilter> rest = new ArrayList<DimFilter>(); for(PrimaryDimFilterContext e : $b) rest.add(e.filter); $filter = new AndDimFilter(Lists.asList($a.filter, rest.toArray(new DimFilter[]{}))); } } ; primaryDimFilter returns [DimFilter filter] : e=selectorDimFilter { $filter = $e.filter; } | l=inListDimFilter { $filter = $l.filter; } | NOT f=dimFilter { $filter = new NotDimFilter($f.filter); } | OPEN! f=dimFilter CLOSE! { $filter = $f.filter; } ; selectorDimFilter returns [DimFilter filter] : dimension=IDENT op=(EQ|NEQ|MATCH) value=QUOTED_STRING { String dim = $dimension.text; String val = unescape($value.text); switch($op.type) { case(EQ): $filter = new SelectorDimFilter(dim, val); break; case(NEQ): $filter = new NotDimFilter(new SelectorDimFilter(dim, val)); break; case(MATCH): $filter = new RegexDimFilter(dim, val); break; } } ; inListDimFilter returns [DimFilter filter] : dimension=IDENT 'in' (OPEN! ( (list+=QUOTED_STRING (COMMA! list+=QUOTED_STRING)*) ) CLOSE!) { List<DimFilter> filterList = new LinkedList<DimFilter>(); for(Token e : $list) filterList.add(new SelectorDimFilter($dimension.text, unescape(e.getText()))); $filter = new OrDimFilter(filterList); } ; timeFilter returns [org.joda.time.Interval interval, QueryGranularity granularity] : 'timestamp' 'between' s=timestamp AND e=timestamp { $interval = new org.joda.time.Interval($s.t, $e.t); } ; granularityFn returns [QueryGranularity granularity] : 'granularity' OPEN! 'timestamp' ',' str=QUOTED_STRING CLOSE! { String granStr = unescape($str.text); try { $granularity = QueryGranularity.fromString(granStr); } catch(IllegalArgumentException e) { $granularity = new PeriodGranularity(new Period(granStr), null, null); } } ; timestamp returns [DateTime t] : NUMBER { String str = $NUMBER.text.trim(); try { $t = new DateTime(NumberFormat.getInstance().parse(str)); } catch(ParseException e) { throw new IllegalArgumentException("Unable to parse number [" + str + "]"); } } | QUOTED_STRING { $t = new DateTime(unescape($QUOTED_STRING.text)); } ;
fix some issues with negative numbers
fix some issues with negative numbers
ANTLR
apache-2.0
kevintvh/druid,dkhwangbo/druid,penuel-leo/druid,druid-io/druid,amikey/druid,cocosli/druid,Fokko/druid,knoguchi/druid,metamx/druid,767326791/druid,tubemogul/druid,redBorder/druid,lcp0578/druid,milimetric/druid,solimant/druid,Kleagleguo/druid,noddi/druid,winval/druid,gianm/druid,minewhat/druid,smartpcr/druid,andy256/druid,monetate/druid,Kleagleguo/druid,authbox-lib/druid,dclim/druid,kevintvh/druid,mangeshpardeshiyahoo/druid,smartpcr/druid,nvoron23/druid,rasahner/druid,mghosh4/druid,zxs/druid,Kleagleguo/druid,OttoOps/druid,jon-wei/druid,dclim/druid,monetate/druid,winval/druid,jon-wei/druid,du00cs/druid,zhaown/druid,anupkumardixit/druid,taochaoqiang/druid,smartpcr/druid,praveev/druid,wenjixin/druid,cocosli/druid,erikdubbelboer/druid,monetate/druid,skyportsystems/druid,authbox-lib/druid,praveev/druid,michaelschiff/druid,calliope7/druid,solimant/druid,premc/druid,andy256/druid,monetate/druid,nishantmonu51/druid,deltaprojects/druid,deltaprojects/druid,yaochitc/druid-dev,fjy/druid,b-slim/druid,qix/druid,pdeva/druid,milimetric/druid,mghosh4/druid,taochaoqiang/druid,amikey/druid,premc/druid,lizhanhui/data_druid,winval/druid,yaochitc/druid-dev,haoch/druid,noddi/druid,amikey/druid,tubemogul/druid,pjain1/druid,tubemogul/druid,haoch/druid,guobingkun/druid,kevintvh/druid,KurtYoung/druid,praveev/druid,Fokko/druid,rasahner/druid,nishantmonu51/druid,Fokko/druid,milimetric/druid,Deebs21/druid,himanshug/druid,767326791/druid,wenjixin/druid,mghosh4/druid,zxs/druid,cocosli/druid,nvoron23/druid,KurtYoung/druid,implydata/druid,pombredanne/druid,gianm/druid,eshen1991/druid,guobingkun/druid,friedhardware/druid,wenjixin/druid,andy256/druid,erikdubbelboer/druid,nvoron23/druid,gianm/druid,liquidm/druid,zengzhihai110/druid,b-slim/druid,zengzhihai110/druid,implydata/druid,friedhardware/druid,erikdubbelboer/druid,optimizely/druid,gianm/druid,Deebs21/druid,guobingkun/druid,liquidm/druid,Fokko/druid,minewhat/druid,se7entyse7en/druid,calliope7/druid,redBorder/druid,nishantmonu51/druid,himanshug/druid,nvoron23/druid,anupkumardixit/druid,lcp0578/druid,pombredanne/druid,eshen1991/druid,wenjixin/druid,elijah513/druid,nishantmonu51/druid,premc/druid,qix/druid,authbox-lib/druid,leventov/druid,fjy/druid,eshen1991/druid,optimizely/druid,se7entyse7en/druid,se7entyse7en/druid,yaochitc/druid-dev,zhihuij/druid,haoch/druid,wenjixin/druid,deltaprojects/druid,nishantmonu51/druid,friedhardware/druid,calliope7/druid,optimizely/druid,lcp0578/druid,zxs/druid,metamx/druid,michaelschiff/druid,zengzhihai110/druid,qix/druid,calliope7/druid,Deebs21/druid,elijah513/druid,metamx/druid,zhaown/druid,lizhanhui/data_druid,mangeshpardeshiyahoo/druid,zxs/druid,cocosli/druid,Deebs21/druid,mrijke/druid,lizhanhui/data_druid,premc/druid,du00cs/druid,pjain1/druid,monetate/druid,elijah513/druid,jon-wei/druid,monetate/druid,jon-wei/druid,fjy/druid,tubemogul/druid,rasahner/druid,himanshug/druid,deltaprojects/druid,jon-wei/druid,b-slim/druid,winval/druid,zengzhihai110/druid,b-slim/druid,Fokko/druid,minewhat/druid,767326791/druid,zhihuij/druid,OttoOps/druid,kevintvh/druid,minewhat/druid,andy256/druid,noddi/druid,dkhwangbo/druid,rasahner/druid,druid-io/druid,mangeshpardeshiyahoo/druid,pdeva/druid,friedhardware/druid,mghosh4/druid,noddi/druid,dkhwangbo/druid,haoch/druid,smartpcr/druid,knoguchi/druid,noddi/druid,zhiqinghuang/druid,solimant/druid,solimant/druid,zhihuij/druid,lcp0578/druid,eshen1991/druid,yaochitc/druid-dev,potto007/druid-avro,zhaown/druid,michaelschiff/druid,himanshug/druid,pjain1/druid,authbox-lib/druid,lizhanhui/data_druid,potto007/druid-avro,liquidm/druid,jon-wei/druid,michaelschiff/druid,smartpcr/druid,du00cs/druid,liquidm/druid,OttoOps/druid,OttoOps/druid,zhiqinghuang/druid,knoguchi/druid,pombredanne/druid,redBorder/druid,zhiqinghuang/druid,potto007/druid-avro,elijah513/druid,premc/druid,pjain1/druid,taochaoqiang/druid,metamx/druid,implydata/druid,fjy/druid,authbox-lib/druid,767326791/druid,druid-io/druid,mghosh4/druid,friedhardware/druid,gianm/druid,guobingkun/druid,druid-io/druid,cocosli/druid,du00cs/druid,potto007/druid-avro,zengzhihai110/druid,pdeva/druid,lcp0578/druid,mrijke/druid,qix/druid,Fokko/druid,pombredanne/druid,redBorder/druid,druid-io/druid,calliope7/druid,KurtYoung/druid,zhaown/druid,amikey/druid,zhiqinghuang/druid,taochaoqiang/druid,implydata/druid,qix/druid,se7entyse7en/druid,lizhanhui/data_druid,kevintvh/druid,Kleagleguo/druid,knoguchi/druid,fjy/druid,haoch/druid,leventov/druid,deltaprojects/druid,anupkumardixit/druid,deltaprojects/druid,mrijke/druid,pjain1/druid,implydata/druid,zhiqinghuang/druid,penuel-leo/druid,mrijke/druid,liquidm/druid,andy256/druid,skyportsystems/druid,gianm/druid,redBorder/druid,tubemogul/druid,skyportsystems/druid,milimetric/druid,skyportsystems/druid,KurtYoung/druid,erikdubbelboer/druid,leventov/druid,penuel-leo/druid,winval/druid,deltaprojects/druid,Fokko/druid,mangeshpardeshiyahoo/druid,767326791/druid,erikdubbelboer/druid,praveev/druid,amikey/druid,leventov/druid,guobingkun/druid,milimetric/druid,se7entyse7en/druid,eshen1991/druid,anupkumardixit/druid,dkhwangbo/druid,monetate/druid,anupkumardixit/druid,potto007/druid-avro,skyportsystems/druid,liquidm/druid,optimizely/druid,elijah513/druid,michaelschiff/druid,Deebs21/druid,implydata/druid,yaochitc/druid-dev,penuel-leo/druid,b-slim/druid,pdeva/druid,zhihuij/druid,Kleagleguo/druid,pjain1/druid,mrijke/druid,minewhat/druid,jon-wei/druid,nishantmonu51/druid,knoguchi/druid,dclim/druid,mghosh4/druid,pjain1/druid,KurtYoung/druid,leventov/druid,zhaown/druid,himanshug/druid,solimant/druid,pdeva/druid,pombredanne/druid,nishantmonu51/druid,dclim/druid,zhihuij/druid,du00cs/druid,penuel-leo/druid,taochaoqiang/druid,zxs/druid,OttoOps/druid,mghosh4/druid,metamx/druid,michaelschiff/druid,optimizely/druid,gianm/druid,rasahner/druid,dclim/druid,nvoron23/druid,praveev/druid,dkhwangbo/druid,michaelschiff/druid,mangeshpardeshiyahoo/druid
3c710c14f5e9dc0d1c93a5577430d1be977c0d7a
PS.g4
PS.g4
grammar PS; options { language=Python2; } WS: [ \t\r\n]+ -> skip; ADD: '+'; SUB: '-'; MUL: '*'; DIV: '/'; L_PAREN: '('; R_PAREN: ')'; L_BRACE: '{'; R_BRACE: '}'; L_BRACKET: '['; R_BRACKET: ']'; BAR: '|'; FUNC_LIM: '\\lim'; LIM_APPROACH_SYM: '\\to' | '\\rightarrow' | '\\Rightarrow' | '\\longrightarrow' | '\\Longrightarrow'; FUNC_INT: '\\int'; FUNC_SUM: '\\sum'; FUNC_PROD: '\\prod'; FUNC_LOG: '\\log'; FUNC_LN: '\\ln'; FUNC_SIN: '\\sin'; FUNC_COS: '\\cos'; FUNC_TAN: '\\tan'; FUNC_CSC: '\\csc'; FUNC_SEC: '\\sec'; FUNC_COT: '\\cot'; FUNC_ARCSIN: '\\arcsin'; FUNC_ARCCOS: '\\arccos'; FUNC_ARCTAN: '\\arctan'; FUNC_ARCCSC: '\\arccsc'; FUNC_ARCSEC: '\\arcsec'; FUNC_ARCCOT: '\\arccot'; FUNC_SINH: '\\sinh'; FUNC_COSH: '\\cosh'; FUNC_TANH: '\\tanh'; FUNC_ARSINH: '\\arsinh'; FUNC_ARCOSH: '\\arcosh'; FUNC_ARTANH: '\\artanh'; FUNC_SQRT: '\\sqrt'; CMD_TIMES: '\\times'; CMD_CDOT: '\\cdot'; CMD_DIV: '\\div'; CMD_FRAC: '\\frac'; UNDERSCORE: '_'; CARET: '^'; fragment WS_CHAR: [ \t\r\n]; DIFFERENTIAL: 'd' WS_CHAR*? ([a-zA-Z] | '\\' [a-zA-Z]+); LETTER: [a-zA-Z]; fragment DIGIT: [0-9]; NUMBER: DIGIT+ (',' DIGIT DIGIT DIGIT)* | DIGIT* (',' DIGIT DIGIT DIGIT)* '.' DIGIT+; EQUAL: '='; LT: '<'; LTE: '\\leq'; GT: '>'; GTE: '\\geq'; BANG: '!'; SYMBOL: '\\' [a-zA-Z]+; math: relation; relation: relation (EQUAL | LT | LTE | GT | GTE) relation | expr; equality: expr EQUAL expr; expr: additive; additive: additive (ADD | SUB) additive | mp; // mult part mp: mp (MUL | CMD_TIMES | CMD_CDOT | DIV | CMD_DIV) mp | unary; mp_nofunc: mp_nofunc (MUL | CMD_TIMES | CMD_CDOT | DIV | CMD_DIV) mp_nofunc | unary_nofunc; unary: (ADD | SUB) unary | postfix+; unary_nofunc: (ADD | SUB) unary_nofunc | postfix postfix_nofunc*; postfix: exp postfix_op*; postfix_nofunc: exp_nofunc postfix_op*; postfix_op: BANG | eval_at; eval_at: BAR (eval_at_sup | eval_at_sub | eval_at_sup eval_at_sub); eval_at_sub: UNDERSCORE L_BRACE (expr | equality) R_BRACE; eval_at_sup: CARET L_BRACE (expr | equality) R_BRACE; exp: exp CARET (atom | L_BRACE expr R_BRACE) subexpr? | comp; exp_nofunc: exp_nofunc CARET (atom | L_BRACE expr R_BRACE) subexpr? | comp_nofunc; comp: group | abs_group | func | atom | frac; comp_nofunc: group | abs_group | atom | frac; group: L_PAREN expr R_PAREN | L_BRACKET expr R_BRACKET; abs_group: BAR expr BAR; atom: (LETTER | SYMBOL) subexpr? | NUMBER | DIFFERENTIAL; frac: CMD_FRAC L_BRACE upper=expr R_BRACE L_BRACE lower=expr R_BRACE; func_normal: FUNC_LOG | FUNC_LN | FUNC_SIN | FUNC_COS | FUNC_TAN | FUNC_CSC | FUNC_SEC | FUNC_COT | FUNC_ARCSIN | FUNC_ARCCOS | FUNC_ARCTAN | FUNC_ARCCSC | FUNC_ARCSEC | FUNC_ARCCOT | FUNC_SINH | FUNC_COSH | FUNC_TANH | FUNC_ARSINH | FUNC_ARCOSH | FUNC_ARTANH; func: func_normal (subexpr? supexpr? | supexpr? subexpr?) (L_PAREN func_arg R_PAREN | func_arg_noparens) | (LETTER | SYMBOL) subexpr? // e.g. f(x) L_PAREN args R_PAREN | FUNC_INT (subexpr supexpr | supexpr subexpr)? (additive? DIFFERENTIAL | frac | additive) | FUNC_SQRT (L_BRACKET root=expr R_BRACKET)? L_BRACE base=expr R_BRACE | (FUNC_SUM | FUNC_PROD) (subeq supexpr | supexpr subeq) mp | FUNC_LIM limit_sub mp; args: (expr WS*? ',' WS*? args) | expr; limit_sub: UNDERSCORE L_BRACE (LETTER | SYMBOL) LIM_APPROACH_SYM expr (CARET L_BRACE (ADD | SUB) R_BRACE)? R_BRACE; func_arg: expr | (expr WS*? ',' WS*? func_arg); func_arg_noparens: mp_nofunc; subexpr: UNDERSCORE (atom | L_BRACE expr R_BRACE); supexpr: CARET (atom | L_BRACE expr R_BRACE); subeq: UNDERSCORE L_BRACE equality R_BRACE; supeq: UNDERSCORE L_BRACE equality R_BRACE;
grammar PS; options { language=Python2; } WS: [ \t\r\n]+ -> skip; ADD: '+'; SUB: '-'; MUL: '*'; DIV: '/'; L_PAREN: '('; R_PAREN: ')'; L_BRACE: '{'; R_BRACE: '}'; L_BRACKET: '['; R_BRACKET: ']'; BAR: '|'; FUNC_LIM: '\\lim'; LIM_APPROACH_SYM: '\\to' | '\\rightarrow' | '\\Rightarrow' | '\\longrightarrow' | '\\Longrightarrow'; FUNC_INT: '\\int'; FUNC_SUM: '\\sum'; FUNC_PROD: '\\prod'; FUNC_LOG: '\\log'; FUNC_LN: '\\ln'; FUNC_SIN: '\\sin'; FUNC_COS: '\\cos'; FUNC_TAN: '\\tan'; FUNC_CSC: '\\csc'; FUNC_SEC: '\\sec'; FUNC_COT: '\\cot'; FUNC_ARCSIN: '\\arcsin'; FUNC_ARCCOS: '\\arccos'; FUNC_ARCTAN: '\\arctan'; FUNC_ARCCSC: '\\arccsc'; FUNC_ARCSEC: '\\arcsec'; FUNC_ARCCOT: '\\arccot'; FUNC_SINH: '\\sinh'; FUNC_COSH: '\\cosh'; FUNC_TANH: '\\tanh'; FUNC_ARSINH: '\\arsinh'; FUNC_ARCOSH: '\\arcosh'; FUNC_ARTANH: '\\artanh'; FUNC_SQRT: '\\sqrt'; CMD_TIMES: '\\times'; CMD_CDOT: '\\cdot'; CMD_DIV: '\\div'; CMD_FRAC: '\\frac'; UNDERSCORE: '_'; CARET: '^'; fragment WS_CHAR: [ \t\r\n]; DIFFERENTIAL: 'd' WS_CHAR*? ([a-zA-Z] | '\\' [a-zA-Z]+); LETTER: [a-zA-Z]; fragment DIGIT: [0-9]; NUMBER: DIGIT+ (',' DIGIT DIGIT DIGIT)* | DIGIT* (',' DIGIT DIGIT DIGIT)* '.' DIGIT+; EQUAL: '='; LT: '<'; LTE: '\\leq'; GT: '>'; GTE: '\\geq'; BANG: '!'; SYMBOL: '\\' [a-zA-Z]+; math: relation; relation: relation (EQUAL | LT | LTE | GT | GTE) relation | expr; equality: expr EQUAL expr; expr: '{'? WS*? additive WS*? '}'?; additive: additive (ADD | SUB) additive | mp; // mult part mp: mp (MUL | CMD_TIMES | CMD_CDOT | DIV | CMD_DIV) mp | unary; mp_nofunc: mp_nofunc (MUL | CMD_TIMES | CMD_CDOT | DIV | CMD_DIV) mp_nofunc | unary_nofunc; unary: (ADD | SUB) unary | postfix+; unary_nofunc: (ADD | SUB) unary_nofunc | postfix postfix_nofunc*; postfix: exp postfix_op*; postfix_nofunc: exp_nofunc postfix_op*; postfix_op: BANG | eval_at; eval_at: BAR (eval_at_sup | eval_at_sub | eval_at_sup eval_at_sub); eval_at_sub: UNDERSCORE L_BRACE (expr | equality) R_BRACE; eval_at_sup: CARET L_BRACE (expr | equality) R_BRACE; exp: exp CARET (atom | L_BRACE expr R_BRACE) subexpr? | comp; exp_nofunc: exp_nofunc CARET (atom | L_BRACE expr R_BRACE) subexpr? | comp_nofunc; comp: group | abs_group | func | atom | frac; comp_nofunc: group | abs_group | atom | frac; group: L_PAREN expr R_PAREN | L_BRACKET expr R_BRACKET; abs_group: BAR expr BAR; atom: (LETTER | SYMBOL) subexpr? | NUMBER | DIFFERENTIAL; frac: CMD_FRAC L_BRACE upper=expr R_BRACE L_BRACE lower=expr R_BRACE; func_normal: FUNC_LOG | FUNC_LN | FUNC_SIN | FUNC_COS | FUNC_TAN | FUNC_CSC | FUNC_SEC | FUNC_COT | FUNC_ARCSIN | FUNC_ARCCOS | FUNC_ARCTAN | FUNC_ARCCSC | FUNC_ARCSEC | FUNC_ARCCOT | FUNC_SINH | FUNC_COSH | FUNC_TANH | FUNC_ARSINH | FUNC_ARCOSH | FUNC_ARTANH; func: func_normal (subexpr? supexpr? | supexpr? subexpr?) (L_PAREN func_arg R_PAREN | func_arg_noparens) | (LETTER | SYMBOL) subexpr? // e.g. f(x) L_PAREN args R_PAREN | FUNC_INT (subexpr supexpr | supexpr subexpr)? (additive? DIFFERENTIAL | frac | additive) | FUNC_SQRT (L_BRACKET root=expr R_BRACKET)? L_BRACE base=expr R_BRACE | (FUNC_SUM | FUNC_PROD) (subeq supexpr | supexpr subeq) mp | FUNC_LIM limit_sub mp; args: (expr WS*? ',' WS*? args) | expr; limit_sub: UNDERSCORE L_BRACE (LETTER | SYMBOL) LIM_APPROACH_SYM expr (CARET L_BRACE (ADD | SUB) R_BRACE)? R_BRACE; func_arg: expr | (expr WS*? ',' WS*? func_arg); func_arg_noparens: mp_nofunc; subexpr: UNDERSCORE (atom | L_BRACE expr R_BRACE); supexpr: CARET (atom | L_BRACE expr R_BRACE); subeq: UNDERSCORE L_BRACE equality R_BRACE; supeq: UNDERSCORE L_BRACE equality R_BRACE;
handle expressions with floating braces, e.g. {a+b} means a+b
handle expressions with floating braces, e.g. {a+b} means a+b
ANTLR
mit
augustt198/latex2sympy
7cfb46849d69decd54a72c83caebc4dd24f2bfff
reo-compiler/src/main/antlr4/nl/cwi/reo/parse/Reo.g4
reo-compiler/src/main/antlr4/nl/cwi/reo/parse/Reo.g4
grammar Reo; /** * Generic structure */ file : (comp | defn)* EOF ; defn : 'define' ID params? portset '{' atom '}' # defnAtomic | 'define' ID params? nodeset '{' comp* '}' # defnComposed ; comp : ID assign? nodeset # compReference | 'for' ID '=' expr '...' expr '{' comp* '}' # compForLoop ; atom : java # atomJava | c # atomC | pa # atomPA | casm # atomCASM | wa # atomWA ; params : '<' ID (',' ID)* '>' ; assign : '<' value (',' value)* '>' ; value : ID | INT | STRING ; nodeset : '(' ')' | '(' nodes (',' nodes)* ')' ; nodes : ID # nodesName | ID '[' expr ']' # nodesIndex | ID '[' expr '...' expr ']' # nodesRange ; portset : '(' port (',' port)* ')' ; port : ID '?' # portInput | ID '!' # portOutput ; expr : ID # exprParameter | INT # exprInteger | INT ID # exprScalar | '-' expr # exprUnaryMin | expr '+' expr # exprAddition | expr '-' expr # exprDifference ; /** * Java */ java : '#Java' FUNC ; /** * C */ c : '#C' FUNC ; /** * Port Automata */ pa : '#PA' pa_stmt* ; pa_stmt : ID '--' sync_const '->' ID ; sync_const : '{' '}' | '{' ID (',' ID)* '}' ; /** * Constraint Automata with State Memory */ casm : '#CASM' casm_stmt* ; casm_stmt : ID '--' sync_const ',' casm_dc '->' ID ; casm_dc : 'true' # casm_dcTrue | casm_term '==' casm_term # casm_dcEql ; casm_term : STRING # casm_termData | 'd(' ID ')' # casm_termPort | ID # casm_termMemoryCurr | ID '\'' # casm_termMemoryNext ; /** * Work Automata */ wa : '#WA' wa_stmt* ; wa_stmt : ID ':' wa_jc # wa_stmtInvar | ID '--' sync_const ',' wa_jc '->' ID # wa_stmtTrans ; wa_jc : 'true' # wa_jcTrue | ID '==' INT # wa_jcEql | ID '<=' INT # wa_jcLeq | wa_jc '&' wa_jc # wa_jcAnd ; /** * Tokens */ ID : [a-zA-Z] [a-zA-Z0-9]* ; INT : ( '0' | [1-9] [0-9]* ) ; STRING : '\'' .*? '\'' ; FUNC : [a-zA-Z] [a-zA-Z0-9_-.:]* ; SPACES : [ \t\r\n]+ -> skip ; SL_COMM : '//' .*? ('\n'|EOF) -> skip ; ML_COMM : '/*' .*? '*/' -> skip ;
grammar Reo; /** * Generic structure */ file : (comp | defn)* EOF ; defn : 'define' ID params? portset '{' atom '}' # defnAtomic | 'define' ID params? nodeset '{' comp* '}' # defnComposed ; comp : ID assign? nodeset # compReference | 'for' ID '=' expr '...' expr '{' comp* '}' # compForLoop ; atom : java # atomJava | c # atomC | pa # atomPA | cam # atomCAM | wa # atomWA ; params : '<' ID (',' ID)* '>' ; assign : '<' value (',' value)* '>' ; value : ID | INT | STRING ; nodeset : '(' ')' | '(' nodes (',' nodes)* ')' ; nodes : ID # nodesName | ID '[' expr ']' # nodesIndex | ID '[' expr '...' expr ']' # nodesRange ; portset : '(' port (',' port)* ')' ; port : ID '?' # portInput | ID '!' # portOutput ; expr : ID # exprParameter | INT # exprInteger | INT ID # exprScalar | '-' expr # exprUnaryMin | expr '+' expr # exprAddition | expr '-' expr # exprDifference ; /** * Java */ java : '#Java' FUNC ; /** * C */ c : '#C' FUNC ; /** * Port Automata */ pa : '#PA' pa_stmt* ; pa_stmt : ID '--' sync_const '->' ID ; sync_const : '{' '}' | '{' ID (',' ID)* '}' ; /** * Constraint Automata with State Memory */ casm : '#CASM' casm_stmt* ; casm_stmt : ID '--' sync_const ',' casm_dc '->' ID ; casm_dc : 'true' # casm_dcTrue | casm_term '==' casm_term # casm_dcEql ; casm_term : STRING # casm_termData | 'd(' ID ')' # casm_termPort | ID # casm_termMemoryCurr | ID '\'' # casm_termMemoryNext ; /** * Work Automata */ wa : '#WA' wa_stmt* ; wa_stmt : ID ':' wa_jc # wa_stmtInvar | ID '--' sync_const ',' wa_jc '->' ID # wa_stmtTrans ; wa_jc : 'true' # wa_jcTrue | ID '==' INT # wa_jcEql | ID '<=' INT # wa_jcLeq | wa_jc '&' wa_jc # wa_jcAnd ; /** * Tokens */ ID : [a-zA-Z] [a-zA-Z0-9]* ; INT : ( '0' | [1-9] [0-9]* ) ; STRING : '\'' .*? '\'' ; FUNC : [a-zA-Z] [a-zA-Z0-9_-.:]* ; SPACES : [ \t\r\n]+ -> skip ; SL_COMM : '//' .*? ('\n'|EOF) -> skip ; ML_COMM : '/*' .*? '*/' -> skip ;
Update Reo.g4
Update Reo.g4
ANTLR
mit
kasperdokter/Reo,kasperdokter/Reo-compiler,kasperdokter/Reo,kasperdokter/Reo-compiler,kasperdokter/Reo,kasperdokter/Reo-compiler,kasperdokter/Reo-compiler,kasperdokter/Reo-compiler,kasperdokter/Reo
f35a22d64ee5edae055850b1e93495b2299dc537
model/stratus/src/main/antlr4/org/xtuml/stratus/parser/MaslLexer.g4
model/stratus/src/main/antlr4/org/xtuml/stratus/parser/MaslLexer.g4
lexer grammar MaslLexer; //============================================================================================================== //============================================================================================================== // // Lexer // //============================================================================================================== //============================================================================================================== // Logical Operators AND : 'and'; OR : 'or'; XOR : 'xor'; // Unary and Additive Operators (Keep in this order to // improve efficiency so unary and additive can be looked // for as ranges) ABS : 'abs'; NOT : 'not'; PLUS : '+'; MINUS : '-'; CONCATENATE : '&'; UNION : 'union'; NOT_IN : 'not_in'; // Multiplicactive Operators DIVIDE : '/'; TIMES : '*'; INTERSECTION : 'intersection'; MOD : 'mod'; POWER : '**'; REM : 'rem'; DISUNION : 'disunion'; // Equality Operators EQUAL : '='; NOT_EQUAL : '/='; // Comparison Operators GT : '>'; GTE : '>='; LT : '<'; LTE : '<='; // Stream Operators STREAM_LINE_IN : '>>>'; STREAM_LINE_OUT : '<<<'; STREAM_IN : '>>'; STREAM_OUT : '<<'; // Special characters ASSIGN : ':='; COLON : ':'; COMMA : ','; DOT : '.'; LTGT : '<>'; PRIME : '\''; RANGE_DOTS : '..'; LPAREN : '('; RPAREN : ')'; LBRACKET : '['; RBRACKET : ']'; SCOPE : '::'; SEMI : ';'; GOES_TO : '=>'; NAVIGATE : '->'; TERMINATOR_SCOPE : '~>'; CASE_OR : '|'; // Keywords ARRAY : 'array'; ANONYMOUS : 'anonymous'; ASSIGNER : 'assigner'; AT : 'at'; BAG : 'bag'; BEGIN : 'begin'; CANNOT_HAPPEN : 'Cannot_Happen' | 'cannot_happen'; CANCEL : 'cancel'; CASE : 'case'; CONDITIONALLY : 'conditionally'; CONSOLE : 'console'; CREATE : 'create'; CREATION : 'creation'; CURRENT_STATE : 'Current_State' /* | 'current_state' */; DECLARE : 'declare'; DEFERRED : 'deferred'; DELAY : 'delay'; DELETE : 'delete'; DELTA : 'delta'; DICTIONARY : 'dictionary'; DIGITS : 'digits'; DOMAIN : 'domain'; ELSE : 'else'; ELSIF : 'elsif'; END : 'end'; ENUM : 'enum'; ERASE : 'erase'; EVENT : 'event'; EXCEPTION : 'exception'; EXIT : 'exit'; FIND : 'find' | 'find_all'; FIND_ONE : 'find_one'; FIND_ONLY : 'find_only'; FOR : 'for'; GENERATE : 'generate'; IDENTIFIER : 'identifier'; IF : 'if'; IGNORE : 'Ignore' /* | 'ignore' */; IN : 'in'; INSTANCE : 'instance'; IS_A : 'is_a'; IS : 'is'; LINK : 'link'; LOOP : 'loop'; MANY : 'many'; NON_EXISTENT : 'Non_Existent' | 'Non_Existant' | 'non_existent'; OBJECT : 'object'; OF : 'of'; ONE : 'one'; ORDERED_BY : 'ordered_by'; OTHERS : 'others'; OUT : 'out'; PRAGMA : 'pragma'; PREFERRED : 'preferred'; PRIVATE : 'private'; PROJECT : 'project'; PUBLIC : 'public'; RAISE : 'raise'; RANGE : 'range'; READONLY : 'readonly'; REFERENTIAL : 'referential'; RELATIONSHIP : 'relationship'; RETURN : 'return'; REVERSE : 'reverse'; REVERSE_ORDERED_BY : 'reverse_ordered_by'; SCHEDULE : 'schedule'; SEQUENCE : 'sequence'; SERVICE : 'service' | 'function'; SET : 'set'; START : 'start'; STATE : 'state'; STRUCTURE : 'structure'; TERMINAL : 'terminal'; TERMINATOR : 'terminator'; THEN : 'then'; THIS : 'this'; TO : 'to'; TRANSITION : 'transition'; TYPE : 'type' | 'subtype'; UNCONDITIONALLY : 'unconditionally'; UNIQUE : 'unique'; UNLINK : 'unlink'; USING : 'using'; WHEN : 'when'; WHILE : 'while'; WITH : 'with'; NULL : 'null'; FLUSH : 'flush'; ENDL : 'endl'; TRUE : 'true'; FALSE : 'false'; LINE_NO : '#LINE#' { setText("#LINE#"); }; FILE_NAME : '#FILE#' { setText("#FILE#"); }; // Numeric Literals IntegerLiteral : Digit Digit? '#' BasedDigit+ | Digit+ ; RealLiteral : Digit+ ( ('.' Digit) | UnbasedExponent ) | '.' Digit+ UnbasedExponent? | Digit Digit? '#' ( BasedDigit+ ( ('.' BasedDigit) | BasedExponent ) | '.' BasedDigit+ BasedExponent? ) ; fragment UnbasedExponent : ('e'|'E')('+'|'-')? Digit+ ; fragment BasedExponent : '#' ('+'|'-')? Digit+ ; fragment Digit : '0'..'9'; fragment BasedDigit : '0'..'9' | 'a'..'z' | 'A'..'Z'; fragment Letter : 'A'..'Z' | 'a'..'z'; // Character and String Literals DurationLiteral : '@P' ( ~('@' | ' ' | '\t' | '\f' | '\n' | '\r') )* '@' ; TimestampLiteral : '@' ( ~('@' | ' ' | '\t' | '\f' | '\n' | '\r') )* '@' ; CharacterLiteral : '\'' ( EscapeSequence | ~('\''|'\\') ) '\'' ; StringLiteral : '"' ( EscapeSequence | ~('\\'|'"') )* '"' ; fragment EscapeSequence : '\\' ('b'|'t'|'n'|'f'|'r'|'"'|'\''|'\\') | UnicodeEscape | OctalEscape ; fragment OctalEscape : '\\' ('0'..'3') ('0'..'7') ('0'..'7') | '\\' ('0'..'7') ('0'..'7') | '\\' ('0'..'7') ; fragment UnicodeEscape : '\\' 'u' HexDigit HexDigit HexDigit HexDigit; fragment HexDigit : ('0'..'9'|'a'..'f'|'A'..'F') ; // identifiers RelationshipName : 'R' '1'..'9' Digit* ; Identifier : ( Letter | '_' ) ( Letter | Digit | '_' )*; Description : '//!' ~('\n'|'\r')* '\r'? '\n'; Comment : '//' ~('\n'|'\r')* '\r'? '\n' { setChannel(HIDDEN); }; Whitespace : (' ' | '\t' | '\f' | '\n' | '\r' )+ { setChannel(HIDDEN); };
lexer grammar MaslLexer; //============================================================================================================== //============================================================================================================== // // Lexer // //============================================================================================================== //============================================================================================================== // Logical Operators AND : 'and'; OR : 'or'; XOR : 'xor'; // Unary and Additive Operators (Keep in this order to // improve efficiency so unary and additive can be looked // for as ranges) ABS : 'abs'; NOT : 'not'; PLUS : '+'; MINUS : '-'; CONCATENATE : '&'; UNION : 'union'; NOT_IN : 'not_in'; // Multiplicactive Operators DIVIDE : '/'; TIMES : '*'; INTERSECTION : 'intersection'; MOD : 'mod'; POWER : '**'; REM : 'rem'; DISUNION : 'disunion'; // Equality Operators EQUAL : '='; NOT_EQUAL : '/='; // Comparison Operators GT : '>'; GTE : '>='; LT : '<'; LTE : '<='; // Stream Operators STREAM_LINE_IN : '>>>'; STREAM_LINE_OUT : '<<<'; STREAM_IN : '>>'; STREAM_OUT : '<<'; // Special characters ASSIGN : ':='; COLON : ':'; COMMA : ','; DOT : '.'; LTGT : '<>'; PRIME : '\''; RANGE_DOTS : '..'; LPAREN : '('; RPAREN : ')'; LBRACKET : '['; RBRACKET : ']'; SCOPE : '::'; SEMI : ';'; GOES_TO : '=>'; NAVIGATE : '->'; TERMINATOR_SCOPE : '~>'; CASE_OR : '|'; // Keywords ARRAY : 'array'; ANONYMOUS : 'anonymous'; ASSIGNER : 'assigner'; AT : 'at'; BAG : 'bag'; BEGIN : 'begin'; CANNOT_HAPPEN : 'Cannot_Happen' | 'cannot_happen'; CANCEL : 'cancel'; CASE : 'case'; CONDITIONALLY : 'conditionally'; CONSOLE : 'console'; CREATE : 'create'; CREATION : 'creation'; CURRENT_STATE : 'Current_State' /* | 'current_state' */; DECLARE : 'declare'; DEFERRED : 'deferred'; DELAY : 'delay'; DELETE : 'delete'; DELTA : 'delta'; DICTIONARY : 'dictionary'; DIGITS : 'digits'; DOMAIN : 'domain'; ELSE : 'else'; ELSIF : 'elsif'; END : 'end'; ENUM : 'enum'; ERASE : 'erase'; EVENT : 'event'; EXCEPTION : 'exception'; EXIT : 'exit'; FIND : 'find' | 'find_all'; FIND_ONE : 'find_one'; FIND_ONLY : 'find_only'; FOR : 'for'; GENERATE : 'generate'; IDENTIFIER : 'identifier'; IF : 'if'; IGNORE : 'Ignore' /* | 'ignore' */; IN : 'in'; INSTANCE : 'instance'; IS_A : 'is_a'; IS : 'is'; LINK : 'link'; LOOP : 'loop'; MANY : 'many'; NON_EXISTENT : 'Non_Existent' | 'Non_Existant' | 'non_existent'; OBJECT : 'object'; OF : 'of'; ONE : 'one'; ORDERED_BY : 'ordered_by'; OTHERS : 'others'; OUT : 'out'; PRAGMA : 'pragma'; PREFERRED : 'preferred'; PRIVATE : 'private'; PROJECT : 'project'; PUBLIC : 'public'; RAISE : 'raise'; RANGE : 'range'; READONLY : 'readonly'; REFERENTIAL : 'referential'; RELATIONSHIP : 'relationship'; RETURN : 'return'; REVERSE : 'reverse'; REVERSE_ORDERED_BY : 'reverse_ordered_by'; SCHEDULE : 'schedule'; SEQUENCE : 'sequence'; SERVICE : 'service' | 'function'; SET : 'set'; START : 'start'; STATE : 'state'; STRUCTURE : 'structure'; TERMINAL : 'terminal'; TERMINATOR : 'terminator'; THEN : 'then'; THIS : 'this'; TO : 'to'; TRANSITION : 'transition'; TYPE : 'type' | 'subtype'; UNCONDITIONALLY : 'unconditionally'; UNIQUE : 'unique'; UNLINK : 'unlink'; USING : 'using'; WHEN : 'when'; WHILE : 'while'; WITH : 'with'; NULL : 'null'; FLUSH : 'flush'; ENDL : 'endl'; TRUE : 'true'; FALSE : 'false'; LINE_NO : '#LINE#' { setText("#LINE#"); }; FILE_NAME : '#FILE#' { setText("#FILE#"); }; // Numeric Literals IntegerLiteral : Digit Digit? '#' BasedDigit+ | Digit+ ; RealLiteral : Digit+ ( ('.' Digit+) | UnbasedExponent ) | '.' Digit+ UnbasedExponent? | Digit Digit? '#' ( BasedDigit+ ( ('.' BasedDigit) | BasedExponent ) | '.' BasedDigit+ BasedExponent? ) ; fragment UnbasedExponent : ('e'|'E')('+'|'-')? Digit+ ; fragment BasedExponent : '#' ('+'|'-')? Digit+ ; fragment Digit : '0'..'9'; fragment BasedDigit : '0'..'9' | 'a'..'z' | 'A'..'Z'; fragment Letter : 'A'..'Z' | 'a'..'z'; // Character and String Literals DurationLiteral : '@P' ( ~('@' | ' ' | '\t' | '\f' | '\n' | '\r') )* '@' ; TimestampLiteral : '@' ( ~('@' | ' ' | '\t' | '\f' | '\n' | '\r') )* '@' ; CharacterLiteral : '\'' ( EscapeSequence | ~('\''|'\\') ) '\'' ; StringLiteral : '"' ( EscapeSequence | ~('\\'|'"') )* '"' ; fragment EscapeSequence : '\\' ('b'|'t'|'n'|'f'|'r'|'"'|'\''|'\\') | UnicodeEscape | OctalEscape ; fragment OctalEscape : '\\' ('0'..'3') ('0'..'7') ('0'..'7') | '\\' ('0'..'7') ('0'..'7') | '\\' ('0'..'7') ; fragment UnicodeEscape : '\\' 'u' HexDigit HexDigit HexDigit HexDigit; fragment HexDigit : ('0'..'9'|'a'..'f'|'A'..'F') ; // identifiers RelationshipName : 'R' '1'..'9' Digit* ; Identifier : ( Letter | '_' ) ( Letter | Digit | '_' )*; Description : '//!' ~('\n'|'\r')* '\r'? '\n'; Comment : '//' ~('\n'|'\r')* '\r'? '\n' { setChannel(HIDDEN); }; Whitespace : (' ' | '\t' | '\f' | '\n' | '\r' )+ { setChannel(HIDDEN); };
fix issue with parsing real literals with multiple fraction digits
fix issue with parsing real literals with multiple fraction digits
ANTLR
apache-2.0
leviathan747/mc,cortlandstarrett/mc,leviathan747/mc,xtuml/mc,leviathan747/mc,cortlandstarrett/mc,cortlandstarrett/mc,leviathan747/mc,xtuml/mc,lwriemen/mc,lwriemen/mc,leviathan747/mc,lwriemen/mc,lwriemen/mc,cortlandstarrett/mc,xtuml/mc,xtuml/mc,xtuml/mc,xtuml/mc,cortlandstarrett/mc,lwriemen/mc,cortlandstarrett/mc,lwriemen/mc,leviathan747/mc
9840716871b4592d7b7fbb8445cf079ac899086f
src/main/antlr4/org/morphling/tuberbasic/TuberBasic.g4
src/main/antlr4/org/morphling/tuberbasic/TuberBasic.g4
grammar TuberBasic; /* c.f. https://github.com/antlr/grammars-v4/ */ basicfile : statements ; statements : statement ('\n' statement)* ; statement : print | end ; print : 'PRINT' formatstring=stringLiteral (expression)* ; end : 'END' ; expression : numberLiteral | stringLiteral ; numberLiteral : NumberLiteral ; stringLiteral : StringLiteral ; NumberLiteral : '-'?('0'..'9')+ ; StringLiteral : '"' ( ESC_SEQ | ~('\\'|'"') )* '"' ; WS : ( ' ' | '\t' | '\n' | '\r' ) -> channel(HIDDEN) ; 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'..'9'|'a'..'f'|'A'..'F') ;
grammar TuberBasic; /* c.f. https://github.com/antlr/grammars-v4/ */ basicfile : statements ; statements : statement ('\n' statement)* ; statement : print | end | fornext | cond ; fornext : 'FOR' variable 'FROM' expression 'TO' expression '\n' statements '\n' 'NEXT' ; cond : 'COND' ('\n' 'TEST' expression '\n' statements)+ 'DNOC' ; print : 'PRINT' formatstring=stringLiteral (expression)* ; end : 'END' ; expression : numberLiteral | stringLiteral | booleanLiteral | variable | expression '=' expression | expression 'AND' expression | twoaryfunction '(' expression ',' expression ')' ; twoaryfunction : 'mod' ; booleanLiteral : 'TRUE' | 'FALSE' ; numberLiteral : NumberLiteral ; stringLiteral : StringLiteral ; variable : Variable ; Variable : ('a'..'z')('a'..'z'|'A'..'Z'|'_'|'0'..'9')* ; NumberLiteral : '-'?('0'..'9')+ ; StringLiteral : '"' ( ESC_SEQ | ~('\\'|'"') )* '"' ; WS : ( ' ' | '\t' | '\n' | '\r' ) -> channel(HIDDEN) ; 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'..'9'|'a'..'f'|'A'..'F') ;
Extend grammar to hopefully be able to parse the Fizz Buzz program.
Extend grammar to hopefully be able to parse the Fizz Buzz program.
ANTLR
mit
fehrenbach/tuber-basic
8eae1ccae4cb76b5bdfb12e429ccc54316062f27
turin-parser/src/main/antlr4/me/tomassetti/parser/antlr/TurinParser.g4
turin-parser/src/main/antlr4/me/tomassetti/parser/antlr/TurinParser.g4
parser grammar TurinParser; options { tokenVocab = TurinLexer; } @header { } turinFile: namespace=namespaceDecl nls (imports+=importDeclaration)* (members+=fileMember)* EOF; // Base nls: NL+; qualifiedId: (parts+=ID POINT)* parts+=ID; // Namespace namespaceDecl: NAMESPACE_KW name=qualifiedId; // Imports importDeclaration: typeImportDeclaration | singleFieldImportDeclaration | allFieldsImportDeclaration | allPackageImportDeclaration; typeImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TID (AS_KW alternativeName=TID)? nls ; singleFieldImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TID POINT fieldName=qualifiedId (AS_KW alternativeName=ID)? nls; allFieldsImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TID POINT ASTERISK nls; allPackageImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT ASTERISK nls; // typeUsage: ref=TID | arrayBase=typeUsage LSQUARE RSQUARE | primitiveType = PRIMITIVE_TYPE | basicType = BASIC_TYPE; commaNl: COMMA NL?; // method definition methodDefinition: type=returnType name=ID LPAREN (params+=formalParam (commaNl params+=formalParam)*)? RPAREN methodBody; returnType: isVoid=VOID_KW | type=typeUsage; methodBody: ASSIGNMENT value=expression nls | LBRACKET nls (statements += statement)* RBRACKET nls; // topLevelPropertyDeclaration: PROPERTY_KW type=typeUsage COLON name=ID nls; inTypePropertyDeclaration: HAS_KW type=typeUsage COLON name=ID nls; propertyReference: HAS_KW name=ID nls; typeMember: inTypePropertyDeclaration | propertyReference | methodDefinition; typeDeclaration: TYPE_KW name=TID LBRACKET nls (typeMembers += typeMember)* RBRACKET nls; // actualParam: expression | name=ID ASSIGNMENT expression; parenExpression: LPAREN internal=expression RPAREN; basicExpression: booleanLiteral | stringLiteral | intLiteral | interpolatedStringLiteral | valueReference | parenExpression; booleanLiteral: negative=FALSE_KW | positive=TRUE_KW; relOperator: EQUAL | DIFFERENT | LESSEQ | LESS | MOREEQ | MORE; expression: invokation | creation | basicExpression | fieldAccess | staticFieldReference | left=expression mathOperator=ASTERISK right=expression | left=expression mathOperator=SLASH right=expression | left=expression mathOperator=PLUS right=expression | left=expression mathOperator=MINUS right=expression | left=expression boolOperator=AND right=expression | left=expression boolOperator=OR right=expression | left=expression relOp=relOperator right=expression | not=NOT expression ; invokation: function=basicExpression LPAREN (params+=actualParam (commaNl params+=actualParam)*)? RPAREN ; fieldAccess: subject=basicExpression POINT name=ID; staticFieldReference: typeReference POINT name=ID; valueReference: name=ID; typeReference: (packag=qualifiedId)? POINT name=TID; stringLiteral: STRING_START (content=STRING_CONTENT)? STRING_STOP; interpolatedStringLiteral: STRING_START (elements+=stringElement)+ STRING_STOP; stringElement: STRING_CONTENT | stringInterpolationElement; stringInterpolationElement: INTERPOLATION_START value=expression INTERPOLATION_END; intLiteral: INT; creation: (pakage=qualifiedId POINT)? name=TID LPAREN (params+=actualParam (commaNl params+=actualParam)*)? RPAREN ; varDecl : VAL_KW (type=typeUsage)? name=ID ASSIGNMENT value=expression nls; expressionStmt: expression nls; returnStmt: RETURN_KW value=expression nls; statement : varDecl | expressionStmt | returnStmt; // formalParam : type=typeUsage name=ID; // program: PROGRAM_KW name=TID LPAREN params+=formalParam (commaNl params+=formalParam)* RPAREN LBRACKET nls (statements += statement)* RBRACKET nls; // fileMember: topLevelPropertyDeclaration | typeDeclaration | program;
parser grammar TurinParser; options { tokenVocab = TurinLexer; } @header { } turinFile: namespace=namespaceDecl nls (imports+=importDeclaration)* (members+=fileMember)* EOF; // Base nls: NL+; qualifiedId: (parts+=ID POINT)* parts+=ID; // Namespace namespaceDecl: NAMESPACE_KW name=qualifiedId; // Imports importDeclaration: typeImportDeclaration | singleFieldImportDeclaration | allFieldsImportDeclaration | allPackageImportDeclaration; typeImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TID (AS_KW alternativeName=TID)? nls ; singleFieldImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TID POINT fieldName=qualifiedId (AS_KW alternativeName=ID)? nls; allFieldsImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT typeName=TID POINT ASTERISK nls; allPackageImportDeclaration: IMPORT_KW packagePart=qualifiedId POINT ASTERISK nls; // typeUsage: ref=TID | arrayBase=typeUsage LSQUARE RSQUARE | primitiveType = PRIMITIVE_TYPE | basicType = BASIC_TYPE; commaNl: COMMA NL?; // method definition methodDefinition: type=returnType name=ID LPAREN (params+=formalParam (commaNl params+=formalParam)*)? RPAREN methodBody; returnType: isVoid=VOID_KW | type=typeUsage; methodBody: ASSIGNMENT value=expression nls | LBRACKET nls (statements += statement)* RBRACKET nls; // topLevelPropertyDeclaration: PROPERTY_KW type=typeUsage COLON name=ID nls; inTypePropertyDeclaration: HAS_KW type=typeUsage COLON name=ID nls; propertyReference: HAS_KW name=ID nls; typeMember: inTypePropertyDeclaration | propertyReference | methodDefinition; typeDeclaration: TYPE_KW name=TID LBRACKET nls (typeMembers += typeMember)* RBRACKET nls; // actualParam: expression | name=ID ASSIGNMENT expression; parenExpression: LPAREN internal=expression RPAREN; basicExpression: booleanLiteral | stringLiteral | intLiteral | interpolatedStringLiteral | valueReference | parenExpression; booleanLiteral: negative=FALSE_KW | positive=TRUE_KW; relOperator: EQUAL | DIFFERENT | LESSEQ | LESS | MOREEQ | MORE; expression: invokation | creation | basicExpression | fieldAccess | staticFieldReference | left=expression mathOperator=ASTERISK right=expression | left=expression mathOperator=SLASH right=expression | left=expression mathOperator=PLUS right=expression | left=expression mathOperator=MINUS right=expression | left=expression boolOperator=AND_KW right=expression | left=expression boolOperator=OR_KW right=expression | left=expression relOp=relOperator right=expression | not=NOT_KW expression ; invokation: function=basicExpression LPAREN (params+=actualParam (commaNl params+=actualParam)*)? RPAREN ; fieldAccess: subject=basicExpression POINT name=ID; staticFieldReference: typeReference POINT name=ID; valueReference: name=ID; typeReference: (packag=qualifiedId)? POINT name=TID; stringLiteral: STRING_START (content=STRING_CONTENT)? STRING_STOP; interpolatedStringLiteral: STRING_START (elements+=stringElement)+ STRING_STOP; stringElement: STRING_CONTENT | stringInterpolationElement; stringInterpolationElement: INTERPOLATION_START value=expression INTERPOLATION_END; intLiteral: INT; creation: (pakage=qualifiedId POINT)? name=TID LPAREN (params+=actualParam (commaNl params+=actualParam)*)? RPAREN ; varDecl : VAL_KW (type=typeUsage)? name=ID ASSIGNMENT value=expression nls; expressionStmt: expression nls; returnStmt: RETURN_KW value=expression nls; statement : varDecl | expressionStmt | returnStmt; // formalParam : type=typeUsage name=ID; // program: PROGRAM_KW name=TID LPAREN params+=formalParam (commaNl params+=formalParam)* RPAREN LBRACKET nls (statements += statement)* RBRACKET nls; // fileMember: topLevelPropertyDeclaration | typeDeclaration | program;
correct parser
correct parser
ANTLR
apache-2.0
ftomassetti/turin-programming-language,ftomassetti/turin-programming-language
a6242f91da62d4ad3113a56012a6d4943dfa437d
sharding-core/src/main/antlr4/imports/SQLServerKeyword.g4
sharding-core/src/main/antlr4/imports/SQLServerKeyword.g4
lexer grammar SQLServerKeyword; import Symbol; ABORT_AFTER_WAIT : A B O R T UL_ A F T E R UL_ W A I T ; ACTION : A C T I O N ; 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 ; AUTO : A U T O ; BEGIN : B E G I N ; BLOCKERS : B L O C K E R S ; BUCKET_COUNT : B U C K E T UL_ C O U N T ; CAST : C A S T ; CLUSTERED : C L U S T E R E D ; COLLATE : C O L L A T E ; 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 ; CONVERT : C O N V E R T ; CURRENT : C U R R E N T ; DATABASE : D A T A B A S E ; DATABASE_DEAULT : D A T A B A S E UL_ D E A U L 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 ; DAY : D A Y ; DAYS : D A Y S ; DELAYED_DURABILITY : D E L A Y E D UL_ D U R A B I L I T Y ; DETERMINISTIC : D E T E R M I N I S T I C ; DISTRIBUTION : D I S T R I B U T I O N ; DOCUMENT : D O C U M E N T ; DROP_EXISTING : D R O P UL_ E X I S T I N G ; DURABILITY : D U R A B I L I T Y ; DW : D W ; 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 ; END : E N D ; 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 : F I L E T A B L E ; 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 ; FILLFACTOR : F I L L F A C T O R ; FILTER_PREDICATE : F I L T E R UL_ P R E D I C A T E ; FOLLOWING : F O L L O W I N G ; FOR : F O R ; FUNCTION : F U N C T I O N ; GRANT : G R A N T ; HASH : H A S H ; HEAP : H E A P ; HIDDEN_ : H I D D E N UL_ ; 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 ; HISTORY_TABLE : H I S T O R Y UL_ T A B L E ; IDENTITY : I D E N T I T Y ; 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 ; INFINITE : I N F I N I T E ; LEFT : L E F T ; LEFT_BRACKET : L E F T UL_ B R A C K E T ; LOCK_ESCALATION : L O C K UL_ E S C A L A T I O N ; LOGIN : L O G I N ; MARK : M A R K ; MASKED : M A S K E D ; MAX : M A X ; MAXDOP : M A X D O P ; MAX_DURATION : M A X UL_ D U R A T I O N ; 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 ; MINUTES : M I N U T E S ; MONTH : M O N T H ; MONTHS : M O N T H S ; MOVE : M O V E ; NOCHECK : N O C H E C K ; NONCLUSTERED : N O N C L U S T E R E D ; NONE : N O N E ; OBJECT : O B J E C T ; OFF : O F F ; ONLINE : O N L I N E ; OPTION : O P T I O N ; OUTBOUND : O U T B O U N D ; OVER : O V E R ; 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 ; PRECEDING : P R E C E D I N G ; PRIVILEGES : P R I V I L E G E S ; RANDOMIZED : R A N D O M I Z E D ; RANGE : R A N G E ; REBUILD : R E B U I L D ; REMOTE_DATA_ARCHIVE : R E M O T E UL_ D A T A UL_ A R C H I V E ; REPEATABLE : R E P E A T A B L E ; REPLICATE : R E P L I C A T E ; REPLICATION : R E P L I C A T I O N ; RESUMABLE : R E S U M A B L E ; RIGHT : R I G H T ; RIGHT_BRACKET : R I G H T UL_ B R A C K E T ; ROLE : R O L E ; ROUND_ROBIN : R O U N D UL_ R O B I N ; ROWGUIDCOL : R O W G U I D C O L ; ROWS : R O W S ; SAVE : S A V E ; SCHEMA : S C H E M A ; 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 ; SELF : S E L F ; SNAPSHOT : S N A P S H O T ; SORT_IN_TEMPDB : S O R T UL_ I N UL_ T E M P D B ; SPARSE : S P A R S E ; 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 ; SWITCH : S W I T C H ; 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 ; TRAN : T R A N ; TRIGGER : T R I G G E R ; UNBOUNDED : U N B O U N D E D ; UNCOMMITTED : U N C O M M I T T E D ; UPDATE : U P D A T E ; USER : U S E R ; VALUES : V A L U E S ; 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 ; YEARS : Y E A R S ; ZONE : Z O N E ;
lexer grammar SQLServerKeyword; import Symbol; ABORT_AFTER_WAIT : A B O R T UL_ A F T E R UL_ W A I T ; ACTION : A C T I O N ; 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 ; AUTO : A U T O ; BEGIN : B E G I N ; BLOCKERS : B L O C K E R S ; BUCKET_COUNT : B U C K E T UL_ C O U N T ; CAST : C A S T ; CLUSTERED : C L U S T E R E D ; COLLATE : C O L L A T E ; 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 ; CONVERT : C O N V E R T ; DATABASE : D A T A B A S E ; DATABASE_DEAULT : D A T A B A S E UL_ D E A U L 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 ; DAYS : D A Y S ; DELAYED_DURABILITY : D E L A Y E D UL_ D U R A B I L I T Y ; DETERMINISTIC : D E T E R M I N I S T I C ; DISTRIBUTION : D I S T R I B U T I O N ; DOCUMENT : D O C U M E N T ; DROP_EXISTING : D R O P UL_ E X I S T I N G ; DURABILITY : D U R A B I L I T Y ; DW : D W ; 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 ; END : E N D ; 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 : F I L E T A B L E ; 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 ; FILLFACTOR : F I L L F A C T O R ; FILTER_PREDICATE : F I L T E R UL_ P R E D I C A T E ; FOLLOWING : F O L L O W I N G ; FOR : F O R ; FUNCTION : F U N C T I O N ; GRANT : G R A N T ; HASH : H A S H ; HEAP : H E A P ; HIDDEN_ : H I D D E N UL_ ; 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 ; HISTORY_TABLE : H I S T O R Y UL_ T A B L E ; IDENTITY : I D E N T I T Y ; 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 ; INFINITE : I N F I N I T E ; LEFT : L E F T ; LEFT_BRACKET : L E F T UL_ B R A C K E T ; LOCK_ESCALATION : L O C K UL_ E S C A L A T I O N ; LOGIN : L O G I N ; MARK : M A R K ; MASKED : M A S K E D ; MAX : M A X ; MAXDOP : M A X D O P ; MAX_DURATION : M A X UL_ D U R A T I O N ; 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 ; MINUTES : M I N U T E S ; MONTH : M O N T H ; MONTHS : M O N T H S ; MOVE : M O V E ; NOCHECK : N O C H E C K ; NONCLUSTERED : N O N C L U S T E R E D ; NONE : N O N E ; OBJECT : O B J E C T ; OFF : O F F ; ONLINE : O N L I N E ; OPTION : O P T I O N ; OUTBOUND : O U T B O U N D ; OVER : O V E R ; 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 ; PRECEDING : P R E C E D I N G ; PRIVILEGES : P R I V I L E G E S ; RANDOMIZED : R A N D O M I Z E D ; RANGE : R A N G E ; REBUILD : R E B U I L D ; REMOTE_DATA_ARCHIVE : R E M O T E UL_ D A T A UL_ A R C H I V E ; REPEATABLE : R E P E A T A B L E ; REPLICATE : R E P L I C A T E ; REPLICATION : R E P L I C A T I O N ; RESUMABLE : R E S U M A B L E ; RIGHT : R I G H T ; RIGHT_BRACKET : R I G H T UL_ B R A C K E T ; ROLE : R O L E ; ROUND_ROBIN : R O U N D UL_ R O B I N ; ROWGUIDCOL : R O W G U I D C O L ; ROWS : R O W S ; SAVE : S A V E ; SCHEMA : S C H E M A ; 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 ; SELF : S E L F ; SNAPSHOT : S N A P S H O T ; SORT_IN_TEMPDB : S O R T UL_ I N UL_ T E M P D B ; SPARSE : S P A R S E ; 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 ; SWITCH : S W I T C H ; 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 ; TRAN : T R A N ; TRIGGER : T R I G G E R ; UNBOUNDED : U N B O U N D E D ; UNCOMMITTED : U N C O M M I T T E D ; UPDATE : U P D A T E ; VALUES : V A L U E S ; 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 ; YEARS : Y E A R S ; ZONE : Z O N E ;
remove common keyword
remove common keyword
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
2d17610c9b4b4546296698ee1f1d156a9a494138
prolog.g4
prolog.g4
/* BSD License Copyright (c) 2013, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar prolog; program : clauselist query? EOF ; clauselist : clause* ; clause : (predicate '.') | (predicate ':-') (predicatelist '.') ; predicatelist : predicate (',' predicate)* ; predicate : atom | atom '(' termlist ')' ; termlist : term ( ',' term )* ; term : VARIABLE | atom | integer | FLOAT | structure ; structure : atom '(' termlist ')' ; query : '?-' predicatelist '.' ; atom : '[' ']' | '{' '}' | SMALLATOM | GRAPHIC_TOKEN | QUOTED_TOKEN | '\'' STRING '\'' //FIXME escapes in strings | '"' STRING '"' | '`' STRING '`' | ';' | '!' ; integer : DECIMAL | BINARY | OCTAL | HEX ; // Lexer SMALLATOM : LCLETTER CHARACTER* ; VARIABLE : UCLETTER CHARACTER* ; DECIMAL: DIGIT+ ; BINARY: [01]+ ; OCTAL: [0-7]+ ; HEX: [0-9a-fA-F]+ ; FLOAT : DECIMAL '.' [0-9]+ ( [eE] [+-] DECIMAL )? ; fragment CHARACTER : LCLETTER | UCLETTER | DIGIT | SPECIAL ; GRAPHIC_TOKEN: GRAPHIC | '\\' ; fragment GRAPHIC: [#$&*+-./:<=>?@^~] ; // 6.5.1 graphic char QUOTED_TOKEN: NON_QUOTE_CHAR | '\'\'' | '"' | '`' ; fragment NON_QUOTE_CHAR // 6.4.2.1 : GRAPHIC | LCLETTER | UCLETTER // == alphanumeric char 6.5.2 // the others partly duplicate stuff, like allowing single space ; fragment SPECIAL : '+' | '-' | '*' | '/' | '\\' | '^' | '~' | ':' | '.' | '?' | '#' | '$' | '&' ; STRING : CHARACTER+ ; fragment LCLETTER : [a-z_]; fragment UCLETTER : [A-Z]; fragment DIGIT : [0-9]; WS : [ \t\r\n]+ -> skip ; COMMENT: '%' ~[\n\r]* ( [\n\r] | EOF) -> channel(HIDDEN) ; MULTILINE_COMMENT: '/*' ( MULTILINE_COMMENT | . )*? ('*/' | EOF) -> channel(HIDDEN);
/* BSD License Copyright (c) 2013, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ grammar prolog; program : term* query? EOF ; query : '?-' termlist '.' ; clause : term ':-' termlist '.' # rule | term '.' # fact ; termlist : term ( ',' term )* //XXX: resolve different meanings of , and implement their precedence ; term : VARIABLE # variable | '(' term ')' # braced_term | integer # integer_term | FLOAT # float // structure / compound term | atom '(' termlist ')' # compound_term | term operator term # binary_operator | operator term # unary_operator | '[' termlist ( '|' term )? ']' # list_term //TODO: priority <= 999 //TODO: find out what [|] list syntax means | '{' termlist '}' # curly_bracketed_term | atom # atom_term ; operator //TODO: modifying operator table : ':-' | '-->' | '?-' | ';' | '->' | ',' | '\\+' | '=' | '\\=' | '==' | '\\==' | '@<' | '@=<' | '@>' | '@>=' | '=..' | 'is' | '=:=' | '=\\=' | '<' | '=<' | '>' | '>=' | '+' | '-' | '/\\' | '\\/' | '*' | '/' | '//' | 'rem' | 'mod' | '<<' | '>>' | '**' | '^' | '\\' ; atom : '[' ']' # empty_list | '{' '}' # empty_braces | SMALLATOM # name | GRAPHIC_TOKEN # graphic | QUOTED_TOKEN # quoted | '\'' STRING '\'' # quoted_string //FIXME escapes in strings | '"' STRING '"' # dq_string | '`' STRING '`' # backq_string | ';' # semicolon | '!' # cut ; integer : DECIMAL | BINARY | OCTAL | HEX ; // Lexer SMALLATOM : LCLETTER CHARACTER* ; VARIABLE : UCLETTER CHARACTER* | '_' CHARACTER+ ; DECIMAL: DIGIT+ ; BINARY: [01]+ ; OCTAL: [0-7]+ ; HEX: [0-9a-fA-F]+ ; FLOAT : DECIMAL '.' [0-9]+ ( [eE] [+-] DECIMAL )? ; fragment CHARACTER : LCLETTER | UCLETTER | DIGIT | SPECIAL ; GRAPHIC_TOKEN: (GRAPHIC | '\\')+ ; fragment GRAPHIC: [#$&*+-./:<=>?@^~] ; // 6.5.1 graphic char QUOTED_TOKEN: NON_QUOTE_CHAR | '\'\'' | '"' | '`' ; fragment NON_QUOTE_CHAR // 6.4.2.1 : GRAPHIC | LCLETTER | UCLETTER // == alphanumeric char 6.5.2 // the others partly duplicate stuff, like allowing single space ; fragment SPECIAL : '+' | '-' | '*' | '/' | '\\' | '^' | '~' | ':' | '.' | '?' | '#' | '$' | '&' ; STRING : CHARACTER+ ; fragment LCLETTER : [a-z_]; fragment UCLETTER : [A-Z]; fragment DIGIT : [0-9]; WS : [ \t\r\n]+ -> skip ; COMMENT: '%' ~[\n\r]* ( [\n\r] | EOF) -> channel(HIDDEN) ; MULTILINE_COMMENT: '/*' ( MULTILINE_COMMENT | . )*? ('*/' | EOF) -> channel(HIDDEN);
implement operators, try to fix term/clause ambiguity
implement operators, try to fix term/clause ambiguity
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
7512032bc710b2deb0e5845f7c3c32ad5975859a
sharding-core/src/main/antlr4/imports/PostgreSQLDCLStatement.g4
sharding-core/src/main/antlr4/imports/PostgreSQLDCLStatement.g4
grammar PostgreSQLDCLStatement; import PostgreSQLKeyword, Keyword, BaseRule, DataType, Symbol; createUser : CREATE USER roleName (WITH? roleOptions)? ; roleOption : SUPERUSER | NOSUPERUSER | CREATEDB | NOCREATEDB | CREATEROLE | NOCREATEROLE | INHERIT | NOINHERIT | LOGIN | NOLOGIN | REPLICATION | NOREPLICATION | BYPASSRLS | NOBYPASSRLS | CONNECTION LIMIT NUMBER | ENCRYPTED? PASSWORD STRING | VALID UNTIL STRING | IN ROLE roleNames | IN GROUP roleNames | ROLE roleNames | ADMIN roleNames | USER roleNames | SYSID STRING ; roleOptions : roleOption (COMMA roleOption)* ; alterUser : ALTER USER roleSpecification WITH roleOptions ; roleSpecification : roleName | CURRENT_USER | SESSION_USER ; renameUser : ALTER USER roleName RENAME TO roleName ; alterUserSetConfig : ALTER USER (roleSpecification | ALL) (IN DATABASE databaseName)? SET STRING ((TO | EQ) (STRING | ID | NUMBER | DEFAULT) | FROM CURRENT) ; alterUserResetConfig : ALTER USER (roleSpecification | ALL) (IN DATABASE databaseName)? RESET (STRING | ALL) ; dropUser : DROP USER (IF EXISTS)? roleNames ; createRole : CREATE ROLE roleName (WITH? roleOptions)? ; alterRole : ALTER ROLE roleSpecification WITH roleOptions ; renameRole : ALTER ROLE roleName RENAME TO roleName ; alterRoleSetConfig : ALTER ROLE (roleSpecification | ALL) (IN DATABASE databaseName)? SET STRING ((TO | EQ) (STRING | ID | NUMBER | DEFAULT) | FROM CURRENT) ; alterRoleResetConfig : ALTER ROLE (roleSpecification | ALL) (IN DATABASE databaseName)? RESET (STRING | ALL) ;
grammar PostgreSQLDCLStatement; import PostgreSQLKeyword, Keyword, BaseRule, DataType, Symbol; createUser : CREATE USER roleName (WITH? roleOptions)? ; roleOption : SUPERUSER | NOSUPERUSER | CREATEDB | NOCREATEDB | CREATEROLE | NOCREATEROLE | INHERIT | NOINHERIT | LOGIN | NOLOGIN | REPLICATION | NOREPLICATION | BYPASSRLS | NOBYPASSRLS | CONNECTION LIMIT NUMBER | ENCRYPTED? PASSWORD STRING | VALID UNTIL STRING | IN ROLE roleNames | IN GROUP roleNames | ROLE roleNames | ADMIN roleNames | USER roleNames | SYSID STRING ; roleOptions : roleOption (COMMA roleOption)* ; alterUser : ALTER USER roleSpecification WITH roleOptions ; roleSpecification : roleName | CURRENT_USER | SESSION_USER ; renameUser : ALTER USER roleName RENAME TO roleName ; alterUserSetConfig : ALTER USER (roleSpecification | ALL) (IN DATABASE databaseName)? SET STRING ((TO | EQ) (STRING | ID | NUMBER | DEFAULT) | FROM CURRENT) ; alterUserResetConfig : ALTER USER (roleSpecification | ALL) (IN DATABASE databaseName)? RESET (STRING | ALL) ; dropUser : DROP USER (IF EXISTS)? roleNames ; createRole : CREATE ROLE roleName (WITH? roleOptions)? ; alterRole : ALTER ROLE roleSpecification WITH roleOptions ; renameRole : ALTER ROLE roleName RENAME TO roleName ; alterRoleSetConfig : ALTER ROLE (roleSpecification | ALL) (IN DATABASE databaseName)? SET STRING ((TO | EQ) (STRING | ID | NUMBER | DEFAULT) | FROM CURRENT) ; alterRoleResetConfig : ALTER ROLE (roleSpecification | ALL) (IN DATABASE databaseName)? RESET (STRING | ALL) ; dropRole : DROP ROLE (IF EXISTS)? roleNames ;
add postgre drop role rule
add postgre drop role rule
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
350ca0487d343053827f34564069b6c6df8608bc
src/main/antlr/ActionLanguage.g4
src/main/antlr/ActionLanguage.g4
grammar ActionLanguage; ACS: 'ACS'; AFTER: 'after'; ALWAYS: 'always'; AT: 'at'; CAUSES: 'causes'; EVER: 'ever'; GENERALLY: 'generally'; IF: 'if'; IMPOSSIBLE: 'imnposible'; INITIALLY: 'initially'; INVOKES: 'invokes'; INVOLVED: 'involved'; NOT: 'not'; OBS: 'OBS'; PERFORMED: 'perfomed'; RELEASES: 'releases'; TRIGGERS: 'triggers'; TYPICALLY: 'typically'; WHEN: 'when'; typicallyCauses: TYPICALLY causes; typicallyInvokes: TYPICALLY invokes; typicallyReleases: TYPICALLY releases; typicallyTriggers: TYPICALLY triggers; initiallisation: INITIALLY fluentsList; causes: action CAUSES fluentsList underCondition; invokes: action INVOKES action afterTime underCondition; releases: action RELEASES fluentsList afterTime underCondition; triggers: fluentsList TRIGGERS action; impossible: IMPOSSIBLE action AT time underCondition; always: ALWAYS fluent; underCondition: IF fluentsList | ; afterTime: AFTER time | ; action: actor task; fluentsList: fluent | fluentsList ',' fluent; scenario: id '{' actions ',' observations '}'; actions: ACS '=' '{' eventsList '}'; eventsList: event | eventsList ',' event; event: '(' action ',' time ')'; observations: '{' observationsList '}'; observationsList: observation | observationsList ',' observation; observation: '(' fluent ',' time ')'; query : question fluent AT time WHEN scenarioId | question PERFORMED action AT time WHEN scenarioId | basicQuestion INVOLVED actor WHEN scenarioId ; question : basicQuestion | 'generally' ; basicQuestion : 'always' | 'ever' ; fluent: id | NOT id; actor: id; task: id; time: DecimalConstant; scenarioId: id; id: Nondigit+; fragment Nondigit: [a-zA-Z_]; fragment DecimalConstant: NonzeroDigit Digit*; fragment NonzeroDigit: [1-9]; fragment Digit: [0-9];
grammar ActionLanguage; ACS: 'ACS'; AFTER: 'after'; ALWAYS: 'always'; AT: 'at'; CAUSES: 'causes'; EVER: 'ever'; GENERALLY: 'generally'; IF: 'if'; IMPOSSIBLE: 'imnposible'; INITIALLY: 'initially'; INVOKES: 'invokes'; INVOLVED: 'involved'; NOT: 'not'; OBS: 'OBS'; PERFORMED: 'perfomed'; RELEASES: 'releases'; TRIGGERS: 'triggers'; TYPICALLY: 'typically'; WHEN: 'when'; programm: actionLanguage '\n' scenariosList '\n' queries; actionLanguage: initiallisation '\n' entriesList; entriesList: entry | entriesList '\n' entry; entry : causes | invokes | releases | triggers | TYPICALLY causes | TYPICALLY invokes | TYPICALLY releases | TYPICALLY triggers | impossible | always ; initiallisation: INITIALLY fluentsList; causes: action CAUSES fluentsList underCondition; invokes: action INVOKES action afterTime underCondition; releases: action RELEASES fluentsList afterTime underCondition; triggers: fluentsList TRIGGERS action; impossible: IMPOSSIBLE action AT time underCondition; always: ALWAYS fluent; underCondition: IF fluentsList | ; afterTime: AFTER time | ; action: actor task; fluentsList: fluent | fluentsList ',' fluent; scenariosList: scenario | scenariosList '\n' scenario; scenario: id '{' actions ',' observations '}'; actions: ACS '=' '{' eventsList '}'; eventsList: event | eventsList ',' event; event: '(' action ',' time ')'; observations: '{' observationsList '}'; observationsList: observation | observationsList ',' observation; observation: '(' fluent ',' time ')'; queries: query | queries '\n' query; query : question fluent AT time WHEN scenarioId | question PERFORMED action AT time WHEN scenarioId | basicQuestion INVOLVED actor WHEN scenarioId ; question : basicQuestion | 'generally' ; basicQuestion : 'always' | 'ever' ; fluent: id | NOT id; actor: id; task: id; time: DecimalConstant; scenarioId: id; id: Nondigit+; fragment Nondigit: [a-zA-Z_]; fragment DecimalConstant: NonzeroDigit Digit*; fragment NonzeroDigit: [1-9]; fragment Digit: [0-9];
Create whole language grammar
Create whole language grammar
ANTLR
isc
janisz/knowledge-representation,janisz/knowledge-representation
3ed9d6519c5838650157c6f3819949a7da36d363
VineScriptLib/Compiler/VineParser.g4
VineScriptLib/Compiler/VineParser.g4
parser grammar VineParser; /* // django syntax: https://docs.djangoproject.com/en/1.10/topics/templates/#the-django-template-language // django: // * var: {{ foo }} // * code: {% if foo %} // * comment: {# comment #} // detail: https://github.com/benjohnson/atom-django-templates/blob/master/grammars/html%20(django).cson grammar VineScript; script: sequence+ EOF; sequence: text | code | ; code: stmt | text ; // conditionStmt or controlStmt (control structure) stmt: conditionStmt | assign | print | stmt ';' | variable ; // {{ foo }} is equal to {% print foo %} // built-in filters: // * upper // * lower // * truncatechars:8 // * truncatewords:2 // * pluralize // * default:"nothing" // * length // * random // * stringformat:"#.0" // * yesno:"yeah,no,maybe" // ---- added by myself: ---- // * min // * max // built-in functions: // * ParseInt(string) // * ParseNumber(string) // * Range(int):[] // custom template tags // https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-tags // custom template filters : // https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-filters //{% autoescape off %} // {{ body }} // {% autoescape on %} // {{ foo }} // {% endautoescape %} //{% endautoescape %} // preformatted: (on by default) {% formatted on %} {% formatted off %} // or like html: {% pre on %} {% pre off %} // maybe: {% tab %} {% br %} '{%' 'set' ID ('='|'to') expr '%}' */ @members{ public enum EVineParseMode { FULL, EXPR } // by default, parse as a passage (full mode) public EVineParseMode ParseMode = EVineParseMode.FULL; private static readonly string errReservedChar = "'\u000B' (vertical tabulation) is a reserved character and is not allowed to be used!"; private static readonly string errVarDefReservedKw = "Can't use a reserved keyword as a variable name!"; private static readonly string errMissingSpaceBefore = "Missing space before "; private static readonly string errMissingSpaceAfter = "Missing space after "; } options { tokenVocab=VineLexer; } /* * Parser Rules */ passage : {ParseMode == EVineParseMode.EXPR}? evalExprMode NL? EOF // active only if we're expr parse mode | block* NL? EOF | { NotifyErrorListeners(errReservedChar); } RESERVED_CHARS //| { NotifyErrorListeners("Error char"); } ERROR_CHAR ; evalExprMode : expr ; // directOutput will add the text/code markups to the output. // The output will then be parsed by the formatter. block : NL # directOutput | text # directOutput // foobar | display # noOutput // {{ foo }} | controlStmt # noOutput // {% if true %} something {% endif %} | simpleStmtBlock # directOutput // {% set foo = 0 %} //| LINE_COMMENT | BLOCK_COMMENT # directOutput // {# comment #} ; text : TXT ; simpleStmtBlock : '{%' setStmt '%}' | '{%' funcCall '%}' ; /** * Display something in the text (variable, expression, function return, ...) **/ display : '{{' expr '}}' ; setStmt : 'set' assignList ; assignList : assign (',' assign)* | assignList { NotifyErrorListeners("Missing ',' separator"); } assign (',' assign)* | assignList { NotifyErrorListeners("Too many ','"); } ',' ',' assignList ; assign : variable (sequenceAccess)* op=('='|'to') expr | variable (sequenceAccess)* op=('+='|'-='|'*='|'/='|'%=') expr ; funcCall : ID '(' expressionList? ')' | ID '(' expressionList? ')' { NotifyErrorListeners("Too many parentheses"); } ')' | ID '(' expressionList? { NotifyErrorListeners("Missing closing ')'"); } ; newSequence : '[' expressionList? ']' # newArray | LBRACE keyValueList? RBRACE # newDict // array errors: | '[' expressionList? ']' { NotifyErrorListeners("Too many brackets"); } ']' # newArrayError | '[' expressionList? { NotifyErrorListeners("Missing closing ']'"); } # newArrayError // dict errors: | LBRACE keyValueList? RBRACE { NotifyErrorListeners("Too many braces"); } ']' # newDictError | LBRACE keyValueList? { NotifyErrorListeners("Missing closing '}'"); } # newDictError ; // if, elif, else, for, end controlStmt : ifStmt (elifStmt)* (elseStmt)? endIfStmt # ifCtrlStmt | forStmt endForStmt # forCtrlStmt ; ifStmt : '{%' 'if' wsa expr '%}' block* ; elifStmt : '{%' 'elif' wsa expr '%}' block* ; elseStmt : '{%' 'else' '%}' block* ; endIfStmt : '{%' 'endif' '%}' ; forStmt : '{%' 'for' wsa variable 'in' expr '%}' NL? block* //| '{%' 'for' wsa key=variable ',' val=variable 'in' expr '%}' NL? block* | '{%' 'for' wsa variable 'in' interval '%}' NL? block* ; endForStmt : '{%' 'endfor' '%}' ; expr : <assoc=right> left=expr '^' right=expr # powExpr | op=('-'|'!') expr # unaryExpr | left=expr op=('*' | '/' | '%') right=expr # mulDivModExpr | left=expr op=('+'|'-') right=expr # addSubExpr | left=expr op=('<'|'>'|'<='|'>=') right=expr # relationalExpr | left=expr op=('=='|'!=') right=expr # equalityExpr | left=expr ('&&'|wsb 'and' wsa) right=expr # andExpr | left=expr ('||'|wsb 'or' wsa) right=expr # orExpr | '(' expr ')' # parensExpr | newSequence # sequenceExpr | funcCall # funcCallExpr | atom # atomExpr | variable (sequenceAccess)* # varExpr ; expressionList : expr (',' expr)* | expr (',' { NotifyErrorListeners("Too many comma separators"); } ','+ expr)+ | expr (',' expr)* { NotifyErrorListeners("Too many comma separators"); } ',' ; keyValue : stringLiteral ':' expr | { NotifyErrorListeners("Invalid key value: it should look like this: '\"key\": value'"); } . ; keyValueList : keyValue (',' keyValue)* | keyValue (',' { NotifyErrorListeners("Too many comma separators"); } ','+ keyValue)+ | keyValue (',' keyValue)* { NotifyErrorListeners("Too many comma separators"); } ',' ; atom: INT # intAtom | FLOAT # floatAtom | (TRUE | FALSE) # boolAtom | stringLiteral # stringAtom | NULL # nullAtom ; stringLiteral : STRING | { NotifyErrorListeners(errReservedChar); } ILLEGAL_STRING ; // Variable access. The '$' prefix is optional variable : '$'? ID ('.' ID)* | { NotifyErrorListeners(errVarDefReservedKw); } reservedKeyword ; sequenceAccess : '[' expr ']' ; interval : left=expr '...' right=expr ; // Call to force whitespace. Kind of hacky? // If the current token is not a white space => error. // We use semantic predicates here because WS is in a different // channel and the parser can't access directly wsb // before : { if (_input.Get(_input.Index - 1).Type != WS) { string offendingSymbol = _input.Get(_input.Index - 1).Text; NotifyErrorListeners(errMissingSpaceBefore + "'" + offendingSymbol + "'"); } } ; wsa // after : { if (_input.Get(_input.Index - 1).Type != WS) { string offendingSymbol = _input.Get(_input.Index - 1).Text; NotifyErrorListeners(errMissingSpaceAfter + "'" + offendingSymbol + "'"); } } ; reservedKeyword : IF | ELIF | ELSE | ENDIF | KW_AND | KW_OR | TO | SET | TRUE | FALSE | NULL ; /* variable: ID # variableValue | variable Dot variable # combinedVariable // | ID[expr]+ ; postfixExpression : atom //should be ID (and maybe allow STRING too) | postfixExpression '[' expr ']' | postfixExpression '(' argumentExpressionList? ')' | postfixExpression '.' ID # attributeLookup | postfixExpression '++' | postfixExpression '--' ; */
parser grammar VineParser; /* // django syntax: https://docs.djangoproject.com/en/1.10/topics/templates/#the-django-template-language // django: // * var: {{ foo }} // * code: {% if foo %} // * comment: {# comment #} // detail: https://github.com/benjohnson/atom-django-templates/blob/master/grammars/html%20(django).cson grammar VineScript; script: sequence+ EOF; sequence: text | code | ; code: stmt | text ; // conditionStmt or controlStmt (control structure) stmt: conditionStmt | assign | print | stmt ';' | variable ; // {{ foo }} is equal to {% print foo %} // built-in filters: // * upper // * lower // * truncatechars:8 // * truncatewords:2 // * pluralize // * default:"nothing" // * length // * random // * stringformat:"#.0" // * yesno:"yeah,no,maybe" // ---- added by myself: ---- // * min // * max // built-in functions: // * ParseInt(string) // * ParseNumber(string) // * Range(int):[] // custom template tags // https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-tags // custom template filters : // https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-filters //{% autoescape off %} // {{ body }} // {% autoescape on %} // {{ foo }} // {% endautoescape %} //{% endautoescape %} // preformatted: (on by default) {% formatted on %} {% formatted off %} // or like html: {% pre on %} {% pre off %} // maybe: {% tab %} {% br %} '{%' 'set' ID ('='|'to') expr '%}' */ @members{ public enum EVineParseMode { FULL, EXPR } // by default, parse as a passage (full mode) public EVineParseMode ParseMode = EVineParseMode.FULL; private static readonly string errReservedChar = "'\u000B' (vertical tabulation) is a reserved character and is not allowed to be used!"; private static readonly string errVarDefReservedKw = "Can't use a reserved keyword as a variable name!"; private static readonly string errMissingSpaceBefore = "Missing space before "; private static readonly string errMissingSpaceAfter = "Missing space after "; } options { tokenVocab=VineLexer; } /* * Parser Rules */ passage : {ParseMode == EVineParseMode.EXPR}? evalExprMode NL? EOF // active only if we're expr parse mode | block* NL? EOF | { NotifyErrorListeners(errReservedChar); } RESERVED_CHARS //| { NotifyErrorListeners("Error char"); } ERROR_CHAR ; evalExprMode : expr ; // directOutput will add the text/code markups to the output. // The output will then be parsed by the formatter. block : NL # directOutput | text # directOutput // foobar | display # noOutput // {{ foo }} | controlStmt # noOutput // {% if true %} something {% endif %} | simpleStmtBlock # directOutput // {% set foo = 0 %} //| LINE_COMMENT | BLOCK_COMMENT # directOutput // {# comment #} ; text : TXT ; simpleStmtBlock : '{%' setStmt '%}' | '{%' funcCall '%}' ; /** * Display something in the text (variable, expression, function return, ...) **/ display : '{{' expr '}}' ; setStmt : 'set' assignList ; assignList : assign (',' assign)* | assignList { NotifyErrorListeners("Missing ',' separator"); } assign (',' assign)* | assignList { NotifyErrorListeners("Too many ','"); } ',' ',' assignList ; assign : variable (sequenceAccess)* op=('='|'to') expr | variable (sequenceAccess)* op=('+='|'-='|'*='|'/='|'%=') expr ; funcCall : ID '(' expressionList? ')' | ID '(' expressionList? ')' { NotifyErrorListeners("Too many parentheses"); } ')' | ID '(' expressionList? { NotifyErrorListeners("Missing closing ')'"); } ; newSequence : '[' expressionList? ']' # newArray | LBRACE keyValueList? RBRACE # newDict // array errors: | '[' expressionList? ']' { NotifyErrorListeners("Too many brackets"); } ']' # newArrayError | '[' expressionList? { NotifyErrorListeners("Missing closing ']'"); } # newArrayError // dict errors: | LBRACE keyValueList? RBRACE { NotifyErrorListeners("Too many braces"); } RBRACE # newDictError | LBRACE keyValueList? { NotifyErrorListeners("Missing closing '}'"); } # newDictError ; // if, elif, else, for, end controlStmt : ifStmt (elifStmt)* (elseStmt)? endIfStmt # ifCtrlStmt | forStmt endForStmt # forCtrlStmt ; ifStmt : '{%' 'if' wsa expr '%}' block* ; elifStmt : '{%' 'elif' wsa expr '%}' block* ; elseStmt : '{%' 'else' '%}' block* ; endIfStmt : '{%' 'endif' '%}' ; forStmt : '{%' 'for' wsa variable 'in' expr '%}' NL? block* //| '{%' 'for' wsa key=variable ',' val=variable 'in' expr '%}' NL? block* | '{%' 'for' wsa variable 'in' interval '%}' NL? block* ; endForStmt : '{%' 'endfor' '%}' ; expr : <assoc=right> left=expr '^' right=expr # powExpr | op=('-'|'!') expr # unaryExpr | left=expr op=('*' | '/' | '%') right=expr # mulDivModExpr | left=expr op=('+'|'-') right=expr # addSubExpr | left=expr op=('<'|'>'|'<='|'>=') right=expr # relationalExpr | left=expr op=('=='|'!=') right=expr # equalityExpr | left=expr ('&&'|wsb 'and' wsa) right=expr # andExpr | left=expr ('||'|wsb 'or' wsa) right=expr # orExpr | '(' expr ')' # parensExpr | newSequence # sequenceExpr | funcCall # funcCallExpr | atom # atomExpr | variable (sequenceAccess)* # varExpr ; expressionList : expr (',' expr)* | expr (',' { NotifyErrorListeners("Too many comma separators"); } ','+ expr)+ | expr (',' expr)* { NotifyErrorListeners("Too many comma separators"); } ',' ; keyValue : stringLiteral ':' expr | { NotifyErrorListeners("Invalid key value: it should look like this: '\"key\": value'"); } . ; keyValueList : keyValue (',' keyValue)* | keyValue (',' { NotifyErrorListeners("Too many comma separators"); } ','+ keyValue)+ | keyValue (',' keyValue)* { NotifyErrorListeners("Too many comma separators"); } ',' ; atom: INT # intAtom | FLOAT # floatAtom | (TRUE | FALSE) # boolAtom | stringLiteral # stringAtom | NULL # nullAtom ; stringLiteral : STRING | { NotifyErrorListeners(errReservedChar); } ILLEGAL_STRING ; // Variable access. The '$' prefix is optional variable : '$'? ID ('.' ID)* | { NotifyErrorListeners(errVarDefReservedKw); } reservedKeyword ; sequenceAccess : '[' expr ']' ; interval : left=expr '...' right=expr ; // Call to force whitespace. Kind of hacky? // If the current token is not a white space => error. // We use semantic predicates here because WS is in a different // channel and the parser can't access directly wsb // before : { if (_input.Get(_input.Index - 1).Type != WS) { string offendingSymbol = _input.Get(_input.Index - 1).Text; NotifyErrorListeners(errMissingSpaceBefore + "'" + offendingSymbol + "'"); } } ; wsa // after : { if (_input.Get(_input.Index - 1).Type != WS) { string offendingSymbol = _input.Get(_input.Index - 1).Text; NotifyErrorListeners(errMissingSpaceAfter + "'" + offendingSymbol + "'"); } } ; reservedKeyword : IF | ELIF | ELSE | ENDIF | KW_AND | KW_OR | TO | SET | TRUE | FALSE | NULL ; /* variable: ID # variableValue | variable Dot variable # combinedVariable // | ID[expr]+ ; postfixExpression : atom //should be ID (and maybe allow STRING too) | postfixExpression '[' expr ']' | postfixExpression '(' argumentExpressionList? ')' | postfixExpression '.' ID # attributeLookup | postfixExpression '++' | postfixExpression '--' ; */
fix catching error alternative for dictionnary creation
Grammar: fix catching error alternative for dictionnary creation
ANTLR
mit
julsam/VineScript
8f8e39c92d41938a5f9299476482c89157246324
g4/math.g4
g4/math.g4
grammar MathExcel; prog : expr+; expr: expr op=('*'|'/'|'%') expr # MulDiv | expr op=('+'|'-') expr # AddSub | NUM | STRING | PARAMETER | '(' expr ')' # parens ; NUM : 0 ('.' [0-9]+)? | [1-9][0-9]* ('.' [0-9]+)? ; STRING : '\'' ('\\' . | . ) '\'' | '"' ('\\' . | .) '"' ; PARAMETER: '[' ~('[') ']'; MUL : '*' ; DIV : '/' ; ADD : '+' ; SUB : '-' ; MOD : '%' ; // 逻辑函数 IF : 'IF' ; IFERROR : 'IFERROR' ; IFNUMBER : 'IFNUMBER' ; IFTEXT : 'IFTEXT' ; ISNUMBER : 'ISNUMBER' ; ISTEXT : 'ISTEXT' ; AND : 'AND' ; OR : 'OR' ; NOT : 'NOT' ; TRUE : 'TRUE' ; FALSE : 'FALSE' ; // 数学与三角函数 PI : 'PI' ; ABS : 'ABS' ; QUOTIENT : 'QUOTIENT' ; MOD : 'MOD' ; SIGN : 'SIGN' ; SQRT : 'SQRT' ; TRUNC : 'TRUNC' ; INT : 'INT' ; GCD : 'GCD' ; LCM : 'LCM' ; COMBIN : 'COMBIN' ; PERMUT : 'PERMUT' ; DEGREES : 'DEGREES' ; RADIANS : 'RADIANS' ; COS : 'COS' ; COSH : 'COSH' ; SIN : 'SIN' ; SINH : 'SINH' ; TAN : 'TAN' ; TANH : 'TANH' ; ACOS : 'ACOS' ; ACOSH : 'ACOSH' ; ASIN : 'ASIN' ; ASINH : 'ASINH' ; ATAN : 'ATAN' ; ATANH : 'ATANH' ; ATAN2 : 'ATAN2' ; ROUND : 'ROUND' ; ROUNDDOWN : 'ROUNDDOWN' ; ROUNDUP : 'ROUNDUP' ; CEILING : 'CEILING' ; FLOOR : 'FLOOR' ; EVEN : 'EVEN' ; ODD : 'ODD' ; MROUND : 'MROUND' ; RAND : 'RAND' ; RANDBETWEEN : 'RANDBETWEEN' ; FACT : 'FACT' ; FACTDOUBLE : 'FACTDOUBLE' ; POWER : 'POWER' ; EXP : 'EXP' ; LN : 'LN' ; LOG : 'LOG' ; LOG10 : 'LOG10' ; MULTINOMIAL : 'MULTINOMIAL' ; PRODUCT : 'PRODUCT' ; SQRTPI : 'SQRTPI' ; SUMSQ : 'SUMSQ' ; // 文本函数 ASC : 'ASC' ; JIS : 'JIS' ; WIDECHAR : 'WIDECHAR' ; CHAR : 'CHAR' ; CLEAN : 'CLEAN' ; CODE : 'CODE' ; CONCATENATE : 'CONCATENATE' ; EXACT : 'EXACT' ; FIND : 'FIND' ; FIXED : 'FIXED' ; LEFT : 'LEFT' ; LEN : 'LEN' ; LOWER : 'LOWER' ; MID : 'MID' ; PROPER : 'PROPER' ; REPLACE : 'REPLACE' ; REPT : 'REPT' ; RIGHT : 'RIGHT' ; RMB : 'RMB' ; SEARCH : 'SEARCH' ; SUBSTITUTE : 'SUBSTITUTE' ; T : 'T' ; TEXT : 'TEXT' ; TRIM : 'TRIM' ; UPPER : 'UPPER' ; VALUE : 'VALUE' ; // 日期与时间函数 DATEVALUE : 'DATEVALUE' ; TIMEVALUE : 'TIMEVALUE' ; DATE : 'DATE' ; TIME : 'TIME' ; NOW : 'NOW' ; TODAY : 'TODAY' ; YEAR : 'YEAR' ; MONTH : 'MONTH' ; DAY : 'DAY' ; HOUR : 'HOUR' ; MINUTE : 'MINUTE' ; SECOND : 'SECOND' ; WEEKDAY : 'WEEKDAY' ; DATEDIF : 'DATEDIF' ; DAYS360 : 'DAYS360' ; EDATE : 'EDATE' ; EOMONTH : 'EOMONTH' ; NETWORKDAYS : 'NETWORKDAYS' ; WORKDAY : 'WORKDAY' ; WEEKNUM : 'WEEKNUM' ; // 统计函数 MAX : 'MAX' ; MEDIAN : 'MEDIAN' ; MIN : 'MIN' ; QUARTILE : 'QUARTILE' ; MODE : 'MODE' ; LARGE : 'LARGE' ; SMALL : 'SMALL' ; PERCENTILE : 'PERCENTILE' ; PERCENTRANK : 'PERCENTRANK' ; AVERAGE : 'AVERAGE' ; AVERAGEIF : 'AVERAGEIF' ; GEOMEAN : 'GEOMEAN' ; HARMEAN : 'HARMEAN' ; COUNT : 'COUNT' ; COUNTIF : 'COUNTIF' ; SUM : 'SUM' ; SUMIF : 'SUMIF' ; AVEDEV : 'AVEDEV' ; STDEV : 'STDEV' ; STDEVP : 'STDEVP' ; DEVSQ : 'DEVSQ' ; VAR : 'VAR' ; VARP : 'VARP' ; NORMDIST : 'NORMDIST' ; NORMINV : 'NORMINV' ; NORMSDIST : 'NORMSDIST' ; NORMSINV : 'NORMSINV' ; BETADIST : 'BETADIST' ; BETAINV : 'BETAINV' ; BINOMDIST : 'BINOMDIST' ; EXPONDIST : 'EXPONDIST' ; FDIST : 'FDIST' ; FINV : 'FINV' ; FISHER : 'FISHER' ; FISHERINV : 'FISHERINV' ; GAMMADIST : 'GAMMADIST' ; GAMMAINV : 'GAMMAINV' ; GAMMALN : 'GAMMALN' ; HYPGEOMDIST : 'HYPGEOMDIST' ; LOGINV : 'LOGINV' ; LOGNORMDIST : 'LOGNORMDIST' ; NEGBINOMDIST : 'NEGBINOMDIST' ; POISSON : 'POISSON' ; TDIST : 'TDIST' ; TINV : 'TINV' ; WEIBULL : 'WEIBULL' ; // 增加函数 类C#方法 URLENCODE : 'URLENCODE' ; URLDECODE : 'URLDECODE' ; HTMLENCODE : 'HTMLENCODE' ; HTMLDECODE : 'HTMLDECODE' ; BASE64TOTEXT : 'BASE64TOTEXT' ; BASE64URLTOTEXT : 'BASE64URLTOTEXT' ; TEXTTOBASE64 : 'TEXTTOBASE64' ; TEXTTOBASE64URL : 'TEXTTOBASE64URL' ; REGEX : 'REGEX' ; REGEXREPALCE : 'REGEXREPALCE' ; ISREGEX : 'ISREGEX' ; ISMATCH : 'ISMATCH' ; GUID : 'GUID' ; MD5 : 'MD5' ; SHA1 : 'SHA1' ; SHA256 : 'SHA256' ; SHA512 : 'SHA512' ; CRC8 : 'CRC8' ; CRC16 : 'CRC16' ; CRC32 : 'CRC32' ; HMACMD5 : 'HMACMD5' ; HMACSHA1 : 'HMACSHA1' ; HMACSHA256 : 'HMACSHA256' ; HMACSHA512 : 'HMACSHA512' ; TRIMSTART : 'TRIMSTART' ; LTRIM : 'LTRIM' ; TRIMEND : 'TRIMEND' ; RTRIM : 'RTRIM' ; INDEXOF : 'INDEXOF' ; LASTINDEXOF : 'LASTINDEXOF' ; SPLIT : 'SPLIT' ; JOIN : 'JOIN' ; SUBSTRING : 'SUBSTRING' ; STARTSWITH : 'STARTSWITH' ; ENDSWITH : 'ENDSWITH' ; ISNULLOREMPTY : 'ISNULLOREMPTY' ; ISNULLORWHITESPACE : 'ISNULLORWHITESPACE' ; TOUPPER : 'TOUPPER' ; TOLOWER : 'TOLOWER' ; REMOVESTART : 'REMOVESTART' ; REMOVEEND : 'REMOVEEND' ; REMOVEBOTH : 'REMOVEBOTH' ; JSON : 'JSON' ; TRYJSON : 'TRYJSON' ; P : 'P' ; PARAM : 'PARAM' ; WS : [ \t\r\n]+ -> skip;
添加 g4文件
添加 g4文件
ANTLR
apache-2.0
toolgood/ToolGood.Algorithm,toolgood/ToolGood.Algorithm
d7fd6dc649b9cc630abef4397f701cb3e931e69f
src/main/antlr4/com/sri/ai/praise/sgsolver/hogm/antlr/HOGM.g4
src/main/antlr4/com/sri/ai/praise/sgsolver/hogm/antlr/HOGM.g4
grammar HOGM; model : statements+=statement* EOF ; statement : declaration | rule_definition ; declaration : sort_decl | random_variable_decl ; sort_decl // sort symbol [ ":" ( number | "Unknown" ) [ ", " constant+ ] ] : SORT name=symbol (':' size=(INTEGER | UNKNOWN) (',' constants+=CONSTANT)*)? ; // "random" symbol : symbol // "random" symbol ":" [ ( symbol | symbol "x" )+ ] "->" symbol random_variable_decl : RANDOM name=symbol ':' range=symbol | RANDOM name=symbol ':' parameters+=symbol (X parameters+=symbol)* '->' range=symbol ; rule_definition : IF formula THEN rule_definition ELSE rule_definition #conditionalRule | f=formula (p=potential)? #formulaWithOptionalPotentialRule ; formula : '(' formula ')' #termWithParentheses | functor=symbol '(' ( args+=formula (',' args+=formula)* )? ')' #formulaFunctionApplication | NOT formula #notFunctionApplication | leftconj=formula AND rightconj=formula #andFunctionApplication | leftconj=formula OR rightconj=formula #orFunctionApplication | IF condition=formula THEN thenbranch=formula ELSE elsebranch=formula #ifThenElseFunctionApplication | quantified_expression #termQuantifiedExpression | constant #termConstant | variable #termVariable ; quantified_expression : FOR ALL index=variable ':' body=formula #forAll | THERE EXISTS index=variable ':' body=formula #thereExists ; constant : CONSTANT ; variable : VARIABLE ; potential : // parenthesis, e.g.:(1+2) '(' potential ')' #potentialWithParentheses // exponentiation, e.g. 2^3^4 -> 2^(3^4) |<assoc=right> base=potential '^' exponent=potential #potentialExponentiation // multiplication or division, e.g.: 2*3/2 -> 2*(3/2) | leftop=potential op=('*' | '/') rightop=potential #potentialMultiplicationOrDivision // addition or subtraction, e.g.: 1-2+3 -> (1-2)+3 | leftop=potential op=('+' | '-') rightop=potential #potentialAdditionOrSubtraction // i.e. a constant value between [0-1] | atomic_potential #potentialValue ; atomic_potential : INTEGER | RATIONAL ; symbol : X | CONSTANT | QUOTED_CONSTANT | VARIABLE ; /* 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 RuleTerminalSymbols.java with any changes made. */ // Keywords NOT : 'not' ; AND : 'and' ; OR : 'or' ; FOR : 'for' ; ALL : 'all' ; THERE : 'there' ; EXISTS : 'exists' ; IF : 'if' ; THEN : 'then' ; ELSE : 'else' ; SORT : 'sort' ; UNKNOWN : 'Unknown'; RANDOM : 'random' ; X : 'x' ; // Logic Operators IMPLICATION : '=>' ; BICONDITIONAL : '<=>' ; // Arithmetic EXPONENTIATION : '^' ; DIVIDE : '/' ; TIMES : '*' ; PLUS : '+' ; SUBTRACT : '-' ; // Comparison EQUAL : '=' ; NOT_EQUAL : '!=' ; // Brackets OPEN_PAREN : '(' ; CLOSE_PAREN : ')' ; 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 : [a-z] ([a-z] | [A-Z] | [0-9] | '_')* ('\'')* ; QUOTED_CONSTANT : '"' (ESCAPE_SEQUENCE | ~('\\' | '"' ) )* '"' | '\'' (ESCAPE_SEQUENCE | ~('\\' | '\'') )* '\'' ; VARIABLE : [A-Z] ([a-z] | [A-Z] | [0-9] | '_')* ('\'')* ; 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
Add initial version of Symbolic Generalized HOGM language.
Add initial version of Symbolic Generalized HOGM language. git-svn-id: https://aic-praise.googlecode.com/svn/trunk@1402 e74e62f3-1872-5a1b-a7a8-c7220c51b9cb Former-commit-id: 97510800ce6c47d269c43896f41f4098562e250d
ANTLR
bsd-3-clause
aic-sri-international/aic-praise,aic-sri-international/aic-praise
be55977d99e2e1eda5c53c10860cec3bccd16d00
pattern_grammar/STIXPattern.g4
pattern_grammar/STIXPattern.g4
grammar STIXPattern; pattern : observationExpressions ; observationExpressions : <assoc=left> observationExpressions FOLLOWEDBY observationExpressions | observationExpressionOr ; observationExpressionOr : <assoc=left> observationExpressionOr OR observationExpressionOr | observationExpressionAnd ; observationExpressionAnd : <assoc=left> observationExpressionAnd AND observationExpressionAnd | observationExpression ; observationExpression : LBRACK comparisonExpression RBRACK # observationExpressionSimple | LPAREN observationExpressions RPAREN # observationExpressionCompound | observationExpression startStopQualifier # observationExpressionStartStop | observationExpression withinQualifier # observationExpressionWithin | observationExpression repeatedQualifier # observationExpressionRepeated ; comparisonExpression : <assoc=left> comparisonExpression OR comparisonExpression | comparisonExpressionAnd ; comparisonExpressionAnd : <assoc=left> comparisonExpressionAnd AND comparisonExpressionAnd | propTest ; propTest : objectPath (EQ|NEQ) primitiveLiteral # propTestEqual | objectPath (GT|LT|GE|LE) orderableLiteral # propTestOrder | objectPath NOT? IN setLiteral # propTestSet | objectPath NOT? LIKE StringLiteral # propTestLike | objectPath NOT? MATCHES StringLiteral # propTestRegex | objectPath NOT? ISSUBSET StringLiteral # propTestIsSubset | objectPath NOT? ISSUPERSET StringLiteral # propTestIsSuperset | LPAREN comparisonExpression RPAREN # propTestParen ; startStopQualifier : START StringLiteral STOP StringLiteral ; withinQualifier : WITHIN IntLiteral timeUnit ; repeatedQualifier : REPEATS IntLiteral TIMES ; objectPath : objectType COLON firstPathComponent objectPathComponent? ; // The following two simple rules are for programmer convenience: you // will get "notification" of object path components in order by the // generated parser, which enables incremental processing during // parsing. objectType : Identifier ; firstPathComponent : Identifier ; objectPathComponent : <assoc=left> objectPathComponent objectPathComponent # pathStep | '.' Identifier # keyPathStep | LBRACK (IntLiteral|ASTERISK) RBRACK # indexPathStep ; setLiteral : LPAREN RPAREN | LPAREN primitiveLiteral (COMMA primitiveLiteral)* RPAREN ; primitiveLiteral : orderableLiteral | BoolLiteral | NULL ; orderableLiteral : IntLiteral | FloatLiteral | StringLiteral | BinaryLiteral | HexLiteral | TimestampLiteral ; timeUnit : MILLISECONDS | SECONDS | MINUTES | HOURS | DAYS | MONTHS | YEARS ; IntLiteral : [+-]? ('0' | [1-9] [0-9]*) ; FloatLiteral : [+-]? [0-9]* '.' [0-9]+ ; HexLiteral : 'h' QUOTE TwoHexDigits* QUOTE ; BinaryLiteral : 'b' QUOTE Base64Char* QUOTE ; StringLiteral : QUOTE ( ~'\'' | '\'\'' )* QUOTE ; BoolLiteral : TRUE | FALSE ; TimestampLiteral : 't' QUOTE [0-9] [0-9] [0-9] [0-9] HYPHEN [0-9] [0-9] HYPHEN [0-9] [0-9] 'T' [0-9] [0-9] COLON [0-9] [0-9] COLON [0-9] [0-9] (DOT [0-9]+)? 'Z' QUOTE ; ////////////////////////////////////////////// // Keywords AND: A N D; OR: O R; NOT: N O T; FOLLOWEDBY: F O L L O W E D B Y; LIKE: L I K E ; MATCHES: M A T C H E S ; ISSUPERSET: I S S U P E R S E T ; ISSUBSET: I S S U B S E T ; LAST: L A S T ; IN: I N; START: S T A R T ; STOP: S T O P ; MILLISECONDS: M I L L I S E C O N D S; SECONDS: S E C O N D S; MINUTES: M I N U T E S; HOURS: H O U R S; DAYS: D A Y S; MONTHS: M O N T H S; YEARS: Y E A R S; TRUE: T R U E; FALSE: F A L S E; NULL: N U L L; WITHIN: W I T H I N; REPEATS: R E P E A T S; TIMES: T I M E S; // After keywords, so the lexer doesn't tokenize them as identifiers. Identifier : '"' (~'"' | '""')* '"' | [a-zA-Z_] [a-zA-Z0-9_-]* ; EQ : '=' | '=='; NEQ : '!=' | '<>'; LT : '<'; LE : '<='; GT : '>'; GE : '>='; QUOTE : '\''; COLON : ':' ; DOT : '.' ; COMMA : ',' ; RPAREN : ')' ; LPAREN : '(' ; RBRACK : ']' ; LBRACK : '[' ; PLUS : '+' ; HYPHEN : MINUS ; MINUS : '-' ; POWER_OP : '^' ; DIVIDE : '/' ; ASTERISK : '*'; fragment A: [aA]; fragment B: [bB]; fragment C: [cC]; fragment D: [dD]; fragment E: [eE]; fragment F: [fF]; fragment G: [gG]; fragment H: [hH]; fragment I: [iI]; fragment J: [jJ]; fragment K: [kK]; fragment L: [lL]; fragment M: [mM]; fragment N: [nN]; fragment O: [oO]; fragment P: [pP]; fragment Q: [qQ]; fragment R: [rR]; fragment S: [sS]; fragment T: [tT]; fragment U: [uU]; fragment V: [vV]; fragment W: [wW]; fragment X: [xX]; fragment Y: [yY]; fragment Z: [zZ]; fragment HexDigit: [A-Fa-f0-9]; fragment TwoHexDigits: HexDigit HexDigit; fragment Base64Char: [A-Za-z0-9+/=]; // Whitespace and comments // WS : [ \t\r\n\u000B\u000C\u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+ -> skip ; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '//' ~[\r\n]* -> skip ;
Add STIX Pattern grammar.
Add STIX Pattern grammar.
ANTLR
bsd-3-clause
oasis-open/cti-stix2-json-schemas
a274f5f75568726516e71af3a2aebef40a0df85a
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 ;
Add JSON grammar
Add JSON grammar
ANTLR
apache-2.0
premun/ingrid
154c7d4d088e347cd9bff9e8b1e5884f3ef34946
objc.g4
objc.g4
// Converted to ANTLR 4 by Terence Parr; added @property and a few others. // Seems to handle stuff like this except for blocks: // https://google-api-objectivec-client.googlecode.com/svn/trunk/Examples/ShoppingSample/ShoppingSampleWindowController.m /** * ObjectiveC version 2 * based on an LL ansic grammars and * and ObjectiveC grammar found in Learning Object C * * It's a Work in progress, most of the .h file can be parsed * June 2008 Cedric Cuche * Updated June 2014, Carlos Mejia. Fix try-catch, add support for @( @{ @[ and blocks **/ grammar ObjC; translation_unit: external_declaration+ EOF; external_declaration: COMMENT | LINE_COMMENT | preprocessor_declaration | function_definition | declaration | class_interface | class_implementation | category_interface | category_implementation | protocol_declaration | protocol_declaration_list | class_declaration_list; preprocessor_declaration: IMPORT | INCLUDE; class_interface: '@interface' class_name (':' superclass_name)? protocol_reference_list? instance_variables? interface_declaration_list? '@end'; category_interface: '@interface' class_name '(' category_name? ')' protocol_reference_list? instance_variables? interface_declaration_list? '@end'; class_implementation: '@implementation' ( class_name ( ':' superclass_name )? instance_variables? ( implementation_definition_list )? ) '@end'; category_implementation: '@implementation'( class_name '(' category_name ')' ( implementation_definition_list )? )'@end'; protocol_declaration: '@protocol'( protocol_name ( protocol_reference_list )? interface_declaration_list? '@optional'? interface_declaration_list? )'@end'; protocol_declaration_list: ('@protocol' protocol_list';') ; class_declaration_list: ('@class' class_list';') ; class_list: class_name (',' class_name)*; protocol_reference_list: ('<' protocol_list '>'); protocol_list: protocol_name (',' protocol_name)*; property_declaration : '@property' property_attributes_declaration? struct_declaration ; property_attributes_declaration : '(' property_attributes_list ')' ; property_attributes_list : property_attribute (',' property_attribute)* ; property_attribute : 'nonatomic' | 'assign' | 'weak' | 'strong' | 'retain' | 'readonly' | 'readwrite' | | 'getter' '=' IDENTIFIER // getter | 'setter' '=' IDENTIFIER ':' // setter | IDENTIFIER ; class_name: IDENTIFIER; superclass_name: IDENTIFIER; category_name: IDENTIFIER; protocol_name: IDENTIFIER; instance_variables : '{' struct_declaration* '}' | '{' visibility_specification struct_declaration+ '}' | '{' struct_declaration+ instance_variables '}' | '{' visibility_specification struct_declaration+ instance_variables '}' ; visibility_specification: '@private' | '@protected' | '@package' | '@public'; interface_declaration_list: (declaration | class_method_declaration | instance_method_declaration | property_declaration)+ ; class_method_declaration: ('+' method_declaration) ; instance_method_declaration: ('-' method_declaration) ; method_declaration: ( method_type )? method_selector ';'; implementation_definition_list : ( function_definition | declaration | class_method_definition | instance_method_definition | property_implementation )+ ; class_method_definition: ('+' method_definition) ; instance_method_definition: ('-' method_definition) ; method_definition: (method_type)? method_selector (init_declarator_list)? ';'? compound_statement; method_selector: selector |(keyword_declarator+ (parameter_list)? ) ; keyword_declarator: selector? ':' method_type* IDENTIFIER; selector: IDENTIFIER; method_type: '(' type_name ')'; property_implementation : '@synthesize' property_synthesize_list ';' | '@dynamic' property_synthesize_list ';' ; property_synthesize_list : property_synthesize_item (',' property_synthesize_item)* ; property_synthesize_item : IDENTIFIER | IDENTIFIER '=' IDENTIFIER ; block_type:type_specifier '(''^' type_specifier? ')' block_parameters? ; type_specifier: 'void' | 'char' | 'short' | 'int' | 'long' | 'float' | 'double' | 'signed' | 'unsigned' | ('id' ( protocol_reference_list )? ) | (class_name ( protocol_reference_list )?) | struct_or_union_specifier | enum_specifier | IDENTIFIER | IDENTIFIER pointer; type_qualifier: 'const' | 'volatile' | protocol_qualifier; protocol_qualifier: 'in' | 'out' | 'inout' | 'bycopy' | 'byref' | 'oneway'; primary_expression: IDENTIFIER | constant | STRING_LITERAL | ('(' expression ')') | 'self' | 'super' | message_expression | selector_expression | protocol_expression | encode_expression | dictionary_expression | array_expression | box_expression | block_expression; dictionary_pair: postfix_expression':'postfix_expression; dictionary_expression: '@''{' dictionary_pair? (',' dictionary_pair)* ','? '}'; array_expression: '@''[' postfix_expression? (',' postfix_expression)* ','? ']'; box_expression: '@''('postfix_expression')' | '@'constant; block_parameters: '(' (type_variable_declarator | 'void')? (',' type_variable_declarator)* ')'; block_expression:'^' type_specifier? block_parameters? compound_statement; message_expression: '[' receiver message_selector ']' ; receiver: expression | class_name | 'super'; message_selector: selector | keyword_argument+; keyword_argument: selector? ':' expression; selector_expression: '@selector' '(' selector_name ')'; selector_name: selector | (selector? ':')+; protocol_expression: '@protocol' '(' protocol_name ')'; encode_expression: '@encode' '(' type_name ')'; type_variable_declarator: declaration_specifiers declarator; try_statement: '@try' compound_statement; catch_statement: '@catch' '('type_variable_declarator')' compound_statement; finally_statement: '@finally' compound_statement; throw_statement: '@throw' '('IDENTIFIER')'; try_block: try_statement ( catch_statement)* ( finally_statement )?; synchronized_statement: '@synchronized' '(' primary_expression ')' compound_statement; autorelease_statement: '@autoreleasepool' compound_statement; function_definition : declaration_specifiers? declarator compound_statement ; declaration : declaration_specifiers init_declarator_list? ';'; declaration_specifiers : (arc_behaviour_specifier | storage_class_specifier | type_specifier | type_qualifier)+ ; arc_behaviour_specifier: '__unsafe_unretained' | '__weak'; storage_class_specifier: 'auto' | 'register' | 'static' | 'extern' | 'typedef'; init_declarator_list : init_declarator (',' init_declarator)* ; init_declarator : declarator ('=' initializer)? ; struct_or_union_specifier: ('struct' | 'union') ( IDENTIFIER | IDENTIFIER? '{' struct_declaration+ '}') ; struct_declaration : specifier_qualifier_list struct_declarator_list ';' ; specifier_qualifier_list : (arc_behaviour_specifier | type_specifier | type_qualifier)+ ; struct_declarator_list : struct_declarator (',' struct_declarator)* ; struct_declarator : declarator | declarator? ':' constant; enum_specifier : 'enum' (':' type_name)? ( identifier ('{' enumerator_list '}')? | '{' enumerator_list '}') | 'NS_OPTIONS' '(' type_name ',' identifier ')' '{' enumerator_list '}' | 'NS_ENUM' '(' type_name ',' identifier ')' '{' enumerator_list '}' ; enumerator_list : enumerator (',' enumerator)* ','? ; enumerator : identifier ('=' constant_expression)?; pointer : '*' declaration_specifiers? | '*' declaration_specifiers? pointer; declarator : pointer ? direct_declarator ; direct_declarator : identifier declarator_suffix* | '(' declarator ')' declarator_suffix* | '(''^' identifier? ')' block_parameters; declarator_suffix : '[' constant_expression? ']' | '(' parameter_list? ')'; parameter_list : parameter_declaration_list ( ',' '...' )? ; parameter_declaration : declaration_specifiers (declarator? | abstract_declarator) ; initializer : assignment_expression | '{' initializer (',' initializer)* ','? '}' ; type_name : specifier_qualifier_list abstract_declarator | block_type; abstract_declarator : pointer abstract_declarator | '(' abstract_declarator ')' abstract_declarator_suffix+ | ('[' constant_expression? ']')+ | ; abstract_declarator_suffix : '[' constant_expression? ']' | '(' parameter_declaration_list? ')' ; parameter_declaration_list : parameter_declaration ( ',' parameter_declaration )* ; statement_list : statement+ ; statement : labeled_statement | expression ';' | compound_statement | selection_statement | iteration_statement | jump_statement | synchronized_statement | autorelease_statement | try_block | ';' ; labeled_statement : identifier ':' statement | 'case' constant_expression ':' statement | 'default' ':' statement ; compound_statement : '{' (declaration|statement_list)* '}' ; selection_statement : 'if' '(' expression ')' statement ('else' statement)? | 'switch' '(' expression ')' statement ; for_in_statement : 'for' '(' type_variable_declarator 'in' expression? ')' statement; for_statement: 'for' '(' ((declaration_specifiers init_declarator_list) | expression)? ';' expression? ';' expression? ')' statement; while_statement: 'while' '(' expression ')' statement; do_statement: 'do' statement 'while' '(' expression ')' ';'; iteration_statement : while_statement | do_statement | for_statement | for_in_statement ; jump_statement : 'goto' identifier ';' | 'continue' ';' | 'break' ';' | 'return' expression? ';' ; expression : assignment_expression (',' assignment_expression)* ; assignment_expression : conditional_expression | unary_expression assignment_operator assignment_expression ; assignment_operator: '=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '&=' | '^=' | '|='; conditional_expression : logical_or_expression ('?' conditional_expression ':' conditional_expression)? ; constant_expression : conditional_expression ; logical_or_expression : logical_and_expression ('||' logical_and_expression)* ; logical_and_expression : inclusive_or_expression ('&&' inclusive_or_expression)* ; inclusive_or_expression : exclusive_or_expression ('|' exclusive_or_expression)* ; exclusive_or_expression : and_expression ('^' and_expression)* ; and_expression : equality_expression ('&' equality_expression)* ; equality_expression : relational_expression (('!=' | '==') relational_expression)* ; relational_expression : shift_expression (('<' | '>' | '<=' | '>=') shift_expression)* ; shift_expression : additive_expression (('<<' | '>>') additive_expression)* ; additive_expression : multiplicative_expression (('+' | '-') multiplicative_expression)* ; multiplicative_expression : cast_expression (('*' | '/' | '%') cast_expression)* ; cast_expression : '(' type_name ')' cast_expression | unary_expression ; unary_expression : postfix_expression | '++' unary_expression | '--' unary_expression | unary_operator cast_expression | 'sizeof' ('(' type_name ')' | unary_expression) ; unary_operator : '&' | '*' | '-' | '~' | '!' ; postfix_expression : primary_expression ('[' expression ']' | '(' argument_expression_list? ')' | '.' identifier | '->' identifier | '++' | '--' )* ; argument_expression_list : assignment_expression (',' assignment_expression)* ; identifier : IDENTIFIER; constant : DECIMAL_LITERAL | HEX_LITERAL | OCTAL_LITERAL | CHARACTER_LITERAL | FLOATING_POINT_LITERAL; // LEXER // §3.9 Keywords AUTORELEASEPOOL : '@autoreleasepool'; CATCH : '@catch'; CLASS : '@class'; DYNAMIC : '@dynamic'; ENCODE : '@encode'; END : '@end'; FINALLY : '@finally'; IMPLEMENTATION : '@implementation'; INTERFACE : '@interface'; PACKAGE : '@package'; PROTOCOL : '@protocol'; OPTIONAL : '@optional'; PRIVATE : '@private'; PROPERTY : '@property'; PROTECTED : '@protected'; PUBLIC : '@public'; SELECTOR : '@selector'; SYNCHRONIZED : '@synchronized'; SYNTHESIZE : '@synthesize'; THROW : '@throw'; TRY : '@try'; SUPER : 'super'; SELF : 'self'; ABSTRACT : 'abstract'; AUTO : 'auto'; BOOLEAN : 'boolean'; BREAK : 'break'; BYCOPY : 'bycopy'; BYREF : 'byref'; CASE : 'case'; CHAR : 'char'; CONST : 'const'; CONTINUE : 'continue'; DEFAULT : 'default'; DO : 'do'; DOUBLE : 'double'; ELSE : 'else'; ENUM : 'enum'; EXTERN : 'extern'; FLOAT : 'float'; FOR : 'for'; ID : 'id'; IF : 'if'; IN : 'in'; INOUT : 'inout'; GOTO : 'goto'; INT : 'int'; LONG : 'long'; ONEWAY : 'oneway'; OUT : 'out'; REGISTER : 'register'; 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'; NS_OPTIONS : 'NS_OPTIONS'; NS_ENUM : 'NS_ENUM'; WWEAK : '__weak'; WUNSAFE_UNRETAINED : '__unsafe_unretained'; // §3.11 Separators LPAREN : '('; RPAREN : ')'; LBRACE : '{'; RBRACE : '}'; LBRACK : '['; RBRACK : ']'; SEMI : ';'; COMMA : ','; DOT : '.'; STRUCTACCESS : '->'; AT : '@'; // Operators ASSIGN : '='; GT : '>'; LT : '<'; BANG : '!'; TILDE : '~'; QUESTION : '?'; COLON : ':'; EQUAL : '=='; LE : '<='; GE : '>='; NOTEQUAL : '!='; AND : '&&'; OR : '||'; INC : '++'; DEC : '--'; ADD : '+'; SUB : '-'; MUL : '*'; DIV : '/'; BITAND : '&'; BITOR : '|'; CARET : '^'; MOD : '%'; SHIFT_R : '>>'; SHIFT_L : '<<'; // Assignment ADD_ASSIGN : '+='; SUB_ASSIGN : '-='; MUL_ASSIGN : '*='; DIV_ASSIGN : '/='; AND_ASSIGN : '&='; OR_ASSIGN : '|='; XOR_ASSIGN : '^='; MOD_ASSIGN : '%='; LSHIFT_ASSIGN : '<<='; RSHIFT_ASSIGN : '>>='; ELIPSIS : '...'; // Property attributes ASSIGNPA : 'assign'; GETTER : 'getter'; NONATOMIC : 'nonatomic'; SETTER : 'setter'; STRONG : 'strong'; RETAIN : 'retain'; READONLY : 'readonly'; READWRITE : 'readwrite'; WEAK : 'weak'; IDENTIFIER : LETTER (LETTER|'0'..'9')* ; fragment LETTER : '$' | 'A'..'Z' | 'a'..'z' | '_' ; CHARACTER_LITERAL : '\'' ( EscapeSequence | ~('\''|'\\') ) '\'' ; /* s_char = [[[any_char - '"'] - '\'] - nl] | escape_sequence; string_literal = ('L' | '@') '"' s_char* '"'; */ STRING_LITERAL : [L@] STRING ; fragment STRING : '"' ( EscapeSequence | ~('\\'|'"') )* '"' ; HEX_LITERAL : '0' ('x'|'X') HexDigit+ IntegerTypeSuffix? ; DECIMAL_LITERAL : ('0' | '1'..'9' '0'..'9'*) IntegerTypeSuffix? ; OCTAL_LITERAL : '0' ('0'..'7')+ IntegerTypeSuffix? ; fragment HexDigit : ('0'..'9'|'a'..'f'|'A'..'F') ; fragment IntegerTypeSuffix : ('u'|'U'|'l'|'L') ; FLOATING_POINT_LITERAL : ('0'..'9')+ ('.' ('0'..'9')*)? Exponent? FloatTypeSuffix? ; fragment Exponent : ('e'|'E') ('+'|'-')? ('0'..'9')+ ; fragment FloatTypeSuffix : ('f'|'F'|'d'|'D') ; fragment EscapeSequence : '\\' ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\') | OctalEscape ; fragment OctalEscape : '\\' ('0'..'3') ('0'..'7') ('0'..'7') | '\\' ('0'..'7') ('0'..'7') | '\\' ('0'..'7') ; fragment UnicodeEscape : '\\' 'u' HexDigit HexDigit HexDigit HexDigit ; IMPORT : '#import' [ \t]* (STRING|ANGLE_STRING) WS -> channel(HIDDEN) ; INCLUDE: '#include'[ \t]* (STRING|ANGLE_STRING) WS -> channel(HIDDEN) ; PRAGMA : '#pragma' ~[\r\n]* -> channel(HIDDEN) ; fragment ANGLE_STRING : '<' .*? '>' ; WS : [ \r\n\t\u000C] -> channel(HIDDEN) ; COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ; // ignore preprocessor defines for now HDEFINE : '#define' ~[\r\n]* -> channel(HIDDEN); HIF : '#if' ~[\r\n]* -> channel(HIDDEN); HELSE : '#else' ~[\r\n]* -> channel(HIDDEN); HUNDEF : '#undef' ~[\r\n]* -> channel(HIDDEN); HIFNDEF : '#ifndef' ~[\r\n]* -> channel(HIDDEN); HENDIF : '#endif' ~[\r\n]* -> channel(HIDDEN);
add objc-grammer file.
add objc-grammer file.
ANTLR
mit
johndpope/objc2swift
39753cb0e90cff1c5ac44f4868da6f8dc53a05e6
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];
Add scheme lexer rules
Add scheme lexer rules
ANTLR
apache-2.0
OrangeShark/citrus-scheme
916e3fc8f8ecec714d16216c381b467415ac4b9b
Composer.g4
Composer.g4
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ grammar Composer; stat: assign NEWLINE {console.log("create new");} | connect NEWLINE {console.log("connect new");} ; assign: ID '=' expr {console.log("assign expr is" + $expr.text);}; connect: expr CONNECT expr {console.log("connect expr is" + $expr.text);}; expr:; CONNECT : '->'; ID : [a-zA-Z_] [a-zA-Z_0-9]* ; // match identifiers <label id="code.tour.expr.3"/> INT : [0-9]+ ; // match integers /** Newline ends a statement */ NEWLINE :'\r'? '\n' ; // return newlines to parser (is end-statement signal) /** Warning: doesn't handle INDENT/DEDENT Python rules */ WS : [ \t]+ -> skip ; // toss out whitespace /** Match comments. Don't match \n here; we'll send NEWLINE to the parser. */ COMMENT : '#' ~[\r\n]* -> skip ;
Create Composer.g4
Create Composer.g4
ANTLR
mit
hanwencheng/ConnectLang
fcab1adb7b50e101217cd44801d30a39f6a52701
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
sharding-core/src/main/antlr4/imports/OracleDCLStatement.g4
grammar OracleDCLStatement; import OracleKeyword, Keyword, OracleBase, BaseRule, DataType, Symbol; programUnit : (FUNCTION | PROCEDURE | PACKAGE) schemaName? ID ;
add programUnit
add programUnit
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
3fc0afb03decb1d7a63a543779a13ffadf73f3ae
pinot-common/src/main/antlr4/com/linkedin/pinot/pql/parsers/PQL2.g4
pinot-common/src/main/antlr4/com/linkedin/pinot/pql/parsers/PQL2.g4
/** * Copyright (C) 2014-2016 LinkedIn Corp. ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar PQL2; root: statement ';'? EOF; statement: selectStatement; selectStatement : SELECT topClause? outputColumns FROM tableName optionalClause* # Select; optionalClause: whereClause # Where | groupByClause # GroupBy | havingClause # Having | orderByClause # OrderBy | topClause # Top | limitClause # Limit ; outputColumns: '*' # StarColumnList | outputColumnProjection (',' outputColumnProjection)* # OutputColumnList; outputColumnProjection: expression (AS (IDENTIFIER | STRING_LITERAL))? # OutputColumn; expression: IDENTIFIER # Identifier | IDENTIFIER '.' IDENTIFIER # Identifier | literal # Constant | '(' expression ')' # ExpressionParenthesisGroup | function '(' expressions? ')' # FunctionCall | expression binaryMathOperator expression # BinaryMathOp ; expressions: expression (',' expression)* # ExpressionList | '*' # StarExpression ; binaryMathOperator: '+' | '-' | '*' | '/'; function: IDENTIFIER; tableName: IDENTIFIER | IDENTIFIER '.' IDENTIFIER | STRING_LITERAL; literal: STRING_LITERAL # StringLiteral | INTEGER_LITERAL # IntegerLiteral | FLOATING_POINT_LITERAL # FloatingPointLiteral ; whereClause: WHERE predicateList; predicateList: predicate (booleanOperator predicate)* ; predicate: '(' predicateList ')' # PredicateParenthesisGroup | comparisonClause # ComparisonPredicate | inClause # InPredicate | betweenClause # BetweenPredicate | isClause # IsPredicate | regexpLikeClause # RegexpLikePredicate ; inClause: expression NOT? IN '(' literal (',' literal)* ')'; isClause: expression IS NOT? NULL; comparisonClause: expression comparisonOperator expression; comparisonOperator: '<' | '>' | '<>' | '<=' | '>=' | '='; betweenClause: expression BETWEEN expression AND expression; regexpLikeClause: REGEXP_LIKE '(' expression ',' literal ')'; booleanOperator: OR | AND; groupByClause: GROUP BY groupByList; groupByList: expression (',' expression)*; havingClause: HAVING predicate; orderByClause: ORDER BY orderByList; orderByList: orderByExpression (',' orderByExpression)*; orderByExpression: expression ordering?; ordering: DESC | ASC; topClause: TOP INTEGER_LITERAL; limitClause: LIMIT INTEGER_LITERAL (',' INTEGER_LITERAL)?; // Keywords AND: A N D; AS: A S; ASC : A S C; BETWEEN: B E T W E E N; BY: B Y; DESC: D E S C; FROM: F R O M; GROUP: G R O U P; HAVING: H A V I N G; IN: I N; IS: I S; NULL: N U L L; LIMIT: L I M I T; NOT : N O T; OR: O R; REGEXP_LIKE: R E G E X P '_' L I K E; LIKE: L I K E; ORDER: O R D E R; SELECT: S E L E C T; TOP: T O P; WHERE: W H E R E; WHITESPACE: [ \t\n]+ -> skip; LINE_COMMENT: '--' ~[\r\n]* -> channel(HIDDEN); IDENTIFIER: [A-Za-z_][A-Za-z0-9_-]*; STRING_LITERAL: '\'' ( ~'\'' | '\'\'')* '\'' | '"' (~'"' | '""')* '"'; INTEGER_LITERAL : SIGN? DIGIT+; FLOATING_POINT_LITERAL : SIGN? DIGIT+ '.' DIGIT* | SIGN? DIGIT* '.' DIGIT+; fragment SIGN: [+-]; fragment DIGIT : [0-9]; fragment A : [aA]; fragment B : [bB]; fragment C : [cC]; fragment D : [dD]; fragment E : [eE]; fragment F : [fF]; fragment G : [gG]; fragment H : [hH]; fragment I : [iI]; fragment J : [jJ]; fragment K : [kK]; fragment L : [lL]; fragment M : [mM]; fragment N : [nN]; fragment O : [oO]; fragment P : [pP]; fragment Q : [qQ]; fragment R : [rR]; fragment S : [sS]; fragment T : [tT]; fragment U : [uU]; fragment V : [vV]; fragment W : [wW]; fragment X : [xX]; fragment Y : [yY]; fragment Z : [zZ];
/** * Copyright (C) 2014-2016 LinkedIn Corp. ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar PQL2; root: statement ';'? EOF; statement: selectStatement; selectStatement : SELECT topClause? outputColumns FROM tableName optionalClause* # Select; optionalClause: whereClause # Where | groupByClause # GroupBy | havingClause # Having | orderByClause # OrderBy | topClause # Top | limitClause # Limit ; outputColumns: '*' # StarColumnList | outputColumnProjection (',' outputColumnProjection)* # OutputColumnList; outputColumnProjection: expression (AS (IDENTIFIER | STRING_LITERAL))? # OutputColumn; expression: IDENTIFIER # Identifier | IDENTIFIER '.' IDENTIFIER # Identifier | literal # Constant | '(' expression ')' # ExpressionParenthesisGroup | function '(' expressions? ')' # FunctionCall | expression binaryMathOperator expression # BinaryMathOp ; expressions: expression (',' expression)* # ExpressionList | '*' # StarExpression ; binaryMathOperator: '+' | '-' | '*' | '/'; function: IDENTIFIER; tableName: IDENTIFIER | IDENTIFIER '.' IDENTIFIER | STRING_LITERAL; literal: STRING_LITERAL # StringLiteral | INTEGER_LITERAL # IntegerLiteral | FLOATING_POINT_LITERAL # FloatingPointLiteral ; whereClause: WHERE predicateList; predicateList: predicate (booleanOperator predicate)* ; predicate: '(' predicateList ')' # PredicateParenthesisGroup | comparisonClause # ComparisonPredicate | inClause # InPredicate | betweenClause # BetweenPredicate | isClause # IsPredicate | regexpLikeClause # RegexpLikePredicate ; inClause: expression NOT? IN '(' literal (',' literal)* ')'; isClause: expression IS NOT? NULL; comparisonClause: expression comparisonOperator expression; comparisonOperator: '<' | '>' | '<>' | '<=' | '>=' | '='; betweenClause: expression BETWEEN expression AND expression; regexpLikeClause: REGEXP_LIKE '(' expression ',' literal ')'; booleanOperator: OR | AND; groupByClause: GROUP BY groupByList; groupByList: expression (',' expression)*; havingClause: HAVING predicate; orderByClause: ORDER BY orderByList; orderByList: orderByExpression (',' orderByExpression)*; orderByExpression: expression ordering?; ordering: DESC | ASC; topClause: TOP INTEGER_LITERAL; limitClause: LIMIT INTEGER_LITERAL (',' INTEGER_LITERAL)?; // Keywords AND: A N D; AS: A S; ASC : A S C; BETWEEN: B E T W E E N; BY: B Y; DESC: D E S C; FROM: F R O M; GROUP: G R O U P; HAVING: H A V I N G; IN: I N; IS: I S; NULL: N U L L; LIMIT: L I M I T; NOT : N O T; OR: O R; REGEXP_LIKE: R E G E X P '_' L I K E; ORDER: O R D E R; SELECT: S E L E C T; TOP: T O P; WHERE: W H E R E; WHITESPACE: [ \t\n]+ -> skip; LINE_COMMENT: '--' ~[\r\n]* -> channel(HIDDEN); IDENTIFIER: [A-Za-z_][A-Za-z0-9_-]*; STRING_LITERAL: '\'' ( ~'\'' | '\'\'')* '\'' | '"' (~'"' | '""')* '"'; INTEGER_LITERAL : SIGN? DIGIT+; FLOATING_POINT_LITERAL : SIGN? DIGIT+ '.' DIGIT* | SIGN? DIGIT* '.' DIGIT+; fragment SIGN: [+-]; fragment DIGIT : [0-9]; fragment A : [aA]; fragment B : [bB]; fragment C : [cC]; fragment D : [dD]; fragment E : [eE]; fragment F : [fF]; fragment G : [gG]; fragment H : [hH]; fragment I : [iI]; fragment J : [jJ]; fragment K : [kK]; fragment L : [lL]; fragment M : [mM]; fragment N : [nN]; fragment O : [oO]; fragment P : [pP]; fragment Q : [qQ]; fragment R : [rR]; fragment S : [sS]; fragment T : [tT]; fragment U : [uU]; fragment V : [vV]; fragment W : [wW]; fragment X : [xX]; fragment Y : [yY]; fragment Z : [zZ];
Remove keyword 'LIKE' from PQL grammar.
Remove keyword 'LIKE' from PQL grammar. Removing the keyword 'LIKE' from PQL grammar as it is not supported currently.
ANTLR
apache-2.0
apucher/pinot,fx19880617/pinot-1,sajavadi/pinot,sajavadi/pinot,linkedin/pinot,fx19880617/pinot-1,apucher/pinot,linkedin/pinot,apucher/pinot,fx19880617/pinot-1,sajavadi/pinot,linkedin/pinot,fx19880617/pinot-1,fx19880617/pinot-1,linkedin/pinot,sajavadi/pinot,apucher/pinot,apucher/pinot,sajavadi/pinot,linkedin/pinot
be11a093b0491fb1542dba0adfea6202e4c9fbf1
watertemplate-engine/grammar.g4
watertemplate-engine/grammar.g4
============================================== grammar ============================================== prop_name_head : Upper- or lowercase letter A through Z ; prop_name_body : | prop_name_head ; prop_name : prop_name_head | prop_name_head prop_name_body ; id : prop_name | prop_name.id ; --------------------------------------------- prop_eval : ~id~ ; if : ~if id: statements :~ | ~if id: statements :else: statements :~ ; for : ~for prop_name in id: statements :~ | ~for prop_name in id: statements :else: statements :~ ; text : Any string ; --------------------------------------------- statement : prop_eval | if | for | text | ε ; statements : statement | statement statements ;
Create grammar.g4
Create grammar.g4
ANTLR
apache-2.0
tiagobento/watertemplate-engine,codefacts/watertemplate-engine,codefacts/watertemplate-engine,tiagobento/watertemplate-engine
ce1ba5ae35aa6289fd32e09d897fba3f2f8cc64e
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
src/net/hillsdon/reviki/wiki/renderer/creole/CreoleTokens.g4
/* Todo: * - Comments justifying and explaining every rule. */ lexer grammar CreoleTokens; options { superClass=ContextSensitiveLexer; } @members { Formatting bold; Formatting italic; Formatting strike; public void setupFormatting() { bold = new Formatting("**"); italic = new Formatting("//"); strike = new Formatting("--"); inlineFormatting.add(bold); inlineFormatting.add(italic); inlineFormatting.add(strike); } public boolean inHeader = false; public boolean start = false; public int listLevel = 0; boolean nowiki = false; boolean cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = false; boolean intr = false; public void doHdr() { String prefix = getText().trim(); boolean seekback = false; if(!prefix.substring(prefix.length() - 1).equals("=")) { prefix = prefix.substring(0, prefix.length() - 1); seekback = true; } if(prefix.length() <= 6) { if(seekback) { seek(-1); } setText(prefix); inHeader = true; } else { setType(Any); } } public void setStart() { String next1 = next(); String next2 = get(1); start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#")); } public void doList(int level) { listLevel = level; seek(-1); setStart(); resetFormatting(); } public void doUrl() { String url = getText(); String last = url.substring(url.length()-1); String next = next(); if((last + next).equals("//") || last.equals(".") || last.equals(",") || last.equals(")")) { seek(-1); setText(url.substring(0, url.length() - 1)); } } public void breakOut() { resetFormatting(); listLevel = 0; inHeader = false; intr = false; nowiki = false; cpp = false; html = false; java = false; xhtml = false; xml = false; } public String[] thisKillsTheFormatting() { String[] ends = new String[4]; if(inHeader || intr || listLevel > 0) { ends[0] = "\n"; } else { ends[0] = null; } if(intr) { ends[1] = "|"; } else { ends[1] = null; } ends[2] = "\n\n"; ends[3] = "\r\n\r\n"; return ends; } public boolean checkWW() { String ww = getText(); String prior = get(-ww.length() - 1); String next = next(); return !(prior.matches("\\w") || next.matches("\\w")); } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' WS? {doHdr();} ; HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ; /* ***** Lists ***** */ U1 : START '*' ~'*' {doList(1);} ; U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ; U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ; U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ; U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ; O1 : START '#' ~'#' {doList(1);} ; O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ; O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ; O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ; O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+? {breakOut();} ; /* ***** Tables ***** */ TdStartLn : LINE '|' {intr=true; setType(TdStart);} ; ThStartLn : LINE '|=' {intr=true; setType(ThStart);} ; RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ; TdStart : '|' {intr}? {breakOut(); intr=true;} ; ThStart : '|=' {intr}? {breakOut(); intr=true;} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active}? {setFormatting(italic, Any);} ; SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ; BEnd : '**' {bold.active}? {unsetFormatting(bold);} ; IEnd : '//' {italic.active}? {unsetFormatting(italic);} ; SEnd : '--' {strike.active}? {unsetFormatting(strike);} ; NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ; StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ; StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ; StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ; StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ; StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ; /* ***** Links ***** */ LiSt : '[[' -> mode(LINK) ; ImSt : '{{' -> mode(LINK) ; /* ***** Breaks ***** */ InlineBrk : '\\\\' ; ParBreak : LineBreak LineBreak+ {breakOut();} ; LineBreak : '\r'? '\n' ; /* ***** Links ***** */ RawUrl : (('http' 's'? | 'ftp') '://' | 'mailto:') (~(' '|'\t'|'\r'|'\n'|'/'|'|'|'['|']')+ '/'?)+ {doUrl();}; WikiWords : ((INTERWIKI UPNUM | UPPER) (ABBR | CAMEL) | INTERWIKI UPNUM+) {checkWW()}? ; fragment INTERWIKI : ALPHA+ ':' ; fragment ABBR : UPPER UPPER+ ; fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ; /* ***** Macros ***** */ MacroSt : '<<' -> mode(MACRO) ; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t')+ ; fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ; fragment START : {start}? | LINE ; fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*; fragment LOWNUM : (LOWER | DIGIT) ; fragment UPNUM : (UPPER | DIGIT) ; fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ; ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ; Sep : ' '* '|' ' '*; InLink : ~(']'|'}'|'|'|'\r'|'\n')+ {setText(getText().trim());}; mode MACRO; MacroName : ~(':'|'>')+ ; MacroSep : ':' -> mode(MACRO_ARGS) ; mode MACRO_ARGS; MacroArgs : . -> more ; MacroEnd : '>>' -> mode(DEFAULT_MODE) ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' (~'}' {seek(-1);} | EOF) {nowiki}? -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
/* Todo: * - Comments justifying and explaining every rule. */ lexer grammar CreoleTokens; options { superClass=ContextSensitiveLexer; } @members { Formatting bold; Formatting italic; Formatting strike; public void setupFormatting() { bold = new Formatting("**"); italic = new Formatting("//"); strike = new Formatting("--"); inlineFormatting.add(bold); inlineFormatting.add(italic); inlineFormatting.add(strike); } public boolean inHeader = false; public boolean start = false; public int listLevel = 0; boolean nowiki = false; boolean cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = false; boolean intr = false; public void doHdr() { String prefix = getText().trim(); boolean seekback = false; if(!prefix.substring(prefix.length() - 1).equals("=")) { prefix = prefix.substring(0, prefix.length() - 1); seekback = true; } if(prefix.length() <= 6) { if(seekback) { seek(-1); } setText(prefix); inHeader = true; } else { setType(Any); } } public void setStart() { String next1 = next(); String next2 = get(1); start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#")); } public void doList(int level) { listLevel = level; seek(-1); setStart(); resetFormatting(); } public void doUrl() { String url = getText(); String last = url.substring(url.length()-1); String next = next(); if((last + next).equals("//") || last.equals(".") || last.equals(",") || last.equals(")")) { seek(-1); setText(url.substring(0, url.length() - 1)); } } public void breakOut() { resetFormatting(); listLevel = 0; inHeader = false; intr = false; nowiki = false; cpp = false; html = false; java = false; xhtml = false; xml = false; } public String[] thisKillsTheFormatting() { String[] ends = new String[4]; if(inHeader || intr || listLevel > 0) { ends[0] = "\n"; } else { ends[0] = null; } if(intr) { ends[1] = "|"; } else { ends[1] = null; } ends[2] = "\n\n"; ends[3] = "\r\n\r\n"; return ends; } public boolean checkWW() { String ww = getText(); String prior = (_input.index() > ww.length()) ? get(-ww.length() - 1) : ""; String next = next(); return !(prior.matches("\\w") || next.matches("\\w")); } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' WS? {doHdr();} ; HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ; /* ***** Lists ***** */ U1 : START '*' ~'*' {doList(1);} ; U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ; U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ; U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ; U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ; O1 : START '#' ~'#' {doList(1);} ; O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ; O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ; O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ; O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+? {breakOut();} ; /* ***** Tables ***** */ TdStartLn : LINE '|' {intr=true; setType(TdStart);} ; ThStartLn : LINE '|=' {intr=true; setType(ThStart);} ; RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ; TdStart : '|' {intr}? {breakOut(); intr=true;} ; ThStart : '|=' {intr}? {breakOut(); intr=true;} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active}? {setFormatting(italic, Any);} ; SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ; BEnd : '**' {bold.active}? {unsetFormatting(bold);} ; IEnd : '//' {italic.active}? {unsetFormatting(italic);} ; SEnd : '--' {strike.active}? {unsetFormatting(strike);} ; NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ; StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ; StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ; StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ; StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ; StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ; /* ***** Links ***** */ LiSt : '[[' -> mode(LINK) ; ImSt : '{{' -> mode(LINK) ; /* ***** Breaks ***** */ InlineBrk : '\\\\' ; ParBreak : LineBreak LineBreak+ {breakOut();} ; LineBreak : '\r'? '\n' ; /* ***** Links ***** */ RawUrl : (('http' 's'? | 'ftp') '://' | 'mailto:') (~(' '|'\t'|'\r'|'\n'|'/'|'|'|'['|']')+ '/'?)+ {doUrl();}; WikiWords : ((INTERWIKI UPNUM | UPPER) (ABBR | CAMEL) | INTERWIKI UPNUM+) {checkWW()}? ; fragment INTERWIKI : ALPHA+ ':' ; fragment ABBR : UPPER UPPER+ ; fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ; /* ***** Macros ***** */ MacroSt : '<<' -> mode(MACRO) ; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t')+ ; fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ; fragment START : {start}? | LINE ; fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*; fragment LOWNUM : (LOWER | DIGIT) ; fragment UPNUM : (UPPER | DIGIT) ; fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ; ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ; Sep : ' '* '|' ' '*; InLink : ~(']'|'}'|'|'|'\r'|'\n')+ {setText(getText().trim());}; mode MACRO; MacroName : ~(':'|'>')+ ; MacroSep : ':' -> mode(MACRO_ARGS) ; mode MACRO_ARGS; MacroArgs : . -> more ; MacroEnd : '>>' -> mode(DEFAULT_MODE) ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' (~'}' {seek(-1);} | EOF) {nowiki}? -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
Handle the case of WikiWords at the start of the page
Handle the case of WikiWords at the start of the page
ANTLR
apache-2.0
CoreFiling/reviki,strr/reviki,strr/reviki,ashirley/reviki,CoreFiling/reviki,ashirley/reviki,CoreFiling/reviki,strr/reviki,ashirley/reviki,strr/reviki,CoreFiling/reviki,strr/reviki,ashirley/reviki,CoreFiling/reviki,ashirley/reviki
dcee7c86c3a5f3bcb1e51caa0180704120338bdd
java/grammars/org/antlr/codebuff/SQLite.g4
java/grammars/org/antlr/codebuff/SQLite.g4
/* * The MIT License (MIT) * * Copyright (c) 2014 by Bart Kiers * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * Project : sqlite-parser; an ANTLR4 grammar for SQLite * https://github.com/bkiers/sqlite-parser * Developed by : Bart Kiers, [email protected] */ grammar SQLite; parse : ( sql_stmt_list | error )* EOF ; error : UNEXPECTED_CHAR { throw new RuntimeException("UNEXPECTED_CHAR=" + $UNEXPECTED_CHAR.text); } ; sql_stmt_list : ';'* sql_stmt ( ';'+ sql_stmt )* ';'* ; sql_stmt : ( K_EXPLAIN ( K_QUERY K_PLAN )? )? ( alter_table_stmt | analyze_stmt | attach_stmt | begin_stmt | commit_stmt | compound_select_stmt | create_index_stmt | create_table_stmt | create_trigger_stmt | create_view_stmt | create_virtual_table_stmt | delete_stmt | delete_stmt_limited | detach_stmt | drop_index_stmt | drop_table_stmt | drop_trigger_stmt | drop_view_stmt | factored_select_stmt | insert_stmt | pragma_stmt | reindex_stmt | release_stmt | rollback_stmt | savepoint_stmt | simple_select_stmt | select_stmt | update_stmt | update_stmt_limited | vacuum_stmt ) ; alter_table_stmt : K_ALTER K_TABLE ( database_name '.' )? table_name ( K_RENAME K_TO new_table_name | K_ADD K_COLUMN? column_def ) ; analyze_stmt : K_ANALYZE ( database_name | table_or_index_name | database_name '.' table_or_index_name )? ; attach_stmt : K_ATTACH K_DATABASE? expr K_AS database_name ; begin_stmt : K_BEGIN ( K_DEFERRED | K_IMMEDIATE | K_EXCLUSIVE )? ( K_TRANSACTION transaction_name? )? ; commit_stmt : ( K_COMMIT | K_END ) ( K_TRANSACTION transaction_name? )? ; compound_select_stmt : ( K_WITH K_RECURSIVE? common_table_expression ( ',' common_table_expression )* )? select_core ( ( K_UNION K_ALL? | K_INTERSECT | K_EXCEPT ) select_core )+ ( K_ORDER K_BY ordering_term ( ',' ordering_term )* )? ( K_LIMIT expr ( ( K_OFFSET | ',' ) expr )? )? ; create_index_stmt : K_CREATE K_UNIQUE? K_INDEX ( K_IF K_NOT K_EXISTS )? ( database_name '.' )? index_name K_ON table_name '(' indexed_column ( ',' indexed_column )* ')' ( K_WHERE expr )? ; create_table_stmt : K_CREATE ( K_TEMP | K_TEMPORARY )? K_TABLE ( K_IF K_NOT K_EXISTS )? ( database_name '.' )? table_name ( '(' column_def ( ',' column_def )* ( ',' table_constraint )* ')' ( K_WITHOUT IDENTIFIER )? | K_AS select_stmt ) ; create_trigger_stmt : K_CREATE ( K_TEMP | K_TEMPORARY )? K_TRIGGER ( K_IF K_NOT K_EXISTS )? ( database_name '.' )? trigger_name ( K_BEFORE | K_AFTER | K_INSTEAD K_OF )? ( K_DELETE | K_INSERT | K_UPDATE ( K_OF column_name ( ',' column_name )* )? ) K_ON ( database_name '.' )? table_name ( K_FOR K_EACH K_ROW )? ( K_WHEN expr )? K_BEGIN ( ( update_stmt | insert_stmt | delete_stmt | select_stmt ) ';' )+ K_END ; create_view_stmt : K_CREATE ( K_TEMP | K_TEMPORARY )? K_VIEW ( K_IF K_NOT K_EXISTS )? ( database_name '.' )? view_name K_AS select_stmt ; create_virtual_table_stmt : K_CREATE K_VIRTUAL K_TABLE ( K_IF K_NOT K_EXISTS )? ( database_name '.' )? table_name K_USING module_name ( '(' module_argument ( ',' module_argument )* ')' )? ; delete_stmt : with_clause? K_DELETE K_FROM qualified_table_name ( K_WHERE expr )? ; delete_stmt_limited : with_clause? K_DELETE K_FROM qualified_table_name ( K_WHERE expr )? ( ( K_ORDER K_BY ordering_term ( ',' ordering_term )* )? K_LIMIT expr ( ( K_OFFSET | ',' ) expr )? )? ; detach_stmt : K_DETACH K_DATABASE? database_name ; drop_index_stmt : K_DROP K_INDEX ( K_IF K_EXISTS )? ( database_name '.' )? index_name ; drop_table_stmt : K_DROP K_TABLE ( K_IF K_EXISTS )? ( database_name '.' )? table_name ; drop_trigger_stmt : K_DROP K_TRIGGER ( K_IF K_EXISTS )? ( database_name '.' )? trigger_name ; drop_view_stmt : K_DROP K_VIEW ( K_IF K_EXISTS )? ( database_name '.' )? view_name ; factored_select_stmt : ( K_WITH K_RECURSIVE? common_table_expression ( ',' common_table_expression )* )? select_core ( compound_operator select_core )* ( K_ORDER K_BY ordering_term ( ',' ordering_term )* )? ( K_LIMIT expr ( ( K_OFFSET | ',' ) expr )? )? ; insert_stmt : with_clause? ( K_INSERT | K_REPLACE | K_INSERT K_OR K_REPLACE | K_INSERT K_OR K_ROLLBACK | K_INSERT K_OR K_ABORT | K_INSERT K_OR K_FAIL | K_INSERT K_OR K_IGNORE ) K_INTO ( database_name '.' )? table_name ( '(' column_name ( ',' column_name )* ')' )? ( K_VALUES '(' expr ( ',' expr )* ')' ( ',' '(' expr ( ',' expr )* ')' )* | select_stmt | K_DEFAULT K_VALUES ) ; pragma_stmt : K_PRAGMA ( database_name '.' )? pragma_name ( '=' pragma_value | '(' pragma_value ')' )? ; reindex_stmt : K_REINDEX ( collation_name | ( database_name '.' )? ( table_name | index_name ) )? ; release_stmt : K_RELEASE K_SAVEPOINT? savepoint_name ; rollback_stmt : K_ROLLBACK ( K_TRANSACTION transaction_name? )? ( K_TO K_SAVEPOINT? savepoint_name )? ; savepoint_stmt : K_SAVEPOINT savepoint_name ; simple_select_stmt : ( K_WITH K_RECURSIVE? common_table_expression ( ',' common_table_expression )* )? select_core ( K_ORDER K_BY ordering_term ( ',' ordering_term )* )? ( K_LIMIT expr ( ( K_OFFSET | ',' ) expr )? )? ; select_stmt : ( K_WITH K_RECURSIVE? common_table_expression ( ',' common_table_expression )* )? select_or_values ( compound_operator select_or_values )* ( K_ORDER K_BY ordering_term ( ',' ordering_term )* )? ( K_LIMIT expr ( ( K_OFFSET | ',' ) expr )? )? ; select_or_values : K_SELECT ( K_DISTINCT | K_ALL )? result_column ( ',' result_column )* ( K_FROM ( table_or_subquery ( ',' table_or_subquery )* | join_clause ) )? ( K_WHERE expr )? ( K_GROUP K_BY expr ( ',' expr )* ( K_HAVING expr )? )? | K_VALUES '(' expr ( ',' expr )* ')' ( ',' '(' expr ( ',' expr )* ')' )* ; update_stmt : with_clause? K_UPDATE ( K_OR K_ROLLBACK | K_OR K_ABORT | K_OR K_REPLACE | K_OR K_FAIL | K_OR K_IGNORE )? qualified_table_name K_SET column_name '=' expr ( ',' column_name '=' expr )* ( K_WHERE expr )? ; update_stmt_limited : with_clause? K_UPDATE ( K_OR K_ROLLBACK | K_OR K_ABORT | K_OR K_REPLACE | K_OR K_FAIL | K_OR K_IGNORE )? qualified_table_name K_SET column_name '=' expr ( ',' column_name '=' expr )* ( K_WHERE expr )? ( ( K_ORDER K_BY ordering_term ( ',' ordering_term )* )? K_LIMIT expr ( ( K_OFFSET | ',' ) expr )? )? ; vacuum_stmt : K_VACUUM ; column_def : column_name type_name? column_constraint* ; type_name : name+ ( '(' signed_number ')' | '(' signed_number ',' signed_number ')' )? ; column_constraint : ( K_CONSTRAINT name )? ( K_PRIMARY K_KEY ( K_ASC | K_DESC )? conflict_clause K_AUTOINCREMENT? | K_NOT? K_NULL conflict_clause | K_UNIQUE conflict_clause | K_CHECK '(' expr ')' | K_DEFAULT (signed_number | literal_value | '(' expr ')') | K_COLLATE collation_name | foreign_key_clause ) ; conflict_clause : ( K_ON K_CONFLICT ( K_ROLLBACK | K_ABORT | K_FAIL | K_IGNORE | K_REPLACE ) )? ; /* SQLite understands the following binary operators, in order from highest to lowest precedence: || * / % + - << >> & | < <= > >= = == != <> IS IS NOT IN LIKE GLOB MATCH REGEXP AND OR */ expr : literal_value | BIND_PARAMETER | ( ( database_name '.' )? table_name '.' )? column_name | unary_operator expr | expr '||' expr | expr ( '*' | '/' | '%' ) expr | expr ( '+' | '-' ) expr | expr ( '<<' | '>>' | '&' | '|' ) expr | expr ( '<' | '<=' | '>' | '>=' ) expr | expr ( '=' | '==' | '!=' | '<>' | K_IS | K_IS K_NOT | K_IN | K_LIKE | K_GLOB | K_MATCH | K_REGEXP ) expr | expr K_AND expr | expr K_OR expr | function_name '(' ( K_DISTINCT? expr ( ',' expr )* | '*' )? ')' | '(' expr ')' | K_CAST '(' expr K_AS type_name ')' | expr K_COLLATE collation_name | expr K_NOT? ( K_LIKE | K_GLOB | K_REGEXP | K_MATCH ) expr ( K_ESCAPE expr )? | expr ( K_ISNULL | K_NOTNULL | K_NOT K_NULL ) | expr K_IS K_NOT? expr | expr K_NOT? K_BETWEEN expr K_AND expr | expr K_NOT? K_IN ( '(' ( select_stmt | expr ( ',' expr )* )? ')' | ( database_name '.' )? table_name ) | ( ( K_NOT )? K_EXISTS )? '(' select_stmt ')' | K_CASE expr? ( K_WHEN expr K_THEN expr )+ ( K_ELSE expr )? K_END | raise_function ; foreign_key_clause : K_REFERENCES foreign_table ( '(' column_name ( ',' column_name )* ')' )? ( ( K_ON ( K_DELETE | K_UPDATE ) ( K_SET K_NULL | K_SET K_DEFAULT | K_CASCADE | K_RESTRICT | K_NO K_ACTION ) | K_MATCH name ) )* ( K_NOT? K_DEFERRABLE ( K_INITIALLY K_DEFERRED | K_INITIALLY K_IMMEDIATE )? )? ; raise_function : K_RAISE '(' ( K_IGNORE | ( K_ROLLBACK | K_ABORT | K_FAIL ) ',' error_message ) ')' ; indexed_column : column_name ( K_COLLATE collation_name )? ( K_ASC | K_DESC )? ; table_constraint : ( K_CONSTRAINT name )? ( ( K_PRIMARY K_KEY | K_UNIQUE ) '(' indexed_column ( ',' indexed_column )* ')' conflict_clause | K_CHECK '(' expr ')' | K_FOREIGN K_KEY '(' column_name ( ',' column_name )* ')' foreign_key_clause ) ; with_clause : K_WITH K_RECURSIVE? cte_table_name K_AS '(' select_stmt ')' ( ',' cte_table_name K_AS '(' select_stmt ')' )* ; qualified_table_name : ( database_name '.' )? table_name ( K_INDEXED K_BY index_name | K_NOT K_INDEXED )? ; ordering_term : expr ( K_COLLATE collation_name )? ( K_ASC | K_DESC )? ; pragma_value : signed_number | name | STRING_LITERAL ; common_table_expression : table_name ( '(' column_name ( ',' column_name )* ')' )? K_AS '(' select_stmt ')' ; result_column : '*' | table_name '.' '*' | expr ( K_AS? column_alias )? ; table_or_subquery : ( database_name '.' )? table_name ( K_AS? table_alias )? ( K_INDEXED K_BY index_name | K_NOT K_INDEXED )? | '(' ( table_or_subquery ( ',' table_or_subquery )* | join_clause ) ')' ( K_AS? table_alias )? | '(' select_stmt ')' ( K_AS? table_alias )? ; join_clause : table_or_subquery ( join_operator table_or_subquery join_constraint )* ; join_operator : ',' | K_NATURAL? ( K_LEFT K_OUTER? | K_INNER | K_CROSS )? K_JOIN ; join_constraint : ( K_ON expr | K_USING '(' column_name ( ',' column_name )* ')' )? ; select_core : K_SELECT ( K_DISTINCT | K_ALL )? result_column ( ',' result_column )* ( K_FROM ( table_or_subquery ( ',' table_or_subquery )* | join_clause ) )? ( K_WHERE expr )? ( K_GROUP K_BY expr ( ',' expr )* ( K_HAVING expr )? )? | K_VALUES '(' expr ( ',' expr )* ')' ( ',' '(' expr ( ',' expr )* ')' )* ; compound_operator : K_UNION | K_UNION K_ALL | K_INTERSECT | K_EXCEPT ; cte_table_name : table_name ( '(' column_name ( ',' column_name )* ')' )? ; signed_number : ( '+' | '-' )? NUMERIC_LITERAL ; literal_value : NUMERIC_LITERAL | STRING_LITERAL | BLOB_LITERAL | K_NULL | K_CURRENT_TIME | K_CURRENT_DATE | K_CURRENT_TIMESTAMP ; unary_operator : '-' | '+' | '~' | K_NOT ; error_message : STRING_LITERAL ; module_argument // TODO check what exactly is permitted here : expr | column_def ; column_alias : IDENTIFIER | STRING_LITERAL ; keyword : K_ABORT | K_ACTION | K_ADD | K_AFTER | K_ALL | K_ALTER | K_ANALYZE | K_AND | K_AS | K_ASC | K_ATTACH | K_AUTOINCREMENT | K_BEFORE | K_BEGIN | K_BETWEEN | K_BY | K_CASCADE | K_CASE | K_CAST | K_CHECK | K_COLLATE | K_COLUMN | K_COMMIT | K_CONFLICT | K_CONSTRAINT | K_CREATE | K_CROSS | K_CURRENT_DATE | K_CURRENT_TIME | K_CURRENT_TIMESTAMP | K_DATABASE | K_DEFAULT | K_DEFERRABLE | K_DEFERRED | K_DELETE | K_DESC | K_DETACH | K_DISTINCT | K_DROP | K_EACH | K_ELSE | K_END | K_ESCAPE | K_EXCEPT | K_EXCLUSIVE | K_EXISTS | K_EXPLAIN | K_FAIL | K_FOR | K_FOREIGN | K_FROM | K_FULL | K_GLOB | K_GROUP | K_HAVING | K_IF | K_IGNORE | K_IMMEDIATE | K_IN | K_INDEX | K_INDEXED | K_INITIALLY | K_INNER | K_INSERT | K_INSTEAD | K_INTERSECT | K_INTO | K_IS | K_ISNULL | K_JOIN | K_KEY | K_LEFT | K_LIKE | K_LIMIT | K_MATCH | K_NATURAL | K_NO | K_NOT | K_NOTNULL | K_NULL | K_OF | K_OFFSET | K_ON | K_OR | K_ORDER | K_OUTER | K_PLAN | K_PRAGMA | K_PRIMARY | K_QUERY | K_RAISE | K_RECURSIVE | K_REFERENCES | K_REGEXP | K_REINDEX | K_RELEASE | K_RENAME | K_REPLACE | K_RESTRICT | K_RIGHT | K_ROLLBACK | K_ROW | K_SAVEPOINT | K_SELECT | K_SET | K_TABLE | K_TEMP | K_TEMPORARY | K_THEN | K_TO | K_TRANSACTION | K_TRIGGER | K_UNION | K_UNIQUE | K_UPDATE | K_USING | K_VACUUM | K_VALUES | K_VIEW | K_VIRTUAL | K_WHEN | K_WHERE | K_WITH | K_WITHOUT ; // TODO check all names below name : any_name ; function_name : any_name ; database_name : any_name ; table_name : any_name ; table_or_index_name : any_name ; new_table_name : any_name ; column_name : any_name ; collation_name : any_name ; foreign_table : any_name ; index_name : any_name ; trigger_name : any_name ; view_name : any_name ; module_name : any_name ; pragma_name : any_name ; savepoint_name : any_name ; table_alias : any_name ; transaction_name : any_name ; any_name : IDENTIFIER | keyword | STRING_LITERAL | '(' any_name ')' ; SCOL : ';'; DOT : '.'; OPEN_PAR : '('; CLOSE_PAR : ')'; COMMA : ','; ASSIGN : '='; STAR : '*'; PLUS : '+'; MINUS : '-'; TILDE : '~'; PIPE2 : '||'; DIV : '/'; MOD : '%'; LT2 : '<<'; GT2 : '>>'; AMP : '&'; PIPE : '|'; LT : '<'; LT_EQ : '<='; GT : '>'; GT_EQ : '>='; EQ : '=='; NOT_EQ1 : '!='; NOT_EQ2 : '<>'; // http://www.sqlite.org/lang_keywords.html K_ABORT : A B O R T; K_ACTION : A C T I O N; K_ADD : A D D; K_AFTER : A F T E R; K_ALL : A L L; K_ALTER : A L T E R; K_ANALYZE : A N A L Y Z E; K_AND : A N D; K_AS : A S; K_ASC : A S C; K_ATTACH : A T T A C H; K_AUTOINCREMENT : A U T O I N C R E M E N T; K_BEFORE : B E F O R E; K_BEGIN : B E G I N; K_BETWEEN : B E T W E E N; K_BY : B Y; K_CASCADE : C A S C A D E; K_CASE : C A S E; K_CAST : C A S T; K_CHECK : C H E C K; K_COLLATE : C O L L A T E; K_COLUMN : C O L U M N; K_COMMIT : C O M M I T; K_CONFLICT : C O N F L I C T; K_CONSTRAINT : C O N S T R A I N T; K_CREATE : C R E A T E; K_CROSS : C R O S S; K_CURRENT_DATE : C U R R E N T '_' D A T E; K_CURRENT_TIME : C U R R E N T '_' T I M E; K_CURRENT_TIMESTAMP : C U R R E N T '_' T I M E S T A M P; K_DATABASE : D A T A B A S E; K_DEFAULT : D E F A U L T; K_DEFERRABLE : D E F E R R A B L E; K_DEFERRED : D E F E R R E D; K_DELETE : D E L E T E; K_DESC : D E S C; K_DETACH : D E T A C H; K_DISTINCT : D I S T I N C T; K_DROP : D R O P; K_EACH : E A C H; K_ELSE : E L S E; K_END : E N D; K_ESCAPE : E S C A P E; K_EXCEPT : E X C E P T; K_EXCLUSIVE : E X C L U S I V E; K_EXISTS : E X I S T S; K_EXPLAIN : E X P L A I N; K_FAIL : F A I L; K_FOR : F O R; K_FOREIGN : F O R E I G N; K_FROM : F R O M; K_FULL : F U L L; K_GLOB : G L O B; K_GROUP : G R O U P; K_HAVING : H A V I N G; K_IF : I F; K_IGNORE : I G N O R E; K_IMMEDIATE : I M M E D I A T E; K_IN : I N; K_INDEX : I N D E X; K_INDEXED : I N D E X E D; K_INITIALLY : I N I T I A L L Y; K_INNER : I N N E R; K_INSERT : I N S E R T; K_INSTEAD : I N S T E A D; K_INTERSECT : I N T E R S E C T; K_INTO : I N T O; K_IS : I S; K_ISNULL : I S N U L L; K_JOIN : J O I N; K_KEY : K E Y; K_LEFT : L E F T; K_LIKE : L I K E; K_LIMIT : L I M I T; K_MATCH : M A T C H; K_NATURAL : N A T U R A L; K_NO : N O; K_NOT : N O T; K_NOTNULL : N O T N U L L; K_NULL : N U L L; K_OF : O F; K_OFFSET : O F F S E T; K_ON : O N; K_OR : O R; K_ORDER : O R D E R; K_OUTER : O U T E R; K_PLAN : P L A N; K_PRAGMA : P R A G M A; K_PRIMARY : P R I M A R Y; K_QUERY : Q U E R Y; K_RAISE : R A I S E; K_RECURSIVE : R E C U R S I V E; K_REFERENCES : R E F E R E N C E S; K_REGEXP : R E G E X P; K_REINDEX : R E I N D E X; K_RELEASE : R E L E A S E; K_RENAME : R E N A M E; K_REPLACE : R E P L A C E; K_RESTRICT : R E S T R I C T; K_RIGHT : R I G H T; K_ROLLBACK : R O L L B A C K; K_ROW : R O W; K_SAVEPOINT : S A V E P O I N T; K_SELECT : S E L E C T; K_SET : S E T; K_TABLE : T A B L E; K_TEMP : T E M P; K_TEMPORARY : T E M P O R A R Y; K_THEN : T H E N; K_TO : T O; K_TRANSACTION : T R A N S A C T I O N; K_TRIGGER : T R I G G E R; K_UNION : U N I O N; K_UNIQUE : U N I Q U E; K_UPDATE : U P D A T E; K_USING : U S I N G; K_VACUUM : V A C U U M; K_VALUES : V A L U E S; K_VIEW : V I E W; K_VIRTUAL : V I R T U A L; K_WHEN : W H E N; K_WHERE : W H E R E; K_WITH : W I T H; K_WITHOUT : W I T H O U T; IDENTIFIER : '"' (~'"' | '""')* '"' | '`' (~'`' | '``')* '`' | '[' ~']'* ']' | [a-zA-Z_] [a-zA-Z_0-9]* // TODO check: needs more chars in set ; NUMERIC_LITERAL : DIGIT+ ( '.' DIGIT* )? ( E [-+]? DIGIT+ )? | '.' DIGIT+ ( E [-+]? DIGIT+ )? ; BIND_PARAMETER : '?' DIGIT* | [:@$] IDENTIFIER ; STRING_LITERAL : '\'' ( ~'\'' | '\'\'' )* '\'' ; BLOB_LITERAL : X STRING_LITERAL ; SINGLE_LINE_COMMENT : '--' ~[\r\n]* -> channel(HIDDEN) ; MULTILINE_COMMENT : '/*' .*? ( '*/' | EOF ) -> channel(HIDDEN) ; SPACES : [ \u000B\t\r\n] -> channel(HIDDEN) ; UNEXPECTED_CHAR : . ; fragment DIGIT : [0-9]; fragment A : [aA]; fragment B : [bB]; fragment C : [cC]; fragment D : [dD]; fragment E : [eE]; fragment F : [fF]; fragment G : [gG]; fragment H : [hH]; fragment I : [iI]; fragment J : [jJ]; fragment K : [kK]; fragment L : [lL]; fragment M : [mM]; fragment N : [nN]; fragment O : [oO]; fragment P : [pP]; fragment Q : [qQ]; fragment R : [rR]; fragment S : [sS]; fragment T : [tT]; fragment U : [uU]; fragment V : [vV]; fragment W : [wW]; fragment X : [xX]; fragment Y : [yY]; fragment Z : [zZ];
add grammar
add grammar
ANTLR
bsd-2-clause
antlr/codebuff,antlr/codebuff,antlr/codebuff
66efa8a953e33d1eda7199afd78a4117400abd38
src/grammar/LLS1.g4
src/grammar/LLS1.g4
// LLS1 (Logical specification language-1) grammar LLS1; statements : (statement '.')+ ; //---------------------------------------------------------- // C,L,P-terms and statement //---------------------------------------------------------- c : Name # NamedC | 'NOT' c # notC | c ':' variable # conceptVariableC | c 'AND' c # andC | c 'OR' c # orC | c 'THAT' p # thatC | 'THOSE' p # thoseC | '(' c ')' # bracketedC ; l : Name # NamedL | 'NOT' l # notL | l 'AND' l # andL | l 'OR' l # orL | 'INV' '(' l ')' # invL | '(' l ')' # bracketedL ; p : 'NOT' p # notP | p 'AND' p # andP | p 'OR' p # orP | l 'SOME' c # someP | l 'EACH' c # eachP | l 'ONLY' c # onlyP | '(' l variable ')' # predicateVariableP | '(' l surrogate ')' # surrogateVariableP | '(' p ')' # bracketedP ; statement : 'NOT' statement # notStatement | statement 'AND' statement # andStatement | statement 'OR' statement # orStatement | statement 'IMP' statement # impStatement | 'EXIST' c # existCStatement | 'EXIST' l # existLStatement | 'NULL' c # nullCStatement | 'NULL' l # nullLStatement | c 'ISA' c # isaCStatement | l 'ISA' l # isaLStatement | c '=' c # equalsCStatement | l '=' l # equalsLStatement | p '=' p # equalsPStatement | c '=' 'NOT' c # notEqualsCStatement | l '=' 'NOT' l # notEqualsLStatement | 'EACH' c p # eachStatement | 'SOME' c p # someStatement | '(' statement ')' # bracketedStatement ; variable : Name; surrogate : Name; //---------------------------------------------------------- // Tokens //---------------------------------------------------------- Name : [a-zA-Z0-9_\-\u0410-\u044F]+ ; Comment : ('//' ~[\r\n]* | '/*' .*? '*/') -> skip ; Space : [ \t\r\n\u000C] -> skip ;
Add grammar for LLS1
Add grammar for LLS1
ANTLR
mit
DMasherov/bkm-lib
f97d1e038e14825964c757f16080f755dc656dd5
sharding-core/sharding-core-parse/sharding-core-parse-sqlserver/src/main/antlr4/imports/sqlserver/DDLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-sqlserver/src/main/antlr4/imports/sqlserver/DDLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE TABLE tableName fileTableClause_ createDefinitionClause_ ; createIndex : CREATE createIndexSpecification_ INDEX indexName ON tableName columnNames ; alterTable : ALTER TABLE tableName alterClause_ ; alterIndex : ALTER INDEX (indexName | ALL) ON tableName ; dropTable : DROP TABLE (IF EXISTS)? tableName (COMMA_ tableName)* ; dropIndex : DROP INDEX (IF EXISTS)? indexName ON tableName ; truncateTable : TRUNCATE TABLE tableName ; fileTableClause_ : (AS FILETABLE)? ; createDefinitionClause_ : createTableDefinitions_ partitionScheme_ fileGroup_ ; createTableDefinitions_ : LP_ createTableDefinition_ (COMMA_ createTableDefinition_)* (COMMA_ periodClause)? RP_ ; createTableDefinition_ : columnDefinition | computedColumnDefinition | columnSetDefinition | tableConstraint | tableIndex ; columnDefinition : columnName dataType columnDefinitionOption* columnConstraints columnIndex? ; columnDefinitionOption : FILESTREAM | COLLATE collationName | SPARSE | MASKED WITH LP_ FUNCTION EQ_ STRING_ RP_ | (CONSTRAINT ignoredIdentifier_)? DEFAULT expr | IDENTITY (LP_ NUMBER_ COMMA_ NUMBER_ RP_)? | NOT FOR REPLICATION | GENERATED ALWAYS AS ROW (START | END) HIDDEN_? | NOT? NULL | ROWGUIDCOL | ENCRYPTED WITH LP_ COLUMN_ENCRYPTION_KEY EQ_ ignoredIdentifier_ COMMA_ ENCRYPTION_TYPE EQ_ (DETERMINISTIC | RANDOMIZED) COMMA_ ALGORITHM EQ_ STRING_ RP_ | columnConstraint (COMMA_ columnConstraint)* | columnIndex ; columnConstraint : (CONSTRAINT ignoredIdentifier_)? (primaryKeyConstraint | columnForeignKeyConstraint | checkConstraint) ; primaryKeyConstraint : (primaryKey | UNIQUE) (diskTablePrimaryKeyConstraintOption | memoryTablePrimaryKeyConstraintOption) ; diskTablePrimaryKeyConstraintOption : (CLUSTERED | NONCLUSTERED)? primaryKeyWithClause? primaryKeyOnClause? ; primaryKeyWithClause : WITH (FILLFACTOR EQ_ NUMBER_ | LP_ indexOption (COMMA_ indexOption)* RP_) ; primaryKeyOnClause : onSchemaColumn | onFileGroup | onString ; onSchemaColumn : ON schemaName LP_ columnName RP_ ; onFileGroup : ON ignoredIdentifier_ ; onString : ON STRING_ ; memoryTablePrimaryKeyConstraintOption : CLUSTERED withBucket? ; withBucket : WITH LP_ BUCKET_COUNT EQ_ NUMBER_ RP_ ; columnForeignKeyConstraint : (FOREIGN KEY)? REFERENCES tableName LP_ columnName RP_ foreignKeyOnAction* ; foreignKeyOnAction : ON (DELETE | UPDATE) foreignKeyOn | NOT FOR REPLICATION ; foreignKeyOn : NO ACTION | CASCADE | SET (NULL | DEFAULT) ; checkConstraint : CHECK(NOT FOR REPLICATION)? LP_ expr RP_ ; columnIndex : INDEX indexName (CLUSTERED | NONCLUSTERED)? (WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause? (FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))? ; indexOnClause : onSchemaColumn | onFileGroup | onDefault ; onDefault : ON DEFAULT ; columnConstraints : (columnConstraint(COMMA_ columnConstraint)*)? ; computedColumnDefinition : columnName AS expr (PERSISTED(NOT NULL)?)? columnConstraint? ; columnSetDefinition : ignoredIdentifier_ IDENTIFIER_ COLUMN_SET FOR ALL_SPARSE_COLUMNS ; tableConstraint : (CONSTRAINT ignoredIdentifier_)? (tablePrimaryConstraint | tableForeignKeyConstraint | checkConstraint) ; tablePrimaryConstraint : primaryKeyUnique (diskTablePrimaryConstraintOption | memoryTablePrimaryConstraintOption) ; primaryKeyUnique : primaryKey | UNIQUE ; diskTablePrimaryConstraintOption : (CLUSTERED | NONCLUSTERED)? columnNames primaryKeyWithClause? primaryKeyOnClause? ; memoryTablePrimaryConstraintOption : NONCLUSTERED (columnNames | hashWithBucket) ; hashWithBucket : HASH columnNames withBucket ; tableForeignKeyConstraint : (FOREIGN KEY)? columnNames REFERENCES tableName columnNames foreignKeyOnAction* ; tableIndex : INDEX indexName ((CLUSTERED | NONCLUSTERED)? columnNames | CLUSTERED COLUMNSTORE | NONCLUSTERED? (COLUMNSTORE columnNames | hashWithBucket) | CLUSTERED COLUMNSTORE (WITH LP_ COMPRESSION_DELAY EQ_ (NUMBER_ MINUTES?) RP_)?) (WHERE expr)? (WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause? (FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))? ; createIndexSpecification_ : UNIQUE? (CLUSTERED | NONCLUSTERED)? ; alterClause_ : modifyColumnSpecification | addColumnSpecification | alterDrop | alterCheckConstraint | alterTrigger | alterSwitch | alterSet | alterTableTableOption | REBUILD ; modifyColumnSpecification : alterColumnOperation dataType (COLLATE collationName)? (NULL | NOT NULL)? SPARSE? ; alterColumnOperation : ALTER COLUMN columnName ; addColumnSpecification : (WITH (CHECK | NOCHECK))? ADD (alterColumnAddOptions | generatedColumnNamesClause) ; alterColumnAddOptions : alterColumnAddOption (COMMA_ alterColumnAddOption)* ; alterColumnAddOption : columnDefinition | computedColumnDefinition | columnSetDefinition | tableConstraint | alterTableTableIndex | constraintForColumn ; constraintForColumn : (CONSTRAINT ignoredIdentifier_)? DEFAULT simpleExpr FOR columnName ; columnNameWithSortsWithParen : LP_ columnNameWithSort (COMMA_ columnNameWithSort)* RP_ ; columnNameWithSort : columnName (ASC | DESC)? ; generatedColumnNamesClause : generatedColumnNameClause COMMA_ periodClause | periodClause COMMA_ generatedColumnNameClause ; generatedColumnNameClause : generatedColumnName DEFAULT simpleExpr (WITH VALUES)? COMMA_ generatedColumnName ; generatedColumnName : columnName dataTypeName_ GENERATED ALWAYS AS ROW (START | END)? HIDDEN_? (NOT NULL)? (CONSTRAINT ignoredIdentifier_)? ; 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_ ; alterDrop : DROP ( alterTableDropConstraint | dropColumnSpecification | dropIndexSpecification | PERIOD FOR SYSTEM_TIME ) ; alterTableDropConstraint : CONSTRAINT? (IF EXISTS)? dropConstraintName (COMMA_ dropConstraintName)* ; dropConstraintName : ignoredIdentifier_ dropConstraintWithClause? ; dropConstraintWithClause : WITH LP_ dropConstraintOption (COMMA_ dropConstraintOption)* RP_ ; dropConstraintOption : (MAXDOP EQ_ NUMBER_ | ONLINE EQ_ (ON | OFF) | MOVE TO (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_)) ; dropColumnSpecification : COLUMN (IF EXISTS)? columnName (COMMA_ columnName)* ; dropIndexSpecification : INDEX (IF EXISTS)? indexName (COMMA_ indexName)* ; alterCheckConstraint : WITH? (CHECK | NOCHECK) CONSTRAINT (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*)) ; alterTrigger : (ENABLE| DISABLE) TRIGGER (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*)) ; alterSwitch : SWITCH (PARTITION expr)? TO tableName (PARTITION expr)? (WITH LP_ lowPriorityLockWait RP_)? ; alterSet : SET LP_ (setFileStreamClause | setSystemVersionClause) RP_ ; setFileStreamClause : FILESTREAM_ON EQ_ (schemaName | ignoredIdentifier_ | STRING_) ; setSystemVersionClause : SYSTEM_VERSIONING EQ_ (OFF | alterSetOnClause) ; alterSetOnClause : ON ( LP_ (HISTORY_TABLE EQ_ tableName)? (COMMA_? DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? (COMMA_? HISTORY_RETENTION_PERIOD EQ_ (INFINITE | (NUMBER_ (DAY | DAYS | WEEK | WEEKS | MONTH | MONTHS | YEAR | YEARS))))? RP_ )? ; alterTableTableIndex : indexWithName (indexNonClusterClause | indexClusterClause) ; indexWithName : INDEX indexName ; indexNonClusterClause : NONCLUSTERED (hashWithBucket | (columnNameWithSortsWithParen alterTableIndexOnClause?)) ; alterTableIndexOnClause : ON ignoredIdentifier_ | DEFAULT ; indexClusterClause : CLUSTERED COLUMNSTORE (WITH COMPRESSION_DELAY EQ_ NUMBER_ MINUTES?)? indexOnClause? ; alterTableTableOption : SET LP_ LOCK_ESCALATION EQ_ (AUTO | TABLE | DISABLE) RP_ | MEMORY_OPTIMIZED EQ_ ON | DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA) | SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)? ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE TABLE tableName fileTableClause_ createDefinitionClause_ ; createIndex : CREATE createIndexSpecification_ INDEX indexName ON tableName columnNames ; alterTable : ALTER TABLE tableName alterClause_ ; alterIndex : ALTER INDEX (indexName | ALL) ON tableName ; dropTable : DROP TABLE (IF EXISTS)? tableName (COMMA_ tableName)* ; dropIndex : DROP INDEX (IF EXISTS)? indexName ON tableName ; truncateTable : TRUNCATE TABLE tableName ; fileTableClause_ : (AS FILETABLE)? ; createDefinitionClause_ : createTableDefinitions_ partitionScheme_ fileGroup_ ; createTableDefinitions_ : LP_ createTableDefinition_ (COMMA_ createTableDefinition_)* (COMMA_ periodClause)? RP_ ; createTableDefinition_ : columnDefinition | computedColumnDefinition | columnSetDefinition | tableConstraint | tableIndex ; columnDefinition : columnName dataType columnDefinitionOption* columnConstraints columnIndex? ; columnDefinitionOption : FILESTREAM | COLLATE collationName | SPARSE | MASKED WITH LP_ FUNCTION EQ_ STRING_ RP_ | (CONSTRAINT ignoredIdentifier_)? DEFAULT expr | IDENTITY (LP_ NUMBER_ COMMA_ NUMBER_ RP_)? | NOT FOR REPLICATION | GENERATED ALWAYS AS ROW (START | END) HIDDEN_? | NOT? NULL | ROWGUIDCOL | ENCRYPTED WITH LP_ COLUMN_ENCRYPTION_KEY EQ_ ignoredIdentifier_ COMMA_ ENCRYPTION_TYPE EQ_ (DETERMINISTIC | RANDOMIZED) COMMA_ ALGORITHM EQ_ STRING_ RP_ | columnConstraint (COMMA_ columnConstraint)* | columnIndex ; columnConstraint : (CONSTRAINT ignoredIdentifier_)? (primaryKeyConstraint | columnForeignKeyConstraint | checkConstraint) ; primaryKeyConstraint : (primaryKey | UNIQUE) (diskTablePrimaryKeyConstraintOption | memoryTablePrimaryKeyConstraintOption) ; diskTablePrimaryKeyConstraintOption : (CLUSTERED | NONCLUSTERED)? primaryKeyWithClause? primaryKeyOnClause? ; primaryKeyWithClause : WITH (FILLFACTOR EQ_ NUMBER_ | LP_ indexOption (COMMA_ indexOption)* RP_) ; primaryKeyOnClause : onSchemaColumn | onFileGroup | onString ; onSchemaColumn : ON schemaName LP_ columnName RP_ ; onFileGroup : ON ignoredIdentifier_ ; onString : ON STRING_ ; memoryTablePrimaryKeyConstraintOption : CLUSTERED withBucket? ; withBucket : WITH LP_ BUCKET_COUNT EQ_ NUMBER_ RP_ ; columnForeignKeyConstraint : (FOREIGN KEY)? REFERENCES tableName LP_ columnName RP_ foreignKeyOnAction* ; foreignKeyOnAction : ON (DELETE | UPDATE) foreignKeyOn | NOT FOR REPLICATION ; foreignKeyOn : NO ACTION | CASCADE | SET (NULL | DEFAULT) ; checkConstraint : CHECK(NOT FOR REPLICATION)? LP_ expr RP_ ; columnIndex : INDEX indexName (CLUSTERED | NONCLUSTERED)? (WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause? (FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))? ; indexOnClause : onSchemaColumn | onFileGroup | onDefault ; onDefault : ON DEFAULT ; columnConstraints : (columnConstraint(COMMA_ columnConstraint)*)? ; computedColumnDefinition : columnName AS expr (PERSISTED(NOT NULL)?)? columnConstraint? ; columnSetDefinition : ignoredIdentifier_ IDENTIFIER_ COLUMN_SET FOR ALL_SPARSE_COLUMNS ; tableConstraint : (CONSTRAINT ignoredIdentifier_)? (tablePrimaryConstraint | tableForeignKeyConstraint | checkConstraint) ; tablePrimaryConstraint : primaryKeyUnique (diskTablePrimaryConstraintOption | memoryTablePrimaryConstraintOption) ; primaryKeyUnique : primaryKey | UNIQUE ; diskTablePrimaryConstraintOption : (CLUSTERED | NONCLUSTERED)? columnNames primaryKeyWithClause? primaryKeyOnClause? ; memoryTablePrimaryConstraintOption : NONCLUSTERED (columnNames | hashWithBucket) ; hashWithBucket : HASH columnNames withBucket ; tableForeignKeyConstraint : (FOREIGN KEY)? columnNames REFERENCES tableName columnNames foreignKeyOnAction* ; tableIndex : INDEX indexName ((CLUSTERED | NONCLUSTERED)? columnNames | CLUSTERED COLUMNSTORE | NONCLUSTERED? (COLUMNSTORE columnNames | hashWithBucket) | CLUSTERED COLUMNSTORE (WITH LP_ COMPRESSION_DELAY EQ_ (NUMBER_ MINUTES?) RP_)?) (WHERE expr)? (WITH LP_ indexOption (COMMA_ indexOption)* RP_)? indexOnClause? (FILESTREAM_ON (ignoredIdentifier_ | schemaName | STRING_))? ; createIndexSpecification_ : UNIQUE? (CLUSTERED | NONCLUSTERED)? ; alterClause_ : modifyColumnSpecification | addColumnSpecification | alterDrop | alterCheckConstraint | alterTrigger | alterSwitch | alterSet | alterTableOption | REBUILD ; modifyColumnSpecification : alterColumnOperation dataType (COLLATE collationName)? (NULL | NOT NULL)? SPARSE? ; alterColumnOperation : ALTER COLUMN columnName ; addColumnSpecification : (WITH (CHECK | NOCHECK))? ADD (alterColumnAddOptions | generatedColumnNamesClause) ; alterColumnAddOptions : alterColumnAddOption (COMMA_ alterColumnAddOption)* ; alterColumnAddOption : columnDefinition | computedColumnDefinition | columnSetDefinition | tableConstraint | alterTableTableIndex | constraintForColumn ; constraintForColumn : (CONSTRAINT ignoredIdentifier_)? DEFAULT simpleExpr FOR columnName ; columnNameWithSortsWithParen : LP_ columnNameWithSort (COMMA_ columnNameWithSort)* RP_ ; columnNameWithSort : columnName (ASC | DESC)? ; generatedColumnNamesClause : generatedColumnNameClause COMMA_ periodClause | periodClause COMMA_ generatedColumnNameClause ; generatedColumnNameClause : generatedColumnName DEFAULT simpleExpr (WITH VALUES)? COMMA_ generatedColumnName ; generatedColumnName : columnName dataTypeName_ GENERATED ALWAYS AS ROW (START | END)? HIDDEN_? (NOT NULL)? (CONSTRAINT ignoredIdentifier_)? ; alterDrop : DROP (alterTableDropConstraint | dropColumnSpecification | dropIndexSpecification | PERIOD FOR SYSTEM_TIME) ; alterTableDropConstraint : CONSTRAINT? (IF EXISTS)? dropConstraintName (COMMA_ dropConstraintName)* ; dropConstraintName : ignoredIdentifier_ dropConstraintWithClause? ; dropConstraintWithClause : WITH LP_ dropConstraintOption (COMMA_ dropConstraintOption)* RP_ ; dropConstraintOption : (MAXDOP EQ_ NUMBER_ | ONLINE EQ_ (ON | OFF) | MOVE TO (schemaName LP_ columnName RP_ | ignoredIdentifier_ | STRING_)) ; dropColumnSpecification : COLUMN (IF EXISTS)? columnName (COMMA_ columnName)* ; dropIndexSpecification : INDEX (IF EXISTS)? indexName (COMMA_ indexName)* ; alterCheckConstraint : WITH? (CHECK | NOCHECK) CONSTRAINT (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*)) ; alterTrigger : (ENABLE| DISABLE) TRIGGER (ALL | (ignoredIdentifier_ (COMMA_ ignoredIdentifier_)*)) ; alterSwitch : SWITCH (PARTITION expr)? TO tableName (PARTITION expr)? (WITH LP_ lowPriorityLockWait RP_)? ; alterSet : SET LP_ (setFileStreamClause | setSystemVersionClause) RP_ ; setFileStreamClause : FILESTREAM_ON EQ_ (schemaName | ignoredIdentifier_ | STRING_) ; setSystemVersionClause : SYSTEM_VERSIONING EQ_ (OFF | ON alterSetOnClause?) ; alterSetOnClause : LP_ (HISTORY_TABLE EQ_ tableName)? dataConsistencyCheckClause_? historyRetentionPeriodClause_? RP_ ; dataConsistencyCheckClause_ : COMMA_? DATA_CONSISTENCY_CHECK EQ_ (ON | OFF) ; historyRetentionPeriodClause_ : COMMA_? HISTORY_RETENTION_PERIOD EQ_ historyRetentionPeriod ; historyRetentionPeriod : INFINITE | (NUMBER_ (DAY | DAYS | WEEK | WEEKS | MONTH | MONTHS | YEAR | YEARS)) ; alterTableTableIndex : indexWithName (indexNonClusterClause | indexClusterClause) ; indexWithName : INDEX indexName ; indexNonClusterClause : NONCLUSTERED (hashWithBucket | (columnNameWithSortsWithParen alterTableIndexOnClause?)) ; alterTableIndexOnClause : ON ignoredIdentifier_ | DEFAULT ; indexClusterClause : CLUSTERED COLUMNSTORE (WITH COMPRESSION_DELAY EQ_ NUMBER_ MINUTES?)? indexOnClause? ; alterTableOption : SET LP_ LOCK_ESCALATION EQ_ (AUTO | TABLE | DISABLE) RP_ | MEMORY_OPTIMIZED EQ_ ON | DURABILITY EQ_ (SCHEMA_ONLY | SCHEMA_AND_DATA) | SYSTEM_VERSIONING EQ_ ON (LP_ HISTORY_TABLE EQ_ tableName (COMMA_ DATA_CONSISTENCY_CHECK EQ_ (ON | OFF))? RP_)? ; 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_ ;
modify alterClause_ rule
modify alterClause_ rule
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
af47f7f19f1056ef0aeb62cf771941bc09033184
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.matches("[\\.,)\"]")) { seek(-1); setText(url.substring(0, url.length() - 1)); } } public void breakOut() { resetFormatting(); listLevel = 0; inHeader = false; intr = false; nowiki = false; cpp = false; html = false; java = false; xhtml = false; xml = false; } public String[] thisKillsTheFormatting() { String[] ends = new String[4]; if(inHeader || intr || listLevel > 0) { ends[0] = "\n"; } else { ends[0] = null; } if(intr) { ends[1] = "|"; } else { ends[1] = null; } ends[2] = "\n\n"; ends[3] = "\r\n\r\n"; return ends; } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' WS? {doHdr();} ; HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ; /* ***** Lists ***** */ U1 : START '*' ~'*' {doList(1);} ; U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ; U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ; U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ; U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ; U6 : START '******' ~'*' {listLevel >= 5}? {doList(6);} ; U7 : START '*******' ~'*' {listLevel >= 6}? {doList(7);} ; U8 : START '********' ~'*' {listLevel >= 7}? {doList(8);} ; U9 : START '*********' ~'*' {listLevel >= 8}? {doList(9);} ; U10 : START '**********' ~'*' {listLevel >= 9}? {doList(10);} ; O1 : START '#' ~'#' {doList(1);} ; O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ; O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ; O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ; O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ; O6 : START '######' ~'#' {listLevel >= 5}? {doList(6);} ; O7 : START '#######' ~'#' {listLevel >= 6}? {doList(7);} ; O8 : START '########' ~'#' {listLevel >= 7}? {doList(8);} ; O9 : START '#########' ~'#' {listLevel >= 8}? {doList(9);} ; O10 : START '##########' ~'#' {listLevel >= 9}? {doList(10);} ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+? {breakOut();} ; /* ***** Tables ***** */ TdStartLn : LINE '|' {intr=true; setType(TdStart);} ; ThStartLn : LINE '|=' {intr=true; setType(ThStart);} ; RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ; TdStart : '|' {intr}? {breakOut(); intr=true;} ; ThStart : '|=' {intr}? {breakOut(); intr=true;} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active}? {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();} ; Attachment : UPPER ALNUM* ALPHA ALNUM+ '.' LOWER LOWNUM+ {checkBounds("[a-zA-Z0-9@\\./=-]", "[a-zA-Z0-9@/=-]")}? ; WikiWords : ((INTERWIKI UPNUM | UPPER) (ABBR | CAMEL) | INTERWIKI UPNUM+) {checkBounds("[\\.\\w]", "\\w")}? ; fragment INTERWIKI : ALPHA ALNUM+ ':' ; fragment ABBR : UPPER UPPER+ ; fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ; /* ***** Macros ***** */ MacroSt : '<<' -> mode(MACRO) ; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t')+ ; fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ; fragment START : {start}? | LINE ; fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*; fragment LOWNUM : (LOWER | DIGIT) ; fragment UPNUM : (UPPER | DIGIT) ; fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ; ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ; Sep : ' '* '|' ' '*; InLink : ~(']'|'}'|'|'|'\r'|'\n')+ {setText(getText().trim());}; mode MACRO; MacroName : ~(':'|'>')+ ; MacroSep : ':' -> mode(MACRO_ARGS) ; mode MACRO_ARGS; MacroArgs : . -> more ; MacroEnd : '>>' -> mode(DEFAULT_MODE) ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' (~'}' {seek(-1);} | EOF) {nowiki}? -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
/* Todo: * - Comments justifying and explaining every rule. */ lexer grammar CreoleTokens; options { superClass=ContextSensitiveLexer; } @members { Formatting bold; Formatting italic; Formatting strike; public void setupFormatting() { bold = new Formatting("**"); italic = new Formatting("//"); strike = new Formatting("--"); inlineFormatting.add(bold); inlineFormatting.add(italic); inlineFormatting.add(strike); } public boolean inHeader = false; public boolean start = false; public int listLevel = 0; boolean nowiki = false; boolean cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = false; boolean intr = false; public void doHdr() { String prefix = getText().trim(); boolean seekback = false; if(!prefix.substring(prefix.length() - 1).equals("=")) { prefix = prefix.substring(0, prefix.length() - 1); seekback = true; } if(prefix.length() <= 6) { if(seekback) { seek(-1); } setText(prefix); inHeader = true; } else { setType(Any); } } public void setStart() { String next1 = next(); String next2 = get(1); start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#")); } public void doList(int level) { listLevel = level; seek(-1); setStart(); resetFormatting(); } public void doUrl() { String url = getText(); String last = url.substring(url.length()-1); String next = next(); if((last + next).equals("//") || last.matches("[\\.,)\"]")) { seek(-1); setText(url.substring(0, url.length() - 1)); } } public void breakOut() { resetFormatting(); listLevel = 0; inHeader = false; intr = false; nowiki = false; cpp = false; html = false; java = false; xhtml = false; xml = false; } public String[] thisKillsTheFormatting() { String[] ends = new String[4]; if(inHeader || intr || listLevel > 0) { ends[0] = "\n"; } else { ends[0] = null; } if(intr) { ends[1] = "|"; } else { ends[1] = null; } ends[2] = "\n\n"; ends[3] = "\r\n\r\n"; return ends; } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' WS? {doHdr();} ; HEnd : ' '* '='* (LineBreak | ParBreak) {inHeader}? {breakOut();} ; /* ***** Lists ***** */ U1 : START '*' ~'*' {doList(1);} ; U2 : START '**' ~'*' {listLevel >= 1}? {doList(2);} ; U3 : START '***' ~'*' {listLevel >= 2}? {doList(3);} ; U4 : START '****' ~'*' {listLevel >= 3}? {doList(4);} ; U5 : START '*****' ~'*' {listLevel >= 4}? {doList(5);} ; U6 : START '******' ~'*' {listLevel >= 5}? {doList(6);} ; U7 : START '*******' ~'*' {listLevel >= 6}? {doList(7);} ; U8 : START '********' ~'*' {listLevel >= 7}? {doList(8);} ; U9 : START '*********' ~'*' {listLevel >= 8}? {doList(9);} ; U10 : START '**********' ~'*' {listLevel >= 9}? {doList(10);} ; O1 : START '#' ~'#' {doList(1);} ; O2 : START '##' ~'#' {listLevel >= 1}? {doList(2);} ; O3 : START '###' ~'#' {listLevel >= 2}? {doList(3);} ; O4 : START '####' ~'#' {listLevel >= 3}? {doList(4);} ; O5 : START '#####' ~'#' {listLevel >= 4}? {doList(5);} ; O6 : START '######' ~'#' {listLevel >= 5}? {doList(6);} ; O7 : START '#######' ~'#' {listLevel >= 6}? {doList(7);} ; O8 : START '########' ~'#' {listLevel >= 7}? {doList(8);} ; O9 : START '#########' ~'#' {listLevel >= 8}? {doList(9);} ; O10 : START '##########' ~'#' {listLevel >= 9}? {doList(10);} ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+? {breakOut();} ; /* ***** Tables ***** */ TdStartLn : LINE '|' {intr=true; setType(TdStart);} ; ThStartLn : LINE '|=' {intr=true; setType(ThStart);} ; RowEnd : '|' WS? LineBreak {intr}? {breakOut();} ; TdStart : '|' {intr}? {breakOut(); intr=true;} ; ThStart : '|=' {intr}? {breakOut(); intr=true;} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active}? {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 : PROTOCOL (~(' '|'\t'|'\r'|'\n'|'|'|'['|']')+ '/'?)+ {doUrl();} ; fragment PROTOCOL : ('http' 's'? | 'file' | 'ftp') '://' | 'mailto:' ; Attachment : UPPER ALNUM* ALPHA ALNUM+ '.' LOWER LOWNUM+ {checkBounds("[a-zA-Z0-9@\\./=-]", "[a-zA-Z0-9@/=-]")}? ; WikiWords : ((INTERWIKI UPNUM | UPPER) (ABBR | CAMEL) | INTERWIKI UPNUM+) {checkBounds("[\\.\\w]", "\\w")}? ; fragment INTERWIKI : ALPHA ALNUM+ ':' ; fragment ABBR : UPPER UPPER+ ; fragment CAMEL : (LOWNUM* UPNUM ALNUM* LOWER ALNUM* | ALNUM* LOWER ALNUM* UPNUM+) ; /* ***** Macros ***** */ MacroSt : '<<' -> mode(MACRO) ; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t')+ ; fragment NOTALNUM : ~('A'..'Z'|'a'..'z'|'0'..'9') ; fragment START : {start}? | LINE ; fragment LINE : {getCharPositionInLine()==0}? (' '|'\t')*; fragment LOWNUM : (LOWER | DIGIT) ; fragment UPNUM : (UPPER | DIGIT) ; fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : (']]' | '\r'? '\n') -> mode(DEFAULT_MODE) ; ImEnd : ('}}' | '\r'? '\n') -> mode(DEFAULT_MODE) ; Sep : ' '* '|' ' '*; InLink : ~(']'|'}'|'|'|'\r'|'\n')+ {setText(getText().trim());}; mode MACRO; MacroName : ~(':'|'>')+ ; MacroSep : ':' -> mode(MACRO_ARGS) ; mode MACRO_ARGS; MacroArgs : . -> more ; MacroEnd : '>>' -> mode(DEFAULT_MODE) ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' (~'}' {seek(-1);} | EOF) {nowiki}? -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : ~' ' '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : ~' ' '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : ~' ' '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : ~' ' '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : ~' ' '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : ~' ' '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
Allow file:// raw urls
Allow file:// raw urls
ANTLR
apache-2.0
strr/reviki,strr/reviki,ashirley/reviki,strr/reviki,CoreFiling/reviki,CoreFiling/reviki,strr/reviki,ashirley/reviki,strr/reviki,CoreFiling/reviki,ashirley/reviki,ashirley/reviki,ashirley/reviki,CoreFiling/reviki,CoreFiling/reviki
cbb36f12618776325394b28081a20c56218ff55a
src/Track.g4
src/Track.g4
grammar Track; track: track_decl decl* ; track_decl: 'track' '{' IDENT+ '}' ; decl: block_decl | channel_decl ; block_decl: IDENT '::' 'block' '{' block_body '}' ; block_body: (note)+ ; note: NOTENAME OCTAVE? LENGTH? ; channel_decl: IDENT '::' 'channel' WAVE '{' channel_body '}' ; channel_body: (block_name)+ ; block_name: IDENT ; NOTENAME: 'Ab' | 'A' | 'A#' | 'Bb' | 'B' | 'C' | 'C#' | 'Db' | 'D' | 'D#' | 'Eb' | 'E' | 'F' | 'F#' | 'Gb' | 'G' | 'G#' | 'R' ; OCTAVE: [0-9] | '10' ; LENGTH: [-+.]+ ; WAVE: 'triangle' | 'square' | 'sawtooth' | 'noise' ; IDENT: [a-zA-Z][a-zA-Z0-9_]+ ; WS: [\t\r\n ]+ -> skip ;
Add first attempt at track grammar
Add first attempt at track grammar
ANTLR
mit
hdgarrood/klasma
24330893ab89730a585247345a58736253a5cebf
sharding-core/src/main/antlr4/imports/PostgreSQLDALStatement.g4
sharding-core/src/main/antlr4/imports/PostgreSQLDALStatement.g4
grammar PostgreSQLDALStatement; import PostgreSQLKeyword, Keyword, BaseRule, DataType, Symbol; show : SHOW showParam ; showParam : ALL | SERVER_VERSION ;
add pg dal g4
add pg dal g4
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
4e8df30012b876461014364d64bdc9390a95863b
src/main/antlr/ASP_Core2.g4
src/main/antlr/ASP_Core2.g4
grammar ASP_Core2; /* The ASP Core 2 grammar in ANTLR v4. It is extended a bit to parse widespread syntax used by gringo/clasp. */ program : statements? query?; statements : statement statements?; query : classical_literal QUERY_MARK; statement : CONS body DOT | head (CONS body?)? DOT | WCONS body? DOT SQUARE_OPEN weight_at_level SQUARE_CLOSE | gringo_sharp; // syntax extension head : disjunction | choice; body : ( naf_literal | NAF? aggregate ) (COMMA body)?; disjunction : classical_literal (OR disjunction)?; choice : (term binop)? CURLY_OPEN choice_elements? CURLY_CLOSE (binop term)?; choice_elements : choice_element (SEMICOLON choice_elements)?; choice_element : classical_literal (COLON naf_literals?)?; aggregate : (term binop)? aggregate_function CURLY_OPEN aggregate_elements CURLY_CLOSE (binop term)?; aggregate_elements : aggregate_element (SEMICOLON aggregate_elements)?; aggregate_element : basic_terms? (COLON naf_literals?)?; aggregate_function : AGGREGATE_COUNT | AGGREGATE_MAX | AGGREGATE_MIN | AGGREGATE_SUM; weight_at_level : term (AT term)? (COMMA terms)?; naf_literals : naf_literal (COMMA naf_literals)?; naf_literal : NAF? (classical_literal | builtin_atom); classical_literal : MINUS? ID (PAREN_OPEN terms PAREN_CLOSE)?; builtin_atom : term binop term; binop : EQUAL | UNEQUAL | LESS | GREATER | LESS_OR_EQ | GREATER_OR_EQ; terms : term (COMMA terms)?; term : ID (PAREN_OPEN terms? PAREN_CLOSE)? | NUMBER | STRING | VARIABLE | ANONYMOUS_VARIABLE | PAREN_OPEN term PAREN_CLOSE | MINUS term | term arithop term | gringo_range; // syntax extension gringo_range : (NUMBER | VARIABLE | ID) DOT DOT (NUMBER | VARIABLE | ID); // NOT Core2 syntax, but widespread gringo_sharp : SHARP ~(DOT)* DOT; // NOT Core2 syntax, but widespread, matching not perfect due to possible earlier dots basic_terms : basic_term (COMMA basic_terms)? ; basic_term : ground_term | variable_term; ground_term : /*SYMBOLIC_CONSTANT*/ ID | STRING | MINUS? NUMBER; variable_term : VARIABLE | ANONYMOUS_VARIABLE; arithop : PLUS | MINUS | TIMES | DIV; ANONYMOUS_VARIABLE : '_'; DOT : '.'; COMMA : ','; QUERY_MARK : '?'; COLON : ':'; SEMICOLON : ';'; OR : '|'; NAF : 'not'; CONS : ':-'; WCONS : ':~'; PLUS : '+'; MINUS : '-'; TIMES : '*'; DIV : '/'; AT : '@'; SHARP : '#'; // NOT Core2 syntax but gringo PAREN_OPEN : '('; PAREN_CLOSE : ')'; SQUARE_OPEN : '['; SQUARE_CLOSE : ']'; CURLY_OPEN : '{'; CURLY_CLOSE : '}'; EQUAL : '='; UNEQUAL : '<>' | '!='; LESS : '<'; GREATER : '>'; LESS_OR_EQ : '<='; GREATER_OR_EQ : '>='; AGGREGATE_COUNT : '#count'; AGGREGATE_MAX : '#max'; AGGREGATE_MIN : '#min'; AGGREGATE_SUM : '#sum'; ID : ('a'..'z') ( 'A'..'Z' | 'a'..'z' | '0'..'9' | '_' )*; VARIABLE : ('A'..'Z') ( 'A'..'Z' | 'a'..'z' | '0'..'9' | '_' )*; NUMBER : '0' | ('1'..'9') ('0'..'9')*; STRING : '"' ( '\\"' | . )*? '"'; COMMENT : '%' ~[\r\n]* -> channel(HIDDEN); MULTI_LINE_COMMEN : '%*' .*? '*%' -> channel(HIDDEN); BLANK : [ \t\r\n\f]+ -> channel(HIDDEN) ;
Add ASP-Core-2 grammar
Add ASP-Core-2 grammar
ANTLR
bsd-2-clause
AntoniusW/Alpha,alpha-asp/Alpha,alpha-asp/Alpha
22f1c9fa0faa18151207f993967c971444d6f04d
modules/lang-painless/src/main/antlr/PainlessLexer.g4
modules/lang-painless/src/main/antlr/PainlessLexer.g4
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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 PainlessLexer; @header { } @members{ /** * Check against the current whitelist to determine whether a token is a type * or not. Called by the {@code TYPE} token defined in {@code PainlessLexer.g4}. * See also * <a href="https://en.wikipedia.org/wiki/The_lexer_hack">The lexer hack</a>. */ protected abstract boolean isSimpleType(String name); /** * Is the preceding {@code /} a the beginning of a regex (true) or a division * (false). */ protected abstract boolean slashIsRegex(); } WS: [ \t\n\r]+ -> skip; COMMENT: ( '//' .*? [\n\r] | '/*' .*? '*/' ) -> skip; LBRACK: '{'; RBRACK: '}'; LBRACE: '['; RBRACE: ']'; LP: '('; RP: ')'; // We switch modes after a dot to ensure there are not conflicts // between shortcuts and decimal values. Without the mode switch // shortcuts such as id.0.0 will fail because 0.0 will be interpreted // as a decimal value instead of two individual list-style shortcuts. DOT: '.' -> mode(AFTER_DOT); NSDOT: '?.' -> mode(AFTER_DOT); COMMA: ','; SEMICOLON: ';'; IF: 'if'; IN: 'in'; ELSE: 'else'; WHILE: 'while'; DO: 'do'; FOR: 'for'; CONTINUE: 'continue'; BREAK: 'break'; RETURN: 'return'; NEW: 'new'; TRY: 'try'; CATCH: 'catch'; THROW: 'throw'; THIS: 'this'; INSTANCEOF: 'instanceof'; BOOLNOT: '!'; BWNOT: '~'; MUL: '*'; DIV: '/' { false == slashIsRegex() }?; REM: '%'; ADD: '+'; SUB: '-'; LSH: '<<'; RSH: '>>'; USH: '>>>'; LT: '<'; LTE: '<='; GT: '>'; GTE: '>='; EQ: '=='; EQR: '==='; NE: '!='; NER: '!=='; BWAND: '&'; XOR: '^'; BWOR: '|'; BOOLAND: '&&'; BOOLOR: '||'; COND: '?'; COLON: ':'; ELVIS: '?:'; REF: '::'; ARROW: '->'; FIND: '=~'; MATCH: '==~'; INCR: '++'; DECR: '--'; ASSIGN: '='; AADD: '+='; ASUB: '-='; AMUL: '*='; ADIV: '/='; AREM: '%='; AAND: '&='; AXOR: '^='; AOR: '|='; ALSH: '<<='; ARSH: '>>='; AUSH: '>>>='; OCTAL: '0' [0-7]+ [lL]?; HEX: '0' [xX] [0-9a-fA-F]+ [lL]?; INTEGER: ( '0' | [1-9] [0-9]* ) [lLfFdD]?; DECIMAL: ( '0' | [1-9] [0-9]* ) (DOT [0-9]+)? ( [eE] [+\-]? [0-9]+ )? [fFdD]?; STRING: ( '"' ( '\\"' | '\\\\' | ~[\\"] )*? '"' ) | ( '\'' ( '\\\'' | '\\\\' | ~[\\'] )*? '\'' ); REGEX: '/' ( ~('/' | '\n') | '\\' ~'\n' )+ '/' [cilmsUux]* { slashIsRegex() }?; TRUE: 'true'; FALSE: 'false'; NULL: 'null'; // The predicate here allows us to remove ambiguities when // dealing with types versus identifiers. We check against // the current whitelist to determine whether a token is a type // or not. Note this works by processing one character at a time // and the rule is added or removed as this happens. This is also known // as "the lexer hack." See (https://en.wikipedia.org/wiki/The_lexer_hack). TYPE: ID ( DOT ID )* { isSimpleType(getText()) }?; ID: [_a-zA-Z] [_a-zA-Z0-9]*; mode AFTER_DOT; DOTINTEGER: ( '0' | [1-9] [0-9]* ) -> mode(DEFAULT_MODE); DOTID: [_a-zA-Z] [_a-zA-Z0-9]* -> mode(DEFAULT_MODE);
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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 PainlessLexer; @members{ /** * Check against the current whitelist to determine whether a token is a type * or not. Called by the {@code TYPE} token defined in {@code PainlessLexer.g4}. * See also * <a href="https://en.wikipedia.org/wiki/The_lexer_hack">The lexer hack</a>. */ protected abstract boolean isSimpleType(String name); /** * Is the preceding {@code /} a the beginning of a regex (true) or a division * (false). */ protected abstract boolean slashIsRegex(); } WS: [ \t\n\r]+ -> skip; COMMENT: ( '//' .*? [\n\r] | '/*' .*? '*/' ) -> skip; LBRACK: '{'; RBRACK: '}'; LBRACE: '['; RBRACE: ']'; LP: '('; RP: ')'; // We switch modes after a dot to ensure there are not conflicts // between shortcuts and decimal values. Without the mode switch // shortcuts such as id.0.0 will fail because 0.0 will be interpreted // as a decimal value instead of two individual list-style shortcuts. DOT: '.' -> mode(AFTER_DOT); NSDOT: '?.' -> mode(AFTER_DOT); COMMA: ','; SEMICOLON: ';'; IF: 'if'; IN: 'in'; ELSE: 'else'; WHILE: 'while'; DO: 'do'; FOR: 'for'; CONTINUE: 'continue'; BREAK: 'break'; RETURN: 'return'; NEW: 'new'; TRY: 'try'; CATCH: 'catch'; THROW: 'throw'; THIS: 'this'; INSTANCEOF: 'instanceof'; BOOLNOT: '!'; BWNOT: '~'; MUL: '*'; DIV: '/' { false == slashIsRegex() }?; REM: '%'; ADD: '+'; SUB: '-'; LSH: '<<'; RSH: '>>'; USH: '>>>'; LT: '<'; LTE: '<='; GT: '>'; GTE: '>='; EQ: '=='; EQR: '==='; NE: '!='; NER: '!=='; BWAND: '&'; XOR: '^'; BWOR: '|'; BOOLAND: '&&'; BOOLOR: '||'; COND: '?'; COLON: ':'; ELVIS: '?:'; REF: '::'; ARROW: '->'; FIND: '=~'; MATCH: '==~'; INCR: '++'; DECR: '--'; ASSIGN: '='; AADD: '+='; ASUB: '-='; AMUL: '*='; ADIV: '/='; AREM: '%='; AAND: '&='; AXOR: '^='; AOR: '|='; ALSH: '<<='; ARSH: '>>='; AUSH: '>>>='; OCTAL: '0' [0-7]+ [lL]?; HEX: '0' [xX] [0-9a-fA-F]+ [lL]?; INTEGER: ( '0' | [1-9] [0-9]* ) [lLfFdD]?; DECIMAL: ( '0' | [1-9] [0-9]* ) (DOT [0-9]+)? ( [eE] [+\-]? [0-9]+ )? [fFdD]?; STRING: ( '"' ( '\\"' | '\\\\' | ~[\\"] )*? '"' ) | ( '\'' ( '\\\'' | '\\\\' | ~[\\'] )*? '\'' ); REGEX: '/' ( ~('/' | '\n') | '\\' ~'\n' )+ '/' [cilmsUux]* { slashIsRegex() }?; TRUE: 'true'; FALSE: 'false'; NULL: 'null'; // The predicate here allows us to remove ambiguities when // dealing with types versus identifiers. We check against // the current whitelist to determine whether a token is a type // or not. Note this works by processing one character at a time // and the rule is added or removed as this happens. This is also known // as "the lexer hack." See (https://en.wikipedia.org/wiki/The_lexer_hack). TYPE: ID ( DOT ID )* { isSimpleType(getText()) }?; ID: [_a-zA-Z] [_a-zA-Z0-9]*; mode AFTER_DOT; DOTINTEGER: ( '0' | [1-9] [0-9]* ) -> mode(DEFAULT_MODE); DOTID: [_a-zA-Z] [_a-zA-Z0-9]* -> mode(DEFAULT_MODE);
Remove @header we no longer need
Remove @header we no longer need
ANTLR
apache-2.0
coding0011/elasticsearch,HonzaKral/elasticsearch,ThiagoGarciaAlves/elasticsearch,C-Bish/elasticsearch,umeshdangat/elasticsearch,elasticdog/elasticsearch,geidies/elasticsearch,bawse/elasticsearch,ZTE-PaaS/elasticsearch,alexshadow007/elasticsearch,kalimatas/elasticsearch,JSCooke/elasticsearch,scorpionvicky/elasticsearch,sneivandt/elasticsearch,fernandozhu/elasticsearch,pozhidaevak/elasticsearch,mortonsykes/elasticsearch,MisterAndersen/elasticsearch,coding0011/elasticsearch,ThiagoGarciaAlves/elasticsearch,brandonkearby/elasticsearch,LeoYao/elasticsearch,StefanGor/elasticsearch,Helen-Zhao/elasticsearch,mjason3/elasticsearch,pozhidaevak/elasticsearch,gfyoung/elasticsearch,C-Bish/elasticsearch,glefloch/elasticsearch,ZTE-PaaS/elasticsearch,njlawton/elasticsearch,nezirus/elasticsearch,jprante/elasticsearch,StefanGor/elasticsearch,strapdata/elassandra,robin13/elasticsearch,markwalkom/elasticsearch,C-Bish/elasticsearch,scottsom/elasticsearch,jprante/elasticsearch,njlawton/elasticsearch,IanvsPoplicola/elasticsearch,wenpos/elasticsearch,LeoYao/elasticsearch,vroyer/elassandra,jimczi/elasticsearch,geidies/elasticsearch,nknize/elasticsearch,s1monw/elasticsearch,kalimatas/elasticsearch,winstonewert/elasticsearch,GlenRSmith/elasticsearch,mohit/elasticsearch,markwalkom/elasticsearch,nilabhsagar/elasticsearch,coding0011/elasticsearch,jimczi/elasticsearch,wangtuo/elasticsearch,i-am-Nathan/elasticsearch,gingerwizard/elasticsearch,maddin2016/elasticsearch,Helen-Zhao/elasticsearch,scottsom/elasticsearch,geidies/elasticsearch,alexshadow007/elasticsearch,bawse/elasticsearch,geidies/elasticsearch,LewayneNaidoo/elasticsearch,shreejay/elasticsearch,MisterAndersen/elasticsearch,gfyoung/elasticsearch,coding0011/elasticsearch,brandonkearby/elasticsearch,mortonsykes/elasticsearch,rlugojr/elasticsearch,uschindler/elasticsearch,mikemccand/elasticsearch,winstonewert/elasticsearch,fred84/elasticsearch,Shepard1212/elasticsearch,a2lin/elasticsearch,rlugojr/elasticsearch,umeshdangat/elasticsearch,wangtuo/elasticsearch,ZTE-PaaS/elasticsearch,mohit/elasticsearch,winstonewert/elasticsearch,uschindler/elasticsearch,fernandozhu/elasticsearch,rlugojr/elasticsearch,artnowo/elasticsearch,IanvsPoplicola/elasticsearch,nezirus/elasticsearch,LewayneNaidoo/elasticsearch,maddin2016/elasticsearch,nezirus/elasticsearch,ZTE-PaaS/elasticsearch,nknize/elasticsearch,artnowo/elasticsearch,GlenRSmith/elasticsearch,obourgain/elasticsearch,masaruh/elasticsearch,robin13/elasticsearch,i-am-Nathan/elasticsearch,qwerty4030/elasticsearch,StefanGor/elasticsearch,geidies/elasticsearch,alexshadow007/elasticsearch,IanvsPoplicola/elasticsearch,LeoYao/elasticsearch,shreejay/elasticsearch,ThiagoGarciaAlves/elasticsearch,masaruh/elasticsearch,gingerwizard/elasticsearch,Shepard1212/elasticsearch,qwerty4030/elasticsearch,StefanGor/elasticsearch,naveenhooda2000/elasticsearch,s1monw/elasticsearch,MisterAndersen/elasticsearch,winstonewert/elasticsearch,fernandozhu/elasticsearch,bawse/elasticsearch,fred84/elasticsearch,geidies/elasticsearch,lks21c/elasticsearch,s1monw/elasticsearch,mikemccand/elasticsearch,HonzaKral/elasticsearch,artnowo/elasticsearch,JackyMai/elasticsearch,Helen-Zhao/elasticsearch,jprante/elasticsearch,JackyMai/elasticsearch,JSCooke/elasticsearch,GlenRSmith/elasticsearch,lks21c/elasticsearch,mohit/elasticsearch,umeshdangat/elasticsearch,scottsom/elasticsearch,markwalkom/elasticsearch,njlawton/elasticsearch,obourgain/elasticsearch,pozhidaevak/elasticsearch,shreejay/elasticsearch,rajanm/elasticsearch,nazarewk/elasticsearch,nknize/elasticsearch,wenpos/elasticsearch,nezirus/elasticsearch,strapdata/elassandra,alexshadow007/elasticsearch,glefloch/elasticsearch,Helen-Zhao/elasticsearch,mjason3/elasticsearch,gingerwizard/elasticsearch,scottsom/elasticsearch,alexshadow007/elasticsearch,masaruh/elasticsearch,JackyMai/elasticsearch,maddin2016/elasticsearch,gingerwizard/elasticsearch,elasticdog/elasticsearch,bawse/elasticsearch,obourgain/elasticsearch,fernandozhu/elasticsearch,IanvsPoplicola/elasticsearch,mjason3/elasticsearch,wenpos/elasticsearch,robin13/elasticsearch,fred84/elasticsearch,qwerty4030/elasticsearch,mjason3/elasticsearch,gingerwizard/elasticsearch,JSCooke/elasticsearch,elasticdog/elasticsearch,uschindler/elasticsearch,winstonewert/elasticsearch,gingerwizard/elasticsearch,robin13/elasticsearch,jprante/elasticsearch,Helen-Zhao/elasticsearch,mikemccand/elasticsearch,bawse/elasticsearch,scorpionvicky/elasticsearch,sneivandt/elasticsearch,uschindler/elasticsearch,ZTE-PaaS/elasticsearch,JackyMai/elasticsearch,LewayneNaidoo/elasticsearch,C-Bish/elasticsearch,gfyoung/elasticsearch,brandonkearby/elasticsearch,pozhidaevak/elasticsearch,sneivandt/elasticsearch,a2lin/elasticsearch,rlugojr/elasticsearch,wangtuo/elasticsearch,MisterAndersen/elasticsearch,wenpos/elasticsearch,strapdata/elassandra,mjason3/elasticsearch,a2lin/elasticsearch,rajanm/elasticsearch,nezirus/elasticsearch,mortonsykes/elasticsearch,mikemccand/elasticsearch,gfyoung/elasticsearch,MisterAndersen/elasticsearch,jimczi/elasticsearch,StefanGor/elasticsearch,lks21c/elasticsearch,naveenhooda2000/elasticsearch,scorpionvicky/elasticsearch,rajanm/elasticsearch,kalimatas/elasticsearch,vroyer/elasticassandra,jimczi/elasticsearch,artnowo/elasticsearch,maddin2016/elasticsearch,gfyoung/elasticsearch,Shepard1212/elasticsearch,HonzaKral/elasticsearch,Stacey-Gammon/elasticsearch,nilabhsagar/elasticsearch,glefloch/elasticsearch,gingerwizard/elasticsearch,njlawton/elasticsearch,JSCooke/elasticsearch,nazarewk/elasticsearch,brandonkearby/elasticsearch,rajanm/elasticsearch,kalimatas/elasticsearch,brandonkearby/elasticsearch,naveenhooda2000/elasticsearch,pozhidaevak/elasticsearch,naveenhooda2000/elasticsearch,i-am-Nathan/elasticsearch,artnowo/elasticsearch,lks21c/elasticsearch,i-am-Nathan/elasticsearch,scottsom/elasticsearch,qwerty4030/elasticsearch,fred84/elasticsearch,markwalkom/elasticsearch,glefloch/elasticsearch,rajanm/elasticsearch,lks21c/elasticsearch,glefloch/elasticsearch,maddin2016/elasticsearch,sneivandt/elasticsearch,scorpionvicky/elasticsearch,strapdata/elassandra,JSCooke/elasticsearch,elasticdog/elasticsearch,umeshdangat/elasticsearch,mortonsykes/elasticsearch,markwalkom/elasticsearch,ThiagoGarciaAlves/elasticsearch,i-am-Nathan/elasticsearch,LeoYao/elasticsearch,markwalkom/elasticsearch,uschindler/elasticsearch,qwerty4030/elasticsearch,s1monw/elasticsearch,rajanm/elasticsearch,kalimatas/elasticsearch,shreejay/elasticsearch,wangtuo/elasticsearch,Stacey-Gammon/elasticsearch,Stacey-Gammon/elasticsearch,IanvsPoplicola/elasticsearch,fred84/elasticsearch,GlenRSmith/elasticsearch,LeoYao/elasticsearch,HonzaKral/elasticsearch,LewayneNaidoo/elasticsearch,LeoYao/elasticsearch,Stacey-Gammon/elasticsearch,mortonsykes/elasticsearch,obourgain/elasticsearch,vroyer/elasticassandra,C-Bish/elasticsearch,ThiagoGarciaAlves/elasticsearch,vroyer/elassandra,vroyer/elasticassandra,mohit/elasticsearch,obourgain/elasticsearch,wangtuo/elasticsearch,jimczi/elasticsearch,scorpionvicky/elasticsearch,masaruh/elasticsearch,nazarewk/elasticsearch,coding0011/elasticsearch,nknize/elasticsearch,masaruh/elasticsearch,ThiagoGarciaAlves/elasticsearch,nknize/elasticsearch,elasticdog/elasticsearch,Stacey-Gammon/elasticsearch,Shepard1212/elasticsearch,LeoYao/elasticsearch,jprante/elasticsearch,robin13/elasticsearch,a2lin/elasticsearch,JackyMai/elasticsearch,shreejay/elasticsearch,nilabhsagar/elasticsearch,strapdata/elassandra,GlenRSmith/elasticsearch,rlugojr/elasticsearch,Shepard1212/elasticsearch,s1monw/elasticsearch,vroyer/elassandra,njlawton/elasticsearch,nazarewk/elasticsearch,nilabhsagar/elasticsearch,wenpos/elasticsearch,naveenhooda2000/elasticsearch,fernandozhu/elasticsearch,mikemccand/elasticsearch,nazarewk/elasticsearch,a2lin/elasticsearch,LewayneNaidoo/elasticsearch,mohit/elasticsearch,umeshdangat/elasticsearch,nilabhsagar/elasticsearch,sneivandt/elasticsearch
3f7bd7d1c01e076f23986d464d5b1f824549c659
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.google.common.base.*; import com.google.common.collect.Lists; import java.util.*; import org.joda.time.*; } @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; String dataSourceName = null; public String getDataSource() { return dataSourceName; } public String unescape(String quoted) { String unquote = quoted.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: '/'; IDENT : (LETTER|DIGIT)(LETTER | DIGIT | '_')* ; QUOTED_STRING : '\'' ( ESCqs | ~'\'' )* '\'' ; ESCqs : '\'' '\''; fragment DIGIT : '0'..'9'; fragment LETTER : 'a'..'z' | 'A'..'Z'; INTEGER : [+-]?DIGIT+ ; DOUBLE: [+-]?DIGIT*\.?DIGIT+(EXPONENT)?; EXPONENT: ('e') ('+'|'-')? ('0'..'9')+; WS : (' ' | '\t' | '\r' '\n' | '\n' | '\r')+ -> skip; query : select_stmt where_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' timeAndDimFilter ; 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.0", -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); } ; /* fieldAccess returns [PostAggregator p] : IDENT { $p = new FieldAccessPostAggregator($IDENT.text, $IDENT.text); } ; */ constant returns [ConstantPostAggregator c] : value=INTEGER { int v = Integer.parseInt($value.text); $c = new ConstantPostAggregator(Integer.toString(v), v); } | value=DOUBLE { double v = Double.parseDouble($value.text); $c = new ConstantPostAggregator(Double.toString(v), v); } ; timeAndDimFilter : t=timeFilter (AND f=dimFilter)? { if($f.ctx != null) this.filter = $f.filter; this.intervals = Lists.newArrayList($t.interval); } | (f=dimFilter)? AND t=timeFilter { if($f.ctx != null) this.filter = $f.filter; this.intervals = Lists.newArrayList($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] : 'timestamp' 'between' s=timestamp AND e=timestamp { $interval = new org.joda.time.Interval(new DateTime(unescape($s.text)), new DateTime(unescape($e.text))); } ; timestamp : INTEGER | QUOTED_STRING ;
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 java.util.*; import org.joda.time.*; } @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 : '\'' '\''; fragment DIGIT : '0'..'9'; fragment LETTER : 'a'..'z' | 'A'..'Z'; DOUBLE: DIGIT*\.?DIGIT+(EXPONENT)?; EXPONENT: ('e') ('+'|'-')? ('0'..'9')+; 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.0", -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=DOUBLE { 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(new DateTime(unescape($s.text)), new DateTime(unescape($e.text))); } ; 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 : DOUBLE | QUOTED_STRING ;
add group by
add group by
ANTLR
apache-2.0
cocosli/druid,knoguchi/druid,praveev/druid,Fokko/druid,andy256/druid,winval/druid,druid-io/druid,leventov/druid,KurtYoung/druid,andy256/druid,noddi/druid,kevintvh/druid,fjy/druid,jon-wei/druid,praveev/druid,kevintvh/druid,du00cs/druid,767326791/druid,yaochitc/druid-dev,haoch/druid,eshen1991/druid,penuel-leo/druid,taochaoqiang/druid,implydata/druid,qix/druid,erikdubbelboer/druid,mangeshpardeshiyahoo/druid,optimizely/druid,premc/druid,tubemogul/druid,yaochitc/druid-dev,metamx/druid,zhiqinghuang/druid,noddi/druid,liquidm/druid,dkhwangbo/druid,deltaprojects/druid,Fokko/druid,implydata/druid,calliope7/druid,cocosli/druid,leventov/druid,eshen1991/druid,liquidm/druid,deltaprojects/druid,rasahner/druid,tubemogul/druid,anupkumardixit/druid,pdeva/druid,potto007/druid-avro,zhaown/druid,andy256/druid,qix/druid,michaelschiff/druid,b-slim/druid,redBorder/druid,minewhat/druid,metamx/druid,authbox-lib/druid,amikey/druid,Kleagleguo/druid,gianm/druid,wenjixin/druid,cocosli/druid,767326791/druid,deltaprojects/druid,mrijke/druid,nishantmonu51/druid,minewhat/druid,premc/druid,KurtYoung/druid,Fokko/druid,guobingkun/druid,zhaown/druid,smartpcr/druid,milimetric/druid,monetate/druid,zhihuij/druid,himanshug/druid,mangeshpardeshiyahoo/druid,jon-wei/druid,nvoron23/druid,zxs/druid,smartpcr/druid,rasahner/druid,himanshug/druid,jon-wei/druid,taochaoqiang/druid,leventov/druid,zhiqinghuang/druid,Fokko/druid,skyportsystems/druid,michaelschiff/druid,erikdubbelboer/druid,kevintvh/druid,liquidm/druid,du00cs/druid,Deebs21/druid,calliope7/druid,KurtYoung/druid,lcp0578/druid,wenjixin/druid,zhihuij/druid,monetate/druid,premc/druid,guobingkun/druid,lcp0578/druid,lizhanhui/data_druid,amikey/druid,monetate/druid,minewhat/druid,du00cs/druid,wenjixin/druid,nvoron23/druid,pdeva/druid,dkhwangbo/druid,nishantmonu51/druid,zxs/druid,druid-io/druid,dkhwangbo/druid,authbox-lib/druid,OttoOps/druid,pombredanne/druid,Deebs21/druid,dclim/druid,milimetric/druid,redBorder/druid,leventov/druid,zengzhihai110/druid,pjain1/druid,zxs/druid,mghosh4/druid,mrijke/druid,zengzhihai110/druid,lizhanhui/data_druid,lizhanhui/data_druid,se7entyse7en/druid,lizhanhui/data_druid,elijah513/druid,implydata/druid,pjain1/druid,mangeshpardeshiyahoo/druid,pombredanne/druid,anupkumardixit/druid,guobingkun/druid,noddi/druid,potto007/druid-avro,monetate/druid,milimetric/druid,du00cs/druid,zhihuij/druid,nishantmonu51/druid,praveev/druid,liquidm/druid,metamx/druid,penuel-leo/druid,guobingkun/druid,Deebs21/druid,nishantmonu51/druid,mangeshpardeshiyahoo/druid,anupkumardixit/druid,qix/druid,jon-wei/druid,amikey/druid,winval/druid,haoch/druid,elijah513/druid,smartpcr/druid,lizhanhui/data_druid,zhihuij/druid,pdeva/druid,mangeshpardeshiyahoo/druid,lcp0578/druid,calliope7/druid,dclim/druid,andy256/druid,767326791/druid,mrijke/druid,dclim/druid,cocosli/druid,authbox-lib/druid,Fokko/druid,praveev/druid,eshen1991/druid,milimetric/druid,authbox-lib/druid,Deebs21/druid,optimizely/druid,optimizely/druid,jon-wei/druid,wenjixin/druid,monetate/druid,tubemogul/druid,smartpcr/druid,solimant/druid,zhaown/druid,liquidm/druid,nishantmonu51/druid,OttoOps/druid,kevintvh/druid,calliope7/druid,himanshug/druid,Fokko/druid,lcp0578/druid,solimant/druid,OttoOps/druid,gianm/druid,se7entyse7en/druid,solimant/druid,praveev/druid,gianm/druid,pjain1/druid,Kleagleguo/druid,gianm/druid,zhiqinghuang/druid,winval/druid,optimizely/druid,metamx/druid,Deebs21/druid,KurtYoung/druid,pjain1/druid,taochaoqiang/druid,haoch/druid,premc/druid,michaelschiff/druid,mghosh4/druid,dclim/druid,mghosh4/druid,taochaoqiang/druid,monetate/druid,winval/druid,kevintvh/druid,zhaown/druid,michaelschiff/druid,milimetric/druid,zhihuij/druid,767326791/druid,zhaown/druid,potto007/druid-avro,du00cs/druid,mghosh4/druid,rasahner/druid,nvoron23/druid,metamx/druid,smartpcr/druid,wenjixin/druid,yaochitc/druid-dev,penuel-leo/druid,elijah513/druid,penuel-leo/druid,knoguchi/druid,friedhardware/druid,mghosh4/druid,himanshug/druid,knoguchi/druid,pombredanne/druid,calliope7/druid,potto007/druid-avro,rasahner/druid,amikey/druid,zengzhihai110/druid,nishantmonu51/druid,skyportsystems/druid,zxs/druid,friedhardware/druid,guobingkun/druid,solimant/druid,potto007/druid-avro,minewhat/druid,pombredanne/druid,mrijke/druid,implydata/druid,se7entyse7en/druid,mrijke/druid,taochaoqiang/druid,Kleagleguo/druid,Kleagleguo/druid,zxs/druid,authbox-lib/druid,pombredanne/druid,tubemogul/druid,michaelschiff/druid,solimant/druid,b-slim/druid,OttoOps/druid,zhiqinghuang/druid,gianm/druid,zengzhihai110/druid,michaelschiff/druid,erikdubbelboer/druid,fjy/druid,KurtYoung/druid,deltaprojects/druid,nvoron23/druid,yaochitc/druid-dev,b-slim/druid,deltaprojects/druid,cocosli/druid,qix/druid,gianm/druid,skyportsystems/druid,fjy/druid,implydata/druid,fjy/druid,deltaprojects/druid,liquidm/druid,dkhwangbo/druid,dkhwangbo/druid,knoguchi/druid,tubemogul/druid,erikdubbelboer/druid,yaochitc/druid-dev,skyportsystems/druid,skyportsystems/druid,haoch/druid,zhiqinghuang/druid,implydata/druid,767326791/druid,premc/druid,nishantmonu51/druid,michaelschiff/druid,jon-wei/druid,erikdubbelboer/druid,druid-io/druid,b-slim/druid,redBorder/druid,friedhardware/druid,druid-io/druid,se7entyse7en/druid,mghosh4/druid,b-slim/druid,pjain1/druid,eshen1991/druid,dclim/druid,pjain1/druid,mghosh4/druid,noddi/druid,himanshug/druid,gianm/druid,andy256/druid,anupkumardixit/druid,deltaprojects/druid,redBorder/druid,lcp0578/druid,anupkumardixit/druid,elijah513/druid,jon-wei/druid,leventov/druid,friedhardware/druid,se7entyse7en/druid,druid-io/druid,penuel-leo/druid,amikey/druid,haoch/druid,pdeva/druid,elijah513/druid,fjy/druid,Kleagleguo/druid,optimizely/druid,eshen1991/druid,OttoOps/druid,zengzhihai110/druid,nvoron23/druid,Fokko/druid,pdeva/druid,pjain1/druid,winval/druid,noddi/druid,qix/druid,redBorder/druid,knoguchi/druid,monetate/druid,friedhardware/druid,rasahner/druid,minewhat/druid
03de07d8fb0e9298ac9a3ea279880e04332da629
java-vtl-lexer/src/main/resources/kohl/hadrien/antlr4/clauses.g4
java-vtl-lexer/src/main/resources/kohl/hadrien/antlr4/clauses.g4
grammar clauses; clause : ( '[' ( rename | filter | keep | calc | attrcalc | aggregate ) ']' )+ ; // [ rename component as string, // component as string role = IDENTIFIER, // component as string role = MEASURE, // component as string role = ATTRIBUTE // ] rename : 'rename' renameParam ; renameParam : renameParam ( ',' renameParam )+ | component 'as' string role? ; filter : 'filter' booleanExpression ; keep : 'keep' booleanExpression ( ',' booleanExpression )* ; calc : 'calc' ; attrcalc : 'attrcalc' ; aggregate : 'aggregate' ; role : 'role' '=' ( 'IDENTIFIER' | 'MEASURE' | 'ATTRIBUTE' ) ; booleanExpression : 'booleanExpression' ; string : 'string' ; component : 'componentName' ; WS : [ \t\n\t] -> skip ;
Add clause grammar
Add clause grammar
ANTLR
apache-2.0
statisticsnorway/java-vtl,statisticsnorway/java-vtl,hadrienk/java-vtl,hadrienk/java-vtl,statisticsnorway/java-vtl,hadrienk/java-vtl,statisticsnorway/java-vtl
018ddc5bbfc2443c1592cc7a844cd729f883be66
src/grammar/mantra/Mantra.g4
src/grammar/mantra/Mantra.g4
grammar Mantra; @header {package mantra;} compilationUnit : (function|clazz|interfaze|enumb)* EOF ; clazz : ('api'|'abstract')* 'class' ID typeArgumentNames? ('extends' type)? ('implements' type (',' type)*)? '{' clazzMember* function* '}' ; interfaze : 'api'? 'interface' ID ('extends' type (',' type)*)? '{' // field* functionHead* '}' ; enumb : 'enum' ID '{' ID (',' ID)* '}' ; clazzMember : clazz | interfaze | field | memberFunction | enumb ; field: ('static'|'api')? vardecl // | 'api'? propdecl | 'api'? valdecl ; commands : stat+ ; memberFunction : ('static'|'api'|'overload')* function ; function : functionHead block ; functionHead : 'def' ID functionSignature ; functionSignature : '(' argList? ')' (':' type)? ; argList : argDef (',' argDef)* ; argDef : decl ('=' expression)? // const exprs ; lambdaSignature // no explicit return types in lambdas : '(' ')' // for use like () => 42.0 | '(' decl (',' decl)* ')' // (x:int) => x*2 | ID // shorthand for inferred arg | '(' ID (',' ID)* ')' // shorthand for inferred args ; blockArgs // no explicit return types in blocks { x,y | return x*y } : decl (',' decl)* // { x:int | ... } | ID (',' ID)* // shorthand for inferred arg types ; funcSignature : '(' ')' ':' type | '(' ')' | '(' argList ')' ':' type | '(' argList ')' ; /* propdecl : 'property' decl ('=' expression)? | 'property' ID ('=' expression)? ; */ vardecl : 'var' decl ('=' expression)? | 'var' ID (',' ID)* ('=' expression)? // type inf can use multiple assign on left ; valdecl : 'val' decl '=' expression | 'val' ID '=' expression ; decl: ID ':' type ; type: classOrInterfaceType ('[' ']')* | builtInType typeArguments? ('[' ']')* | tupleType ('[' ']')* // (int, float)[100] | functionType ('[' ']')* // func<(x:int)>[100] ; tupleType // ordered list of types; tuples accessed with t[1], t[2], etc... : '(' type (',' type)+ ')' ; functionType : 'func' '<' '(' argList? ')' ':' type '>' | 'func' '<' '(' argList ')' '>' | 'func' '<' '(' type ')' ':' type '>' // single argument doesn't need name | 'func' '<' '(' type ')' '>' | 'func' // ref to func with no args, no return value like {} ; classOrInterfaceType : qualifiedName typeArguments? ; typeArguments : '<' type (',' type)* '>' ; typeArgumentNames // only built-in types can use this like llist<string> : '<' ID (',' ID)* '>' ; builtInType : 'boolean' | 'char' | 'byte' | 'short' | 'int' | 'long' | 'float' | 'double' | 'string' | ( 'map' | 'tree' | 'llist' | 'set' ) typeArguments? ; block : '{' stat* '}' ; stat: lvalue (',' lvalue)* assignmentOperator expression | expression // calls, expression in a lambda | vardecl | valdecl | 'for' expression block | 'while' expression block | 'if' expression block ('else' block)? | 'return' expression | 'do' block 'while' expression ';' | 'try' block (catches finallyBlock? | finallyBlock) | 'switch' expression '{' switchCase+ ('default' ':' (stat|block)?)? '}' | 'return' expression? | 'throw' expression | 'break' | 'continue' | 'print' expression | 'throw' expression | clazz | interfaze | function | enumb ; switchCase : 'case' expression (',' expression)* ':' (stat|block)? ; catches : catchClause+ ; catchClause : 'catch' '(' catchType ID ')' block ; catchType : qualifiedName ('|' qualifiedName)* ; finallyBlock : 'finally' block ; argExprList : expression | ID '=' expression (',' ID '=' expression)* ; lvalue : ID | expression '[' expression ']' | expression '.' ID ; expression : primary | expression '.' ID | expression '[' expression ']' | expression ('++' | '--') | 'len' '(' expression ')' // calls expression.size() | expression '(' argExprList? ')' lambda? | ('+'|'-'|'++'|'--') expression | ('~'|'!') expression | expression ('*'|'/'|'%') expression | expression ('+'|'-') expression | expression ('<' '<' | '>' '>' '>' | '>' '>') expression | expression ('<=' | '>=' | '>' | '<') expression | expression 'instanceof' type | expression ('==' | '!=' | 'is') expression | expression '&' expression | expression '^' expression | expression '|' expression | expression ':' expression // range | expression 'and' expression | expression 'or' expression | expression 'in' expression | expression '?' expression ':' expression | expression pipeOperator expression ; pipeOperator : '=>' '[' expression ']' | '=>*' | '*=>' // pipe, merge | '=>' ; primary : '(' expression ')' | tuple | 'this' | 'super' | literal | type '.' 'class' | list | map | set | ctor | lambda | ID // string[] could match string here then [] as next statement; keep this last ; tuple: '(' expression (',' expression)+ ')' ; // can also be a tuple of pipelines, yielding pipeline graph // ctor (ambig with call) ctor: classOrInterfaceType '(' argExprList? ')' // Button(title="foo") | builtInType '(' argExprList? ')' // int(), string() | classOrInterfaceType ('[' expression? ']')+ // User[10][] list of 10 User lists of unspecified initial size | builtInType ('[' expression? ']')+ // int[] list of ints with unspecified initial size, int[10] 10 initial ints ; list: '[' ']' // type inferred | '[' expression (',' expression)* ']' ; map: '[' mapElem (',' mapElem)* ']' ; mapElem : expression '=' expression ; // special case for convenience set(1,2), set<User>(User(), User()) set : 'set' typeArguments? '(' expression (',' expression)* ')' ; lambda : lambdaSignature '->' expression // special case single expression | '{' (blockArgs '|')? stat+ '}' | '{' '}' // empty lambda ; qualifiedName : ID ('.' ID)* ; literal : IntegerLiteral | FloatingPointLiteral | CharacterLiteral | StringLiteral | BooleanLiteral | 'nil' ; assignmentOperator : '=' | '+=' | '-=' | '*=' | '/=' ; ABSTRACT : 'abstract'; API : 'api'; ASSERT : 'assert'; BOOLEAN : 'boolean'; BREAK : 'break'; BYTE : 'byte'; CASE : 'case'; CATCH : 'catch'; CHAR : 'char'; CLASS : 'class'; CONST : 'const'; CONTINUE : 'continue'; DEFAULT : 'default'; DO : 'do'; DOUBLE : 'double'; ELSE : 'else'; ENUM : 'enum'; EXTENDS : 'extends'; FINAL : 'final'; FINALLY : 'finally'; FLOAT : 'float'; FOR : 'for'; IF : 'if'; GOTO : 'goto';// reserved, not used IMPLEMENTS : 'implements'; IMPORT : 'import'; INSTANCEOF : 'instanceof'; INT : 'int'; INTERFACE : 'interface'; LEN : 'len'; LONG : 'long'; NATIVE : 'native'; OVERLOAD : 'overload'; PACKAGE : 'package'; PROPERTY : 'property'; // reserved, not used RETURN : 'return'; SET : 'set'; SHORT : 'short'; STATIC : 'static'; SUPER : 'super'; SWITCH : 'switch'; THIS : 'this'; THROW : 'throw'; TRANSIENT : 'transient'; TRY : 'try'; WHILE : 'while'; VAR : 'var' ; VOID : 'void' ; // §3.10.1 Integer Literals IntegerLiteral : DecimalIntegerLiteral | HexIntegerLiteral | OctalIntegerLiteral | BinaryIntegerLiteral ; fragment DecimalIntegerLiteral : DecimalNumeral IntegerTypeSuffix? ; fragment HexIntegerLiteral : HexNumeral IntegerTypeSuffix? ; fragment OctalIntegerLiteral : OctalNumeral IntegerTypeSuffix? ; fragment BinaryIntegerLiteral : BinaryNumeral IntegerTypeSuffix? ; fragment IntegerTypeSuffix : [lL] ; fragment DecimalNumeral : '0' | NonZeroDigit (Digits? | Underscores Digits) ; fragment Digits : Digit (DigitsAndUnderscores? Digit)? ; fragment Digit : '0' | NonZeroDigit ; fragment NonZeroDigit : [1-9] ; fragment DigitsAndUnderscores : DigitOrUnderscore+ ; fragment DigitOrUnderscore : Digit | '_' ; fragment Underscores : '_'+ ; fragment HexNumeral : '0' [xX] HexDigits ; fragment HexDigits : HexDigit (HexDigitsAndUnderscores? HexDigit)? ; fragment HexDigit : [0-9a-fA-F] ; fragment HexDigitsAndUnderscores : HexDigitOrUnderscore+ ; fragment HexDigitOrUnderscore : HexDigit | '_' ; fragment OctalNumeral : '0' Underscores? OctalDigits ; fragment OctalDigits : OctalDigit (OctalDigitsAndUnderscores? OctalDigit)? ; fragment OctalDigit : [0-7] ; fragment OctalDigitsAndUnderscores : OctalDigitOrUnderscore+ ; fragment OctalDigitOrUnderscore : OctalDigit | '_' ; fragment BinaryNumeral : '0' [bB] BinaryDigits ; fragment BinaryDigits : BinaryDigit (BinaryDigitsAndUnderscores? BinaryDigit)? ; fragment BinaryDigit : [01] ; fragment BinaryDigitsAndUnderscores : BinaryDigitOrUnderscore+ ; fragment BinaryDigitOrUnderscore : BinaryDigit | '_' ; FloatingPointLiteral : DecimalFloatingPointLiteral | HexadecimalFloatingPointLiteral ; fragment DecimalFloatingPointLiteral : Digits '.' Digits? ExponentPart? FloatTypeSuffix? | '.' Digits ExponentPart? FloatTypeSuffix? | Digits ExponentPart FloatTypeSuffix? | Digits FloatTypeSuffix ; fragment ExponentPart : ExponentIndicator SignedInteger ; fragment ExponentIndicator : [eE] ; fragment SignedInteger : Sign? Digits ; fragment Sign : [+-] ; fragment FloatTypeSuffix : [fFdD] ; fragment HexadecimalFloatingPointLiteral : HexSignificand BinaryExponent FloatTypeSuffix? ; fragment HexSignificand : HexNumeral '.'? | '0' [xX] HexDigits? '.' HexDigits ; fragment BinaryExponent : BinaryExponentIndicator SignedInteger ; fragment BinaryExponentIndicator : [pP] ; // §3.10.3 Boolean Literals BooleanLiteral : 'true' | 'false' ; // §3.10.4 Character Literals CharacterLiteral : '\'' SingleCharacter '\'' | '\'' EscapeSequence '\'' ; fragment SingleCharacter : ~['\\\r\n] ; StringLiteral : '"' StringCharacter* '"' ; UNTERMINATED_STRING_LITERAL : '\'' StringCharacter* ; fragment StringCharacter : ~["\\\r\n] | EscapeSequence ; fragment EscapeSequence : '\\' [btnfr"'\\] | OctalEscape ; fragment OctalEscape : '\\' OctalDigit | '\\' OctalDigit OctalDigit | '\\' ZeroToThree OctalDigit OctalDigit ; fragment ZeroToThree : [0-3] ; Nil : 'nil' ; LPAREN : '('; RPAREN : ')'; LBRACE : '{'; RBRACE : '}'; LBRACK : '['; RBRACK : ']'; SEMI : ';'; COMMA : ','; DOT : '.'; //ASSIGN : '='; GT : '>'; LT : '<'; BANG : '!'; TILDE : '~'; QUESTION : '?'; COLON : ':'; EQUAL : '=='; IS : 'is' ; IN : 'in' ; LE : '<='; GE : '>='; NOTEQUAL : '!='; AND : 'and'; OR : 'or'; INC : '++'; DEC : '--'; ADD : '+'; SUB : '-'; MUL : '*'; DIV : '/'; BITAND : '&'; BITOR : '|'; CARET : '^'; MOD : '%'; YIELDS : '->' ; // lambda PIPE : '=>' ; PIPE_MANY : '=>*' ; MERGE_MANY : '*=>' ; ADD_ASSIGN : '+='; SUB_ASSIGN : '-='; MUL_ASSIGN : '*='; DIV_ASSIGN : '/='; ID : JavaLetter JavaLetterOrDigit* // follow Java conventions ; fragment JavaLetter : [a-zA-Z$_] // these are the "java letters" below 0xFF | // covers all characters above 0xFF which are not a surrogate ~[\u0000-\u00FF\uD800-\uDBFF] {Character.isJavaIdentifierStart(_input.LA(-1))}? | // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment JavaLetterOrDigit : [a-zA-Z0-9$_] // these are the "java letters or digits" below 0xFF | // covers all characters above 0xFF which are not a surrogate ~[\u0000-\u00FF\uD800-\uDBFF] {Character.isJavaIdentifierPart(_input.LA(-1))}? | // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; WS : [ \t\u000C]+ -> channel(HIDDEN) ; NL : '\r'? '\n' -> channel(HIDDEN) ; // command separator (ignore for now) DOC_COMMENT : '/**' .*? ('*/' | EOF) -> channel(HIDDEN) ; BLOCK_COMMENT : '/*' .*? ('*/' | EOF) -> channel(HIDDEN) ; LINE_COMMENT : '//' ~[\r\n]* -> channel(HIDDEN) ;
add initial grammar, copying from https://github.com/mantra/grammar/commit/76e3edfae18ab9004860d7c675b54587d0dfd24e
add initial grammar, copying from https://github.com/mantra/grammar/commit/76e3edfae18ab9004860d7c675b54587d0dfd24e
ANTLR
bsd-3-clause
mantra/compiler
e5eba68c9850c748b988ff7e7ee9dee656d04f2d
Rexx/RexxLexer.g4
Rexx/RexxLexer.g4
lexer grammar RexxLexer; // Main rules // %INCLUDE statement STMT_INCLUDE : Include_Statement ; // Skippable stuff LINE_COMMENT : Line_Comment_ -> channel(HIDDEN); BLOCK_COMMENT : Block_Comment_ -> channel(HIDDEN); WHISPACES : Whitespaces_ -> channel(HIDDEN); CONTINUATION : Continue_ -> channel(HIDDEN); // Keywords KWD_ADDRESS : A D D R E S S ; KWD_ARG : A R G ; KWD_BY : B Y ; KWD_CALL : C A L L ; KWD_DIGITS : D I G I T S ; KWD_DO : D O ; KWD_DROP : D R O P ; KWD_ELSE : E L S E ; KWD_END : E N D ; KWD_ENGINEERING : E N G I N E E R I N G ; KWD_ERROR : E R R O R ; KWD_EXIT : E X I T ; KWD_EXPOSE : E X P O S E ; KWD_EXTERNAL : E X T E R N A L ; KWD_FAILURE : F A I L U R E ; KWD_FOR : F O R ; KWD_FOREVER : F O R E V E R ; KWD_FORM : F O R M ; KWD_FUZZ : F U Z Z ; KWD_HALT : H A L T ; KWD_IF : I F ; KWD_INTERPRET : I N T E R P R E T ; KWD_ITERATE : I T E R A T E ; KWD_LEAVE : L E A V E ; KWD_NAME : N A M E ; KWD_NOP : N O P ; KWD_NOVALUE : N O V A L U E ; KWD_NUMERIC : N U M E R I C ; KWD_OFF : O F F ; KWD_ON : O N ; KWD_OPTIONS : O P T I O N S ; KWD_OTHERWISE : O T H E R W I S E ; KWD_PARSE : P A R S E ; KWD_PROCEDURE : P R O C E D U R E ; KWD_PULL : P U L L ; KWD_PUSH : P U S H ; KWD_QUEUE : Q U E U E ; KWD_RETURN : R E T U R N ; KWD_SAY : S A Y ; KWD_SCIENTIFIC : S C I E N T I F I C ; KWD_SELECT : S E L E C T ; KWD_SIGNAL : S I G N A L ; KWD_SOURCE : S O U R C E ; KWD_SYNTAX : S Y N T A X ; KWD_THEN : T H E N ; KWD_TO : T O ; KWD_TRACE : T R A C E ; KWD_UNTIL : U N T I L ; KWD_UPPER : U P P E R ; KWD_VALUE : V A L U E ; KWD_VAR : V A R ; KWD_VERSION : V E R S I O N ; KWD_WHEN : W H E N ; KWD_WHILE : W H I L E ; KWD_WITH : W I T H ; // Brackets BR_O : Br_O_ ; BR_C : Br_C_ ; // Special variables: RC, RESULT, SIGL SPECIAL_VAR : R C | R E S U L T | S I G L ; // Label, const, var, number NUMBER : Number_ ; CONST_SYMBOL : Const_symbol_ ; VAR_SYMBOL : Var_Symbol_ ; // String and concatenation STRING : String_ // Additionally, need to consume X or B at the end not followed by // _!?A-Za-z.#@$0-9 {int currPos = this.getCharIndex(); int textLen = super.getInputStream().size(); if (textLen > currPos) { if (textLen == currPos + 1) { if (super.getInputStream() .getText( new Interval(currPos, currPos)) .matches("[XxBb]")) super.getInputStream().consume(); } else { if (super.getInputStream().getText( new Interval(currPos, currPos + 1)) .matches("[XxBb][^_!?A-Za-z.#@$0-9]")) super.getInputStream().consume(); } }} ; // In concatenation don't need the blanks - will be precoeesed by WHITESPACES CONCAT : VBar_ VBar_ ; // Operations // Assignment (also comparison and template operator) EQ : Eq_ ; // Math: +, -, *, /, //, %, ** // Note: '+' and '-' are also used in prefix expressions and templates PLUS : Plus_ ; MINUS : Minus_ ; MUL : Asterisk_ ; DIV : Slash_ ; QUOTINENT : Percent_sign_ ; REMAINDER : Slash_ Slash_ ; POW : Asterisk_ Asterisk_ ; // Logical: NOT, OR, AND, XOR // Note: '\\' also used for prefix expressions NOT : Not_ ; OR : VBar_ ; XOR : Amp_ Amp_ ; AND : Amp_ ; // Comparison // Strict comparison: ==, \==, >>, <<, >>=, <<=, \>>, \<< CMPS_Eq : Eq_ Eq_ ; CMPS_Neq : Not_ Eq_ Eq_ ; CMPS_M : More_ More_ ; CMPS_L : Less_ Less_ ; CMPS_MEq : More_ More_ Eq_ ; CMPS_LEq : Less_ Less_ Eq_ ; CMPS_NM : Not_ More_ More_ ; CMPS_NL : Not_ Less_ Less_ ; // Non-strict: =, \=, <>, ><, >, <, >=, <=, \>, \< // Note: '=' is taken from Assignment (EQ) CMP_NEq : Not_ Eq_ ; CMP_LM : Less_ More_ ; CMP_ML : More_ Less_ ; CMP_M : More_ ; CMP_L : Less_ ; CMP_MEq : More_ Eq_ ; CMP_LEq : Less_ Eq_ ; CMP_NM : Not_ More_ ; CMP_NL : Not_ Less_ ; // Additional elements // . STOP : Stop_ ; // , COMMA : Comma_ ; // : COLON : Colon_ ; // End of line EOL : Eol_ ; // Semicolumn SEMICOL : Scol_ ; // -------------------------------------------------------- // Fragments // Comments // Include statement - need to account for this fragment Include_Statement : Comment_S Bo? Percent_sign_ I N C L U D E Bo Var_Symbol_+ Bo? Comment_E ; // Line comment - no EOL allowed inside. fragment Line_Comment_ : Comment_S Line_Commentpart*? Asterisk_*? ( Comment_E | EOF ) ; fragment Line_Commentpart : Line_Comment_ | Slash_ Line_Comment_ | Slash_ ~[*\n\r]+? | Asterisk_ ~[/\n\r]+? | ~[/*\n\r]+ ; fragment Block_Comment_ : Comment_S Block_Commentpart*? Asterisk_*? ( Comment_E | EOF ) ; fragment Block_Commentpart : Block_Comment_ | Slash_ Block_Comment_ | Slash_ ~[*]+? | Asterisk_ ~[/]+? | ~[/*]+ ; fragment Comment_E : Asterisk_ Slash_ ; fragment Comment_S : Slash_ Asterisk_ ; // Whitespaces fragment Whitespaces_ : Blank+ ; // Continuation - full comments, but no EOL between fragment Continue_ : Comma_ ( Block_Comment_ | Line_Comment_ | Blank )*? Eol_; fragment Eol_ : New_Line_ Caret_Return_ | Caret_Return_ New_Line_ | New_Line_ | Caret_Return_ ; // Whitespaces fragment Bo : Blank+ ; fragment Blank : Space_ | Other_blank_character ; fragment Other_blank_character : Form_Feed_ | HTab_ | VTab_ ; // Label, const, var, number // Label, var fragment Var_Symbol_ : General_letter Var_symbol_char*; fragment Var_symbol_char : General_letter | Digit_ | Stop_ ; fragment General_letter : Underscore_ | Exclamation_mark_ | Question_mark_ | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | Extra_letter ; fragment Extra_letter : Hash_ | At_ | Dollar_ ; // Const fragment Const_symbol_ : Digit_ Var_symbol_char* ; fragment Digit_ : [0-9] ; // Number fragment Number_ : Plain_number Exponent_? ; fragment Plain_number : Digit_+ Stop_? Digit_* | Stop_ Digit_+ ; fragment Exponent_ : E ( Plus_ | Minus_ )? Digit_+ ; // String and concatenation fragment String_ : Quoted_string ; fragment Quoted_string : Quotation_mark_string | Apostrophe_string ; fragment Quotation_mark_string : Quote_ (String_char | Embedded_quotation_mark | Apostrophe_)* Quote_ ; fragment Embedded_quotation_mark: Quote_ Quote_ ; fragment Apostrophe_string : Apostrophe_ (String_char | Embedded_apostrophe | Quote_)* Apostrophe_ ; fragment Embedded_apostrophe : Apostrophe_ Apostrophe_ ; fragment String_char : String_or_comment_char | Asterisk_ | Slash_ ; fragment String_or_comment_char : Digit_ | Stop_ | Special | Operator_only | General_letter | Blank | Other_character ; fragment Special : Comma_ | Colon_ | Scol_ | Br_C_ | Br_O_ ; fragment Operator_only : Plus_ | Minus_ | Percent_sign_ | VBar_ | Amp_ | Eq_ | Not_ | More_ | Less_ ; fragment Other_character : ~["'\n\r*/] ; fragment Not_ : Backslash_ | Other_negator ; fragment Other_negator : Caret_ | Logical_Not_ | Slash_ ; // Single characters fragment Stop_ : '.' ; fragment Comma_ : ',' ; fragment Colon_ : ':' ; fragment Scol_ : ';' ; fragment Eq_ : '=' ; fragment Plus_ : '+' ; fragment Minus_ : '-' ; fragment Caret_ : '^' ; fragment Logical_Not_ : '¬' ; fragment Underscore_ : '_' ; fragment Exclamation_mark_ : '!' ; fragment Question_mark_ : '?' ; fragment Br_O_ : '(' ; fragment Br_C_ : ')' ; fragment Space_ : ' ' ; fragment Form_Feed_ : '\f' ; fragment HTab_ : '\t' ; fragment VTab_ : '\u000b' ; fragment Caret_Return_ : '\r' ; fragment New_Line_ : '\n' ; fragment Quote_ : '"' ; fragment Apostrophe_ : '\'' ; fragment Slash_ : '/' ; fragment Backslash_ : '\\' ; fragment Asterisk_ : '*' ; fragment More_ : '>' ; fragment Less_ : '<' ; fragment Percent_sign_ : '%' ; fragment VBar_ : '|' ; fragment Amp_ : '&' ; fragment Hash_ : '#' ; fragment At_ : '@' ; fragment Dollar_ : '$' ; // Letters fragment A : ('a'|'A'); fragment B : ('b'|'B'); fragment C : ('c'|'C'); fragment D : ('d'|'D'); fragment E : ('e'|'E'); fragment F : ('f'|'F'); fragment G : ('g'|'G'); fragment H : ('h'|'H'); fragment I : ('i'|'I'); fragment J : ('j'|'J'); fragment K : ('k'|'K'); fragment L : ('l'|'L'); fragment M : ('m'|'M'); fragment N : ('n'|'N'); fragment O : ('o'|'O'); fragment P : ('p'|'P'); fragment Q : ('q'|'Q'); fragment R : ('r'|'R'); fragment S : ('s'|'S'); fragment T : ('t'|'T'); fragment U : ('u'|'U'); fragment V : ('v'|'V'); fragment W : ('w'|'W'); fragment X : ('x'|'X'); fragment Y : ('y'|'Y'); fragment Z : ('z'|'Z'); // Unsupported characters UNSUPPORTED_CHARACTER : . ;
Create RexxLexer.g4
Create RexxLexer.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
0aa8b244725625b488b9fd43012038516b39a361
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 ;
Add full C grammar for reference
Add full C grammar for reference
ANTLR
mit
Sibert-Aerts/c2p,Sibert-Aerts/c2p,Sibert-Aerts/c2p
2fe8e94f5de6d799558aa7b199c07603fba9541a
atl/ATL.g4
atl/ATL.g4
/* Copyright 2015 Spikes N.V. 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. Initially developed in the context of ARTIST EU project www.artist-project.eu */ grammar ATL; /* * Parser Rules */ unit : module | library | query; module : 'module' (STRING|IDENTIFIER) ';' 'create' targetModelPattern transformationMode sourceModelPattern ';' libraryRef* moduleElement*; // Small change introducing targetModelPattern, sourceModelPattern, transformationMode to facilitate fetching the information via the parser targetModelPattern : oclModel (',' oclModel)*; sourceModelPattern : oclModel (',' oclModel)*; transformationMode : 'refining' | 'from'; library : 'library' (STRING|IDENTIFIER) ';' libraryRef* helper*; query : 'query' (STRING|IDENTIFIER) '=' oclExpression ';' libraryRef* helper*; libraryRef : 'uses' STRING ';'; moduleElement : helper | rule; helper : 'helper' oclFeatureDefinition ';'; oclFeatureDefinition : oclContextDefinition? 'def' ':' oclFeature; oclContextDefinition : 'context' oclType; oclFeature : operation | attribute; operation : IDENTIFIER '(' (parameter (',' parameter)*)? ')' ':' oclType '=' oclExpression; parameter : IDENTIFIER ':' oclType; attribute : IDENTIFIER ':' oclType '=' oclExpression; rule : calledRule | matchedRule; matchedRule : lazyMatchedRule | matchedRule_abstractContents; lazyMatchedRule : 'unique'? 'lazy' 'abstract'? 'refining'? 'rule' IDENTIFIER ('extends' IDENTIFIER)? '{' inPattern ('using' '{' ruleVariableDeclaration* '}')? outPattern? actionBlock? '}'; ruleVariableDeclaration : IDENTIFIER ':' oclType '=' oclExpression ';'; calledRule : 'entrypoint'? 'endpoint'? 'rule' IDENTIFIER '(' (parameter (',' parameter)*)? ')' '{' ('using' '{' ruleVariableDeclaration* '}')? outPattern? actionBlock? '}'; inPattern : 'from' inPatternElement (',' inPatternElement)* ('(' oclExpression ')')?; inPatternElement : simpleInPatternElement; simpleInPatternElement : IDENTIFIER ':' oclType ('in' IDENTIFIER (',' IDENTIFIER)*)?; outPattern : 'to' outPatternElement (',' outPatternElement)*; outPatternElement : simpleOutPatternElement | forEachOutPatternElement; simpleOutPatternElement : IDENTIFIER ':' oclType ('in' IDENTIFIER)? ('mapsTo' IDENTIFIER)? ('(' (binding (',' binding)*)? ')')?; forEachOutPatternElement : IDENTIFIER ':' 'distinct' oclType 'foreach' '(' iterator 'in' oclExpression ')' ('mapsTo' IDENTIFIER)? ('(' (binding (',' binding)*)? ')')?; binding : IDENTIFIER '<-' oclExpression; actionBlock : 'do' '{' statement* '}'; statement : ifStat | expressionStat | bindingStat | forStat; bindingStat : oclExpression '<-' oclExpression ';'; expressionStat : oclExpression ';'; ifStat : 'if' '(' oclExpression ')' (statement | '{' statement* '}') ('else' (statement | '{' statement* '}'))?; forStat : 'for' '(' iterator 'in' oclExpression ')' '{' statement* '}'; oclModel : IDENTIFIER ':' IDENTIFIER; oclModelElement : IDENTIFIER '!' (STRING|IDENTIFIER); oclExpression : priority_5 | letExp; iteratorExp : IDENTIFIER '(' iterator (',' iterator)* '|' oclExpression ')'; iterateExp : 'iterate' '(' iterator (',' iterator)* ';' variableDeclaration '|' oclExpression ')'; collectionOperationCallExp : IDENTIFIER '(' (oclExpression (',' oclExpression)*)? ')'; operationCallExp : IDENTIFIER '(' (oclExpression (',' oclExpression)*)? ')'; navigationOrAttributeCallExp : IDENTIFIER; iterator : IDENTIFIER; oclUndefinedExp : 'OclUndefined'; primitiveExp : numericExp | booleanExp | stringExp; numericExp : integerExp | realExp; booleanExp : 'true' | 'false'; integerExp : INTEGER; realExp : FLOAT; stringExp : STRING; ifExp : 'if' oclExpression 'then' oclExpression 'else' oclExpression 'endif'; variableExp : IDENTIFIER; superExp : 'super'; letExp : 'let' variableDeclaration 'in' oclExpression; variableDeclaration : IDENTIFIER ':' oclType '=' oclExpression; enumLiteralExp : '#' IDENTIFIER; collectionExp : bagExp | setExp | orderedSetExp | sequenceExp; bagExp : 'Bag' '{' (oclExpression (',' oclExpression)*)? '}'; setExp : 'Set' '{' (oclExpression (',' oclExpression)*)? '}'; orderedSetExp : 'OrderedSet' '{' (oclExpression (',' oclExpression)*)? '}'; sequenceExp : 'Sequence' '{' (oclExpression (',' oclExpression)*)? '}'; mapExp : 'Map' '{' (mapElement (',' mapElement)*)? '}'; mapElement : '(' oclExpression ',' oclExpression ')'; tupleExp : 'Tuple' '{' (tuplePart (',' tuplePart)*)? '}'; tuplePart : IDENTIFIER (':' oclType)? '=' oclExpression; oclType : oclModelElement | oclAnyType | tupleType | mapType | primitive | collectionType | oclType_abstractContents; oclAnyType : oclAnyType_abstractContents; tupleType : 'TupleType' '(' (tupleTypeAttribute (',' tupleTypeAttribute)*)? ')'; tupleTypeAttribute : IDENTIFIER ':' oclType; mapType : 'Map' '(' oclType ',' oclType ')'; primitive : numericType | booleanType | stringType; numericType : integerType | realType; integerType : 'Integer'; realType : 'Real'; booleanType : 'Boolean'; stringType : 'String'; collectionType : bagType | setType | orderedSetType | sequenceType | collectionType_abstractContents; bagType : 'Bag' '(' oclType ')'; setType : 'Set' '(' oclType ')'; orderedSetType : 'OrderedSet' '(' oclType ')'; sequenceType : 'Sequence' '(' oclType ')'; priority_0 : primary_oclExpression ('.' (operationCallExp | navigationOrAttributeCallExp) | '->' (iteratorExp | iterateExp | collectionOperationCallExp))*; priority_1 : 'not' priority_0 | '-' priority_0 | priority_0; priority_2 : priority_1 ('*' priority_1 | '/' priority_1 | 'div' priority_1 | 'mod' priority_1)*; priority_3 : priority_2 ('+' priority_2 | '-' priority_2)*; priority_4 : priority_3 ('=' priority_3 | '>' priority_3 | '<' priority_3 | '>=' priority_3 | '<=' priority_3 | '<>' priority_3)*; priority_5 : priority_4 ('and' priority_4 | 'or' priority_4 | 'xor' priority_4 | 'implies' priority_4)*; matchedRule_abstractContents : 'nodefault'? 'abstract'? 'refining'? 'rule' IDENTIFIER ('extends' IDENTIFIER)? '{' inPattern ('using' '{' ruleVariableDeclaration* '}')? outPattern? actionBlock? '}'; oclType_abstractContents : 'OclType'; oclAnyType_abstractContents : 'OclAny'; collectionType_abstractContents : 'Collection' '(' oclType ')'; primary_oclExpression : variableExp | oclUndefinedExp | primitiveExp | ifExp | superExp | enumLiteralExp | collectionExp | mapExp | tupleExp | oclType | '(' oclExpression ')'; STRING : '"' DoubleStringCharacters? '"' | '\'' SingleStringCharacters? '\'' ; fragment DoubleStringCharacters : DoubleStringCharacter+ ; fragment DoubleStringCharacter : ~["\\] | '\\' [btnfr"'\\] ; fragment SingleStringCharacters : SingleStringCharacter+ ; fragment SingleStringCharacter : ~['\\] | '\\' [btnfr"'\\] ; // Integer Literals INTEGER : DecimalIntegerLiteral ; fragment DecimalIntegerLiteral : DecimalNumeral ; fragment DecimalNumeral : '0' | NonZeroDigit Digits? ; fragment Digits : Digit Digit* ; fragment Digit : '0' | NonZeroDigit ; fragment NonZeroDigit : [1-9] ; FLOAT : DecimalFloatingPointLiteral ; fragment DecimalFloatingPointLiteral : Digits '.' Digits? ExponentPart? FloatTypeSuffix? | '.' Digits ExponentPart? FloatTypeSuffix? | Digits ExponentPart FloatTypeSuffix? | Digits FloatTypeSuffix ; fragment ExponentPart : ExponentIndicator SignedInteger ; fragment ExponentIndicator : [eE] ; fragment SignedInteger : Sign? Digits ; fragment Sign : [+-] ; fragment FloatTypeSuffix : [fFdD] ; IDENTIFIER : LetterOrDigit LetterOrDigit* ; fragment Letter : [a-zA-Z$_] // these are the "Java letters" ; fragment LetterOrDigit : [a-zA-Z0-9$_] // these are the "Java letters or digits" ; // // Whitespace and comments // WS : [ \t\r\n\u000C]+ -> skip ; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '--' ~[\r\n]* -> skip ;
Add (lowercase folder)
Add (lowercase folder)
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