pydantic-jsonpointer 0.1.0b1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,849 @@
1
+ """Mypy plugin for pydantic-jsonpointer.
2
+
3
+ Validates that ``_ModelPath`` attribute and index access respects the
4
+ model class's field declarations.
5
+
6
+ In mypy 2.x, implicit attribute access on ``_ModelPath`` (e.g.,
7
+ ``mp.name``) is intercepted via ``get_attribute_hook`` rather than
8
+ ``get_method_signature_hook`` for ``__getattr__``. Explicit method calls
9
+ (e.g., ``mp[0]`` via ``__getitem__``) use ``get_method_signature_hook``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Any, Callable
15
+
16
+ from mypy.nodes import Expression, IntExpr, NameExpr, StrExpr, TypeInfo, UnaryExpr, Var
17
+ from mypy.plugin import AttributeContext, MethodSigContext, Plugin
18
+ from mypy.typeops import ( # type: ignore[attr-defined]
19
+ expand_type_by_instance,
20
+ map_instance_to_supertype,
21
+ )
22
+ from mypy.types import (
23
+ AnyType,
24
+ Instance,
25
+ LiteralType,
26
+ NoneType,
27
+ ProperType,
28
+ TupleType,
29
+ Type,
30
+ TypeOfAny,
31
+ UnionType,
32
+ get_proper_type,
33
+ )
34
+
35
+ _MODEL_PATH_FULLNAME = "pydantic_jsonpointer._model_path._ModelPath"
36
+
37
+
38
+ def _is_base_model(info: TypeInfo) -> bool:
39
+ for base in info.mro:
40
+ if base.fullname == "pydantic.main.BaseModel":
41
+ return True
42
+ return False
43
+
44
+
45
+ _ROOTMODEL_FULLNAMES = frozenset(
46
+ {
47
+ "pydantic.main.RootModel",
48
+ "pydantic.root_model.RootModel",
49
+ }
50
+ )
51
+
52
+ _MAX_ROOTMODEL_PEEL_DEPTH = 64
53
+
54
+
55
+ def _is_root_model(info: TypeInfo) -> bool:
56
+ for base in info.mro:
57
+ if base.fullname in _ROOTMODEL_FULLNAMES:
58
+ return True
59
+ return False
60
+
61
+
62
+ def _get_rootmodel_inner_raw(inst: Instance) -> ProperType | None:
63
+ """Return the raw inner type T from a RootModel Instance, not limited to Instance.
64
+
65
+ Handles three cases:
66
+ - Direct ``RootModel[T]`` annotation: reads the type arg from inst.args[0].
67
+ - Named subclass (e.g. ``TagList(RootModel[list[Item]])``) with no type args.
68
+ - Concrete subclass of a generic RootModel (e.g. ``AddressBox(Box[Address])``
69
+ where ``Box = RootModel[list[T]]``): uses map_instance_to_supertype to
70
+ compose substitutions through the full inheritance chain.
71
+
72
+ Unlike _get_rootmodel_inner, does not restrict the return type to Instance,
73
+ so TupleType and multi-branch UnionType inner types are returned as-is.
74
+ """
75
+ if inst.type.fullname in _ROOTMODEL_FULLNAMES and inst.args:
76
+ return get_proper_type(inst.args[0])
77
+ # Find the RootModel TypeInfo in the MRO and use map_instance_to_supertype
78
+ # to resolve TypeVar substitutions through the full inheritance chain.
79
+ # This correctly handles concrete subclasses like AddressBox(Box[Address])
80
+ # where Box = RootModel[list[T]] — inst.args is empty, but
81
+ # map_instance_to_supertype composes T=Address through Wrapper's bases.
82
+ for mro_type in inst.type.mro:
83
+ if mro_type.fullname in _ROOTMODEL_FULLNAMES:
84
+ try:
85
+ mapped = map_instance_to_supertype(inst, mro_type)
86
+ if mapped.args:
87
+ return get_proper_type(mapped.args[0])
88
+ except Exception:
89
+ pass
90
+ break
91
+ # Fallback: original MRO base walk for any edge case not covered above.
92
+ for mro_type in inst.type.mro:
93
+ for base in mro_type.bases:
94
+ if not isinstance(base, Instance):
95
+ continue
96
+ if base.type.fullname not in _ROOTMODEL_FULLNAMES:
97
+ continue
98
+ if not base.args:
99
+ continue
100
+ inner: Type = base.args[0]
101
+ if inst.args:
102
+ inner = expand_type_by_instance(inner, inst)
103
+ return get_proper_type(inner)
104
+ return None
105
+
106
+
107
+ def _is_indexed_container_type(info: TypeInfo) -> bool:
108
+ return info.fullname in (
109
+ "builtins.list",
110
+ "builtins.tuple",
111
+ )
112
+
113
+
114
+ def _advance_attr_mypy(typ: Type) -> Instance | None:
115
+ """Mypy-level _advance_attr. Returns model Instance or None."""
116
+ typ = get_proper_type(typ)
117
+
118
+ if isinstance(typ, UnionType):
119
+ items = [t for t in typ.items if not isinstance(get_proper_type(t), NoneType)]
120
+ if len(items) == 1:
121
+ return _advance_attr_mypy(items[0])
122
+ return None
123
+
124
+ if isinstance(typ, Instance):
125
+ # Check RootModel before BaseModel: RootModel IS a BaseModel subclass,
126
+ # so _is_base_model would match first and return the wrapper type unchanged.
127
+ if _is_root_model(typ.type):
128
+ # Use _get_rootmodel_inner_raw so that direct RootModel[T] annotations
129
+ # (not just named subclasses) are unwrapped via inst.args[0].
130
+ inner = _get_rootmodel_inner_raw(typ)
131
+ if inner is not None:
132
+ return _advance_attr_mypy(inner)
133
+ return None
134
+ if _is_base_model(typ.type):
135
+ return typ
136
+
137
+ return None
138
+
139
+
140
+ def _advance_index_mypy(typ: Type, *, _list_peeled: bool = False) -> Instance | None:
141
+ """Mypy-level _advance_index. Returns item Instance or None.
142
+
143
+ A BaseModel is only returned after peeling exactly one list or tuple
144
+ container, mirroring what _advance_index does at runtime. Peeling a
145
+ RootModel wrapper alone does not count — the inner type must still be a
146
+ list/tuple for indexing to be valid.
147
+
148
+ Uses _get_rootmodel_inner_raw rather than typ.args so that both generic
149
+ RootModel[T] usages and concrete subclasses (TagList, DoubleWrap) are
150
+ handled uniformly.
151
+
152
+ Returns None when the item is a non-BaseModel type (e.g. list[list[Item]]
153
+ yields list[Item] as the item — use _raw_item_annotation_mypy to get that).
154
+ """
155
+ typ = get_proper_type(typ)
156
+
157
+ if isinstance(typ, UnionType):
158
+ items = [t for t in typ.items if not isinstance(get_proper_type(t), NoneType)]
159
+ if len(items) == 1:
160
+ return _advance_index_mypy(items[0], _list_peeled=_list_peeled)
161
+ return None
162
+
163
+ if isinstance(typ, Instance):
164
+ if _is_root_model(typ.type):
165
+ inner = _get_rootmodel_inner_raw(typ)
166
+ if inner is not None:
167
+ return _advance_index_mypy(inner, _list_peeled=_list_peeled)
168
+ return None
169
+
170
+ if _is_indexed_container_type(typ.type) and typ.args:
171
+ if _list_peeled:
172
+ # Already peeled one container layer; item is another container,
173
+ # not a BaseModel — caller must use _raw_item_annotation_mypy.
174
+ return None
175
+ return _advance_index_mypy(typ.args[0], _list_peeled=True)
176
+
177
+ if _list_peeled and _is_base_model(typ.type):
178
+ return typ
179
+
180
+ return None
181
+
182
+
183
+ def _raw_item_annotation_mypy(typ: Type) -> Type | None:
184
+ """Return the item annotation from a list/tuple container after peeling wrappers.
185
+
186
+ Unlike _advance_index_mypy, does not require the item to be a BaseModel.
187
+ Used by _hook_getitem to carry the pending annotation forward when the item
188
+ is itself a container (e.g. list[list[Item]] -> list[Item]).
189
+ """
190
+ typ = get_proper_type(typ)
191
+
192
+ if isinstance(typ, UnionType):
193
+ items = [t for t in typ.items if not isinstance(get_proper_type(t), NoneType)]
194
+ if len(items) == 1:
195
+ return _raw_item_annotation_mypy(items[0])
196
+ return None
197
+
198
+ if isinstance(typ, Instance):
199
+ if _is_root_model(typ.type):
200
+ inner = _get_rootmodel_inner_raw(typ)
201
+ if inner is not None:
202
+ return _raw_item_annotation_mypy(inner)
203
+ return None
204
+ if _is_indexed_container_type(typ.type) and typ.args:
205
+ return get_proper_type(typ.args[0])
206
+
207
+ return None
208
+
209
+
210
+ def _make_modelpath_any(typeinfo: TypeInfo) -> Instance:
211
+ """Build _ModelPath[Any, Any] from the live _ModelPath TypeInfo.
212
+
213
+ Used to terminate the type chain cleanly when the next model can't be
214
+ determined statically (leaf type, ambiguous Union, root-level Any).
215
+ """
216
+ any_t = AnyType(TypeOfAny.implementation_artifact)
217
+ return Instance(typeinfo, [any_t, any_t])
218
+
219
+
220
+ def _extract_int_index(
221
+ arg_expr: object, ctx: MethodSigContext | None = None
222
+ ) -> int | None:
223
+ """Extract a non-negative integer index from an IntExpr, digit-string StrExpr, or
224
+ any expression whose inferred type is Literal[int] (e.g. a named Literal variable).
225
+
226
+ Mirrors the runtime normalization in _ModelPath.__getitem__: a string index
227
+ that is a valid RFC 6901 array token (ASCII digits, no leading zero except "0"
228
+ itself) resolves to the same tuple slot as the equivalent integer literal.
229
+ """
230
+ if isinstance(arg_expr, IntExpr):
231
+ return arg_expr.value
232
+ if isinstance(arg_expr, StrExpr):
233
+ v = arg_expr.value
234
+ if v and all("0" <= c <= "9" for c in v) and (len(v) == 1 or v[0] != "0"):
235
+ return int(v)
236
+ if ctx is not None:
237
+ if isinstance(arg_expr, Expression):
238
+ try:
239
+ expr_type = ctx.api.get_expression_type(arg_expr)
240
+ except Exception:
241
+ return None
242
+ if expr_type is not None:
243
+ proper = get_proper_type(expr_type)
244
+ if isinstance(proper, LiteralType):
245
+ if (
246
+ isinstance(proper.value, int)
247
+ and proper.fallback.type.fullname != "builtins.bool"
248
+ ):
249
+ return proper.value
250
+ if isinstance(proper.value, str):
251
+ v = proper.value
252
+ if (
253
+ v
254
+ and all("0" <= c <= "9" for c in v)
255
+ and (len(v) == 1 or v[0] != "0")
256
+ ):
257
+ return int(v)
258
+ return None
259
+
260
+
261
+ def _expr_has_bool_type(ctx: MethodSigContext, arg_expr: object) -> bool:
262
+ """Return True when mypy has inferred a bool type for the expression.
263
+
264
+ Covers all bool-typed expressions: literals, named variables, attribute
265
+ access (obj.flag), calls (flag_fn()), and comparisons (1 == 1).
266
+ Falls back to False when the type is not yet available (e.g. for exotic
267
+ expression forms where get_expression_type returns None).
268
+ """
269
+ from mypy.nodes import Expression
270
+
271
+ if not isinstance(arg_expr, Expression):
272
+ return False
273
+ try:
274
+ typ = ctx.api.get_expression_type(arg_expr)
275
+ except Exception:
276
+ return False
277
+ if typ is None:
278
+ return False
279
+ proper = get_proper_type(typ)
280
+ if isinstance(proper, Instance) and proper.type.fullname == "builtins.bool":
281
+ return True
282
+ # Literal[True] / Literal[False] have a LiteralType with bool fallback.
283
+ if (
284
+ isinstance(proper, LiteralType)
285
+ and proper.fallback.type.fullname == "builtins.bool"
286
+ ):
287
+ return True
288
+ return False
289
+
290
+
291
+ def _check_literal_index(ctx: MethodSigContext) -> bool:
292
+ """Validate the first argument against RFC 6901 array token rules.
293
+
294
+ Emits ctx.api.fail() and returns False for invalid literal indices
295
+ (negative integers, strings that are not valid RFC 6901 array tokens and
296
+ not the tail marker "-") and for bool-typed expressions (which are always
297
+ invalid regardless of value). Returns True when the argument is absent,
298
+ non-literal non-bool, or a valid token.
299
+ """
300
+ if not (ctx.args and ctx.args[0]):
301
+ return True
302
+ arg_expr = ctx.args[0][0]
303
+ # General type-based bool check: covers attribute access (obj.flag),
304
+ # function calls (flag_fn()), comparisons (1 == 1), named variables, and
305
+ # literals — any expression whose inferred type is bool.
306
+ if _expr_has_bool_type(ctx, arg_expr):
307
+ ctx.api.fail(
308
+ "invalid array index: bool is not a valid RFC 6901 array token",
309
+ ctx.context,
310
+ )
311
+ return False
312
+ # Fallback AST-based check for True/False literals in case get_expression_type
313
+ # hasn't typed the expression yet (defensive guard only).
314
+ if isinstance(arg_expr, NameExpr) and arg_expr.fullname in (
315
+ "builtins.True",
316
+ "builtins.False",
317
+ ):
318
+ ctx.api.fail(
319
+ f"invalid array index {arg_expr.name!r}: "
320
+ "bool is not a valid RFC 6901 array token",
321
+ ctx.context,
322
+ )
323
+ return False
324
+ # Negative literals appear as UnaryExpr('-', IntExpr(n)) in mypy's AST.
325
+ # Note: -0 evaluates to 0 which is a valid RFC 6901 token; only truly
326
+ # negative values (non-zero operand) should be rejected.
327
+ if isinstance(arg_expr, UnaryExpr) and arg_expr.op == "-":
328
+ if isinstance(arg_expr.expr, IntExpr) and arg_expr.expr.value > 0:
329
+ ctx.api.fail(
330
+ f"invalid array index {-arg_expr.expr.value!r}: "
331
+ "negative integers are not valid RFC 6901 array tokens",
332
+ ctx.context,
333
+ )
334
+ return False
335
+ if isinstance(arg_expr, IntExpr) and arg_expr.value < 0:
336
+ ctx.api.fail(
337
+ f"invalid array index {arg_expr.value!r}: "
338
+ "negative integers are not valid RFC 6901 array tokens",
339
+ ctx.context,
340
+ )
341
+ return False
342
+ if isinstance(arg_expr, StrExpr):
343
+ v = arg_expr.value
344
+ if v != "-":
345
+ valid = (
346
+ bool(v)
347
+ and all("0" <= c <= "9" for c in v)
348
+ and (len(v) == 1 or v[0] != "0")
349
+ )
350
+ if not valid:
351
+ ctx.api.fail(
352
+ f"invalid array token {v!r}: "
353
+ "must be a non-negative integer string or '-'",
354
+ ctx.context,
355
+ )
356
+ return False
357
+ # Named Literal variables not already caught by AST checks above: use type
358
+ # inference to validate negative int literals and invalid string tokens.
359
+ if isinstance(arg_expr, Expression):
360
+ try:
361
+ expr_type = ctx.api.get_expression_type(arg_expr)
362
+ except Exception:
363
+ pass
364
+ else:
365
+ if expr_type is not None:
366
+ proper_t = get_proper_type(expr_type)
367
+ if isinstance(proper_t, LiteralType):
368
+ val = proper_t.value
369
+ if (
370
+ isinstance(val, int)
371
+ and proper_t.fallback.type.fullname != "builtins.bool"
372
+ and val < 0
373
+ ):
374
+ ctx.api.fail(
375
+ f"invalid array index {val!r}: "
376
+ "negative integers are not valid RFC 6901 array tokens",
377
+ ctx.context,
378
+ )
379
+ return False
380
+ if isinstance(val, str) and val != "-":
381
+ valid_str = (
382
+ bool(val)
383
+ and all("0" <= c <= "9" for c in val)
384
+ and (len(val) == 1 or val[0] != "0")
385
+ )
386
+ if not valid_str:
387
+ ctx.api.fail(
388
+ f"invalid array token {val!r}: "
389
+ "must be a non-negative integer string or '-'",
390
+ ctx.context,
391
+ )
392
+ return False
393
+ return True
394
+
395
+
396
+ def _is_dash_index(ctx: MethodSigContext) -> bool:
397
+ """Return True when the first __getitem__ argument is or evaluates to '-'.
398
+
399
+ Covers inline StrExpr("-") and named Literal["-"] variables via type
400
+ inference so the tuple tail-marker context-loss path is symmetric with
401
+ literal-index validation in _check_literal_index.
402
+ """
403
+ if not (ctx.args and ctx.args[0]):
404
+ return False
405
+ arg_expr = ctx.args[0][0]
406
+ if isinstance(arg_expr, StrExpr):
407
+ return arg_expr.value == "-"
408
+ if isinstance(arg_expr, Expression):
409
+ try:
410
+ expr_type = ctx.api.get_expression_type(arg_expr)
411
+ except Exception:
412
+ return False
413
+ if expr_type is not None:
414
+ proper = get_proper_type(expr_type)
415
+ if isinstance(proper, LiteralType) and proper.value == "-":
416
+ return True
417
+ return False
418
+
419
+
420
+ def _is_ambiguous_basemodel_union(field_type: Type) -> bool:
421
+ """True iff field_type is a Union of >=2 BaseModel branches (non-None)."""
422
+ proper = get_proper_type(field_type)
423
+ if not isinstance(proper, UnionType):
424
+ return False
425
+ non_none = [t for t in proper.items if not isinstance(get_proper_type(t), NoneType)]
426
+ if len(non_none) <= 1:
427
+ return False
428
+ for branch in non_none:
429
+ inner = get_proper_type(branch)
430
+ if not isinstance(inner, Instance):
431
+ return False
432
+ if not _is_base_model(inner.type):
433
+ return False
434
+ return True
435
+
436
+
437
+ def _has_any_indexable_branch(typ: Type) -> bool:
438
+ """True iff typ is a Union containing at least one list or tuple branch.
439
+
440
+ Used to avoid false-positive 'index applied to non-list type' errors for
441
+ fields like list[A] | list[B] where indexing is valid at runtime (it just
442
+ loses model context, matching the _model_ctx_lost=True runtime path).
443
+ """
444
+ proper = get_proper_type(typ)
445
+ if not isinstance(proper, UnionType):
446
+ return False
447
+ for item in proper.items:
448
+ branch = get_proper_type(item)
449
+ if isinstance(branch, NoneType):
450
+ continue
451
+ if isinstance(branch, Instance) and _is_indexed_container_type(branch.type):
452
+ return True
453
+ if isinstance(branch, TupleType):
454
+ return True
455
+ # Peel RootModel[list[...]] / RootModel[tuple[...]] so that fields like
456
+ # `wrapped: RootModel[list[Item]] | int` are not false-positived.
457
+ if isinstance(branch, Instance) and _is_root_model(branch.type):
458
+ inner = _get_rootmodel_inner_raw(branch)
459
+ if inner is not None:
460
+ if isinstance(inner, Instance) and _is_indexed_container_type(
461
+ inner.type
462
+ ):
463
+ return True
464
+ if isinstance(inner, TupleType):
465
+ return True
466
+ return False
467
+
468
+
469
+ def _hook_modelpath_attr(ctx: AttributeContext, attr_name: str) -> Type:
470
+ """Attribute hook for _ModelPath.* access.
471
+
472
+ Synthesizes a parametrized _ModelPath[NextModel, FieldType] so chained
473
+ .attr accesses fire this hook again with the advanced model class.
474
+ """
475
+ default = ctx.default_attr_type
476
+
477
+ mp_type = ctx.type
478
+ if mp_type is None or not isinstance(mp_type, Instance):
479
+ return default
480
+ if mp_type.type.fullname != _MODEL_PATH_FULLNAME:
481
+ return default
482
+ if len(mp_type.args) < 1:
483
+ return default
484
+
485
+ model_instance = get_proper_type(mp_type.args[0])
486
+ # Chain already collapsed upstream (e.g. ambiguous Union, previous error) — propagate Any.
487
+ # But if arg[1] (pending_type) is still a concrete type, model context was just lost at a
488
+ # leaf field (not yet errored): emit an error so runtime AttributeError is caught statically.
489
+ if isinstance(model_instance, AnyType):
490
+ if len(mp_type.args) >= 2:
491
+ pending_type = get_proper_type(mp_type.args[1])
492
+ if not isinstance(pending_type, AnyType):
493
+ ctx.api.fail(
494
+ f"cannot chain .{attr_name}: model type context was lost; "
495
+ "finalize with build() or ()",
496
+ ctx.context,
497
+ )
498
+ return _make_modelpath_any(mp_type.type)
499
+ if not isinstance(model_instance, Instance):
500
+ return default
501
+
502
+ # Peel RootModel wrappers down to the inner BaseModel.
503
+ # Use _get_rootmodel_inner_raw so that direct RootModel[T] (not just named
504
+ # subclasses) is handled correctly via inst.args[0].
505
+ for _ in range(_MAX_ROOTMODEL_PEEL_DEPTH):
506
+ if not _is_root_model(model_instance.type):
507
+ break
508
+ inner_raw: ProperType | None = _get_rootmodel_inner_raw(model_instance)
509
+ if inner_raw is None:
510
+ break
511
+ # Peel Optional[Inner] / Inner | None — mirrors _get_rootmodel_inner logic.
512
+ if isinstance(inner_raw, UnionType):
513
+ non_none = [
514
+ t
515
+ for t in inner_raw.items
516
+ if not isinstance(get_proper_type(t), NoneType)
517
+ ]
518
+ inner_raw = get_proper_type(non_none[0]) if len(non_none) == 1 else None
519
+ if not isinstance(inner_raw, Instance) or not _is_base_model(inner_raw.type):
520
+ break
521
+ model_instance = inner_raw
522
+
523
+ if _is_root_model(model_instance.type):
524
+ ctx.api.fail(
525
+ f"cannot chain .{attr_name} on '{model_instance.type.name}': "
526
+ "RootModel subclasses are traversed transparently; "
527
+ "use [index] to navigate into the wrapped container instead",
528
+ ctx.context,
529
+ )
530
+ return _make_modelpath_any(mp_type.type)
531
+
532
+ sym = model_instance.type.get(attr_name)
533
+ if sym is None or not isinstance(sym.node, Var) or sym.node.is_classvar:
534
+ ctx.api.fail(
535
+ f"'{model_instance.type.name}' has no field '{attr_name}'",
536
+ ctx.context,
537
+ )
538
+ # Collapse to Any so follow-on accesses don't emit spurious cascade errors
539
+ # against the now-invalid chain (runtime stops at the first bad access).
540
+ return _make_modelpath_any(mp_type.type)
541
+
542
+ field_type: Type | None = sym.node.type
543
+ if field_type is not None:
544
+ if model_instance.args:
545
+ field_type = expand_type_by_instance(field_type, model_instance)
546
+ else:
547
+ # Concrete subclass of a generic BaseModel (no own type args).
548
+ # Find the declaring class (where the field's TypeVar lives) and map
549
+ # model_instance to it to get the concrete substitution.
550
+ # Handles class AddressWrapper(Wrapper[Address]) where item: T in Wrapper.
551
+ declaring_info: TypeInfo | None = getattr(sym.node, "info", None)
552
+ if declaring_info is not None and declaring_info is not model_instance.type:
553
+ try:
554
+ mapped = map_instance_to_supertype(model_instance, declaring_info)
555
+ if mapped.args:
556
+ field_type = expand_type_by_instance(field_type, mapped)
557
+ except Exception:
558
+ pass
559
+ next_model = _advance_attr_mypy(field_type) if field_type is not None else None
560
+
561
+ if next_model is None:
562
+ # Leaf type or ambiguous Union — model context is lost after this step.
563
+ if field_type is not None and _is_ambiguous_basemodel_union(field_type):
564
+ ctx.api.fail(
565
+ f"field '{attr_name}' is an ambiguous BaseModel Union; "
566
+ "narrow via isinstance() and call pointer_from_model() on "
567
+ "the narrowed value for further static validation",
568
+ ctx.context,
569
+ )
570
+ return _make_modelpath_any(mp_type.type)
571
+ # Leaf field: set arg[0] to Any so subsequent .attr access propagates Any
572
+ # without validating against the parent model (false-negative prevention),
573
+ # but preserve field_type in arg[1] so __getitem__ can still reject
574
+ # indexing into a non-list leaf type (e.g. .name[0] on str field).
575
+ return Instance(
576
+ mp_type.type,
577
+ [
578
+ AnyType(TypeOfAny.implementation_artifact),
579
+ field_type
580
+ if field_type is not None
581
+ else AnyType(TypeOfAny.implementation_artifact),
582
+ ],
583
+ )
584
+
585
+ pending: Type = (
586
+ field_type
587
+ if field_type is not None
588
+ else AnyType(TypeOfAny.implementation_artifact)
589
+ )
590
+ return Instance(mp_type.type, [next_model, pending])
591
+
592
+
593
+ def _hook_getitem(ctx: MethodSigContext) -> Any:
594
+ """Hook for _ModelPath.__getitem__. Validates list-like context and
595
+ returns a signature whose ret_type carries the advanced item model so
596
+ subsequent .attr access fires _hook_modelpath_attr against it.
597
+ """
598
+ sig = ctx.default_signature
599
+
600
+ self_type = ctx.type
601
+ if self_type is None or not isinstance(self_type, Instance):
602
+ return sig
603
+ if self_type.type.fullname != _MODEL_PATH_FULLNAME:
604
+ return sig
605
+ if len(self_type.args) < 2:
606
+ return sig
607
+
608
+ model_instance = get_proper_type(self_type.args[0])
609
+ pending = get_proper_type(self_type.args[1])
610
+ # AnyType model_instance means .attr context was already lost (leaf field), but
611
+ # pending may carry a concrete type for indexability checking (.name[0] → error).
612
+ if not isinstance(model_instance, (Instance, AnyType)):
613
+ return sig
614
+
615
+ # RootModel entry without a recorded pending annotation: peel via args/MRO.
616
+ if isinstance(model_instance, Instance) and isinstance(pending, AnyType):
617
+ if _is_root_model(model_instance.type):
618
+ inner = _get_rootmodel_inner_raw(model_instance)
619
+ if inner is not None:
620
+ pending = inner
621
+
622
+ if isinstance(pending, AnyType):
623
+ if isinstance(model_instance, Instance):
624
+ # Concrete non-RootModel root with no pending container annotation:
625
+ # direct indexing is not valid at this position.
626
+ ctx.api.fail(
627
+ f"cannot index into '{model_instance.type.name}': "
628
+ "navigate to a list or tuple field first",
629
+ ctx.context,
630
+ )
631
+ return sig.copy_modified(ret_type=_make_modelpath_any(self_type.type))
632
+ # Context already lost (AnyType model); RFC 6901 token-form validation only.
633
+ _check_literal_index(ctx)
634
+ return sig
635
+
636
+ if isinstance(pending, NoneType):
637
+ # Hard context loss from a prior '-' dash step (NoneType sentinel set by
638
+ # the dash-list branch above). Further indexing cannot recover model context.
639
+ ctx.api.fail(
640
+ "cannot chain [index]: model type context was lost after a '-' token; "
641
+ "finalize with build() or ()",
642
+ ctx.context,
643
+ )
644
+ return sig.copy_modified(ret_type=_make_modelpath_any(self_type.type))
645
+
646
+ if not _check_literal_index(ctx):
647
+ return sig
648
+
649
+ # "-" is rejected by TupleAdapter at runtime for both tuple[T, ...] and
650
+ # tuple[A, B]; emit a hard error and lose model context so that subsequent
651
+ # [i] steps cannot "recover" into a specific model type. This mirrors
652
+ # _advance(..., index=None) → None in _model_path.py and prevents false
653
+ # positives like pair["-"][0].city type-checking when the chain fails at
654
+ # traversal time. Use _is_dash_index so named Literal["-"] variables are
655
+ # detected via type inference, not just inline StrExpr.
656
+ if _is_dash_index(ctx):
657
+ _pend = get_proper_type(pending)
658
+ if isinstance(_pend, Instance) and _is_root_model(_pend.type):
659
+ _inner = _get_rootmodel_inner_raw(_pend)
660
+ if _inner is not None:
661
+ _pend = get_proper_type(_inner)
662
+ # Peel Optional / single-branch union so Optional[tuple[A, B]] is
663
+ # recognised as a tuple for the dash-index diagnostic.
664
+ if isinstance(_pend, UnionType):
665
+ _non_none = [
666
+ t for t in _pend.items if not isinstance(get_proper_type(t), NoneType)
667
+ ]
668
+ if len(_non_none) == 1:
669
+ _pend = get_proper_type(_non_none[0])
670
+ # After peeling Optional, retry RootModel peel for
671
+ # Optional[RootModel[tuple[...]]] so the tuple-tail diagnostic fires.
672
+ if isinstance(_pend, Instance) and _is_root_model(_pend.type):
673
+ _inner_retry = _get_rootmodel_inner_raw(_pend)
674
+ if _inner_retry is not None:
675
+ _pend = _inner_retry
676
+ if (
677
+ isinstance(_pend, Instance) and _pend.type.fullname == "builtins.tuple"
678
+ ) or isinstance(_pend, TupleType):
679
+ ctx.api.fail(
680
+ "index '-' is not valid for tuple fields: "
681
+ "TupleAdapter rejects the tail-pointer token at traversal time; "
682
+ "use a non-negative integer index instead",
683
+ ctx.context,
684
+ )
685
+ return sig.copy_modified(ret_type=_make_modelpath_any(self_type.type))
686
+ # For list (and any other non-tuple) fields: "-" is valid as a terminal
687
+ # add-position token but must not allow further model-aware chaining.
688
+ # Store NoneType() as a sentinel in arg[1] so both the attr hook
689
+ # (items["-"].city) and the getitem hook (rows["-"][0]) can detect
690
+ # this hard context-loss state and emit "context was lost" errors.
691
+ # NoneType() is distinguishable from AnyType (which signals "fully lost")
692
+ # and from a real field type (which signals "leaf-field context loss").
693
+ return sig.copy_modified(
694
+ ret_type=Instance(
695
+ self_type.type,
696
+ [AnyType(TypeOfAny.implementation_artifact), NoneType()],
697
+ )
698
+ )
699
+
700
+ item_type = _advance_index_mypy(pending)
701
+ if item_type is None:
702
+ # Distinguish "not indexable" from "item is a non-BaseModel container".
703
+ # For nested containers like list[list[Item]], carry the item annotation
704
+ # forward so the next [0] can still validate against it.
705
+ raw_item = _raw_item_annotation_mypy(pending)
706
+ if raw_item is None:
707
+ # Peel RootModel wrappers to check the actual underlying container type.
708
+ # This handles fields like `wrapped: RootModel[tuple[A, B]]` and
709
+ # `wrapped: RootModel[list[A] | list[B]]` where the inner type is
710
+ # indexable at runtime but not reachable via _get_rootmodel_inner.
711
+ proper_pending = get_proper_type(pending)
712
+ if isinstance(proper_pending, Instance) and _is_root_model(
713
+ proper_pending.type
714
+ ):
715
+ inner_raw = _get_rootmodel_inner_raw(proper_pending)
716
+ if inner_raw is not None:
717
+ proper_pending = inner_raw
718
+ # Peel Optional / single-branch union so Optional[tuple[A, B]] reaches
719
+ # the TupleType branch below instead of falling through to _has_any_indexable_branch.
720
+ if isinstance(proper_pending, UnionType):
721
+ _non_none = [
722
+ t
723
+ for t in proper_pending.items
724
+ if not isinstance(get_proper_type(t), NoneType)
725
+ ]
726
+ if len(_non_none) == 1:
727
+ proper_pending = get_proper_type(_non_none[0])
728
+ # After peeling Optional, retry RootModel peel for
729
+ # Optional[RootModel[tuple[...]]] so the TupleType branch is reached.
730
+ if isinstance(proper_pending, Instance) and _is_root_model(
731
+ proper_pending.type
732
+ ):
733
+ _inner_opt_root = _get_rootmodel_inner_raw(proper_pending)
734
+ if _inner_opt_root is not None:
735
+ proper_pending = _inner_opt_root
736
+ if isinstance(proper_pending, TupleType):
737
+ # Try to advance to the element model using the literal index so
738
+ # that subsequent .attr access can be validated.
739
+ if ctx.args and ctx.args[0]:
740
+ arg_expr = ctx.args[0][0]
741
+ idx = _extract_int_index(arg_expr, ctx)
742
+ if idx is not None:
743
+ n = len(proper_pending.items)
744
+ if 0 <= idx < n:
745
+ proper_item: ProperType = get_proper_type(
746
+ proper_pending.items[idx]
747
+ )
748
+ # Peel Optional[BaseModel] -> BaseModel
749
+ if isinstance(proper_item, UnionType):
750
+ non_none_items = [
751
+ t
752
+ for t in proper_item.items
753
+ if not isinstance(get_proper_type(t), NoneType)
754
+ ]
755
+ if len(non_none_items) == 1:
756
+ proper_item = get_proper_type(non_none_items[0])
757
+ # Bare BaseModel -> advance model context
758
+ if isinstance(proper_item, Instance) and _is_base_model(
759
+ proper_item.type
760
+ ):
761
+ new_ret = Instance(
762
+ self_type.type,
763
+ [
764
+ proper_item,
765
+ AnyType(TypeOfAny.implementation_artifact),
766
+ ],
767
+ )
768
+ return sig.copy_modified(ret_type=new_ret)
769
+ # Container item (list[X], tuple[...]) -> carry
770
+ # forward as pending so the next [0] can resolve
771
+ if isinstance(
772
+ proper_item, Instance
773
+ ) and _is_indexed_container_type(proper_item.type):
774
+ new_ret = Instance(
775
+ self_type.type,
776
+ [model_instance, proper_item],
777
+ )
778
+ return sig.copy_modified(ret_type=new_ret)
779
+ # Fixed-length tuple element -> carry TupleType
780
+ # forward so the next [i] can still be validated
781
+ if isinstance(proper_item, TupleType):
782
+ new_ret = Instance(
783
+ self_type.type,
784
+ [model_instance, proper_item],
785
+ )
786
+ return sig.copy_modified(ret_type=new_ret)
787
+ # Leaf-type element: preserve proper_item as pending
788
+ # so the attr hook can emit a context-lost error on
789
+ # any subsequent .attr chain.
790
+ return sig.copy_modified(
791
+ ret_type=Instance(
792
+ self_type.type,
793
+ [
794
+ AnyType(TypeOfAny.implementation_artifact),
795
+ proper_item,
796
+ ],
797
+ )
798
+ )
799
+ else:
800
+ # Literal index is out of range for this fixed-length tuple.
801
+ ctx.api.fail(
802
+ f"tuple index {idx} is out of range "
803
+ f"(tuple has {n} element(s))",
804
+ ctx.context,
805
+ )
806
+ return sig.copy_modified(
807
+ ret_type=_make_modelpath_any(self_type.type)
808
+ )
809
+ return sig.copy_modified(ret_type=_make_modelpath_any(self_type.type))
810
+ if _has_any_indexable_branch(proper_pending):
811
+ return sig.copy_modified(
812
+ ret_type=Instance(
813
+ self_type.type,
814
+ [AnyType(TypeOfAny.implementation_artifact), proper_pending],
815
+ )
816
+ )
817
+ ctx.api.fail("index applied to non-list type", ctx.context)
818
+ return sig
819
+ new_ret = Instance(self_type.type, [model_instance, raw_item])
820
+ return sig.copy_modified(ret_type=new_ret)
821
+
822
+ new_ret = Instance(
823
+ self_type.type,
824
+ [item_type, AnyType(TypeOfAny.implementation_artifact)],
825
+ )
826
+ return sig.copy_modified(ret_type=new_ret)
827
+
828
+
829
+ class ModelPathPlugin(Plugin):
830
+ """Mypy plugin that validates _ModelPath field access at type-check time."""
831
+
832
+ def get_attribute_hook(
833
+ self, fullname: str
834
+ ) -> Callable[[AttributeContext], Type] | None:
835
+ if fullname.startswith(f"{_MODEL_PATH_FULLNAME}."):
836
+ attr_name = fullname[len(_MODEL_PATH_FULLNAME) + 1 :]
837
+ return lambda ctx: _hook_modelpath_attr(ctx, attr_name)
838
+ return None
839
+
840
+ def get_method_signature_hook(
841
+ self, fullname: str
842
+ ) -> Callable[[MethodSigContext], Any] | None:
843
+ if fullname == f"{_MODEL_PATH_FULLNAME}.__getitem__":
844
+ return _hook_getitem
845
+ return None
846
+
847
+
848
+ def plugin(version: str) -> type[Plugin]:
849
+ return ModelPathPlugin