-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtake_while.dart
95 lines (87 loc) · 2.06 KB
/
take_while.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
part of '../../bytes.dart';
/// Parses while [predicate] satisfies the criteria and returns a substring of
/// the parsed data.
///
/// Example:
/// ```dart
/// TakeWhile(CharClass('[#x21-#x7e]'))
/// ```
class TakeWhile extends ParserBuilder<String, String> {
static const _template16 = '''
final {{pos}} = state.pos;
while (state.pos < source.length) {
final c = source.codeUnitAt(state.pos);
final ok = {{test}};
if (!ok) {
break;
}
state.pos++;
}
state.ok = true;
if (state.ok) {
{{res0}} = {{pos}} == state.pos ? '' : source.substring({{pos}}, state.pos);
}''';
static const _template16Fast = '''
while (state.pos < source.length) {
final c = source.codeUnitAt(state.pos);
final ok = {{test}};
if (!ok) {
break;
}
state.pos++;
}
state.ok = true;''';
static const _template32 = '''
final {{pos}} = state.pos;
while (state.pos < source.length) {
final pos = state.pos;
final c = source.readRune(state);
final ok = {{test}};
if (!ok) {
state.pos = pos;
break;
}
}
state.ok = true;
if (state.ok) {
{{res0}} = {{pos}} == state.pos ? '' : source.substring({{pos}}, state.pos);
}''';
static const _template32Fast = '''
while (state.pos < source.length) {
final pos = state.pos;
final c = source.readRune(state);
final ok = {{test}};
if (!ok) {
state.pos = pos;
break;
}
}
state.ok = true;''';
final SemanticAction<bool> predicate;
const TakeWhile(this.predicate);
@override
String build(Context context, ParserResult? result) {
context.refersToStateSource = true;
final fast = result == null;
final values = context.allocateLocals(['pos']);
values.addAll({
'test': predicate.build(context, 'test', ['c']),
});
final isUnicode = predicate.isUnicode;
final String template;
if (isUnicode) {
if (fast) {
template = _template32Fast;
} else {
template = _template32;
}
} else {
if (fast) {
template = _template16Fast;
} else {
template = _template16;
}
}
return render(template, values, [result]);
}
}