Question

I'm attempting to create a simple DSL to handle reasonably complex dice-rolling instructions using Irony .NET. The basic calculator functionality was simple enough to implement (addition, subtraction, etc). However, when I reached the point where I finally got around to adding the roll expression, I ran into trouble. Ideally, I would like a roll expression to take the form: ndm Where n is the number of dice to roll, and m is the number of sides on each die.

My problem here is that I want the expressions next to the d, and if I do this Irony complains that the d is an invalid character. Spaces around it work (1 d 6), and replacing it with a non-alphanumeric character works(1%6). At the moment I have it working simply by replacing each d in the source with " d ", but this obviously won't work when I get to variables (which I plan on prefacing with '$' to set them apart).

Question is, how can I make it work without the spaces (1d6), preferably without any massive changes in the grammar? (Note: It's perfectly okay if it still works with the spaces, I just don't want them to be required.)

expression = new NonTerminal("expression");
add = new NonTerminal("add");
subtract = new NonTerminal("subtract");
multiply = new NonTerminal("multiply");
divide = new NonTerminal("divide");
roll = new NonTerminal("roll");

expression.Rule = number | add | subtract | multiply | divide | roll;
add.Rule = expression + "+" + expression;
subtract.Rule = expression + "-" + expression;
multiply.Rule = expression + "*" + expression;
divide.Rule = expression + "/" + expression;
roll.Rule = expression + "d" + expression;

RegisterOperators(1, "+", "-");
RegisterOperators(2, "*", "/");
RegisterOperators(3, "d");

MarkPunctuation("+", "-", "*", "/", "d");
MarkTransient(expression);

this.Root = expression;
Was it helpful?

Solution

The problem is you need some way of telling where a token starts and ends. Without being able to first break up the string into tokens, the grammar can't figure out what's what.

I do believe Irony does support this, have a look at AssignWhitespaceAndDelimiters(), it looks like "d" needs to be added to the list of key terms, or could be added as a delimiter itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top