Debian Codegraph @

text_parser.go

raw symbols SCIP
1 // Parser for text plist formats.
2 // @see https://github.com/apple/swift-corelibs-foundation/blob/master/CoreFoundation/Parsing.subproj/CFOldStylePList.c
3 // @see https://github.com/gnustep/libs-base/blob/master/Source/NSPropertyList.m
4 // This parser also handles strings files.
5
6 package plist
7
8 import (
9 "encoding/base64"
10 "encoding/binary"
11 "errors"
12 "fmt"
13 "io"
14 "io/ioutil"
15 "runtime"
16 "strings"
17 "time"
18 "unicode/utf16"
19 "unicode/utf8"
20 )
21
22 type textPlistParser struct {
23 reader io.Reader
24 format int
25
26 input string
27 start int
28 pos int
29 width int
30 }
31
32 func convertU16(buffer []byte, bo binary.ByteOrder) (string, error) {
33 if len(buffer)%2 != 0 {
34 return "", errors.New("truncated utf16")
35 }
36
37 tmp := make([]uint16, len(buffer)/2)
38 for i := 0; i < len(buffer); i += 2 {
39 tmp[i/2] = bo.Uint16(buffer[i : i+2])
40 }
41 return string(utf16.Decode(tmp)), nil
42 }
43
44 func guessEncodingAndConvert(buffer []byte) (string, error) {
45 if len(buffer) >= 3 && buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF {
46 // UTF-8 BOM
47 return zeroCopy8BitString(buffer, 3, len(buffer)-3), nil
48 } else if len(buffer) >= 2 {
49 // UTF-16 guesses
50
51 switch {
52 // stream is big-endian (BOM is FE FF or head is 00 XX)
53 case (buffer[0] == 0xFE && buffer[1] == 0xFF):
54 return convertU16(buffer[2:], binary.BigEndian)
55 case (buffer[0] == 0 && buffer[1] != 0):
56 return convertU16(buffer, binary.BigEndian)
57
58 // stream is little-endian (BOM is FE FF or head is XX 00)
59 case (buffer[0] == 0xFF && buffer[1] == 0xFE):
60 return convertU16(buffer[2:], binary.LittleEndian)
61 case (buffer[0] != 0 && buffer[1] == 0):
62 return convertU16(buffer, binary.LittleEndian)
63 }
64 }
65
66 // fallback: assume ASCII (not great!)
67 return zeroCopy8BitString(buffer, 0, len(buffer)), nil
68 }
69
70 func (p *textPlistParser) parseDocument() (pval cfValue, parseError error) {
71 defer func() {
72 if r := recover(); r != nil {
73 if _, ok := r.(runtime.Error); ok {
74 panic(r)
75 }
76 // Wrap all non-invalid-plist errors.
77 parseError = plistParseError{"text", r.(error)}
78 }
79 }()
80
81 buffer, err := ioutil.ReadAll(p.reader)
82 if err != nil {
83 panic(err)
84 }
85
86 p.input, err = guessEncodingAndConvert(buffer)
87 if err != nil {
88 panic(err)
89 }
90
91 val := p.parsePlistValue()
92
93 p.skipWhitespaceAndComments()
94 if p.peek() != eof {
95 if _, ok := val.(cfString); !ok {
96 p.error("garbage after end of document")
97 }
98
99 // Try parsing as .strings.
100 // See -[NSDictionary propertyListFromStringsFileFormat:].
101 p.start = 0
102 p.pos = 0
103 val = p.parseDictionary(true)
104 }
105
106 pval = val
107
108 return
109 }
110
111 const eof rune = -1
112
113 func (p *textPlistParser) error(e string, args ...interface{}) {
114 line := strings.Count(p.input[:p.pos], "\n")
115 char := p.pos - strings.LastIndex(p.input[:p.pos], "\n") - 1
116 panic(fmt.Errorf("%s at line %d character %d", fmt.Sprintf(e, args...), line, char))
117 }
118
119 func (p *textPlistParser) next() rune {
120 if int(p.pos) >= len(p.input) {
121 p.width = 0
122 return eof
123 }
124 r, w := utf8.DecodeRuneInString(p.input[p.pos:])
125 p.width = w
126 p.pos += p.width
127 return r
128 }
129
130 func (p *textPlistParser) backup() {
131 p.pos -= p.width
132 }
133
134 func (p *textPlistParser) peek() rune {
135 r := p.next()
136 p.backup()
137 return r
138 }
139
140 func (p *textPlistParser) emit() string {
141 s := p.input[p.start:p.pos]
142 p.start = p.pos
143 return s
144 }
145
146 func (p *textPlistParser) ignore() {
147 p.start = p.pos
148 }
149
150 func (p *textPlistParser) empty() bool {
151 return p.start == p.pos
152 }
153
154 func (p *textPlistParser) scanUntil(ch rune) {
155 if x := strings.IndexRune(p.input[p.pos:], ch); x >= 0 {
156 p.pos += x
157 return
158 }
159 p.pos = len(p.input)
160 }
161
162 func (p *textPlistParser) scanUntilAny(chs string) {
163 if x := strings.IndexAny(p.input[p.pos:], chs); x >= 0 {
164 p.pos += x
165 return
166 }
167 p.pos = len(p.input)
168 }
169
170 func (p *textPlistParser) scanCharactersInSet(ch *characterSet) {
171 for ch.Contains(p.next()) {
172 }
173 p.backup()
174 }
175
176 func (p *textPlistParser) scanCharactersNotInSet(ch *characterSet) {
177 var r rune
178 for {
179 r = p.next()
180 if r == eof || ch.Contains(r) {
181 break
182 }
183 }
184 p.backup()
185 }
186
187 func (p *textPlistParser) skipWhitespaceAndComments() {
188 for {
189 p.scanCharactersInSet(&whitespace)
190 if strings.HasPrefix(p.input[p.pos:], "//") {
191 p.scanCharactersNotInSet(&newlineCharacterSet)
192 } else if strings.HasPrefix(p.input[p.pos:], "/*") {
193 if x := strings.Index(p.input[p.pos:], "*/"); x >= 0 {
194 p.pos += x + 2 // skip the */ as well
195 continue // consume more whitespace
196 } else {
197 p.error("unexpected eof in block comment")
198 }
199 } else {
200 break
201 }
202 }
203 p.ignore()
204 }
205
206 func (p *textPlistParser) parseOctalDigits(max int) uint64 {
207 var val uint64
208
209 for i := 0; i < max; i++ {
210 r := p.next()
211
212 if r >= '0' && r <= '7' {
213 val <<= 3
214 val |= uint64((r - '0'))
215 } else {
216 p.backup()
217 break
218 }
219 }
220 return val
221 }
222
223 func (p *textPlistParser) parseHexDigits(max int) uint64 {
224 var val uint64
225
226 for i := 0; i < max; i++ {
227 r := p.next()
228
229 if r >= 'a' && r <= 'f' {
230 val <<= 4
231 val |= 10 + uint64((r - 'a'))
232 } else if r >= 'A' && r <= 'F' {
233 val <<= 4
234 val |= 10 + uint64((r - 'A'))
235 } else if r >= '0' && r <= '9' {
236 val <<= 4
237 val |= uint64((r - '0'))
238 } else {
239 p.backup()
240 break
241 }
242 }
243 return val
244 }
245
246 // the \ has already been consumed
247 func (p *textPlistParser) parseEscape() string {
248 var s string
249 switch p.next() {
250 case 'a':
251 s = "\a"
252 case 'b':
253 s = "\b"
254 case 'v':
255 s = "\v"
256 case 'f':
257 s = "\f"
258 case 't':
259 s = "\t"
260 case 'r':
261 s = "\r"
262 case 'n':
263 s = "\n"
264 case '\\':
265 s = `\`
266 case '"':
267 s = `"`
268 case 'x': // This is our extension.
269 s = string(rune(p.parseHexDigits(2)))
270 case 'u', 'U': // 'u' is a GNUstep extension.
271 s = string(rune(p.parseHexDigits(4)))
272 case '0', '1', '2', '3', '4', '5', '6', '7':
273 p.backup() // we've already consumed one of the digits
274 s = string(rune(p.parseOctalDigits(3)))
275 default:
276 p.backup() // everything else should be accepted
277 }
278 p.ignore() // skip the entire escape sequence
279 return s
280 }
281
282 // the " has already been consumed
283 func (p *textPlistParser) parseQuotedString() cfString {
284 p.ignore() // ignore the "
285
286 slowPath := false
287 s := ""
288
289 for {
290 p.scanUntilAny(`"\`)
291 switch p.peek() {
292 case eof:
293 p.error("unexpected eof in quoted string")
294 case '"':
295 section := p.emit()
296 p.pos++ // skip "
297 if !slowPath {
298 return cfString(section)
299 } else {
300 s += section
301 return cfString(s)
302 }
303 case '\\':
304 slowPath = true
305 s += p.emit()
306 p.next() // consume \
307 s += p.parseEscape()
308 }
309 }
310 }
311
312 func (p *textPlistParser) parseUnquotedString() cfString {
313 p.scanCharactersNotInSet(&gsQuotable)
314 s := p.emit()
315 if s == "" {
316 p.error("invalid unquoted string (found an unquoted character that should be quoted?)")
317 }
318
319 return cfString(s)
320 }
321
322 // the { has already been consumed
323 func (p *textPlistParser) parseDictionary(ignoreEof bool) cfValue {
324 //p.ignore() // ignore the {
325 var keypv cfValue
326 keys := make([]string, 0, 32)
327 values := make([]cfValue, 0, 32)
328 outer:
329 for {
330 p.skipWhitespaceAndComments()
331
332 switch p.next() {
333 case eof:
334 if !ignoreEof {
335 p.error("unexpected eof in dictionary")
336 }
337 fallthrough
338 case '}':
339 break outer
340 case '"':
341 keypv = p.parseQuotedString()
342 default:
343 p.backup()
344 keypv = p.parseUnquotedString()
345 }
346
347 // INVARIANT: key can't be nil; parseQuoted and parseUnquoted
348 // will panic out before they return nil.
349
350 p.skipWhitespaceAndComments()
351
352 var val cfValue
353 n := p.next()
354 if n == ';' {
355 // This is supposed to be .strings-specific.
356 // GNUstep parses this as an empty string.
357 // Apple copies the key like we do.
358 val = keypv
359 } else if n == '=' {
360 // whitespace is consumed within
361 val = p.parsePlistValue()
362
363 p.skipWhitespaceAndComments()
364
365 if p.next() != ';' {
366 p.error("missing ; in dictionary")
367 }
368 } else {
369 p.error("missing = in dictionary")
370 }
371
372 keys = append(keys, string(keypv.(cfString)))
373 values = append(values, val)
374 }
375
376 dict := &cfDictionary{keys: keys, values: values}
377 return dict.maybeUID(p.format == OpenStepFormat)
378 }
379
380 // the ( has already been consumed
381 func (p *textPlistParser) parseArray() *cfArray {
382 //p.ignore() // ignore the (
383 values := make([]cfValue, 0, 32)
384 outer:
385 for {
386 p.skipWhitespaceAndComments()
387
388 switch p.next() {
389 case eof:
390 p.error("unexpected eof in array")
391 case ')':
392 break outer // done here
393 case ',':
394 continue // restart; ,) is valid and we don't want to blow it
395 default:
396 p.backup()
397 }
398
399 pval := p.parsePlistValue() // whitespace is consumed within
400 if str, ok := pval.(cfString); ok && string(str) == "" {
401 // Empty strings in arrays are apparently skipped?
402 // TODO: Figure out why this was implemented.
403 continue
404 }
405 values = append(values, pval)
406 }
407 return &cfArray{values}
408 }
409
410 // the <* have already been consumed
411 func (p *textPlistParser) parseGNUStepValue() cfValue {
412 typ := p.next()
413
414 if typ == '>' || typ == eof { // <*>, <*EOF
415 p.error("invalid GNUStep extended value")
416 }
417
418 if typ != 'I' && typ != 'R' && typ != 'B' && typ != 'D' {
419 // early out: no need to collect the value if we'll fail to understand it
420 p.error("unknown GNUStep extended value type `" + string(typ) + "'")
421 }
422
423 if p.peek() == '"' { // <*x"
424 p.next()
425 }
426
427 p.ignore()
428 p.scanUntil('>')
429
430 if p.peek() == eof { // <*xEOF or <*x"EOF
431 p.error("unterminated GNUStep extended value")
432 }
433
434 if p.empty() { // <*x>, <*x"">
435 p.error("empty GNUStep extended value")
436 }
437
438 v := p.emit()
439 p.next() // consume the >
440
441 if v[len(v)-1] == '"' {
442 // GNUStep tolerates malformed quoted values, as in <*I5"> and <*I"5>
443 // It purportedly does so by stripping the trailing quote
444 v = v[:len(v)-1]
445 }
446
447 switch typ {
448 case 'I':
449 if len(v) == 0 {
450 p.error("truncated GNUStep extended value")
451 }
452 if v[0] == '-' {
453 n := mustParseInt(v, 10, 64)
454 return &cfNumber{signed: true, value: uint64(n)}
455 } else {
456 n := mustParseUint(v, 10, 64)
457 return &cfNumber{signed: false, value: n}
458 }
459 case 'R':
460 n := mustParseFloat(v, 64)
461 return &cfReal{wide: true, value: n} // TODO(DH) 32/64
462 case 'B':
463 if len(v) == 0 {
464 p.error("truncated GNUStep extended value")
465 }
466 b := v[0] == 'Y'
467 return cfBoolean(b)
468 case 'D':
469 t, err := time.Parse(textPlistTimeLayout, v)
470 if err != nil {
471 p.error(err.Error())
472 }
473
474 return cfDate(t.In(time.UTC))
475 }
476 // We should never get here; we checked the type above
477 return nil
478 }
479
480 // the <[ have already been consumed
481 func (p *textPlistParser) parseGNUStepBase64() cfData {
482 p.ignore()
483 p.scanUntil(']')
484 v := p.emit()
485
486 if p.next() != ']' {
487 p.error("invalid GNUStep base64 data (expected ']')")
488 }
489
490 if p.next() != '>' {
491 p.error("invalid GNUStep base64 data (expected '>')")
492 }
493
494 // Emulate NSDataBase64DecodingIgnoreUnknownCharacters
495 filtered := strings.Map(base64ValidChars.Map, v)
496 data, err := base64.StdEncoding.DecodeString(filtered)
497 if err != nil {
498 p.error("invalid GNUStep base64 data: " + err.Error())
499 }
500 return cfData(data)
501 }
502
503 // The < has already been consumed
504 func (p *textPlistParser) parseHexData() cfData {
505 buf := make([]byte, 256)
506 i := 0
507 c := 0
508
509 for {
510 r := p.next()
511 switch r {
512 case eof:
513 p.error("unexpected eof in data")
514 case '>':
515 if c&1 == 1 {
516 p.error("uneven number of hex digits in data")
517 }
518 p.ignore()
519 return cfData(buf[:i])
520 // Apple and GNUstep both want these in pairs. We are a bit more lax.
521 // GS accepts comments too, but that seems like a lot of work.
522 case ' ', '\t', '\n', '\r', '\u2028', '\u2029':
523 continue
524 }
525
526 buf[i] <<= 4
527 if r >= 'a' && r <= 'f' {
528 buf[i] |= 10 + byte((r - 'a'))
529 } else if r >= 'A' && r <= 'F' {
530 buf[i] |= 10 + byte((r - 'A'))
531 } else if r >= '0' && r <= '9' {
532 buf[i] |= byte((r - '0'))
533 } else {
534 p.error("unexpected hex digit `%c'", r)
535 }
536
537 c++
538 if c&1 == 0 {
539 i++
540 if i >= len(buf) {
541 realloc := make([]byte, len(buf)*2)
542 copy(realloc, buf)
543 buf = realloc
544 }
545 }
546 }
547 }
548
549 func (p *textPlistParser) parsePlistValue() cfValue {
550 for {
551 p.skipWhitespaceAndComments()
552
553 switch p.next() {
554 case eof:
555 return &cfDictionary{}
556 case '<':
557 switch p.next() {
558 case '*':
559 p.format = GNUStepFormat
560 return p.parseGNUStepValue()
561 case '[':
562 p.format = GNUStepFormat
563 return p.parseGNUStepBase64()
564 default:
565 p.backup()
566 return p.parseHexData()
567 }
568 case '"':
569 return p.parseQuotedString()
570 case '{':
571 return p.parseDictionary(false)
572 case '(':
573 return p.parseArray()
574 default:
575 p.backup()
576 return p.parseUnquotedString()
577 }
578 }
579 }
580
581 func newTextPlistParser(r io.Reader) *textPlistParser {
582 return &textPlistParser{
583 reader: r,
584 format: OpenStepFormat,
585 }
586 }