| 1 | // © 2024 and later: Unicode, Inc. and others. |
| 2 | // License & terms of use: http://www.unicode.org/copyright.html |
| 3 | |
| 4 | #include "unicode/utypes.h" |
| 5 | |
| 6 | #if !UCONFIG_NO_NORMALIZATION |
| 7 | |
| 8 | #if !UCONFIG_NO_FORMATTING |
| 9 | |
| 10 | #if !UCONFIG_NO_MF2 |
| 11 | |
| 12 | #include "unicode/uniset.h" |
| 13 | #include "messageformat2_errors.h" |
| 14 | #include "messageformat2_macros.h" |
| 15 | #include "messageformat2_parser.h" |
| 16 | #include "ucln_in.h" |
| 17 | #include "umutex.h" |
| 18 | #include "uvector.h" // U_ASSERT |
| 19 | |
| 20 | U_NAMESPACE_BEGIN |
| 21 | |
| 22 | namespace message2 { |
| 23 | |
| 24 | using namespace pluralimpl; |
| 25 | |
| 26 | using namespace data_model; |
| 27 | |
| 28 | /* |
| 29 | The `ERROR()` macro sets a syntax error in the context |
| 30 | and sets the offset in `parseError` to `index`. It does not alter control flow. |
| 31 | */ |
| 32 | #define ERROR(errorCode) \ |
| 33 | if (!errors.hasSyntaxError()) { \ |
| 34 | setParseError(parseError, index); \ |
| 35 | errors.addSyntaxError(errorCode); \ |
| 36 | } |
| 37 | |
| 38 | #define ERROR_AT(errorCode, i) \ |
| 39 | if (!errors.hasSyntaxError()) { \ |
| 40 | setParseError(parseError, i); \ |
| 41 | errors.addSyntaxError(errorCode); \ |
| 42 | } |
| 43 | |
| 44 | // Increments the line number and updates the "characters seen before |
| 45 | // current line" count in `parseError`, iff `peek()` is a newline |
| 46 | void Parser::maybeAdvanceLine() { |
| 47 | if (peek() == LF) { |
| 48 | parseError.line++; |
| 49 | // add 1 to index to get the number of characters seen so far |
| 50 | // (including the newline) |
| 51 | parseError.lengthBeforeCurrentLine = index + 1; |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | /* |
| 56 | Signals an error and returns either if `parseError` already denotes an |
| 57 | error, or `index` is out of bounds for the string `source` |
| 58 | */ |
| 59 | #define CHECK_BOUNDS(errorCode) \ |
| 60 | if (!inBounds()) { \ |
| 61 | ERROR(errorCode); \ |
| 62 | return; \ |
| 63 | } |
| 64 | #define CHECK_BOUNDS_1(errorCode) \ |
| 65 | if (!inBounds(1)) { \ |
| 66 | ERROR_AT(errorCode, index + 1); \ |
| 67 | return; \ |
| 68 | } |
| 69 | |
| 70 | // ------------------------------------- |
| 71 | // Helper functions |
| 72 | |
| 73 | static void copyContext(const UChar in[U_PARSE_CONTEXT_LEN], UChar out[U_PARSE_CONTEXT_LEN]) { |
| 74 | for (int32_t i = 0; i < U_PARSE_CONTEXT_LEN; i++) { |
| 75 | out[i] = in[i]; |
| 76 | if (in[i] == '\0') { |
| 77 | break; |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | /* static */ void Parser::translateParseError(const MessageParseError &messageParseError, UParseError &parseError) { |
| 83 | parseError.line = messageParseError.line; |
| 84 | parseError.offset = messageParseError.offset; |
| 85 | copyContext(messageParseError.preContext, parseError.preContext); |
| 86 | copyContext(messageParseError.postContext, parseError.postContext); |
| 87 | } |
| 88 | |
| 89 | /* static */ void Parser::setParseError(MessageParseError &parseError, uint32_t index) { |
| 90 | // Translate absolute to relative offset |
| 91 | parseError.offset = index // Start with total number of characters seen |
| 92 | - parseError.lengthBeforeCurrentLine; // Subtract all characters before the current line |
| 93 | // TODO: Fill this in with actual pre and post-context |
| 94 | parseError.preContext[0] = 0; |
| 95 | parseError.postContext[0] = 0; |
| 96 | } |
| 97 | |
| 98 | // ------------------------------------- |
| 99 | // Initialization of UnicodeSets |
| 100 | |
| 101 | namespace unisets { |
| 102 | |
| 103 | UnicodeSet* gUnicodeSets[unisets::UNISETS_KEY_COUNT] = {}; |
| 104 | |
| 105 | inline UnicodeSet* getImpl(Key key) { |
| 106 | return gUnicodeSets[key]; |
| 107 | } |
| 108 | |
| 109 | icu::UInitOnce gMF2ParseUniSetsInitOnce {}; |
| 110 | } |
| 111 | |
| 112 | UnicodeSet* initContentChars(UErrorCode& status) { |
| 113 | if (U_FAILURE(status)) { |
| 114 | return nullptr; |
| 115 | } |
| 116 | |
| 117 | UnicodeSet* result = new UnicodeSet(0x0001, 0x0008); // Omit NULL, HTAB and LF |
| 118 | if (result == nullptr) { |
| 119 | status = U_MEMORY_ALLOCATION_ERROR; |
| 120 | return nullptr; |
| 121 | } |
| 122 | result->add(0x000B, 0x000C); // Omit CR |
| 123 | result->add(0x000E, 0x001F); // Omit SP |
| 124 | result->add(0x0021, 0x002D); // Omit '.' |
| 125 | result->add(0x002F, 0x003F); // Omit '@' |
| 126 | result->add(0x0041, 0x005B); // Omit '\' |
| 127 | result->add(0x005D, 0x007A); // Omit { | } |
| 128 | result->add(0x007E, 0x2FFF); // Omit IDEOGRAPHIC_SPACE |
| 129 | result->add(0x3001, 0x10FFFF); // Allowing surrogates is intentional |
| 130 | result->freeze(); |
| 131 | return result; |
| 132 | } |
| 133 | |
| 134 | UnicodeSet* initWhitespace(UErrorCode& status) { |
| 135 | if (U_FAILURE(status)) { |
| 136 | return nullptr; |
| 137 | } |
| 138 | |
| 139 | UnicodeSet* result = new UnicodeSet(); |
| 140 | if (result == nullptr) { |
| 141 | status = U_MEMORY_ALLOCATION_ERROR; |
| 142 | return nullptr; |
| 143 | } |
| 144 | result->add(SPACE); |
| 145 | result->add(HTAB); |
| 146 | result->add(CR); |
| 147 | result->add(LF); |
| 148 | result->add(IDEOGRAPHIC_SPACE); |
| 149 | result->freeze(); |
| 150 | return result; |
| 151 | } |
| 152 | |
| 153 | UnicodeSet* initBidiControls(UErrorCode& status) { |
| 154 | UnicodeSet* result = new UnicodeSet(UnicodeString("[\\u061C]"), status); |
| 155 | if (U_FAILURE(status)) { |
| 156 | return nullptr; |
| 157 | } |
| 158 | result->add(0x200E, 0x200F); |
| 159 | result->add(0x2066, 0x2069); |
| 160 | result->freeze(); |
| 161 | return result; |
| 162 | } |
| 163 | |
| 164 | UnicodeSet* initAlpha(UErrorCode& status) { |
| 165 | UnicodeSet* result = new UnicodeSet(UnicodeString("[:letter:]"), status); |
| 166 | if (U_FAILURE(status)) { |
| 167 | return nullptr; |
| 168 | } |
| 169 | result->freeze(); |
| 170 | return result; |
| 171 | } |
| 172 | |
| 173 | UnicodeSet* initDigits(UErrorCode& status) { |
| 174 | UnicodeSet* result = new UnicodeSet(UnicodeString("[:number:]"), status); |
| 175 | if (U_FAILURE(status)) { |
| 176 | return nullptr; |
| 177 | } |
| 178 | result->freeze(); |
| 179 | return result; |
| 180 | } |
| 181 | |
| 182 | UnicodeSet* initNameStartChars(UErrorCode& status) { |
| 183 | if (U_FAILURE(status)) { |
| 184 | return nullptr; |
| 185 | } |
| 186 | |
| 187 | UnicodeSet* isAlpha = unisets::gUnicodeSets[unisets::ALPHA] = initAlpha(status); |
| 188 | if (U_FAILURE(status)) { |
| 189 | return nullptr; |
| 190 | } |
| 191 | UnicodeSet* result = new UnicodeSet(*isAlpha); |
| 192 | if (result == nullptr) { |
| 193 | status = U_MEMORY_ALLOCATION_ERROR; |
| 194 | return nullptr; |
| 195 | }; |
| 196 | result->add(UNDERSCORE); |
| 197 | result->add(0x00C0, 0x00D6); |
| 198 | result->add(0x00D8, 0x00F6); |
| 199 | result->add(0x00F8, 0x02FF); |
| 200 | result->add(0x0370, 0x037D); |
| 201 | result->add(0x037F, 0x061B); |
| 202 | result->add(0x061D, 0x1FFF); |
| 203 | result->add(0x200C, 0x200D); |
| 204 | result->add(0x2070, 0x218F); |
| 205 | result->add(0x2C00, 0x2FEF); |
| 206 | result->add(0x3001, 0xD7FF); |
| 207 | result->add(0xF900, 0xFDCF); |
| 208 | result->add(0xFDF0, 0xFFFD); |
| 209 | result->add(0x100000, 0xEFFFF); |
| 210 | result->freeze(); |
| 211 | return result; |
| 212 | } |
| 213 | |
| 214 | UnicodeSet* initNameChars(UErrorCode& status) { |
| 215 | if (U_FAILURE(status)) { |
| 216 | return nullptr; |
| 217 | } |
| 218 | |
| 219 | UnicodeSet* nameStart = unisets::gUnicodeSets[unisets::NAME_START] = initNameStartChars(status); |
| 220 | UnicodeSet* digit = unisets::gUnicodeSets[unisets::DIGIT] = initDigits(status); |
| 221 | if (U_FAILURE(status)) { |
| 222 | return nullptr; |
| 223 | } |
| 224 | UnicodeSet* result = new UnicodeSet(); |
| 225 | if (result == nullptr) { |
| 226 | status = U_MEMORY_ALLOCATION_ERROR; |
| 227 | return nullptr; |
| 228 | }; |
| 229 | result->addAll(*nameStart); |
| 230 | result->addAll(*digit); |
| 231 | result->add(HYPHEN); |
| 232 | result->add(PERIOD); |
| 233 | result->add(0x00B7); |
| 234 | result->add(0x0300, 0x036F); |
| 235 | result->add(0x203F, 0x2040); |
| 236 | result->freeze(); |
| 237 | return result; |
| 238 | } |
| 239 | |
| 240 | UnicodeSet* initTextChars(UErrorCode& status) { |
| 241 | if (U_FAILURE(status)) { |
| 242 | return nullptr; |
| 243 | } |
| 244 | |
| 245 | UnicodeSet* content = unisets::gUnicodeSets[unisets::CONTENT] = initContentChars(status); |
| 246 | UnicodeSet* whitespace = unisets::gUnicodeSets[unisets::WHITESPACE] = initWhitespace(status); |
| 247 | if (U_FAILURE(status)) { |
| 248 | return nullptr; |
| 249 | } |
| 250 | UnicodeSet* result = new UnicodeSet(); |
| 251 | if (result == nullptr) { |
| 252 | status = U_MEMORY_ALLOCATION_ERROR; |
| 253 | return nullptr; |
| 254 | }; |
| 255 | result->addAll(*content); |
| 256 | result->addAll(*whitespace); |
| 257 | result->add(PERIOD); |
| 258 | result->add(AT); |
| 259 | result->add(PIPE); |
| 260 | result->freeze(); |
| 261 | return result; |
| 262 | } |
| 263 | |
| 264 | UnicodeSet* initQuotedChars(UErrorCode& status) { |
| 265 | if (U_FAILURE(status)) { |
| 266 | return nullptr; |
| 267 | } |
| 268 | |
| 269 | unisets::gUnicodeSets[unisets::TEXT] = initTextChars(status); |
| 270 | if (U_FAILURE(status)) { |
| 271 | return nullptr; |
| 272 | } |
| 273 | UnicodeSet* result = new UnicodeSet(); |
| 274 | if (result == nullptr) { |
| 275 | status = U_MEMORY_ALLOCATION_ERROR; |
| 276 | return nullptr; |
| 277 | }; |
| 278 | // content and whitespace were initialized by `initTextChars()` |
| 279 | UnicodeSet* content = unisets::getImpl(unisets::CONTENT); |
| 280 | if (content == nullptr) { |
| 281 | status = U_MEMORY_ALLOCATION_ERROR; |
| 282 | return nullptr; |
| 283 | } |
| 284 | result->addAll(*content); |
| 285 | UnicodeSet* whitespace = unisets::getImpl(unisets::WHITESPACE); |
| 286 | if (whitespace == nullptr) { |
| 287 | status = U_MEMORY_ALLOCATION_ERROR; |
| 288 | return nullptr; |
| 289 | } |
| 290 | result->addAll(*whitespace); |
| 291 | result->add(PERIOD); |
| 292 | result->add(AT); |
| 293 | result->add(LEFT_CURLY_BRACE); |
| 294 | result->add(RIGHT_CURLY_BRACE); |
| 295 | result->freeze(); |
| 296 | return result; |
| 297 | } |
| 298 | |
| 299 | UnicodeSet* initEscapableChars(UErrorCode& status) { |
| 300 | if (U_FAILURE(status)) { |
| 301 | return nullptr; |
| 302 | } |
| 303 | |
| 304 | UnicodeSet* result = new UnicodeSet(); |
| 305 | if (result == nullptr) { |
| 306 | status = U_MEMORY_ALLOCATION_ERROR; |
| 307 | return nullptr; |
| 308 | } |
| 309 | result->add(PIPE); |
| 310 | result->add(BACKSLASH); |
| 311 | result->add(LEFT_CURLY_BRACE); |
| 312 | result->add(RIGHT_CURLY_BRACE); |
| 313 | result->freeze(); |
| 314 | return result; |
| 315 | } |
| 316 | |
| 317 | namespace unisets { |
| 318 | |
| 319 | UBool U_CALLCONV cleanupMF2ParseUniSets() { |
| 320 | for (int32_t i = 0; i < UNISETS_KEY_COUNT; i++) { |
| 321 | delete gUnicodeSets[i]; |
| 322 | gUnicodeSets[i] = nullptr; |
| 323 | } |
| 324 | gMF2ParseUniSetsInitOnce.reset(); |
| 325 | return true; |
| 326 | } |
| 327 | |
| 328 | void U_CALLCONV initMF2ParseUniSets(UErrorCode& status) { |
| 329 | ucln_i18n_registerCleanup(UCLN_I18N_MF2_UNISETS, cleanupMF2ParseUniSets); |
| 330 | /* |
| 331 | Each of the init functions initializes the UnicodeSets |
| 332 | that it depends on. |
| 333 | |
| 334 | initBidiControls (no dependencies) |
| 335 | |
| 336 | initEscapableChars (no dependencies) |
| 337 | |
| 338 | initNameChars depends on |
| 339 | initDigits |
| 340 | initNameStartChars depends on |
| 341 | initAlpha |
| 342 | |
| 343 | initQuotedChars depends on |
| 344 | initTextChars depends on |
| 345 | initContentChars |
| 346 | initWhitespace |
| 347 | */ |
| 348 | gUnicodeSets[unisets::BIDI] = initBidiControls(status); |
| 349 | gUnicodeSets[unisets::NAME_CHAR] = initNameChars(status); |
| 350 | gUnicodeSets[unisets::QUOTED] = initQuotedChars(status); |
| 351 | gUnicodeSets[unisets::ESCAPABLE] = initEscapableChars(status); |
| 352 | |
| 353 | if (U_FAILURE(status)) { |
| 354 | cleanupMF2ParseUniSets(); |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | const UnicodeSet* get(Key key, UErrorCode& status) { |
| 359 | umtx_initOnce(gMF2ParseUniSetsInitOnce, &initMF2ParseUniSets, status); |
| 360 | if (U_FAILURE(status)) { |
| 361 | return nullptr; |
| 362 | } |
| 363 | UnicodeSet* result = getImpl(key); |
| 364 | if (result == nullptr) { |
| 365 | status = U_MEMORY_ALLOCATION_ERROR; |
| 366 | } |
| 367 | return result; |
| 368 | } |
| 369 | |
| 370 | } |
| 371 | |
| 372 | // ------------------------------------- |
| 373 | // Predicates |
| 374 | |
| 375 | /* |
| 376 | The following helper predicates should exactly match nonterminals in the MessageFormat 2 grammar: |
| 377 | |
| 378 | `isContentChar()` : `content-char` |
| 379 | `isTextChar()` : `text-char` |
| 380 | `isAlpha()` : `ALPHA` |
| 381 | `isDigit()` : `DIGIT` |
| 382 | `isNameStart()` : `name-start` |
| 383 | `isNameChar()` : `name-char` |
| 384 | `isUnquotedStart()` : `unquoted-start` |
| 385 | `isQuotedChar()` : `quoted-char` |
| 386 | `isWhitespace()` : `s` |
| 387 | */ |
| 388 | |
| 389 | bool Parser::isContentChar(UChar32 c) const { |
| 390 | return contentChars->contains(c); |
| 391 | } |
| 392 | |
| 393 | // See `bidi` in the MF2 grammar |
| 394 | bool Parser::isBidiControl(UChar32 c) const { |
| 395 | return bidiControlChars->contains(c); |
| 396 | } |
| 397 | |
| 398 | // See `ws` in the MessageFormat 2 grammar |
| 399 | bool Parser::isWhitespace(UChar32 c) const { |
| 400 | return whitespaceChars->contains(c); |
| 401 | } |
| 402 | |
| 403 | bool Parser::isTextChar(UChar32 c) const { |
| 404 | return textChars->contains(c); |
| 405 | } |
| 406 | |
| 407 | bool Parser::isAlpha(UChar32 c) const { |
| 408 | return alphaChars->contains(c); |
| 409 | } |
| 410 | |
| 411 | bool Parser::isDigit(UChar32 c) const { |
| 412 | return digitChars->contains(c); |
| 413 | } |
| 414 | |
| 415 | bool Parser::isNameStart(UChar32 c) const { |
| 416 | return nameStartChars->contains(c); |
| 417 | } |
| 418 | |
| 419 | bool Parser::isNameChar(UChar32 c) const { |
| 420 | return nameChars->contains(c); |
| 421 | } |
| 422 | |
| 423 | bool Parser::isUnquotedStart(UChar32 c) const { |
| 424 | return isNameChar(c); |
| 425 | } |
| 426 | |
| 427 | bool Parser::isQuotedChar(UChar32 c) const { |
| 428 | return quotedChars->contains(c); |
| 429 | } |
| 430 | |
| 431 | bool Parser::isEscapableChar(UChar32 c) const { |
| 432 | return escapableChars->contains(c); |
| 433 | } |
| 434 | |
| 435 | // Returns true iff `c` can begin a `function` nonterminal |
| 436 | static bool isFunctionStart(UChar32 c) { |
| 437 | switch (c) { |
| 438 | case COLON: { |
| 439 | return true; |
| 440 | } |
| 441 | default: { |
| 442 | return false; |
| 443 | } |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | // Returns true iff `c` can begin an `annotation` nonterminal |
| 448 | static bool isAnnotationStart(UChar32 c) { |
| 449 | return isFunctionStart(c); |
| 450 | } |
| 451 | |
| 452 | // Returns true iff `c` can begin a `literal` nonterminal |
| 453 | bool Parser::isLiteralStart(UChar32 c) const { |
| 454 | return (c == PIPE || isNameStart(c) || c == HYPHEN || isDigit(c)); |
| 455 | } |
| 456 | |
| 457 | // Returns true iff `c` can begin a `key` nonterminal |
| 458 | bool Parser::isKeyStart(UChar32 c) const { |
| 459 | return (c == ASTERISK || isLiteralStart(c)); |
| 460 | } |
| 461 | |
| 462 | bool Parser::isDeclarationStart() { |
| 463 | return (peek() == ID_LOCAL[0] |
| 464 | && inBounds(1) |
| 465 | && peek(1) == ID_LOCAL[1]) |
| 466 | || (peek() == ID_INPUT[0] |
| 467 | && inBounds(1) |
| 468 | && peek(1) == ID_INPUT[1]); |
| 469 | } |
| 470 | |
| 471 | // ------------------------------------- |
| 472 | // Parsing functions |
| 473 | |
| 474 | |
| 475 | /* |
| 476 | TODO: Since handling the whitespace ambiguities needs to be repeated |
| 477 | in several different places and is hard to factor out, |
| 478 | it probably would be better to replace the parser with a lexer + parser |
| 479 | to separate tokenizing from parsing, which would simplify the code significantly. |
| 480 | This has the disadvantage that there is no token grammar for MessageFormat, |
| 481 | so one would have to be invented that isn't a component of the spec. |
| 482 | */ |
| 483 | |
| 484 | /* |
| 485 | This is a recursive-descent scannerless parser that, |
| 486 | with a few exceptions, uses 1 character of lookahead. |
| 487 | |
| 488 | This may not be an exhaustive list, as the additions of attributes and reserved |
| 489 | statements introduced several new ambiguities. |
| 490 | |
| 491 | All but three of the exceptions involve ambiguities about the meaning of whitespace. |
| 492 | One ambiguity not involving whitespace is: |
| 493 | identifier -> namespace ":" name |
| 494 | vs. |
| 495 | identifier -> name |
| 496 | |
| 497 | `namespace` and `name` can't be distinguished without arbitrary lookahead. |
| 498 | (For how this is handled, see parseIdentifier()) |
| 499 | |
| 500 | The second ambiguity not involving whitespace is: |
| 501 | complex-message -> *(declaration[s]) complex-body |
| 502 | -> declaration *(declaration[s]) complex-body |
| 503 | -> declaration complex-body |
| 504 | -> reserved-statement complex-body |
| 505 | -> .foo {$x} .match // ... |
| 506 | When processing the '.', arbitrary lookahead is required to distinguish the |
| 507 | arbitrary-length unsupported keyword from `.match`. |
| 508 | (For how this is handled, see parseDeclarations()). |
| 509 | |
| 510 | The third ambiguity not involving whitespace is: |
| 511 | complex-message -> *(declaration [s]) complex-body |
| 512 | -> reserved-statement *(declaration [s]) complex-body |
| 513 | -> reserved-statement complex-body |
| 514 | -> reserved-statement quotedPattern |
| 515 | -> reserved-keyword [s reserved-body] 1*([s] expression) quoted-pattern |
| 516 | -> reserved-keyword expression quoted-pattern |
| 517 | Example: .foo {1} {{1}} |
| 518 | |
| 519 | Without lookahead, the opening '{' of the quoted pattern can't be distinguished |
| 520 | from the opening '{' of another expression in the unsupported statement. |
| 521 | (Though this only requires 1 character of lookahead.) |
| 522 | |
| 523 | Otherwise: |
| 524 | |
| 525 | There are at least seven ambiguities in the grammar that can't be resolved with finite |
| 526 | lookahead (since whitespace sequences can be arbitrarily long). They are resolved |
| 527 | with a form of backtracking (early exit). No state needs to be saved/restored |
| 528 | since whitespace doesn't affect the shape of the resulting parse tree, so it's |
| 529 | not true backtracking. |
| 530 | |
| 531 | In addition, the grammar has been refactored |
| 532 | in a semantics-preserving way in some cases to make the code easier to structure. |
| 533 | |
| 534 | First: variant = when 1*(s key) [s] pattern |
| 535 | Example: when k {a} |
| 536 | When reading the first space after 'k', it's ambiguous whether it's the |
| 537 | required space before another key, or the optional space before `pattern`. |
| 538 | (See comments in parseNonEmptyKeys()) |
| 539 | |
| 540 | Second: expression = "{" [s] (((literal / variable) [s annotation]) / annotation) [s] "}" |
| 541 | annotation = (function *(s option)) / reserved |
| 542 | Example: {:f } |
| 543 | When reading the first space after 'f', it's ambiguous whether it's the |
| 544 | required space before an option, or the optional trailing space after an options list |
| 545 | (in this case, the options list is empty). |
| 546 | (See comments in parseOptions() -- handling this case also meant it was easier to base |
| 547 | the code on a slightly refactored grammar, which should be semantically equivalent.) |
| 548 | |
| 549 | Third: expression = "{" [s] (((literal / variable) [s annotation]) / annotation) [s] "}" |
| 550 | annotation = (function *(s option)) / reserved |
| 551 | Example: {@a } |
| 552 | Similar to the previous case; see comments in parseReserved() |
| 553 | |
| 554 | Fourth: expression = "{" [s] (((literal / variable) [s annotation]) / annotation) [s] "}" |
| 555 | Example: {|foo| } |
| 556 | When reading the first space after the '|', it's ambiguous whether it's the required |
| 557 | space before an annotation, or the optional trailing space before the '}'. |
| 558 | (See comments in parseLiteralOrVariableWithAnnotation(); handling this case relies on |
| 559 | the same grammar refactoring as the second exception.) |
| 560 | |
| 561 | Most functions match a non-terminal in the grammar, except as explained |
| 562 | in comments. |
| 563 | |
| 564 | Fifth: matcher = match-statement 1*([s] variant) |
| 565 | -> match 1 *([s] selector) 1*([s] variant) |
| 566 | Example: match {42} * {{_}} |
| 567 | When reading the space after the first '}', it's unclear whether |
| 568 | it's the optional space before another selector, or the optional space |
| 569 | before a variant. |
| 570 | |
| 571 | Sixth: annotation-expression = "{" [s] annotation *(s attribute) [s] "}" |
| 572 | -> "{" [s] function *(s attribute) [s] "}" |
| 573 | -> "{" [s] ":" identifier *(s option) *(s attribute) [s] "}" |
| 574 | -> "{" [s] ":" identifier s attribute *(s attribute) [s] "}" |
| 575 | |
| 576 | Example: {:func @foo} |
| 577 | (Note: the same ambiguity is present with variable-expression and literal-expression) |
| 578 | |
| 579 | Seventh: |
| 580 | |
| 581 | |
| 582 | When parsing the space, it's unclear whether it's the optional space before an |
| 583 | option, or the optional space before an attribute. |
| 584 | |
| 585 | Unless otherwise noted in a comment, all helper functions that take |
| 586 | a `source` string, an `index` unsigned int, and an `errorCode` `UErrorCode` |
| 587 | have the precondition: |
| 588 | `index` < `len()` |
| 589 | and the postcondition: |
| 590 | `U_FAILURE(errorCode)` || `index < `len()` |
| 591 | */ |
| 592 | |
| 593 | /* |
| 594 | No pre, no post. |
| 595 | A message may end with whitespace, so `index` may equal `len()` on exit. |
| 596 | */ |
| 597 | void Parser::parseRequiredWS(UErrorCode& errorCode) { |
| 598 | bool sawWhitespace = false; |
| 599 | |
| 600 | // The loop exits either when we consume all the input, |
| 601 | // or when we see a non-whitespace character. |
| 602 | while (true) { |
| 603 | // Check if all input has been consumed |
| 604 | if (!inBounds()) { |
| 605 | // If whitespace isn't required -- or if we saw it already -- |
| 606 | // then the caller is responsible for checking this case and |
| 607 | // setting an error if necessary. |
| 608 | if (sawWhitespace) { |
| 609 | // Not an error. |
| 610 | return; |
| 611 | } |
| 612 | // Otherwise, whitespace is required; the end of the input has |
| 613 | // been reached without whitespace. This is an error. |
| 614 | ERROR(errorCode); |
| 615 | return; |
| 616 | } |
| 617 | |
| 618 | // Input remains; process the next character if it's whitespace, |
| 619 | // exit the loop otherwise |
| 620 | if (isWhitespace(peek())) { |
| 621 | sawWhitespace = true; |
| 622 | // Increment line number in parse error if we consume a newline |
| 623 | maybeAdvanceLine(); |
| 624 | next(); |
| 625 | } else { |
| 626 | break; |
| 627 | } |
| 628 | } |
| 629 | |
| 630 | if (!sawWhitespace) { |
| 631 | ERROR(errorCode); |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | void Parser::parseOptionalBidi() { |
| 636 | while (true) { |
| 637 | if (!inBounds()) { |
| 638 | return; |
| 639 | } |
| 640 | if (isBidiControl(peek())) { |
| 641 | next(); |
| 642 | } else { |
| 643 | break; |
| 644 | } |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | /* |
| 649 | No pre, no post, because a message may end with whitespace |
| 650 | Matches `s` in the MF2 grammar |
| 651 | */ |
| 652 | void Parser::parseRequiredWhitespace(UErrorCode& errorCode) { |
| 653 | parseOptionalBidi(); |
| 654 | parseRequiredWS(errorCode); |
| 655 | parseOptionalWhitespace(); |
| 656 | normalizedInput += SPACE; |
| 657 | } |
| 658 | |
| 659 | /* |
| 660 | No pre, no post, for the same reason as `parseWhitespaceMaybeRequired()`. |
| 661 | */ |
| 662 | void Parser::parseOptionalWhitespace() { |
| 663 | while (true) { |
| 664 | if (!inBounds()) { |
| 665 | return; |
| 666 | } |
| 667 | auto cp = peek(); |
| 668 | if (isWhitespace(cp) || isBidiControl(cp)) { |
| 669 | maybeAdvanceLine(); |
| 670 | next(); |
| 671 | } else { |
| 672 | break; |
| 673 | } |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | // Consumes a single character, signaling an error if `peek()` != `c` |
| 678 | // No postcondition -- a message can end with a '}' token |
| 679 | void Parser::parseToken(UChar32 c, UErrorCode& errorCode) { |
| 680 | CHECK_BOUNDS(errorCode); |
| 681 | |
| 682 | if (peek() == c) { |
| 683 | next(); |
| 684 | normalizedInput += c; |
| 685 | return; |
| 686 | } |
| 687 | // Next character didn't match -- error out |
| 688 | ERROR(errorCode); |
| 689 | } |
| 690 | |
| 691 | /* |
| 692 | Consumes a fixed-length token, signaling an error if the token isn't a prefix of |
| 693 | the string beginning at `peek()` |
| 694 | No postcondition -- a message can end with a '}' token |
| 695 | */ |
| 696 | void Parser::parseToken(const std::u16string_view& token, UErrorCode& errorCode) { |
| 697 | U_ASSERT(inBounds()); |
| 698 | |
| 699 | int32_t tokenPos = 0; |
| 700 | while (tokenPos < static_cast<int32_t>(token.length())) { |
| 701 | if (peek() != token[tokenPos]) { |
| 702 | ERROR(errorCode); |
| 703 | return; |
| 704 | } |
| 705 | normalizedInput += token[tokenPos]; |
| 706 | next(); |
| 707 | tokenPos++; |
| 708 | } |
| 709 | } |
| 710 | |
| 711 | /* |
| 712 | Consumes optional whitespace, possibly advancing `index` to `index'`, |
| 713 | then consumes a fixed-length token (signaling an error if the token isn't a prefix of |
| 714 | the string beginning at `source[index']`), |
| 715 | then consumes optional whitespace again |
| 716 | */ |
| 717 | void Parser::parseTokenWithWhitespace(const std::u16string_view& token, UErrorCode& errorCode) { |
| 718 | // No need for error check or bounds check before parseOptionalWhitespace |
| 719 | parseOptionalWhitespace(); |
| 720 | // Establish precondition |
| 721 | CHECK_BOUNDS(errorCode); |
| 722 | parseToken(token, errorCode); |
| 723 | parseOptionalWhitespace(); |
| 724 | // Guarantee postcondition |
| 725 | CHECK_BOUNDS(errorCode); |
| 726 | } |
| 727 | |
| 728 | /* |
| 729 | Consumes optional whitespace, possibly advancing `index` to `index'`, |
| 730 | then consumes a single character (signaling an error if it doesn't match |
| 731 | `source[index']`), |
| 732 | then consumes optional whitespace again |
| 733 | */ |
| 734 | void Parser::parseTokenWithWhitespace(UChar32 c, UErrorCode& errorCode) { |
| 735 | // No need for error check or bounds check before parseOptionalWhitespace() |
| 736 | parseOptionalWhitespace(); |
| 737 | // Establish precondition |
| 738 | CHECK_BOUNDS(errorCode); |
| 739 | parseToken(c, errorCode); |
| 740 | parseOptionalWhitespace(); |
| 741 | // Guarantee postcondition |
| 742 | CHECK_BOUNDS(errorCode); |
| 743 | } |
| 744 | |
| 745 | /* |
| 746 | Consumes a non-empty sequence of `name-char`s, the first of which is |
| 747 | also a `name-start`. |
| 748 | that begins with a character `start` such that `isNameStart(start)`. |
| 749 | |
| 750 | Returns this sequence. |
| 751 | |
| 752 | (Matches the `name` nonterminal in the grammar.) |
| 753 | */ |
| 754 | UnicodeString Parser::parseName(UErrorCode& errorCode) { |
| 755 | UnicodeString name; |
| 756 | |
| 757 | U_ASSERT(inBounds()); |
| 758 | |
| 759 | if (!(isNameStart(peek()) || isBidiControl(peek()))) { |
| 760 | ERROR(errorCode); |
| 761 | return name; |
| 762 | } |
| 763 | |
| 764 | // name = [bidi] name-start *name-char [bidi] |
| 765 | |
| 766 | // [bidi] |
| 767 | parseOptionalBidi(); |
| 768 | |
| 769 | // name-start *name-char |
| 770 | while (isNameChar(peek())) { |
| 771 | UChar32 c = peek(); |
| 772 | name += c; |
| 773 | normalizedInput += c; |
| 774 | next(); |
| 775 | if (!inBounds()) { |
| 776 | ERROR(errorCode); |
| 777 | break; |
| 778 | } |
| 779 | } |
| 780 | |
| 781 | // [bidi] |
| 782 | parseOptionalBidi(); |
| 783 | |
| 784 | return name; |
| 785 | } |
| 786 | |
| 787 | /* |
| 788 | Consumes a '$' followed by a `name`, returning a VariableName |
| 789 | with `name` as its name |
| 790 | |
| 791 | (Matches the `variable` nonterminal in the grammar.) |
| 792 | */ |
| 793 | VariableName Parser::parseVariableName(UErrorCode& errorCode) { |
| 794 | VariableName result; |
| 795 | |
| 796 | U_ASSERT(inBounds()); |
| 797 | |
| 798 | parseToken(DOLLAR, errorCode); |
| 799 | if (!inBounds()) { |
| 800 | ERROR(errorCode); |
| 801 | return result; |
| 802 | } |
| 803 | return VariableName(parseName(errorCode)); |
| 804 | } |
| 805 | |
| 806 | /* |
| 807 | Corresponds to the `identifier` nonterminal in the grammar |
| 808 | */ |
| 809 | UnicodeString Parser::parseIdentifier(UErrorCode& errorCode) { |
| 810 | U_ASSERT(inBounds()); |
| 811 | |
| 812 | UnicodeString result; |
| 813 | // The following is a hack to get around ambiguity in the grammar: |
| 814 | // identifier -> namespace ":" name |
| 815 | // vs. |
| 816 | // identifier -> name |
| 817 | // can't be distinguished without arbitrary lookahead. |
| 818 | // Instead, we treat the production as: |
| 819 | // identifier -> namespace *(":"name) |
| 820 | // and then check for multiple colons. |
| 821 | |
| 822 | // Parse namespace |
| 823 | result += parseName(errorCode); |
| 824 | int32_t firstColon = -1; |
| 825 | while (inBounds() && peek() == COLON) { |
| 826 | // Parse ':' separator |
| 827 | if (firstColon == -1) { |
| 828 | firstColon = index; |
| 829 | } |
| 830 | parseToken(COLON, errorCode); |
| 831 | result += COLON; |
| 832 | // Check for message ending with something like "foo:" |
| 833 | if (!inBounds()) { |
| 834 | ERROR(errorCode); |
| 835 | } else { |
| 836 | // Parse name part |
| 837 | result += parseName(errorCode); |
| 838 | } |
| 839 | } |
| 840 | |
| 841 | // If there's at least one ':', scan from the first ':' |
| 842 | // to the end of the name to check for multiple ':'s |
| 843 | if (firstColon != -1) { |
| 844 | for (int32_t i = firstColon + 1; i < result.length(); i++) { |
| 845 | if (result[i] == COLON) { |
| 846 | ERROR_AT(errorCode, i); |
| 847 | return {}; |
| 848 | } |
| 849 | } |
| 850 | } |
| 851 | |
| 852 | return result; |
| 853 | } |
| 854 | |
| 855 | /* |
| 856 | Consumes a reference to a function, matching the ": identifier" |
| 857 | in the `function` nonterminal in the grammar. |
| 858 | |
| 859 | Returns the function name. |
| 860 | */ |
| 861 | FunctionName Parser::parseFunction(UErrorCode& errorCode) { |
| 862 | U_ASSERT(inBounds()); |
| 863 | if (!isFunctionStart(peek())) { |
| 864 | ERROR(errorCode); |
| 865 | return FunctionName(); |
| 866 | } |
| 867 | |
| 868 | normalizedInput += peek(); |
| 869 | next(); // Consume the function start character |
| 870 | if (!inBounds()) { |
| 871 | ERROR(errorCode); |
| 872 | return FunctionName(); |
| 873 | } |
| 874 | return parseIdentifier(errorCode); |
| 875 | } |
| 876 | |
| 877 | |
| 878 | /* |
| 879 | Precondition: peek() == BACKSLASH |
| 880 | |
| 881 | Consume an escaped character. |
| 882 | Corresponds to `escaped-char` in the grammar. |
| 883 | |
| 884 | No postcondition (a message can end with an escaped char) |
| 885 | */ |
| 886 | UnicodeString Parser::parseEscapeSequence(UErrorCode& errorCode) { |
| 887 | U_ASSERT(inBounds()); |
| 888 | U_ASSERT(peek() == BACKSLASH); |
| 889 | normalizedInput += BACKSLASH; |
| 890 | next(); // Skip the initial backslash |
| 891 | UnicodeString str; |
| 892 | if (inBounds()) { |
| 893 | // Expect a '{', '|' or '}' |
| 894 | switch (peek()) { |
| 895 | case LEFT_CURLY_BRACE: |
| 896 | case RIGHT_CURLY_BRACE: |
| 897 | case PIPE: |
| 898 | case BACKSLASH: { |
| 899 | /* Append to the output string */ |
| 900 | str += peek(); |
| 901 | /* Update normalizedInput */ |
| 902 | normalizedInput += peek(); |
| 903 | /* Consume the character */ |
| 904 | next(); |
| 905 | return str; |
| 906 | } |
| 907 | default: { |
| 908 | // No other characters are allowed here |
| 909 | break; |
| 910 | } |
| 911 | } |
| 912 | } |
| 913 | // If control reaches here, there was an error |
| 914 | ERROR(errorCode); |
| 915 | return str; |
| 916 | } |
| 917 | |
| 918 | |
| 919 | /* |
| 920 | Consume and return a quoted literal, matching the `literal` nonterminal in the grammar. |
| 921 | */ |
| 922 | Literal Parser::parseQuotedLiteral(UErrorCode& errorCode) { |
| 923 | bool error = false; |
| 924 | |
| 925 | UnicodeString contents; |
| 926 | if (U_SUCCESS(errorCode)) { |
| 927 | // Parse the opening '|' |
| 928 | parseToken(PIPE, errorCode); |
| 929 | if (!inBounds()) { |
| 930 | ERROR(errorCode); |
| 931 | error = true; |
| 932 | } else { |
| 933 | // Parse the contents |
| 934 | bool done = false; |
| 935 | while (!done) { |
| 936 | if (peek() == BACKSLASH) { |
| 937 | contents += parseEscapeSequence(errorCode); |
| 938 | } else if (isQuotedChar(peek())) { |
| 939 | contents += peek(); |
| 940 | // Handle cases like: |
| 941 | // |}{| -- we want to escape everywhere that |
| 942 | // can be escaped, to make round-trip checking |
| 943 | // easier -- so this case normalizes to |
| 944 | // |\}\{| |
| 945 | if (isEscapableChar(peek())) { |
| 946 | normalizedInput += BACKSLASH; |
| 947 | } |
| 948 | normalizedInput += peek(); |
| 949 | next(); // Consume this character |
| 950 | maybeAdvanceLine(); |
| 951 | } else { |
| 952 | // Assume the sequence of literal characters ends here |
| 953 | done = true; |
| 954 | } |
| 955 | if (!inBounds()) { |
| 956 | ERROR(errorCode); |
| 957 | error = true; |
| 958 | break; |
| 959 | } |
| 960 | } |
| 961 | } |
| 962 | } |
| 963 | |
| 964 | if (error) { |
| 965 | return {}; |
| 966 | } |
| 967 | |
| 968 | // Parse the closing '|' |
| 969 | parseToken(PIPE, errorCode); |
| 970 | |
| 971 | return Literal(true, contents); |
| 972 | } |
| 973 | |
| 974 | // Parse (1*DIGIT) |
| 975 | UnicodeString Parser::parseDigits(UErrorCode& errorCode) { |
| 976 | if (U_FAILURE(errorCode)) { |
| 977 | return {}; |
| 978 | } |
| 979 | |
| 980 | U_ASSERT(isDigit(peek())); |
| 981 | |
| 982 | UnicodeString contents; |
| 983 | do { |
| 984 | contents += peek(); |
| 985 | normalizedInput += peek(); |
| 986 | next(); |
| 987 | if (!inBounds()) { |
| 988 | ERROR(errorCode); |
| 989 | return {}; |
| 990 | } |
| 991 | } while (isDigit(peek())); |
| 992 | |
| 993 | return contents; |
| 994 | } |
| 995 | /* |
| 996 | Consume and return an unquoted literal, matching the `unquoted` nonterminal in the grammar. |
| 997 | */ |
| 998 | Literal Parser::parseUnquotedLiteral(UErrorCode& errorCode) { |
| 999 | if (U_FAILURE(errorCode)) { |
| 1000 | return {}; |
| 1001 | } |
| 1002 | |
| 1003 | // unquoted -> name |
| 1004 | if (isNameStart(peek())) { |
| 1005 | return Literal(false, parseName(errorCode)); |
| 1006 | } |
| 1007 | |
| 1008 | // unquoted -> number |
| 1009 | // Parse the contents |
| 1010 | UnicodeString contents; |
| 1011 | |
| 1012 | // Parse the sign |
| 1013 | if (peek() == HYPHEN) { |
| 1014 | contents += peek(); |
| 1015 | normalizedInput += peek(); |
| 1016 | next(); |
| 1017 | } |
| 1018 | if (!inBounds()) { |
| 1019 | ERROR(errorCode); |
| 1020 | return {}; |
| 1021 | } |
| 1022 | |
| 1023 | // Parse the integer part |
| 1024 | if (peek() == ((UChar32)0x0030) /* 0 */) { |
| 1025 | contents += peek(); |
| 1026 | normalizedInput += peek(); |
| 1027 | next(); |
| 1028 | } else if (isDigit(peek())) { |
| 1029 | contents += parseDigits(errorCode); |
| 1030 | } else { |
| 1031 | // Error -- nothing else can start a number literal |
| 1032 | ERROR(errorCode); |
| 1033 | return {}; |
| 1034 | } |
| 1035 | |
| 1036 | // Parse the decimal point if present |
| 1037 | if (peek() == PERIOD) { |
| 1038 | contents += peek(); |
| 1039 | normalizedInput += peek(); |
| 1040 | next(); |
| 1041 | if (!inBounds()) { |
| 1042 | ERROR(errorCode); |
| 1043 | return {}; |
| 1044 | } |
| 1045 | // Parse the fraction part |
| 1046 | if (isDigit(peek())) { |
| 1047 | contents += parseDigits(errorCode); |
| 1048 | } else { |
| 1049 | // '.' not followed by digit is a parse error |
| 1050 | ERROR(errorCode); |
| 1051 | return {}; |
| 1052 | } |
| 1053 | } |
| 1054 | |
| 1055 | if (!inBounds()) { |
| 1056 | ERROR(errorCode); |
| 1057 | return {}; |
| 1058 | } |
| 1059 | |
| 1060 | // Parse the exponent part if present |
| 1061 | if (peek() == UPPERCASE_E || peek() == LOWERCASE_E) { |
| 1062 | contents += peek(); |
| 1063 | normalizedInput += peek(); |
| 1064 | next(); |
| 1065 | if (!inBounds()) { |
| 1066 | ERROR(errorCode); |
| 1067 | return {}; |
| 1068 | } |
| 1069 | // Parse sign if present |
| 1070 | if (peek() == PLUS || peek() == HYPHEN) { |
| 1071 | contents += peek(); |
| 1072 | normalizedInput += peek(); |
| 1073 | next(); |
| 1074 | if (!inBounds()) { |
| 1075 | ERROR(errorCode); |
| 1076 | return {}; |
| 1077 | } |
| 1078 | } |
| 1079 | // Parse exponent digits |
| 1080 | if (!isDigit(peek())) { |
| 1081 | ERROR(errorCode); |
| 1082 | return {}; |
| 1083 | } |
| 1084 | contents += parseDigits(errorCode); |
| 1085 | } |
| 1086 | |
| 1087 | return Literal(false, contents); |
| 1088 | } |
| 1089 | |
| 1090 | /* |
| 1091 | Consume and return a literal, matching the `literal` nonterminal in the grammar. |
| 1092 | */ |
| 1093 | Literal Parser::parseLiteral(UErrorCode& errorCode) { |
| 1094 | Literal result; |
| 1095 | if (!inBounds()) { |
| 1096 | ERROR(errorCode); |
| 1097 | } else { |
| 1098 | if (peek() == PIPE) { |
| 1099 | result = parseQuotedLiteral(errorCode); |
| 1100 | } else { |
| 1101 | result = parseUnquotedLiteral(errorCode); |
| 1102 | } |
| 1103 | // Guarantee postcondition |
| 1104 | if (!inBounds()) { |
| 1105 | ERROR(errorCode); |
| 1106 | } |
| 1107 | } |
| 1108 | |
| 1109 | return result; |
| 1110 | } |
| 1111 | |
| 1112 | /* |
| 1113 | Consume a @name-value pair, matching the `attribute` nonterminal in the grammar. |
| 1114 | |
| 1115 | Adds the option to `options` |
| 1116 | */ |
| 1117 | template<class T> |
| 1118 | void Parser::parseAttribute(AttributeAdder<T>& attrAdder, UErrorCode& errorCode) { |
| 1119 | U_ASSERT(inBounds()); |
| 1120 | |
| 1121 | U_ASSERT(peek() == AT); |
| 1122 | // Consume the '@' |
| 1123 | parseToken(AT, errorCode); |
| 1124 | |
| 1125 | // Parse LHS |
| 1126 | UnicodeString lhs = parseIdentifier(errorCode); |
| 1127 | |
| 1128 | // Prepare to "backtrack" to resolve ambiguity |
| 1129 | // about whether whitespace precedes another |
| 1130 | // attribute, or the '=' sign |
| 1131 | int32_t savedIndex = index; |
| 1132 | parseOptionalWhitespace(); |
| 1133 | |
| 1134 | Operand rand; |
| 1135 | if (peek() == EQUALS) { |
| 1136 | // Parse '=' |
| 1137 | parseTokenWithWhitespace(EQUALS, errorCode); |
| 1138 | |
| 1139 | UnicodeString rhsStr; |
| 1140 | // Parse RHS, which must be a literal |
| 1141 | // attribute = "@" identifier [o "=" o literal] |
| 1142 | rand = Operand(parseLiteral(errorCode)); |
| 1143 | } else { |
| 1144 | // attribute -> "@" identifier [[s] "=" [s]] |
| 1145 | // Use null operand, which `rand` is already set to |
| 1146 | // "Backtrack" by restoring the whitespace (if there was any) |
| 1147 | index = savedIndex; |
| 1148 | } |
| 1149 | |
| 1150 | attrAdder.addAttribute(lhs, std::move(Operand(rand)), errorCode); |
| 1151 | } |
| 1152 | |
| 1153 | /* |
| 1154 | Consume a name-value pair, matching the `option` nonterminal in the grammar. |
| 1155 | |
| 1156 | Adds the option to `optionList` |
| 1157 | */ |
| 1158 | template<class T> |
| 1159 | void Parser::parseOption(OptionAdder<T>& addOption, UErrorCode& errorCode) { |
| 1160 | U_ASSERT(inBounds()); |
| 1161 | |
| 1162 | // Parse LHS |
| 1163 | UnicodeString lhs = parseIdentifier(errorCode); |
| 1164 | |
| 1165 | // Parse '=' |
| 1166 | parseTokenWithWhitespace(EQUALS, errorCode); |
| 1167 | |
| 1168 | UnicodeString rhsStr; |
| 1169 | Operand rand; |
| 1170 | // Parse RHS, which is either a literal or variable |
| 1171 | switch (peek()) { |
| 1172 | case DOLLAR: { |
| 1173 | rand = Operand(parseVariableName(errorCode)); |
| 1174 | break; |
| 1175 | } |
| 1176 | default: { |
| 1177 | // Must be a literal |
| 1178 | rand = Operand(parseLiteral(errorCode)); |
| 1179 | break; |
| 1180 | } |
| 1181 | } |
| 1182 | U_ASSERT(!rand.isNull()); |
| 1183 | |
| 1184 | // Finally, add the key=value mapping |
| 1185 | // Use a local error code, check for duplicate option error and |
| 1186 | // record it as with other errors |
| 1187 | UErrorCode status = U_ZERO_ERROR; |
| 1188 | addOption.addOption(lhs, std::move(rand), status); |
| 1189 | if (U_FAILURE(status)) { |
| 1190 | U_ASSERT(status == U_MF_DUPLICATE_OPTION_NAME_ERROR); |
| 1191 | errors.setDuplicateOptionName(errorCode); |
| 1192 | } |
| 1193 | } |
| 1194 | |
| 1195 | /* |
| 1196 | Note: there are multiple overloads of parseOptions() for parsing |
| 1197 | options within markup, vs. within an expression, vs. parsing |
| 1198 | attributes. This should be refactored. TODO |
| 1199 | */ |
| 1200 | |
| 1201 | /* |
| 1202 | Consume optional whitespace followed by a sequence of options |
| 1203 | (possibly empty), separated by whitespace |
| 1204 | */ |
| 1205 | template <class T> |
| 1206 | void Parser::parseOptions(OptionAdder<T>& addOption, UErrorCode& errorCode) { |
| 1207 | // Early exit if out of bounds -- no more work is possible |
| 1208 | CHECK_BOUNDS(errorCode); |
| 1209 | |
| 1210 | /* |
| 1211 | Arbitrary lookahead is required to parse option lists. To see why, consider |
| 1212 | these rules from the grammar: |
| 1213 | |
| 1214 | expression = "{" [s] (((literal / variable) [s annotation]) / annotation) [s] "}" |
| 1215 | annotation = (function *(s option)) / reserved |
| 1216 | |
| 1217 | And this example: |
| 1218 | {:foo } |
| 1219 | |
| 1220 | Derivation: |
| 1221 | expression -> "{" [s] (((literal / variable) [s annotation]) / annotation) [s] "}" |
| 1222 | -> "{" [s] annotation [s] "}" |
| 1223 | -> "{" [s] ((function *(s option)) / reserved) [s] "}" |
| 1224 | -> "{" [s] function *(s option) [s] "}" |
| 1225 | |
| 1226 | In this example, knowing whether to expect a '}' or the start of another option |
| 1227 | after the whitespace would require arbitrary lookahead -- in other words, which |
| 1228 | rule should we apply? |
| 1229 | *(s option) -> s option *(s option) |
| 1230 | or |
| 1231 | *(s option) -> |
| 1232 | |
| 1233 | The same would apply to the example {:foo k=v } (note the trailing space after "v"). |
| 1234 | |
| 1235 | This is addressed using a form of backtracking and (to make the backtracking easier |
| 1236 | to apply) a slight refactoring to the grammar. |
| 1237 | |
| 1238 | This code is written as if the grammar is: |
| 1239 | expression = "{" [s] (((literal / variable) ([s] / [s annotation])) / annotation) "}" |
| 1240 | annotation = (function *(s option) [s]) / (reserved [s]) |
| 1241 | |
| 1242 | Parsing the `*(s option) [s]` sequence can be done within `parseOptions()`, meaning |
| 1243 | that `parseExpression()` can safely require a '}' after `parseOptions()` finishes. |
| 1244 | |
| 1245 | Note that when "backtracking" really just means early exit, since only whitespace |
| 1246 | is involved and there's no state to save. |
| 1247 | |
| 1248 | There is a separate but similar ambiguity as to whether the space precedes |
| 1249 | an option or an attribute. |
| 1250 | */ |
| 1251 | |
| 1252 | while(true) { |
| 1253 | // If the next character is not whitespace, that means we've already |
| 1254 | // parsed the entire options list (which may have been empty) and there's |
| 1255 | // no trailing whitespace. In that case, exit. |
| 1256 | if (!isWhitespace(peek())) { |
| 1257 | break; |
| 1258 | } |
| 1259 | int32_t firstWhitespace = index; |
| 1260 | |
| 1261 | // In any case other than an empty options list, there must be at least |
| 1262 | // one whitespace character. |
| 1263 | parseRequiredWhitespace(errorCode); |
| 1264 | // Restore precondition |
| 1265 | CHECK_BOUNDS(errorCode); |
| 1266 | |
| 1267 | // If a name character follows, then at least one more option remains |
| 1268 | // in the list. |
| 1269 | // Otherwise, we've consumed all the options and any trailing whitespace, |
| 1270 | // and can exit. |
| 1271 | // Note that exiting is sort of like backtracking: "(s option)" doesn't apply, |
| 1272 | // so we back out to [s]. |
| 1273 | if (!isNameStart(peek())) { |
| 1274 | // We've consumed all the options (meaning that either we consumed non-empty |
| 1275 | // whitespace, or consumed at least one option.) |
| 1276 | // Done. |
| 1277 | // Remove the required whitespace from normalizedInput |
| 1278 | normalizedInput.truncate(normalizedInput.length() - 1); |
| 1279 | // "Backtrack" so as to leave the optional whitespace there |
| 1280 | // when parsing attributes |
| 1281 | index = firstWhitespace; |
| 1282 | break; |
| 1283 | } |
| 1284 | parseOption(addOption, errorCode); |
| 1285 | } |
| 1286 | } |
| 1287 | |
| 1288 | /* |
| 1289 | Consume optional whitespace followed by a sequence of attributes |
| 1290 | (possibly empty), separated by whitespace |
| 1291 | */ |
| 1292 | template<class T> |
| 1293 | void Parser::parseAttributes(AttributeAdder<T>& attrAdder, UErrorCode& errorCode) { |
| 1294 | |
| 1295 | // Early exit if out of bounds -- no more work is possible |
| 1296 | if (!inBounds()) { |
| 1297 | ERROR(errorCode); |
| 1298 | return; |
| 1299 | } |
| 1300 | |
| 1301 | /* |
| 1302 | Arbitrary lookahead is required to parse attribute lists, similarly to option lists. |
| 1303 | (See comment in parseOptions()). |
| 1304 | */ |
| 1305 | |
| 1306 | while(true) { |
| 1307 | // If the next character is not whitespace, that means we've already |
| 1308 | // parsed the entire attributes list (which may have been empty) and there's |
| 1309 | // no trailing whitespace. In that case, exit. |
| 1310 | if (!isWhitespace(peek())) { |
| 1311 | break; |
| 1312 | } |
| 1313 | |
| 1314 | // In any case other than an empty attributes list, there must be at least |
| 1315 | // one whitespace character. |
| 1316 | parseRequiredWhitespace(errorCode); |
| 1317 | // Restore precondition |
| 1318 | if (!inBounds()) { |
| 1319 | ERROR(errorCode); |
| 1320 | break; |
| 1321 | } |
| 1322 | |
| 1323 | // If an '@' follows, then at least one more attribute remains |
| 1324 | // in the list. |
| 1325 | // Otherwise, we've consumed all the attributes and any trailing whitespace, |
| 1326 | // and can exit. |
| 1327 | // Note that exiting is sort of like backtracking: "(s attributes)" doesn't apply, |
| 1328 | // so we back out to [s]. |
| 1329 | if (peek() != AT) { |
| 1330 | // We've consumed all the attributes (meaning that either we consumed non-empty |
| 1331 | // whitespace, or consumed at least one attribute.) |
| 1332 | // Done. |
| 1333 | // Remove the whitespace from normalizedInput |
| 1334 | normalizedInput.truncate(normalizedInput.length() - 1); |
| 1335 | break; |
| 1336 | } |
| 1337 | parseAttribute(attrAdder, errorCode); |
| 1338 | } |
| 1339 | } |
| 1340 | |
| 1341 | /* |
| 1342 | Consume a function call, matching the `annotation` |
| 1343 | nonterminal in the grammar |
| 1344 | |
| 1345 | Returns an `Operator` representing this (a reserved is a parse error) |
| 1346 | */ |
| 1347 | Operator Parser::parseAnnotation(UErrorCode& status) { |
| 1348 | U_ASSERT(inBounds()); |
| 1349 | Operator::Builder ratorBuilder(status); |
| 1350 | if (U_FAILURE(status)) { |
| 1351 | return {}; |
| 1352 | } |
| 1353 | if (isFunctionStart(peek())) { |
| 1354 | // Consume the function name |
| 1355 | FunctionName func = parseFunction(status); |
| 1356 | ratorBuilder.setFunctionName(std::move(func)); |
| 1357 | |
| 1358 | OptionAdder<Operator::Builder> addOptions(ratorBuilder); |
| 1359 | // Consume the options (which may be empty) |
| 1360 | parseOptions(addOptions, status); |
| 1361 | } else { |
| 1362 | ERROR(status); |
| 1363 | } |
| 1364 | return ratorBuilder.build(status); |
| 1365 | } |
| 1366 | |
| 1367 | /* |
| 1368 | Consume a literal or variable (depending on `isVariable`), |
| 1369 | followed by either required whitespace followed by an annotation, |
| 1370 | or optional whitespace. |
| 1371 | */ |
| 1372 | void Parser::parseLiteralOrVariableWithAnnotation(bool isVariable, |
| 1373 | Expression::Builder& builder, |
| 1374 | UErrorCode& status) { |
| 1375 | CHECK_ERROR(status); |
| 1376 | |
| 1377 | U_ASSERT(inBounds()); |
| 1378 | |
| 1379 | Operand rand; |
| 1380 | if (isVariable) { |
| 1381 | rand = Operand(parseVariableName(status)); |
| 1382 | } else { |
| 1383 | rand = Operand(parseLiteral(status)); |
| 1384 | } |
| 1385 | |
| 1386 | builder.setOperand(std::move(rand)); |
| 1387 | |
| 1388 | /* |
| 1389 | Parsing a literal or variable with an optional annotation requires arbitrary lookahead. |
| 1390 | To see why, consider this rule from the grammar: |
| 1391 | |
| 1392 | expression = "{" [s] (((literal / variable) [s annotation]) / annotation) [s] "}" |
| 1393 | |
| 1394 | And this example: |
| 1395 | |
| 1396 | {|foo| } |
| 1397 | |
| 1398 | Derivation: |
| 1399 | expression -> "{" [s] (((literal / variable) [s annotation]) / annotation) [s] "}" |
| 1400 | -> "{" [s] ((literal / variable) [s annotation]) [s] "}" |
| 1401 | -> "{" [s] (literal [s annotation]) [s] "}" |
| 1402 | |
| 1403 | When reading the ' ' after the second '|', it's ambiguous whether that's the required |
| 1404 | space before an annotation, or the optional space before the '}'. |
| 1405 | |
| 1406 | To make this ambiguity easier to handle, this code is based on the same grammar |
| 1407 | refactoring for the `expression` nonterminal that `parseOptions()` relies on. See |
| 1408 | the comment in `parseOptions()` for details. |
| 1409 | */ |
| 1410 | |
| 1411 | if (isWhitespace(peek())) { |
| 1412 | int32_t firstWhitespace = index; |
| 1413 | |
| 1414 | // If the next character is whitespace, either [s annotation] or [s] applies |
| 1415 | // (the character is either the required space before an annotation, or optional |
| 1416 | // trailing space after the literal or variable). It's still ambiguous which |
| 1417 | // one does apply. |
| 1418 | parseOptionalWhitespace(); |
| 1419 | // Restore precondition |
| 1420 | CHECK_BOUNDS(status); |
| 1421 | |
| 1422 | // This next check resolves the ambiguity between [s annotation] and [s] |
| 1423 | bool isSAnnotation = isAnnotationStart(peek()); |
| 1424 | |
| 1425 | if (isSAnnotation) { |
| 1426 | normalizedInput += SPACE; |
| 1427 | } |
| 1428 | |
| 1429 | if (isSAnnotation) { |
| 1430 | // The previously consumed whitespace precedes an annotation |
| 1431 | builder.setOperator(parseAnnotation(status)); |
| 1432 | } else { |
| 1433 | // Either there's a right curly brace (will be consumed by the caller), |
| 1434 | // or there's an error and the trailing whitespace should be |
| 1435 | // handled by the caller. However, this is not an error |
| 1436 | // here because we're just parsing `literal [s annotation]`. |
| 1437 | index = firstWhitespace; |
| 1438 | } |
| 1439 | } else { |
| 1440 | // Either there was never whitespace, or |
| 1441 | // the previously consumed whitespace is the optional trailing whitespace; |
| 1442 | // either the next character is '}' or the error will be handled by parseExpression. |
| 1443 | // Do nothing, since the operand was already set |
| 1444 | } |
| 1445 | |
| 1446 | // At the end of this code, the next character should either be '}', |
| 1447 | // whitespace followed by a '}', |
| 1448 | // or end-of-input |
| 1449 | } |
| 1450 | |
| 1451 | /* |
| 1452 | Consume an expression, matching the `expression` nonterminal in the grammar |
| 1453 | */ |
| 1454 | |
| 1455 | static void exprFallback(Expression::Builder& exprBuilder) { |
| 1456 | // Construct a literal consisting just of The U+FFFD REPLACEMENT CHARACTER |
| 1457 | // per https://github.com/unicode-org/message-format-wg/blob/main/spec/formatting.md#fallback-resolution |
| 1458 | exprBuilder.setOperand(Operand(Literal(false, UnicodeString(REPLACEMENT)))); |
| 1459 | } |
| 1460 | |
| 1461 | static Expression exprFallback(UErrorCode& status) { |
| 1462 | Expression result; |
| 1463 | if (U_SUCCESS(status)) { |
| 1464 | Expression::Builder exprBuilder(status); |
| 1465 | if (U_SUCCESS(status)) { |
| 1466 | // Construct a literal consisting just of The U+FFFD REPLACEMENT CHARACTER |
| 1467 | // per https://github.com/unicode-org/message-format-wg/blob/main/spec/formatting.md#fallback-resolution |
| 1468 | exprBuilder.setOperand(Operand(Literal(false, UnicodeString(REPLACEMENT)))); |
| 1469 | UErrorCode status = U_ZERO_ERROR; |
| 1470 | result = exprBuilder.build(status); |
| 1471 | // An operand was set, so there can't be an error |
| 1472 | U_ASSERT(U_SUCCESS(status)); |
| 1473 | } |
| 1474 | } |
| 1475 | return result; |
| 1476 | } |
| 1477 | |
| 1478 | Expression Parser::parseExpression(UErrorCode& status) { |
| 1479 | if (U_FAILURE(status)) { |
| 1480 | return {}; |
| 1481 | } |
| 1482 | |
| 1483 | // Early return if out of input -- no more work is possible |
| 1484 | U_ASSERT(inBounds()); |
| 1485 | |
| 1486 | // Parse opening brace |
| 1487 | parseToken(LEFT_CURLY_BRACE, status); |
| 1488 | // Optional whitespace after opening brace |
| 1489 | parseOptionalWhitespace(); |
| 1490 | |
| 1491 | Expression::Builder exprBuilder(status); |
| 1492 | // Restore precondition |
| 1493 | if (!inBounds()) { |
| 1494 | exprFallback(exprBuilder); |
| 1495 | } else { |
| 1496 | // literal '|', variable '$' or annotation |
| 1497 | switch (peek()) { |
| 1498 | case PIPE: { |
| 1499 | // Quoted literal |
| 1500 | parseLiteralOrVariableWithAnnotation(false, exprBuilder, status); |
| 1501 | break; |
| 1502 | } |
| 1503 | case DOLLAR: { |
| 1504 | // Variable |
| 1505 | parseLiteralOrVariableWithAnnotation(true, exprBuilder, status); |
| 1506 | break; |
| 1507 | } |
| 1508 | default: { |
| 1509 | if (isAnnotationStart(peek())) { |
| 1510 | Operator rator = parseAnnotation(status); |
| 1511 | exprBuilder.setOperator(std::move(rator)); |
| 1512 | } else if (isUnquotedStart(peek())) { |
| 1513 | // Unquoted literal |
| 1514 | parseLiteralOrVariableWithAnnotation(false, exprBuilder, status); |
| 1515 | } else { |
| 1516 | // Not a literal, variable or annotation -- error out |
| 1517 | ERROR(status); |
| 1518 | exprFallback(exprBuilder); |
| 1519 | break; |
| 1520 | } |
| 1521 | break; |
| 1522 | } |
| 1523 | } |
| 1524 | } |
| 1525 | |
| 1526 | // Parse attributes |
| 1527 | AttributeAdder<Expression::Builder> attrAdder(exprBuilder); |
| 1528 | parseAttributes(attrAdder, status); |
| 1529 | |
| 1530 | // Parse optional space |
| 1531 | // (the last [s] in e.g. "{" [s] literal [s annotation] *(s attribute) [s] "}") |
| 1532 | parseOptionalWhitespace(); |
| 1533 | |
| 1534 | // Either an operand or operator (or both) must have been set already, |
| 1535 | // so there can't be an error |
| 1536 | UErrorCode localStatus = U_ZERO_ERROR; |
| 1537 | Expression result = exprBuilder.build(localStatus); |
| 1538 | U_ASSERT(U_SUCCESS(localStatus)); |
| 1539 | |
| 1540 | // Check for end-of-input and missing '}' |
| 1541 | if (!inBounds()) { |
| 1542 | ERROR(status); |
| 1543 | } else { |
| 1544 | // Otherwise, it's safe to check for the '}' |
| 1545 | parseToken(RIGHT_CURLY_BRACE, status); |
| 1546 | } |
| 1547 | return result; |
| 1548 | } |
| 1549 | |
| 1550 | /* |
| 1551 | Parse a .local declaration, matching the `local-declaration` |
| 1552 | production in the grammar |
| 1553 | */ |
| 1554 | void Parser::parseLocalDeclaration(UErrorCode& status) { |
| 1555 | // End-of-input here would be an error; even empty |
| 1556 | // declarations must be followed by a body |
| 1557 | CHECK_BOUNDS(status); |
| 1558 | |
| 1559 | parseToken(ID_LOCAL, status); |
| 1560 | parseRequiredWhitespace(status); |
| 1561 | |
| 1562 | // Restore precondition |
| 1563 | CHECK_BOUNDS(status); |
| 1564 | VariableName lhs = parseVariableName(status); |
| 1565 | parseTokenWithWhitespace(EQUALS, status); |
| 1566 | // Restore precondition before calling parseExpression() |
| 1567 | CHECK_BOUNDS(status); |
| 1568 | |
| 1569 | Expression rhs = parseExpression(status); |
| 1570 | |
| 1571 | // Add binding from lhs to rhs, unless there was an error |
| 1572 | // (This ensures that if there was a correct lhs but a |
| 1573 | // parse error in rhs, the fallback for uses of the |
| 1574 | // lhs will be its own name rather than the rhs) |
| 1575 | /* This affects the behavior of this test case, which the spec |
| 1576 | is ambiguous about: |
| 1577 | |
| 1578 | .local $bar {|foo|} {{{$bar}}} |
| 1579 | |
| 1580 | Should `$bar` still be bound to a value although |
| 1581 | its declaration is syntactically incorrect (missing the '=')? |
| 1582 | This code says no, but it needs to change if |
| 1583 | https://github.com/unicode-org/message-format-wg/issues/703 |
| 1584 | is resolved differently. |
| 1585 | */ |
| 1586 | CHECK_ERROR(status); |
| 1587 | if (!errors.hasSyntaxError()) { |
| 1588 | dataModel.addBinding(Binding(std::move(lhs), std::move(rhs)), status); |
| 1589 | // Check if status is U_DUPLICATE_DECLARATION_ERROR |
| 1590 | // and add that as an internal error if so |
| 1591 | if (status == U_MF_DUPLICATE_DECLARATION_ERROR) { |
| 1592 | status = U_ZERO_ERROR; |
| 1593 | errors.addError(StaticErrorType::DuplicateDeclarationError, status); |
| 1594 | } |
| 1595 | } |
| 1596 | } |
| 1597 | |
| 1598 | /* |
| 1599 | Parse an .input declaration, matching the `local-declaration` |
| 1600 | production in the grammar |
| 1601 | */ |
| 1602 | void Parser::parseInputDeclaration(UErrorCode& status) { |
| 1603 | // End-of-input here would be an error; even empty |
| 1604 | // declarations must be followed by a body |
| 1605 | CHECK_BOUNDS(status); |
| 1606 | |
| 1607 | parseToken(ID_INPUT, status); |
| 1608 | parseOptionalWhitespace(); |
| 1609 | |
| 1610 | // Restore precondition before calling parseExpression() |
| 1611 | CHECK_BOUNDS(status); |
| 1612 | |
| 1613 | // Save the index for error diagnostics |
| 1614 | int32_t exprIndex = index; |
| 1615 | Expression rhs = parseExpression(status); |
| 1616 | |
| 1617 | // Here we have to check that the rhs is a variable-expression |
| 1618 | if (!rhs.getOperand().isVariable()) { |
| 1619 | // This case is a syntax error; report it at the beginning |
| 1620 | // of the expression |
| 1621 | ERROR_AT(status, exprIndex); |
| 1622 | return; |
| 1623 | } |
| 1624 | |
| 1625 | VariableName lhs = rhs.getOperand().asVariable(); |
| 1626 | |
| 1627 | // Add binding from lhs to rhs |
| 1628 | // This just adds a new local variable that shadows the message |
| 1629 | // argument referred to, which is harmless. |
| 1630 | // When evaluating the RHS, the new local is not in scope |
| 1631 | // and the message argument will be correctly referred to. |
| 1632 | CHECK_ERROR(status); |
| 1633 | if (!errors.hasSyntaxError()) { |
| 1634 | dataModel.addBinding(Binding::input(std::move(lhs), std::move(rhs), status), status); |
| 1635 | // Check if status is U_MF_DUPLICATE_DECLARATION_ERROR |
| 1636 | // and add that as an internal error if so |
| 1637 | if (status == U_MF_DUPLICATE_DECLARATION_ERROR) { |
| 1638 | status = U_ZERO_ERROR; |
| 1639 | errors.addError(StaticErrorType::DuplicateDeclarationError, status); |
| 1640 | } |
| 1641 | } |
| 1642 | } |
| 1643 | |
| 1644 | /* |
| 1645 | Consume a possibly-empty sequence of declarations separated by whitespace; |
| 1646 | each declaration matches the `declaration` nonterminal in the grammar |
| 1647 | |
| 1648 | Builds up an environment representing those declarations |
| 1649 | */ |
| 1650 | void Parser::parseDeclarations(UErrorCode& status) { |
| 1651 | // End-of-input here would be an error; even empty |
| 1652 | // declarations must be followed by a body |
| 1653 | CHECK_BOUNDS(status); |
| 1654 | |
| 1655 | while (peek() == PERIOD) { |
| 1656 | CHECK_BOUNDS_1(status); |
| 1657 | if (peek(1) == ID_LOCAL[1]) { |
| 1658 | parseLocalDeclaration(status); |
| 1659 | } else if (peek(1) == ID_INPUT[1]) { |
| 1660 | parseInputDeclaration(status); |
| 1661 | } else { |
| 1662 | // Done parsing declarations |
| 1663 | break; |
| 1664 | } |
| 1665 | |
| 1666 | // Avoid looping infinitely |
| 1667 | CHECK_ERROR(status); |
| 1668 | |
| 1669 | parseOptionalWhitespace(); |
| 1670 | // Restore precondition |
| 1671 | CHECK_BOUNDS(status); |
| 1672 | } |
| 1673 | } |
| 1674 | |
| 1675 | /* |
| 1676 | Consume a text character |
| 1677 | matching the `text-char` nonterminal in the grammar |
| 1678 | |
| 1679 | No postcondition (a message can end with a text-char) |
| 1680 | */ |
| 1681 | UnicodeString Parser::parseTextChar(UErrorCode& status) { |
| 1682 | UnicodeString str; |
| 1683 | if (!inBounds() || !(isTextChar(peek()))) { |
| 1684 | // Error -- text-char is expected here |
| 1685 | ERROR(status); |
| 1686 | } else { |
| 1687 | // See comment in parseQuotedLiteral() |
| 1688 | if (isEscapableChar(peek())) { |
| 1689 | normalizedInput += BACKSLASH; |
| 1690 | } |
| 1691 | normalizedInput += peek(); |
| 1692 | str += peek(); |
| 1693 | next(); |
| 1694 | maybeAdvanceLine(); |
| 1695 | } |
| 1696 | return str; |
| 1697 | } |
| 1698 | |
| 1699 | /* |
| 1700 | Consume an `nmtoken`, `literal`, or the string "*", matching |
| 1701 | the `key` nonterminal in the grammar |
| 1702 | */ |
| 1703 | Key Parser::parseKey(UErrorCode& status) { |
| 1704 | U_ASSERT(inBounds()); |
| 1705 | |
| 1706 | Key k; // wildcard by default |
| 1707 | // Literal | '*' |
| 1708 | switch (peek()) { |
| 1709 | case ASTERISK: { |
| 1710 | next(); |
| 1711 | normalizedInput += ASTERISK; |
| 1712 | // Guarantee postcondition |
| 1713 | if (!inBounds()) { |
| 1714 | ERROR(status); |
| 1715 | return k; |
| 1716 | } |
| 1717 | break; |
| 1718 | } |
| 1719 | default: { |
| 1720 | // Literal |
| 1721 | k = Key(parseLiteral(status)); |
| 1722 | break; |
| 1723 | } |
| 1724 | } |
| 1725 | return k; |
| 1726 | } |
| 1727 | |
| 1728 | /* |
| 1729 | Consume a non-empty sequence of `key`s separated by whitespace |
| 1730 | |
| 1731 | Takes ownership of `keys` |
| 1732 | */ |
| 1733 | SelectorKeys Parser::parseNonEmptyKeys(UErrorCode& status) { |
| 1734 | SelectorKeys result; |
| 1735 | |
| 1736 | if (U_FAILURE(status)) { |
| 1737 | return result; |
| 1738 | } |
| 1739 | |
| 1740 | U_ASSERT(inBounds()); |
| 1741 | |
| 1742 | /* |
| 1743 | Arbitrary lookahead is required to parse key lists. To see why, consider |
| 1744 | this rule from the grammar: |
| 1745 | |
| 1746 | variant = key *(s key) [s] quoted-pattern |
| 1747 | |
| 1748 | And this example: |
| 1749 | when k1 k2 {a} |
| 1750 | |
| 1751 | Derivation: |
| 1752 | variant -> key *(s key) [s] quoted-pattern |
| 1753 | -> key s key *(s key) quoted-pattern |
| 1754 | |
| 1755 | After matching ' ' to `s` and 'k2' to `key`, it would require arbitrary lookahead |
| 1756 | to know whether to expect the start of a pattern or the start of another key. |
| 1757 | In other words: is the second whitespace sequence the required space in *(s key), |
| 1758 | or the optional space in [s] quoted-pattern? |
| 1759 | |
| 1760 | This is addressed using "backtracking" (similarly to `parseOptions()`). |
| 1761 | */ |
| 1762 | |
| 1763 | SelectorKeys::Builder keysBuilder(status); |
| 1764 | if (U_FAILURE(status)) { |
| 1765 | return result; |
| 1766 | } |
| 1767 | |
| 1768 | // Since the first key is required, it's simplest to parse it separately. |
| 1769 | keysBuilder.add(parseKey(status), status); |
| 1770 | |
| 1771 | // Restore precondition |
| 1772 | if (!inBounds()) { |
| 1773 | ERROR(status); |
| 1774 | return result; |
| 1775 | } |
| 1776 | |
| 1777 | // We've seen at least one whitespace-key pair, so now we can parse |
| 1778 | // *(s key) [s] |
| 1779 | while (peek() != LEFT_CURLY_BRACE || isWhitespace(peek()) || isBidiControl(peek())) { |
| 1780 | bool wasWhitespace = isWhitespace(peek()) || isBidiControl(peek()); |
| 1781 | parseRequiredWhitespace(status); |
| 1782 | if (!wasWhitespace) { |
| 1783 | // Avoid infinite loop when parsing something like: |
| 1784 | // when * @{!... |
| 1785 | next(); |
| 1786 | } |
| 1787 | |
| 1788 | // Restore precondition |
| 1789 | if (!inBounds()) { |
| 1790 | ERROR(status); |
| 1791 | return result; |
| 1792 | } |
| 1793 | |
| 1794 | // At this point, it's ambiguous whether we are inside (s key) or [s]. |
| 1795 | // This check resolves that ambiguity. |
| 1796 | if (peek() == LEFT_CURLY_BRACE) { |
| 1797 | // A pattern follows, so what we just parsed was the optional |
| 1798 | // trailing whitespace. All the keys have been parsed. |
| 1799 | |
| 1800 | // Unpush the whitespace from `normalizedInput` |
| 1801 | normalizedInput.truncate(normalizedInput.length() - 1); |
| 1802 | break; |
| 1803 | } |
| 1804 | keysBuilder.add(parseKey(status), status); |
| 1805 | } |
| 1806 | |
| 1807 | return keysBuilder.build(status); |
| 1808 | } |
| 1809 | |
| 1810 | Pattern Parser::parseQuotedPattern(UErrorCode& status) { |
| 1811 | U_ASSERT(inBounds()); |
| 1812 | |
| 1813 | parseToken(LEFT_CURLY_BRACE, status); |
| 1814 | parseToken(LEFT_CURLY_BRACE, status); |
| 1815 | Pattern p = parseSimpleMessage(status); |
| 1816 | parseToken(RIGHT_CURLY_BRACE, status); |
| 1817 | parseToken(RIGHT_CURLY_BRACE, status); |
| 1818 | return p; |
| 1819 | } |
| 1820 | |
| 1821 | /* |
| 1822 | Consume a `placeholder`, matching the nonterminal in the grammar |
| 1823 | No postcondition (a markup can end a message) |
| 1824 | */ |
| 1825 | Markup Parser::parseMarkup(UErrorCode& status) { |
| 1826 | U_ASSERT(inBounds(1)); |
| 1827 | |
| 1828 | U_ASSERT(peek() == LEFT_CURLY_BRACE); |
| 1829 | |
| 1830 | Markup::Builder builder(status); |
| 1831 | if (U_FAILURE(status)) { |
| 1832 | return {}; |
| 1833 | } |
| 1834 | |
| 1835 | // Consume the '{' |
| 1836 | next(); |
| 1837 | normalizedInput += LEFT_CURLY_BRACE; |
| 1838 | parseOptionalWhitespace(); |
| 1839 | bool closing = false; |
| 1840 | switch (peek()) { |
| 1841 | case NUMBER_SIGN: { |
| 1842 | // Open or standalone; consume the '#' |
| 1843 | normalizedInput += peek(); |
| 1844 | next(); |
| 1845 | break; |
| 1846 | } |
| 1847 | case SLASH: { |
| 1848 | // Closing |
| 1849 | normalizedInput += peek(); |
| 1850 | closing = true; |
| 1851 | next(); |
| 1852 | break; |
| 1853 | } |
| 1854 | default: { |
| 1855 | ERROR(status); |
| 1856 | return {}; |
| 1857 | } |
| 1858 | } |
| 1859 | |
| 1860 | // Parse the markup identifier |
| 1861 | builder.setName(parseIdentifier(status)); |
| 1862 | |
| 1863 | // Parse the options, which must begin with a ' ' |
| 1864 | // if present |
| 1865 | if (inBounds() && (isWhitespace(peek()) || isBidiControl(peek()))) { |
| 1866 | OptionAdder<Markup::Builder> optionAdder(builder); |
| 1867 | parseOptions(optionAdder, status); |
| 1868 | } |
| 1869 | |
| 1870 | // Parse the attributes, which also must begin |
| 1871 | // with a ' ' |
| 1872 | if (inBounds() && (isWhitespace(peek()) || isBidiControl(peek()))) { |
| 1873 | AttributeAdder<Markup::Builder> attrAdder(builder); |
| 1874 | parseAttributes(attrAdder, status); |
| 1875 | } |
| 1876 | |
| 1877 | parseOptionalWhitespace(); |
| 1878 | |
| 1879 | bool standalone = false; |
| 1880 | // Check if this is a standalone or not |
| 1881 | if (!closing) { |
| 1882 | if (inBounds() && peek() == SLASH) { |
| 1883 | standalone = true; |
| 1884 | normalizedInput += SLASH; |
| 1885 | next(); |
| 1886 | } |
| 1887 | } |
| 1888 | |
| 1889 | parseToken(RIGHT_CURLY_BRACE, status); |
| 1890 | |
| 1891 | if (standalone) { |
| 1892 | builder.setStandalone(); |
| 1893 | } else if (closing) { |
| 1894 | builder.setClose(); |
| 1895 | } else { |
| 1896 | builder.setOpen(); |
| 1897 | } |
| 1898 | |
| 1899 | return builder.build(status); |
| 1900 | } |
| 1901 | |
| 1902 | /* |
| 1903 | Consume a `placeholder`, matching the nonterminal in the grammar |
| 1904 | No postcondition (a placeholder can end a message) |
| 1905 | */ |
| 1906 | std::variant<Expression, Markup> Parser::parsePlaceholder(UErrorCode& status) { |
| 1907 | U_ASSERT(peek() == LEFT_CURLY_BRACE); |
| 1908 | |
| 1909 | if (!inBounds()) { |
| 1910 | ERROR(status); |
| 1911 | return exprFallback(status); |
| 1912 | } |
| 1913 | |
| 1914 | // Need to look ahead arbitrarily since whitespace |
| 1915 | // can appear before the '{' and '#' |
| 1916 | // in markup |
| 1917 | int32_t tempIndex = 1; |
| 1918 | bool isMarkup = false; |
| 1919 | while (inBounds(1)) { |
| 1920 | UChar32 c = peek(tempIndex); |
| 1921 | if (c == NUMBER_SIGN || c == SLASH) { |
| 1922 | isMarkup = true; |
| 1923 | break; |
| 1924 | } |
| 1925 | if (!(isWhitespace(c) || isBidiControl(c))) { |
| 1926 | break; |
| 1927 | } |
| 1928 | tempIndex++; |
| 1929 | } |
| 1930 | |
| 1931 | if (isMarkup) { |
| 1932 | return parseMarkup(status); |
| 1933 | } |
| 1934 | return parseExpression(status); |
| 1935 | } |
| 1936 | |
| 1937 | /* |
| 1938 | Consume a `simple-message`, matching the nonterminal in the grammar |
| 1939 | Postcondition: `index == len()` or U_FAILURE(status); |
| 1940 | for a syntactically correct message, this will consume the entire input |
| 1941 | */ |
| 1942 | Pattern Parser::parseSimpleMessage(UErrorCode& status) { |
| 1943 | Pattern::Builder result(status); |
| 1944 | |
| 1945 | if (U_SUCCESS(status)) { |
| 1946 | Expression expression; |
| 1947 | while (inBounds()) { |
| 1948 | switch (peek()) { |
| 1949 | case LEFT_CURLY_BRACE: { |
| 1950 | // Must be placeholder |
| 1951 | std::variant<Expression, Markup> piece = parsePlaceholder(status); |
| 1952 | if (std::holds_alternative<Expression>(piece)) { |
| 1953 | Expression expr = *std::get_if<Expression>(&piece); |
| 1954 | result.add(std::move(expr), status); |
| 1955 | } else { |
| 1956 | Markup markup = *std::get_if<Markup>(&piece); |
| 1957 | result.add(std::move(markup), status); |
| 1958 | } |
| 1959 | break; |
| 1960 | } |
| 1961 | case BACKSLASH: { |
| 1962 | // Must be escaped-char |
| 1963 | result.add(parseEscapeSequence(status), status); |
| 1964 | break; |
| 1965 | } |
| 1966 | case RIGHT_CURLY_BRACE: { |
| 1967 | // Distinguish unescaped '}' from end of quoted pattern |
| 1968 | break; |
| 1969 | } |
| 1970 | default: { |
| 1971 | // Must be text-char |
| 1972 | result.add(parseTextChar(status), status); |
| 1973 | break; |
| 1974 | } |
| 1975 | } |
| 1976 | if (peek() == RIGHT_CURLY_BRACE) { |
| 1977 | // End of quoted pattern |
| 1978 | break; |
| 1979 | } |
| 1980 | // Don't loop infinitely |
| 1981 | if (errors.hasSyntaxError() || U_FAILURE(status)) { |
| 1982 | break; |
| 1983 | } |
| 1984 | } |
| 1985 | } |
| 1986 | return result.build(status); |
| 1987 | } |
| 1988 | |
| 1989 | void Parser::parseVariant(UErrorCode& status) { |
| 1990 | CHECK_ERROR(status); |
| 1991 | |
| 1992 | // At least one key is required |
| 1993 | SelectorKeys keyList(parseNonEmptyKeys(status)); |
| 1994 | |
| 1995 | // parseNonEmptyKeys() consumes any trailing whitespace, |
| 1996 | // so the pattern can be consumed next. |
| 1997 | |
| 1998 | // Restore precondition before calling parsePattern() |
| 1999 | // (which must return a non-null value) |
| 2000 | CHECK_BOUNDS(status); |
| 2001 | Pattern rhs = parseQuotedPattern(status); |
| 2002 | |
| 2003 | dataModel.addVariant(std::move(keyList), std::move(rhs), status); |
| 2004 | } |
| 2005 | |
| 2006 | /* |
| 2007 | Consume a `selectors` (matching the nonterminal in the grammar), |
| 2008 | followed by a non-empty sequence of `variant`s (matching the nonterminal |
| 2009 | in the grammar) preceded by whitespace |
| 2010 | No postcondition (on return, `index` might equal `len()` with no syntax error |
| 2011 | because a message can end with a variant) |
| 2012 | */ |
| 2013 | void Parser::parseSelectors(UErrorCode& status) { |
| 2014 | CHECK_ERROR(status); |
| 2015 | |
| 2016 | U_ASSERT(inBounds()); |
| 2017 | |
| 2018 | parseToken(ID_MATCH, status); |
| 2019 | |
| 2020 | bool empty = true; |
| 2021 | // Parse selectors |
| 2022 | // "Backtracking" is required here. It's not clear if whitespace is |
| 2023 | // (`[s]` selector) or (`[s]` variant) |
| 2024 | while (isWhitespace(peek()) || peek() == DOLLAR) { |
| 2025 | int32_t whitespaceStart = index; |
| 2026 | parseRequiredWhitespace(status); |
| 2027 | // Restore precondition |
| 2028 | CHECK_BOUNDS(status); |
| 2029 | if (peek() != DOLLAR) { |
| 2030 | // This is not necessarily an error, but rather, |
| 2031 | // means the whitespace we parsed was the optional |
| 2032 | // whitespace preceding the first variant, not the |
| 2033 | // required whitespace preceding a subsequent variable. |
| 2034 | // In that case, "push back" the whitespace. |
| 2035 | normalizedInput.truncate(normalizedInput.length() - 1); |
| 2036 | index = whitespaceStart; |
| 2037 | break; |
| 2038 | } |
| 2039 | VariableName var = parseVariableName(status); |
| 2040 | empty = false; |
| 2041 | |
| 2042 | dataModel.addSelector(std::move(var), status); |
| 2043 | CHECK_ERROR(status); |
| 2044 | } |
| 2045 | |
| 2046 | // At least one selector is required |
| 2047 | if (empty) { |
| 2048 | ERROR(status); |
| 2049 | return; |
| 2050 | } |
| 2051 | |
| 2052 | #define CHECK_END_OF_INPUT \ |
| 2053 | if (!inBounds()) { \ |
| 2054 | break; \ |
| 2055 | } \ |
| 2056 | |
| 2057 | // Parse variants |
| 2058 | // matcher = match-statement s variant *(o variant) |
| 2059 | |
| 2060 | // Parse first variant |
| 2061 | parseRequiredWhitespace(status); |
| 2062 | if (!inBounds()) { |
| 2063 | ERROR(status); |
| 2064 | return; |
| 2065 | } |
| 2066 | parseVariant(status); |
| 2067 | if (!inBounds()) { |
| 2068 | // Not an error; there might be only one variant |
| 2069 | return; |
| 2070 | } |
| 2071 | |
| 2072 | while (isWhitespace(peek()) || isBidiControl(peek()) || isKeyStart(peek())) { |
| 2073 | parseOptionalWhitespace(); |
| 2074 | // Restore the precondition. |
| 2075 | // Trailing whitespace is allowed. |
| 2076 | if (!inBounds()) { |
| 2077 | return; |
| 2078 | } |
| 2079 | |
| 2080 | parseVariant(status); |
| 2081 | |
| 2082 | // Restore the precondition, *without* erroring out if we've |
| 2083 | // reached the end of input. That's because it's valid for the |
| 2084 | // message to end with a variant that has no trailing whitespace. |
| 2085 | // Why do we need to check this condition twice inside the loop? |
| 2086 | // Because if we don't check it here, the `isWhitespace()` call in |
| 2087 | // the loop head will read off the end of the input string. |
| 2088 | CHECK_END_OF_INPUT |
| 2089 | |
| 2090 | if (errors.hasSyntaxError() || U_FAILURE(status)) { |
| 2091 | break; |
| 2092 | } |
| 2093 | } |
| 2094 | } |
| 2095 | |
| 2096 | /* |
| 2097 | Consume a `body` (matching the nonterminal in the grammar), |
| 2098 | No postcondition (on return, `index` might equal `len()` with no syntax error, |
| 2099 | because a message can end with a body (trailing whitespace is optional) |
| 2100 | */ |
| 2101 | |
| 2102 | void Parser::errorPattern(UErrorCode& status) { |
| 2103 | errors.addSyntaxError(status); |
| 2104 | // Set to empty pattern |
| 2105 | Pattern::Builder result = Pattern::Builder(status); |
| 2106 | CHECK_ERROR(status); |
| 2107 | |
| 2108 | // If still in bounds, then add the remaining input as a single text part |
| 2109 | // to the pattern |
| 2110 | /* |
| 2111 | TODO: this behavior isn't documented in the spec, but it comes from |
| 2112 | https://github.com/messageformat/messageformat/blob/e0087bff312d759b67a9129eac135d318a1f0ce7/packages/mf2-messageformat/src/__fixtures/test-messages.json#L236 |
| 2113 | and a pending pull request https://github.com/unicode-org/message-format-wg/pull/462 will clarify |
| 2114 | whether this is the intent behind the spec |
| 2115 | */ |
| 2116 | UnicodeString partStr(LEFT_CURLY_BRACE); |
| 2117 | while (inBounds()) { |
| 2118 | partStr += peek(); |
| 2119 | next(); |
| 2120 | } |
| 2121 | // Add curly braces around the entire output (same comment as above) |
| 2122 | partStr += RIGHT_CURLY_BRACE; |
| 2123 | result.add(std::move(partStr), status); |
| 2124 | dataModel.setPattern(result.build(status)); |
| 2125 | } |
| 2126 | |
| 2127 | void Parser::parseBody(UErrorCode& status) { |
| 2128 | CHECK_ERROR(status); |
| 2129 | |
| 2130 | // Out-of-input is a syntax warning |
| 2131 | if (!inBounds()) { |
| 2132 | errorPattern(status); |
| 2133 | return; |
| 2134 | } |
| 2135 | |
| 2136 | // Body must be either a pattern or selectors |
| 2137 | switch (peek()) { |
| 2138 | case LEFT_CURLY_BRACE: { |
| 2139 | // Pattern |
| 2140 | dataModel.setPattern(parseQuotedPattern(status)); |
| 2141 | break; |
| 2142 | } |
| 2143 | case ID_MATCH[0]: { |
| 2144 | // Selectors |
| 2145 | parseSelectors(status); |
| 2146 | return; |
| 2147 | } |
| 2148 | default: { |
| 2149 | ERROR(status); |
| 2150 | errorPattern(status); |
| 2151 | return; |
| 2152 | } |
| 2153 | } |
| 2154 | } |
| 2155 | |
| 2156 | // ------------------------------------- |
| 2157 | // Parses the source pattern. |
| 2158 | |
| 2159 | void Parser::parse(UParseError &parseErrorResult, UErrorCode& status) { |
| 2160 | CHECK_ERROR(status); |
| 2161 | |
| 2162 | bool complex = false; |
| 2163 | // First, "look ahead" to determine if this is a simple or complex |
| 2164 | // message. To do that, check the first non-whitespace character. |
| 2165 | while (inBounds(index) && (isWhitespace(peek()) || isBidiControl(peek()))) { |
| 2166 | next(); |
| 2167 | } |
| 2168 | |
| 2169 | // Message can be empty, so we need to only look ahead |
| 2170 | // if we know it's non-empty |
| 2171 | if (inBounds()) { |
| 2172 | if (peek() == PERIOD |
| 2173 | || (inBounds(1) |
| 2174 | && peek() == LEFT_CURLY_BRACE |
| 2175 | && peek(1) == LEFT_CURLY_BRACE)) { |
| 2176 | complex = true; |
| 2177 | } |
| 2178 | } |
| 2179 | // Reset index |
| 2180 | index = 0; |
| 2181 | |
| 2182 | // Message can be empty, so we need to only look ahead |
| 2183 | // if we know it's non-empty |
| 2184 | if (complex) { |
| 2185 | parseOptionalWhitespace(); |
| 2186 | parseDeclarations(status); |
| 2187 | parseBody(status); |
| 2188 | parseOptionalWhitespace(); |
| 2189 | } else { |
| 2190 | // Simple message |
| 2191 | // For normalization, quote the pattern |
| 2192 | normalizedInput += LEFT_CURLY_BRACE; |
| 2193 | normalizedInput += LEFT_CURLY_BRACE; |
| 2194 | dataModel.setPattern(parseSimpleMessage(status)); |
| 2195 | normalizedInput += RIGHT_CURLY_BRACE; |
| 2196 | normalizedInput += RIGHT_CURLY_BRACE; |
| 2197 | } |
| 2198 | |
| 2199 | CHECK_ERROR(status); |
| 2200 | |
| 2201 | // There are no errors; finally, check that the entire input was consumed |
| 2202 | if (!allConsumed()) { |
| 2203 | ERROR(status); |
| 2204 | } |
| 2205 | |
| 2206 | // Finally, copy the relevant fields of the internal `MessageParseError` |
| 2207 | // into the `UParseError` argument |
| 2208 | translateParseError(parseError, parseErrorResult); |
| 2209 | } |
| 2210 | |
| 2211 | Parser::~Parser() {} |
| 2212 | |
| 2213 | } // namespace message2 |
| 2214 | U_NAMESPACE_END |
| 2215 | |
| 2216 | #endif /* #if !UCONFIG_NO_MF2 */ |
| 2217 | |
| 2218 | #endif /* #if !UCONFIG_NO_FORMATTING */ |
| 2219 | |
| 2220 | #endif /* #if !UCONFIG_NO_NORMALIZATION */ |