Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/tomlkit/container.py: 67%

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

746 statements  

1from __future__ import annotations 

2 

3import copy 

4import math 

5 

6from collections.abc import Iterator 

7from typing import TYPE_CHECKING 

8from typing import Any 

9 

10 

11if TYPE_CHECKING: 

12 from typing import Self 

13 

14from tomlkit._compat import decode 

15from tomlkit._types import _CustomDict 

16from tomlkit._utils import merge_dicts 

17from tomlkit.exceptions import InvalidStringError 

18from tomlkit.exceptions import KeyAlreadyPresent 

19from tomlkit.exceptions import NonExistentKey 

20from tomlkit.exceptions import TOMLKitError 

21from tomlkit.items import AoT 

22from tomlkit.items import Comment 

23from tomlkit.items import Item 

24from tomlkit.items import Key 

25from tomlkit.items import Null 

26from tomlkit.items import SingleKey 

27from tomlkit.items import String 

28from tomlkit.items import StringType 

29from tomlkit.items import Table 

30from tomlkit.items import Trivia 

31from tomlkit.items import Whitespace 

32from tomlkit.items import item as _item 

33 

34 

35def _is_empty_aot(item: Item) -> bool: 

36 """Whether ``item`` is an array of tables with no elements left.""" 

37 return isinstance(item, AoT) and not item.body 

38 

39 

40def _emits_header(key: Key, table: Table) -> bool: 

41 """Whether rendering ``table`` under ``key`` emits a ``[header]`` line. 

42 

43 A super table normally renders as nothing but the path prefix of its 

44 children, so it opens no scope of its own. 

45 """ 

46 return ( 

47 not table.is_super_table() 

48 or ( 

49 any( 

50 not isinstance(v, (Table, AoT, Whitespace, Null)) 

51 for _, v in table.value.body 

52 ) 

53 and not key.is_dotted() 

54 ) 

55 or ( 

56 any( 

57 k is not None and k.is_dotted() 

58 for k, v in table.value.body 

59 if isinstance(v, Table) 

60 ) 

61 and not key.is_dotted() 

62 ) 

63 ) 

64 

65 

66def _header_less_aots( 

67 body: list[tuple[Key | None, Item]], prefix: str = "" 

68) -> list[tuple[str, AoT]]: 

69 """Every emptied array of tables reachable without crossing a header. 

70 

71 An emptied array of tables has no ``[[key]]`` header left to render, so it 

72 falls back to the inline ``key = []`` form -- and TOML reads a bare 

73 key/value pair into whichever table the closest preceding header opened. 

74 So the fallbacks of a scope have to be written at the top of that scope, 

75 with a key relative to it, and that includes the ones sitting inside super 

76 tables, which emit no header to separate them. 

77 

78 Returns ``(dotted key, aot)`` pairs, keyed relative to the scope ``body`` 

79 belongs to. 

80 """ 

81 found: list[tuple[str, AoT]] = [] 

82 for k, v in body: 

83 if k is None: 

84 continue 

85 path = f"{prefix}.{k.as_string()}" if prefix else k.as_string() 

86 if _is_empty_aot(v): 

87 found.append((path, v)) 

88 elif isinstance(v, Table) and not _emits_header(k, v): 

89 found.extend(_header_less_aots(v.value.body, path)) 

90 return found 

91 

92 

93def _render_empty_aot(key: str, aot: AoT) -> str: 

94 """Render an emptied array of tables as an inline empty array.""" 

95 return ( 

96 f"{aot.trivia.indent}" 

97 f"{decode(key)}" 

98 f" = []" 

99 f"{aot.trivia.comment_ws}" 

100 f"{decode(aot.trivia.comment)}" 

101 f"{aot.trivia.trail or chr(10)}" 

102 ) 

103 

104 

105class Container(_CustomDict): # type: ignore[type-arg] 

106 """ 

107 A container for items within a TOMLDocument. 

108 

109 This class implements the `dict` interface with copy/deepcopy protocol. 

110 """ 

111 

112 def __init__(self, parsed: bool = False) -> None: 

113 self._map: dict[Key, int | tuple[int, ...]] = {} 

114 self._body: list[tuple[Key | None, Item]] = [] 

115 self._parsed = parsed 

116 self._table_keys: list[Key] = [] 

117 # number of already-validated fragments and the temp container they 

118 # were merged into, per out-of-order key; lets parse-time validation 

119 # resume where the previous pass stopped instead of re-merging every 

120 # fragment (quadratic) on each append 

121 self._validation_cache: dict[Key, tuple[int, Container]] = {} 

122 # superset of the keys mapped to an index tuple, so validating all 

123 # out-of-order tables doesn't have to scan every key in the map; 

124 # stale entries are filtered by the per-key isinstance check 

125 self._out_of_order_keys: set[Key] = set() 

126 

127 @property 

128 def body(self) -> list[tuple[Key | None, Item]]: 

129 return self._body 

130 

131 def unwrap(self) -> dict[str, Any]: 

132 """Returns as pure python object (ppo)""" 

133 unwrapped: dict[str, Any] = {} 

134 # Resolve each key straight from _map, which already holds the parsed 

135 # Key objects and their body index, instead of via self.items(): the 

136 # inherited MutableMapping iteration goes through __getitem__, which 

137 # rebuilds a SingleKey from the bare string on every key only to throw 

138 # it away. Out-of-order keys (a tuple index) still go through 

139 # OutOfOrderTableProxy so their validation (and fragment merge) runs 

140 # exactly as before. _map is keyed for lookup, not ordered: replacing a 

141 # value re-inserts its key and moves it last, so take the order from the 

142 # body index, which is what dumps() and items() follow. 

143 for key, idx in sorted( 

144 self._map.items(), 

145 key=lambda item: item[1][0] if isinstance(item[1], tuple) else item[1], 

146 ): 

147 if isinstance(idx, tuple): 

148 value: Any = OutOfOrderTableProxy(self, idx) 

149 else: 

150 value = self._body[idx][1] 

151 unwrapped[key.key] = value.unwrap() if hasattr(value, "unwrap") else value 

152 

153 return unwrapped 

154 

155 @property 

156 def value(self) -> dict[str, Any]: 

157 """The wrapped dict value""" 

158 d: dict[str, Any] = {} 

159 for k, v in self._body: 

160 if k is None: 

161 continue 

162 

163 key_str = k.key 

164 val: Any = v.value 

165 

166 if isinstance(val, Container): 

167 val = val.value 

168 

169 if key_str in d: 

170 merge_dicts(d[key_str], val) 

171 else: 

172 d[key_str] = val 

173 

174 return d 

175 

176 def parsing(self, parsing: bool) -> None: 

177 self._parsed = parsing 

178 self._validation_cache.clear() 

179 

180 for _, v in self._body: 

181 if isinstance(v, Table): 

182 v.value.parsing(parsing) 

183 elif isinstance(v, AoT): 

184 for t in v.body: 

185 t.value.parsing(parsing) 

186 

187 def add(self, key: Key | Item | str, item: Any = None) -> Container: 

188 """ 

189 Adds an item to the current Container. 

190 

191 :Example: 

192 

193 >>> # add a key-value pair 

194 >>> doc.add('key', 'value') 

195 >>> # add a comment or whitespace or newline 

196 >>> doc.add(comment('# comment')) 

197 """ 

198 if item is None: 

199 if not isinstance(key, (Comment, Whitespace)): 

200 raise ValueError( 

201 "Non comment/whitespace items must have an associated key" 

202 ) 

203 

204 return self.append(None, key) 

205 

206 assert not isinstance(key, Item) 

207 return self.append(key, item) 

208 

209 def _handle_dotted_key(self, key: Key, value: Item) -> None: 

210 if isinstance(value, (Table, AoT)): 

211 raise TOMLKitError("Can't add a table to a dotted key") 

212 name, *mid, last = key 

213 name._dotted = True 

214 table = current = Table(Container(True), Trivia(), False, is_super_table=True) 

215 for _name in mid: 

216 _name._dotted = True 

217 new_table = Table(Container(True), Trivia(), False, is_super_table=True) 

218 current.append(_name, new_table) 

219 current = new_table 

220 

221 last.sep = key.sep 

222 current.append(last, value) 

223 

224 self.append(name, table) 

225 return 

226 

227 def _get_last_index_before_table(self) -> int: 

228 last_index = -1 

229 for i, (k, v) in enumerate(self._body): 

230 if isinstance(v, Null): 

231 continue # Null elements are inserted after deletion 

232 

233 if isinstance(v, Whitespace) and not v.is_fixed(): 

234 continue 

235 

236 if isinstance(v, (Table, AoT)) and k is not None and not k.is_dotted(): 

237 break 

238 

239 if ( 

240 isinstance(v, Table) 

241 and k is not None 

242 and k.is_dotted() 

243 and self._renders_table_header(v) 

244 ): 

245 # A dotted-key super table renders inline (`a.b = 1`) only as 

246 # long as none of its children render a `[table]` header; once 

247 # one does, anything appended after it would land inside that 

248 # table's scope. 

249 break 

250 last_index = i 

251 return last_index + 1 

252 

253 def _renders_table_header(self, table: Table) -> bool: 

254 for k, v in table.value.body: 

255 if isinstance(v, AoT): 

256 return True 

257 if isinstance(v, Table): 

258 if k is not None and k.is_dotted() and v.is_super_table(): 

259 if self._renders_table_header(v): 

260 return True 

261 else: 

262 return True 

263 return False 

264 

265 def _validate_out_of_order_table(self, key: Key | None = None) -> None: 

266 if key is None: 

267 for k in list(self._out_of_order_keys): 

268 assert k is not None 

269 self._validate_out_of_order_table(k) 

270 return 

271 if key not in self._map: 

272 return 

273 current_idx = self._map[key] 

274 if not isinstance(current_idx, tuple): 

275 return 

276 if self._parsed: 

277 # while parsing, every fragment appended to an out-of-order key 

278 # triggers a validation pass; resume from the cached temp 

279 # container so each fragment is merged (and deep-copied) once 

280 # instead of on every later pass. Fragments are only ever 

281 # appended during parsing, so a count prefix stays valid; any 

282 # other mutation clears the cache. 

283 validated, temp = self._validation_cache.get(key, (0, None)) 

284 if validated > len(current_idx): 

285 validated, temp = 0, None 

286 try: 

287 temp = OutOfOrderTableProxy.validate( 

288 self, current_idx[validated:], temp 

289 ) 

290 except Exception: 

291 # the temp container may be partially mutated; don't let a 

292 # caught-and-retried failure resume from a poisoned cache 

293 self._validation_cache.pop(key, None) 

294 raise 

295 self._validation_cache[key] = (len(current_idx), temp) 

296 return 

297 OutOfOrderTableProxy.validate(self, current_idx) 

298 

299 def append( 

300 self, key: Key | str | None, item: Any, validate: bool = True 

301 ) -> Container: 

302 """Similar to :meth:`add` but both key and value must be given.""" 

303 if not isinstance(key, Key) and key is not None: 

304 key = SingleKey(key) 

305 

306 if not isinstance(item, Item): 

307 item = _item(item) 

308 

309 if key is not None and key.is_multi(): 

310 self._handle_dotted_key(key, item) 

311 return self 

312 

313 if isinstance(item, (AoT, Table)) and item.name is None: 

314 assert isinstance(key, Key) 

315 item.name = key.key 

316 

317 prev = self._previous_item() 

318 prev_ws = isinstance(prev, Whitespace) or ends_with_whitespace(prev) 

319 if isinstance(item, Table): 

320 if not self._parsed: 

321 item.invalidate_display_name() 

322 if ( 

323 self._body 

324 and not (self._parsed or item.trivia.indent or prev_ws) 

325 and key is not None 

326 and not key.is_dotted() 

327 ): 

328 item.trivia.indent = "\n" 

329 

330 if isinstance(item, AoT) and self._body and not self._parsed: 

331 item.invalidate_display_name() 

332 if item and not ("\n" in item[0].trivia.indent or prev_ws): 

333 item[0].trivia.indent = "\n" + item[0].trivia.indent 

334 

335 if key is not None and key in self: 

336 current_idx = self._map[key] 

337 if isinstance(current_idx, tuple): 

338 current_body_element = self._body[current_idx[-1]] 

339 else: 

340 current_body_element = self._body[current_idx] 

341 

342 current = current_body_element[1] 

343 

344 if isinstance(item, Table): 

345 if not isinstance(current, (Table, AoT)): 

346 raise KeyAlreadyPresent(key) 

347 

348 if item.is_aot_element(): 

349 # New AoT element found later on 

350 # Adding it to the current AoT 

351 if not isinstance(current, AoT): 

352 current = AoT([current, item], parsed=self._parsed) 

353 

354 self._replace(key, key, current) 

355 else: 

356 current.append(item) 

357 

358 return self 

359 elif isinstance(current, AoT): 

360 if not item.is_aot_element(): 

361 if item.is_super_table() and len(current.body): 

362 # A sub-table header such as `[fruit.apple.texture]` 

363 # appearing after the array `[[fruit]]` (possibly with 

364 # unrelated tables in between) extends the last element 

365 # of the array, per the TOML spec. 

366 last = current[-1] 

367 for k, v in item.value.body: 

368 last.value.append(k, v) 

369 

370 return self 

371 # Tried to define a table after an AoT with the same name. 

372 raise KeyAlreadyPresent(key) 

373 

374 current.append(item) 

375 

376 return self 

377 elif current.is_super_table(): 

378 if item.is_super_table(): 

379 # We need to merge both super tables 

380 if ( 

381 key.is_dotted() 

382 or ( 

383 current_body_element[0] is not None 

384 and current_body_element[0].is_dotted() 

385 ) 

386 or self._table_keys[-1] != current_body_element[0] 

387 ): 

388 if key.is_dotted() and not self._parsed: 

389 idx = self._get_last_index_before_table() 

390 else: 

391 idx = len(self._body) 

392 

393 if idx < len(self._body): 

394 self._insert_at(idx, key, item) 

395 else: 

396 self._raw_append(key, item) 

397 

398 if validate: 

399 self._validate_out_of_order_table(key) 

400 

401 return self 

402 

403 # Merge the new super table's body into the existing one 

404 # in place. Previously this deep-copied `current` before 

405 # appending, which is O(size of current) on every merge 

406 # and therefore O(n^2) when many subtables share a super 

407 # table (e.g. consecutive `[a.b.c]` / `[a.b.d]` headers). 

408 # Mutating in place is O(1) per merge. The defensive copy 

409 # that protected the out-of-order validation pass has been 

410 # moved into OutOfOrderTableProxy (its only consumer). 

411 for k, v in item.value.body: 

412 current.append(k, v) 

413 

414 return self 

415 elif ( 

416 current_body_element[0] is not None 

417 and current_body_element[0].is_dotted() 

418 ): 

419 raise TOMLKitError("Redefinition of an existing table") 

420 else: 

421 # Merging a concrete table into an existing implicit/super 

422 # table is only valid if it does not redefine existing 

423 # subtrees via dotted keys and does not change prior types. 

424 assert isinstance(current, Table) 

425 self._validate_table_candidate(current, item) 

426 elif not item.is_super_table(): 

427 raise KeyAlreadyPresent(key) 

428 else: 

429 # An existing concrete table (current) is being extended by 

430 # a super-table (item) — e.g. [a] b=1 then [a.b] c=2 out of 

431 # order, or [a] b.c=1 then [a.b] d=2. Validate that the 

432 # super-table does not redefine any existing key, raising 

433 # early at parse time. When validation passes, fall through 

434 # — _raw_append below will create an out-of-order entry and 

435 # preserve table ordering in the document. 

436 assert isinstance(current, Table) 

437 self._validate_table_candidate(current, item) 

438 elif isinstance(item, AoT): 

439 if not isinstance(current, AoT): 

440 # Tried to define an AoT after a table with the same name. 

441 raise KeyAlreadyPresent(key) 

442 

443 for table in item.body: 

444 current.append(table) 

445 

446 return self 

447 else: 

448 raise KeyAlreadyPresent(key) 

449 

450 is_table = isinstance(item, (Table, AoT)) 

451 if ( 

452 key is not None 

453 and self._body 

454 and not self._parsed 

455 and (not is_table or key.is_dotted()) 

456 ): 

457 # If there is already at least one table in the current container 

458 # and the given item is not a table, we need to find the last 

459 # item that is not a table and insert after it 

460 # If no such item exists, insert at the top of the table 

461 last_index = self._get_last_index_before_table() 

462 

463 if last_index < len(self._body): 

464 after_item = self._body[last_index][1] 

465 if not ( 

466 isinstance(after_item, Whitespace) 

467 or "\n" in after_item.trivia.indent 

468 ): 

469 after_item.trivia.indent = "\n" + after_item.trivia.indent 

470 return self._insert_at(last_index, key, item) 

471 else: 

472 previous_item = self._body[-1][1] 

473 if isinstance(previous_item, Table) and previous_item.is_super_table(): 

474 previous_child = previous_item.value._previous_item() 

475 if ( 

476 previous_child is not None 

477 and not isinstance(previous_child, Whitespace) 

478 and "\n" in previous_item.trivia.trail 

479 and "\n" not in previous_child.trivia.trail 

480 ): 

481 previous_child.trivia.trail += previous_item.trivia.trail 

482 if not ( 

483 isinstance(previous_item, Whitespace) 

484 or ends_with_whitespace(previous_item) 

485 or "\n" in previous_item.trivia.trail 

486 ): 

487 previous_item.trivia.trail += "\n" 

488 

489 self._raw_append(key, item) 

490 if validate and key is not None: 

491 self._validate_out_of_order_table(key) 

492 return self 

493 

494 def _validate_table_candidate(self, current: Table, candidate: Table) -> None: 

495 for k, v in candidate.value.body: 

496 if k is None: 

497 continue 

498 

499 if k in current.value._map: 

500 existing = current.value.item(k) 

501 if isinstance(existing, (Table, AoT)) != isinstance(v, (Table, AoT)): 

502 raise KeyAlreadyPresent(k) 

503 if k.is_dotted() and not ( 

504 isinstance(existing, Table) and existing.is_super_table() 

505 ): 

506 raise TOMLKitError("Redefinition of an existing table") 

507 if isinstance(existing, Table) and isinstance(v, Table): 

508 if not existing.is_super_table() and not v.is_super_table(): 

509 # Both sides are concrete `[table]` definitions of the 

510 # same name; the table is declared twice. 

511 raise KeyAlreadyPresent(k) 

512 # One side is still an implicit/super table, so a duplicate 

513 # (if any) is nested deeper - keep checking the subtree. 

514 self._validate_table_candidate(existing, v) 

515 continue 

516 

517 if not k.is_dotted(): 

518 # Even when the candidate key itself is not dotted, an 

519 # existing dotted key may already use it as a prefix — 

520 # e.g. [a] b.c=1 then [a.b] d=2 (b prefixes b.c). 

521 for existing_key in current.value._map: 

522 if existing_key.is_dotted() and next(iter(existing_key)) == k: 

523 raise TOMLKitError("Redefinition of an existing table") 

524 continue 

525 

526 head = next(iter(k)) 

527 if head in current.value._map: 

528 raise TOMLKitError("Redefinition of an existing table") 

529 

530 def _raw_append(self, key: Key | None, item: Item) -> None: 

531 if key is not None and key in self._map: 

532 current_idx = self._map[key] 

533 if not isinstance(current_idx, tuple): 

534 current_idx = (current_idx,) 

535 

536 current = self._body[current_idx[-1]][1] 

537 if not isinstance(current, Table): 

538 raise KeyAlreadyPresent(key) 

539 

540 self._map[key] = (*current_idx, len(self._body)) 

541 self._out_of_order_keys.add(key) 

542 elif key is not None: 

543 self._map[key] = len(self._body) 

544 

545 self._body.append((key, item)) 

546 if isinstance(item, (Table, AoT)) and key is not None: 

547 self._table_keys.append(key) 

548 

549 if key is not None: 

550 dict.__setitem__(self, key.key, item.value) 

551 

552 def _remove_at(self, idx: int) -> None: 

553 key = self._body[idx][0] 

554 assert key is not None 

555 index = self._map.get(key) 

556 if index is None: 

557 raise NonExistentKey(key) 

558 self._validation_cache.clear() 

559 self._body[idx] = (None, Null()) 

560 

561 if isinstance(index, tuple): 

562 index_list = list(index) 

563 index_list.remove(idx) 

564 if len(index_list) == 1: 

565 self._map[key] = index_list.pop() 

566 else: 

567 self._map[key] = tuple(index_list) 

568 else: 

569 dict.__delitem__(self, key.key) 

570 self._map.pop(key) 

571 

572 def remove(self, key: Key | str) -> Container: 

573 """Remove a key from the container.""" 

574 if not isinstance(key, Key): 

575 key = SingleKey(key) 

576 

577 idx = self._map.pop(key, None) 

578 if idx is None: 

579 raise NonExistentKey(key) 

580 

581 self._validation_cache.clear() 

582 if isinstance(idx, tuple): 

583 for i in idx: 

584 self._body[i] = (None, Null()) 

585 else: 

586 self._body[idx] = (None, Null()) 

587 

588 dict.__delitem__(self, key.key) 

589 

590 return self 

591 

592 def _insert_at(self, idx: int, key: Key | str, item: Any) -> Container: 

593 if idx > len(self._body) - 1: 

594 raise ValueError(f"Unable to insert at position {idx}") 

595 

596 if not isinstance(key, Key): 

597 key = SingleKey(key) 

598 

599 item = _item(item) 

600 

601 if idx > 0: 

602 previous_item = self._body[idx - 1][1] 

603 if not ( 

604 isinstance(previous_item, Whitespace) 

605 or ends_with_whitespace(previous_item) 

606 or isinstance(item, (AoT, Table)) 

607 or "\n" in previous_item.trivia.trail 

608 ): 

609 previous_item.trivia.trail += "\n" 

610 

611 # Increment indices after the current index 

612 for k, v in self._map.items(): 

613 if isinstance(v, tuple): 

614 new_indices = [] 

615 for v_ in v: 

616 if v_ >= idx: 

617 v_ = v_ + 1 

618 

619 new_indices.append(v_) 

620 

621 self._map[k] = tuple(new_indices) 

622 elif v >= idx: 

623 self._map[k] = v + 1 

624 

625 if key in self._map: 

626 current_idx = self._map[key] 

627 if not isinstance(current_idx, tuple): 

628 current_idx = (current_idx,) 

629 self._map[key] = (*current_idx, idx) 

630 self._out_of_order_keys.add(key) 

631 else: 

632 self._map[key] = idx 

633 self._body.insert(idx, (key, item)) 

634 

635 dict.__setitem__(self, key.key, item.value) 

636 

637 return self 

638 

639 def item(self, key: Key | str) -> Item | OutOfOrderTableProxy: 

640 """Get an item for the given key.""" 

641 if not isinstance(key, Key): 

642 key = SingleKey(key) 

643 

644 idx = self._map.get(key) 

645 if idx is None: 

646 raise NonExistentKey(key) 

647 

648 if isinstance(idx, tuple): 

649 # The item we are getting is an out of order table 

650 # so we need a proxy to retrieve the proper objects 

651 # from the parent container 

652 return OutOfOrderTableProxy(self, idx) 

653 

654 return self._body[idx][1] 

655 

656 def last_item(self) -> Item | None: 

657 """Get the last item.""" 

658 if self._body: 

659 return self._body[-1][1] 

660 return None 

661 

662 def as_string(self) -> str: 

663 """Render as TOML string.""" 

664 s = "" 

665 for path, aot in _header_less_aots(self._body): 

666 s += _render_empty_aot(path, aot) 

667 for k, v in self._body: 

668 if k is not None: 

669 if _is_empty_aot(v): 

670 continue 

671 if isinstance(v, Table): 

672 if ( 

673 s.strip(" ") 

674 and not s.strip(" ").endswith("\n") 

675 and "\n" not in v.trivia.indent 

676 ): 

677 s += "\n" 

678 s += self._render_table(k, v) 

679 elif isinstance(v, AoT): 

680 if ( 

681 s.strip(" ") 

682 and not s.strip(" ").endswith("\n") 

683 and "\n" not in v.trivia.indent 

684 ): 

685 s += "\n" 

686 s += self._render_aot(k, v) 

687 else: 

688 s += self._render_simple_item(k, v) 

689 else: 

690 s += self._render_simple_item(k, v) 

691 

692 return s 

693 

694 def _render_table(self, key: Key, table: Table, prefix: str | None = None) -> str: 

695 cur = "" 

696 

697 if table.display_name is not None: 

698 _key = table.display_name 

699 else: 

700 _key = key.as_string() 

701 

702 if prefix is not None: 

703 _key = prefix + "." + _key 

704 

705 header_emitted = _emits_header(key, table) 

706 if header_emitted: 

707 open_, close = "[", "]" 

708 if table.is_aot_element(): 

709 open_, close = "[[", "]]" 

710 

711 newline_in_table_trivia = ( 

712 "\n" if "\n" not in table.trivia.trail and len(table.value) > 0 else "" 

713 ) 

714 cur += ( 

715 f"{table.trivia.indent}" 

716 f"{open_}" 

717 f"{decode(_key)}" 

718 f"{close}" 

719 f"{table.trivia.comment_ws}" 

720 f"{decode(table.trivia.comment)}" 

721 f"{table.trivia.trail}" 

722 f"{newline_in_table_trivia}" 

723 ) 

724 elif table.trivia.indent == "\n": 

725 cur += table.trivia.indent 

726 

727 if header_emitted: 

728 # A super table opens no scope, so its fallbacks belong to -- and 

729 # were already written by -- the nearest enclosing header instead. 

730 for path, aot in _header_less_aots(table.value.body): 

731 cur += _render_empty_aot(path, aot) 

732 for k, v in table.value.body: 

733 if k is not None and _is_empty_aot(v): 

734 continue 

735 elif isinstance(v, Table): 

736 if ( 

737 cur.strip(" ") 

738 and not cur.strip(" ").endswith("\n") 

739 and "\n" not in v.trivia.indent 

740 ): 

741 cur += "\n" 

742 assert k is not None 

743 if v.is_super_table(): 

744 if k.is_dotted() and not key.is_dotted(): 

745 # Dotted key inside table 

746 cur += self._render_table(k, v) 

747 else: 

748 cur += self._render_table(k, v, prefix=_key) 

749 else: 

750 cur += self._render_table(k, v, prefix=_key) 

751 elif isinstance(v, AoT): 

752 if ( 

753 cur.strip(" ") 

754 and not cur.strip(" ").endswith("\n") 

755 and "\n" not in v.trivia.indent 

756 ): 

757 cur += "\n" 

758 assert k is not None 

759 cur += self._render_aot(k, v, prefix=_key) 

760 else: 

761 cur += self._render_simple_item( 

762 k, v, prefix=_key if key.is_dotted() else None 

763 ) 

764 

765 return cur 

766 

767 def _render_aot(self, key: Key, aot: AoT, prefix: str | None = None) -> str: 

768 _key = key.as_string() 

769 if prefix is not None: 

770 _key = prefix + "." + _key 

771 

772 cur = "" 

773 _key = decode(_key) 

774 for table in aot.body: 

775 cur += self._render_aot_table(table, prefix=_key) 

776 

777 return cur 

778 

779 def _render_aot_table(self, table: Table, prefix: str | None = None) -> str: 

780 cur = "" 

781 _key = prefix or "" 

782 open_, close = "[[", "]]" 

783 

784 cur += ( 

785 f"{table.trivia.indent}" 

786 f"{open_}" 

787 f"{decode(_key)}" 

788 f"{close}" 

789 f"{table.trivia.comment_ws}" 

790 f"{decode(table.trivia.comment)}" 

791 f"{table.trivia.trail}" 

792 ) 

793 

794 for path, aot in _header_less_aots(table.value.body): 

795 cur += _render_empty_aot(path, aot) 

796 for k, v in table.value.body: 

797 if k is not None and _is_empty_aot(v): 

798 continue 

799 elif isinstance(v, Table): 

800 assert k is not None 

801 if v.is_super_table(): 

802 if k.is_dotted(): 

803 # Dotted key inside table 

804 cur += self._render_table(k, v) 

805 else: 

806 cur += self._render_table(k, v, prefix=_key) 

807 else: 

808 cur += self._render_table(k, v, prefix=_key) 

809 elif isinstance(v, AoT): 

810 assert k is not None 

811 cur += self._render_aot(k, v, prefix=_key) 

812 else: 

813 cur += self._render_simple_item(k, v) 

814 

815 return cur 

816 

817 def _render_simple_item( 

818 self, key: Key | None, item: Item, prefix: str | None = None 

819 ) -> str: 

820 if key is None: 

821 return item.as_string() 

822 

823 _key = key.as_string() 

824 if prefix is not None: 

825 _key = prefix + "." + _key 

826 

827 return ( 

828 f"{item.trivia.indent}" 

829 f"{decode(_key)}" 

830 f"{key.sep}" 

831 f"{decode(item.as_string())}" 

832 f"{item.trivia.comment_ws}" 

833 f"{decode(item.trivia.comment)}" 

834 f"{item.trivia.trail}" 

835 ) 

836 

837 def __len__(self) -> int: 

838 return dict.__len__(self) 

839 

840 def __iter__(self) -> Iterator[str]: 

841 return iter(dict.keys(self)) 

842 

843 # Dictionary methods 

844 def __getitem__(self, key: Key | str) -> Any: 

845 item = self.item(key) 

846 if isinstance(item, Item) and item.is_boolean(): 

847 return item.value 

848 

849 return item 

850 

851 def __contains__(self, key: object) -> bool: 

852 # Native membership test. The inherited ``MutableMapping.__contains__`` 

853 # resolves the value via ``__getitem__``/``item()`` (and builds a 

854 # ``NonExistentKey`` on every absent key) only to discard it. Resolve the 

855 # key the same way ``item()`` does -- ``str`` becomes a ``SingleKey`` 

856 # (a non-str/non-``Key`` argument still raises ``TypeError``) -- then 

857 # probe ``_map`` directly. For an out-of-order table the proxy is still 

858 # built so its validation runs exactly as before. 

859 if not isinstance(key, Key): 

860 key = SingleKey(key) # type: ignore[arg-type] 

861 idx = self._map.get(key) 

862 if idx is None: 

863 return False 

864 if isinstance(idx, tuple): 

865 # during parsing every fragment append re-probes membership; 

866 # if the validation cache covers exactly these fragments they 

867 # are already known to merge cleanly, so skip rebuilding the 

868 # proxy (which is linear in the number of fragments) 

869 validated, _ = self._validation_cache.get(key, (0, None)) 

870 if not (self._parsed and validated == len(idx)): 

871 OutOfOrderTableProxy(self, idx) 

872 return True 

873 

874 def _item_for_key( 

875 self, key: Key | str, value: object, parent: Item | None = None 

876 ) -> Item: 

877 # Inspect plain strings before conversion, so an explicit String keeps 

878 # the caller's chosen quoting style. 

879 if isinstance(value, str) and not isinstance(value, String): 

880 previous = self.get(key) 

881 if isinstance(previous, String) and previous._t is StringType.SLL: 

882 try: 

883 return String.from_raw(value, StringType.SLL) 

884 except InvalidStringError: 

885 # Some values need the escaping provided by a basic string. 

886 pass 

887 return _item(value, _parent=parent) 

888 

889 def __setitem__(self, key: Key | str, value: Any) -> None: 

890 if key in self: 

891 old_key = next(filter(lambda k: k == key, self._map)) 

892 value = self._item_for_key(key, value) 

893 self._replace(old_key, key, value) 

894 else: 

895 self.append(key, value) 

896 

897 def __delitem__(self, key: Key | str) -> None: 

898 self.remove(key) 

899 

900 def setdefault(self, key: Key | str, default: Any = None) -> Any: 

901 if key not in self: 

902 self[key] = default 

903 return self[key] 

904 

905 def _replace(self, key: Key | str, new_key: Key | str, value: Item) -> None: 

906 if not isinstance(key, Key): 

907 key = SingleKey(key) 

908 

909 idx = self._map.get(key) 

910 if idx is None: 

911 raise NonExistentKey(key) 

912 

913 self._replace_at(idx, new_key, value) 

914 

915 def _replace_at( 

916 self, idx: int | tuple[int, ...], new_key: Key | str, value: Item 

917 ) -> None: 

918 value = _item(value) 

919 self._validation_cache.clear() 

920 

921 if isinstance(idx, tuple): 

922 for i in idx[1:]: 

923 self._body[i] = (None, Null()) 

924 

925 idx = idx[0] 

926 

927 k, v = self._body[idx] 

928 assert k is not None 

929 # A dotted key renders its value inline (e.g. ``a.b = 1``), which is only 

930 # consistent with a super table. When the replacement value renders with 

931 # its own ``[header]`` instead (a non-super table, or an array of tables), 

932 # keeping the dotted key duplicates the prefix onto the header (#524) and 

933 # lets the header swallow following dotted siblings (#542). Drop the dotted 

934 # key so the replacement renders as a plain table/array of tables. 

935 dotted_to_header = k.is_dotted() and ( 

936 isinstance(value, AoT) 

937 or (isinstance(value, Table) and not value.is_super_table()) 

938 ) 

939 # That new header also captures every sibling that renders inline -- plain 

940 # values and dotted keys -- if any still follow it (#513), so it must be 

941 # moved past them, exactly as a value-to-table change already is. 

942 reposition_dotted = dotted_to_header and any( 

943 not isinstance(cur_val, (Null, Whitespace)) 

944 and not ( 

945 isinstance(cur_val, (Table, AoT)) 

946 and (cur_key is None or not cur_key.is_dotted()) 

947 ) 

948 for cur_key, cur_val in self._body[idx + 1 :] 

949 ) 

950 if not isinstance(new_key, Key): 

951 if ( 

952 isinstance(value, (AoT, Table)) != isinstance(v, (AoT, Table)) 

953 or new_key != k.key 

954 or dotted_to_header 

955 ): 

956 new_key = SingleKey(new_key) 

957 else: # Inherit the sep of the old key 

958 new_key = k 

959 

960 del self._map[k] 

961 self._map[new_key] = idx 

962 if new_key != k: 

963 dict.__delitem__(self, k.key) 

964 

965 if ( 

966 isinstance(value, (AoT, Table)) != isinstance(v, (AoT, Table)) 

967 or reposition_dotted 

968 ): 

969 self.remove(k) 

970 if isinstance(value, (AoT, Table)): 

971 # New tables must appear after all entries that render inline: 

972 # plain values and dotted keys (which are super tables). Skip 

973 # those and insert before the first real ``[header]`` so the new 

974 # table cannot swallow a following sibling on round-trip. 

975 for i in range(idx, len(self._body)): 

976 cur_key, cur_val = self._body[i] 

977 if isinstance(cur_val, (AoT, Table)) and not ( 

978 cur_key is not None and cur_key.is_dotted() 

979 ): 

980 self._insert_at(i, new_key, value) 

981 idx = i 

982 break 

983 else: 

984 idx = -1 

985 self.append(new_key, value) 

986 else: 

987 # the replaced table's slot lies in the table region, where a 

988 # plain value would be captured by the preceding table on 

989 # round-trip; append() puts it with the other root-level values 

990 idx = -1 

991 self.append(new_key, value) 

992 else: 

993 # Copying trivia 

994 if not isinstance(value, (Whitespace, AoT)): 

995 value.trivia.indent = v.trivia.indent 

996 value.trivia.comment_ws = value.trivia.comment_ws or v.trivia.comment_ws 

997 value.trivia.comment = value.trivia.comment or v.trivia.comment 

998 value.trivia.trail = v.trivia.trail 

999 self._body[idx] = (new_key, value) 

1000 

1001 if value is not v and hasattr(value, "invalidate_display_name"): 

1002 value.invalidate_display_name() 

1003 

1004 if isinstance(value, Table): 

1005 # Insert a cosmetic new line for tables if: 

1006 # - it does not have it yet OR is not followed by one 

1007 # - it is not the last item, or 

1008 # - The table being replaced has a newline 

1009 result = self._previous_item_with_index() 

1010 assert result is not None 

1011 last, _ = result 

1012 idx = last if idx < 0 else idx 

1013 has_ws = ends_with_whitespace(value) 

1014 replace_has_ws = ( 

1015 isinstance(v, Table) 

1016 and v.value.body 

1017 and isinstance(v.value.body[-1][1], Whitespace) 

1018 ) 

1019 next_ws = idx < last and isinstance(self._body[idx + 1][1], Whitespace) 

1020 if (idx < last or replace_has_ws) and not (next_ws or has_ws): 

1021 value.append(None, Whitespace("\n")) 

1022 

1023 assert isinstance(new_key, Key) 

1024 dict.__setitem__(self, new_key.key, value.value) 

1025 

1026 def __str__(self) -> str: 

1027 return str(self.value) 

1028 

1029 def __repr__(self) -> str: 

1030 return repr(self.value) 

1031 

1032 def __eq__(self, other: object) -> bool: 

1033 if not isinstance(other, dict): 

1034 return NotImplemented 

1035 

1036 return bool(_equal_with_nan(self.value, other)) 

1037 

1038 def _getstate(self, protocol: int) -> tuple[bool]: 

1039 return (self._parsed,) 

1040 

1041 def __reduce__(self) -> tuple[type, tuple[bool], tuple[Any, ...]]: 

1042 return self.__reduce_ex__(2) 

1043 

1044 def __reduce_ex__(self, protocol: int) -> tuple[type, tuple[bool], tuple[Any, ...]]: # type: ignore[override] 

1045 return ( 

1046 self.__class__, 

1047 self._getstate(protocol), 

1048 (self._map, self._body, self._parsed, self._table_keys), 

1049 ) 

1050 

1051 def __setstate__(self, state: tuple[Any, ...]) -> None: 

1052 self._map = state[0] 

1053 self._body = state[1] 

1054 self._parsed = state[2] 

1055 self._table_keys = state[3] 

1056 self._out_of_order_keys = { 

1057 k for k, v in self._map.items() if isinstance(v, tuple) 

1058 } 

1059 

1060 for key, item in self._body: 

1061 if key is not None: 

1062 dict.__setitem__(self, key.key, item.value) 

1063 

1064 def copy(self) -> Self: 

1065 return copy.copy(self) 

1066 

1067 def __copy__(self) -> Self: 

1068 c = self.__class__(self._parsed) 

1069 for k, v in dict.items(self): 

1070 dict.__setitem__(c, k, v) 

1071 

1072 c._body += self.body 

1073 c._map.update(self._map) 

1074 c._out_of_order_keys |= self._out_of_order_keys 

1075 

1076 return c 

1077 

1078 def _previous_item_with_index( 

1079 self, idx: int | None = None, ignore: tuple[type, ...] = (Null,) 

1080 ) -> tuple[int, Item] | None: 

1081 """Find the immediate previous item before index ``idx``""" 

1082 if idx is None or idx > len(self._body): 

1083 idx = len(self._body) 

1084 for i in range(idx - 1, -1, -1): 

1085 v = self._body[i][-1] 

1086 if not isinstance(v, ignore): 

1087 return i, v 

1088 return None 

1089 

1090 def _previous_item( 

1091 self, idx: int | None = None, ignore: tuple[type, ...] = (Null,) 

1092 ) -> Item | None: 

1093 """Find the immediate previous item before index ``idx``. 

1094 If ``idx`` is not given, the last item is returned. 

1095 """ 

1096 prev = self._previous_item_with_index(idx, ignore) 

1097 return prev[-1] if prev else None 

1098 

1099 

1100class OutOfOrderTableProxy(_CustomDict): # type: ignore[type-arg] 

1101 @staticmethod 

1102 def validate( 

1103 container: Container, 

1104 indices: tuple[int, ...], 

1105 temp_container: Container | None = None, 

1106 ) -> Container: 

1107 """Validate out of order tables in the given container""" 

1108 # Append all items to a temp container to see if there is any error. 

1109 # We deep-copy each value before appending: appending a super table 

1110 # merges it in place into a matching one already in temp_container, and 

1111 # those values are the live subtables of `container`. Without the copy 

1112 # the merge would mutate the caller's tables (and corrupt a later 

1113 # validation pass). The container merge itself is now copy-free for 

1114 # speed, so this is where the isolation lives. 

1115 # Passing a previous pass's temp container back in (with the already 

1116 # validated indices stripped from `indices`) resumes the validation 

1117 # incrementally. 

1118 if temp_container is None: 

1119 temp_container = Container(True) 

1120 for i in indices: 

1121 _, item = container._body[i] 

1122 

1123 if isinstance(item, Table): 

1124 for k, v in item.value.body: 

1125 temp_container.append(k, copy.deepcopy(v), validate=True) 

1126 

1127 temp_container._validate_out_of_order_table() 

1128 return temp_container 

1129 

1130 def __init__(self, container: Container, indices: tuple[int, ...]) -> None: 

1131 self._container = container 

1132 self._internal_container = Container(True) 

1133 self._tables: list[Table] = [] 

1134 self._tables_map: dict[Key, list[int]] = {} 

1135 

1136 for i in indices: 

1137 _, _item = self._container._body[i] 

1138 

1139 if isinstance(_item, Table): 

1140 self._tables.append(_item) 

1141 table_idx = len(self._tables) - 1 

1142 for k, v in _item.value.body: 

1143 merged = self._merge_aot_fragment(k, v) 

1144 if merged is None: 

1145 self._internal_container._raw_append(k, v) 

1146 else: 

1147 v = merged 

1148 key_indices = self._tables_map.setdefault(k, []) # type: ignore[arg-type] 

1149 if table_idx not in key_indices: 

1150 key_indices.append(table_idx) 

1151 if k is not None: 

1152 dict.__setitem__(self, k.key, v) 

1153 

1154 self._internal_container._validate_out_of_order_table() 

1155 

1156 def _merge_aot_fragment(self, key: Key | None, item: Item) -> AoT | None: 

1157 """ 

1158 Merge an array-of-tables fragment from a later out-of-order table part. 

1159 

1160 An AoT whose elements are split across out-of-order parts of the same 

1161 table arrives here once per part; ``_raw_append`` only knows how to 

1162 chain duplicate ``Table`` parts and would raise ``KeyAlreadyPresent``. 

1163 The fragments are presented as a new merged ``AoT`` referencing the 

1164 live element tables, without mutating either fragment (the parts keep 

1165 rendering their own elements). 

1166 

1167 Returns the merged ``AoT``, or ``None`` if this is not such a fragment. 

1168 """ 

1169 internal = self._internal_container 

1170 if key is None or not isinstance(item, AoT) or key not in internal._map: 

1171 return None 

1172 idx = internal._map[key] 

1173 if isinstance(idx, tuple): 

1174 # A tuple index means the key already resolved to several body 

1175 # positions, which here only happens for a degenerate collision 

1176 # (e.g. a non-AoT part sharing the key). Three or more genuine AoT 

1177 # fragments do not reach this branch: each later fragment merges 

1178 # into the single growing AoT below, so ``idx`` stays an int. 

1179 return None 

1180 existing = internal._body[idx][1] 

1181 if not isinstance(existing, AoT): 

1182 return None 

1183 

1184 merged = AoT([*existing.body, *item.body], parsed=True) 

1185 internal._body[idx] = (internal._body[idx][0], merged) 

1186 dict.__setitem__(internal, key.key, merged.value) 

1187 return merged 

1188 

1189 def unwrap(self) -> dict[str, Any]: 

1190 return self._internal_container.unwrap() 

1191 

1192 @property 

1193 def value(self) -> dict[str, Any]: 

1194 return self._internal_container.value 

1195 

1196 def __str__(self) -> str: 

1197 return str(self.value) 

1198 

1199 def __repr__(self) -> str: 

1200 return repr(self.value) 

1201 

1202 def __contains__(self, key: object) -> bool: 

1203 # Native membership test. The inherited ``MutableMapping.__contains__`` 

1204 # resolves the value via ``__getitem__`` (and builds a ``NonExistentKey`` 

1205 # on every absent key) only to discard it. Probe the internal container 

1206 # directly -- the same predicate ``__getitem__`` already uses -- which is 

1207 # itself a native ``_map`` lookup that still rebuilds the proxy for an 

1208 # out-of-order key so its validation runs exactly as before. 

1209 return key in self._internal_container 

1210 

1211 def __getitem__(self, key: Key | str) -> Any: 

1212 if key not in self._internal_container: 

1213 raise NonExistentKey(key) 

1214 

1215 return self._internal_container[key] 

1216 

1217 def __setitem__(self, key: Key | str, value: Any) -> None: 

1218 from .items import item as _item_fn 

1219 

1220 def _is_table_or_aot(it: Any) -> bool: 

1221 return isinstance(_item_fn(it), (Table, AoT)) 

1222 

1223 _key: Key = key if isinstance(key, Key) else SingleKey(key) 

1224 

1225 if _key in self._tables_map: 

1226 # Overwrite the first occurrence and remove this key from later parts. 

1227 map_indices = self._tables_map[_key] 

1228 while len(map_indices) > 1: 

1229 table = self._tables[map_indices.pop()] 

1230 del table[key] 

1231 if not table: 

1232 self._remove_table(table) 

1233 old_value = self._tables[map_indices[0]][key] 

1234 if _is_table_or_aot(old_value) and not _is_table_or_aot(value): 

1235 # Remove the entry from the map and set value again. 

1236 del self._tables[map_indices[0]][key] 

1237 del self._tables_map[_key] 

1238 self[key] = value 

1239 return 

1240 self._tables[map_indices[0]][key] = value 

1241 elif self._tables: 

1242 table_index = 0 

1243 if not _is_table_or_aot(value): # if the value is a plain value 

1244 for i, table in enumerate(self._tables): 

1245 # find the first table that allows plain values 

1246 if any(not _is_table_or_aot(v) for _, v in table.items()): 

1247 table_index = i 

1248 break 

1249 else: 

1250 # No part holds a plain value yet, so the chosen part must 

1251 # start rendering its own ``[key]`` header. Prefer a part 

1252 # that is not a super table (it already renders that header): 

1253 # turning a header-less super part concrete here would emit a 

1254 # second, duplicate header next to an existing concrete part 

1255 # and produce TOML that no longer parses. 

1256 for i, table in enumerate(self._tables): 

1257 if not table.is_super_table(): 

1258 table_index = i 

1259 break 

1260 self._tables[table_index][key] = value 

1261 self._tables_map[_key] = [table_index] 

1262 else: 

1263 self._container[key] = value 

1264 

1265 self._internal_container[key] = value 

1266 if key is not None: 

1267 dict.__setitem__(self, key, value) 

1268 

1269 def _remove_table(self, table: Table) -> None: 

1270 """Remove table from the parent container""" 

1271 self._tables.remove(table) 

1272 for idx, body_item in enumerate(self._container._body): 

1273 if body_item[1] is table: 

1274 self._container._remove_at(idx) 

1275 break 

1276 

1277 def __delitem__(self, key: Key | str) -> None: 

1278 _key: Key = key if isinstance(key, Key) else SingleKey(key) 

1279 if _key not in self._tables_map: 

1280 raise NonExistentKey(key) 

1281 

1282 for i in reversed(self._tables_map[_key]): 

1283 table = self._tables[i] 

1284 del table[key] 

1285 if not table and len(self._tables) > 1: 

1286 self._remove_table(table) 

1287 

1288 del self._tables_map[_key] 

1289 del self._internal_container[key] 

1290 if key is not None: 

1291 dict.__delitem__(self, key) 

1292 

1293 def __iter__(self) -> Iterator[str]: 

1294 return iter(dict.keys(self)) 

1295 

1296 def __len__(self) -> int: 

1297 return dict.__len__(self) 

1298 

1299 def setdefault(self, key: Key | str, default: Any = None) -> Any: 

1300 if key not in self: 

1301 self[key] = default 

1302 return self[key] 

1303 

1304 

1305def ends_with_whitespace(it: Any) -> bool: 

1306 """Returns ``True`` if the given item ``it`` is a ``Table`` or ``AoT`` object 

1307 ending with a ``Whitespace``. 

1308 """ 

1309 if isinstance(it, Whitespace): 

1310 return True 

1311 if isinstance(it, Table): 

1312 previous = it.value._previous_item() 

1313 return previous is not None and ends_with_whitespace(previous) 

1314 return isinstance(it, AoT) and len(it) > 0 and ends_with_whitespace(it[-1]) 

1315 

1316 

1317def _equal_with_nan(left: Any, right: Any) -> bool: 

1318 if isinstance(left, dict) and isinstance(right, dict): 

1319 if left.keys() != right.keys(): 

1320 return False 

1321 return all(_equal_with_nan(left[k], right[k]) for k in left) 

1322 

1323 if isinstance(left, list) and isinstance(right, list): 

1324 if len(left) != len(right): 

1325 return False 

1326 return all(_equal_with_nan(l, r) for l, r in zip(left, right)) # noqa: E741 

1327 

1328 if isinstance(left, float) and isinstance(right, float): 

1329 if math.isnan(left) and math.isnan(right): 

1330 return True 

1331 

1332 return bool(left == right)