-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathyaml.go
More file actions
394 lines (340 loc) · 10.6 KB
/
yaml.go
File metadata and controls
394 lines (340 loc) · 10.6 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package languages
import (
"unicode"
"github.com/aretext/aretext/syntax/parser"
)
const (
yamlTokenRoleKey = parser.TokenRoleCustom1
yamlTokenRoleAliasOrAnchor = parser.TokenRoleCustom2
)
// YamlParseFunc returns a parse func for YAML.
func YamlParseFunc() parser.Func {
parseBlockStyle := yamlTransitionToFlowParseFunc().
Or(yamlKeyParseFunc()).
Or(yamlOverrideParseFunc()).
Or(yamlListParseFunc()).
Or(yamlAnchorAliasParseFunc()).
Or(yamlCommentParseFunc()).
Or(yamlBlockScalarParseFunc())
parseFlowStyle := yamlFlowStyleBracketsAndBracesParseFunc().
Or(yamlKeyParseFunc()).
Or(yamlCommentParseFunc()).
Or(yamlFlowScalarParseFunc())
return initialState(
yamlParseState{},
func(iter parser.TrackingRuneIter, state parser.State) parser.Result {
yamlState := state.(yamlParseState)
if len(yamlState.flowStyleStack) > 0 {
return parseFlowStyle(iter, state)
} else {
return parseBlockStyle(iter, state)
}
})
}
func yamlSkipIndentation(f parser.Func) parser.Func {
consumeIndentation := consumeRunesLike(func(r rune) bool {
return r == ' ' || r == '\t'
})
return consumeIndentation.MaybeBefore(f)
}
func yamlTransitionToFlowParseFunc() parser.Func {
parseFlowMapStart := consumeString("{").
Map(setState(yamlParseState{flowStyleStack: []yamlFlowStyle{yamlFlowStyleMap}}))
parseFlowArrayStart := consumeString("[").
Map(setState(yamlParseState{flowStyleStack: []yamlFlowStyle{yamlFlowStyleArray}}))
return yamlSkipIndentation(parseFlowMapStart.Or(parseFlowArrayStart))
}
func yamlFlowStyleBracketsAndBracesParseFunc() parser.Func {
pushFlowStack := func(flowState yamlFlowStyle) parser.MapFn {
return func(result parser.Result) parser.Result {
yamlState := result.NextState.(yamlParseState)
yamlState.flowStyleStack = append(yamlState.flowStyleStack, flowState)
return parser.Result{
NumConsumed: result.NumConsumed,
ComputedTokens: result.ComputedTokens,
NextState: parser.State(yamlState),
}
}
}
popFlowStack := func(flowState yamlFlowStyle) parser.MapFn {
return func(result parser.Result) parser.Result {
yamlState := result.NextState.(yamlParseState)
n := len(yamlState.flowStyleStack)
if n == 0 || yamlState.flowStyleStack[n-1] != flowState {
return result
}
yamlState.flowStyleStack = yamlState.flowStyleStack[0 : n-1]
return parser.Result{
NumConsumed: result.NumConsumed,
ComputedTokens: result.ComputedTokens,
NextState: parser.State(yamlState),
}
}
}
parseOpenBrace := consumeString("{").
Map(pushFlowStack(yamlFlowStyleMap))
parseCloseBrace := consumeString("}").
Map(popFlowStack(yamlFlowStyleMap))
parseOpenBracket := consumeString("[").
Map(pushFlowStack(yamlFlowStyleArray))
parseCloseBracket := consumeString("]").
Map(popFlowStack(yamlFlowStyleArray))
return yamlSkipIndentation(
parseOpenBrace.
Or(parseCloseBrace).
Or(parseOpenBracket).
Or(parseCloseBracket))
}
func yamlIdentifierRune(r rune) bool {
return unicode.IsLetter(r) || (r >= '0' && r <= '9') || r == '.' || r == '_' || r == '-' || r == '/'
}
func yamlKeyParseFunc() parser.Func {
consumeToKeyEnd := jsonConsumeToKeyEndParseFunc()
parseUnquotedKey := consumeRunesLike(yamlIdentifierRune).Then(consumeToKeyEnd)
parseQuotedKey := yamlStringParseFunc().Then(consumeToKeyEnd)
return yamlSkipIndentation(
parseUnquotedKey.
Or(parseQuotedKey).
ThenNot(consumeSingleRuneLike(func(r rune) bool {
return !unicode.IsSpace(r) // must be followed by space, newline, or EOF
})).
Map(recognizeToken(yamlTokenRoleKey)))
}
func yamlOverrideParseFunc() parser.Func {
return yamlSkipIndentation(
consumeString("<<:").
Map(recognizeToken(parser.TokenRoleOperator)))
}
func yamlAnchorAliasParseFunc() parser.Func {
return yamlSkipIndentation(
consumeString("*").
Or(consumeString("&")).
Then(consumeRunesLike(yamlIdentifierRune)).
Map(recognizeToken(yamlTokenRoleAliasOrAnchor)))
}
func yamlListParseFunc() parser.Func {
return yamlSkipIndentation(
consumeString("-").
ThenNot(consumeSingleRuneLike(func(r rune) bool {
return !unicode.IsSpace(r) // must be followed by space, newline, or EOF
})).
Map(recognizeToken(parser.TokenRoleOperator)))
}
func yamlStringParseFunc() parser.Func {
// Consume string wrapped in single-quotes, but treat '' as an escaped quote.
consumeSingleQuotedString := parser.Func(
func(iter parser.TrackingRuneIter, state parser.State) parser.Result {
// Consume first single-quote.
var n uint64
r, err := iter.NextRune()
if err != nil || r != '\'' {
return parser.FailedResult
}
n++
// Consume the rest of the string.
for {
r, err = iter.NextRune()
if err != nil {
// Couldn't find a closing quote.
return parser.FailedResult
}
n++
if r == '\'' {
// Found a single quote.
r, err = iter.NextRune()
if err != nil || r != '\'' {
// Found the end of the string.
return parser.Result{
NumConsumed: n,
NextState: state,
}
}
// The next rune is also a quote, so this is an escaped quote.
// Consume it and keep going.
n++
}
}
})
return consumeSingleQuotedString.
Or(consumeCStyleString('"', true)).
Map(recognizeToken(parser.TokenRoleString))
}
// Match at least two words separated by a space, continuing to the end of the line.
// Example: "123 abc" matches, but "123" does not.
func yamlMultiWordUnquotedScalarParseFunc(scalarRunePredicate func(r rune) bool) parser.Func {
return func(iter parser.TrackingRuneIter, state parser.State) parser.Result {
var searchState int
var n uint64
for {
r, err := iter.NextRune()
if err != nil || !scalarRunePredicate(r) {
break
}
n++
switch searchState {
case 0:
// Initially looking for non-space.
if !(r == ' ' || r == '\t') {
searchState = 1
}
case 1:
// Then look for a space.
if r == ' ' || r == '\t' {
searchState = 2
}
case 2:
// Then look for a non-space again.
if !(r == ' ' || r == '\t') {
searchState = 3
}
}
}
if searchState == 3 {
return parser.Result{
NumConsumed: n,
NextState: state,
}
} else {
return parser.FailedResult
}
}
}
func yamlSingleWordUnquotedScalarParseFunc(scalarRunePredicate func(r rune) bool) parser.Func {
keywords := []string{"true", "false", "null"}
yamlScalarRune := func(r rune) bool {
return scalarRunePredicate(r) && !unicode.IsSpace(r)
}
return consumeRunesLike(yamlScalarRune).
MapWithInput(recognizeKeywordOrConsume(keywords))
}
func yamlBlockScalarParseFunc() parser.Func {
scalarRunePredicate := func(r rune) bool {
return !(r == '#' || r == '\n')
}
parseMultiWordUnquotedScalar := yamlMultiWordUnquotedScalarParseFunc(scalarRunePredicate)
parseSingleWordUnquotedScalar := yamlSingleWordUnquotedScalarParseFunc(scalarRunePredicate)
parseBlockStyleIndicator := consumeString("|").Or(consumeString(">")).
Map(recognizeToken(parser.TokenRoleOperator))
parseBlockChompingIndicator := consumeString("-").Or(consumeString("+")).
Map(recognizeToken(parser.TokenRoleOperator))
// Count indentation from the current position.
// The YAML spec forbids mixing tabs and spaces in indentation, so we don't differentiate
// between them (both increase the indentation level by one).
countIndentation := func(iter parser.TrackingRuneIter) uint64 {
var n uint64
for {
r, err := iter.NextRune()
if err != nil || !(r == ' ' || r == '\t' || r == '\n') {
break
}
n++
}
return n
}
skipToEndOfLineOrFile := func(iter *parser.TrackingRuneIter) uint64 {
var n uint64
for {
r, err := iter.NextRune()
if err != nil {
break
}
n++
if r == '\n' {
break
}
}
return n
}
// This is a bit of a hack that most YAML syntax highlighters use.
// Suppose we have a block scalar like this:
//
// key1:
// first line
// second line
// third line
// key2: 123
//
// How do we know that the scalar ends before "key2"?
// We count the spaces at the start of "first line", then consume every
// subsequent line indented by at least that many spaces.
consumeBlockLines := parser.Func(
func(iter parser.TrackingRuneIter, state parser.State) parser.Result {
firstLineIndent := countIndentation(iter)
n := skipToEndOfLineOrFile(&iter)
for {
nextLineIndent := countIndentation(iter)
if nextLineIndent < firstLineIndent {
break
} else {
m := skipToEndOfLineOrFile(&iter)
if m == 0 {
// End of file.
break
}
n += m
}
}
return parser.Result{
NumConsumed: n,
NextState: state,
}
})
parseBlockLines := consumeToNextLineFeed.
ThenMaybe(consumeBlockLines).
Map(recognizeToken(parser.TokenRoleString))
parseBlockScalar := parseBlockStyleIndicator.
ThenMaybe(parseBlockChompingIndicator).
ThenMaybe(parseBlockLines)
return yamlSkipIndentation(
parseBlockScalar.
Or(yamlStringParseFunc()).
Or(parseMultiWordUnquotedScalar).
Or(jsonNumberParseFunc()).
Or(parseSingleWordUnquotedScalar))
}
func yamlFlowScalarParseFunc() parser.Func {
scalarRunePredicate := func(r rune) bool {
return !(r == ',' || r == '{' || r == '}' || r == '[' || r == ']' || r == '#' || r == '\n')
}
return yamlSkipIndentation(
yamlStringParseFunc().
Or(yamlMultiWordUnquotedScalarParseFunc(scalarRunePredicate)).
Or(jsonNumberParseFunc()).
Or(yamlSingleWordUnquotedScalarParseFunc(scalarRunePredicate)))
}
func yamlCommentParseFunc() parser.Func {
return consumeString("#").
ThenMaybe(consumeToNextLineFeed).
Map(recognizeToken(parser.TokenRoleComment))
}
// yamlFlowStyle represents the current flow style (map or array)
// "Flow" style in YAML uses brackets and braces to deliminate maps and arrays
// (similar to JSON). This contrasts with the more common "block" style.
type yamlFlowStyle byte
const (
yamlFlowStyleMap = yamlFlowStyle(iota)
yamlFlowStyleArray
)
// yamlParseState represents the state of the YAML parser.
// We use this to determine whether we're currently parsing a flow style or block style.
// To do this, maintain a stack of flow style states. Starting a map or array ("{" or "[")
// pushes to the stack; ending a map or array ("}" or "]") pops from the stack.
// If the stack is empty, we're in block style; otherwise, we're in flow style.
type yamlParseState struct {
flowStyleStack []yamlFlowStyle
}
func (s yamlParseState) Equals(other parser.State) bool {
otherState, ok := other.(yamlParseState)
if !ok {
return false
}
if len(s.flowStyleStack) != len(otherState.flowStyleStack) {
return false
}
for i := 0; i < len(s.flowStyleStack); i++ {
if s.flowStyleStack[i] != otherState.flowStyleStack[i] {
return false
}
}
return true
}