fastdrc 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fastdrc/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """FastDRC — design rules drawn by example, compiled to a working DRC deck.
2
+
3
+ You draw a rule the way a design manual does (shapes, an arrow where a distance
4
+ matters, what must hold); the compiler derives the layer operations and a backend
5
+ writes the deck. See :mod:`fastdrc.process` (a deck: build, check, self-test),
6
+ :mod:`fastdrc.backend` (backends are plugins) and :mod:`fastdrc.editor`.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ __version__ = "0.0.1"
fastdrc/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Enable `python -m fastdrc ...` (delegates to the CLI)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fastdrc.cli import main
6
+
7
+ if __name__ == "__main__":
8
+ main()
fastdrc/backend.py ADDED
@@ -0,0 +1,191 @@
1
+ """Pluggable DRC backends.
2
+
3
+ A backend turns an analyzed `Rule` into a target artifact. There is no data IR:
4
+ a backend's ``compile(rule)`` works directly against our functions -- topology
5
+ relations, parsed constraints, measures -- via the `Rule` API, and emits its
6
+ target (KLayout `.drc` now, a native-engine driver later). The rule->target
7
+ interpretation lives in each backend; the shared substrate is `topology` +
8
+ `constraint` + `Rule`.
9
+
10
+ Backends register by name and are selected at compile time. Because every
11
+ backend consumes the same `Rule`, two can compile the same rule and their
12
+ results compared as a cross-check.
13
+
14
+ A backend is a PLUGIN. The ones shipped here (``klayout``, ``docs``, ``facts``,
15
+ ``cases``) load on first use; any installed package can add one by declaring an entry
16
+ point in the group ``fastdrc.backends``::
17
+
18
+ [project.entry-points."fastdrc.backends"]
19
+ mytarget = "mypackage.mymodule:MyBackend"
20
+
21
+ where ``MyBackend`` subclasses `Backend`, sets ``name`` and implements ``compile``. It
22
+ then works everywhere a backend is named: ``fastdrc rules ... --to mytarget``,
23
+ ``fastdrc build DIR --with mytarget``, the editor's text pane.
24
+
25
+ A backend may also RUN what it compiles on a layout (``runs = True``, with `ready` and
26
+ `run`). ``fastdrc build | check | selftest --backend NAME`` then compile the deck with
27
+ it and run it with it; KLayout is the one shipped here that does, and nothing else in
28
+ the tool names it.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ from .rule import Rule
34
+
35
+
36
+ class RunError(RuntimeError):
37
+ """A backend could not run a deck (not installed, or it failed)."""
38
+
39
+
40
+ class Backend:
41
+ name = "abstract"
42
+ extension = ".txt" # of the file `fastdrc build` writes for this backend
43
+ about = "" # one line for `fastdrc backends`
44
+ runs = False # can it also RUN the deck it compiles on a layout?
45
+
46
+ # ---- running a deck: what `fastdrc check` and `fastdrc selftest` ask of a backend that `runs` ----
47
+ def ready(self):
48
+ """None if the backend can run its deck here; otherwise what is missing, as a sentence."""
49
+ return f"the {self.name} backend writes a file; it does not run one"
50
+
51
+ def by_hand(self, deck, layout) -> str:
52
+ """How to run the deck oneself (shown when the backend is not `ready`); may be ''."""
53
+ return ""
54
+
55
+ def run(self, deck, layout, top=None, report=None) -> dict:
56
+ """Run the compiled `deck` (a file this backend wrote) on `layout`, a GDS / OASIS
57
+ file; `top` names the cell to check (default: the layout's), `report` where to
58
+ leave the backend's own report, if it writes one. Returns::
59
+
60
+ {"rules": {rule name: (description, [(x0, y0, x1, y1) | None, ...])}, # µm, one box per violation (None: no place);
61
+ "report": path or None} # every rule of the deck, clean ones with []
62
+
63
+ Raises `RunError` if it cannot run or fails."""
64
+ raise RunError(self.ready() or f"the {self.name} backend has no run step")
65
+
66
+ def files(self, rules, stem) -> dict:
67
+ """What this backend writes for a set of rules, as ``{file name: text}`` --
68
+ one file by default; a backend producing several (a layout generator and what
69
+ to expect of it) overrides this."""
70
+ return {stem + self.extension: self.compile_all(rules)}
71
+
72
+ def compile(self, rule: Rule) -> str:
73
+ raise NotImplementedError
74
+
75
+ def headed(self, text, about) -> str:
76
+ """The compiled deck with lines `about` it (which rules of the process it holds)
77
+ put at its head, in this target's comment form. Default: left as it is."""
78
+ return text
79
+
80
+ def compile_all(self, rules) -> str:
81
+ """Compile several rules (rule dicts or `Rule`s) into one output. A backend
82
+ with a shared preamble (a deck) overrides this to emit it once."""
83
+ return "\n".join(self.compile(r if isinstance(r, Rule) else Rule(r)) for r in rules)
84
+
85
+ def compile_data(self, data: dict) -> str:
86
+ """Compile what a rule FILE holds: one rule, or a sheet of many (one drawn
87
+ scene, see `fastdrc.sheet`)."""
88
+ from .sheet import is_sheet, rules_of
89
+ if not is_sheet(data):
90
+ return self.compile(Rule(data))
91
+ return self.compile_all(rules_of(data))
92
+
93
+
94
+ _REGISTRY: dict[str, type] = {}
95
+
96
+
97
+ def register(cls):
98
+ _REGISTRY[cls.name] = cls
99
+ return cls
100
+
101
+
102
+ _BUILTIN = ("backend_klayout", "backend_docs", "backend_cases", "backend_svg")
103
+ _loaded = False
104
+
105
+
106
+ def _discover():
107
+ """Load the backends shipped with fastdrc and those other packages offer through
108
+ the ``fastdrc.backends`` entry-point group. A plugin that fails to load is skipped
109
+ (and named in `problems`), never fatal."""
110
+ global _loaded
111
+ if _loaded:
112
+ return
113
+ _loaded = True
114
+ import importlib
115
+ for mod in _BUILTIN:
116
+ importlib.import_module(f"{__package__}.{mod}")
117
+ try:
118
+ from importlib.metadata import entry_points
119
+ found = entry_points(group="fastdrc.backends")
120
+ except Exception: # noqa: BLE001
121
+ found = []
122
+ for ep in found:
123
+ try:
124
+ cls = ep.load()
125
+ if not getattr(cls, "name", None) or cls.name == "abstract":
126
+ cls.name = ep.name
127
+ _REGISTRY.setdefault(cls.name, cls)
128
+ except Exception as ex: # noqa: BLE001
129
+ problems.append(f"backend plugin {ep.name!r} could not be loaded: {ex}")
130
+
131
+
132
+ problems: list[str] = []
133
+
134
+
135
+ def get(name, **kw) -> Backend:
136
+ """A backend by name. Keyword arguments it does not take are left out, so a caller
137
+ can offer what it has (a layer map, a title) to any backend."""
138
+ _discover()
139
+ if name not in _REGISTRY:
140
+ raise KeyError(f"no backend {name!r}; available: {sorted(_REGISTRY)}")
141
+ cls = _REGISTRY[name]
142
+ import inspect
143
+ params = inspect.signature(cls.__init__).parameters
144
+ if not any(p.kind is p.VAR_KEYWORD for p in params.values()):
145
+ kw = {k: v for k, v in kw.items() if k in params}
146
+ return cls(**kw)
147
+
148
+
149
+ def available() -> list[str]:
150
+ _discover()
151
+ return sorted(_REGISTRY)
152
+
153
+
154
+ def runner(name, **kw) -> Backend:
155
+ """A backend that runs what it compiles, by name."""
156
+ b = get(name, **kw)
157
+ if not b.runs:
158
+ raise KeyError(f"the {name!r} backend does not run decks; these do: "
159
+ + ", ".join(n for n in available() if _REGISTRY[n].runs))
160
+ return b
161
+
162
+
163
+ @register
164
+ class FactsBackend(Backend):
165
+ """Reference backend: report the facts the `Rule` API exposes. Demonstrates
166
+ a backend built purely from our topology + constraint functions, and acts
167
+ as a swappability check against the real codegen backends."""
168
+
169
+ name = "facts"
170
+ extension = ".facts.txt"
171
+ about = "the facts read from each drawing (for debugging a drawing)"
172
+
173
+ def compile(self, rule: Rule) -> str:
174
+ lines = [f"rule {rule.name}"] if rule.name else []
175
+ forms = rule.shape_forms()
176
+ for name in rule.shapes:
177
+ lines.append(f"shape {name}: layer={rule.layer_of(name)} "
178
+ f"net={rule.net_of(name)}"
179
+ + (f" class={forms[name]}" if name in forms else ""))
180
+ roles = rule.side_roles()
181
+ for edge, kind, form, lo, hi in rule.length_facts():
182
+ side = f"{roles[edge]} side" if edge in roles else "edge"
183
+ lines.append(f"length: {kind} {side} {edge} {form} {lo}..{hi}")
184
+ for shape, form in rule.form_checks():
185
+ lines.append(f"class: check {shape} must be {form}")
186
+ for (a, b), rel in rule.relations().items():
187
+ lines.append(f"topology: {a} {rel} {b}")
188
+ for bnd in rule.bounds():
189
+ kind = "min" if bnd.is_min else "max"
190
+ lines.append(f"bound: {bnd.var} {bnd.op} {bnd.value} ({kind})")
191
+ return "\n".join(lines) + "\n"