Fixing/upgrading csv example.
from __future__ import unicode_literals
from parglare import Grammar, Parser
+from parglare.actions import pass_inner, pass_nochange, pass_single, \
+ collect_sep
grammar = r"""
CSVFile = OptionalNewLines Records OptionalNewLines;
-Records = Record | Records OptionalNewLines Record;
+Records = Records OptionalNewLines Record| Record;
Record = Fields NewLine;
-Fields = Field | Fields "," Field;
+Fields = Fields "," Field | Field;
Field = QuotedField | FieldContent;
NewLines = NewLine | NewLines NewLine;
OptionalNewLines = NewLines | EMPTY;
@@ -16,45 +18,16 @@ NewLine = "\n";
"""
-def collect_with_sep(_, nodes):
- res = nodes[0]
- res.append(nodes[2])
- return res
-
-
-def collect(_, nodes):
- res = nodes[0]
- res.append(nodes[1])
- return res
-
-
-def pass_value(_, value):
- return value
-
-
-def pass_single_node(_, nodes):
- return nodes[0]
-
-
-def pass_none(_, n):
- return None
-
-
# Semantic Actions
actions = {
- "CSVFile": lambda _, nodes: nodes[1],
- "Records:1": lambda _, nodes: [nodes[0]],
- "Records:2": collect_with_sep,
- "Record": lambda _, nodes: nodes[0],
- "Fields:1": lambda _, nodes: [nodes[0]],
- "Fields:2": collect_with_sep,
- "Field": pass_single_node,
- "QuotedField": lambda _, nodes: nodes[1],
- "FieldContent": pass_value,
- "FieldContentQuoted": pass_value,
- "NewLines": pass_none,
- "NewLine": pass_none,
- "OptionalNewLines": pass_none,
+ "CSVFile": pass_inner,
+ "Records": collect_sep,
+ "Record": pass_single,
+ "Fields": collect_sep,
+ "Field": pass_single,
+ "QuotedField": pass_inner,
+ "FieldContent": pass_nochange,
+ "FieldContentQuoted": pass_nochange,
}
