adesha 0.1.0__tar.gz

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.
adesha-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
adesha-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,119 @@
1
+ Metadata-Version: 2.4
2
+ Name: adesha
3
+ Version: 0.1.0
4
+ Summary: A Sanskrit programming language — from Pāṇini to silicon.
5
+ Author: Ayush Bhoi
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/ayushbhoi08-lab/adesha
8
+ Project-URL: Repository, https://github.com/ayushbhoi08-lab/adesha
9
+ Project-URL: Documentation, https://ayushbhoi08-lab.github.io/adesha/
10
+ Keywords: sanskrit,programming-language,interpreter,education,panini,devanagari
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Education
19
+ Classifier: Topic :: Software Development :: Interpreters
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Dynamic: license-file
24
+
25
+ # Ādeśa (आदेश)
26
+
27
+ **A Sanskrit programming language — from Pāṇini to silicon.**
28
+
29
+ Ādeśa ("command") is a small interpreted language whose keywords are real Sanskrit imperatives, written in the pure-ASCII [Harvard-Kyoto](https://en.wikipedia.org/wiki/Harvard-Kyoto) convention so they type on any keyboard. When you write `vada` you are writing वद — the loṭ lakāra imperative *"Speak!"* — and the machine obeys.
30
+
31
+ ```text
32
+ $ python adesha.py
33
+ Ādeśa shell (Harvard-Kyoto) — type 'samApti' to quit.
34
+ >> vada namaste lokAH
35
+ namaste lokAH
36
+ >> punaH tri vada punarukti
37
+ punarukti
38
+ punarukti
39
+ punarukti
40
+ ```
41
+
42
+ `punaH tri` — "again, three times." Numbers can be Sanskrit words (`eka`, `dvi`, `tri`, … `aSTottarazata` = 108) or digits; both work everywhere.
43
+
44
+ ## Why Sanskrit?
45
+
46
+ Not decoration — lineage. Pāṇini's **Aṣṭādhyāyī** (~500 BCE) is a formal generative grammar of ~4,000 ordered rewrite rules with meta-rules and context-sensitive transformations — structurally the same device as the BNF notation that defines modern programming languages (computer scientists sometimes call it the *Pāṇini–Backus form*). **Piṅgala's** Chandaḥśāstra (~200 BCE) encoded poetic meter as sequences of light (laghu) and heavy (guru) syllables — a binary notation, two millennia early. Sanskrit is arguably the only human language that was *formally specified*, the way programming languages are. Ādeśa is built on that inheritance: Sanskrit **structure and vocabulary** — never a claim that the machine "understands" Sanskrit meaning.
47
+
48
+ ## The language in one screen
49
+
50
+ ```text
51
+ # lesson0_final.adesha — my first program
52
+ sthApaya nama rAma # "establish!" — set a variable
53
+ vada namaste nama # "speak!" — print (namaste rAma)
54
+
55
+ yadi nama == rAma # "if"
56
+ vada sAdhu # blocks end with iti ("thus")
57
+ anyathA # "otherwise"
58
+ vada anyat
59
+ iti
60
+
61
+ vidhi ghata n # "procedure" — define a function
62
+ yadi n <= eka
63
+ dehi 1 # "give!" — return a value
64
+ iti
65
+ dehi n * ghata(n - 1)
66
+ iti
67
+ gaNaya ghata(paJca) # "compute!" — 120 (recursion works)
68
+
69
+ samUha s # "collection" — make a list
70
+ yojaya s Adi # "join!" — append
71
+ vada s[eka] # 1-based indexing: eka is the first element
72
+
73
+ mudrA nama # "seal!" — 108-bit integrity fingerprint
74
+ ```
75
+
76
+ Booleans are `satya`/`asatya`. Logic is `ca`/`vA`/`na` (and/or/not). Errors speak both languages with a numbered `doSa` code, a line number, and a did-you-mean:
77
+
78
+ ```text
79
+ >> vad namaste
80
+ doSa-001: ajYAta Adeza 'vad' (did you mean: vada?) — unknown command 'vad' (did you mean: vada?)
81
+ ```
82
+
83
+ Every keyword is registered in three spellings: Harvard-Kyoto canonical (`sthApaya`), lowercase (`sthapaya`), and Devanagari (`स्थापय`).
84
+
85
+ ## Sealed scripts
86
+
87
+ `adesha seal file.adesha` stamps a script with its own fingerprint footer; `adesha parIkSA file.adesha` later answers **siddha** (intact, exit 0) or **bhraSTa** (tampered, exit 1). Like a wax seal on a letter — tamper-evident homework, lesson files, and documents.
88
+
89
+ ## Two layers, honestly labeled
90
+
91
+ Ādeśa is a two-layer stack:
92
+
93
+ - **`adesha/`** — the high-level language (this repo, fully self-contained, Python stdlib only).
94
+ - **`aos_asm.py`** — a low-level layer whose FOLD/lane operations mirror a private RNS chip design (the A0S project). It runs here on a **software model**. The chip-true `lane_residue()` in this repo was verified against the chip's RTL by co-simulation: **1,000/1,000 randomized inputs agree bit-for-bit** across the built-in mirror, the verified golden model, and the Verilog core under Icarus Verilog — see [tests/reports/c2_parity_report.md](tests/reports/c2_parity_report.md). The chip design itself is not in this repo, and nothing here requires it.
95
+
96
+ Two different numbers, two different jobs: `mudrA` is a 108-bit *software* integrity fingerprint (mod M107); the *chip lane residue* (mod 12289) reflects Harvard-Kyoto prosodic weight and is deliberately **not** an integrity primitive.
97
+
98
+ ## Try it
99
+
100
+ ```bash
101
+ git clone https://github.com/ayushbhoi08-lab/adesha.git
102
+ cd adesha
103
+ python adesha.py # REPL
104
+ python adesha.py examples/zloka_mudra.adesha # seal a Bhagavad Gītā verse
105
+ python adesha.py --trace run examples/function.adesha # watch it execute
106
+ python -m pytest tests -q # the test suite
107
+ ```
108
+
109
+ The browser playground (Pyodide, zero install) lives in [playground/](playground/) — serve it with `python -m http.server` from that folder, or open it directly at **https://ayushbhoi08-lab.github.io/adesha/**.
110
+
111
+ New to programming? Start with [Lesson Zero](docs/lessons/lesson0.md) — five steps that teach one programming concept and one real Sanskrit grammar note at a time.
112
+
113
+ ## Status
114
+
115
+ Active, early, and honest about it. The language core (tokenizer, expression parser, blocks, functions with recursion, lists, dual-language errors, seal/verify CLI) is complete and tested. On the roadmap: a sandhi-based macro layer (Pāṇini's own mechanism as a language feature), an aṣṭa-dik turtle for teaching, and offline Sanskrit voice commands. This project makes **no claims** of natural-language understanding, translation, or NLP.
116
+
117
+ ## License
118
+
119
+ [Apache-2.0](LICENSE)
adesha-0.1.0/README.md ADDED
@@ -0,0 +1,95 @@
1
+ # Ādeśa (आदेश)
2
+
3
+ **A Sanskrit programming language — from Pāṇini to silicon.**
4
+
5
+ Ādeśa ("command") is a small interpreted language whose keywords are real Sanskrit imperatives, written in the pure-ASCII [Harvard-Kyoto](https://en.wikipedia.org/wiki/Harvard-Kyoto) convention so they type on any keyboard. When you write `vada` you are writing वद — the loṭ lakāra imperative *"Speak!"* — and the machine obeys.
6
+
7
+ ```text
8
+ $ python adesha.py
9
+ Ādeśa shell (Harvard-Kyoto) — type 'samApti' to quit.
10
+ >> vada namaste lokAH
11
+ namaste lokAH
12
+ >> punaH tri vada punarukti
13
+ punarukti
14
+ punarukti
15
+ punarukti
16
+ ```
17
+
18
+ `punaH tri` — "again, three times." Numbers can be Sanskrit words (`eka`, `dvi`, `tri`, … `aSTottarazata` = 108) or digits; both work everywhere.
19
+
20
+ ## Why Sanskrit?
21
+
22
+ Not decoration — lineage. Pāṇini's **Aṣṭādhyāyī** (~500 BCE) is a formal generative grammar of ~4,000 ordered rewrite rules with meta-rules and context-sensitive transformations — structurally the same device as the BNF notation that defines modern programming languages (computer scientists sometimes call it the *Pāṇini–Backus form*). **Piṅgala's** Chandaḥśāstra (~200 BCE) encoded poetic meter as sequences of light (laghu) and heavy (guru) syllables — a binary notation, two millennia early. Sanskrit is arguably the only human language that was *formally specified*, the way programming languages are. Ādeśa is built on that inheritance: Sanskrit **structure and vocabulary** — never a claim that the machine "understands" Sanskrit meaning.
23
+
24
+ ## The language in one screen
25
+
26
+ ```text
27
+ # lesson0_final.adesha — my first program
28
+ sthApaya nama rAma # "establish!" — set a variable
29
+ vada namaste nama # "speak!" — print (namaste rAma)
30
+
31
+ yadi nama == rAma # "if"
32
+ vada sAdhu # blocks end with iti ("thus")
33
+ anyathA # "otherwise"
34
+ vada anyat
35
+ iti
36
+
37
+ vidhi ghata n # "procedure" — define a function
38
+ yadi n <= eka
39
+ dehi 1 # "give!" — return a value
40
+ iti
41
+ dehi n * ghata(n - 1)
42
+ iti
43
+ gaNaya ghata(paJca) # "compute!" — 120 (recursion works)
44
+
45
+ samUha s # "collection" — make a list
46
+ yojaya s Adi # "join!" — append
47
+ vada s[eka] # 1-based indexing: eka is the first element
48
+
49
+ mudrA nama # "seal!" — 108-bit integrity fingerprint
50
+ ```
51
+
52
+ Booleans are `satya`/`asatya`. Logic is `ca`/`vA`/`na` (and/or/not). Errors speak both languages with a numbered `doSa` code, a line number, and a did-you-mean:
53
+
54
+ ```text
55
+ >> vad namaste
56
+ doSa-001: ajYAta Adeza 'vad' (did you mean: vada?) — unknown command 'vad' (did you mean: vada?)
57
+ ```
58
+
59
+ Every keyword is registered in three spellings: Harvard-Kyoto canonical (`sthApaya`), lowercase (`sthapaya`), and Devanagari (`स्थापय`).
60
+
61
+ ## Sealed scripts
62
+
63
+ `adesha seal file.adesha` stamps a script with its own fingerprint footer; `adesha parIkSA file.adesha` later answers **siddha** (intact, exit 0) or **bhraSTa** (tampered, exit 1). Like a wax seal on a letter — tamper-evident homework, lesson files, and documents.
64
+
65
+ ## Two layers, honestly labeled
66
+
67
+ Ādeśa is a two-layer stack:
68
+
69
+ - **`adesha/`** — the high-level language (this repo, fully self-contained, Python stdlib only).
70
+ - **`aos_asm.py`** — a low-level layer whose FOLD/lane operations mirror a private RNS chip design (the A0S project). It runs here on a **software model**. The chip-true `lane_residue()` in this repo was verified against the chip's RTL by co-simulation: **1,000/1,000 randomized inputs agree bit-for-bit** across the built-in mirror, the verified golden model, and the Verilog core under Icarus Verilog — see [tests/reports/c2_parity_report.md](tests/reports/c2_parity_report.md). The chip design itself is not in this repo, and nothing here requires it.
71
+
72
+ Two different numbers, two different jobs: `mudrA` is a 108-bit *software* integrity fingerprint (mod M107); the *chip lane residue* (mod 12289) reflects Harvard-Kyoto prosodic weight and is deliberately **not** an integrity primitive.
73
+
74
+ ## Try it
75
+
76
+ ```bash
77
+ git clone https://github.com/ayushbhoi08-lab/adesha.git
78
+ cd adesha
79
+ python adesha.py # REPL
80
+ python adesha.py examples/zloka_mudra.adesha # seal a Bhagavad Gītā verse
81
+ python adesha.py --trace run examples/function.adesha # watch it execute
82
+ python -m pytest tests -q # the test suite
83
+ ```
84
+
85
+ The browser playground (Pyodide, zero install) lives in [playground/](playground/) — serve it with `python -m http.server` from that folder, or open it directly at **https://ayushbhoi08-lab.github.io/adesha/**.
86
+
87
+ New to programming? Start with [Lesson Zero](docs/lessons/lesson0.md) — five steps that teach one programming concept and one real Sanskrit grammar note at a time.
88
+
89
+ ## Status
90
+
91
+ Active, early, and honest about it. The language core (tokenizer, expression parser, blocks, functions with recursion, lists, dual-language errors, seal/verify CLI) is complete and tested. On the roadmap: a sandhi-based macro layer (Pāṇini's own mechanism as a language feature), an aṣṭa-dik turtle for teaching, and offline Sanskrit voice commands. This project makes **no claims** of natural-language understanding, translation, or NLP.
92
+
93
+ ## License
94
+
95
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,2 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Ādeśa — Sanskrit-imperative programming language (high-level layer)."""
@@ -0,0 +1,113 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ doSa (दोष, "fault/error") system — A0.3.
4
+
5
+ All interpreter errors flow through here. Every doSa has:
6
+ - a three-digit numeric code
7
+ - a Sanskrit line (Harvard-Kyoto)
8
+ - an English line
9
+ - optional position ([pankti L] where pankti = "line")
10
+
11
+ Format:
12
+ doSa-001 [pankti 7]: ajYAta Adeza "vad" — unknown command "vad" (did you mean: vada?)
13
+
14
+ Public API:
15
+ DosA the one exception that crosses run_line -> REPL/script
16
+ raise_dosa(code, ...) build and raise a DosA
17
+ suggest(word, names) nearest match within edit distance <= 2, or ""
18
+ """
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # doSa code table
22
+ # Values are (sanskrit_template, english_template).
23
+ # Templates are str.format_map()-style with named keys.
24
+ # ---------------------------------------------------------------------------
25
+ _TABLE = {
26
+ 1: ("ajYAta Adeza {word!r}{hint}",
27
+ "unknown command {word!r}{hint}"),
28
+ 2: ("varNa-doSa: {msg}",
29
+ "character/token error: {msg}"),
30
+ 3: ("gaNanA-doSa (vyAkaraNa): {msg}",
31
+ "expression parse error: {msg}"),
32
+ 4: ("gaNanA-doSa (kAla): {msg}",
33
+ "runtime error: {msg}"),
34
+ 5: ("yadi: dvibindu AvazyakaH (yadi n > 3 : vada bahu)",
35
+ "yadi: ':' is required (yadi n > 3 : vada bahu)"),
36
+ 6: ("Adeza-tarka riktaH: {cmd!r} ko tarka cAhie",
37
+ "command {cmd!r} needs an argument"),
38
+ 7: ("punaH: saMkhyA AvazyakA — {word!r} milA",
39
+ "punaH: count must be an integer, got {word!r}"),
40
+ 8: ("iti asthAna {msg}",
41
+ "unmatched iti — {msg}"),
42
+ 9: ("iti hInaH {word!r} prabandhaH",
43
+ "missing iti for {word!r} block"),
44
+ 10: ("anyathA asthAne — yadi bahire",
45
+ "anyathA outside yadi block"),
46
+ 11: ("vidhi-doSa: {msg}",
47
+ "function error: {msg}"),
48
+ 12: ("samUha-doSa: {msg}",
49
+ "list error: {msg}"),
50
+ 13: ("anukrama-doSa: {msg}",
51
+ "index error: {msg}"),
52
+ 99: ("AntarikA-doSa: {msg}",
53
+ "internal error: {msg}"),
54
+ }
55
+
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # Edit distance (Levenshtein) for did-you-mean
59
+ # ---------------------------------------------------------------------------
60
+ def _edit_distance(a, b):
61
+ la, lb = len(a), len(b)
62
+ # small optimisation: bail early if lengths differ by more than 2
63
+ if abs(la - lb) > 2:
64
+ return abs(la - lb)
65
+ prev = list(range(lb + 1))
66
+ for i, ca in enumerate(a, 1):
67
+ curr = [i] + [0] * lb
68
+ for j, cb in enumerate(b, 1):
69
+ curr[j] = min(
70
+ prev[j] + 1,
71
+ curr[j - 1] + 1,
72
+ prev[j - 1] + (0 if ca == cb else 1),
73
+ )
74
+ prev = curr
75
+ return prev[lb]
76
+
77
+
78
+ def suggest(word, candidates, max_dist=2):
79
+ """Return ' (did you mean: X?)' if a candidate is within max_dist, else ''."""
80
+ best, best_d = None, max_dist + 1
81
+ for c in candidates:
82
+ d = _edit_distance(word.lower(), c.lower())
83
+ if d < best_d:
84
+ best, best_d = c, d
85
+ return f" (did you mean: {best}?)" if best is not None else ""
86
+
87
+
88
+ # ---------------------------------------------------------------------------
89
+ # DosA exception
90
+ # ---------------------------------------------------------------------------
91
+ class DosA(Exception):
92
+ """The single exception that the REPL and script runner catch and display."""
93
+
94
+ def __init__(self, code, line=None, **kw):
95
+ self.code = code
96
+ self.line = line
97
+ self.kw = kw
98
+ super().__init__(str(self))
99
+
100
+ def __str__(self):
101
+ sk_tmpl, en_tmpl = _TABLE.get(self.code, ("doSa", "error"))
102
+ try:
103
+ sk = sk_tmpl.format_map(self.kw)
104
+ en = en_tmpl.format_map(self.kw)
105
+ except (KeyError, ValueError) as exc:
106
+ sk = en = f"(formatting error: {exc})"
107
+ pos = f" [pankti {self.line}]" if self.line else ""
108
+ return f"doSa-{self.code:03d}{pos}: {sk} — {en}"
109
+
110
+
111
+ def raise_dosa(code, line=None, **kw):
112
+ """Build and immediately raise a DosA."""
113
+ raise DosA(code, line=line, **kw)