I’m writing a PLC language interpreter using C#. My interpreter has its own type hierarchy: elemental types (integers, boolean,..) and derived types (structs, arrays,…). I’m having problems while creating multidimensinal arrays from my ANTLR grammar.
This is the way my language declares multidimensional arrays (3×2 int array):
TYPE
MY_ARRAY : ARRAY [0..2, 1..2] OF INT;
END_TYPE
My antlr grammar for parsing unidimensional array declarations is next:
decl_derivated
: 'TYPE' NEWLINE* ID ':' NEWLINE* type_decl ';' NEWLINE* 'END_TYPE' NEWLINE* -> ^(TYPEDEF<TypeDefinition>[$ID.text, $type_decl.type])
;
type_decl returns [Type type]
: 'STRUCT' NEWLINE* decl_fields 'END_STRUCT' { $type = new STRUCT($decl_fields.fieldList); }
| 'ARRAY' '[' range ']' 'OF' type_var { $type = new ARRAY($type_var.type, $range.init, $range.end); }
;
range returns [int init, int end]
: ini=CTE_INT '..' en=CTE_INT { $init = int.Parse($ini.text); $end = int.Parse($en.text); }
;
type_var returns [Type type]
: 'BOOL' { $type = new BOOL(); }
| 'INT' { $type = new INT(); }
| 'REAL' { $type = new REAL(); }
;
/* lexer */
ID : (LETTER | '_') (LETTER | DIGIT | '_')*
;
fragment
DIGIT : '0'..'9'
;
fragment
INTEGER : DIGIT ('_'|DIGIT)*
;
fragment
EXPONENT : ('e'|'E') ('+'|'-')? INTEGER ;
fragment
CTE_INT
: ('+'|'-'| ) INTEGER
;
fragment
CTE_REAL
: ('+'|'-'| /*vacio*/ ) INTEGER '.' INTEGER EXPONENT?
;
RANGE : '..' ;
RANGE_OR_INT
: ( CTE_INT RANGE ) => CTE_INT { $type=CTE_INT; }
| ( CTE_REAL ) => CTE_REAL { $type=CTE_REAL; }
| CTE_INT { $type=CTE_INT; }
;
NEWLINE : '\r'? '\n'
| '\r'
;
I have no problems to parser multidimensional arrays changing my grammar in array declaration to:
type_decl returns [Type type]
: 'ARRAY' '[' range (',' range)* ']' 'OF' type_var
I don’t know how to write my constructor for this multidimensional arrays.
Anyone can help me?
Thank you.
SOLUTION
Finally, I’ve achieved a better and more elegant solution. I’ve added two new methods to my ARRAY data type class: one for adding a new dimension and another one for setting the base type.
ANTLR grammar:
Anyway, thank you for your time 😉