Checks that the shape of a `switch` block is valid. Returns an array of errors.
(ast: html.Block)
| 537 | |
| 538 | /** Checks that the shape of a `switch` block is valid. Returns an array of errors. */ |
| 539 | function validateSwitchBlock(ast: html.Block): ParseError[] { |
| 540 | const errors: ParseError[] = []; |
| 541 | let hasDefault = false; |
| 542 | |
| 543 | if (ast.parameters.length !== 1) { |
| 544 | errors.push( |
| 545 | new ParseError(ast.startSourceSpan, '@switch block must have exactly one parameter'), |
| 546 | ); |
| 547 | return errors; |
| 548 | } |
| 549 | |
| 550 | for (const node of ast.children) { |
| 551 | // Skip over comments and empty text nodes inside the switch block. |
| 552 | // Empty text nodes can be used for formatting while comments don't affect the runtime. |
| 553 | if ( |
| 554 | node instanceof html.Comment || |
| 555 | (node instanceof html.Text && node.value.trim().length === 0) |
| 556 | ) { |
| 557 | continue; |
| 558 | } |
| 559 | |
| 560 | if ( |
| 561 | !(node instanceof html.Block) || |
| 562 | (node.name !== 'case' && node.name !== 'default' && node.name !== 'default never') |
| 563 | ) { |
| 564 | errors.push( |
| 565 | new ParseError(node.sourceSpan, '@switch block can only contain @case and @default blocks'), |
| 566 | ); |
| 567 | continue; |
| 568 | } |
| 569 | |
| 570 | if (node.name === 'default never') { |
| 571 | if (hasDefault) { |
| 572 | errors.push( |
| 573 | new ParseError(node.startSourceSpan, '@switch block can only have one @default block'), |
| 574 | ); |
| 575 | } |
| 576 | hasDefault = true; |
| 577 | } else if (node.name === 'default') { |
| 578 | if (hasDefault) { |
| 579 | errors.push( |
| 580 | new ParseError(node.startSourceSpan, '@switch block can only have one @default block'), |
| 581 | ); |
| 582 | } else if (node.parameters.length > 0) { |
| 583 | errors.push(new ParseError(node.startSourceSpan, '@default block cannot have parameters')); |
| 584 | } |
| 585 | hasDefault = true; |
| 586 | } else if (node.name === 'case' && node.parameters.length !== 1) { |
| 587 | errors.push( |
| 588 | new ParseError(node.startSourceSpan, '@case block must have exactly one parameter'), |
| 589 | ); |
| 590 | } |
| 591 | } |
| 592 | |
| 593 | return errors; |
| 594 | } |
| 595 | |
| 596 | /** |
no test coverage detected