1 Commits

Author SHA1 Message Date
cclecle
f443623a4a no working work 2025-10-12 22:46:15 +02:00
19 changed files with 1148 additions and 216 deletions

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>{{project_name}}</name>
<name>anytraverser</name>
<comment></comment>
<projects>
</projects>

View File

@@ -1,10 +1,10 @@
# pyChaChaDummyProject (c) by chacha
# anytraverser (c) by chacha
#
# pyChaChaDummyProject is licensed under a
# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Unported License.
# anytraverser is licensed under a
# PolyForm Noncommercial License 1.0.0
#
# You should have received a copy of the license along with this
# work. If not, see <https://creativecommons.org/licenses/by-nc-sa/4.0/>.
# work. If not, see <https://polyformproject.org/licenses/noncommercial/1.0.0>.
FROM debian:bookworm-slim

8
Jenkinsfile vendored
View File

@@ -1,10 +1,10 @@
// pyChaChaDummyProject (c) by chacha
// anytraverser (c) by chacha
//
// pyChaChaDummyProject is licensed under a
// Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Unported License.
// anytraverser is licensed under a
// PolyForm Noncommercial License 1.0.0
//
// You should have received a copy of the license along with this
// work. If not, see <https://creativecommons.org/licenses/by-nc-sa/4.0/>.
// work. If not, see <https://polyformproject.org/licenses/noncommercial/1.0.0>.
import groovy.xml.XmlUtil
import static javax.xml.xpath.XPathConstants.*

View File

@@ -1,175 +1,131 @@
# License
# PolyForm Noncommercial License 1.0.0
# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
<https://polyformproject.org/licenses/noncommercial/1.0.0>
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
## Acceptance
**Using Creative Commons Public Licenses**
In order to get any license under these terms, you must agree
to them as both strict obligations and conditions to all
your licenses.
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
## Copyright License
* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
The licensor grants you a copyright license for the
software to do everything you might do with the software
that would otherwise infringe the licensor's copyright
in it for any permitted purpose. However, you may
only distribute the software according to [Distribution
License](#distribution-license) and make changes or new works
based on the software according to [Changes and New Works
License](#changes-and-new-works-license).
* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensors permission is not necessary for any reasonfor example, because of any applicable exception or limitation to copyrightthen that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
## Distribution License
## Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License
The licensor grants you an additional copyright license
to distribute copies of the software. Your license
to distribute covers distributing the software with
changes and new works permitted by [Changes and New Works
License](#changes-and-new-works-license).
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
## Notices
### Section 1 Definitions.
You must ensure that anyone who gets a copy of any part of
the software from you also gets a copy of these terms or the
URL for them above, as well as copies of any plain-text lines
beginning with `Required Notice:` that the licensor provided
with the software. For example:
a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
## Changes and New Works License
c. __BY-NC-SA Compatible License__ means a license listed at [creativecommons.org/compatiblelicenses](http://creativecommons.org/compatiblelicenses), approved by Creative Commons as essentially the equivalent of this Public License.
The licensor grants you an additional copyright license to
make changes and new works based on the software for any
permitted purpose.
d. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
## Patent License
e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
The licensor grants you a patent license for the software that
covers patent claims the licensor can license, or becomes able
to license, that you would infringe by using the software.
f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
## Noncommercial Purposes
g. __License Elements__ means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike.
Any noncommercial purpose is a permitted purpose.
h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
## Personal Uses
i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
Personal use for research, experiment, and testing for
the benefit of public knowledge, personal study, private
entertainment, hobby projects, amateur pursuits, or religious
observance, without any anticipated commercial application,
is use for a permitted purpose.
j. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
## Noncommercial Organizations
k. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
Use by any charitable organization, educational institution,
public research organization, public safety or health
organization, environmental protection organization,
or government institution is use for a permitted purpose
regardless of the source of funding or obligations resulting
from the funding.
l. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
## Fair Use
m. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
You may have "fair use" rights for the software under the
law. These terms do not limit them.
n. __You__ means the individual or entity exercising the Licensed Rights under this Public License. __Your__ has a corresponding meaning.
## No Other Rights
### Section 2 Scope.
These terms do not allow you to sublicense or transfer any of
your licenses to anyone else, or prevent the licensor from
granting licenses to anyone else. These terms do not imply
any other licenses.
a. ___License grant.___
## Patent Defense
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
If you make any written claim that the software infringes or
contributes to infringement of any patent, your patent license
for the software granted under these terms ends immediately. If
your company makes such a claim, your patent license ends
immediately for work on behalf of your company.
A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
## Violations
B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
The first time you are notified in writing that you have
violated any of these terms, or done anything with the software
not covered by your licenses, your licenses can nonetheless
continue if you come into full compliance with these terms,
and take practical steps to correct past violations, within
32 days of receiving notice. Otherwise, all your licenses
end immediately.
2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
## No Liability
3. __Term.__ The term of this Public License is specified in Section 6(a).
***As far as the law allows, the software comes as is, without
any warranty or condition, and the licensor will not be liable
to you for any damages arising out of these terms or the use
or nature of the software, under any kind of legal claim.***
4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
## Definitions
5. __Downstream recipients.__
The **licensor** is the individual or entity offering these
terms, and the **software** is the software the licensor makes
available under these terms.
A. __Offer from the Licensor Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
**You** refers to the individual or entity agreeing to these
terms.
B. __Additional offer from the Licensor Adapted Material.__ Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapters License You apply.
**Your company** is any legal entity, sole proprietorship,
or other kind of organization that you work for, plus all
organizations that have control over, are under the control of,
or are under common control with that organization. **Control**
means ownership of substantially all the assets of an entity,
or the power to direct its management and policies by vote,
contract, or otherwise. Control can be direct or indirect.
C. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
**Your licenses** are all the licenses granted to you for the
software under these terms.
6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. ___Other rights.___
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
### Section 3 License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
a. ___Attribution.___
1. If You Share the Licensed Material (including in modified form), You must:
A. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
b. ___ShareAlike.___
In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
1. The Adapters License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
### Section 4 Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
### Section 5 Disclaimer of Warranties and Limitation of Liability.
a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__
b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
### Section 6 Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
### Section 7 Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
### Section 8 Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
>
> Creative Commons may be contacted at creativecommons.org
**Use** means anything you do with the software requiring one
of your licenses.

View File

@@ -4,7 +4,7 @@
![](https://chacha.ddns.net/jenkins/buildStatus/icon?job={{repository}}-{{branch}}&build=0&config=coverage)
![](https://chacha.ddns.net/jenkins/buildStatus/icon?job={{repository}}-{{branch}}&build=0&config=maintainability)
![](https://chacha.ddns.net/jenkins/buildStatus/icon?job={{repository}}-{{branch}}&build=0&config=quality)
![](https://chacha.ddns.net/jenkins/buildStatus/icon?subject=licence&status=CC%20BY-NC-SA%204.0&color=teal)
![](https://chacha.ddns.net/jenkins/buildStatus/icon?subject=licence&status=PolyForm-Noncommercial-1.0.0&color=teal)
![](docs-static/Library.jpg)

View File

@@ -1,10 +1,10 @@
# pyChaChaDummyProject (c) by chacha
# anytraverser (c) by chacha
#
# pyChaChaDummyProject is licensed under a
# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Unported License.
# anytraverser is licensed under a
# PolyForm Noncommercial License 1.0.0
#
# You should have received a copy of the license along with this
# work. If not, see <https://creativecommons.org/licenses/by-nc-sa/4.0/>.
# work. If not, see <https://polyformproject.org/licenses/noncommercial/1.0.0>.
[build-system]
requires = ["setuptools>=63", "wheel", "setuptools_scm"]
@@ -18,7 +18,7 @@ name = "anytraverser"
description = "Stream either Data or Annotations; hook into each step with Triggers to validate, transform, and build objects."
readme = "README.md"
requires-python = ">=3.11"
keywords = ["chacha","chacha","template","anytraverser"]
keywords = ["chacha","anytraverser"]
license = { file = "LICENSE.md" }
authors = [
@@ -31,6 +31,7 @@ classifiers = [
"Development Status :: 4 - Beta",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.11",
"License :: PolyForm-Noncommercial-1.0.0",
]
dependencies = [
'importlib-metadata; python_version<"3.9"',

View File

@@ -1,14 +1,15 @@
# anytraverser (c) by chacha
#
# anytraverser is licensed under a
# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Unported License.
# anytraverser is licensed under a
# PolyForm Noncommercial License 1.0.0
#
# You should have received a copy of the license along with this
# work. If not, see <https://creativecommons.org/licenses/by-nc-sa/4.0/>.
# work. If not, see <https://polyformproject.org/licenses/noncommercial/1.0.0>.
"""
Main module __init__ file.
"""
from .__metadata__ import __version__, __Summuary__, __Name__
from .test_module import test_function
from .walkers.annotation_walker import AnnotationWalker
from .triggers.test_trigger import DataValidation

View File

@@ -1,10 +1,10 @@
# anytraverser (c) by chacha
#
# anytraverser is licensed under a
# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Unported License.
# anytraverser is licensed under a
# PolyForm Noncommercial License 1.0.0
#
# You should have received a copy of the license along with this
# work. If not, see <https://creativecommons.org/licenses/by-nc-sa/4.0/>.
# work. If not, see <https://polyformproject.org/licenses/noncommercial/1.0.0>.
"""
Metadata module module
@@ -15,7 +15,7 @@ import warnings
try: # pragma: no cover
__version__ = version("anytraverser")
except PackageNotFoundError: # pragma: no cover
except PackageNotFoundError: # pragma: no cover
warnings.warn("can not read __version__, assuming local test context, setting it to ?.?.?")
__version__ = "?.?.?"

101
src/anytraverser/context.py Normal file
View File

@@ -0,0 +1,101 @@
from typing import Any, Self, Optional, ChainMap, FrozenSet, Mapping
from enum import Enum, auto
class NodeRole(Enum):
ELEM = auto()
KEY = auto()
VAL = auto()
UNION = auto()
BRANCH = auto()
ANNO = auto()
ARG = auto()
class AnnotationWalkerCtx:
def __init__(
self,
origin: Any,
args: Any,
layer: int,
parent: Optional[Self] = None,
allowed_types: set[type, ...] = frozenset(),
allowed_annotations: dict[str, Any] = {},
):
self.__origin = origin
self.args = args
self.__layer = layer
self.__parent = parent
self.__allowed_types: set[type, ...] = allowed_types
self.__allowed_annotations: dict[str, Any] = allowed_annotations
self.__ext: dict[Any, ChainMap] = {} # per-trigger namespaces (lazy)
# NEW: edge routing metadata (walker sets; triggers read)
self.__node_role: NodeRole | None = NodeRole.ELEM
self.__edge_token: Any | None = None # index/key/branch-id/etc.
self.__arg_index: int | None = None # which schema arg of the parent this child is
@property
def origin(self) -> Any:
return self.__origin
@property
def layer(self) -> int:
return self.__layer
@property
def parent(self) -> Self:
return self.__parent
@property
def allowed_types(self) -> FrozenSet[type]:
return self.__allowed_types
@property
def allowed_annotations(self) -> Mapping[str, Any]:
return self.__allowed_annotations
# NEW: read-only edge metadata for routing inside triggers
@property
def node_role(self) -> NodeRole | None:
return self.__node_role
@property
def edge_token(self) -> Any | None:
return self.__edge_token
@property
def arg_index(self) -> int | None:
return self.__arg_index
def ns(self, owner: Any) -> ChainMap:
"""
A per-trigger overlay namespace that inherits from parent ctx.
Use as: bag = ctx.ns(self); bag['whatever'] = ...
Lookups fall back to parent's bag automatically.
"""
if owner in self.__ext:
return self.__ext[owner]
# Determine the parent chain for this owner
parent_chain = ()
if self.__parent is not None and hasattr(self.__parent, "_AnnotationWalkerCtx__ext"):
parent_map = self.__parent._AnnotationWalkerCtx__ext.get(owner) # access private attr intentionally
if isinstance(parent_map, ChainMap):
# IMPORTANT: preserve the whole chain (not the ChainMap object as a single mapping)
parent_chain = tuple(parent_map.maps)
elif isinstance(parent_map, dict):
parent_chain = (parent_map,)
else:
parent_chain = ()
# Build a new ChainMap whose first map is this node's local overlay
cm = ChainMap({}, *parent_chain)
self.__ext[owner] = cm
return cm
def _set_edge(self, *, role: str | None, token: Any | None, arg_index: int | None) -> None:
self.__node_role = role
self.__edge_token = token
self.__arg_index = arg_index

View File

View File

@@ -0,0 +1,6 @@
class UnsupportedFieldType(RuntimeError):
pass
class IncompletelyAnnotatedField(RuntimeError):
pass

View File

@@ -0,0 +1,69 @@
from typing import Self, Any, Optional
from dataclasses import dataclass
from .context import AnnotationWalkerCtx
@dataclass(frozen=True)
class TriggerResult:
# If provided, children won't be walked and this value is returned.
replace_with: Any | None = None
# If true, skip walking children but don't replace current node value.
skip_children: bool = False
# If provided, walker will restart processing with the given value
restart_with: Any | None = None # NEW
@staticmethod
def passthrough() -> Self:
return TriggerResult()
@staticmethod
def replace(value: Any) -> Self:
return TriggerResult(replace_with=value, skip_children=True)
@staticmethod
def skip() -> Self:
return TriggerResult(skip_children=True)
@staticmethod
def restart(value: Any) -> Self:
return TriggerResult(restart_with=value)
class AnnotationTrigger:
def init_trigger(self) -> None:
pass
def process_enter(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
return None
def process_annotated(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
return None
def process_union(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
return None
def process_dict(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
return None
def process_tuple(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
return None
def process_list(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
return None
def process_set(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
return None
def process_unknown(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
return None
def process_simple(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
return None
def process_exit(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
return None
def end_trigger(self, ctx: Optional[AnnotationWalkerCtx]) -> None:
pass

View File

@@ -1,43 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# anytraverser (c) by chacha
#
# anytraverser is licensed under a
# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Unported License.
#
# You should have received a copy of the license along with this
# work. If not, see <https://creativecommons.org/licenses/by-nc-sa/4.0/>.
"""Phasellus tellus lectus, volutpat eu dapibus ut, suscipit vel augue.
Tips:
Aliquam non leo vel libero sagittis viverra. Quisque lobortis nunc sit amet augue euismod laoreet.
Note:
Maecenas volutpat porttitor pretium. Aliquam suscipit quis nisi non imperdiet.
Note:
Vivamus et efficitur lorem, eget imperdiet tortor. Integer vel interdum sem.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING: # Only imports the below statements during type checking
pass
def test_function(testvar: int) -> int:
""" A test function that return testvar+1 and print "Hello world !"
Proin eget sapien eget ipsum efficitur mollis nec ac nibh.
Note:
Morbi id lectus maximus, condimentum nunc eget, porta felis. In tristique velit tortor.
Args:
testvar: any integer
Returns:
testvar+1
"""
print("Hello world !")
return testvar+1

View File

View File

@@ -0,0 +1,181 @@
from typing import Any, Union
from types import UnionType
from copy import copy, deepcopy
from ..protocols import AnnotationTrigger, TriggerResult
from ..context import AnnotationWalkerCtx, NodeRole
from ..errors import UnsupportedFieldType, IncompletelyAnnotatedField
from pprint import pprint
class DataValidation(AnnotationTrigger):
def __init__(self, value: Any) -> None:
self._root = value
def init_trigger(self) -> None:
self._data_id = 0
def _get_new_id(self) -> int:
self._data_id = self._data_id + 1
return self._data_id
def process_enter(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
print("")
print(f"process_enter ({id(ctx)}): {ctx.node_role} / {ctx.edge_token}")
# print(f"arg_index: {ctx.arg_index}")
ns = ctx.ns(self)
if not ctx.parent:
print("= ROOT NODE =")
ns["cursors"] = [self._root]
ns["next_cursors"] = []
ns["current_branch_id"] = self._get_new_id()
ns["current_leaf_id"] = self._get_new_id()
ns["leaf_status"] = dict()
ns["leaf_status"][ns["current_leaf_id"]] = True
ns["leak_origin_branch"] = dict()
ns["leak_origin_branch"][ns["current_leaf_id"]] = ns["current_branch_id"]
else:
pns = ctx.parent.ns(self)
ns["cursors"] = pns["next_cursors"]
if ctx.node_role == NodeRole.BRANCH:
ns["current_leaf_id"] = self._get_new_id()
ns["leaf_status"][ns["current_leaf_id"]] = True
ns["leak_origin_branch"][ns["current_leaf_id"]] = ns["current_branch_id"]
print(f"- NEW leaf ({ns['current_leaf_id']}), from branch ({ns['current_branch_id']})")
print(f"DATA to check: {ns['cursors'] }")
def process_union(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
print(f"process_union ({id(ctx)})")
ns = ctx.ns(self)
ns["current_branch_id"] = self._get_new_id()
print(f"+ NEW branch ({ns['current_branch_id']})")
def process_list(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
print(f"process_list ({id(ctx)})")
ns = ctx.ns(self)
ns["next_cursors"] = ns["cursors"]
return
# print(b["cursor"])
remaining = []
for val in ns["candidates"]:
if not isinstance(val, list):
print(f"!!!!!!!!!!!!!!! NOT A LIST !! ({val})")
ns["branch_is_valid"] = False
remaining.append(val)
ns["candidates"].clear()
ns["candidates"].extend(remaining)
if issubclass(ctx.origin, UnionType):
path_id = self._get_new_id()
ns["branch_next_cursor"][path_id] = ns["cursor"]
ns["branch_nex_candidates"][path_id] = [type(elem_t) for elem_t in ns["cursor"]]
ns["branch_is_valid"][path_id] = ns["branch_is_valid"]
def process_simple(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
print(f"??? process_allowed ({id(ctx)})")
ns = ctx.ns(self)
return
remaining = [elem for elem in ns["cursors"] if not isinstance(elem, ctx.origin)]
print(f"remaining: {remaining}")
ns["candidates"].clear()
ns["candidates"].extend(remaining)
def process_exit(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
print(f"!!! process_exit ({id(ctx)})")
ns = ctx.ns(self)
print("")
def end_trigger(self, ctx: AnnotationWalkerCtx):
# print("end_trigger")
ns = ctx.ns(self)
def process_dict(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
# print(f"process_dict {ctx}")
ns = ctx.ns(self)
def process_tuple(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
# print(f"process_tuple {ctx}")
ns = ctx.ns(self)
def process_set(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
# print(f"process_set {ctx}")
ns = ctx.ns(self)
def process_unknown(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
# print(f"process_unknown {ctx}")
ns = ctx.ns(self)
raise RuntimeError(f"Unknown type: {ctx.origin}")
def process_annotated(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
# print(f"process_annotated {ctx}")
pass
class LAMSchemaValidation(AnnotationTrigger):
def init_trigger(self) -> None:
print(f"Initializing {self.__class__.__name__}")
def process_annotated(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
print("process_annotated")
print(ctx.origin)
print(ctx.args)
if len(ctx.args) != 2:
raise UnsupportedFieldType("Annotated[T,x] requires 2 parameters")
if ctx.parent is not None:
raise UnsupportedFieldType("Annotated[T,x] is only supported as parent annotation")
return None
def process_union(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
print("process_union")
print(ctx.args)
if (len(ctx.args) != 2) or (type(None) not in list(ctx.args)):
raise UnsupportedFieldType("Union[] is only supported to implement Optional[] (takes 2 parameters, including None)")
return None
def process_dict(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
print("process_dict")
if len(ctx.args) != 2:
raise IncompletelyAnnotatedField(f"Dict Annotation requires 2 inner definitions: {ctx.origin}")
if not ctx.args[0] in ctx.allowed_types:
raise IncompletelyAnnotatedField(f"Dict Key must be simple builtin: {ctx.origin}")
return None
def process_tuple(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
print("process_tuple")
if len(ctx.args) == 0:
raise IncompletelyAnnotatedField(f"Annotation requires inner definition: {ctx.origin}")
return None
def process_list(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
print("process_list")
if len(ctx.args) == 0:
raise IncompletelyAnnotatedField(f"Annotation requires inner definition: {ctx.origin}")
return None
def process_set(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
print("process_set")
if len(ctx.args) == 0:
raise IncompletelyAnnotatedField(f"Annotation requires inner definition: {ctx.origin}")
return None
def process_allowed(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
print("process_allowed")
if ctx.origin is type(None) or ctx.origin is None:
if ctx.parent is None or not (ctx.parent.origin is Union or ctx.parent.origin is UnionType):
raise IncompletelyAnnotatedField(f"None is only accepted with Union, to implement Optional[]")
return None
def process_exit(self, ctx: AnnotationWalkerCtx) -> None | TriggerResult:
print(f"process_exit: {ctx.origin}")
return None
def end_trigger(self, ctx: AnnotationWalkerCtx):
pass

View File

@@ -0,0 +1,389 @@
from typing import Any, Union, Optional, get_origin, get_args, Annotated
from types import UnionType
from ..protocols import AnnotationTrigger
from ..context import AnnotationWalkerCtx
class SchemaValidationError(TypeError):
def __init__(self, path: tuple[Any, ...], msg: str):
dotted = "".join(f"[{p}]" if isinstance(p, int) else (f".{p}" if path and i else str(p)) for i, p in enumerate(path)) or "<root>"
super().__init__(f"{dotted}: {msg}")
self.path = path
class HorizontalValidationTrigger(AnnotationTrigger):
def __init__(
self,
value: Any,
*,
strict_bool: bool = False,
collect_all: bool = True,
union_summary_max_per_branch: int = 3, # NEW
show_branch_types: bool = True, # NEW
):
self._root_value = value
self._strict_bool = strict_bool
self._collect_all = collect_all
self._union_summary_max = union_summary_max_per_branch
self._show_branch_types = show_branch_types
self._seeded = False
self._id_counter = 0
# ---------- utilities ----------
# ---------- utilities ----------
def _mk_cand(self, value: Any, path: tuple[Any, ...]):
cid = self._id_counter
self._id_counter += 1
return {"id": cid, "value": value, "path": path}
def _spawn_from(self, bag, parent_cand: dict, value: Any, path: tuple[Any, ...]):
nc = self._mk_cand(value, path)
# Inherit union_roots map from parent (create if missing)
roots = dict(parent_cand.get("union_roots", {}))
nc["union_roots"] = roots
# If we are in a union branch, ensure current scope is stamped
if "__union_branch_id" in bag and "__union_state_ref" in bag:
cur_scope = bag.get("__union_scope_id")
if cur_scope is not None:
roots.setdefault(cur_scope, parent_cand.get("union_roots", {}).get(cur_scope, parent_cand["id"]))
return nc
def _bag(self, ctx: AnnotationWalkerCtx):
bag = ctx.ns(self)
local = bag.maps[0]
parent_bag = ctx.parent.ns(self) if ctx.parent is not None else None
# (existing seeding & routing)...
# ------------- NEW: inherit enclosing union flags to all descendants -------------
if parent_bag is not None:
for k in ("__union_state_ref", "__union_branch_id", "__union_scope_id"):
if (k in parent_bag) and (k not in local):
local[k] = parent_bag[k]
# ------------- If immediate child of a Union (branch) -------------
if ctx.parent is not None and ctx.parent.origin is UnionType and ctx.edge_role == "branch":
ubag = ctx.parent.ns(self)
branches = ubag.setdefault("union_branches_state", {})
bid = ctx.edge_token
bstate = branches.setdefault(bid, {"failed_ids": set(), "errors": []})
local["errors"] = bstate["errors"]
local["__union_branch_id"] = bid
local["__union_state_ref"] = ubag
# keep current union scope id (from parent union node)
local["__union_scope_id"] = ubag.get("__union_scope_id")
# STAMP union_roots for all candidates at branch entry
stamped = []
cur_scope = local.get("__union_scope_id")
for c in local.get("candidates", []):
c2 = dict(c)
roots = dict(c2.get("union_roots", {}))
if cur_scope is not None:
roots.setdefault(cur_scope, roots.get(cur_scope, c2["id"]))
c2["union_roots"] = roots
stamped.append(c2)
local["candidates"] = stamped
return bag
def _mark_branch_fail(self, bag, cand: dict):
if "__union_branch_id" in bag and "__union_state_ref" in bag:
bid = bag["__union_branch_id"]
uref = bag["__union_state_ref"]
branches = uref.setdefault("union_branches_state", {})
bstate = branches.setdefault(bid, {"failed_ids": set(), "errors": []})
root_id = cand.get("union_cid", cand["id"])
bstate["failed_ids"].add(root_id)
def _err(self, bag, cand, msg: str):
"""
Record an error. If we are inside a union branch, attach (cid, scope) so the
outer union can attribute it correctly to its branch/candidate.
"""
e = SchemaValidationError(cand["path"], msg)
# Find nearest union scope (walk ChainMap parents if needed)
def nearest_union_scope(b):
if "__union_scope_id" in b:
return b["__union_scope_id"]
# ChainMap.get() already searches parents; use get() with a sentinel
sentinel = object()
v = b.get("__union_scope_id", sentinel)
return None if v is sentinel else v
in_union_branch = ("__union_branch_id" in bag) and ("__union_state_ref" in bag)
if in_union_branch:
# union-root candidate id for attribution (propagated by spawn_from / branch entry)
root_id = cand.get("union_cid", cand["id"])
scope = nearest_union_scope(bag)
# Branch-local error bucket lives under union state
uref = bag["__union_state_ref"]
bid = bag["__union_branch_id"]
branches = uref.setdefault("union_branches_state", {})
bstate = branches.setdefault(bid, {"failed_ids": set(), "errors": []})
bstate["failed_ids"].add(root_id)
bstate["errors"].append({"cid": root_id, "scope": scope, "err": e})
return
# Outside any union branch: add to global errors (and optional fail-fast)
bag["errors"].append(e)
if not self._collect_all:
raise e
def _check_leaf(self, bag, cand: dict, T: type):
v = cand["value"]
if T is type(None):
if v is not None:
self._err(bag, cand, "expected None")
return
if self._strict_bool and T is bool and type(v) is not bool:
self._err(bag, cand, f"expected bool, got {type(v).__name__}")
return
if v is None or not isinstance(v, T):
got = "None" if v is None else type(v).__name__
self._err(bag, cand, f"expected {T.__name__}, got {got}")
# ---------- entry hooks (seed pending; validate leaves; no aggregation here) ----------
def process_allowed(self, ctx: AnnotationWalkerCtx):
bag = self._bag(ctx)
T = ctx.origin
for cand in bag.get("candidates", []):
self._check_leaf(bag, cand, T)
def process_list(self, ctx: AnnotationWalkerCtx):
bag = self._bag(ctx)
cands = bag.get("candidates", [])
if len(ctx.args) != 1:
for cand in cands:
self._err(bag, cand, "List[T] requires 1 argument")
return
pending = []
for cand in cands:
v = cand["value"]
if not isinstance(v, list):
self._err(bag, cand, f"expected list, got {type(v).__name__}")
continue
base = cand["path"]
for i in range(len(v)):
pending.append(self._spawn_from(bag, cand, v[i], base + (i,)))
bag["pending_elem"] = pending
def process_tuple(self, ctx: AnnotationWalkerCtx):
bag = self._bag(ctx)
cands = bag.get("candidates", [])
vararg = len(ctx.args) == 2 and ctx.args[1] is Ellipsis
if vararg:
pending = []
for cand in cands:
v = cand["value"]
if not isinstance(v, tuple):
self._err(bag, cand, f"expected tuple, got {type(v).__name__}")
continue
base = cand["path"]
for i in range(len(v)):
pending.append(self._spawn_from(bag, cand, v[i], base + (i,)))
bag["pending_elem"] = pending
else:
arity = len(ctx.args)
slots: dict[int, list] = {}
for cand in cands:
v = cand["value"]
if not isinstance(v, tuple):
self._err(bag, cand, f"expected tuple, got {type(v).__name__}")
continue
if len(v) != arity:
self._err(bag, cand, f"expected tuple len {arity}, got {len(v)}")
continue
base = cand["path"]
for i, elem in enumerate(v):
slots.setdefault(i, []).append(self._spawn_from(bag, cand, elem, base + (i,)))
for i, group in slots.items():
bag[f"pending_arg_{i}"] = group
def process_set(self, ctx: AnnotationWalkerCtx):
bag = self._bag(ctx)
cands = bag.get("candidates", [])
if len(ctx.args) != 1:
for cand in cands:
self._err(bag, cand, "Set[T]/FrozenSet[T] requires 1 argument")
return
pending = []
for cand in cands:
v = cand["value"]
if not isinstance(v, (set, frozenset)):
self._err(bag, cand, f"expected set/frozenset, got {type(v).__name__}")
continue
base = cand["path"]
for e in v:
pending.append(self._spawn_from(bag, cand, e, base + ("<elem>",)))
bag["pending_elem"] = pending
def process_dict(self, ctx: AnnotationWalkerCtx):
bag = self._bag(ctx)
cands = bag.get("candidates", [])
if len(ctx.args) != 2:
for cand in cands:
self._err(bag, cand, "Dict[K,V] requires 2 arguments")
return
pkeys, pvals = [], []
for cand in cands:
v = cand["value"]
if not isinstance(v, dict):
self._err(bag, cand, f"expected dict, got {type(v).__name__}")
continue
base = cand["path"]
for k, val in v.items():
pkeys.append(self._spawn_from(bag, cand, k, base + ("<key>",)))
pvals.append(self._spawn_from(bag, cand, val, base + (k,)))
bag["pending_key"] = pkeys
bag["pending_val"] = pvals
def process_annotated(self, ctx: AnnotationWalkerCtx):
# No checks here; inner T will validate routed candidates.
self._bag(ctx)
def process_union(self, ctx: AnnotationWalkerCtx):
bag = self._bag(ctx)
cands = bag.get("candidates", [])
# Preserve enclosing union scope id (if any) so inner unions can bubble to it
if "__outer_union_scope_id" not in bag and "__union_scope_id" in bag:
bag["__outer_union_scope_id"] = bag["__union_scope_id"]
bag["union_candidate_ids"] = [c["id"] for c in cands]
bag.setdefault("union_branches_state", {}) # bid -> {"failed_ids": set(), "errors": []}
bag["union_branch_labels"] = [self._pretty_type(a) for a in ctx.args]
# Set THIS union's scope id (distinct from the preserved outer scope)
bag["__union_scope_id"] = id(ctx)
# ---------- exit (aggregation only) ----------
def process_exit(self, ctx: AnnotationWalkerCtx):
if ctx.origin is not UnionType:
return None
bag = ctx.ns(self)
root_errors = bag.get("errors", [])
branches = bag.get("union_branches_state", {})
cand_ids = bag.get("union_candidate_ids", [])
labels = bag.get("union_branch_labels", [])
scope_id = bag.get("__union_scope_id")
outer_scope_id = bag.get("__outer_union_scope_id") # preserved from parent (if any)
# Build per-branch error map for THIS union scope
per_branch_errors: dict[int, dict[int, list[SchemaValidationError]]] = {}
for bid, state in branches.items():
berrs = state.get("errors", [])
m: dict[int, list[SchemaValidationError]] = {}
for item in berrs:
if isinstance(item, dict):
if item.get("scope") != scope_id:
continue
cid = item.get("cid")
err = item.get("err")
if cid is not None and isinstance(err, SchemaValidationError):
m.setdefault(cid, []).append(err)
elif isinstance(item, SchemaValidationError):
for cid in state.get("failed_ids", set()):
m.setdefault(cid, []).append(item)
# de-dupe per cid
for cid, lst in m.items():
seen = set()
uniq = []
for e in lst:
key = (e.path, str(e))
if key not in seen:
seen.add(key)
uniq.append(e)
m[cid] = uniq
per_branch_errors[bid] = m
# Decision: pass if ANY branch has zero scoped errors
for cid in cand_ids:
branch_pass = any(len(per_branch_errors.get(bid, {}).get(cid, [])) == 0 for bid in branches.keys())
if branch_pass:
continue
# --- Bubble to enclosing union if we are inside one (i.e., this union is in a branch) ---
if ("__union_state_ref" in bag) and ("__union_branch_id" in bag):
uref = bag["__union_state_ref"] # enclosing union node bag
up_bid = bag["__union_branch_id"] # which enclosing branch we are in
up_branches = uref.setdefault("union_branches_state", {})
up_state = up_branches.setdefault(up_bid, {"failed_ids": set(), "errors": []})
up_scope = uref.get("__union_scope_id")
# Find local candidate to recover outer root via union_roots
cands_here = bag.get("candidates", [])
lc = next((c for c in cands_here if c["id"] == cid), None)
if lc is not None and outer_scope_id is not None:
outer_root = lc.get("union_roots", {}).get(outer_scope_id, lc["id"])
else:
outer_root = cid
up_state["failed_ids"].add(outer_root)
up_state["errors"].append(
{
"cid": outer_root,
"scope": up_scope,
"err": SchemaValidationError((), "mismatch"),
}
)
# Build readable per-branch summary at THIS union site
cands_here = bag.get("candidates", [])
path = next((c["path"] for c in cands_here if c["id"] == cid), ())
lines = ["no union branch matched; tried:"]
for bid, state in branches.items():
label = labels[bid] if bid < len(labels) else f"branch {bid}"
these = per_branch_errors.get(bid, {}).get(cid, [])
if not these:
lines.append(f" - {label}: mismatch")
continue
N = getattr(self, "_union_summary_max", 3)
shown = these[:N]
lines.append(f" - {label}: {len(these)} issue(s)")
for e in shown:
lines.append(f" - {e}")
if len(these) > N:
lines.append(f" - (+{len(these) - N} more)")
root_errors.append(SchemaValidationError(path, "\n".join(lines)))
return None
def end_trigger(self, ctx: Optional[AnnotationWalkerCtx]):
if ctx is None:
return
errors = ctx.ns(self).get("errors", [])
if errors:
# Raise them together; swap for your preferred error carrier if needed
raise ExceptionGroup("schema validation failed", errors)
# --- pretty type for messages (best-effort) ---
def _pretty_type(self, t: Any) -> str:
origin = get_origin(t) or t
args = get_args(t)
try:
if origin is UnionType or origin is Union:
return " | ".join(self._pretty_type(a) for a in args)
if origin in (list, tuple, set, frozenset, dict, Annotated):
if origin is dict and len(args) == 2:
return f"dict[{self._pretty_type(args[0])}, {self._pretty_type(args[1])}]"
if origin in (list, set, frozenset) and len(args) == 1:
name = "list" if origin is list else ("set" if origin is set else "frozenset")
return f"{name}[{self._pretty_type(args[0])}]"
if origin is tuple:
if len(args) == 2 and args[1] is Ellipsis:
return f"tuple[{self._pretty_type(args[0])}, ...]"
return f"tuple[{', '.join(self._pretty_type(a) for a in args)}]"
if origin is Annotated and args:
return f"Annotated[{self._pretty_type(args[0])}, ...]"
if isinstance(origin, type):
return origin.__name__
return str(t)
except Exception:
return repr(t)

View File

View File

@@ -0,0 +1,273 @@
import typing
from typing import Any, Union, Optional, List, Dict, Tuple, Set, Annotated, Callable, get_origin, get_args
import types
from types import NoneType, UnionType
from frozendict import frozendict
from ..protocols import AnnotationTrigger, TriggerResult
from ..context import AnnotationWalkerCtx, NodeRole
class AnnotationWalker:
DEFAULT_ALLOWED_TYPES = frozenset({str, int, float, complex, bool, bytes, NoneType})
DEFAULT_ALLOWED_ANNOTATIONS: dict[str, Any] = frozendict(
{
"Union": Union,
"Optional": Optional,
"List": List,
"Dict": Dict,
"Tuple": Tuple,
"Set": Set,
# "FrozenSet": FrozenSet,
"Annotated": Annotated,
# builtins:
"int": int,
"str": str,
"float": float,
"bool": bool,
"complex": complex,
"bytes": bytes,
"None": type(None),
"list": list,
"dict": dict,
"set": set,
# "frozenset": frozenset,
"tuple": tuple,
}
)
def __init__(self, ann: Any, triggers: tuple[AnnotationTrigger, ...], **kwargs):
if not triggers:
raise RuntimeError("AnnotationWalker requires trigger(s)")
# Normalize triggers into instances
insts: list[AnnotationTrigger] = []
for t in triggers if isinstance(triggers, tuple) else (triggers,):
if isinstance(t, AnnotationTrigger):
insts.append(t)
elif isinstance(t, type) and issubclass(t, AnnotationTrigger):
insts.append(t())
else:
raise RuntimeError(f"Unsupported trigger: {t}")
self._triggers = tuple(insts)
# Allowed types / annotations
atypes = set(type(self).DEFAULT_ALLOWED_TYPES)
if "ex_allowed_types" in kwargs:
atypes.update(kwargs["ex_allowed_types"])
self._allowed_types = frozenset(atypes)
annots = dict(type(self).DEFAULT_ALLOWED_ANNOTATIONS)
if "ex_allowed_annotations" in kwargs:
annots.update(kwargs["ex_allowed_annotations"])
self._allowed_annotations = frozendict(annots)
# Annotation can be string
self.__ann = ann
if isinstance(ann, str):
self.__ann = eval(ann, {"__builtins__": {}}, self._allowed_annotations)
def run(self) -> TriggerResult:
for t in self._triggers:
t.init_trigger()
self.root_ctx = None
self._walk(self.__ann, None)
for t in self._triggers:
t.end_trigger(self.root_ctx)
# --- Helpers ---
def _new_ctx(self, origin, args, layer, parent):
return AnnotationWalkerCtx(origin, args, layer, parent, self._allowed_types, self._allowed_annotations)
def _apply_triggers(self, method: str, ctx: AnnotationWalkerCtx) -> TriggerResult:
final = TriggerResult.passthrough()
for t in self._triggers:
res = getattr(t, method)(ctx)
if not res:
continue
if res.restart_with is not None:
return res # short-circuit on restart
if res.replace_with is not None:
final = TriggerResult.replace(res.replace_with)
if res.skip_children:
final = TriggerResult(
replace_with=final.replace_with,
skip_children=True,
)
return final
def _apply_exits(self, ctx: AnnotationWalkerCtx) -> Any | None:
"""
Run exits in order: type-specific (if implemented) then generic `process_exit`.
Only `replace_with` is honored at exit; last `replace_with` wins.
"""
final = None
for t in self._triggers:
res = t.process_exit(ctx)
if res and (res.replace_with is not None):
final = res.replace_with
return final
def _handle_with_triggers(
self,
trigger_name: str,
ctx: AnnotationWalkerCtx,
args_handler: Callable[[AnnotationWalkerCtx], Any] | None = None,
) -> Any:
# ENTER
self._apply_triggers("process_enter", ctx)
# SPECIFIC
res = self._apply_triggers(trigger_name, ctx)
if res.restart_with is not None:
return self._walk(res.restart_with, ctx.parent)
if res.replace_with is not None:
exit_val = self._apply_exits(ctx)
return exit_val if exit_val is not None else res.replace_with
node_value = None
if not res.skip_children:
if args_handler:
node_value = args_handler(ctx)
else:
# DEFAULT: descend once per schema arg; mark as positional arg
node_value = tuple(self._walk_child(a, ctx, arg_index=i, role="arg", token=i) for i, a in enumerate(ctx.args))
# EXIT
exit_val = self._apply_exits(ctx)
return exit_val if exit_val is not None else node_value
def _walk_args_tuple(self, ctx: AnnotationWalkerCtx):
# Tuple[T, ...] (variadic): one schema child, mark role='elem'
if len(ctx.args) == 2 and ctx.args[1] is Ellipsis:
return (
self._walk_child(ctx.args[0], ctx, arg_index=0, role=NodeRole.ELEM, token=None),
Ellipsis,
)
# Fixed tuple: each positional arg gets role='arg'
return tuple(self._walk_child(a, ctx, arg_index=i, role=NodeRole.ARG, token=i) for i, a in enumerate(ctx.args))
# --- Dispatcher ---
def _walk(self, type_: Any, parent_ctx: Optional[AnnotationWalkerCtx]) -> Any:
# For logs only: show the calling layer
# print(f"[{parent_ctx.layer if parent_ctx else 0}] walking through: {type_}")
origin = get_origin(type_) or type_
if origin is None:
origin = NoneType
if origin is Union:
origin = UnionType
if not isinstance(origin, type):
raise RuntimeError("Annotation must be using type(s), not instances")
args = get_args(type_)
# IMPORTANT:
# If caller (_walk_child) already constructed a child ctx with edge metadata,
# reuse that object as *the* ctx for this node instead of allocating a new one.
if isinstance(parent_ctx, AnnotationWalkerCtx) and parent_ctx.origin is origin and parent_ctx.args == args:
ctx = parent_ctx
else:
# Root or internal calls that didn't prebuild the ctx
layer = 0 if parent_ctx is None else parent_ctx.layer + 1
ctx = self._new_ctx(origin, args, layer, parent_ctx)
# Remember root ctx for end_trigger()
if ctx.parent is None:
self.root_ctx = ctx
# print(origin)
match origin:
case typing.Annotated:
# inner type gets role='annotated'
return self._handle_with_triggers(
"process_annotated",
ctx,
args_handler=lambda c: (
self._walk_child(c.args[0], c, arg_index=0, role=NodeRole.ANNO, token=None) if c.args else None
),
)
case types.UnionType:
# branches get role='branch' and token=branch index
return self._handle_with_triggers(
"process_union",
ctx,
args_handler=lambda c: tuple(
self._walk_child(a, c, arg_index=i, role=NodeRole.BRANCH, token=i) for i, a in enumerate(c.args)
),
)
case _ if issubclass(origin, dict):
# arg0=key (role='key'), arg1=value (role='val')
return self._handle_with_triggers(
"process_dict",
ctx,
args_handler=lambda c: (
self._walk_child(c.args[0], c, arg_index=0, role=NodeRole.KEY, token=None),
self._walk_child(c.args[1], c, arg_index=1, role=NodeRole.VAL, token=None),
),
)
case _ if issubclass(origin, tuple):
return self._handle_with_triggers("process_tuple", ctx, self._walk_args_tuple)
case _ if issubclass(origin, list):
# single child T with role='elem'
return self._handle_with_triggers(
"process_list",
ctx,
args_handler=lambda c: (
self._walk_child(c.args[0], c, arg_index=0, role=NodeRole.ELEM, token=None) if c.args else None
),
)
case _ if issubclass(origin, set):
# single child T with role='elem'
return self._handle_with_triggers(
"process_set",
ctx,
args_handler=lambda c: (
self._walk_child(c.args[0], c, arg_index=0, role=NodeRole.ELEM, token=None) if c.args else None
),
)
case _ if origin in self._allowed_types:
return self._handle_with_triggers("process_simple", ctx)
case _:
res = self._apply_triggers("process_unknown", ctx)
if res.restart_with is not None:
return self._walk(res.restart_with, ctx.parent)
if res.replace_with is not None:
return res.replace_with
raise RuntimeError(f"Not supported Field: {ctx.origin}, Supported list: {self._allowed_types}")
def _walk_child(
self,
type_expr: Any,
parent_ctx: AnnotationWalkerCtx,
*,
arg_index: int,
role: str | None,
token: Any | None,
) -> Any:
origin = get_origin(type_expr) or type_expr
if origin is None:
origin = NoneType
if origin is Union:
origin = UnionType
if not isinstance(origin, type):
raise RuntimeError("Annotation must be using type(s), not instances")
args = get_args(type_expr)
child_ctx = self._new_ctx(origin, args, parent_ctx.layer + 1, parent_ctx)
# stamp routing metadata for triggers
child_ctx._set_edge(role=role, token=token, arg_index=arg_index)
# IMPORTANT: recurse with the CHILD as the parent_ctx for the next step,
# so the walker uses this child ctx (with edge metadata & incremented layer).
return self._walk(type_expr, child_ctx)

View File

@@ -8,8 +8,8 @@
import unittest
from os import chdir
from io import StringIO
from contextlib import redirect_stdout,redirect_stderr
from io import StringIO
from contextlib import redirect_stdout, redirect_stderr
from pathlib import Path
print(__name__)
@@ -20,16 +20,14 @@ from src import anytraverser
testdir_path = Path(__file__).parent.resolve()
chdir(testdir_path.parent.resolve())
class Testtest_module(unittest.TestCase):
def setUp(self) -> None:
chdir(testdir_path.parent.resolve())
def test_version(self):
self.assertNotEqual(anytraverser.__version__,"?.?.?")
def test_test_module(self):
with redirect_stdout(StringIO()) as capted_stdout, redirect_stderr(StringIO()) as capted_stderr:
self.assertEqual(anytraverser.test_function(41),42)
self.assertEqual(len(capted_stderr.getvalue()),0)
self.assertEqual(capted_stdout.getvalue().strip(),"Hello world !")
def test_version(self):
ann = list[int | str | list[int | float]]
value = [1, "un", 2, "deux", [1, 2, "q"]]
trig = anytraverser.DataValidation(value)
walker = anytraverser.walkers.annotation_walker.AnnotationWalker(ann, (trig,))
walker.run()