Skip to content

Commit e3e3d99

Browse files
authored
Merge pull request #4 from OpenHCSDev/refactor/L6-codegen
0.2.0: generated source loads back every value it names
2 parents 108a8ed + 541af70 commit e3e3d99

12 files changed

Lines changed: 678 additions & 271 deletions

File tree

‎docs/api.rst‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ API orientation
44
``Assignment`` and ``CodeBlock``
55
Structured top-level source items.
66

7-
``generate_python_source(obj, header="", clean_mode=False, *, context=None)``
8-
Generate complete executable source and required imports. A caller-supplied
9-
``FormatContext`` is retained across both render passes and owns clean mode.
7+
``generate_python_source(obj, header="", clean_mode=False)``
8+
Generate complete executable source and required imports, with shared and
9+
repeated absolute paths bound once at the top.
1010

1111
``to_source(value, context=None)``
1212
Format one value into a ``SourceFragment``.
@@ -19,8 +19,17 @@ API orientation
1919
Resolve import requirements and aliases for colliding names.
2020

2121
``FormatContext`` and ``SourceFragment``
22-
Immutable typed formatting state and output records. ``FormatContext`` may
23-
carry exact-type ``extensions`` and exposes them through ``extension(type)``.
22+
Immutable formatting state and output records.
23+
24+
``imported_name(module, qualname, context)``
25+
Spell an importable object by its qualified name, honouring collision aliases.
26+
27+
``PythonSourceLiteral``
28+
Base for values that spell their own source through ``source_fragment``.
29+
30+
``PathRendering``, ``PathCollector``, ``PathFactoring``, ``PathConstructor``
31+
How a render pass spells paths: plainly, while recording, or through the
32+
document's path bindings.
2433

2534
The canonical import surface is ``pycodify.__all__``.
2635

‎docs/architecture.rst‎

Lines changed: 37 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ Two-Pass Algorithm
66

77
Generating executable source requires knowing import aliases before emitting code. But aliases depend on detecting collisions, which requires visiting all types first. This creates a dependency: code generation requires alias resolution, but alias resolution requires traversing the object graph.
88

9-
pycodify solves this with two passes:
9+
pycodify solves this with two passes, preceded by a path-discovery pass
10+
(see *Path factoring* below):
1011

1112
1. **Collection pass**: Traverse the object, emit code fragments, and collect
1213
``(module, name)`` import pairs.
@@ -31,12 +32,26 @@ Each type maps to a ``SourceFormatter`` that emits a ``SourceFragment(code, impo
3132
return isinstance(value, Enum)
3233
3334
def format(self, value: Enum, context: FormatContext) -> SourceFragment:
34-
cls = value.__class__
35-
import_pair = (cls.__module__, cls.__name__)
36-
name = context.name_mappings.get(import_pair, cls.__name__)
37-
return SourceFragment(f"{name}.{value.name}", frozenset([import_pair]))
35+
enum_type = imported_name(type(value).__module__, type(value).__qualname__, context)
36+
return SourceFragment(f"{enum_type.code}.{value.name}", enum_type.imports)
3837
39-
Priority-based dispatch selects the most specific formatter. Domain extensions add formatters without modifying core code.
38+
Priority-based dispatch selects the most specific formatter. Domain extensions add formatters without modifying core code. A value no formatter accepts raises ``TypeError``: pycodify never emits ``repr`` text it cannot load back.
39+
40+
Qualified names
41+
---------------
42+
43+
``imported_name(module, qualname, context)`` is the one rule for spelling an
44+
importable object. It imports the root of ``__qualname__`` and spells the rest as
45+
attribute access, so ``Outer.Mode.FAST`` imports ``Outer``. Enum members,
46+
classes, functions, class-bound methods, named tuples and dataclass constructors
47+
all use it. Objects defined inside a function raise ``TypeError``.
48+
49+
Values that own their spelling
50+
------------------------------
51+
52+
A value whose source is not its constructor subclasses ``PythonSourceLiteral``
53+
and implements ``source_fragment(context)``, typically building on
54+
``imported_name`` so collision aliases apply.
4055

4156
Core Components
4257
---------------
@@ -49,7 +64,7 @@ Core Components
4964

5065
**FormatContext**
5166
Carries indentation depth, ``clean_mode``, the ``(module, name)`` to
52-
local-name mapping, and caller-owned typed extensions. ``indented()`` returns
67+
local-name mapping, and the pass's ``PathRendering``. ``indented()`` returns
5368
a copied context and does not mutate its caller.
5469

5570
**resolve_imports**
@@ -60,27 +75,17 @@ Core Components
6075
Orchestrates collection, resolution, and regeneration to produce a complete
6176
source string.
6277

63-
Immutable typed context extensions
64-
----------------------------------
65-
66-
``FormatContext`` is frozen. Its default mappings are read-only mapping proxies,
67-
and context evolution uses dataclass replacement rather than mutation. A host
68-
may supply an ``extensions`` mapping keyed by the exact nominal type of each
69-
rendering policy or state record. A formatter retrieves one value with
70-
``context.extension(ExtensionType)``; pycodify does not search base classes,
71-
string keys, or a fallback chain.
72-
73-
``generate_python_source(..., context=context)`` threads the caller's context
74-
through collection and regeneration. Import resolution replaces only
75-
``name_mappings`` for the second pass, so typed extensions and all other context
76-
fields survive. When a context is supplied, its ``clean_mode`` is authoritative;
77-
the separate ``clean_mode=`` argument is used only when pycodify constructs the
78-
context.
78+
Path factoring
79+
--------------
7980

80-
Extensions provide formatting context, not formatter dispatch. New value
81-
families still extend the ``SourceFormatter`` registry, while the exact extension
82-
type allows that formatter to obtain host-owned rendering information without
83-
adding host imports or fields to pycodify core.
81+
``generate_python_source`` first renders the document with a ``PathCollector``
82+
on ``FormatContext.paths`` to record every ``pathlib.Path`` value. A
83+
``PathFactoring`` plan then binds each directory shared by two or more absolute
84+
paths (``path_root = Path('/data/screen')``) and each repeated absolute path
85+
(``path_1 = path_root / 'plate_A'``) once, at the top of the document, and the
86+
two rendering passes spell those paths through the bindings. Relative paths and
87+
strings are never factored. ``to_source`` alone uses the base ``PathRendering``,
88+
which spells each path as ``Path('...')``.
8489

8590
Clean Mode
8691
----------
@@ -107,25 +112,13 @@ not sandboxing or validation of generated programs. Hosts must restrict inputs
107112
and custom formatters to trusted sources, review persisted code before running
108113
it, and define their own compatibility policy for imported domain APIs.
109114

110-
Lazy Dataclass Integration
111-
---------------------------
112-
113-
For dataclasses with ``__getattribute__`` interception (used for hierarchical config inheritance), formatters use ``object.__getattribute__`` to access raw field values without triggering lazy resolution:
114-
115-
.. code-block:: python
116-
117-
# In DataclassFormatter
118-
if hasattr(instance, "_resolve_field_value"):
119-
# Bypass __getattribute__ to get raw None vs concrete value
120-
current_value = object.__getattribute__(instance, field_name)
121-
else:
122-
current_value = getattr(instance, field_name)
123-
124-
This distinguishes explicitly-set values from inherited ones during serialization.
125-
126115
Module Structure
127116
----------------
128117

129118
- **core.py**: Main API (``Assignment``, ``generate_python_source``)
130-
- **formatters.py**: Built-in formatters (dataclass, enum, primitive types)
119+
- **formatters.py**: Built-in formatters (dataclass, enum, class, callable, primitive types)
120+
- **paths.py**: Document-level path factoring
121+
122+
Lazy configuration dataclasses (ObjectState) are formatted by
123+
``objectstate.codegen``, which registers its own formatter.
131124
- **imports.py**: Import resolution and collision handling

‎docs/usage.rst‎

Lines changed: 16 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -117,62 +117,37 @@ level. ``name_mappings`` maps ``(module, imported_name)`` pairs to the local
117117
names chosen by ``resolve_imports``; callers normally let
118118
``generate_python_source`` populate it during the second pass.
119119

120-
Typed rendering extensions
121-
--------------------------
120+
Values that own their source
121+
----------------------------
122122

123-
A host can attach immutable rendering context without adding host-specific state
124-
to pycodify. Keys are exact nominal types, and the same context reaches both
125-
render passes:
123+
A value whose source is not its dataclass constructor implements
124+
``PythonSourceLiteral``:
126125

127126
.. code-block:: python
128127
129128
from dataclasses import dataclass
130-
from types import MappingProxyType
131129
132130
from pycodify import (
133131
Assignment,
134132
FormatContext,
135-
SourceFormatter,
133+
PythonSourceLiteral,
136134
SourceFragment,
137135
generate_python_source,
136+
imported_name,
138137
)
139138
140139
@dataclass(frozen=True)
141-
class RenderPolicy:
142-
marker: str
143-
144-
class PolicyValue:
145-
pass
146-
147-
class PolicyValueFormatter(SourceFormatter):
148-
priority = 200
149-
150-
def can_format(self, value):
151-
return isinstance(value, PolicyValue)
152-
153-
def format(self, value, context):
154-
del value
155-
policy = context.extension(RenderPolicy)
156-
if policy is None:
157-
raise RuntimeError("RenderPolicy is required")
158-
return SourceFragment(repr(policy.marker))
159-
160-
context = FormatContext(
161-
clean_mode=True,
162-
extensions=MappingProxyType(
163-
{RenderPolicy: RenderPolicy(marker="preserved")}
164-
),
165-
)
166-
source = generate_python_source(
167-
Assignment("value", PolicyValue()),
168-
context=context,
169-
)
170-
assert source == "value = 'preserved'"
140+
class RegistryLookup(PythonSourceLiteral):
141+
key: str
142+
143+
def source_fragment(self, context: FormatContext) -> SourceFragment:
144+
lookup = imported_name("myapp.registry", "get_function", context)
145+
return SourceFragment(f"{lookup.code}({self.key!r})", lookup.imports)
171146
172-
``extension(RenderPolicy)`` does not return a value stored under a base class or
173-
string key. This exact-type lookup keeps extension ownership explicit. Treat the
174-
extension mapping as immutable; use a new ``FormatContext`` when the host needs
175-
different state.
147+
source = generate_python_source(Assignment("func", RegistryLookup("gauss")))
148+
# from myapp.registry import get_function
149+
#
150+
# func = get_function('gauss')
176151
177152
Nested Dataclasses
178153
-------------------

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
44

55
[project]
66
name = "pycodify"
7-
version = "0.1.3"
7+
version = "0.2.0"
88
description = "Python source code as a serialization format with automatic import resolution"
99
authors = [{name = "Tristan Simas", email = "tristan.simas@mail.mcgill.ca"}]
1010
license = {text = "MIT"}

‎src/pycodify/__init__.py‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,39 @@
1+
# Register default formatters
2+
from . import formatters as _formatters # noqa: F401
13
from .core import (
24
Assignment,
35
BlankLine,
46
CodeBlock,
57
Comment,
68
FormatContext,
9+
PathRendering,
10+
PythonSourceLiteral,
711
SourceFormatter,
812
SourceFragment,
913
generate_python_source,
14+
imported_name,
1015
to_source,
1116
)
1217
from .imports import resolve_imports
18+
from .paths import PathCollector, PathConstructor, PathFactoring
1319

14-
# Register default formatters
15-
from . import formatters as _formatters # noqa: F401
16-
17-
__version__ = "0.1.3"
20+
__version__ = "0.2.0"
1821

1922
__all__ = [
2023
"Assignment",
2124
"BlankLine",
2225
"CodeBlock",
2326
"Comment",
2427
"FormatContext",
28+
"PathCollector",
29+
"PathConstructor",
30+
"PathFactoring",
31+
"PathRendering",
32+
"PythonSourceLiteral",
2533
"SourceFormatter",
2634
"SourceFragment",
2735
"generate_python_source",
36+
"imported_name",
2837
"resolve_imports",
2938
"to_source",
3039
]

0 commit comments

Comments
 (0)