_core.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. from __future__ import annotations
  2. from collections.abc import Iterable, Iterator, Sequence
  3. from enum import Enum
  4. from typing import Any, Callable, ClassVar, Generic, Protocol, TypeVar
  5. from urllib.parse import unquote, urldefrag, urljoin
  6. from attrs import evolve, field
  7. from rpds import HashTrieMap, HashTrieSet, List
  8. from referencing import exceptions
  9. from referencing._attrs import frozen
  10. from referencing.typing import URI, Anchor as AnchorType, D, Mapping, Retrieve
  11. EMPTY_UNCRAWLED: HashTrieSet[URI] = HashTrieSet()
  12. EMPTY_PREVIOUS_RESOLVERS: List[URI] = List()
  13. class _Unset(Enum):
  14. """
  15. What sillyness...
  16. """
  17. SENTINEL = 1
  18. _UNSET = _Unset.SENTINEL
  19. class _MaybeInSubresource(Protocol[D]):
  20. def __call__(
  21. self,
  22. segments: Sequence[int | str],
  23. resolver: Resolver[D],
  24. subresource: Resource[D],
  25. ) -> Resolver[D]: ...
  26. def _detect_or_error(contents: D) -> Specification[D]:
  27. if not isinstance(contents, Mapping):
  28. raise exceptions.CannotDetermineSpecification(contents)
  29. jsonschema_dialect_id = contents.get("$schema") # type: ignore[reportUnknownMemberType]
  30. if not isinstance(jsonschema_dialect_id, str):
  31. raise exceptions.CannotDetermineSpecification(contents)
  32. from referencing.jsonschema import specification_with
  33. return specification_with(jsonschema_dialect_id)
  34. def _detect_or_default(
  35. default: Specification[D],
  36. ) -> Callable[[D], Specification[D]]:
  37. def _detect(contents: D) -> Specification[D]:
  38. if not isinstance(contents, Mapping):
  39. return default
  40. jsonschema_dialect_id = contents.get("$schema") # type: ignore[reportUnknownMemberType]
  41. if jsonschema_dialect_id is None:
  42. return default
  43. from referencing.jsonschema import specification_with
  44. return specification_with(
  45. jsonschema_dialect_id, # type: ignore[reportUnknownArgumentType]
  46. default=default,
  47. )
  48. return _detect
  49. class _SpecificationDetector:
  50. def __get__(
  51. self,
  52. instance: Specification[D] | None,
  53. cls: type[Specification[D]],
  54. ) -> Callable[[D], Specification[D]]:
  55. if instance is None:
  56. return _detect_or_error
  57. else:
  58. return _detect_or_default(instance)
  59. @frozen
  60. class Specification(Generic[D]):
  61. """
  62. A specification which defines referencing behavior.
  63. The various methods of a `Specification` allow for varying referencing
  64. behavior across JSON Schema specification versions, etc.
  65. """
  66. #: A short human-readable name for the specification, used for debugging.
  67. name: str
  68. #: Find the ID of a given document.
  69. id_of: Callable[[D], URI | None]
  70. #: Retrieve the subresources of the given document (without traversing into
  71. #: the subresources themselves).
  72. subresources_of: Callable[[D], Iterable[D]]
  73. #: While resolving a JSON pointer, conditionally enter a subresource
  74. #: (if e.g. we have just entered a keyword whose value is a subresource)
  75. maybe_in_subresource: _MaybeInSubresource[D]
  76. #: Retrieve the anchors contained in the given document.
  77. _anchors_in: Callable[
  78. [Specification[D], D],
  79. Iterable[AnchorType[D]],
  80. ] = field(alias="anchors_in")
  81. #: An opaque specification where resources have no subresources
  82. #: nor internal identifiers.
  83. OPAQUE: ClassVar[Specification[Any]]
  84. #: Attempt to discern which specification applies to the given contents.
  85. #:
  86. #: May be called either as an instance method or as a class method, with
  87. #: slightly different behavior in the following case:
  88. #:
  89. #: Recall that not all contents contains enough internal information about
  90. #: which specification it is written for -- the JSON Schema ``{}``,
  91. #: for instance, is valid under many different dialects and may be
  92. #: interpreted as any one of them.
  93. #:
  94. #: When this method is used as an instance method (i.e. called on a
  95. #: specific specification), that specification is used as the default
  96. #: if the given contents are unidentifiable.
  97. #:
  98. #: On the other hand when called as a class method, an error is raised.
  99. #:
  100. #: To reiterate, ``DRAFT202012.detect({})`` will return ``DRAFT202012``
  101. #: whereas the class method ``Specification.detect({})`` will raise an
  102. #: error.
  103. #:
  104. #: (Note that of course ``DRAFT202012.detect(...)`` may return some other
  105. #: specification when given a schema which *does* identify as being for
  106. #: another version).
  107. #:
  108. #: Raises:
  109. #:
  110. #: `CannotDetermineSpecification`
  111. #:
  112. #: if the given contents don't have any discernible
  113. #: information which could be used to guess which
  114. #: specification they identify as
  115. detect = _SpecificationDetector()
  116. def __repr__(self) -> str:
  117. return f"<Specification name={self.name!r}>"
  118. def anchors_in(self, contents: D):
  119. """
  120. Retrieve the anchors contained in the given document.
  121. """
  122. return self._anchors_in(self, contents)
  123. def create_resource(self, contents: D) -> Resource[D]:
  124. """
  125. Create a resource which is interpreted using this specification.
  126. """
  127. return Resource(contents=contents, specification=self)
  128. Specification.OPAQUE = Specification(
  129. name="opaque",
  130. id_of=lambda contents: None,
  131. subresources_of=lambda contents: [],
  132. anchors_in=lambda specification, contents: [],
  133. maybe_in_subresource=lambda segments, resolver, subresource: resolver,
  134. )
  135. @frozen
  136. class Resource(Generic[D]):
  137. r"""
  138. A document (deserialized JSON) with a concrete interpretation under a spec.
  139. In other words, a Python object, along with an instance of `Specification`
  140. which describes how the document interacts with referencing -- both
  141. internally (how it refers to other `Resource`\ s) and externally (how it
  142. should be identified such that it is referenceable by other documents).
  143. """
  144. contents: D
  145. _specification: Specification[D] = field(alias="specification")
  146. @classmethod
  147. def from_contents(
  148. cls,
  149. contents: D,
  150. default_specification: (
  151. type[Specification[D]] | Specification[D]
  152. ) = Specification,
  153. ) -> Resource[D]:
  154. """
  155. Create a resource guessing which specification applies to the contents.
  156. Raises:
  157. `CannotDetermineSpecification`
  158. if the given contents don't have any discernible
  159. information which could be used to guess which
  160. specification they identify as
  161. """
  162. specification = default_specification.detect(contents)
  163. return specification.create_resource(contents=contents)
  164. @classmethod
  165. def opaque(cls, contents: D) -> Resource[D]:
  166. """
  167. Create an opaque `Resource` -- i.e. one with opaque specification.
  168. See `Specification.OPAQUE` for details.
  169. """
  170. return Specification.OPAQUE.create_resource(contents=contents)
  171. def id(self) -> URI | None:
  172. """
  173. Retrieve this resource's (specification-specific) identifier.
  174. """
  175. id = self._specification.id_of(self.contents)
  176. if id is None:
  177. return
  178. return id.rstrip("#")
  179. def subresources(self) -> Iterable[Resource[D]]:
  180. """
  181. Retrieve this resource's subresources.
  182. """
  183. return (
  184. Resource.from_contents(
  185. each,
  186. default_specification=self._specification,
  187. )
  188. for each in self._specification.subresources_of(self.contents)
  189. )
  190. def anchors(self) -> Iterable[AnchorType[D]]:
  191. """
  192. Retrieve this resource's (specification-specific) identifier.
  193. """
  194. return self._specification.anchors_in(self.contents)
  195. def pointer(self, pointer: str, resolver: Resolver[D]) -> Resolved[D]:
  196. """
  197. Resolve the given JSON pointer.
  198. Raises:
  199. `exceptions.PointerToNowhere`
  200. if the pointer points to a location not present in the document
  201. """
  202. if not pointer:
  203. return Resolved(contents=self.contents, resolver=resolver)
  204. contents = self.contents
  205. segments: list[int | str] = []
  206. for segment in unquote(pointer[1:]).split("/"):
  207. if isinstance(contents, Sequence):
  208. segment = int(segment)
  209. else:
  210. segment = segment.replace("~1", "/").replace("~0", "~")
  211. try:
  212. contents = contents[segment] # type: ignore[reportUnknownArgumentType]
  213. except LookupError as lookup_error:
  214. error = exceptions.PointerToNowhere(ref=pointer, resource=self)
  215. raise error from lookup_error
  216. segments.append(segment)
  217. last = resolver
  218. resolver = self._specification.maybe_in_subresource(
  219. segments=segments,
  220. resolver=resolver,
  221. subresource=self._specification.create_resource(contents),
  222. )
  223. if resolver is not last:
  224. segments = []
  225. return Resolved(contents=contents, resolver=resolver) # type: ignore[reportUnknownArgumentType]
  226. def _fail_to_retrieve(uri: URI):
  227. raise exceptions.NoSuchResource(ref=uri)
  228. @frozen
  229. class Registry(Mapping[URI, Resource[D]]):
  230. r"""
  231. A registry of `Resource`\ s, each identified by their canonical URIs.
  232. Registries store a collection of in-memory resources, and optionally
  233. enable additional resources which may be stored elsewhere (e.g. in a
  234. database, a separate set of files, over the network, etc.).
  235. They also lazily walk their known resources, looking for subresources
  236. within them. In other words, subresources contained within any added
  237. resources will be retrievable via their own IDs (though this discovery of
  238. subresources will be delayed until necessary).
  239. Registries are immutable, and their methods return new instances of the
  240. registry with the additional resources added to them.
  241. The ``retrieve`` argument can be used to configure retrieval of resources
  242. dynamically, either over the network, from a database, or the like.
  243. Pass it a callable which will be called if any URI not present in the
  244. registry is accessed. It must either return a `Resource` or else raise a
  245. `NoSuchResource` exception indicating that the resource does not exist
  246. even according to the retrieval logic.
  247. """
  248. _resources: HashTrieMap[URI, Resource[D]] = field(
  249. default=HashTrieMap(),
  250. converter=HashTrieMap.convert, # type: ignore[reportGeneralTypeIssues]
  251. alias="resources",
  252. )
  253. _anchors: HashTrieMap[tuple[URI, str], AnchorType[D]] = HashTrieMap()
  254. _uncrawled: HashTrieSet[URI] = EMPTY_UNCRAWLED
  255. _retrieve: Retrieve[D] = field(default=_fail_to_retrieve, alias="retrieve")
  256. def __getitem__(self, uri: URI) -> Resource[D]:
  257. """
  258. Return the (already crawled) `Resource` identified by the given URI.
  259. """
  260. try:
  261. return self._resources[uri.rstrip("#")]
  262. except KeyError:
  263. raise exceptions.NoSuchResource(ref=uri) from None
  264. def __iter__(self) -> Iterator[URI]:
  265. """
  266. Iterate over all crawled URIs in the registry.
  267. """
  268. return iter(self._resources)
  269. def __len__(self) -> int:
  270. """
  271. Count the total number of fully crawled resources in this registry.
  272. """
  273. return len(self._resources)
  274. def __rmatmul__(
  275. self,
  276. new: Resource[D] | Iterable[Resource[D]],
  277. ) -> Registry[D]:
  278. """
  279. Create a new registry with resource(s) added using their internal IDs.
  280. Resources must have a internal IDs (e.g. the :kw:`$id` keyword in
  281. modern JSON Schema versions), otherwise an error will be raised.
  282. Both a single resource as well as an iterable of resources works, i.e.:
  283. * ``resource @ registry`` or
  284. * ``[iterable, of, multiple, resources] @ registry``
  285. which -- again, assuming the resources have internal IDs -- is
  286. equivalent to calling `Registry.with_resources` as such:
  287. .. code:: python
  288. registry.with_resources(
  289. (resource.id(), resource) for resource in new_resources
  290. )
  291. Raises:
  292. `NoInternalID`
  293. if the resource(s) in fact do not have IDs
  294. """
  295. if isinstance(new, Resource):
  296. new = (new,)
  297. resources = self._resources
  298. uncrawled = self._uncrawled
  299. for resource in new:
  300. id = resource.id()
  301. if id is None:
  302. raise exceptions.NoInternalID(resource=resource)
  303. uncrawled = uncrawled.insert(id)
  304. resources = resources.insert(id, resource)
  305. return evolve(self, resources=resources, uncrawled=uncrawled)
  306. def __repr__(self) -> str:
  307. size = len(self)
  308. pluralized = "resource" if size == 1 else "resources"
  309. if self._uncrawled:
  310. uncrawled = len(self._uncrawled)
  311. if uncrawled == size:
  312. summary = f"uncrawled {pluralized}"
  313. else:
  314. summary = f"{pluralized}, {uncrawled} uncrawled"
  315. else:
  316. summary = f"{pluralized}"
  317. return f"<Registry ({size} {summary})>"
  318. def get_or_retrieve(self, uri: URI) -> Retrieved[D, Resource[D]]:
  319. """
  320. Get a resource from the registry, crawling or retrieving if necessary.
  321. May involve crawling to find the given URI if it is not already known,
  322. so the returned object is a `Retrieved` object which contains both the
  323. resource value as well as the registry which ultimately contained it.
  324. """
  325. resource = self._resources.get(uri)
  326. if resource is not None:
  327. return Retrieved(registry=self, value=resource)
  328. registry = self.crawl()
  329. resource = registry._resources.get(uri)
  330. if resource is not None:
  331. return Retrieved(registry=registry, value=resource)
  332. try:
  333. resource = registry._retrieve(uri)
  334. except (
  335. exceptions.CannotDetermineSpecification,
  336. exceptions.NoSuchResource,
  337. ):
  338. raise
  339. except Exception as error:
  340. raise exceptions.Unretrievable(ref=uri) from error
  341. else:
  342. registry = registry.with_resource(uri, resource)
  343. return Retrieved(registry=registry, value=resource)
  344. def remove(self, uri: URI):
  345. """
  346. Return a registry with the resource identified by a given URI removed.
  347. """
  348. if uri not in self._resources:
  349. raise exceptions.NoSuchResource(ref=uri)
  350. return evolve(
  351. self,
  352. resources=self._resources.remove(uri),
  353. uncrawled=self._uncrawled.discard(uri),
  354. anchors=HashTrieMap(
  355. (k, v) for k, v in self._anchors.items() if k[0] != uri
  356. ),
  357. )
  358. def anchor(self, uri: URI, name: str):
  359. """
  360. Retrieve a given anchor from a resource which must already be crawled.
  361. """
  362. value = self._anchors.get((uri, name))
  363. if value is not None:
  364. return Retrieved(value=value, registry=self)
  365. registry = self.crawl()
  366. value = registry._anchors.get((uri, name))
  367. if value is not None:
  368. return Retrieved(value=value, registry=registry)
  369. resource = self[uri]
  370. canonical_uri = resource.id()
  371. if canonical_uri is not None:
  372. value = registry._anchors.get((canonical_uri, name))
  373. if value is not None:
  374. return Retrieved(value=value, registry=registry)
  375. if "/" in name:
  376. raise exceptions.InvalidAnchor(
  377. ref=uri,
  378. resource=resource,
  379. anchor=name,
  380. )
  381. raise exceptions.NoSuchAnchor(ref=uri, resource=resource, anchor=name)
  382. def contents(self, uri: URI) -> D:
  383. """
  384. Retrieve the (already crawled) contents identified by the given URI.
  385. """
  386. return self[uri].contents
  387. def crawl(self) -> Registry[D]:
  388. """
  389. Crawl all added resources, discovering subresources.
  390. """
  391. resources = self._resources
  392. anchors = self._anchors
  393. uncrawled = [(uri, resources[uri]) for uri in self._uncrawled]
  394. while uncrawled:
  395. uri, resource = uncrawled.pop()
  396. id = resource.id()
  397. if id is not None:
  398. uri = urljoin(uri, id)
  399. resources = resources.insert(uri, resource)
  400. for each in resource.anchors():
  401. anchors = anchors.insert((uri, each.name), each)
  402. uncrawled.extend((uri, each) for each in resource.subresources())
  403. return evolve(
  404. self,
  405. resources=resources,
  406. anchors=anchors,
  407. uncrawled=EMPTY_UNCRAWLED,
  408. )
  409. def with_resource(self, uri: URI, resource: Resource[D]):
  410. """
  411. Add the given `Resource` to the registry, without crawling it.
  412. """
  413. return self.with_resources([(uri, resource)])
  414. def with_resources(
  415. self,
  416. pairs: Iterable[tuple[URI, Resource[D]]],
  417. ) -> Registry[D]:
  418. r"""
  419. Add the given `Resource`\ s to the registry, without crawling them.
  420. """
  421. resources = self._resources
  422. uncrawled = self._uncrawled
  423. for uri, resource in pairs:
  424. # Empty fragment URIs are equivalent to URIs without the fragment.
  425. # TODO: Is this true for non JSON Schema resources? Probably not.
  426. uri = uri.rstrip("#")
  427. uncrawled = uncrawled.insert(uri)
  428. resources = resources.insert(uri, resource)
  429. return evolve(self, resources=resources, uncrawled=uncrawled)
  430. def with_contents(
  431. self,
  432. pairs: Iterable[tuple[URI, D]],
  433. **kwargs: Any,
  434. ) -> Registry[D]:
  435. r"""
  436. Add the given contents to the registry, autodetecting when necessary.
  437. """
  438. return self.with_resources(
  439. (uri, Resource.from_contents(each, **kwargs))
  440. for uri, each in pairs
  441. )
  442. def combine(self, *registries: Registry[D]) -> Registry[D]:
  443. """
  444. Combine together one or more other registries, producing a unified one.
  445. """
  446. if registries == (self,):
  447. return self
  448. resources = self._resources
  449. anchors = self._anchors
  450. uncrawled = self._uncrawled
  451. retrieve = self._retrieve
  452. for registry in registries:
  453. resources = resources.update(registry._resources)
  454. anchors = anchors.update(registry._anchors)
  455. uncrawled = uncrawled.update(registry._uncrawled)
  456. if registry._retrieve is not _fail_to_retrieve:
  457. if registry._retrieve is not retrieve is not _fail_to_retrieve:
  458. raise ValueError( # noqa: TRY003
  459. "Cannot combine registries with conflicting retrieval "
  460. "functions.",
  461. )
  462. retrieve = registry._retrieve
  463. return evolve(
  464. self,
  465. anchors=anchors,
  466. resources=resources,
  467. uncrawled=uncrawled,
  468. retrieve=retrieve,
  469. )
  470. def resolver(self, base_uri: URI = "") -> Resolver[D]:
  471. """
  472. Return a `Resolver` which resolves references against this registry.
  473. """
  474. return Resolver(base_uri=base_uri, registry=self)
  475. def resolver_with_root(self, resource: Resource[D]) -> Resolver[D]:
  476. """
  477. Return a `Resolver` with a specific root resource.
  478. """
  479. uri = resource.id() or ""
  480. return Resolver(
  481. base_uri=uri,
  482. registry=self.with_resource(uri, resource),
  483. )
  484. #: An anchor or resource.
  485. AnchorOrResource = TypeVar("AnchorOrResource", AnchorType[Any], Resource[Any])
  486. @frozen
  487. class Retrieved(Generic[D, AnchorOrResource]):
  488. """
  489. A value retrieved from a `Registry`.
  490. """
  491. value: AnchorOrResource
  492. registry: Registry[D]
  493. @frozen
  494. class Resolved(Generic[D]):
  495. """
  496. A reference resolved to its contents by a `Resolver`.
  497. """
  498. contents: D
  499. resolver: Resolver[D]
  500. @frozen
  501. class Resolver(Generic[D]):
  502. """
  503. A reference resolver.
  504. Resolvers help resolve references (including relative ones) by
  505. pairing a fixed base URI with a `Registry`.
  506. This object, under normal circumstances, is expected to be used by
  507. *implementers of libraries* built on top of `referencing` (e.g. JSON Schema
  508. implementations or other libraries resolving JSON references),
  509. not directly by end-users populating registries or while writing
  510. schemas or other resources.
  511. References are resolved against the base URI, and the combined URI
  512. is then looked up within the registry.
  513. The process of resolving a reference may itself involve calculating
  514. a *new* base URI for future reference resolution (e.g. if an
  515. intermediate resource sets a new base URI), or may involve encountering
  516. additional subresources and adding them to a new registry.
  517. """
  518. _base_uri: URI = field(alias="base_uri")
  519. _registry: Registry[D] = field(alias="registry")
  520. _previous: List[URI] = field(default=List(), repr=False, alias="previous")
  521. def lookup(self, ref: URI) -> Resolved[D]:
  522. """
  523. Resolve the given reference to the resource it points to.
  524. Raises:
  525. `exceptions.Unresolvable`
  526. or a subclass thereof (see below) if the reference isn't
  527. resolvable
  528. `exceptions.NoSuchAnchor`
  529. if the reference is to a URI where a resource exists but
  530. contains a plain name fragment which does not exist within
  531. the resource
  532. `exceptions.PointerToNowhere`
  533. if the reference is to a URI where a resource exists but
  534. contains a JSON pointer to a location within the resource
  535. that does not exist
  536. """
  537. if ref.startswith("#"):
  538. uri, fragment = self._base_uri, ref[1:]
  539. else:
  540. uri, fragment = urldefrag(urljoin(self._base_uri, ref))
  541. try:
  542. retrieved = self._registry.get_or_retrieve(uri)
  543. except exceptions.NoSuchResource:
  544. raise exceptions.Unresolvable(ref=ref) from None
  545. except exceptions.Unretrievable as error:
  546. raise exceptions.Unresolvable(ref=ref) from error
  547. if fragment.startswith("/"):
  548. resolver = self._evolve(registry=retrieved.registry, base_uri=uri)
  549. return retrieved.value.pointer(pointer=fragment, resolver=resolver)
  550. if fragment:
  551. retrieved = retrieved.registry.anchor(uri, fragment)
  552. resolver = self._evolve(registry=retrieved.registry, base_uri=uri)
  553. return retrieved.value.resolve(resolver=resolver)
  554. resolver = self._evolve(registry=retrieved.registry, base_uri=uri)
  555. return Resolved(contents=retrieved.value.contents, resolver=resolver)
  556. def in_subresource(self, subresource: Resource[D]) -> Resolver[D]:
  557. """
  558. Create a resolver for a subresource (which may have a new base URI).
  559. """
  560. id = subresource.id()
  561. if id is None:
  562. return self
  563. return evolve(self, base_uri=urljoin(self._base_uri, id))
  564. def dynamic_scope(self) -> Iterable[tuple[URI, Registry[D]]]:
  565. """
  566. In specs with such a notion, return the URIs in the dynamic scope.
  567. """
  568. for uri in self._previous:
  569. yield uri, self._registry
  570. def _evolve(self, base_uri: URI, **kwargs: Any):
  571. """
  572. Evolve, appending to the dynamic scope.
  573. """
  574. previous = self._previous
  575. if self._base_uri and (not previous or base_uri != self._base_uri):
  576. previous = previous.push_front(self._base_uri)
  577. return evolve(self, base_uri=base_uri, previous=previous, **kwargs)
  578. @frozen
  579. class Anchor(Generic[D]):
  580. """
  581. A simple anchor in a `Resource`.
  582. """
  583. name: str
  584. resource: Resource[D]
  585. def resolve(self, resolver: Resolver[D]):
  586. """
  587. Return the resource for this anchor.
  588. """
  589. return Resolved(contents=self.resource.contents, resolver=resolver)