Writing a ParseKit grammar with a varying number of fields (in order)
-
28-05-2021 - |
Question
I'm not super experienced in writing grammars, but let's say I have a record type like these: (examples)
record # 1 source ages params A = 1 and b = 2 fields are A, B, C with values 1, 2, 3;
record # 2;
record # 3 source ages;
record # 4 params A = 1 and b = 2 fields are A, B, C with values 1, 2, 3;
record # 5 source ages fields are A, B, C with values 1, 2, 3;
record # 6 with values 1, 2, 3;
Basically:
- Must start with "record # Number" and end with a semi-colon.
- May contain 0 or 1 captures in the following order:
- source dataset
- parameters of dataset
- fields from dataset
- values from dataset
Here is my grammar, it's not working:
--- start grammar:
@start = record;
record = 'record' '#' numeric rest* ';';
rest = 'source' alphanumeric paramsAndOrFieldsAndOrWithValues*;
paramsAndOrFieldsAndOrWithValues = (paramsList)? (fieldsList)? (valuesList)?;
paramsList = 'params' alpha expr numeric ('and' alpha expr numeric)*;
fieldsList = 'fields' 'are' alpha (comma alpha)*;
valuesList = 'with' 'values' numeric (comma numeric)*;
alpha = Word;
numeric = Number;
alphanumeric = (alpha | numeric | '_' | '.');
comma = ',';
expr = '=';
--- end grammar
@"Developer from ParseKit", can you please help me?
Thanks :)
Solution
Developer of ParseKit here.
Your grammar is a little bit off. I worked up a grammar which matches your example input. I've run this using the DebugApp
target, and can confirm that it works for your example.
@start = records;
records = record+;
record = prefix source? params? fields? values? suffix;
prefix = 'record' '#' Number;
suffix = ';';
// source
source = 'source' Word;
// params
params = 'params' expr ('and' expr)*;
expr = name '=' Number;
name = Word;
// fields
fields = 'fields' 'are' name (',' name)*;
// values
values = 'with' 'values' val (',' val)*;
val = Number;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow