Have a look at my grammar
grammar protocol;
options {
language = Java;
output = AST;
}
//imaginary tokens
tokens{
BOOL;
CHAR;
STRING;
}
parse
: declaration
;
declaration
: variable
;
variable
: locals
;
locals
: (bool
| char
| string)+
;
bool
:'bool' ID -> ^(BOOL ID)
;
char
: 'char' ID -> ^(CHAR ID)
;
string
:'string' ID -> ^(STRING ID)
;
ID
: (('a'..'z' | 'A'..'Z'|'_')('a'..'z' | 'A'..'Z'|'0'..'9'|'_'))*
;
INT
: ('0'..'9')+
;
WHITESPACE
: ('\t' | ' ' | '\r' | '\n' | '\u000C')+ {$channel = HIDDEN;}
;
For the following input,
bool boolVariable
char charVariable
string stringVariable
My grammar creates the following AST
I can't declare a variable more than once. I don't want to declare variables of the same type at once separated by commas but I want like this
bool boolVariable1
bool boolVariable2
bool boolVariable3
string stringVariable1
string stringVariable2
After doing this, I want all variables to be of two main types. Shared and local. In Java, a shared variable (static) is the one who has single copy for all the objects whereas local variable has separate copy for each object. I want user to explicitly specify the scope of the variable before defining the variable set. Like,
locals:
bool boolVariable1
bool boolVariable2
bool boolVariable3
string stringVariable1
string stringVariable2
shared:
bool boolVariable4
bool boolVariable5
bool boolVariable6
string stringVariable3
string stringVariable4
char charVariable1
Moreover, is there any way that I can check user cann't have two variables of the same name? Like,
bool boolVariable
bool boolVariable
should give some sort of error or like that.
Any thoughts/help?
Thank you
EDIT - SOLUTION
grammar protocol;
options {
language = Java;
output = AST;
}
//imaginary tokens
tokens{
BOOL;
CHAR;
STRING;
SBOOL;
SCHAR;
SSTRING;
}
parse
: declaration
;
declaration
: variable
;
variable
: (locals
| shared)*
;
locals
: 'locals:' (bool| char| string)*
;
bool
:'bool' ID -> ^(BOOL ID)
;
char
: 'char' ID -> ^(CHAR ID)
;
string
:'string' ID -> ^(STRING ID)
;
shared
: 'shared:' (sbool| schar| sstring)*
;
sbool
:'bool' ID -> ^(SBOOL ID)
;
schar
: 'char' ID -> ^(SCHAR ID)
;
sstring
:'string' ID -> ^(SSTRING ID)
;
ID
: (('a'..'z' | 'A'..'Z'|'_')('a'..'z' | 'A'..'Z'|'0'..'9'|'_'))*
;
INT
: ('0'..'9')+
;
WHITESPACE
: ('\t' | ' ' | '\r' | '\n' | '\u000C')+ {$channel = HIDDEN;}
;