OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 library yaml.scanner; |
| 6 |
| 7 import 'package:collection/collection.dart'; |
| 8 import 'package:string_scanner/string_scanner.dart'; |
| 9 import 'package:source_span/source_span.dart'; |
| 10 |
| 11 import 'style.dart'; |
| 12 import 'token.dart'; |
| 13 import 'utils.dart'; |
| 14 import 'yaml_exception.dart'; |
| 15 |
| 16 /// A scanner that reads a string of Unicode characters and emits [Token]s. |
| 17 /// |
| 18 /// This is based on the libyaml scanner, available at |
| 19 /// https://github.com/yaml/libyaml/blob/master/src/scanner.c. The license for |
| 20 /// that is available in ../../libyaml-license.txt. |
| 21 class Scanner { |
| 22 static const TAB = 0x9; |
| 23 static const LF = 0xA; |
| 24 static const CR = 0xD; |
| 25 static const SP = 0x20; |
| 26 static const DOLLAR = 0x24; |
| 27 static const LEFT_PAREN = 0x28; |
| 28 static const RIGHT_PAREN = 0x29; |
| 29 static const PLUS = 0x2B; |
| 30 static const COMMA = 0x2C; |
| 31 static const HYPHEN = 0x2D; |
| 32 static const PERIOD = 0x2E; |
| 33 static const QUESTION = 0x3F; |
| 34 static const COLON = 0x3A; |
| 35 static const SEMICOLON = 0x3B; |
| 36 static const EQUALS = 0x3D; |
| 37 static const LEFT_SQUARE = 0x5B; |
| 38 static const RIGHT_SQUARE = 0x5D; |
| 39 static const LEFT_CURLY = 0x7B; |
| 40 static const RIGHT_CURLY = 0x7D; |
| 41 static const HASH = 0x23; |
| 42 static const AMPERSAND = 0x26; |
| 43 static const ASTERISK = 0x2A; |
| 44 static const EXCLAMATION = 0x21; |
| 45 static const VERTICAL_BAR = 0x7C; |
| 46 static const LEFT_ANGLE = 0x3C; |
| 47 static const RIGHT_ANGLE = 0x3E; |
| 48 static const SINGLE_QUOTE = 0x27; |
| 49 static const DOUBLE_QUOTE = 0x22; |
| 50 static const PERCENT = 0x25; |
| 51 static const AT = 0x40; |
| 52 static const GRAVE_ACCENT = 0x60; |
| 53 static const TILDE = 0x7E; |
| 54 |
| 55 static const NULL = 0x0; |
| 56 static const BELL = 0x7; |
| 57 static const BACKSPACE = 0x8; |
| 58 static const VERTICAL_TAB = 0xB; |
| 59 static const FORM_FEED = 0xC; |
| 60 static const ESCAPE = 0x1B; |
| 61 static const SLASH = 0x2F; |
| 62 static const BACKSLASH = 0x5C; |
| 63 static const UNDERSCORE = 0x5F; |
| 64 static const NEL = 0x85; |
| 65 static const NBSP = 0xA0; |
| 66 static const LINE_SEPARATOR = 0x2028; |
| 67 static const PARAGRAPH_SEPARATOR = 0x2029; |
| 68 static const BOM = 0xFEFF; |
| 69 |
| 70 static const NUMBER_0 = 0x30; |
| 71 static const NUMBER_9 = 0x39; |
| 72 |
| 73 static const LETTER_A = 0x61; |
| 74 static const LETTER_B = 0x62; |
| 75 static const LETTER_E = 0x65; |
| 76 static const LETTER_F = 0x66; |
| 77 static const LETTER_N = 0x6E; |
| 78 static const LETTER_R = 0x72; |
| 79 static const LETTER_T = 0x74; |
| 80 static const LETTER_U = 0x75; |
| 81 static const LETTER_V = 0x76; |
| 82 static const LETTER_X = 0x78; |
| 83 static const LETTER_Z = 0x7A; |
| 84 |
| 85 static const LETTER_CAP_A = 0x41; |
| 86 static const LETTER_CAP_F = 0x46; |
| 87 static const LETTER_CAP_L = 0x4C; |
| 88 static const LETTER_CAP_N = 0x4E; |
| 89 static const LETTER_CAP_P = 0x50; |
| 90 static const LETTER_CAP_U = 0x55; |
| 91 static const LETTER_CAP_X = 0x58; |
| 92 static const LETTER_CAP_Z = 0x5A; |
| 93 |
| 94 /// The underlying [SpanScanner] used to read characters from the source text. |
| 95 /// |
| 96 /// This is also used to track line and column information and to generate |
| 97 /// [SourceSpan]s. |
| 98 final SpanScanner _scanner; |
| 99 |
| 100 /// Whether this scanner has produced a [TokenType.STREAM_START] token |
| 101 /// indicating the beginning of the YAML stream. |
| 102 var _streamStartProduced = false; |
| 103 |
| 104 /// Whether this scanner has produced a [TokenType.STREAM_END] token |
| 105 /// indicating the end of the YAML stream. |
| 106 var _streamEndProduced = false; |
| 107 |
| 108 /// The queue of tokens yet to be emitted. |
| 109 /// |
| 110 /// These are queued up in advance so that [TokenType.KEY] tokens can be |
| 111 /// inserted once the scanner determines that a series of tokens represents a |
| 112 /// mapping key. |
| 113 final _tokens = new QueueList<Token>(); |
| 114 |
| 115 /// The number of tokens that have been emitted. |
| 116 /// |
| 117 /// This doesn't count tokens in [tokens]. |
| 118 var _tokensParsed = 0; |
| 119 |
| 120 /// Whether the next token in [_tokens] is ready to be returned. |
| 121 /// |
| 122 /// It might not be ready if there may still be a [TokenType.KEY] inserted |
| 123 /// before it. |
| 124 var _tokenAvailable = false; |
| 125 |
| 126 /// The stack of indent levels for the current nested block contexts. |
| 127 /// |
| 128 /// The YAML spec specifies that the initial indentation level is -1 spaces. |
| 129 final _indents = <int>[-1]; |
| 130 |
| 131 /// Whether a simple key is allowed in this context. |
| 132 /// |
| 133 /// A simple key refers to any mapping key that doesn't have an explicit "?". |
| 134 var _simpleKeyAllowed = true; |
| 135 |
| 136 /// The stack of potential simple keys for each level of flow nesting. |
| 137 /// |
| 138 /// Entries in this list may be `null`, indicating that there is no valid |
| 139 /// simple key for the associated level of nesting. |
| 140 /// |
| 141 /// When a ":" is parsed and there's a simple key available, a [TokenType.KEY] |
| 142 /// token is inserted in [_tokens] before that key's token. This allows the |
| 143 /// parser to tell that the key is intended to be a mapping key. |
| 144 final _simpleKeys = <_SimpleKey>[null]; |
| 145 |
| 146 /// The current indentation level. |
| 147 int get _indent => _indents.last; |
| 148 |
| 149 /// Whether the scanner's currently positioned in a block-level structure (as |
| 150 /// opposed to flow-level). |
| 151 bool get _inBlockContext => _simpleKeys.length == 1; |
| 152 |
| 153 /// Whether the current character is a line break or the end of the source. |
| 154 bool get _isBreakOrEnd => _scanner.isDone || _isBreak; |
| 155 |
| 156 /// Whether the current character is a line break. |
| 157 bool get _isBreak => _isBreakAt(0); |
| 158 |
| 159 /// Whether the current character is whitespace or the end of the source. |
| 160 bool get _isBlankOrEnd => _isBlankOrEndAt(0); |
| 161 |
| 162 /// Whether the current character is whitespace. |
| 163 bool get _isBlank => _isBlankAt(0); |
| 164 |
| 165 /// Whether the current character is a valid tag name character. |
| 166 /// |
| 167 /// See http://yaml.org/spec/1.2/spec.html#ns-tag-name. |
| 168 bool get _isTagChar { |
| 169 var char = _scanner.peekChar(); |
| 170 if (char == null) return false; |
| 171 switch (char) { |
| 172 case HYPHEN: |
| 173 case SEMICOLON: |
| 174 case SLASH: |
| 175 case COLON: |
| 176 case AT: |
| 177 case AMPERSAND: |
| 178 case EQUALS: |
| 179 case PLUS: |
| 180 case DOLLAR: |
| 181 case PERIOD: |
| 182 case TILDE: |
| 183 case QUESTION: |
| 184 case ASTERISK: |
| 185 case SINGLE_QUOTE: |
| 186 case LEFT_PAREN: |
| 187 case RIGHT_PAREN: |
| 188 case PERCENT: |
| 189 return true; |
| 190 default: |
| 191 return (char >= NUMBER_0 && char <= NUMBER_9) || |
| 192 (char >= LETTER_A && char <= LETTER_Z) || |
| 193 (char >= LETTER_CAP_A && char <= LETTER_CAP_Z); |
| 194 } |
| 195 } |
| 196 |
| 197 /// Whether the current character is a valid anchor name character. |
| 198 /// |
| 199 /// See http://yaml.org/spec/1.2/spec.html#ns-anchor-name. |
| 200 bool get _isAnchorChar { |
| 201 if (!_isNonSpace) return false; |
| 202 |
| 203 switch (_scanner.peekChar()) { |
| 204 case COMMA: |
| 205 case LEFT_SQUARE: |
| 206 case RIGHT_SQUARE: |
| 207 case LEFT_CURLY: |
| 208 case RIGHT_CURLY: |
| 209 return false; |
| 210 default: |
| 211 return true; |
| 212 } |
| 213 } |
| 214 |
| 215 /// Whether the character at the current position is a decimal digit. |
| 216 bool get _isDigit { |
| 217 var char = _scanner.peekChar(); |
| 218 return char != null && (char >= NUMBER_0 && char <= NUMBER_9); |
| 219 } |
| 220 |
| 221 /// Whether the character at the current position is a hexidecimal |
| 222 /// digit. |
| 223 bool get _isHex { |
| 224 var char = _scanner.peekChar(); |
| 225 if (char == null) return false; |
| 226 return (char >= NUMBER_0 && char <= NUMBER_9) || |
| 227 (char >= LETTER_A && char <= LETTER_F) || |
| 228 (char >= LETTER_CAP_A && char <= LETTER_CAP_F); |
| 229 } |
| 230 |
| 231 /// Whether the character at the current position is a plain character. |
| 232 /// |
| 233 /// See http://yaml.org/spec/1.2/spec.html#ns-plain-char(c). |
| 234 bool get _isPlainChar => _isPlainCharAt(0); |
| 235 |
| 236 /// Whether the character at the current position is a printable character |
| 237 /// other than a line break or byte-order mark. |
| 238 /// |
| 239 /// See http://yaml.org/spec/1.2/spec.html#nb-char. |
| 240 bool get _isNonBreak { |
| 241 var char = _scanner.peekChar(); |
| 242 if (char == null) return false; |
| 243 switch (char) { |
| 244 case LF: |
| 245 case CR: |
| 246 case BOM: |
| 247 return false; |
| 248 case TAB: |
| 249 case NEL: |
| 250 return true; |
| 251 default: |
| 252 return (char >= 0x00020 && char <= 0x00007E) || |
| 253 (char >= 0x000A0 && char <= 0x00D7FF) || |
| 254 (char >= 0x0E000 && char <= 0x00FFFD) || |
| 255 (char >= 0x10000 && char <= 0x10FFFF); |
| 256 } |
| 257 } |
| 258 |
| 259 /// Whether the character at the current position is a printable character |
| 260 /// other than whitespace. |
| 261 /// |
| 262 /// See http://yaml.org/spec/1.2/spec.html#nb-char. |
| 263 bool get _isNonSpace { |
| 264 var char = _scanner.peekChar(); |
| 265 if (char == null) return false; |
| 266 switch (char) { |
| 267 case LF: |
| 268 case CR: |
| 269 case BOM: |
| 270 case SP: |
| 271 return false; |
| 272 case NEL: |
| 273 return true; |
| 274 default: |
| 275 return (char >= 0x00020 && char <= 0x00007E) || |
| 276 (char >= 0x000A0 && char <= 0x00D7FF) || |
| 277 (char >= 0x0E000 && char <= 0x00FFFD) || |
| 278 (char >= 0x10000 && char <= 0x10FFFF); |
| 279 } |
| 280 } |
| 281 |
| 282 /// Returns Whether or not the current character begins a documentation |
| 283 /// indicator. |
| 284 /// |
| 285 /// If so, this sets the scanner's last match to that indicator. |
| 286 bool get _isDocumentIndicator { |
| 287 return _scanner.column == 0 && _isBlankOrEndAt(3) && |
| 288 (_scanner.matches('---') || _scanner.matches('...')); |
| 289 } |
| 290 |
| 291 /// Creates a scanner that scans [source]. |
| 292 /// |
| 293 /// [sourceUrl] can be a String or a [Uri]. |
| 294 Scanner(String source, {sourceUrl}) |
| 295 : _scanner = new SpanScanner(source, sourceUrl: sourceUrl); |
| 296 |
| 297 /// Consumes and returns the next token. |
| 298 Token scan() { |
| 299 if (_streamEndProduced) throw new StateError("Out of tokens."); |
| 300 if (!_tokenAvailable) _fetchMoreTokens(); |
| 301 |
| 302 var token = _tokens.removeFirst(); |
| 303 _tokenAvailable = false; |
| 304 _tokensParsed++; |
| 305 _streamEndProduced = token is Token && |
| 306 token.type == TokenType.STREAM_END; |
| 307 return token; |
| 308 } |
| 309 |
| 310 /// Consumes the next token and returns the one after that. |
| 311 Token advance() { |
| 312 scan(); |
| 313 return peek(); |
| 314 } |
| 315 |
| 316 /// Returns the next token without consuming it. |
| 317 Token peek() { |
| 318 if (_streamEndProduced) return null; |
| 319 if (!_tokenAvailable) _fetchMoreTokens(); |
| 320 return _tokens.first; |
| 321 } |
| 322 |
| 323 /// Ensures that [_tokens] contains at least one token which can be returned. |
| 324 void _fetchMoreTokens() { |
| 325 while (true) { |
| 326 if (_tokens.isNotEmpty) { |
| 327 _staleSimpleKeys(); |
| 328 |
| 329 // If the current token could be a simple key, we need to scan more |
| 330 // tokens until we determine whether it is or not. Otherwise we might |
| 331 // not emit the `KEY` token before we emit the value of the key. |
| 332 if (!_simpleKeys.any((key) => |
| 333 key != null && key.tokenNumber == _tokensParsed)) { |
| 334 break; |
| 335 } |
| 336 } |
| 337 |
| 338 _fetchNextToken(); |
| 339 } |
| 340 _tokenAvailable = true; |
| 341 } |
| 342 |
| 343 /// The dispatcher for token fetchers. |
| 344 void _fetchNextToken() { |
| 345 if (!_streamStartProduced) { |
| 346 _fetchStreamStart(); |
| 347 return; |
| 348 } |
| 349 |
| 350 _scanToNextToken(); |
| 351 _staleSimpleKeys(); |
| 352 _unrollIndent(_scanner.column); |
| 353 |
| 354 if (_scanner.isDone) { |
| 355 _fetchStreamEnd(); |
| 356 return; |
| 357 } |
| 358 |
| 359 if (_scanner.column == 0) { |
| 360 if (_scanner.peekChar() == PERCENT) { |
| 361 _fetchDirective(); |
| 362 return; |
| 363 } |
| 364 |
| 365 if (_isBlankOrEndAt(3)) { |
| 366 if (_scanner.matches('---')) { |
| 367 _fetchDocumentIndicator(TokenType.DOCUMENT_START); |
| 368 return; |
| 369 } |
| 370 |
| 371 if (_scanner.matches('...')) { |
| 372 _fetchDocumentIndicator(TokenType.DOCUMENT_END); |
| 373 return; |
| 374 } |
| 375 } |
| 376 } |
| 377 |
| 378 switch (_scanner.peekChar()) { |
| 379 case LEFT_SQUARE: |
| 380 _fetchFlowCollectionStart(TokenType.FLOW_SEQUENCE_START); |
| 381 return; |
| 382 case LEFT_CURLY: |
| 383 _fetchFlowCollectionStart(TokenType.FLOW_MAPPING_START); |
| 384 return; |
| 385 case RIGHT_SQUARE: |
| 386 _fetchFlowCollectionEnd(TokenType.FLOW_SEQUENCE_END); |
| 387 return; |
| 388 case RIGHT_CURLY: |
| 389 _fetchFlowCollectionEnd(TokenType.FLOW_MAPPING_END); |
| 390 return; |
| 391 case COMMA: |
| 392 _fetchFlowEntry(); |
| 393 return; |
| 394 case ASTERISK: |
| 395 _fetchAnchor(anchor: false); |
| 396 return; |
| 397 case AMPERSAND: |
| 398 _fetchAnchor(anchor: true); |
| 399 return; |
| 400 case EXCLAMATION: |
| 401 _fetchTag(); |
| 402 return; |
| 403 case SINGLE_QUOTE: |
| 404 _fetchFlowScalar(singleQuote: true); |
| 405 return; |
| 406 case DOUBLE_QUOTE: |
| 407 _fetchFlowScalar(singleQuote: false); |
| 408 return; |
| 409 case VERTICAL_BAR: |
| 410 if (!_inBlockContext) _invalidScalarCharacter(); |
| 411 _fetchBlockScalar(literal: true); |
| 412 return; |
| 413 case RIGHT_ANGLE: |
| 414 if (!_inBlockContext) _invalidScalarCharacter(); |
| 415 _fetchBlockScalar(literal: false); |
| 416 return; |
| 417 case PERCENT: |
| 418 case AT: |
| 419 case GRAVE_ACCENT: |
| 420 _invalidScalarCharacter(); |
| 421 return; |
| 422 |
| 423 // These characters may sometimes begin plain scalars. |
| 424 case HYPHEN: |
| 425 if (_isPlainCharAt(1)) { |
| 426 _fetchPlainScalar(); |
| 427 } else { |
| 428 _fetchBlockEntry(); |
| 429 } |
| 430 return; |
| 431 case QUESTION: |
| 432 if (_isPlainCharAt(1)) { |
| 433 _fetchPlainScalar(); |
| 434 } else { |
| 435 _fetchKey(); |
| 436 } |
| 437 return; |
| 438 case COLON: |
| 439 if (!_inBlockContext && _tokens.isNotEmpty) { |
| 440 // If a colon follows a "JSON-like" value (an explicit map or list, or |
| 441 // a quoted string) it isn't required to have whitespace after it |
| 442 // since it unambiguously describes a map. |
| 443 var token = _tokens.last; |
| 444 if (token.type == TokenType.FLOW_SEQUENCE_END || |
| 445 token.type == TokenType.FLOW_MAPPING_END || |
| 446 (token.type == TokenType.SCALAR && token.style.isQuoted)) { |
| 447 _fetchValue(); |
| 448 return; |
| 449 } |
| 450 } |
| 451 |
| 452 if (_isPlainCharAt(1)) { |
| 453 _fetchPlainScalar(); |
| 454 } else { |
| 455 _fetchValue(); |
| 456 } |
| 457 return; |
| 458 default: |
| 459 if (!_isNonBreak) _invalidScalarCharacter(); |
| 460 |
| 461 _fetchPlainScalar(); |
| 462 return; |
| 463 } |
| 464 |
| 465 throw 'Inaccessible'; |
| 466 } |
| 467 |
| 468 /// Throws an error about a disallowed character. |
| 469 void _invalidScalarCharacter() => |
| 470 _scanner.error("Unexpected character.", length: 1); |
| 471 |
| 472 /// Checks the list of potential simple keys and remove the positions that |
| 473 /// cannot contain simple keys anymore. |
| 474 void _staleSimpleKeys() { |
| 475 for (var i = 0; i < _simpleKeys.length; i++) { |
| 476 var key = _simpleKeys[i]; |
| 477 if (key == null) continue; |
| 478 |
| 479 // libyaml requires that all simple keys be a single line and no longer |
| 480 // than 1024 characters. However, in section 7.4.2 of the spec |
| 481 // (http://yaml.org/spec/1.2/spec.html#id2790832), these restrictions are |
| 482 // only applied when the curly braces are omitted. It's difficult to |
| 483 // retain enough context to know which keys need to have the restriction |
| 484 // placed on them, so for now we go the other direction and allow |
| 485 // everything but multiline simple keys in a block context. |
| 486 if (!_inBlockContext) continue; |
| 487 |
| 488 if (key.location.line == _scanner.line) continue; |
| 489 |
| 490 if (key.required) { |
| 491 throw new YamlException("Expected ':'.", _scanner.emptySpan); |
| 492 } |
| 493 |
| 494 _simpleKeys[i] = null; |
| 495 } |
| 496 } |
| 497 |
| 498 /// Checks if a simple key may start at the current position and saves it if |
| 499 /// so. |
| 500 void _saveSimpleKey() { |
| 501 // A simple key is required at the current position if the scanner is in the |
| 502 // block context and the current column coincides with the indentation |
| 503 // level. |
| 504 var required = _inBlockContext && _indent == _scanner.column; |
| 505 |
| 506 // A simple key is required only when it is the first token in the current |
| 507 // line. Therefore it is always allowed. But we add a check anyway. |
| 508 assert(_simpleKeyAllowed || !required); |
| 509 |
| 510 if (!_simpleKeyAllowed) return; |
| 511 |
| 512 // If the current position may start a simple key, save it. |
| 513 _removeSimpleKey(); |
| 514 _simpleKeys[_simpleKeys.length - 1] = new _SimpleKey( |
| 515 _tokensParsed + _tokens.length, |
| 516 _scanner.location, |
| 517 required: required); |
| 518 } |
| 519 |
| 520 /// Removes a potential simple key at the current flow level. |
| 521 void _removeSimpleKey() { |
| 522 var key = _simpleKeys.last; |
| 523 if (key != null && key.required) { |
| 524 throw new YamlException("Could not find expected ':' for simple key.", |
| 525 key.location.pointSpan()); |
| 526 } |
| 527 |
| 528 _simpleKeys[_simpleKeys.length - 1] = null; |
| 529 } |
| 530 |
| 531 /// Increases the flow level and resizes the simple key list. |
| 532 void _increaseFlowLevel() { |
| 533 _simpleKeys.add(null); |
| 534 } |
| 535 |
| 536 /// Decreases the flow level. |
| 537 void _decreaseFlowLevel() { |
| 538 if (_inBlockContext) return; |
| 539 _simpleKeys.removeLast(); |
| 540 } |
| 541 |
| 542 /// Pushes the current indentation level to the stack and sets the new level |
| 543 /// if [column] is greater than [_indent]. |
| 544 /// |
| 545 /// If it is, appends or inserts the specified token into [_tokens]. If |
| 546 /// [tokenNumber] is provided, the corresponding token will be replaced; |
| 547 /// otherwise, the token will be added at the end. |
| 548 void _rollIndent(int column, TokenType type, SourceLocation location, |
| 549 {int tokenNumber}) { |
| 550 if (!_inBlockContext) return; |
| 551 if (_indent != -1 && _indent >= column) return; |
| 552 |
| 553 // Push the current indentation level to the stack and set the new |
| 554 // indentation level. |
| 555 _indents.add(column); |
| 556 |
| 557 // Create a token and insert it into the queue. |
| 558 var token = new Token(type, location.pointSpan()); |
| 559 if (tokenNumber == null) { |
| 560 _tokens.add(token); |
| 561 } else { |
| 562 _tokens.insert(tokenNumber - _tokensParsed, token); |
| 563 } |
| 564 } |
| 565 |
| 566 /// Pops indentation levels from [_indents] until the current level becomes |
| 567 /// less than or equal to [column]. |
| 568 /// |
| 569 /// For each indentation level, appends a [TokenType.BLOCK_END] token. |
| 570 void _unrollIndent(int column) { |
| 571 if (!_inBlockContext) return; |
| 572 |
| 573 while (_indent > column) { |
| 574 _tokens.add(new Token(TokenType.BLOCK_END, _scanner.emptySpan)); |
| 575 _indents.removeLast(); |
| 576 } |
| 577 } |
| 578 |
| 579 /// Pops indentation levels from [_indents] until the current level resets to |
| 580 /// -1. |
| 581 /// |
| 582 /// For each indentation level, appends a [TokenType.BLOCK_END] token. |
| 583 void _resetIndent() => _unrollIndent(-1); |
| 584 |
| 585 /// Produces a [TokenType.STREAM_START] token. |
| 586 void _fetchStreamStart() { |
| 587 // Much of libyaml's initialization logic here is done in variable |
| 588 // initializers instead. |
| 589 _streamStartProduced = true; |
| 590 _tokens.add(new Token(TokenType.STREAM_START, _scanner.emptySpan)); |
| 591 } |
| 592 |
| 593 /// Produces a [TokenType.STREAM_END] token. |
| 594 void _fetchStreamEnd() { |
| 595 _resetIndent(); |
| 596 _removeSimpleKey(); |
| 597 _simpleKeyAllowed = false; |
| 598 _tokens.add(new Token(TokenType.STREAM_END, _scanner.emptySpan)); |
| 599 } |
| 600 |
| 601 /// Produces a [TokenType.VERSION_DIRECTIVE] or [TokenType.TAG_DIRECTIVE] |
| 602 /// token. |
| 603 void _fetchDirective() { |
| 604 _resetIndent(); |
| 605 _removeSimpleKey(); |
| 606 _simpleKeyAllowed = false; |
| 607 var directive = _scanDirective(); |
| 608 if (directive != null) _tokens.add(directive); |
| 609 } |
| 610 |
| 611 /// Produces a [TokenType.DOCUMENT_START] or [TokenType.DOCUMENT_END] token. |
| 612 void _fetchDocumentIndicator(TokenType type) { |
| 613 _resetIndent(); |
| 614 _removeSimpleKey(); |
| 615 _simpleKeyAllowed = false; |
| 616 |
| 617 // Consume the indicator token. |
| 618 var start = _scanner.state; |
| 619 _scanner.readChar(); |
| 620 _scanner.readChar(); |
| 621 _scanner.readChar(); |
| 622 |
| 623 _tokens.add(new Token(type, _scanner.spanFrom(start))); |
| 624 } |
| 625 |
| 626 /// Produces a [TokenType.FLOW_SEQUENCE_START] or |
| 627 /// [TokenType.FLOW_MAPPING_START] token. |
| 628 void _fetchFlowCollectionStart(TokenType type) { |
| 629 _saveSimpleKey(); |
| 630 _increaseFlowLevel(); |
| 631 _simpleKeyAllowed = true; |
| 632 _addCharToken(type); |
| 633 } |
| 634 |
| 635 /// Produces a [TokenType.FLOW_SEQUENCE_END] or [TokenType.FLOW_MAPPING_END] |
| 636 /// token. |
| 637 void _fetchFlowCollectionEnd(TokenType type) { |
| 638 _removeSimpleKey(); |
| 639 _decreaseFlowLevel(); |
| 640 _simpleKeyAllowed = false; |
| 641 _addCharToken(type); |
| 642 } |
| 643 |
| 644 /// Produces a [TokenType.FLOW_ENTRY] token. |
| 645 void _fetchFlowEntry() { |
| 646 _removeSimpleKey(); |
| 647 _simpleKeyAllowed = true; |
| 648 _addCharToken(TokenType.FLOW_ENTRY); |
| 649 } |
| 650 |
| 651 /// Produces a [TokenType.BLOCK_ENTRY] token. |
| 652 void _fetchBlockEntry() { |
| 653 if (_inBlockContext) { |
| 654 if (!_simpleKeyAllowed) { |
| 655 throw new YamlException( |
| 656 "Block sequence entries are not allowed in this context.", |
| 657 _scanner.emptySpan); |
| 658 } |
| 659 |
| 660 _rollIndent( |
| 661 _scanner.column, |
| 662 TokenType.BLOCK_SEQUENCE_START, |
| 663 _scanner.emptySpan.start); |
| 664 } else { |
| 665 // It is an error for the '-' indicator to occur in the flow context, but |
| 666 // we let the Parser detect and report it because it's able to point to |
| 667 // the context. |
| 668 } |
| 669 |
| 670 _removeSimpleKey(); |
| 671 _simpleKeyAllowed = true; |
| 672 _addCharToken(TokenType.BLOCK_ENTRY); |
| 673 } |
| 674 |
| 675 /// Produces the [TokenType.KEY] token. |
| 676 void _fetchKey() { |
| 677 if (_inBlockContext) { |
| 678 if (!_simpleKeyAllowed) { |
| 679 throw new YamlException("Mapping keys are not allowed in this context.", |
| 680 _scanner.emptySpan); |
| 681 } |
| 682 |
| 683 _rollIndent( |
| 684 _scanner.column, |
| 685 TokenType.BLOCK_MAPPING_START, |
| 686 _scanner.emptySpan.start); |
| 687 } |
| 688 |
| 689 // Simple keys are allowed after `?` in a block context. |
| 690 _simpleKeyAllowed = _inBlockContext; |
| 691 _addCharToken(TokenType.KEY); |
| 692 } |
| 693 |
| 694 /// Produces the [TokenType.VALUE] token. |
| 695 void _fetchValue() { |
| 696 var simpleKey = _simpleKeys.last; |
| 697 if (simpleKey != null) { |
| 698 // Add a [TokenType.KEY] directive before the first token of the simple |
| 699 // key so the parser knows that it's part of a key/value pair. |
| 700 _tokens.insert(simpleKey.tokenNumber - _tokensParsed, |
| 701 new Token(TokenType.KEY, simpleKey.location.pointSpan())); |
| 702 |
| 703 // In the block context, we may need to add the |
| 704 // [TokenType.BLOCK_MAPPING_START] token. |
| 705 _rollIndent( |
| 706 simpleKey.location.column, |
| 707 TokenType.BLOCK_MAPPING_START, |
| 708 simpleKey.location, |
| 709 tokenNumber: simpleKey.tokenNumber); |
| 710 |
| 711 // Remove the simple key. |
| 712 _simpleKeys[_simpleKeys.length - 1] = null; |
| 713 |
| 714 // A simple key cannot follow another simple key. |
| 715 _simpleKeyAllowed = false; |
| 716 } else if (_inBlockContext) { |
| 717 // If we're here, we've found the ':' indicator following a complex key. |
| 718 |
| 719 if (!_simpleKeyAllowed) { |
| 720 throw new YamlException( |
| 721 "Mapping values are not allowed in this context.", |
| 722 _scanner.emptySpan); |
| 723 } |
| 724 |
| 725 _rollIndent( |
| 726 _scanner.column, |
| 727 TokenType.BLOCK_MAPPING_START, |
| 728 _scanner.location); |
| 729 _simpleKeyAllowed = true; |
| 730 } else if (_simpleKeyAllowed) { |
| 731 // If we're here, we've found the ':' indicator with an empty key. This |
| 732 // behavior differs from libyaml, which disallows empty implicit keys. |
| 733 _simpleKeyAllowed = false; |
| 734 _addCharToken(TokenType.KEY); |
| 735 } |
| 736 |
| 737 _addCharToken(TokenType.VALUE); |
| 738 } |
| 739 |
| 740 /// Adds a token with [type] to [_tokens]. |
| 741 /// |
| 742 /// The span of the new token is the current character. |
| 743 void _addCharToken(TokenType type) { |
| 744 var start = _scanner.state; |
| 745 _scanner.readChar(); |
| 746 _tokens.add(new Token(type, _scanner.spanFrom(start))); |
| 747 } |
| 748 |
| 749 /// Produces a [TokenType.ALIAS] or [TokenType.ANCHOR] token. |
| 750 void _fetchAnchor({bool anchor: true}) { |
| 751 _saveSimpleKey(); |
| 752 _simpleKeyAllowed = false; |
| 753 _tokens.add(_scanAnchor(anchor: anchor)); |
| 754 } |
| 755 |
| 756 /// Produces a [TokenType.TAG] token. |
| 757 void _fetchTag() { |
| 758 _saveSimpleKey(); |
| 759 _simpleKeyAllowed = false; |
| 760 _tokens.add(_scanTag()); |
| 761 } |
| 762 |
| 763 /// Produces a [TokenType.SCALAR] token with style [ScalarStyle.LITERAL] or |
| 764 /// [ScalarStyle.FOLDED]. |
| 765 void _fetchBlockScalar({bool literal: false}) { |
| 766 _removeSimpleKey(); |
| 767 _simpleKeyAllowed = true; |
| 768 _tokens.add(_scanBlockScalar(literal: literal)); |
| 769 } |
| 770 |
| 771 /// Produces a [TokenType.SCALAR] token with style [ScalarStyle.SINGLE_QUOTED] |
| 772 /// or [ScalarStyle.DOUBLE_QUOTED]. |
| 773 void _fetchFlowScalar({bool singleQuote: false}) { |
| 774 _saveSimpleKey(); |
| 775 _simpleKeyAllowed = false; |
| 776 _tokens.add(_scanFlowScalar(singleQuote: singleQuote)); |
| 777 } |
| 778 |
| 779 /// Produces a [TokenType.SCALAR] token with style [ScalarStyle.PLAIN]. |
| 780 void _fetchPlainScalar() { |
| 781 _saveSimpleKey(); |
| 782 _simpleKeyAllowed = false; |
| 783 _tokens.add(_scanPlainScalar()); |
| 784 } |
| 785 |
| 786 /// Eats whitespace and comments until the next token is found. |
| 787 void _scanToNextToken() { |
| 788 var afterLineBreak = false; |
| 789 while (true) { |
| 790 // Allow the BOM to start a line. |
| 791 if (_scanner.column == 0) _scanner.scan("\uFEFF"); |
| 792 |
| 793 // Eat whitespace. |
| 794 // |
| 795 // libyaml disallows tabs after "-", "?", or ":", but the spec allows |
| 796 // them. See section 6.2: http://yaml.org/spec/1.2/spec.html#id2778241. |
| 797 while (_scanner.peekChar() == SP || |
| 798 ((!_inBlockContext || !afterLineBreak) && |
| 799 _scanner.peekChar() == TAB)) { |
| 800 _scanner.readChar(); |
| 801 } |
| 802 |
| 803 if (_scanner.peekChar() == TAB) { |
| 804 _scanner.error("Tab characters are not allowed as indentation.", |
| 805 length: 1); |
| 806 } |
| 807 |
| 808 // Eat a comment until a line break. |
| 809 _skipComment(); |
| 810 |
| 811 // If we're at a line break, eat it. |
| 812 if (_isBreak) { |
| 813 _skipLine(); |
| 814 |
| 815 // In the block context, a new line may start a simple key. |
| 816 if (_inBlockContext) _simpleKeyAllowed = true; |
| 817 afterLineBreak = true; |
| 818 } else { |
| 819 // Otherwise we've found a token. |
| 820 break; |
| 821 } |
| 822 } |
| 823 } |
| 824 |
| 825 /// Scans a [TokenType.YAML_DIRECTIVE] or [TokenType.TAG_DIRECTIVE] token. |
| 826 /// |
| 827 /// %YAML 1.2 # a comment \n |
| 828 /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 829 /// %TAG !yaml! tag:yaml.org,2002: \n |
| 830 /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 831 Token _scanDirective() { |
| 832 var start = _scanner.state; |
| 833 |
| 834 // Eat '%'. |
| 835 _scanner.readChar(); |
| 836 |
| 837 var token; |
| 838 var name = _scanDirectiveName(); |
| 839 if (name == "YAML") { |
| 840 token = _scanVersionDirectiveValue(start); |
| 841 } else if (name == "TAG") { |
| 842 token = _scanTagDirectiveValue(start); |
| 843 } else { |
| 844 warn("Warning: unknown directive.", _scanner.spanFrom(start)); |
| 845 |
| 846 // libyaml doesn't support unknown directives, but the spec says to ignore |
| 847 // them and warn: http://yaml.org/spec/1.2/spec.html#id2781147. |
| 848 while (!_isBreakOrEnd) { |
| 849 _scanner.readChar(); |
| 850 } |
| 851 |
| 852 return null; |
| 853 } |
| 854 |
| 855 // Eat the rest of the line, including any comments. |
| 856 _skipBlanks(); |
| 857 _skipComment(); |
| 858 |
| 859 if (!_isBreakOrEnd) { |
| 860 throw new YamlException( |
| 861 "Expected comment or line break after directive.", |
| 862 _scanner.spanFrom(start)); |
| 863 } |
| 864 |
| 865 _skipLine(); |
| 866 return token; |
| 867 } |
| 868 |
| 869 /// Scans a directive name. |
| 870 /// |
| 871 /// %YAML 1.2 # a comment \n |
| 872 /// ^^^^ |
| 873 /// %TAG !yaml! tag:yaml.org,2002: \n |
| 874 /// ^^^ |
| 875 String _scanDirectiveName() { |
| 876 // libyaml only allows word characters in directive names, but the spec |
| 877 // disagrees: http://yaml.org/spec/1.2/spec.html#ns-directive-name. |
| 878 var start = _scanner.position; |
| 879 while (_isNonSpace) { |
| 880 _scanner.readChar(); |
| 881 } |
| 882 |
| 883 var name = _scanner.substring(start); |
| 884 if (name.isEmpty) { |
| 885 throw new YamlException("Expected directive name.", _scanner.emptySpan); |
| 886 } else if (!_isBlankOrEnd) { |
| 887 throw new YamlException( |
| 888 "Unexpected character in directive name.", _scanner.emptySpan); |
| 889 } |
| 890 |
| 891 return name; |
| 892 } |
| 893 |
| 894 /// Scans the value of a version directive. |
| 895 /// |
| 896 /// %YAML 1.2 # a comment \n |
| 897 /// ^^^^^^ |
| 898 Token _scanVersionDirectiveValue(LineScannerState start) { |
| 899 _skipBlanks(); |
| 900 |
| 901 var major = _scanVersionDirectiveNumber(); |
| 902 _scanner.expect('.'); |
| 903 var minor = _scanVersionDirectiveNumber(); |
| 904 |
| 905 return new VersionDirectiveToken(_scanner.spanFrom(start), major, minor); |
| 906 } |
| 907 |
| 908 /// Scans the version number of a version directive. |
| 909 /// |
| 910 /// %YAML 1.2 # a comment \n |
| 911 /// ^ |
| 912 /// %YAML 1.2 # a comment \n |
| 913 /// ^ |
| 914 int _scanVersionDirectiveNumber() { |
| 915 var start = _scanner.position; |
| 916 while (_isDigit) { |
| 917 _scanner.readChar(); |
| 918 } |
| 919 |
| 920 var number = _scanner.substring(start); |
| 921 if (number.isEmpty) { |
| 922 throw new YamlException("Expected version number.", _scanner.emptySpan); |
| 923 } |
| 924 |
| 925 return int.parse(number); |
| 926 } |
| 927 |
| 928 /// Scans the value of a tag directive. |
| 929 /// |
| 930 /// %TAG !yaml! tag:yaml.org,2002: \n |
| 931 /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 932 Token _scanTagDirectiveValue(LineScannerState start) { |
| 933 _skipBlanks(); |
| 934 |
| 935 var handle = _scanTagHandle(directive: true); |
| 936 if (!_isBlank) { |
| 937 throw new YamlException("Expected whitespace.", _scanner.emptySpan); |
| 938 } |
| 939 |
| 940 _skipBlanks(); |
| 941 |
| 942 var prefix = _scanTagUri(); |
| 943 if (!_isBlankOrEnd) { |
| 944 throw new YamlException("Expected whitespace.", _scanner.emptySpan); |
| 945 } |
| 946 |
| 947 return new TagDirectiveToken(_scanner.spanFrom(start), handle, prefix); |
| 948 } |
| 949 |
| 950 /// Scans a [TokenType.ANCHOR] token. |
| 951 Token _scanAnchor({bool anchor: true}) { |
| 952 var start = _scanner.state; |
| 953 |
| 954 // Eat the indicator character. |
| 955 _scanner.readChar(); |
| 956 |
| 957 // libyaml only allows word characters in anchor names, but the spec |
| 958 // disagrees: http://yaml.org/spec/1.2/spec.html#ns-anchor-char. |
| 959 var startPosition = _scanner.position; |
| 960 while (_isAnchorChar) { |
| 961 _scanner.readChar(); |
| 962 } |
| 963 var name = _scanner.substring(startPosition); |
| 964 |
| 965 var next = _scanner.peekChar(); |
| 966 if (name.isEmpty || |
| 967 (!_isBlankOrEnd && next != QUESTION && next != COLON && |
| 968 next != COMMA && next != RIGHT_SQUARE && next != RIGHT_CURLY && |
| 969 next != PERCENT && next != AT && next != GRAVE_ACCENT)) { |
| 970 throw new YamlException("Expected alphanumeric character.", |
| 971 _scanner.emptySpan); |
| 972 } |
| 973 |
| 974 if (anchor) { |
| 975 return new AnchorToken(_scanner.spanFrom(start), name); |
| 976 } else { |
| 977 return new AliasToken(_scanner.spanFrom(start), name); |
| 978 } |
| 979 } |
| 980 |
| 981 /// Scans a [TokenType.TAG] token. |
| 982 Token _scanTag() { |
| 983 var handle; |
| 984 var suffix; |
| 985 var start = _scanner.state; |
| 986 |
| 987 // Check if the tag is in the canonical form. |
| 988 if (_scanner.peekChar(1) == LEFT_ANGLE) { |
| 989 // Eat '!<'. |
| 990 _scanner.readChar(); |
| 991 _scanner.readChar(); |
| 992 |
| 993 handle = ''; |
| 994 suffix = _scanTagUri(); |
| 995 |
| 996 _scanner.expect('>'); |
| 997 } else { |
| 998 // The tag has either the '!suffix' or the '!handle!suffix' form. |
| 999 |
| 1000 // First, try to scan a handle. |
| 1001 handle = _scanTagHandle(); |
| 1002 |
| 1003 if (handle.length > 1 && handle.startsWith('!') && handle.endsWith('!')) { |
| 1004 suffix = _scanTagUri(flowSeparators: false); |
| 1005 } else { |
| 1006 suffix = _scanTagUri(head: handle, flowSeparators: false); |
| 1007 |
| 1008 // There was no explicit handle. |
| 1009 if (suffix.isEmpty) { |
| 1010 // This is the special '!' tag. |
| 1011 handle = null; |
| 1012 suffix = '!'; |
| 1013 } else { |
| 1014 handle = '!'; |
| 1015 } |
| 1016 } |
| 1017 } |
| 1018 |
| 1019 // libyaml insists on whitespace after a tag, but example 7.2 indicates |
| 1020 // that it's not required: http://yaml.org/spec/1.2/spec.html#id2786720. |
| 1021 |
| 1022 return new TagToken(_scanner.spanFrom(start), handle, suffix); |
| 1023 } |
| 1024 |
| 1025 /// Scans a tag handle. |
| 1026 String _scanTagHandle({bool directive: false}) { |
| 1027 _scanner.expect('!'); |
| 1028 |
| 1029 var buffer = new StringBuffer('!'); |
| 1030 |
| 1031 // libyaml only allows word characters in tags, but the spec disagrees: |
| 1032 // http://yaml.org/spec/1.2/spec.html#ns-tag-char. |
| 1033 var start = _scanner.position; |
| 1034 while (_isTagChar) { |
| 1035 _scanner.readChar(); |
| 1036 } |
| 1037 buffer.write(_scanner.substring(start)); |
| 1038 |
| 1039 if (_scanner.peekChar() == EXCLAMATION) { |
| 1040 buffer.writeCharCode(_scanner.readChar()); |
| 1041 } else { |
| 1042 // It's either the '!' tag or not really a tag handle. If it's a %TAG |
| 1043 // directive, it's an error. If it's a tag token, it must be part of a |
| 1044 // URI. |
| 1045 if (directive && buffer.toString() != '!') _scanner.expect('!'); |
| 1046 } |
| 1047 |
| 1048 return buffer.toString(); |
| 1049 } |
| 1050 |
| 1051 /// Scans a tag URI. |
| 1052 /// |
| 1053 /// [head] is the initial portion of the tag that's already been scanned. |
| 1054 /// [flowSeparators] indicates whether the tag URI can contain flow |
| 1055 /// separators. |
| 1056 String _scanTagUri({String head, bool flowSeparators: true}) { |
| 1057 var length = head == null ? 0 : head.length; |
| 1058 var buffer = new StringBuffer(); |
| 1059 |
| 1060 // Copy the head if needed. |
| 1061 // |
| 1062 // Note that we don't copy the leading '!' character. |
| 1063 if (length > 1) buffer.write(head.substring(1)); |
| 1064 |
| 1065 // The set of characters that may appear in URI is as follows: |
| 1066 // |
| 1067 // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', |
| 1068 // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', |
| 1069 // '%'. |
| 1070 // |
| 1071 // In a shorthand tag annotation, the flow separators ',', '[', and ']' are |
| 1072 // disallowed. |
| 1073 var start = _scanner.position; |
| 1074 var char = _scanner.peekChar(); |
| 1075 while (_isTagChar || (flowSeparators && |
| 1076 (char == COMMA || char == LEFT_SQUARE || char == RIGHT_SQUARE))) { |
| 1077 _scanner.readChar(); |
| 1078 char = _scanner.peekChar(); |
| 1079 } |
| 1080 |
| 1081 // libyaml manually decodes the URL, but we don't have to do that. |
| 1082 return Uri.decodeFull(_scanner.substring(start)); |
| 1083 } |
| 1084 |
| 1085 /// Scans a block scalar. |
| 1086 Token _scanBlockScalar({bool literal: false}) { |
| 1087 var start = _scanner.state; |
| 1088 |
| 1089 // Eat the indicator '|' or '>'. |
| 1090 _scanner.readChar(); |
| 1091 |
| 1092 // Check for a chomping indicator. |
| 1093 var chomping = _Chomping.CLIP; |
| 1094 var increment = 0; |
| 1095 var char = _scanner.peekChar(); |
| 1096 if (char == PLUS || char == HYPHEN) { |
| 1097 chomping = char == PLUS ? _Chomping.KEEP : _Chomping.STRIP; |
| 1098 _scanner.readChar(); |
| 1099 |
| 1100 // Check for an indentation indicator. |
| 1101 if (_isDigit) { |
| 1102 // Check that the indentation is greater than 0. |
| 1103 if (_scanner.peekChar() == NUMBER_0) { |
| 1104 throw new YamlException( |
| 1105 "0 may not be used as an indentation indicator.", |
| 1106 _scanner.spanFrom(start)); |
| 1107 } |
| 1108 |
| 1109 increment = _scanner.readChar() - NUMBER_0; |
| 1110 } |
| 1111 } else if (_isDigit) { |
| 1112 // Do the same as above, but in the opposite order. |
| 1113 if (_scanner.peekChar() == NUMBER_0) { |
| 1114 throw new YamlException( |
| 1115 "0 may not be used as an indentation indicator.", |
| 1116 _scanner.spanFrom(start)); |
| 1117 } |
| 1118 |
| 1119 increment = _scanner.readChar() - NUMBER_0; |
| 1120 |
| 1121 char = _scanner.peekChar(); |
| 1122 if (char == PLUS || char == HYPHEN) { |
| 1123 chomping = char == PLUS ? _Chomping.KEEP : _Chomping.STRIP; |
| 1124 _scanner.readChar(); |
| 1125 } |
| 1126 } |
| 1127 |
| 1128 // Eat whitespace and comments to the end of the line. |
| 1129 _skipBlanks(); |
| 1130 _skipComment(); |
| 1131 |
| 1132 // Check if we're at the end of the line. |
| 1133 if (!_isBreakOrEnd) { |
| 1134 throw new YamlException("Expected comment or line break.", |
| 1135 _scanner.emptySpan); |
| 1136 } |
| 1137 |
| 1138 _skipLine(); |
| 1139 |
| 1140 // If the block scalar has an explicit indentation indicator, add that to |
| 1141 // the current indentation to get the indentation level for the scalar's |
| 1142 // contents. |
| 1143 var indent = 0; |
| 1144 if (increment != 0) { |
| 1145 indent = _indent >= 0 ? _indent + increment : increment; |
| 1146 } |
| 1147 |
| 1148 // Scan the leading line breaks to determine the indentation level if |
| 1149 // needed. |
| 1150 var pair = _scanBlockScalarBreaks(indent); |
| 1151 indent = pair.first; |
| 1152 var trailingBreaks = pair.last; |
| 1153 |
| 1154 // Scan the block scalar contents. |
| 1155 var buffer = new StringBuffer(); |
| 1156 var leadingBreak = ''; |
| 1157 var leadingBlank = false; |
| 1158 var trailingBlank = false; |
| 1159 while (_scanner.column == indent && !_scanner.isDone) { |
| 1160 // Check for a document indicator. libyaml doesn't do this, but the spec |
| 1161 // mandates it. See example 9.5: |
| 1162 // http://yaml.org/spec/1.2/spec.html#id2801606. |
| 1163 if (_isDocumentIndicator) break; |
| 1164 |
| 1165 // We are at the beginning of a non-empty line. |
| 1166 |
| 1167 // Is there trailing whitespace? |
| 1168 trailingBlank = _isBlank; |
| 1169 |
| 1170 // Check if we need to fold the leading line break. |
| 1171 if (!literal && leadingBreak.isNotEmpty && !leadingBlank && |
| 1172 !trailingBlank) { |
| 1173 // Do we need to join the lines with a space? |
| 1174 if (trailingBreaks.isEmpty) buffer.writeCharCode(SP); |
| 1175 } else { |
| 1176 buffer.write(leadingBreak); |
| 1177 } |
| 1178 leadingBreak = ''; |
| 1179 |
| 1180 // Append the remaining line breaks. |
| 1181 buffer.write(trailingBreaks); |
| 1182 |
| 1183 // Is there leading whitespace? |
| 1184 leadingBlank = _isBlank; |
| 1185 |
| 1186 var startPosition = _scanner.position; |
| 1187 while (!_isBreakOrEnd) { |
| 1188 _scanner.readChar(); |
| 1189 } |
| 1190 buffer.write(_scanner.substring(startPosition)); |
| 1191 |
| 1192 // libyaml always reads a line here, but this breaks on block scalars at |
| 1193 // the end of the document that end without newlines. See example 8.1: |
| 1194 // http://yaml.org/spec/1.2/spec.html#id2793888. |
| 1195 if (!_scanner.isDone) leadingBreak = _readLine(); |
| 1196 |
| 1197 // Eat the following indentation and spaces. |
| 1198 var pair = _scanBlockScalarBreaks(indent); |
| 1199 indent = pair.first; |
| 1200 trailingBreaks = pair.last; |
| 1201 } |
| 1202 |
| 1203 // Chomp the tail. |
| 1204 if (chomping != _Chomping.STRIP) buffer.write(leadingBreak); |
| 1205 if (chomping == _Chomping.KEEP) buffer.write(trailingBreaks); |
| 1206 |
| 1207 return new ScalarToken(_scanner.spanFrom(start), buffer.toString(), |
| 1208 literal ? ScalarStyle.LITERAL : ScalarStyle.FOLDED); |
| 1209 } |
| 1210 |
| 1211 /// Scans indentation spaces and line breaks for a block scalar. |
| 1212 /// |
| 1213 /// Determines the intendation level if needed. Returns the new indentation |
| 1214 /// level and the text of the line breaks. |
| 1215 Pair<int, String> _scanBlockScalarBreaks(int indent) { |
| 1216 var maxIndent = 0; |
| 1217 var breaks = new StringBuffer(); |
| 1218 |
| 1219 while (true) { |
| 1220 while ((indent == 0 || _scanner.column < indent) && |
| 1221 _scanner.peekChar() == SP) { |
| 1222 _scanner.readChar(); |
| 1223 } |
| 1224 |
| 1225 if (_scanner.column > maxIndent) maxIndent = _scanner.column; |
| 1226 |
| 1227 // libyaml throws an error here if a tab character is detected, but the |
| 1228 // spec treats tabs like any other non-space character. See example 8.2: |
| 1229 // http://yaml.org/spec/1.2/spec.html#id2794311. |
| 1230 |
| 1231 if (!_isBreak) break; |
| 1232 breaks.write(_readLine()); |
| 1233 } |
| 1234 |
| 1235 if (indent == 0) { |
| 1236 indent = maxIndent; |
| 1237 if (indent < _indent + 1) indent = _indent + 1; |
| 1238 |
| 1239 // libyaml forces indent to be at least 1 here, but that doesn't seem to |
| 1240 // be supported by the spec. |
| 1241 } |
| 1242 |
| 1243 return new Pair(indent, breaks.toString()); |
| 1244 } |
| 1245 |
| 1246 // Scans a quoted scalar. |
| 1247 Token _scanFlowScalar({bool singleQuote: false}) { |
| 1248 var start = _scanner.state; |
| 1249 var buffer = new StringBuffer(); |
| 1250 |
| 1251 // Eat the left quote. |
| 1252 _scanner.readChar(); |
| 1253 |
| 1254 while (true) { |
| 1255 // Check that there are no document indicators at the beginning of the |
| 1256 // line. |
| 1257 if (_isDocumentIndicator) { |
| 1258 _scanner.error("Unexpected document indicator."); |
| 1259 } |
| 1260 |
| 1261 if (_scanner.isDone) { |
| 1262 throw new YamlException("Unexpected end of file.", _scanner.emptySpan); |
| 1263 } |
| 1264 |
| 1265 var leadingBlanks = false; |
| 1266 while (!_isBlankOrEnd) { |
| 1267 var char = _scanner.peekChar(); |
| 1268 if (singleQuote && char == SINGLE_QUOTE && |
| 1269 _scanner.peekChar(1) == SINGLE_QUOTE) { |
| 1270 // An escaped single quote. |
| 1271 _scanner.readChar(); |
| 1272 _scanner.readChar(); |
| 1273 buffer.writeCharCode(SINGLE_QUOTE); |
| 1274 } else if (char == (singleQuote ? SINGLE_QUOTE : DOUBLE_QUOTE)) { |
| 1275 // The closing quote. |
| 1276 break; |
| 1277 } else if (!singleQuote && char == BACKSLASH && _isBreakAt(1)) { |
| 1278 // An escaped newline. |
| 1279 _scanner.readChar(); |
| 1280 _skipLine(); |
| 1281 leadingBlanks = true; |
| 1282 break; |
| 1283 } else if (!singleQuote && char == BACKSLASH) { |
| 1284 var escapeStart = _scanner.state; |
| 1285 |
| 1286 // An escape sequence. |
| 1287 var codeLength = null; |
| 1288 switch (_scanner.peekChar(1)) { |
| 1289 case NUMBER_0: |
| 1290 buffer.writeCharCode(NULL); |
| 1291 break; |
| 1292 case LETTER_A: |
| 1293 buffer.writeCharCode(BELL); |
| 1294 break; |
| 1295 case LETTER_B: |
| 1296 buffer.writeCharCode(BACKSPACE); |
| 1297 break; |
| 1298 case LETTER_T: |
| 1299 case TAB: |
| 1300 buffer.writeCharCode(TAB); |
| 1301 break; |
| 1302 case LETTER_N: |
| 1303 buffer.writeCharCode(LF); |
| 1304 break; |
| 1305 case LETTER_V: |
| 1306 buffer.writeCharCode(VERTICAL_TAB); |
| 1307 break; |
| 1308 case LETTER_F: |
| 1309 buffer.writeCharCode(FORM_FEED); |
| 1310 break; |
| 1311 case LETTER_R: |
| 1312 buffer.writeCharCode(CR); |
| 1313 break; |
| 1314 case LETTER_E: |
| 1315 buffer.writeCharCode(ESCAPE); |
| 1316 break; |
| 1317 case SP: |
| 1318 case DOUBLE_QUOTE: |
| 1319 case SLASH: |
| 1320 case BACKSLASH: |
| 1321 // libyaml doesn't support an escaped forward slash, but it was |
| 1322 // added in YAML 1.2. See section 5.7: |
| 1323 // http://yaml.org/spec/1.2/spec.html#id2776092 |
| 1324 buffer.writeCharCode(_scanner.peekChar(1)); |
| 1325 break; |
| 1326 case LETTER_CAP_N: |
| 1327 buffer.writeCharCode(NEL); |
| 1328 break; |
| 1329 case UNDERSCORE: |
| 1330 buffer.writeCharCode(NBSP); |
| 1331 break; |
| 1332 case LETTER_CAP_L: |
| 1333 buffer.writeCharCode(LINE_SEPARATOR); |
| 1334 break; |
| 1335 case LETTER_CAP_P: |
| 1336 buffer.writeCharCode(PARAGRAPH_SEPARATOR); |
| 1337 break; |
| 1338 case LETTER_X: |
| 1339 codeLength = 2; |
| 1340 break; |
| 1341 case LETTER_U: |
| 1342 codeLength = 4; |
| 1343 break; |
| 1344 case LETTER_CAP_U: |
| 1345 codeLength = 8; |
| 1346 break; |
| 1347 default: |
| 1348 throw new YamlException("Unknown escape character.", |
| 1349 _scanner.spanFrom(escapeStart)); |
| 1350 } |
| 1351 |
| 1352 _scanner.readChar(); |
| 1353 _scanner.readChar(); |
| 1354 |
| 1355 if (codeLength != null) { |
| 1356 var value = 0; |
| 1357 for (var i = 0; i < codeLength; i++) { |
| 1358 if (!_isHex) { |
| 1359 _scanner.readChar(); |
| 1360 throw new YamlException( |
| 1361 "Expected $codeLength-digit hexidecimal number.", |
| 1362 _scanner.spanFrom(escapeStart)); |
| 1363 } |
| 1364 |
| 1365 value = (value << 4) + _asHex(_scanner.readChar()); |
| 1366 } |
| 1367 |
| 1368 // Check the value and write the character. |
| 1369 if ((value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF) { |
| 1370 throw new YamlException( |
| 1371 "Invalid Unicode character escape code.", |
| 1372 _scanner.spanFrom(escapeStart)); |
| 1373 } |
| 1374 |
| 1375 buffer.writeCharCode(value); |
| 1376 } |
| 1377 } else { |
| 1378 buffer.writeCharCode(_scanner.readChar()); |
| 1379 } |
| 1380 } |
| 1381 |
| 1382 // Check if we're at the end of a scalar. |
| 1383 if (_scanner.peekChar() == (singleQuote ? SINGLE_QUOTE : DOUBLE_QUOTE)) { |
| 1384 break; |
| 1385 } |
| 1386 |
| 1387 var whitespace = new StringBuffer(); |
| 1388 var leadingBreak = ''; |
| 1389 var trailingBreaks = new StringBuffer(); |
| 1390 while (_isBlank || _isBreak) { |
| 1391 if (_isBlank) { |
| 1392 // Consume a space or a tab. |
| 1393 if (!leadingBlanks) { |
| 1394 whitespace.writeCharCode(_scanner.readChar()); |
| 1395 } else { |
| 1396 _scanner.readChar(); |
| 1397 } |
| 1398 } else { |
| 1399 // Check if it's a first line break. |
| 1400 if (!leadingBlanks) { |
| 1401 whitespace.clear(); |
| 1402 leadingBreak = _readLine(); |
| 1403 leadingBlanks = true; |
| 1404 } else { |
| 1405 trailingBreaks.write(_readLine()); |
| 1406 } |
| 1407 } |
| 1408 } |
| 1409 |
| 1410 // Join the whitespace or fold line breaks. |
| 1411 if (leadingBlanks) { |
| 1412 if (leadingBreak.isNotEmpty && trailingBreaks.isEmpty) { |
| 1413 buffer.writeCharCode(SP); |
| 1414 } else { |
| 1415 buffer.write(trailingBreaks); |
| 1416 } |
| 1417 } else { |
| 1418 buffer.write(whitespace); |
| 1419 whitespace.clear(); |
| 1420 } |
| 1421 } |
| 1422 |
| 1423 // Eat the right quote. |
| 1424 _scanner.readChar(); |
| 1425 |
| 1426 return new ScalarToken(_scanner.spanFrom(start), buffer.toString(), |
| 1427 singleQuote ? ScalarStyle.SINGLE_QUOTED : ScalarStyle.DOUBLE_QUOTED); |
| 1428 } |
| 1429 |
| 1430 /// Scans a plain scalar. |
| 1431 Token _scanPlainScalar() { |
| 1432 var start = _scanner.state; |
| 1433 var buffer = new StringBuffer(); |
| 1434 var leadingBreak = ''; |
| 1435 var trailingBreaks = ''; |
| 1436 var whitespace = new StringBuffer(); |
| 1437 var indent = _indent + 1; |
| 1438 |
| 1439 while (true) { |
| 1440 // Check for a document indicator. |
| 1441 if (_isDocumentIndicator) break; |
| 1442 |
| 1443 // Check for a comment. |
| 1444 if (_scanner.peekChar() == HASH) break; |
| 1445 |
| 1446 if (_isPlainChar) { |
| 1447 // Join the whitespace or fold line breaks. |
| 1448 if (leadingBreak.isNotEmpty) { |
| 1449 if (trailingBreaks.isEmpty) { |
| 1450 buffer.writeCharCode(SP); |
| 1451 } else { |
| 1452 buffer.write(trailingBreaks); |
| 1453 } |
| 1454 leadingBreak = ''; |
| 1455 trailingBreaks = ''; |
| 1456 } else { |
| 1457 buffer.write(whitespace); |
| 1458 whitespace.clear(); |
| 1459 } |
| 1460 } |
| 1461 |
| 1462 // libyaml's notion of valid identifiers differs substantially from YAML |
| 1463 // 1.2's. We use [_isPlainChar] instead of libyaml's character here. |
| 1464 var startPosition = _scanner.position; |
| 1465 while (_isPlainChar) { |
| 1466 _scanner.readChar(); |
| 1467 } |
| 1468 buffer.write(_scanner.substring(startPosition)); |
| 1469 |
| 1470 // Is it the end? |
| 1471 if (!_isBlank && !_isBreak) break; |
| 1472 |
| 1473 while (_isBlank || _isBreak) { |
| 1474 if (_isBlank) { |
| 1475 // Check for a tab character messing up the intendation. |
| 1476 if (leadingBreak.isNotEmpty && _scanner.column < indent && |
| 1477 _scanner.peekChar() == TAB) { |
| 1478 _scanner.error("Expected a space but found a tab.", length: 1); |
| 1479 } |
| 1480 |
| 1481 if (leadingBreak.isEmpty) { |
| 1482 whitespace.writeCharCode(_scanner.readChar()); |
| 1483 } else { |
| 1484 _scanner.readChar(); |
| 1485 } |
| 1486 } else { |
| 1487 // Check if it's a first line break. |
| 1488 if (leadingBreak.isEmpty) { |
| 1489 leadingBreak = _readLine(); |
| 1490 whitespace.clear(); |
| 1491 } else { |
| 1492 trailingBreaks = _readLine(); |
| 1493 } |
| 1494 } |
| 1495 } |
| 1496 |
| 1497 // Check the indentation level. |
| 1498 if (_inBlockContext && _scanner.column < indent) break; |
| 1499 } |
| 1500 |
| 1501 // Allow a simple key after a plain scalar with leading blanks. |
| 1502 if (leadingBreak.isNotEmpty) _simpleKeyAllowed = true; |
| 1503 |
| 1504 return new ScalarToken(_scanner.spanFrom(start), buffer.toString(), |
| 1505 ScalarStyle.PLAIN); |
| 1506 } |
| 1507 |
| 1508 /// Moves past the current line break, if there is one. |
| 1509 void _skipLine() { |
| 1510 var char = _scanner.peekChar(); |
| 1511 if (char != CR && char != LF) return; |
| 1512 _scanner.readChar(); |
| 1513 if (char == CR && _scanner.peekChar() == LF) _scanner.readChar(); |
| 1514 } |
| 1515 |
| 1516 // Moves past the current line break and returns a newline. |
| 1517 String _readLine() { |
| 1518 var char = _scanner.peekChar(); |
| 1519 |
| 1520 // libyaml supports NEL, PS, and LS characters as line separators, but this |
| 1521 // is explicitly forbidden in section 5.4 of the YAML spec. |
| 1522 if (char != CR && char != LF) { |
| 1523 throw new YamlException("Expected newline.", _scanner.emptySpan); |
| 1524 } |
| 1525 |
| 1526 _scanner.readChar(); |
| 1527 // CR LF | CR | LF -> LF |
| 1528 if (char == CR && _scanner.peekChar() == LF) _scanner.readChar(); |
| 1529 return "\n"; |
| 1530 } |
| 1531 |
| 1532 // Returns whether the character at [offset] is whitespace. |
| 1533 bool _isBlankAt(int offset) { |
| 1534 var char = _scanner.peekChar(offset); |
| 1535 return char == SP || char == TAB; |
| 1536 } |
| 1537 |
| 1538 // Returns whether the character at [offset] is a line break. |
| 1539 bool _isBreakAt(int offset) { |
| 1540 // Libyaml considers NEL, LS, and PS to be line breaks as well, but that's |
| 1541 // contrary to the spec. |
| 1542 var char = _scanner.peekChar(offset); |
| 1543 return char == CR || char == LF; |
| 1544 } |
| 1545 |
| 1546 // Returns whether the character at [offset] is whitespace or past the end of |
| 1547 // the source. |
| 1548 bool _isBlankOrEndAt(int offset) { |
| 1549 var char = _scanner.peekChar(offset); |
| 1550 return char == null || char == SP || char == TAB || char == CR || |
| 1551 char == LF; |
| 1552 } |
| 1553 |
| 1554 /// Returns whether the character at [offset] is a plain character. |
| 1555 /// |
| 1556 /// See http://yaml.org/spec/1.2/spec.html#ns-plain-char(c). |
| 1557 bool _isPlainCharAt(int offset) { |
| 1558 switch (_scanner.peekChar(offset)) { |
| 1559 case COLON: |
| 1560 return _isPlainSafeAt(offset + 1); |
| 1561 case HASH: |
| 1562 var previous = _scanner.peekChar(offset - 1); |
| 1563 return previous != SP && previous != TAB; |
| 1564 default: |
| 1565 return _isPlainSafeAt(offset); |
| 1566 } |
| 1567 } |
| 1568 |
| 1569 /// Returns whether the character at [offset] is a plain-safe character. |
| 1570 /// |
| 1571 /// See http://yaml.org/spec/1.2/spec.html#ns-plain-safe(c). |
| 1572 bool _isPlainSafeAt(int offset) { |
| 1573 var char = _scanner.peekChar(offset); |
| 1574 switch (char) { |
| 1575 case COMMA: |
| 1576 case LEFT_SQUARE: |
| 1577 case RIGHT_SQUARE: |
| 1578 case LEFT_CURLY: |
| 1579 case RIGHT_CURLY: |
| 1580 // These characters are delimiters in a flow context and thus are only |
| 1581 // safe in a block context. |
| 1582 return _inBlockContext; |
| 1583 case SP: |
| 1584 case TAB: |
| 1585 case LF: |
| 1586 case CR: |
| 1587 case BOM: |
| 1588 return false; |
| 1589 case NEL: |
| 1590 return true; |
| 1591 default: |
| 1592 return char != null && |
| 1593 ((char >= 0x00020 && char <= 0x00007E) || |
| 1594 (char >= 0x000A0 && char <= 0x00D7FF) || |
| 1595 (char >= 0x0E000 && char <= 0x00FFFD) || |
| 1596 (char >= 0x10000 && char <= 0x10FFFF)); |
| 1597 } |
| 1598 } |
| 1599 |
| 1600 /// Returns the hexidecimal value of [char]. |
| 1601 int _asHex(int char) { |
| 1602 if (char <= NUMBER_9) return char - NUMBER_0; |
| 1603 if (char <= LETTER_CAP_F) return 10 + char - LETTER_CAP_A; |
| 1604 return 10 + char - LETTER_A; |
| 1605 } |
| 1606 |
| 1607 /// Moves the scanner past any blank characters. |
| 1608 void _skipBlanks() { |
| 1609 while (_isBlank) { |
| 1610 _scanner.readChar(); |
| 1611 } |
| 1612 } |
| 1613 |
| 1614 /// Moves the scanner past a comment, if one starts at the current position. |
| 1615 void _skipComment() { |
| 1616 if (_scanner.peekChar() != HASH) return; |
| 1617 while (!_isBreakOrEnd) { |
| 1618 _scanner.readChar(); |
| 1619 } |
| 1620 } |
| 1621 } |
| 1622 |
| 1623 /// A record of the location of a potential simple key. |
| 1624 class _SimpleKey { |
| 1625 /// The index of the token that begins the simple key. |
| 1626 /// |
| 1627 /// This is the index relative to all tokens emitted, rather than relative to |
| 1628 /// [_tokens]. |
| 1629 final int tokenNumber; |
| 1630 |
| 1631 /// The source location of the beginning of the simple key. |
| 1632 /// |
| 1633 /// This is used for error reporting and for determining when a simple key is |
| 1634 /// no longer on the current line. |
| 1635 final SourceLocation location; |
| 1636 |
| 1637 /// Whether this key must exist for the document to be scanned. |
| 1638 final bool required; |
| 1639 |
| 1640 _SimpleKey(this.tokenNumber, this.location, {bool required}) |
| 1641 : required = required; |
| 1642 } |
| 1643 |
| 1644 /// An enum of chomping indicators that describe how to handle trailing |
| 1645 /// whitespace for a block scalar. |
| 1646 /// |
| 1647 /// See http://yaml.org/spec/1.2/spec.html#id2794534. |
| 1648 class _Chomping { |
| 1649 /// All trailing whitespace is discarded. |
| 1650 static const STRIP = const _Chomping("STRIP"); |
| 1651 |
| 1652 /// A single trailing newline is retained. |
| 1653 static const CLIP = const _Chomping("CLIP"); |
| 1654 |
| 1655 /// All trailing whitespace is preserved. |
| 1656 static const KEEP = const _Chomping("KEEP"); |
| 1657 |
| 1658 final String name; |
| 1659 |
| 1660 const _Chomping(this.name); |
| 1661 |
| 1662 String toString() => name; |
| 1663 } |
OLD | NEW |