Transform and validate expr in '{.attr[item]}'.format(expr) into expr.attr['item']. If validation fails, return TempNode(AnyType).
(
self, spec: ConversionSpecifier, repl: Expression, ctx: Context
)
| 568 | return True |
| 569 | |
| 570 | def apply_field_accessors( |
| 571 | self, spec: ConversionSpecifier, repl: Expression, ctx: Context |
| 572 | ) -> Expression: |
| 573 | """Transform and validate expr in '{.attr[item]}'.format(expr) into expr.attr['item']. |
| 574 | |
| 575 | If validation fails, return TempNode(AnyType). |
| 576 | """ |
| 577 | assert spec.key, "Keys must be auto-generated first!" |
| 578 | if spec.field == spec.key: |
| 579 | return repl |
| 580 | assert spec.field |
| 581 | |
| 582 | temp_errors = Errors(self.chk.options) |
| 583 | dummy = DUMMY_FIELD_NAME + spec.field[len(spec.key) :] |
| 584 | temp_ast = parse( |
| 585 | dummy, |
| 586 | fnam="<format>", |
| 587 | module=None, |
| 588 | options=self.chk.options, |
| 589 | errors=temp_errors, |
| 590 | file_exists=False, |
| 591 | eager=True, |
| 592 | ) |
| 593 | if temp_errors.is_errors(): |
| 594 | self.msg.fail( |
| 595 | f'Syntax error in format specifier "{spec.field}"', |
| 596 | ctx, |
| 597 | code=codes.STRING_FORMATTING, |
| 598 | ) |
| 599 | return TempNode(AnyType(TypeOfAny.from_error)) |
| 600 | |
| 601 | # These asserts are guaranteed by the original regexp. |
| 602 | assert isinstance(temp_ast, MypyFile) |
| 603 | temp_ast = temp_ast.defs[0] |
| 604 | assert isinstance(temp_ast, ExpressionStmt) |
| 605 | temp_ast = temp_ast.expr |
| 606 | if not self.validate_and_transform_accessors(temp_ast, repl, spec, ctx=ctx): |
| 607 | return TempNode(AnyType(TypeOfAny.from_error)) |
| 608 | |
| 609 | # Check if there are any other errors (like missing members). |
| 610 | # TODO: fix column to point to actual start of the format specifier _within_ string. |
| 611 | temp_ast.line = ctx.line |
| 612 | temp_ast.column = ctx.column |
| 613 | self.chk.expr_checker.accept(temp_ast) |
| 614 | return temp_ast |
| 615 | |
| 616 | def validate_and_transform_accessors( |
| 617 | self, |
no test coverage detected