Coverage for sources/classcore/standard/explanations.py: 100%
99 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-15 18:04 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-15 18:04 +0000
1# vim: set filetype=python fileencoding=utf-8:
2# -*- coding: utf-8 -*-
4#============================================================================#
5# #
6# Licensed under the Apache License, Version 2.0 (the "License"); #
7# you may not use this file except in compliance with the License. #
8# You may obtain a copy of the License at #
9# #
10# http://www.apache.org/licenses/LICENSE-2.0 #
11# #
12# Unless required by applicable law or agreed to in writing, software #
13# under the License is distributed on an "AS IS" BASIS, #
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
15# See the License for the specific language governing permissions and #
16# limitations under the License. #
17# #
18#============================================================================#
21''' Explanations of attribute behavior decisions. '''
24from .. import utilities as _utilities
25from . import __
26from . import behaviors as _behaviors
27from . import decorators as _decorators
28from . import nomina as _nomina
31_framework_names_prefix = '_classcore_'
34@_decorators.dataclass_with_standard_behaviors( )
35class Decision:
36 ''' Decision which one operation reached for one attribute.
38 The decision subclasses form a closed hierarchy; the decision
39 type is the discriminant. Verdict permissibility is derived
40 from the decision type.
41 '''
44@_decorators.dataclass_with_standard_behaviors( )
45class PermitByInapplicability( Decision ):
46 ''' Permission because the governing behavior is inactive. '''
49@_decorators.dataclass_with_standard_behaviors( )
50class PermitByOmni( Decision ):
51 ''' Permission by the omni marker, which permits every name. '''
54@_decorators.dataclass_with_standard_behaviors( )
55class PermitByNames( Decision ):
56 ''' Permission by exclusion names membership. '''
57 name: str
60@_decorators.dataclass_with_standard_behaviors( )
61class PermitByPredicate( Decision ):
62 ''' Permission by an exclusion predicate. '''
63 predicate: str
66@_decorators.dataclass_with_standard_behaviors( )
67class PermitByRegex( Decision ):
68 ''' Permission by an exclusion regex. '''
69 pattern: str
72@_decorators.dataclass_with_standard_behaviors( )
73class Prohibit( Decision ):
74 ''' Prohibition: the behavior is active and no rule permits. '''
77@_decorators.dataclass_with_standard_behaviors( )
78class Verdict:
79 ''' Verdict for one operation on one attribute. '''
80 operation: str
81 decision: Decision
83 @property
84 def permissible( self ) -> bool:
85 ''' Returns whether the operation is permissible. '''
86 return not isinstance( self.decision, Prohibit )
89@_decorators.dataclass_with_standard_behaviors( )
90class AssignVerdict( Verdict ):
91 ''' Verdict for attribute assignment. '''
94@_decorators.dataclass_with_standard_behaviors( )
95class DeleteVerdict( Verdict ):
96 ''' Verdict for attribute deletion. '''
99@_decorators.dataclass_with_standard_behaviors( )
100class SurveyVerdict( Verdict ):
101 ''' Verdict for attribute visibility in survey results. '''
104@_decorators.dataclass_with_standard_behaviors( )
105class AttributeExplanation:
106 ''' Decision trace for one attribute of one target. '''
107 target: str
108 name: str
109 behaviors: __.cabc.Mapping[ str, __.cabc.Set[ str ] ]
110 operations: __.cabc.Mapping[ str, Verdict ]
111 internal: bool
113 def __repr__( self ) -> str:
114 ''' Returns summary of the decision trace. '''
115 lines = [
116 f"{self.name!r} on {self.target}"
117 + ( ' [internal]' if self.internal else '' ) ]
118 for level, labels in self.behaviors.items( ):
119 lines.append(
120 f"behaviors: {', '.join( sorted( labels ) )}"
121 + f" ({level})" )
122 for operation in ( 'assign', 'delete', 'survey' ):
123 verdict = self.operations.get( operation )
124 if verdict is None: continue # pragma: no cover
125 lines.append( f"{operation}: {self._render( verdict.decision )}" )
126 return '\n'.join( lines )
128 def _render( self, decision: Decision, / ) -> str:
129 if isinstance( decision, PermitByInapplicability ):
130 return 'permitted (behavior inapplicable)'
131 if isinstance( decision, PermitByOmni ):
132 return "permitted by omni '*'"
133 if isinstance( decision, PermitByNames ):
134 return f"permitted by names {decision.name!r}"
135 if isinstance( decision, PermitByPredicate ):
136 return f"permitted by predicate {decision.predicate!r}"
137 if isinstance( decision, PermitByRegex ):
138 return f"permitted by regex {decision.pattern!r}"
139 if isinstance( decision, Prohibit ):
140 return 'prohibited (no permitting rule)'
141 raise ValueError( type( decision ) )
144def explain_attribute(
145 target: object, name: str, /, *,
146 attributes_namer: _nomina.AttributesNamer = __.calculate_attrname,
147) -> AttributeExplanation:
148 ''' Returns decision trace for attribute name on target.
150 All operations follow precedence semantics: omni, then names
151 membership, then the first matching predicate, then the first
152 matching regex; prohibition when the governing behavior is
153 active and nothing permits; permission by inapplicability when
154 the behavior is inactive. For class targets, the classes-level
155 configuration is evaluated; for instance targets, the
156 instances-level configuration is evaluated against the
157 instance's class hierarchy — matching the levels the behavior
158 cores evaluate. Records report the normalized level names
159 ('class' and 'instance') at which behaviors and exclusion
160 configuration were found. Explanations are observational: they
161 neither bypass nor alter concealment or immutability. They are
162 not side-effect-free for arbitrary callbacks, however:
163 producing a record invokes user predicates and internal-name
164 detectors to determine the same outcome the cores would.
166 Survey explanations describe normalized first-match semantics;
167 the survey core's current once-per-matching-rule duplication is
168 characterized as a defect whose repair is deferred separately.
169 '''
170 class_target = __.inspect.isclass( target )
171 level = 'class' if class_target else 'instances'
172 level_normalized = 'class' if class_target else 'instance'
173 behaviors = _behaviors.survey_active_behaviors(
174 target, attributes_namer = attributes_namer, level = level )
175 immutability = _nomina.immutability_label in behaviors
176 concealment = _nomina.concealment_label in behaviors
177 operations: dict[ str, Verdict ] = { }
178 for operation, verdict_class, basename, active in (
179 ( 'assign', AssignVerdict, 'mutables', immutability ),
180 ( 'delete', DeleteVerdict, 'mutables', immutability ),
181 ( 'survey', SurveyVerdict, 'visibles', concealment ),
182 ):
183 rule = (
184 _behaviors.provide_permitter_if_applicable(
185 target, attributes_namer = attributes_namer,
186 level = level, basename = basename, name = name )
187 if active else None )
188 operations[ operation ] = verdict_class(
189 operation = operation,
190 decision = produce_decision( rule, active ) )
191 return AttributeExplanation(
192 target = _utilities.describe_object( target ),
193 name = name,
194 behaviors = __.types.MappingProxyType(
195 { level_normalized: frozenset( behaviors ) } ),
196 operations = __.types.MappingProxyType( operations ),
197 internal = is_internal_name( target, name ) )
200def is_internal_name( target: object, name: str, / ) -> bool:
201 ''' Returns whether name is internal to the target's machinery.
203 Contributions are discovered on the metaclass chain: for a
204 class target, its metaclass method resolution order; for an
205 instance target, the metaclass resolution order of its type
206 (the metaclass chain is reached through the double type
207 transformation — the instance's own type resolution order
208 enumerates the class bases, never the metaclass). Decorator-
209 based classes carry their contributions on the class itself,
210 so the class resolution order is consulted as well. Each
211 contribution is a detector produced by the machinery which
212 built the class, so a name is internal only where the
213 machinery that generates it operates. Classification scope is
214 the machinery chain and is independent of per-class mutability
215 exemptions: a name may be internal on a class where it is not
216 mutable, and mutable where it is not internal.
217 '''
218 cls = target if __.inspect.isclass( target ) else type( target )
219 chains = (
220 type( cls ).__mro__, cls.__mro__ ) # Metaclass chain, then class.
221 contribution_name = __.calculate_contribution_name( )
222 for chain in chains:
223 for holder in chain:
224 contributions = holder.__dict__.get( contribution_name )
225 if not contributions: continue
226 for detector in contributions:
227 if detector( name ): return True
228 return False
231def produce_decision(
232 rule: __.typx.Optional[ tuple[ str, __.typx.Any ] ], active: bool, /
233) -> Decision:
234 ''' Returns decision for governing-behavior activity and first rule.
236 Rules are the (kind, raw verifier) pairs produced by
237 provide_permitter_if_applicable; the kind vocabulary matches the
238 omni/names/predicate/regex precedence stages. Verifier detail
239 text is rendered here, at the record layer, so enforcement
240 paths which consult the same rules never depend on rendering.
241 '''
242 if not active: return PermitByInapplicability( )
243 if rule is None: return Prohibit( )
244 kind, verifier = rule
245 if kind == 'omni': return PermitByOmni( )
246 if kind == 'names': return PermitByNames( name = verifier )
247 if kind == 'predicate':
248 return PermitByPredicate(
249 predicate = _behaviors.render_verifier_text( verifier ) )
250 if kind == 'regex':
251 return PermitByRegex(
252 pattern = _behaviors.render_verifier_text( verifier ) )
253 raise ValueError( kind )