Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/tomlkit/items.py: 60%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from __future__ import annotations
3import abc
4import copy
5import dataclasses
6import inspect
7import re
8import string
10from collections.abc import Collection
11from collections.abc import Iterable
12from collections.abc import Iterator
13from collections.abc import Sequence
14from datetime import date
15from datetime import datetime
16from datetime import time
17from datetime import timedelta
18from datetime import tzinfo
19from enum import Enum
20from typing import TYPE_CHECKING
21from typing import Any
22from typing import SupportsIndex
23from typing import TypeVar
24from typing import overload
26from tomlkit._compat import PY38
27from tomlkit._compat import decode
28from tomlkit._types import _CustomDict
29from tomlkit._types import _CustomFloat
30from tomlkit._types import _CustomInt
31from tomlkit._types import _CustomList
32from tomlkit._utils import CONTROL_CHARS
33from tomlkit._utils import escape_string
34from tomlkit._utils import validate_comment
35from tomlkit.exceptions import ConvertError
36from tomlkit.exceptions import InvalidStringError
39if TYPE_CHECKING:
40 from typing import Protocol
42 from tomlkit import container
43 from tomlkit.container import OutOfOrderTableProxy
45 class Encoder(Protocol):
46 def __call__(self, __value: Any, /) -> Item: ...
49ItemT = TypeVar("ItemT", bound="Item")
50CUSTOM_ENCODERS: list[Encoder] = []
51AT = TypeVar("AT", bound="AbstractTable")
54@overload
55def item(value: bool, _parent: Item | None = ..., _sort_keys: bool = ...) -> Bool: ... # type: ignore[overload-overlap]
58@overload
59def item(value: int, _parent: Item | None = ..., _sort_keys: bool = ...) -> Integer: ...
62@overload
63def item(value: float, _parent: Item | None = ..., _sort_keys: bool = ...) -> Float: ...
66@overload
67def item(value: str, _parent: Item | None = ..., _sort_keys: bool = ...) -> String: ...
70@overload
71def item( # type: ignore[overload-overlap]
72 value: datetime, _parent: Item | None = ..., _sort_keys: bool = ...
73) -> DateTime: ...
76@overload
77def item(value: date, _parent: Item | None = ..., _sort_keys: bool = ...) -> Date: ...
80@overload
81def item(value: time, _parent: Item | None = ..., _sort_keys: bool = ...) -> Time: ...
84@overload
85def item(
86 value: Sequence[dict[str, Any]], _parent: Item | None = ..., _sort_keys: bool = ...
87) -> AoT: ...
90@overload
91def item(
92 value: Sequence[Any], _parent: Item | None = ..., _sort_keys: bool = ...
93) -> Array: ...
96@overload
97def item(
98 value: dict[str, Any], _parent: Array = ..., _sort_keys: bool = ...
99) -> InlineTable: ...
102@overload
103def item(
104 value: dict[str, Any], _parent: Item | None = ..., _sort_keys: bool = ...
105) -> Table: ...
108@overload
109def item(value: ItemT, _parent: Item | None = ..., _sort_keys: bool = ...) -> ItemT: ...
112@overload
113def item(value: object, _parent: Item | None = ..., _sort_keys: bool = ...) -> Item: ...
116def item(value: Any, _parent: Item | None = None, _sort_keys: bool = False) -> Item:
117 """Create a TOML item from a Python object.
119 :Example:
121 >>> item(42)
122 42
123 >>> item([1, 2, 3])
124 [1, 2, 3]
125 >>> item({'a': 1, 'b': 2})
126 a = 1
127 b = 2
128 """
130 from tomlkit.container import Container
132 if isinstance(value, Item):
133 return value
135 if isinstance(value, bool):
136 return Bool(value, Trivia())
137 elif isinstance(value, int):
138 return Integer(value, Trivia(), str(value))
139 elif isinstance(value, float):
140 return Float(value, Trivia(), str(value))
141 elif isinstance(value, dict):
142 table_constructor = (
143 InlineTable if isinstance(_parent, (Array, InlineTable)) else Table
144 )
145 val = table_constructor(Container(), Trivia(), False)
146 for k, v in sorted(
147 value.items(),
148 key=lambda i: (isinstance(i[1], dict), i[0]) if _sort_keys else 1,
149 ):
150 val[k] = item(v, _parent=val, _sort_keys=_sort_keys)
152 return val
153 elif isinstance(value, (list, tuple)):
154 a: AoT | Array
155 if (
156 value
157 and all(isinstance(v, dict) for v in value)
158 and (_parent is None or isinstance(_parent, Table))
159 ):
160 a = AoT([])
161 table_constructor = Table
162 else:
163 a = Array([], Trivia())
164 table_constructor = InlineTable
166 if table_constructor is Table:
167 # AoT tables render as ``[[table]]`` headers, so dict-valued keys
168 # must come last to avoid them capturing the following keys.
169 def _sort_key(i: tuple[Any, Any]) -> Any:
170 return (isinstance(i[1], dict), i[0] if _sort_keys else 1)
171 else:
172 # Inline tables cannot capture, so there is no need to put
173 # dict-valued keys last: preserve insertion order, or sort purely
174 # by key when explicitly requested. See #546.
175 def _sort_key(i: tuple[Any, Any]) -> Any:
176 return i[0] if _sort_keys else 1
178 for v in value:
179 if isinstance(v, dict):
180 table = table_constructor(Container(), Trivia(), True)
182 for k, _v in sorted(v.items(), key=_sort_key):
183 i = item(_v, _parent=table, _sort_keys=_sort_keys)
184 if isinstance(table, InlineTable):
185 i.trivia.trail = ""
187 table[k] = i
189 v = table
191 a.append(v)
193 return a
194 elif isinstance(value, str):
195 return String.from_raw(value)
196 elif isinstance(value, datetime):
197 return DateTime(
198 value.year,
199 value.month,
200 value.day,
201 value.hour,
202 value.minute,
203 value.second,
204 value.microsecond,
205 value.tzinfo,
206 Trivia(),
207 _format_datetime(value).replace("+00:00", "Z"),
208 fold=value.fold,
209 )
210 elif isinstance(value, date):
211 return Date(value.year, value.month, value.day, Trivia(), value.isoformat())
212 elif isinstance(value, time):
213 return Time(
214 value.hour,
215 value.minute,
216 value.second,
217 value.microsecond,
218 value.tzinfo,
219 Trivia(),
220 _format_time(value),
221 fold=value.fold,
222 )
223 else:
224 for encoder in CUSTOM_ENCODERS:
225 try:
226 # Check if encoder accepts keyword arguments for backward compatibility
227 sig = inspect.signature(encoder)
228 has_kwargs = any(
229 p.kind == p.VAR_KEYWORD for p in sig.parameters.values()
230 )
231 first_parameter = next(iter(sig.parameters.values()), None)
232 bound_name = (
233 first_parameter.name
234 if first_parameter is not None
235 and first_parameter.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
236 else None
237 )
238 context = {"_parent": _parent, "_sort_keys": _sort_keys}
239 kwargs = {
240 name: argument
241 for name, argument in context.items()
242 if name != bound_name
243 and (
244 has_kwargs
245 or (
246 name in sig.parameters
247 and sig.parameters[name].kind
248 in (
249 inspect.Parameter.POSITIONAL_OR_KEYWORD,
250 inspect.Parameter.KEYWORD_ONLY,
251 )
252 )
253 )
254 }
255 rv = encoder(value, **kwargs)
256 except ConvertError:
257 pass
258 else:
259 if not isinstance(rv, Item):
260 raise ConvertError(
261 f"Custom encoder is expected to return an instance of Item, got {type(rv)}"
262 )
263 return rv
265 raise ConvertError(f"Unable to convert an object of {type(value)} to a TOML item")
268def _format_time(value: time) -> str:
269 # TOML local times carry no offset or timezone (the spec's examples
270 # are plain ``07:32:00``); keeping the offset in the rendered raw
271 # value would produce a literal this library's own parser rejects.
272 # Built from the fields (not ``isoformat``/``replace``) so it stays
273 # correct even when called on a ``Time`` from ``Time._new``.
274 s = f"{value.hour:02d}:{value.minute:02d}:{value.second:02d}"
275 if value.microsecond:
276 s += f".{value.microsecond:06d}".rstrip("0")
277 return s
280def _format_datetime(value: datetime) -> str:
281 # TOML offsets are ``HH:MM``, but ``isoformat`` adds seconds for an
282 # offset that is not a whole number of minutes (e.g. the LMT offsets
283 # ``zoneinfo`` gives for historical dates), which no TOML parser accepts.
284 # Such a value is written as the same instant in UTC. The conversion
285 # uses a plain ``datetime`` so it does not go back through ``_new``.
286 offset = value.utcoffset()
287 if offset is None or not offset % timedelta(minutes=1):
288 return value.isoformat()
289 utc = (
290 datetime(
291 value.year,
292 value.month,
293 value.day,
294 value.hour,
295 value.minute,
296 value.second,
297 value.microsecond,
298 )
299 - offset
300 )
301 return utc.isoformat() + "+00:00"
304# A carriage return that is not the CR of a CRLF line ending. Inside a multiline
305# string only a raw line feed or a CRLF pair is a valid line ending; a lone CR is
306# a control character that a basic string must escape.
307_BARE_CR = re.compile(r"\r(?!\n)")
309_BARE_KEY_CHARS = frozenset(string.ascii_letters + string.digits + "-_")
312class StringType(Enum):
313 # Single Line Basic
314 SLB = '"'
315 # Multi Line Basic
316 MLB = '"""'
317 # Single Line Literal
318 SLL = "'"
319 # Multi Line Literal
320 MLL = "'''"
322 @classmethod
323 def select(cls, literal: bool = False, multiline: bool = False) -> StringType:
324 return {
325 (False, False): cls.SLB,
326 (False, True): cls.MLB,
327 (True, False): cls.SLL,
328 (True, True): cls.MLL,
329 }[(literal, multiline)]
331 @property
332 def escaped_sequences(self) -> Collection[str]:
333 # https://toml.io/en/v1.0.0#string
334 return _ESCAPED_SEQUENCES[self]
336 @property
337 def invalid_sequences(self) -> Collection[str]:
338 # https://toml.io/en/v1.0.0#string
339 # CR stays forbidden in multiline: the value is checked with CRLF
340 # pairs collapsed, so any remaining CR is a lone control character
341 return _INVALID_SEQUENCES[self]
343 @property
344 def unit(self) -> str:
345 return self.value[0]
347 def is_basic(self) -> bool:
348 return self is StringType.SLB or self is StringType.MLB
350 def is_literal(self) -> bool:
351 return self is StringType.SLL or self is StringType.MLL
353 def is_singleline(self) -> bool:
354 return self is StringType.SLB or self is StringType.SLL
356 def is_multiline(self) -> bool:
357 return self is StringType.MLB or self is StringType.MLL
359 def toggle(self) -> StringType:
360 return {
361 StringType.SLB: StringType.MLB,
362 StringType.MLB: StringType.SLB,
363 StringType.SLL: StringType.MLL,
364 StringType.MLL: StringType.SLL,
365 }[self]
368_ESCAPED_IN_BASIC = CONTROL_CHARS | {"\\"}
369_FORBIDDEN_IN_LITERAL = CONTROL_CHARS - {"\t"}
370_ESCAPED_SEQUENCES: dict[StringType, Collection[str]] = {
371 StringType.SLB: _ESCAPED_IN_BASIC | {'"'},
372 # raw line breaks are allowed in multiline strings
373 StringType.MLB: (_ESCAPED_IN_BASIC | {'"""'}) - {"\n", "\r"},
374 StringType.SLL: (),
375 StringType.MLL: (),
376}
377_INVALID_SEQUENCES: dict[StringType, Collection[str]] = {
378 StringType.SLB: (),
379 StringType.MLB: (),
380 StringType.SLL: _FORBIDDEN_IN_LITERAL | {"'"},
381 StringType.MLL: (_FORBIDDEN_IN_LITERAL | {"'''"}) - {"\n"},
382}
385class BoolType(Enum):
386 TRUE = "true"
387 FALSE = "false"
389 def __bool__(self) -> bool:
390 return {BoolType.TRUE: True, BoolType.FALSE: False}[self]
392 def __iter__(self) -> Iterator[str]:
393 return iter(self.value)
395 def __len__(self) -> int:
396 return len(self.value)
399@dataclasses.dataclass
400class Trivia:
401 """
402 Trivia information (aka metadata).
403 """
405 # Whitespace before a value.
406 indent: str = ""
407 # Whitespace after a value, but before a comment.
408 comment_ws: str = ""
409 # Comment, starting with # character, or empty string if no comment.
410 comment: str = ""
411 # Trailing newline.
412 trail: str = "\n"
414 def copy(self) -> Trivia:
415 return dataclasses.replace(self)
418class KeyType(Enum):
419 """
420 The type of a Key.
422 Keys can be bare (unquoted), or quoted using basic ("), or literal (')
423 quotes following the same escaping rules as single-line StringType.
424 """
426 Bare = ""
427 Basic = '"'
428 Literal = "'"
431class Key(abc.ABC):
432 """Base class for a key"""
434 sep: str
435 _original: str
436 _keys: list[SingleKey]
437 _dotted: bool
438 key: str
440 @abc.abstractmethod
441 def __hash__(self) -> int:
442 pass
444 @abc.abstractmethod
445 def __eq__(self, __o: object) -> bool:
446 pass
448 def is_dotted(self) -> bool:
449 """If the key is followed by other keys"""
450 return self._dotted
452 def __iter__(self) -> Iterator[SingleKey]:
453 return iter(self._keys)
455 def concat(self, other: Key) -> DottedKey:
456 """Concatenate keys into a dotted key"""
457 keys = self._keys + other._keys
458 return DottedKey(keys, sep=self.sep)
460 def is_multi(self) -> bool:
461 """Check if the key contains multiple keys"""
462 return len(self._keys) > 1
464 def as_string(self) -> str:
465 """The TOML representation"""
466 return self._original
468 def __str__(self) -> str:
469 return self.as_string()
471 def __repr__(self) -> str:
472 return f"<Key {self.as_string()}>"
475class SingleKey(Key):
476 """A single key"""
478 def __init__(
479 self,
480 k: str,
481 t: KeyType | None = None,
482 sep: str | None = None,
483 original: str | None = None,
484 ) -> None:
485 if not isinstance(k, str):
486 raise TypeError("Keys must be strings")
488 if t is None:
489 if not k or not _BARE_KEY_CHARS.issuperset(k):
490 t = KeyType.Basic
491 else:
492 t = KeyType.Bare
494 self.t = t
495 if sep is None:
496 sep = " = "
498 self.sep = sep
499 self.key = k
500 if original is None:
501 key_str = escape_string(k) if t == KeyType.Basic else k
502 original = f"{t.value}{key_str}{t.value}"
504 self._original = original
505 self._keys = [self]
506 self._dotted = False
508 @property
509 def delimiter(self) -> str:
510 """The delimiter: double quote/single quote/none"""
511 return self.t.value
513 def is_bare(self) -> bool:
514 """Check if the key is bare"""
515 return self.t == KeyType.Bare
517 def __hash__(self) -> int:
518 return hash(self.key)
520 def __eq__(self, other: Any) -> bool:
521 if isinstance(other, Key):
522 return isinstance(other, SingleKey) and self.key == other.key
524 return bool(self.key == other)
527class DottedKey(Key):
528 def __init__(
529 self,
530 keys: Iterable[SingleKey],
531 sep: str | None = None,
532 original: str | None = None,
533 ) -> None:
534 self._keys = list(keys)
535 if original is None:
536 original = ".".join(k.as_string() for k in self._keys)
538 self.sep = " = " if sep is None else sep
539 self._original = original
540 self._dotted = False
541 self.key = ".".join(k.key for k in self._keys)
543 def __hash__(self) -> int:
544 return hash(tuple(self._keys))
546 def __eq__(self, __o: object) -> bool:
547 return isinstance(__o, DottedKey) and self._keys == __o._keys
550class Item:
551 """
552 An item within a TOML document.
553 """
555 def __init__(self, trivia: Trivia) -> None:
556 self._trivia = trivia
558 @property
559 def trivia(self) -> Trivia:
560 """The trivia element associated with this item"""
561 return self._trivia
563 @property
564 def discriminant(self) -> int:
565 raise NotImplementedError()
567 def as_string(self) -> str:
568 """The TOML representation"""
569 raise NotImplementedError()
571 @property
572 def value(self) -> Any:
573 return self
575 def unwrap(self) -> Any:
576 """Returns as pure python object (ppo)"""
577 raise NotImplementedError()
579 # Helpers
581 def comment(self, comment: str) -> Item:
582 """Attach a comment to this item"""
583 validate_comment(comment)
584 if not comment.strip().startswith("#"):
585 comment = "# " + comment
587 self._trivia.comment_ws = " "
588 self._trivia.comment = comment
590 return self
592 def indent(self, indent: int) -> Item:
593 """Indent this item with given number of spaces"""
594 if self._trivia.indent.startswith("\n"):
595 self._trivia.indent = "\n" + " " * indent
596 else:
597 self._trivia.indent = " " * indent
599 return self
601 def is_boolean(self) -> bool:
602 return isinstance(self, Bool)
604 def is_table(self) -> bool:
605 return isinstance(self, Table)
607 def is_inline_table(self) -> bool:
608 return isinstance(self, InlineTable)
610 def is_aot(self) -> bool:
611 return isinstance(self, AoT)
613 def _getstate(self, protocol: int = 3) -> tuple[object, ...]:
614 return (self._trivia,)
616 def __reduce__(self) -> tuple[type, tuple[object, ...]]:
617 return self.__reduce_ex__(2)
619 def __reduce_ex__(self, protocol: int) -> tuple[type, tuple[object, ...]]: # type: ignore[override]
620 return self.__class__, self._getstate(protocol)
623class Whitespace(Item):
624 """
625 A whitespace literal.
626 """
628 def __init__(self, s: str, fixed: bool = False) -> None:
629 self._s = s
630 self._fixed = fixed
632 @property
633 def s(self) -> str:
634 return self._s
636 @property
637 def value(self) -> str:
638 """The wrapped string of the whitespace"""
639 return self._s
641 @property
642 def trivia(self) -> Trivia:
643 raise RuntimeError("Called trivia on a Whitespace variant.")
645 @property
646 def discriminant(self) -> int:
647 return 0
649 def is_fixed(self) -> bool:
650 """If the whitespace is fixed, it can't be merged or discarded from the output."""
651 return self._fixed
653 def as_string(self) -> str:
654 return self._s
656 def __repr__(self) -> str:
657 return f"<{self.__class__.__name__} {self._s!r}>"
659 def _getstate(self, protocol: int = 3) -> tuple[str, bool]:
660 return self._s, self._fixed
663class Comment(Item):
664 """
665 A comment literal.
666 """
668 @property
669 def discriminant(self) -> int:
670 return 1
672 def as_string(self) -> str:
673 return (
674 f"{self._trivia.indent}{decode(self._trivia.comment)}{self._trivia.trail}"
675 )
677 def __str__(self) -> str:
678 return f"{self._trivia.indent}{decode(self._trivia.comment)}"
681class Integer(Item, _CustomInt):
682 """
683 An integer literal.
684 """
686 def __new__(cls, value: int, trivia: Trivia, raw: str) -> Integer:
687 return int.__new__(cls, value)
689 def __init__(self, value: int, trivia: Trivia, raw: str) -> None:
690 super().__init__(trivia)
691 self._original = value
692 self._raw = raw
693 self._sign = False
695 if re.match(r"^[+\-]\d+$", raw):
696 self._sign = True
698 def unwrap(self) -> int:
699 return self._original
701 __int__ = unwrap
703 def __hash__(self) -> int:
704 return hash(self.unwrap())
706 @property
707 def discriminant(self) -> int:
708 return 2
710 @property
711 def value(self) -> int:
712 """The wrapped integer value"""
713 return self
715 def as_string(self) -> str:
716 return self._raw
718 def _new(self, result: int) -> Integer:
719 raw = str(result)
720 if self._sign and result >= 0:
721 raw = f"+{raw}"
723 return Integer(result, self._trivia.copy(), raw)
725 def _getstate(self, protocol: int = 3) -> tuple[int, Trivia, str]:
726 return int(self), self._trivia, self._raw
728 # int methods — explicit typed wrappers
729 def __abs__(self) -> Integer:
730 return self._new(int.__abs__(self))
732 def __add__(self, other: object) -> Integer:
733 result = int.__add__(self, other) # type: ignore[operator]
734 if result is NotImplemented:
735 return result # type: ignore[return-value]
736 return self._new(result)
738 def __and__(self, other: object) -> Integer:
739 result = int.__and__(self, other) # type: ignore[operator]
740 if result is NotImplemented:
741 return result # type: ignore[return-value]
742 return self._new(result)
744 def __ceil__(self) -> Integer:
745 return self._new(int.__ceil__(self))
747 __eq__ = int.__eq__
749 def __floor__(self) -> Integer:
750 return self._new(int.__floor__(self))
752 def __floordiv__(self, other: object) -> Integer:
753 result = int.__floordiv__(self, other) # type: ignore[operator]
754 if result is NotImplemented:
755 return result # type: ignore[return-value]
756 return self._new(result)
758 def __invert__(self) -> Integer:
759 return self._new(int.__invert__(self))
761 __le__ = int.__le__
763 def __lshift__(self, other: object) -> Integer:
764 result = int.__lshift__(self, other) # type: ignore[operator]
765 if result is NotImplemented:
766 return result # type: ignore[return-value]
767 return self._new(result)
769 __lt__ = int.__lt__
771 def __mod__(self, other: object) -> Integer:
772 result = int.__mod__(self, other) # type: ignore[operator]
773 if result is NotImplemented:
774 return result # type: ignore[return-value]
775 return self._new(result)
777 def __mul__(self, other: object) -> Integer:
778 result = int.__mul__(self, other) # type: ignore[operator]
779 if result is NotImplemented:
780 return result # type: ignore[return-value]
781 return self._new(result)
783 def __neg__(self) -> Integer:
784 return self._new(int.__neg__(self))
786 def __or__(self, other: object) -> Integer:
787 result = int.__or__(self, other) # type: ignore[operator]
788 if result is NotImplemented:
789 return result # type: ignore[return-value]
790 return self._new(result)
792 def __pos__(self) -> Integer:
793 return self._new(int.__pos__(self))
795 def __pow__(self, other: int, mod: int | None = None) -> Integer: # type: ignore[override]
796 result = (
797 int.__pow__(self, other) if mod is None else int.__pow__(self, other, mod)
798 )
799 return self._new(result)
801 def __radd__(self, other: object) -> Integer:
802 result = int.__radd__(self, other) # type: ignore[operator]
803 if result is NotImplemented:
804 return result # type: ignore[return-value]
805 return self._new(result)
807 def __rand__(self, other: object) -> Integer:
808 result = int.__rand__(self, other) # type: ignore[operator]
809 if result is NotImplemented:
810 return result # type: ignore[return-value]
811 return self._new(result)
813 def __rfloordiv__(self, other: object) -> Integer:
814 result = int.__rfloordiv__(self, other) # type: ignore[operator]
815 if result is NotImplemented:
816 return result # type: ignore[return-value]
817 return self._new(result)
819 def __rlshift__(self, other: object) -> Integer:
820 result = int.__rlshift__(self, other) # type: ignore[operator]
821 if result is NotImplemented:
822 return result # type: ignore[return-value]
823 return self._new(result)
825 def __rmod__(self, other: object) -> Integer:
826 result = int.__rmod__(self, other) # type: ignore[operator]
827 if result is NotImplemented:
828 return result # type: ignore[return-value]
829 return self._new(result)
831 def __rmul__(self, other: object) -> Integer:
832 result = int.__rmul__(self, other) # type: ignore[operator]
833 if result is NotImplemented:
834 return result # type: ignore[return-value]
835 return self._new(result)
837 def __ror__(self, other: object) -> Integer:
838 result = int.__ror__(self, other) # type: ignore[operator]
839 if result is NotImplemented:
840 return result # type: ignore[return-value]
841 return self._new(result)
843 def __round__(self, ndigits: int = 0) -> Integer: # type: ignore[override]
844 return self._new(int.__round__(self, ndigits))
846 def __rpow__(self, other: int, mod: int | None = None) -> Integer: # type: ignore[misc]
847 result = (
848 int.__rpow__(self, other) if mod is None else int.__rpow__(self, other, mod)
849 )
850 return self._new(result)
852 def __rrshift__(self, other: object) -> Integer:
853 result = int.__rrshift__(self, other) # type: ignore[operator]
854 if result is NotImplemented:
855 return result # type: ignore[return-value]
856 return self._new(result)
858 def __rshift__(self, other: object) -> Integer:
859 result = int.__rshift__(self, other) # type: ignore[operator]
860 if result is NotImplemented:
861 return result # type: ignore[return-value]
862 return self._new(result)
864 def __rxor__(self, other: object) -> Integer:
865 result = int.__rxor__(self, other) # type: ignore[operator]
866 if result is NotImplemented:
867 return result # type: ignore[return-value]
868 return self._new(result)
870 def __sub__(self, other: object) -> Integer:
871 result = int.__sub__(self, other) # type: ignore[operator]
872 if result is NotImplemented:
873 return result # type: ignore[return-value]
874 return self._new(result)
876 def __rsub__(self, other: object) -> Integer:
877 result = int.__rsub__(self, other) # type: ignore[operator]
878 if result is NotImplemented:
879 return result # type: ignore[return-value]
880 return self._new(result)
882 def __trunc__(self) -> Integer:
883 return self._new(int.__trunc__(self))
885 def __xor__(self, other: object) -> Integer:
886 result = int.__xor__(self, other) # type: ignore[operator]
887 if result is NotImplemented:
888 return result # type: ignore[return-value]
889 return self._new(result)
891 def __rtruediv__(self, other: object) -> Float:
892 result = int.__rtruediv__(self, other) # type: ignore[operator]
893 if result is NotImplemented:
894 return result # type: ignore[return-value]
895 return Float._new(self, result) # type: ignore[arg-type]
897 def __truediv__(self, other: object) -> Float:
898 result = int.__truediv__(self, other) # type: ignore[operator]
899 if result is NotImplemented:
900 return result # type: ignore[return-value]
901 return Float._new(self, result) # type: ignore[arg-type]
904class Float(Item, _CustomFloat):
905 """
906 A float literal.
907 """
909 def __new__(cls, value: float, trivia: Trivia, raw: str) -> Float:
910 return float.__new__(cls, value)
912 def __init__(self, value: float, trivia: Trivia, raw: str) -> None:
913 super().__init__(trivia)
914 self._original = value
915 self._raw = raw
916 self._sign = False
918 if re.match(r"^[+\-].+$", raw):
919 self._sign = True
921 def unwrap(self) -> float:
922 return self._original
924 __float__ = unwrap
926 def __hash__(self) -> int:
927 return hash(self.unwrap())
929 @property
930 def discriminant(self) -> int:
931 return 3
933 @property
934 def value(self) -> float:
935 """The wrapped float value"""
936 return self
938 def as_string(self) -> str:
939 return self._raw
941 def _new(self, result: float) -> Float:
942 raw = str(result)
944 # -0.0 >= 0 is True, but str(-0.0) already carries its sign.
945 if self._sign and result >= 0 and not raw.startswith("-"):
946 raw = f"+{raw}"
948 return Float(result, self._trivia.copy(), raw)
950 def _getstate(self, protocol: int = 3) -> tuple[float, Trivia, str]:
951 return float(self), self._trivia, self._raw
953 # float methods — explicit typed wrappers
954 def __abs__(self) -> Float:
955 return self._new(float.__abs__(self))
957 def __add__(self, other: object) -> Float:
958 result = float.__add__(self, other) # type: ignore[operator]
959 if result is NotImplemented:
960 return result # type: ignore[return-value]
961 return self._new(result)
963 __eq__ = float.__eq__
965 def __floordiv__(self, other: object) -> Float:
966 result = float.__floordiv__(self, other) # type: ignore[operator]
967 if result is NotImplemented:
968 return result # type: ignore[return-value]
969 return self._new(result)
971 __le__ = float.__le__
972 __lt__ = float.__lt__
974 def __mod__(self, other: object) -> Float:
975 result = float.__mod__(self, other) # type: ignore[operator]
976 if result is NotImplemented:
977 return result # type: ignore[return-value]
978 return self._new(result)
980 def __mul__(self, other: object) -> Float:
981 result = float.__mul__(self, other) # type: ignore[operator]
982 if result is NotImplemented:
983 return result # type: ignore[return-value]
984 return self._new(result)
986 def __neg__(self) -> Float:
987 return self._new(float.__neg__(self))
989 def __pos__(self) -> Float:
990 return self._new(float.__pos__(self))
992 def __pow__(self, other: object, mod: None = None) -> Float:
993 result = float.__pow__(self, other) # type: ignore[operator]
994 if result is NotImplemented:
995 return result # type: ignore[no-any-return]
996 return self._new(result)
998 def __radd__(self, other: object) -> Float:
999 result = float.__radd__(self, other) # type: ignore[operator]
1000 if result is NotImplemented:
1001 return result # type: ignore[return-value]
1002 return self._new(result)
1004 def __rfloordiv__(self, other: object) -> Float:
1005 result = float.__rfloordiv__(self, other) # type: ignore[operator]
1006 if result is NotImplemented:
1007 return result # type: ignore[return-value]
1008 return self._new(result)
1010 def __rmod__(self, other: object) -> Float:
1011 result = float.__rmod__(self, other) # type: ignore[operator]
1012 if result is NotImplemented:
1013 return result # type: ignore[return-value]
1014 return self._new(result)
1016 def __rmul__(self, other: object) -> Float:
1017 result = float.__rmul__(self, other) # type: ignore[operator]
1018 if result is NotImplemented:
1019 return result # type: ignore[return-value]
1020 return self._new(result)
1022 @overload
1023 def __round__(self, ndigits: None = None) -> Integer: ...
1025 @overload
1026 def __round__(self, ndigits: SupportsIndex) -> Float: ...
1028 def __round__(self, ndigits: SupportsIndex | None = None) -> Integer | Float:
1029 if ndigits is None:
1030 return Integer._new(self, float.__round__(self)) # type: ignore[arg-type]
1031 return self._new(float.__round__(self, ndigits))
1033 def __rpow__(self, other: object, mod: None = None) -> Float:
1034 result = float.__rpow__(self, other) # type: ignore[operator]
1035 if result is NotImplemented:
1036 return result # type: ignore[no-any-return]
1037 return self._new(result)
1039 def __rtruediv__(self, other: object) -> Float:
1040 result = float.__rtruediv__(self, other) # type: ignore[operator]
1041 if result is NotImplemented:
1042 return result # type: ignore[return-value]
1043 return self._new(result)
1045 def __truediv__(self, other: object) -> Float:
1046 result = float.__truediv__(self, other) # type: ignore[operator]
1047 if result is NotImplemented:
1048 return result # type: ignore[return-value]
1049 return self._new(result)
1051 def __sub__(self, other: object) -> Float:
1052 result = float.__sub__(self, other) # type: ignore[operator]
1053 if result is NotImplemented:
1054 return result # type: ignore[return-value]
1055 return self._new(result)
1057 def __rsub__(self, other: object) -> Float:
1058 result = float.__rsub__(self, other) # type: ignore[operator]
1059 if result is NotImplemented:
1060 return result # type: ignore[return-value]
1061 return self._new(result)
1063 __trunc__ = float.__trunc__
1064 __ceil__ = float.__ceil__
1065 __floor__ = float.__floor__
1068class Bool(Item):
1069 """
1070 A boolean literal.
1071 """
1073 def __init__(self, t: int | BoolType, trivia: Trivia) -> None:
1074 super().__init__(trivia)
1076 self._value = bool(t)
1078 def unwrap(self) -> bool:
1079 return bool(self)
1081 @property
1082 def discriminant(self) -> int:
1083 return 4
1085 @property
1086 def value(self) -> bool:
1087 """The wrapped boolean value"""
1088 return self._value
1090 def as_string(self) -> str:
1091 return str(self._value).lower()
1093 def _getstate(self, protocol: int = 3) -> tuple[bool, Trivia]:
1094 return self._value, self._trivia
1096 def __bool__(self) -> bool:
1097 return self._value
1099 __nonzero__ = __bool__
1101 def __eq__(self, other: object) -> bool:
1102 if isinstance(other, Bool):
1103 other = other.value
1105 if not isinstance(other, bool):
1106 return NotImplemented
1108 return other == self._value
1110 def __hash__(self) -> int:
1111 return hash(self._value)
1113 def __repr__(self) -> str:
1114 return repr(self._value)
1117class DateTime(Item, datetime):
1118 """
1119 A datetime literal.
1120 """
1122 def __new__(
1123 cls,
1124 year: int,
1125 month: int,
1126 day: int,
1127 hour: int,
1128 minute: int,
1129 second: int,
1130 microsecond: int,
1131 tzinfo: tzinfo | None,
1132 trivia: Trivia | None = None,
1133 raw: str | None = None,
1134 fold: int = 0,
1135 **kwargs: object,
1136 ) -> DateTime:
1137 return datetime.__new__(
1138 cls,
1139 year,
1140 month,
1141 day,
1142 hour,
1143 minute,
1144 second,
1145 microsecond,
1146 tzinfo=tzinfo,
1147 fold=fold,
1148 )
1150 def __init__(
1151 self,
1152 year: int,
1153 month: int,
1154 day: int,
1155 hour: int,
1156 minute: int,
1157 second: int,
1158 microsecond: int,
1159 tzinfo: tzinfo | None,
1160 trivia: Trivia | None = None,
1161 raw: str | None = None,
1162 fold: int = 0,
1163 **kwargs: object,
1164 ) -> None:
1165 super().__init__(trivia or Trivia())
1167 self._raw = raw or _format_datetime(self)
1169 def unwrap(self) -> datetime:
1170 (
1171 year,
1172 month,
1173 day,
1174 hour,
1175 minute,
1176 second,
1177 microsecond,
1178 tzinfo,
1179 _,
1180 _,
1181 ) = self._getstate()
1182 return datetime(
1183 year, month, day, hour, minute, second, microsecond, tzinfo, fold=self.fold
1184 )
1186 @property
1187 def discriminant(self) -> int:
1188 return 5
1190 @property
1191 def value(self) -> datetime:
1192 return self
1194 def as_string(self) -> str:
1195 return self._raw
1197 def __add__(self, other: timedelta) -> DateTime:
1198 if PY38:
1199 result = datetime(
1200 self.year,
1201 self.month,
1202 self.day,
1203 self.hour,
1204 self.minute,
1205 self.second,
1206 self.microsecond,
1207 self.tzinfo,
1208 ).__add__(other)
1209 else:
1210 result = super().__add__(other)
1212 return self._new(result)
1214 @overload # type: ignore[override]
1215 def __sub__(self, other: timedelta) -> DateTime: ...
1217 @overload
1218 def __sub__(self, other: datetime) -> timedelta: ...
1220 def __sub__(self, other: timedelta | datetime) -> DateTime | timedelta:
1221 if PY38:
1222 result = datetime(
1223 self.year,
1224 self.month,
1225 self.day,
1226 self.hour,
1227 self.minute,
1228 self.second,
1229 self.microsecond,
1230 self.tzinfo,
1231 fold=self.fold,
1232 ).__sub__(other)
1233 else:
1234 result = super().__sub__(other) # type: ignore[operator]
1236 if isinstance(result, datetime):
1237 result = self._new(result)
1239 return result
1241 def replace(self, *args: object, **kwargs: object) -> DateTime:
1242 return self._new(super().replace(*args, **kwargs)) # type: ignore[arg-type]
1244 def astimezone(self, tz: tzinfo | None = None) -> DateTime:
1245 result = super().astimezone(tz)
1246 if PY38:
1247 return result
1248 return self._new(result)
1250 def _new(self, result: datetime) -> DateTime:
1251 raw = _format_datetime(result)
1253 return DateTime(
1254 result.year,
1255 result.month,
1256 result.day,
1257 result.hour,
1258 result.minute,
1259 result.second,
1260 result.microsecond,
1261 result.tzinfo,
1262 self._trivia.copy(),
1263 raw,
1264 fold=result.fold,
1265 )
1267 def _getstate(
1268 self, protocol: int = 3
1269 ) -> tuple[int, int, int, int, int, int, int, tzinfo | None, Trivia, str]:
1270 return (
1271 self.year,
1272 self.month,
1273 self.day,
1274 self.hour,
1275 self.minute,
1276 self.second,
1277 self.microsecond,
1278 self.tzinfo,
1279 self._trivia,
1280 self._raw,
1281 )
1284class Date(Item, date):
1285 """
1286 A date literal.
1287 """
1289 def __new__(
1290 cls,
1291 year: int,
1292 month: int,
1293 day: int,
1294 trivia: Trivia | None = None,
1295 raw: str = "",
1296 ) -> Date:
1297 return date.__new__(cls, year, month, day)
1299 def __init__(
1300 self,
1301 year: int,
1302 month: int,
1303 day: int,
1304 trivia: Trivia | None = None,
1305 raw: str = "",
1306 ) -> None:
1307 super().__init__(trivia or Trivia())
1309 self._raw = raw
1311 def unwrap(self) -> date:
1312 (year, month, day, _, _) = self._getstate()
1313 return date(year, month, day)
1315 @property
1316 def discriminant(self) -> int:
1317 return 6
1319 @property
1320 def value(self) -> date:
1321 return self
1323 def as_string(self) -> str:
1324 return self._raw
1326 def __add__(self, other: timedelta) -> Date:
1327 if PY38:
1328 result = date(self.year, self.month, self.day).__add__(other)
1329 else:
1330 result = super().__add__(other)
1332 return self._new(result)
1334 @overload # type: ignore[override]
1335 def __sub__(self, other: timedelta) -> Date: ...
1337 @overload
1338 def __sub__(self, other: date) -> timedelta: ...
1340 def __sub__(self, other: timedelta | date) -> Date | timedelta:
1341 if PY38:
1342 result = date(self.year, self.month, self.day).__sub__(other)
1343 else:
1344 result = super().__sub__(other) # type: ignore[operator]
1346 if isinstance(result, date):
1347 result = self._new(result)
1349 return result
1351 def replace(self, *args: object, **kwargs: object) -> Date:
1352 return self._new(super().replace(*args, **kwargs)) # type: ignore[arg-type]
1354 def _new(self, result: date) -> Date:
1355 raw = result.isoformat()
1357 return Date(result.year, result.month, result.day, self._trivia.copy(), raw)
1359 def _getstate(self, protocol: int = 3) -> tuple[int, int, int, Trivia, str]:
1360 return (self.year, self.month, self.day, self._trivia, self._raw)
1363class Time(Item, time):
1364 """
1365 A time literal.
1366 """
1368 def __new__(
1369 cls,
1370 hour: int,
1371 minute: int,
1372 second: int,
1373 microsecond: int,
1374 tzinfo: tzinfo | None,
1375 trivia: Trivia | None = None,
1376 raw: str = "",
1377 fold: int = 0,
1378 ) -> Time:
1379 return time.__new__(cls, hour, minute, second, microsecond, tzinfo, fold=fold)
1381 def __init__(
1382 self,
1383 hour: int,
1384 minute: int,
1385 second: int,
1386 microsecond: int,
1387 tzinfo: tzinfo | None,
1388 trivia: Trivia | None = None,
1389 raw: str = "",
1390 fold: int = 0,
1391 ) -> None:
1392 super().__init__(trivia or Trivia())
1394 self._raw = raw
1396 def unwrap(self) -> time:
1397 (hour, minute, second, microsecond, tzinfo, _, _) = self._getstate()
1398 return time(hour, minute, second, microsecond, tzinfo, fold=self.fold)
1400 @property
1401 def discriminant(self) -> int:
1402 return 7
1404 @property
1405 def value(self) -> time:
1406 return self
1408 def as_string(self) -> str:
1409 return self._raw
1411 def replace(self, *args: object, **kwargs: object) -> Time:
1412 return self._new(super().replace(*args, **kwargs)) # type: ignore[arg-type]
1414 def _new(self, result: time) -> Time:
1415 raw = _format_time(result)
1417 return Time(
1418 result.hour,
1419 result.minute,
1420 result.second,
1421 result.microsecond,
1422 result.tzinfo,
1423 self._trivia.copy(),
1424 raw,
1425 fold=result.fold,
1426 )
1428 def _getstate(
1429 self, protocol: int = 3
1430 ) -> tuple[int, int, int, int, tzinfo | None, Trivia, str]:
1431 return (
1432 self.hour,
1433 self.minute,
1434 self.second,
1435 self.microsecond,
1436 self.tzinfo,
1437 self._trivia,
1438 self._raw,
1439 )
1442class _ArrayItemGroup:
1443 __slots__ = ("comma", "comment", "indent", "value")
1445 def __init__(
1446 self,
1447 value: Item | None = None,
1448 indent: Whitespace | None = None,
1449 comma: Whitespace | None = None,
1450 comment: Comment | None = None,
1451 ) -> None:
1452 self.value = value
1453 self.indent = indent
1454 self.comma = comma
1455 self.comment = comment
1457 def __iter__(self) -> Iterator[Item]:
1458 return (
1459 x
1460 for x in (self.indent, self.value, self.comma, self.comment)
1461 if x is not None
1462 )
1464 def __repr__(self) -> str:
1465 return repr(tuple(self))
1467 def is_whitespace(self) -> bool:
1468 return self.value is None and self.comment is None
1470 def __bool__(self) -> bool:
1471 try:
1472 next(iter(self))
1473 except StopIteration:
1474 return False
1475 return True
1478class Array(Item, _CustomList): # type: ignore[type-arg]
1479 """
1480 An array literal
1481 """
1483 def __init__(
1484 self, value: list[Item], trivia: Trivia, multiline: bool = False
1485 ) -> None:
1486 super().__init__(trivia)
1487 list.__init__(
1488 self,
1489 [v for v in value if not isinstance(v, (Whitespace, Comment, Null))],
1490 )
1491 self._index_map: dict[int, int] = {}
1492 self._value = self._group_values(value)
1493 self._multiline = multiline
1494 self._reindex()
1496 def _group_values(self, value: list[Item]) -> list[_ArrayItemGroup]:
1497 """Group the values into (indent, value, comma, comment) tuples"""
1498 groups = []
1499 this_group = _ArrayItemGroup()
1500 start_new_group = False
1501 for item in value:
1502 if isinstance(item, Whitespace):
1503 if "," not in item.s or start_new_group:
1504 groups.append(this_group)
1505 this_group = _ArrayItemGroup(indent=item)
1506 start_new_group = False
1507 else:
1508 if this_group.value is None:
1509 # when comma is met and no value is provided, add a dummy Null
1510 this_group.value = Null()
1511 this_group.comma = item
1512 elif isinstance(item, Comment):
1513 if this_group.value is None:
1514 this_group.value = Null()
1515 this_group.comment = item
1516 # Comments are the last item in a group.
1517 start_new_group = True
1518 elif this_group.value is None:
1519 this_group.value = item
1520 else:
1521 groups.append(this_group)
1522 this_group = _ArrayItemGroup(value=item)
1523 groups.append(this_group)
1524 return [group for group in groups if group]
1526 def unwrap(self) -> list[Any]:
1527 unwrapped = []
1528 for v in self:
1529 if hasattr(v, "unwrap"):
1530 unwrapped.append(v.unwrap())
1531 else:
1532 unwrapped.append(v)
1533 return unwrapped
1535 @property
1536 def discriminant(self) -> int:
1537 return 8
1539 @property
1540 def value(self) -> list[Item]:
1541 return self
1543 def _iter_items(self) -> Iterator[Item]:
1544 for v in self._value:
1545 yield from v
1547 def multiline(self, multiline: bool) -> Array:
1548 """Change the array to display in multiline or not.
1550 :Example:
1552 >>> a = item([1, 2, 3])
1553 >>> print(a.as_string())
1554 [1, 2, 3]
1555 >>> print(a.multiline(True).as_string())
1556 [
1557 1,
1558 2,
1559 3,
1560 ]
1561 """
1562 self._multiline = multiline
1564 return self
1566 def as_string(self) -> str:
1567 if not self._multiline or not self._value:
1568 rendered = list(self._iter_items())
1569 inner = "".join(v.as_string() for v in rendered)
1570 if rendered and isinstance(rendered[-1], Comment):
1571 # A trailing comment (e.g. from add_line(comment=...)) carries
1572 # no newline, so keep the closing bracket off the comment line
1573 # to produce parseable output (GH #580).
1574 inner += "\n" + self.trivia.indent
1575 return f"[{inner}]"
1577 s = "[\n"
1578 s += "".join(
1579 self.trivia.indent
1580 + " " * 4
1581 + v.value.as_string()
1582 + ("," if not isinstance(v.value, Null) else "")
1583 + (v.comment.as_string() if v.comment is not None else "")
1584 + "\n"
1585 for v in self._value
1586 if v.value is not None
1587 )
1588 s += self.trivia.indent + "]"
1590 return s
1592 def _reindex(self) -> None:
1593 self._index_map.clear()
1594 index = 0
1595 for i, v in enumerate(self._value):
1596 if v.value is None or isinstance(v.value, Null):
1597 continue
1598 self._index_map[index] = i
1599 index += 1
1601 def add_line(
1602 self,
1603 *items: Any,
1604 indent: str = " ",
1605 comment: str | None = None,
1606 add_comma: bool = True,
1607 newline: bool = True,
1608 ) -> None:
1609 """Add multiple items in a line to control the format precisely.
1610 When add_comma is True, only accept actual values and
1611 ", " will be added between values automatically.
1613 :Example:
1615 >>> a = array()
1616 >>> a.add_line(1, 2, 3)
1617 >>> a.add_line(4, 5, 6)
1618 >>> a.add_line(indent="")
1619 >>> print(a.as_string())
1620 [
1621 1, 2, 3,
1622 4, 5, 6,
1623 ]
1624 """
1625 if comment:
1626 validate_comment(comment)
1627 new_values: list[Item] = []
1628 first_indent = f"\n{indent}" if newline else indent
1629 if first_indent:
1630 new_values.append(Whitespace(first_indent))
1631 whitespace = ""
1632 data_values = []
1633 for i, el in enumerate(items):
1634 it = item(el, _parent=self)
1635 if isinstance(it, Comment) or (add_comma and isinstance(el, Whitespace)):
1636 raise ValueError(f"item type {type(it)} is not allowed in add_line")
1637 if not isinstance(it, Whitespace):
1638 if whitespace:
1639 new_values.append(Whitespace(whitespace))
1640 whitespace = ""
1641 new_values.append(it)
1642 data_values.append(it.value)
1643 if add_comma:
1644 new_values.append(Whitespace(","))
1645 if i != len(items) - 1:
1646 new_values.append(Whitespace(" "))
1647 elif "," not in it.s:
1648 whitespace += it.s
1649 else:
1650 new_values.append(it)
1651 if whitespace:
1652 new_values.append(Whitespace(whitespace))
1653 if comment:
1654 indent = " " if items else ""
1655 new_values.append(
1656 Comment(Trivia(indent=indent, comment=f"# {comment}", trail=""))
1657 )
1658 list.extend(self, data_values)
1659 if len(self._value) > 0:
1660 last_item = self._value[-1]
1661 last_value_item = next(
1662 (
1663 v
1664 for v in self._value[::-1]
1665 if v.value is not None and not isinstance(v.value, Null)
1666 ),
1667 None,
1668 )
1669 if last_value_item is not None:
1670 last_value_item.comma = Whitespace(",")
1671 if last_item.is_whitespace():
1672 self._value[-1:-1] = self._group_values(new_values)
1673 else:
1674 self._value.extend(self._group_values(new_values))
1675 else:
1676 self._value.extend(self._group_values(new_values))
1677 self._reindex()
1679 def clear(self) -> None:
1680 """Clear the array."""
1681 list.clear(self)
1682 self._index_map.clear()
1683 self._value.clear()
1685 def __len__(self) -> int:
1686 return list.__len__(self)
1688 def item(self, index: int) -> Item:
1689 return list.__getitem__(self, index) # type: ignore[no-any-return]
1691 def __getitem__(self, key: int | slice) -> Any: # type: ignore[override]
1692 return list.__getitem__(self, key)
1694 def __setitem__(self, key: int | slice, value: Any) -> None: # type: ignore[override]
1695 if isinstance(key, slice):
1696 raise ValueError("slice assignment is not supported")
1697 it = item(value, _parent=self)
1698 list.__setitem__(self, key, it)
1699 if key < 0:
1700 key += len(self)
1701 self._value[self._index_map[key]].value = it
1703 def insert(self, pos: int, value: Any) -> None: # type: ignore[override]
1704 it = item(value, _parent=self)
1705 length = len(self)
1706 if not isinstance(it, (Comment, Whitespace)):
1707 list.insert(self, pos, it)
1708 if pos < 0:
1709 pos += length
1710 if pos < 0:
1711 pos = 0
1713 idx = 0 # insert position of the self._value list
1714 default_indent = " "
1715 if pos < length:
1716 try:
1717 idx = self._index_map[pos]
1718 except KeyError as e:
1719 raise IndexError("list index out of range") from e
1720 else:
1721 idx = len(self._value)
1722 if idx >= 1 and self._value[idx - 1].is_whitespace():
1723 # The last item is a pure whitespace(\n ), insert before it
1724 idx -= 1
1725 _indent = self._value[idx].indent
1726 if _indent is not None and "\n" in _indent.s:
1727 default_indent = "\n "
1728 indent: Whitespace | None = None
1729 comma: Whitespace | None = Whitespace(",") if pos < length else None
1730 if idx < len(self._value) and not self._value[idx].is_whitespace():
1731 # Prefer to copy the indentation from the item after
1732 indent = self._value[idx].indent
1733 if idx > 0:
1734 last_item = self._value[idx - 1]
1735 if indent is None:
1736 indent = last_item.indent
1737 if not isinstance(last_item.value, Null) and "\n" in default_indent:
1738 # Copy the comma from the last item if 1) it contains a value and
1739 # 2) the array is multiline
1740 comma = last_item.comma
1741 comma_in_indent = indent is not None and "," in indent.s
1742 if (
1743 last_item.comma is None
1744 and not isinstance(last_item.value, Null)
1745 and not comma_in_indent
1746 ):
1747 # Add comma to the last item to separate it from the following
1748 # items, unless the new item's indent already starts with a
1749 # comma (comma-first style).
1750 last_item.comma = Whitespace(",")
1751 if indent is not None and "," in indent.s:
1752 # Comma-first style: the item that will follow the new one brings
1753 # its own leading comma, so the new item must not add a trailing
1754 # comma of its own.
1755 comma = None
1756 if indent is None and (idx > 0 or "\n" in default_indent):
1757 # apply default indent if it isn't the first item or the array is multiline.
1758 indent = Whitespace(default_indent)
1759 new_item = _ArrayItemGroup(value=it, indent=indent, comma=comma)
1760 self._value.insert(idx, new_item)
1761 if (
1762 pos >= length
1763 and len(self._index_map) == length
1764 and not isinstance(it, (Comment, Whitespace, Null))
1765 ):
1766 self._index_map[length] = idx
1767 else:
1768 self._reindex()
1770 def __delitem__(self, key: int | slice) -> None: # type: ignore[override]
1771 length = len(self)
1772 list.__delitem__(self, key)
1774 if isinstance(key, slice):
1775 indices_to_remove = list(range(*key.indices(length)))
1776 else:
1777 indices_to_remove = [length + key if key < 0 else key]
1778 for i in sorted(indices_to_remove, reverse=True):
1779 try:
1780 idx = self._index_map[i]
1781 except KeyError as e:
1782 if not isinstance(key, slice):
1783 raise IndexError("list index out of range") from e
1784 else:
1785 group_rm = self._value[idx]
1786 del self._value[idx]
1787 if (
1788 idx == 0
1789 and len(self._value) > 0
1790 and (ind := self._value[idx].indent)
1791 and "\n" not in ind.s
1792 ):
1793 # Remove the indentation of the first item if not newline
1794 self._value[idx].indent = None
1795 comma_in_indent = (
1796 group_rm.indent is not None and "," in group_rm.indent.s
1797 )
1798 comma_in_comma = group_rm.comma is not None and "," in group_rm.comma.s
1799 if comma_in_indent and comma_in_comma:
1800 # Removed group had both commas. Add one to the next group.
1801 group = self._value[idx] if len(self._value) > idx else None
1802 if group is not None:
1803 if group.indent is None:
1804 group.indent = Whitespace(",")
1805 elif "," not in group.indent.s:
1806 # Insert the comma after the newline
1807 try:
1808 newline_index = group.indent.s.index("\n")
1809 group.indent._s = (
1810 group.indent.s[: newline_index + 1]
1811 + ","
1812 + group.indent.s[newline_index + 1 :]
1813 )
1814 except ValueError:
1815 group.indent._s = "," + group.indent.s
1816 elif not comma_in_indent and not comma_in_comma:
1817 # Removed group had no commas. Remove the next comma found.
1818 for j in range(idx, len(self._value)):
1819 group = self._value[j]
1820 if group.indent is not None and "," in group.indent.s:
1821 group.indent._s = group.indent.s.replace(",", "", 1)
1822 break
1823 if group_rm.indent is not None and "\n" in group_rm.indent.s:
1824 # Restore the removed group's newline onto the next group
1825 # if the next group does not have a newline.
1826 # i.e. the two were on the same line
1827 group = self._value[idx] if len(self._value) > idx else None
1828 if group is not None and (
1829 group.indent is None or "\n" not in group.indent.s
1830 ):
1831 group.indent = group_rm.indent
1833 if len(self._value) > 0:
1834 v = self._value[-1]
1835 if not v.is_whitespace():
1836 # remove the comma of the last item
1837 v.comma = None
1839 self._reindex()
1841 def _getstate(self, protocol: int = 3) -> tuple[list[Item], Trivia, bool]:
1842 return list(self._iter_items()), self._trivia, self._multiline
1845class AbstractTable(Item, _CustomDict): # type: ignore[type-arg]
1846 """Common behaviour of both :class:`Table` and :class:`InlineTable`"""
1848 def __init__(self, value: container.Container, trivia: Trivia):
1849 Item.__init__(self, trivia)
1851 self._value = value
1853 for k, v in self._value.body:
1854 if k is not None:
1855 dict.__setitem__(self, k.key, v)
1857 def unwrap(self) -> dict[str, Any]:
1858 # Delegate to the inner container's unwrap, which walks its _body
1859 # directly instead of re-resolving every key through items()/__getitem__
1860 # (which rebuilds a SingleKey, and an OutOfOrderTableProxy for
1861 # out-of-order keys, per key just to throw it away).
1862 return self._value.unwrap()
1864 @property
1865 def value(self) -> container.Container:
1866 return self._value
1868 @overload
1869 def append(self: AT, key: None, value: Comment | Whitespace) -> AT: ...
1871 @overload
1872 def append(self: AT, key: Key | str, value: Any) -> AT: ...
1874 def append(self: AT, key: Key | str | None, value: Any) -> AT:
1875 raise NotImplementedError
1877 @overload
1878 def add(self: AT, key: Comment | Whitespace) -> AT: ...
1880 @overload
1881 def add(self: AT, key: Key | str, value: Any = ...) -> AT: ...
1883 def add(
1884 self: AT, key: Key | str | Comment | Whitespace, value: Any | None = None
1885 ) -> AT:
1886 if value is None:
1887 if not isinstance(key, (Comment, Whitespace)):
1888 msg = "Non comment/whitespace items must have an associated key"
1889 raise ValueError(msg)
1891 return self.append(None, key)
1893 if isinstance(key, (Comment, Whitespace)):
1894 raise ValueError("Comment/Whitespace keys must not have a value")
1896 return self.append(key, value)
1898 def remove(self: AT, key: Key | str) -> AT:
1899 self._value.remove(key)
1901 if isinstance(key, Key):
1902 key = key.key
1904 if key is not None:
1905 dict.__delitem__(self, key)
1907 return self
1909 def item(self, key: Key | str) -> Item | OutOfOrderTableProxy:
1910 return self._value.item(key)
1912 def setdefault(self, key: Key | str, default: Any) -> Any: # type: ignore[override]
1913 super().setdefault(key, default)
1914 return self[key]
1916 def __str__(self) -> str:
1917 return str(self.value)
1919 def copy(self: AT) -> AT:
1920 return copy.copy(self)
1922 def __repr__(self) -> str:
1923 return repr(self.value)
1925 def __iter__(self) -> Iterator[str]:
1926 return iter(self._value)
1928 def __len__(self) -> int:
1929 return len(self._value)
1931 def __delitem__(self, key: Key | str) -> None:
1932 self.remove(key)
1934 def __getitem__(self, key: Key | str) -> Any:
1935 return self._value[key]
1937 def __contains__(self, key: object) -> bool:
1938 # Native membership test. The inherited ``MutableMapping.__contains__``
1939 # resolves the value via ``__getitem__`` (``self._value[key]``) -- and
1940 # builds a ``NonExistentKey`` on every absent key -- only to discard it.
1941 # Delegate straight to the inner container instead: its ``__contains__``
1942 # answers from ``_map`` while still building the ``OutOfOrderTableProxy``
1943 # for an out-of-order entry, so validation runs exactly as before.
1944 return key in self._value
1946 def __setitem__(self, key: Key | str, value: Any) -> None:
1947 if not isinstance(value, Item):
1948 value = self._value._item_for_key(key, value, parent=self)
1950 is_replace = key in self
1951 self._value[key] = value
1953 if key is not None:
1954 dict.__setitem__(self, key, value)
1956 if is_replace:
1957 return
1958 m = re.match("(?s)^[^ ]*([ ]+).*$", self._trivia.indent)
1959 if not m:
1960 return
1962 indent = m.group(1)
1964 if not isinstance(value, Whitespace):
1965 m = re.match("(?s)^([^ ]*)(.*)$", value.trivia.indent)
1966 if not m:
1967 value.trivia.indent = indent
1968 else:
1969 value.trivia.indent = m.group(1) + indent + m.group(2)
1972class Table(AbstractTable):
1973 """
1974 A table literal.
1975 """
1977 def __init__(
1978 self,
1979 value: container.Container,
1980 trivia: Trivia,
1981 is_aot_element: bool,
1982 is_super_table: bool | None = None,
1983 name: str | None = None,
1984 display_name: str | None = None,
1985 ) -> None:
1986 super().__init__(value, trivia)
1988 self.name = name
1989 self.display_name = display_name
1990 self._is_aot_element = is_aot_element
1991 self._is_super_table = is_super_table
1993 @property
1994 def discriminant(self) -> int:
1995 return 9
1997 def __copy__(self) -> Table:
1998 return type(self)(
1999 self._value.copy(),
2000 self._trivia.copy(),
2001 self._is_aot_element,
2002 self._is_super_table,
2003 self.name,
2004 self.display_name,
2005 )
2007 def append(self, key: Key | str | None, _item: Any) -> Table:
2008 """
2009 Appends a (key, item) to the table.
2010 """
2011 if not isinstance(_item, Item):
2012 _item = item(_item, _parent=self)
2014 self._value.append(key, _item)
2016 if isinstance(key, Key):
2017 key = next(iter(key)).key
2018 _item = self._value[key]
2020 if key is not None:
2021 dict.__setitem__(self, key, _item)
2023 m = re.match(r"(?s)^[^ ]*([ ]+).*$", self._trivia.indent)
2024 if not m:
2025 return self
2027 indent = m.group(1)
2029 # A table split out of order is looked up as an OutOfOrderTableProxy,
2030 # which has no trivia; its parts keep their own indentation.
2031 if isinstance(_item, Item) and not isinstance(_item, Whitespace):
2032 m = re.match("(?s)^([^ ]*)(.*)$", _item.trivia.indent)
2033 if not m:
2034 _item.trivia.indent = indent
2035 else:
2036 _item.trivia.indent = m.group(1) + indent + m.group(2)
2038 return self
2040 def raw_append(self, key: Key | str | None, _item: Any) -> Table:
2041 """Similar to :meth:`append` but does not copy indentation."""
2042 if not isinstance(_item, Item):
2043 _item = item(_item)
2045 self._value.append(key, _item, validate=False)
2047 if isinstance(key, Key):
2048 key = next(iter(key)).key
2049 _item = self._value[key]
2051 if key is not None:
2052 dict.__setitem__(self, key, _item)
2054 return self
2056 def is_aot_element(self) -> bool:
2057 """True if the table is the direct child of an AOT element."""
2058 return self._is_aot_element
2060 def is_super_table(self) -> bool:
2061 """A super table is the intermediate parent of a nested table as in [a.b.c].
2062 If true, it won't appear in the TOML representation."""
2063 if self._is_super_table is not None:
2064 return self._is_super_table
2065 if not self:
2066 return False
2067 # If the table has children and all children are tables, then it is a super table.
2068 for k, child in self.items():
2069 if not isinstance(k, Key):
2070 k = SingleKey(k)
2071 index = self.value._map[k]
2072 if isinstance(index, tuple):
2073 return False
2074 real_key = self.value.body[index][0]
2075 if (
2076 not isinstance(child, (Table, AoT))
2077 or real_key is None
2078 or real_key.is_dotted()
2079 ):
2080 return False
2081 return True
2083 def as_string(self) -> str:
2084 return self._value.as_string()
2086 # Helpers
2088 def indent(self, indent: int) -> Table:
2089 """Indent the table with given number of spaces."""
2090 super().indent(indent)
2092 m = re.match("(?s)^[^ ]*([ ]+).*$", self._trivia.indent)
2093 if not m:
2094 indent_str = ""
2095 else:
2096 indent_str = m.group(1)
2098 for _, item in self._value.body:
2099 if not isinstance(item, Whitespace):
2100 item.trivia.indent = indent_str + item.trivia.indent
2102 return self
2104 def invalidate_display_name(self) -> None:
2105 """Call ``invalidate_display_name`` on the contained tables"""
2106 self.display_name = None
2108 for child in self.values():
2109 if hasattr(child, "invalidate_display_name"):
2110 child.invalidate_display_name()
2112 def _getstate(
2113 self, protocol: int = 3
2114 ) -> tuple[container.Container, Trivia, bool, bool | None, str | None, str | None]:
2115 return (
2116 self._value,
2117 self._trivia,
2118 self._is_aot_element,
2119 self._is_super_table,
2120 self.name,
2121 self.display_name,
2122 )
2125class InlineTable(AbstractTable):
2126 """
2127 An inline table literal.
2128 """
2130 def __init__(
2131 self, value: container.Container, trivia: Trivia, new: bool = False
2132 ) -> None:
2133 super().__init__(value, trivia)
2135 self._new = new
2137 @property
2138 def discriminant(self) -> int:
2139 return 10
2141 def append(self, key: Key | str | None, _item: Any) -> InlineTable:
2142 """
2143 Appends a (key, item) to the table.
2144 """
2145 if not isinstance(_item, Item):
2146 _item = item(_item, _parent=self)
2148 self._validate_child(_item)
2150 if not isinstance(_item, (Whitespace, Comment)):
2151 if not _item.trivia.indent and len(self._value) > 0 and not self._new:
2152 _item.trivia.indent = " "
2153 if _item.trivia.comment:
2154 _item.trivia.comment = ""
2156 self._value.append(key, _item)
2158 if isinstance(key, Key):
2159 key = key.key
2161 if key is not None:
2162 dict.__setitem__(self, key, _item)
2164 return self
2166 def _validate_child(self, _item: Item) -> None:
2167 if isinstance(_item, Table):
2168 raise ValueError("Inline tables cannot contain a table")
2170 def as_string(self) -> str:
2171 buf = "{"
2172 emitted_key = False
2173 needs_separator = False
2174 # Single pass over the body to precompute everything the render loop
2175 # needs, instead of rescanning the tail on every separator comma (which
2176 # was O(n^2) on large inline tables): whether any explicit-comma
2177 # whitespace is present, the index of the last real key, and the index
2178 # of the last Null (deleted) element.
2179 has_explicit_commas = False
2180 last_item_idx = None
2181 last_null_idx = -1
2182 for _i, (_k, _v) in enumerate(self._value.body):
2183 if _k is not None:
2184 last_item_idx = _i
2185 elif isinstance(_v, Whitespace) and "," in _v.s:
2186 has_explicit_commas = True
2187 if isinstance(_v, Null):
2188 last_null_idx = _i
2189 pending_separator = False
2190 # Buffer position right after the last rendered value, used to place a
2191 # deferred separator comma after the value rather than after a trailing
2192 # comment/whitespace.
2193 last_value_end = len(buf)
2194 for i, (k, v) in enumerate(self._value.body):
2195 if k is None:
2196 if isinstance(v, Whitespace) and "," in v.s:
2197 if not emitted_key:
2198 buf += v.as_string().replace(",", "", 1)
2199 continue
2201 # Equivalent to scanning body[i + 1 :] for a Null / a real
2202 # key, but O(1) using the indices precomputed above.
2203 has_following_null = last_null_idx > i
2204 has_following_key = last_item_idx is not None and last_item_idx > i
2205 if has_following_null and not has_following_key:
2206 buf += v.as_string().replace(",", "", 1)
2207 continue
2209 if pending_separator:
2210 # A previous key was removed, leaving this comma as a
2211 # duplicate of an already emitted separator. Drop it to
2212 # avoid producing an invalid ``, ,`` sequence.
2213 buf += v.as_string().replace(",", "", 1)
2214 continue
2216 pending_separator = True
2218 if i == len(self._value.body) - 1:
2219 if self._new:
2220 buf = buf.rstrip(", ")
2221 elif not has_explicit_commas or "," in v.as_string():
2222 buf = buf.rstrip(",")
2224 v_string = v.as_string()
2225 buf += v_string
2226 if "," in v_string:
2227 needs_separator = False
2229 continue
2231 if has_explicit_commas and needs_separator:
2232 # Insert the deferred separator right after the previous value,
2233 # not after any trailing comment/whitespace -- otherwise the
2234 # comma is swallowed by a trailing comment (see #512).
2235 # Match the conventional ", " spacing used by the explicit
2236 # separators already in the table. Only add the space when the
2237 # text that will follow the comma (the previous value's trailing
2238 # trivia plus the new key's own indent) does not already start
2239 # with one, so a padded table like ``{ a = 1 }`` -- which
2240 # contributes the space itself -- does not end up double-spaced.
2241 following = buf[last_value_end:] + v.trivia.indent
2242 separator = "," if following.startswith(" ") else ", "
2243 buf = f"{buf[:last_value_end]}{separator}{buf[last_value_end:]}"
2244 needs_separator = False
2246 v_trivia_trail = v.trivia.trail.replace("\n", "")
2247 if k.is_dotted() and isinstance(v, Table):
2248 # A table materialized from a dotted key renders one
2249 # `prefix.child = value` pair per child, so that keys added
2250 # after parsing stay attached to the dotted prefix.
2251 rendered = ", ".join(self._render_dotted(k, v))
2252 else:
2253 rendered = (
2254 f"{k.as_string() + ('.' if k.is_dotted() else '')}"
2255 f"{k.sep}"
2256 f"{v.as_string()}"
2257 )
2258 buf += f"{v.trivia.indent}{rendered}"
2259 last_value_end = len(buf)
2260 buf += f"{v.trivia.comment}{v_trivia_trail}"
2261 emitted_key = True
2262 pending_separator = False
2263 if has_explicit_commas:
2264 needs_separator = True
2266 if (
2267 not has_explicit_commas
2268 and last_item_idx is not None
2269 and i < last_item_idx
2270 ):
2271 buf += ","
2272 if self._new:
2273 buf += " "
2275 buf += "}"
2277 return buf
2279 def _render_dotted(self, key: Key, table: Table) -> list[str]:
2280 """Render a table materialized from a dotted key as a list of
2281 ``prefix.child = value`` strings, recursing into nested dotted
2282 children."""
2283 prefix = f"{key.as_string()}.{key.sep}"
2284 parts = []
2285 for k, v in table.value.body:
2286 if k is None:
2287 continue
2288 if isinstance(v, Table):
2289 parts.extend(f"{prefix}{sub}" for sub in self._render_dotted(k, v))
2290 else:
2291 trail = v.trivia.trail.replace("\n", "")
2292 parts.append(
2293 f"{prefix}{v.trivia.indent}{k.as_string()}{k.sep}{v.as_string()}"
2294 f"{v.trivia.comment_ws}{v.trivia.comment}{trail}"
2295 )
2296 if not parts:
2297 # every key under the prefix was removed, keep it as an empty table
2298 return [f"{key.as_string()} = {{}}"]
2299 return parts
2301 def __setitem__(self, key: Key | str, value: Any) -> None:
2302 if hasattr(value, "trivia") and value.trivia.comment:
2303 value.trivia.comment = ""
2304 if not isinstance(value, Item):
2305 value = self._value._item_for_key(key, value, parent=self)
2306 self._validate_child(value)
2307 super().__setitem__(key, value)
2309 def __copy__(self) -> InlineTable:
2310 return type(self)(self._value.copy(), self._trivia.copy(), self._new)
2312 def _getstate(self, protocol: int = 3) -> tuple[container.Container, Trivia]:
2313 return (self._value, self._trivia)
2316class String(str, Item):
2317 """
2318 A string literal.
2319 """
2321 def __new__(
2322 cls, t: StringType, value: str, original: str, trivia: Trivia
2323 ) -> String:
2324 return super().__new__(cls, value)
2326 def __init__(self, t: StringType, _: str, original: str, trivia: Trivia) -> None:
2327 super().__init__(trivia)
2329 self._t = t
2330 self._original = original
2332 def unwrap(self) -> str:
2333 return str(self)
2335 @property
2336 def discriminant(self) -> int:
2337 return 11
2339 @property
2340 def value(self) -> str:
2341 return self
2343 def as_string(self) -> str:
2344 return f"{self._t.value}{decode(self._original)}{self._t.value}"
2346 @property
2347 def type(self) -> StringType:
2348 return self._t
2350 def __add__(self, other: str) -> String:
2351 result = super().__add__(other)
2352 if isinstance(other, String):
2353 original = self._original + other._original
2354 else:
2355 escaped = self._t.escaped_sequences
2356 original = self._original + (
2357 escape_string(other, escaped) if escaped else other
2358 )
2360 return self._new(result, original)
2362 def _new(self, result: str, original: str) -> String:
2363 return String(self._t, result, original, self._trivia.copy())
2365 def _getstate(self, protocol: int = 3) -> tuple[StringType, str, str, Trivia]:
2366 return self._t, str(self), self._original, self._trivia
2368 @classmethod
2369 def from_raw(
2370 cls, value: str, type_: StringType = StringType.SLB, escape: bool = True
2371 ) -> String:
2372 value = decode(value)
2374 invalid = type_.invalid_sequences
2375 # collapse CRLF line endings so only a lone CR trips the CR check
2376 checked = value.replace("\r\n", "\n")
2377 if any(c in checked for c in invalid):
2378 raise InvalidStringError(value, invalid, type_.value)
2380 string_value = value
2381 if escape:
2382 string_value = escape_string(string_value, type_.escaped_sequences)
2383 if type_ is StringType.MLB and escape:
2384 string_value = _BARE_CR.sub(r"\\r", string_value)
2385 if type_.is_multiline() and string_value[:1] in ("\n", "\r"):
2386 # A newline immediately following the opening delimiter of a
2387 # multiline string is trimmed by the parser, so a value that
2388 # starts with a newline would otherwise lose it on round-trip.
2389 # Emit an extra leading newline (the trimmed one) to preserve it.
2390 string_value = "\n" + string_value
2392 return cls(type_, value, string_value, Trivia())
2395class AoT(Item, _CustomList): # type: ignore[type-arg]
2396 """
2397 An array of table literal
2398 """
2400 def __init__(
2401 self, body: list[Table], name: str | None = None, parsed: bool = False
2402 ) -> None:
2403 self.name = name
2404 self._body: list[Table] = []
2405 self._parsed = parsed
2407 super().__init__(Trivia(trail=""))
2409 for table in body:
2410 self.append(table)
2412 def unwrap(self) -> list[dict[str, Any]]:
2413 unwrapped = []
2414 for t in self._body:
2415 if hasattr(t, "unwrap"):
2416 unwrapped.append(t.unwrap())
2417 else:
2418 unwrapped.append(t)
2419 return unwrapped
2421 @property
2422 def body(self) -> list[Table]:
2423 return self._body
2425 @property
2426 def discriminant(self) -> int:
2427 return 12
2429 @property
2430 def value(self) -> list[dict[str, Any]]:
2431 return [v.value for v in self._body]
2433 def __len__(self) -> int:
2434 return len(self._body)
2436 @overload # type: ignore[override]
2437 def __getitem__(self, key: slice) -> list[Table]: ...
2439 @overload
2440 def __getitem__(self, key: int) -> Table: ...
2442 def __getitem__(self, key: int | slice) -> Table | list[Table]:
2443 return self._body[key]
2445 def __setitem__(self, key: slice | int, value: Any) -> None: # type: ignore[override]
2446 if isinstance(key, slice):
2447 value = [item(v, _parent=self) for v in value]
2448 else:
2449 value = item(value, _parent=self)
2450 self._body[key] = value
2451 list.__setitem__(self, key, value)
2453 def __delitem__(self, key: slice | int) -> None: # type: ignore[override]
2454 del self._body[key]
2455 list.__delitem__(self, key)
2457 def insert(self, index: int, value: dict[str, Any]) -> None: # type: ignore[override]
2458 value = item(value, _parent=self)
2459 if not isinstance(value, Table):
2460 raise ValueError(f"Unsupported insert value type: {type(value)}")
2461 length = len(self)
2462 if index < 0:
2463 index += length
2464 if index < 0:
2465 index = 0
2466 elif index >= length:
2467 index = length
2468 m = re.match("(?s)^[^ ]*([ ]+).*$", self._trivia.indent)
2469 if m:
2470 indent = m.group(1)
2472 m = re.match("(?s)^([^ ]*)(.*)$", value.trivia.indent)
2473 if not m:
2474 value.trivia.indent = indent
2475 else:
2476 value.trivia.indent = m.group(1) + indent + m.group(2)
2477 prev_table = self._body[index - 1] if 0 < index and length else None
2478 next_table = self._body[index + 1] if index < length - 1 else None
2479 if not self._parsed:
2480 if prev_table and "\n" not in value.trivia.indent:
2481 value.trivia.indent = "\n" + value.trivia.indent
2482 if next_table and "\n" not in next_table.trivia.indent:
2483 next_table.trivia.indent = "\n" + next_table.trivia.indent
2484 self._body.insert(index, value)
2485 list.insert(self, index, value)
2487 def invalidate_display_name(self) -> None:
2488 """Call ``invalidate_display_name`` on the contained tables"""
2489 for child in self:
2490 if hasattr(child, "invalidate_display_name"):
2491 child.invalidate_display_name()
2493 def as_string(self) -> str:
2494 b = ""
2495 for table in self._body:
2496 b += table.as_string()
2498 return b
2500 def __repr__(self) -> str:
2501 return f"<AoT {self.value}>"
2503 def _getstate(self, protocol: int = 3) -> tuple[list[Table], str | None, bool]:
2504 return self._body, self.name, self._parsed
2507class Null(Item):
2508 """
2509 A null item.
2510 """
2512 def __init__(self) -> None:
2513 super().__init__(Trivia(trail=""))
2515 def unwrap(self) -> None:
2516 return None
2518 @property
2519 def discriminant(self) -> int:
2520 return -1
2522 @property
2523 def value(self) -> None:
2524 return None
2526 def as_string(self) -> str:
2527 return ""
2529 def _getstate(self, protocol: int = 3) -> tuple[()]:
2530 return ()