OLD | NEW |
| (Empty) |
1 part of petitparser.reflection; | |
2 | |
3 /// A function transforming one parser to another one. | |
4 typedef Parser TransformationHandler(Parser parser); | |
5 | |
6 /// Transforms all parsers reachable from [parser] with the given [handler]. | |
7 /// The identity function returns a copy of the the incoming parser. | |
8 /// | |
9 /// The implementation first creates a copy of each parser reachable in the | |
10 /// input grammar; then the resulting grammar is traversed until all references | |
11 /// to old parsers are replaced with the transformed ones. | |
12 Parser transformParser(Parser parser, TransformationHandler handler) { | |
13 var mapping = new Map.identity(); | |
14 for (var each in allParser(parser)) { | |
15 mapping[each] = handler(each.copy()); | |
16 } | |
17 var seen = new Set.from(mapping.values); | |
18 var todo = new List.from(mapping.values); | |
19 while (todo.isNotEmpty) { | |
20 var parent = todo.removeLast(); | |
21 for (var child in parent.children) { | |
22 if (mapping.containsKey(child)) { | |
23 parent.replace(child, mapping[child]); | |
24 } else if (!seen.contains(child)) { | |
25 seen.add(child); | |
26 todo.add(child); | |
27 } | |
28 } | |
29 } | |
30 return mapping[parser]; | |
31 } | |
OLD | NEW |