views:

124

answers:

2

I'm sure I'll get told to do it another way, but for specific reasons it has to be done this way. If it didn't, I wouldn't be stuck :-P

The scripting language I'm working on has to accept variables defined like this:

Variables: x(1), y("hi");

This is a requirement. I wrote a small grammar before that would let me define them like this

int x = 1;
string y = "hi";

but the requirements changed. The way it was before my grammar looked like this

syntax sDeclareVar = t:sType i:tID "=" x:sExpression ";"  => DeclareVar { VariableName{i},Type{t},Value{x}};

sType's values were either System.String, Int32, etc., then the variable name, and then whatever the expression was. I then projected this into a DeclareVar node and gave it the parameters required, in the code I parsed it to XML and then had MGrammar parse the XML and traversed my AST just fine. Since they want to be able to do variables without declaring the type, I'm kind of stuck on what to do now, i.e. how do I get my variables that don't have a declared type stored into the appropriate classes. Any help would be appreciated, hopefully it all makes sense.

A: 

It depends on how the rest of your grammar is structured, but you might be stuck doing something roughly along the lines of:

syntax sDeclareVar = "Variables:" sVarList ":";
syntax sVarList = sVarDeclaration ("," sVarList)?;
syntax sVarDeclaration = sIntVarDeclaration | sStringVarDeclaration | ...
syntax sIntVarDeclaration = i:tID "(" x:sIntegerLiteral ")"  => DeclareVar VariableName{i},Type{Int32},Value{x}};
syntax sStringVarDeclaration = i:tID "(" x:sStringLiteral ")"  => DeclareVar VariableName{i},Type{System.String},Value{x}};

and so forth.

MarkusQ
A: 

Thanks Markus, that got me on the right track, here's what I ended up doing.

syntax sDeclareVar = tVariableKeywords s:Common.List(sVarDeclaration) ";" => VariableList{Statements{s}};

syntax sVarDeclaration = s:sIntVarDeclaration => s | s:sStringVarDeclaration => s;

syntax sIntVarDeclaration = ","? i:tID "(" x:tIntegerLiteral ")" => DeclareVar{VariableName{i}, Type{Type{RawValue{"System.Int32"}}}, Value{IntegerLiteral{RawValue{x}}}};

syntax sStringVarDeclaration = ","? i:tID '(' x:tStringLiteral ')' => DeclareVar{VariableName{i}, Type{Type{RawValue{"System.String"}}}, Value{StringLiteral{RawValue{x}}}};

So close to what you had above, it was easier to store the variables in a list though, and I also had to add some projections to get some of the nodes out of the graph I didn't need. Thanks for the help.