7 Build your own Grammar!
7.1 Example of a context free grammar
Below is an example for a grammar for numbers:
| ‹Number› | ::= | ‹PositiveNumber› |
| | | | -‹PositiveNumber› |
| ‹PositiveNumber› | ::= | ‹Integer› |
| | | | ‹Decimal› |
| ‹Integer› | ::= | ‹DigitNotZero› ‹Digit›* |
| | | | 0 |
| ‹Decimal› | ::= | ‹Integer› . ‹Digit›+ |
| ‹DigitNotZero› | ::= | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| ‹Digit› | ::= | 0 | ‹DigitNotZero› |
Examples for Strings that fulfill the ‹Number› definition of this grammar are: 0, 420, -87, 3.1416, -2.09900.
Examples for Strings that do not fulfill the ‹Number› definition of this grammar are: 007, -.65, 13., zwölf, 111Nonsense222.
Here is an example of an AST based on the previous grammar.
{
"production": "<Number>",
"code": "-|3,14|",
"holes": [
{
"production": "<PositiveNumber>",
"code": "|3,14|",
"holes": [{
"production": "<Decimal>",
"code": "|3|,|1||4|",
"holes": [
{
"production": "<Integer>",
"code": "|3|",
"holes":[{
"production": "<DigitNotZero>",
"code": "3"
}]
},
{
"production": "<Digit>",
"code": "|1|",
"holes":[{
"production": "<DigitNotZero>",
"code": "1"
}]
},
{
"production": "<Digit>",
"code": "|4|",
"holes":[{
"production": "<DigitNotZero>",
"code": "4"
}]
}
]
}]
}
],
"grammar": {
"<Number>": ["<PositiveNumber>", "-<PositiveNumber>"],
"<PositiveNumber>": ["<Integer>", "<Decimal>"],
"<Integer>": ["<DigitNotZero><Digit>*", "0"],
"<Decimal>": ["<Integer>.<Digit>+"],
"<DigitNotZero>": ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
"<Digit>": ["0", "<DigitNotZero>"]
}
}
{
"production": "<Number>",
"code": "|420|",
"holes": [
{
"production": "<PositiveNumber>",
"code": "|420|",
"holes": [{
"production": "<Integer>",
"code": "|4||2||0|",
"holes": [
{
"production": "<DigitNotZero>",
"code": "4"
},
{
"production": "<Digit>",
"code": "|2|",
"holes": [{
"production": "<DigitNotZero>",
"code": "2"
}]
},
{
"production": "<Digit>",
"code": "0"
}
]
}]
}
],
"grammar": {
"<Number>": ["<PositiveNumber>", "-<PositiveNumber>"],
"<PositiveNumber>": ["<Integer>", "<Decimal>"],
"<Integer>": ["<DigitNotZero><Digit>*", "0"],
"<Decimal>": ["<Integer>.<Digit>+"],
"<DigitNotZero>": ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
"<Digit>": ["0", "<DigitNotZero>"]
}
}