nrtech-nyx 0.1.0a1__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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: nrtech-nyx
3
+ Version: 0.1.0a1
4
+ Summary: Protótipo da linguagem de programação científica NYX
5
+ Author: NR TECH
6
+ License: Apache-2.0
7
+ Keywords: nyx,programming-language,scientific-computing,data-science
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Environment :: Console
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Topic :: Scientific/Engineering
15
+ Classifier: Topic :: Software Development :: Interpreters
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest<10,>=8.0; extra == "dev"
21
+ Dynamic: license-file
22
+
23
+ # NYX — Numerical Yield eXchange
24
+
25
+ **Linguagem de programação científica orientada a dados**
26
+
27
+ *Think Scientifically. Compute Intelligently.*
28
+
29
+ NYX é um projeto autoral da NR TECH para desenvolver uma linguagem independente voltada à computação científica, à engenharia de dados e à integração de inteligência artificial.
30
+
31
+ > **Estado atual:** protótipo executável 0.1.0a1. O núcleo inicial já possui lexer, parser de descida recursiva, AST própria, interpretador e interface de linha de comando. A linguagem ainda está em estágio alfa e não oferece, nesta versão, estruturas tabulares, bibliotecas científicas, compilação nativa, IR ou recursos de IA.
32
+
33
+ ## Identidade e propósito
34
+
35
+ - **N — Numerical:** fundamento matemático e computacional.
36
+ - **Y — Yield:** produção de resultados e conhecimento.
37
+ - **X — eXchange:** integração e interoperabilidade.
38
+
39
+ A NYX possui sintaxe, gramática, frontend, AST e regras de avaliação próprias. Python é utilizado como linguagem hospedeira do protótipo, não como gramática ou mecanismo semântico delegado.
40
+
41
+ ## Núcleo implementado
42
+
43
+ - Lexer com localização de tokens.
44
+ - Parser recursivo e AST própria.
45
+ - Literais: Integer, Float, String, Boolean e Null.
46
+ - Declaração de variáveis com `let`.
47
+ - Expressões aritméticas, relacionais e lógicas.
48
+ - Precedência de operadores e agrupamento.
49
+ - Saída com `print(...)`.
50
+ - Diagnósticos léxicos, sintáticos e de execução com linha e coluna.
51
+ - CLI para executar arquivos `.nyx`.
52
+
53
+ ## Exemplo executável
54
+
55
+ ```nyx
56
+ let samples = 120;
57
+ let ratio = 0.875;
58
+ let title = "NYX — Numerical Yield eXchange";
59
+
60
+ print(title);
61
+ print(samples * ratio);
62
+ print(samples >= 100 and ratio < 1.0);
63
+ ```
64
+
65
+ Consulte [examples/00_primeiro_programa.nyx](examples/00_primeiro_programa.nyx).
66
+
67
+ ## Instalação para desenvolvimento
68
+
69
+ Requisitos: Python 3.10 ou superior.
70
+
71
+ ```bash
72
+ git clone https://github.com/nrdataanalysis-1908/NYX.git
73
+ cd NYX
74
+ python -m venv .venv
75
+ ```
76
+
77
+ Ative o ambiente virtual e instale as dependências de desenvolvimento:
78
+
79
+ ```bash
80
+ # Windows PowerShell
81
+ .venv\Scripts\Activate.ps1
82
+ python -m pip install -e ".[dev]"
83
+
84
+ # Linux/macOS
85
+ source .venv/bin/activate
86
+ python -m pip install -e ".[dev]"
87
+ ```
88
+
89
+ Execute um programa:
90
+
91
+ ```bash
92
+ nyx run examples/00_primeiro_programa.nyx
93
+ ```
94
+
95
+ Ou, durante o desenvolvimento:
96
+
97
+ ```bash
98
+ python -m nyx run examples/00_primeiro_programa.nyx
99
+ ```
100
+
101
+ Execute os testes:
102
+
103
+ ```bash
104
+ python -m pytest -q
105
+ ```
106
+
107
+ ## Especificação e arquitetura
108
+
109
+ - [Especificação inicial da linguagem](docs/ESPECIFICACAO_INICIAL.md)
110
+ - [Arquitetura](docs/ARQUITETURA.md)
111
+ - [Roadmap](docs/ROADMAP.md)
112
+ - [Exemplos científicos conceituais](docs/EXEMPLOS_CIENTIFICOS.md)
113
+
114
+ Os exemplos científicos anteriores continuam sendo propostas de sintaxe e domínio; apenas o exemplo `00_primeiro_programa.nyx` corresponde ao subconjunto executável do protótipo atual.
115
+
116
+ ## Próximas etapas
117
+
118
+ 1. Ampliar a cobertura de testes e consolidar diagnósticos.
119
+ 2. Introduzir blocos, controle de fluxo e funções.
120
+ 3. Formalizar análise semântica e sistema de tipos.
121
+ 4. Desenvolver coleções e operações matemáticas.
122
+ 5. Criar estruturas tabulares e operações de dados.
123
+ 6. Projetar IR, otimização e paralelismo com benchmarks reproduzíveis.
124
+ 7. Integrar recursos de IA por interfaces desacopladas.
125
+
126
+ ## Licença
127
+
128
+ Apache License 2.0. Consulte [LICENSE](LICENSE).
@@ -0,0 +1,106 @@
1
+ # NYX — Numerical Yield eXchange
2
+
3
+ **Linguagem de programação científica orientada a dados**
4
+
5
+ *Think Scientifically. Compute Intelligently.*
6
+
7
+ NYX é um projeto autoral da NR TECH para desenvolver uma linguagem independente voltada à computação científica, à engenharia de dados e à integração de inteligência artificial.
8
+
9
+ > **Estado atual:** protótipo executável 0.1.0a1. O núcleo inicial já possui lexer, parser de descida recursiva, AST própria, interpretador e interface de linha de comando. A linguagem ainda está em estágio alfa e não oferece, nesta versão, estruturas tabulares, bibliotecas científicas, compilação nativa, IR ou recursos de IA.
10
+
11
+ ## Identidade e propósito
12
+
13
+ - **N — Numerical:** fundamento matemático e computacional.
14
+ - **Y — Yield:** produção de resultados e conhecimento.
15
+ - **X — eXchange:** integração e interoperabilidade.
16
+
17
+ A NYX possui sintaxe, gramática, frontend, AST e regras de avaliação próprias. Python é utilizado como linguagem hospedeira do protótipo, não como gramática ou mecanismo semântico delegado.
18
+
19
+ ## Núcleo implementado
20
+
21
+ - Lexer com localização de tokens.
22
+ - Parser recursivo e AST própria.
23
+ - Literais: Integer, Float, String, Boolean e Null.
24
+ - Declaração de variáveis com `let`.
25
+ - Expressões aritméticas, relacionais e lógicas.
26
+ - Precedência de operadores e agrupamento.
27
+ - Saída com `print(...)`.
28
+ - Diagnósticos léxicos, sintáticos e de execução com linha e coluna.
29
+ - CLI para executar arquivos `.nyx`.
30
+
31
+ ## Exemplo executável
32
+
33
+ ```nyx
34
+ let samples = 120;
35
+ let ratio = 0.875;
36
+ let title = "NYX — Numerical Yield eXchange";
37
+
38
+ print(title);
39
+ print(samples * ratio);
40
+ print(samples >= 100 and ratio < 1.0);
41
+ ```
42
+
43
+ Consulte [examples/00_primeiro_programa.nyx](examples/00_primeiro_programa.nyx).
44
+
45
+ ## Instalação para desenvolvimento
46
+
47
+ Requisitos: Python 3.10 ou superior.
48
+
49
+ ```bash
50
+ git clone https://github.com/nrdataanalysis-1908/NYX.git
51
+ cd NYX
52
+ python -m venv .venv
53
+ ```
54
+
55
+ Ative o ambiente virtual e instale as dependências de desenvolvimento:
56
+
57
+ ```bash
58
+ # Windows PowerShell
59
+ .venv\Scripts\Activate.ps1
60
+ python -m pip install -e ".[dev]"
61
+
62
+ # Linux/macOS
63
+ source .venv/bin/activate
64
+ python -m pip install -e ".[dev]"
65
+ ```
66
+
67
+ Execute um programa:
68
+
69
+ ```bash
70
+ nyx run examples/00_primeiro_programa.nyx
71
+ ```
72
+
73
+ Ou, durante o desenvolvimento:
74
+
75
+ ```bash
76
+ python -m nyx run examples/00_primeiro_programa.nyx
77
+ ```
78
+
79
+ Execute os testes:
80
+
81
+ ```bash
82
+ python -m pytest -q
83
+ ```
84
+
85
+ ## Especificação e arquitetura
86
+
87
+ - [Especificação inicial da linguagem](docs/ESPECIFICACAO_INICIAL.md)
88
+ - [Arquitetura](docs/ARQUITETURA.md)
89
+ - [Roadmap](docs/ROADMAP.md)
90
+ - [Exemplos científicos conceituais](docs/EXEMPLOS_CIENTIFICOS.md)
91
+
92
+ Os exemplos científicos anteriores continuam sendo propostas de sintaxe e domínio; apenas o exemplo `00_primeiro_programa.nyx` corresponde ao subconjunto executável do protótipo atual.
93
+
94
+ ## Próximas etapas
95
+
96
+ 1. Ampliar a cobertura de testes e consolidar diagnósticos.
97
+ 2. Introduzir blocos, controle de fluxo e funções.
98
+ 3. Formalizar análise semântica e sistema de tipos.
99
+ 4. Desenvolver coleções e operações matemáticas.
100
+ 5. Criar estruturas tabulares e operações de dados.
101
+ 6. Projetar IR, otimização e paralelismo com benchmarks reproduzíveis.
102
+ 7. Integrar recursos de IA por interfaces desacopladas.
103
+
104
+ ## Licença
105
+
106
+ Apache License 2.0. Consulte [LICENSE](LICENSE).
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=69", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "nrtech-nyx"
7
+ version = "0.1.0a1"
8
+ description = "Protótipo da linguagem de programação científica NYX"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [{ name = "NR TECH" }]
13
+ keywords = ["nyx", "programming-language", "scientific-computing", "data-science"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Environment :: Console",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: Apache Software License",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Topic :: Scientific/Engineering",
22
+ "Topic :: Software Development :: Interpreters",
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ dev = ["pytest>=8.0,<10"]
27
+
28
+ [project.scripts]
29
+ nyx = "nyx.cli:main"
30
+
31
+ [tool.setuptools]
32
+ package-dir = {"" = "src"}
33
+
34
+ [tool.setuptools.packages.find]
35
+ where = ["src"]
36
+
37
+ [tool.pytest.ini_options]
38
+ testpaths = ["tests"]
39
+ addopts = "-ra"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: nrtech-nyx
3
+ Version: 0.1.0a1
4
+ Summary: Protótipo da linguagem de programação científica NYX
5
+ Author: NR TECH
6
+ License: Apache-2.0
7
+ Keywords: nyx,programming-language,scientific-computing,data-science
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Environment :: Console
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Topic :: Scientific/Engineering
15
+ Classifier: Topic :: Software Development :: Interpreters
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest<10,>=8.0; extra == "dev"
21
+ Dynamic: license-file
22
+
23
+ # NYX — Numerical Yield eXchange
24
+
25
+ **Linguagem de programação científica orientada a dados**
26
+
27
+ *Think Scientifically. Compute Intelligently.*
28
+
29
+ NYX é um projeto autoral da NR TECH para desenvolver uma linguagem independente voltada à computação científica, à engenharia de dados e à integração de inteligência artificial.
30
+
31
+ > **Estado atual:** protótipo executável 0.1.0a1. O núcleo inicial já possui lexer, parser de descida recursiva, AST própria, interpretador e interface de linha de comando. A linguagem ainda está em estágio alfa e não oferece, nesta versão, estruturas tabulares, bibliotecas científicas, compilação nativa, IR ou recursos de IA.
32
+
33
+ ## Identidade e propósito
34
+
35
+ - **N — Numerical:** fundamento matemático e computacional.
36
+ - **Y — Yield:** produção de resultados e conhecimento.
37
+ - **X — eXchange:** integração e interoperabilidade.
38
+
39
+ A NYX possui sintaxe, gramática, frontend, AST e regras de avaliação próprias. Python é utilizado como linguagem hospedeira do protótipo, não como gramática ou mecanismo semântico delegado.
40
+
41
+ ## Núcleo implementado
42
+
43
+ - Lexer com localização de tokens.
44
+ - Parser recursivo e AST própria.
45
+ - Literais: Integer, Float, String, Boolean e Null.
46
+ - Declaração de variáveis com `let`.
47
+ - Expressões aritméticas, relacionais e lógicas.
48
+ - Precedência de operadores e agrupamento.
49
+ - Saída com `print(...)`.
50
+ - Diagnósticos léxicos, sintáticos e de execução com linha e coluna.
51
+ - CLI para executar arquivos `.nyx`.
52
+
53
+ ## Exemplo executável
54
+
55
+ ```nyx
56
+ let samples = 120;
57
+ let ratio = 0.875;
58
+ let title = "NYX — Numerical Yield eXchange";
59
+
60
+ print(title);
61
+ print(samples * ratio);
62
+ print(samples >= 100 and ratio < 1.0);
63
+ ```
64
+
65
+ Consulte [examples/00_primeiro_programa.nyx](examples/00_primeiro_programa.nyx).
66
+
67
+ ## Instalação para desenvolvimento
68
+
69
+ Requisitos: Python 3.10 ou superior.
70
+
71
+ ```bash
72
+ git clone https://github.com/nrdataanalysis-1908/NYX.git
73
+ cd NYX
74
+ python -m venv .venv
75
+ ```
76
+
77
+ Ative o ambiente virtual e instale as dependências de desenvolvimento:
78
+
79
+ ```bash
80
+ # Windows PowerShell
81
+ .venv\Scripts\Activate.ps1
82
+ python -m pip install -e ".[dev]"
83
+
84
+ # Linux/macOS
85
+ source .venv/bin/activate
86
+ python -m pip install -e ".[dev]"
87
+ ```
88
+
89
+ Execute um programa:
90
+
91
+ ```bash
92
+ nyx run examples/00_primeiro_programa.nyx
93
+ ```
94
+
95
+ Ou, durante o desenvolvimento:
96
+
97
+ ```bash
98
+ python -m nyx run examples/00_primeiro_programa.nyx
99
+ ```
100
+
101
+ Execute os testes:
102
+
103
+ ```bash
104
+ python -m pytest -q
105
+ ```
106
+
107
+ ## Especificação e arquitetura
108
+
109
+ - [Especificação inicial da linguagem](docs/ESPECIFICACAO_INICIAL.md)
110
+ - [Arquitetura](docs/ARQUITETURA.md)
111
+ - [Roadmap](docs/ROADMAP.md)
112
+ - [Exemplos científicos conceituais](docs/EXEMPLOS_CIENTIFICOS.md)
113
+
114
+ Os exemplos científicos anteriores continuam sendo propostas de sintaxe e domínio; apenas o exemplo `00_primeiro_programa.nyx` corresponde ao subconjunto executável do protótipo atual.
115
+
116
+ ## Próximas etapas
117
+
118
+ 1. Ampliar a cobertura de testes e consolidar diagnósticos.
119
+ 2. Introduzir blocos, controle de fluxo e funções.
120
+ 3. Formalizar análise semântica e sistema de tipos.
121
+ 4. Desenvolver coleções e operações matemáticas.
122
+ 5. Criar estruturas tabulares e operações de dados.
123
+ 6. Projetar IR, otimização e paralelismo com benchmarks reproduzíveis.
124
+ 7. Integrar recursos de IA por interfaces desacopladas.
125
+
126
+ ## Licença
127
+
128
+ Apache License 2.0. Consulte [LICENSE](LICENSE).
@@ -0,0 +1,19 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/nrtech_nyx.egg-info/PKG-INFO
5
+ src/nrtech_nyx.egg-info/SOURCES.txt
6
+ src/nrtech_nyx.egg-info/dependency_links.txt
7
+ src/nrtech_nyx.egg-info/entry_points.txt
8
+ src/nrtech_nyx.egg-info/requires.txt
9
+ src/nrtech_nyx.egg-info/top_level.txt
10
+ src/nyx/__init__.py
11
+ src/nyx/__main__.py
12
+ src/nyx/ast_nodes.py
13
+ src/nyx/cli.py
14
+ src/nyx/errors.py
15
+ src/nyx/interpreter.py
16
+ src/nyx/lexer.py
17
+ src/nyx/parser.py
18
+ src/nyx/tokens.py
19
+ tests/test_language.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ nyx = nyx.cli:main
@@ -0,0 +1,3 @@
1
+
2
+ [dev]
3
+ pytest<10,>=8.0
@@ -0,0 +1,16 @@
1
+ """NYX — Numerical Yield eXchange language prototype."""
2
+ from .interpreter import Interpreter
3
+ from .lexer import Lexer
4
+ from .parser import Parser
5
+
6
+ __version__ = "0.1.0a1"
7
+
8
+
9
+ def run(source: str, output=print) -> None:
10
+ """Tokenize, parse and execute a NYX source string."""
11
+ tokens = Lexer(source).scan_tokens()
12
+ statements = Parser(tokens).parse()
13
+ Interpreter(output=output).interpret(statements)
14
+
15
+
16
+ __all__ = ["Interpreter", "Lexer", "Parser", "run", "__version__"]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,42 @@
1
+ """Immutable syntax tree nodes for NYX."""
2
+ from dataclasses import dataclass
3
+ from .tokens import Token
4
+
5
+
6
+ @dataclass(frozen=True, slots=True)
7
+ class Literal:
8
+ value: object
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class Variable:
13
+ name: Token
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class Unary:
18
+ operator: Token
19
+ right: object
20
+
21
+
22
+ @dataclass(frozen=True, slots=True)
23
+ class Binary:
24
+ left: object
25
+ operator: Token
26
+ right: object
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class Grouping:
31
+ expression: object
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class LetStatement:
36
+ name: Token
37
+ initializer: object
38
+
39
+
40
+ @dataclass(frozen=True, slots=True)
41
+ class PrintStatement:
42
+ expression: object
@@ -0,0 +1,29 @@
1
+ """Command-line interface for NYX."""
2
+ import argparse
3
+ from pathlib import Path
4
+ import sys
5
+
6
+ from . import run
7
+ from .errors import NyxError
8
+
9
+
10
+ def main(argv=None) -> int:
11
+ parser = argparse.ArgumentParser(prog="nyx", description="NYX language prototype")
12
+ subparsers = parser.add_subparsers(dest="command", required=True)
13
+ run_parser = subparsers.add_parser("run", help="execute a .nyx source file")
14
+ run_parser.add_argument("file", type=Path, help="path to source file")
15
+ args = parser.parse_args(argv)
16
+
17
+ if not args.file.is_file():
18
+ print(f"nyx: file not found: {args.file}", file=sys.stderr)
19
+ return 2
20
+ try:
21
+ run(args.file.read_text(encoding="utf-8"))
22
+ except (NyxError, UnicodeError) as exc:
23
+ print(str(exc), file=sys.stderr)
24
+ return 1
25
+ return 0
26
+
27
+
28
+ if __name__ == "__main__":
29
+ raise SystemExit(main())
@@ -0,0 +1,17 @@
1
+ """Source-aware diagnostics for NYX."""
2
+
3
+
4
+ class NyxError(Exception):
5
+ """Base class for language errors."""
6
+
7
+
8
+ class LexError(NyxError):
9
+ """Raised when source text cannot be tokenized."""
10
+
11
+
12
+ class ParseError(NyxError):
13
+ """Raised when tokens do not match the grammar."""
14
+
15
+
16
+ class RuntimeNyxError(NyxError):
17
+ """Raised when a valid program fails during evaluation."""
@@ -0,0 +1,104 @@
1
+ """Tree-walk interpreter for the NYX language MVP."""
2
+ from .ast_nodes import Binary, Grouping, LetStatement, Literal, PrintStatement, Unary, Variable
3
+ from .errors import RuntimeNyxError
4
+ from .tokens import TokenType
5
+
6
+
7
+ class Interpreter:
8
+ def __init__(self, output=print):
9
+ self.environment: dict[str, object] = {}
10
+ self.output = output
11
+
12
+ def interpret(self, statements: list[object]) -> None:
13
+ for statement in statements:
14
+ self._execute(statement)
15
+
16
+ def _execute(self, statement) -> None:
17
+ if isinstance(statement, LetStatement):
18
+ name = statement.name.lexeme
19
+ if name in self.environment:
20
+ self._runtime_error(statement.name, f"Variable '{name}' is already declared.")
21
+ self.environment[name] = self._evaluate(statement.initializer)
22
+ elif isinstance(statement, PrintStatement):
23
+ self.output(self._evaluate(statement.expression))
24
+ else:
25
+ raise RuntimeNyxError("Unsupported statement node.")
26
+
27
+ def _evaluate(self, expression):
28
+ if isinstance(expression, Literal):
29
+ return expression.value
30
+ if isinstance(expression, Grouping):
31
+ return self._evaluate(expression.expression)
32
+ if isinstance(expression, Variable):
33
+ name = expression.name.lexeme
34
+ if name not in self.environment:
35
+ self._runtime_error(expression.name, f"Undefined variable '{name}'.")
36
+ return self.environment[name]
37
+ if isinstance(expression, Unary):
38
+ right = self._evaluate(expression.right)
39
+ if expression.operator.type == TokenType.NOT:
40
+ self._require_bool(right, expression.operator)
41
+ return not right
42
+ self._require_number(right, expression.operator)
43
+ return -right if expression.operator.type == TokenType.MINUS else right
44
+ if isinstance(expression, Binary):
45
+ return self._binary(expression)
46
+ raise RuntimeNyxError("Unsupported expression node.")
47
+
48
+ def _binary(self, expression: Binary):
49
+ op = expression.operator
50
+ left = self._evaluate(expression.left)
51
+ if op.type == TokenType.OR:
52
+ self._require_bool(left, op)
53
+ return left or self._logical_right(expression.right, op)
54
+ if op.type == TokenType.AND:
55
+ self._require_bool(left, op)
56
+ return left and self._logical_right(expression.right, op)
57
+ right = self._evaluate(expression.right)
58
+ if op.type in (TokenType.PLUS, TokenType.MINUS, TokenType.STAR,
59
+ TokenType.SLASH, TokenType.PERCENT):
60
+ self._require_number(left, op)
61
+ self._require_number(right, op)
62
+ if op.type == TokenType.PLUS:
63
+ return left + right
64
+ if op.type == TokenType.MINUS:
65
+ return left - right
66
+ if op.type == TokenType.STAR:
67
+ return left * right
68
+ if op.type == TokenType.SLASH:
69
+ if right == 0:
70
+ self._runtime_error(op, "Division by zero.")
71
+ return left / right
72
+ if right == 0:
73
+ self._runtime_error(op, "Modulo by zero.")
74
+ return left % right
75
+ if op.type in (TokenType.LESS, TokenType.LESS_EQUAL, TokenType.GREATER,
76
+ TokenType.GREATER_EQUAL):
77
+ if type(left) not in (int, float) or type(right) not in (int, float):
78
+ self._runtime_error(op, "Comparison operators require numeric operands.")
79
+ return {
80
+ TokenType.LESS: left < right,
81
+ TokenType.LESS_EQUAL: left <= right,
82
+ TokenType.GREATER: left > right,
83
+ TokenType.GREATER_EQUAL: left >= right,
84
+ }[op.type]
85
+ if op.type in (TokenType.EQUAL_EQUAL, TokenType.BANG_EQUAL):
86
+ equal = type(left) is type(right) and left == right
87
+ return equal if op.type == TokenType.EQUAL_EQUAL else not equal
88
+ self._runtime_error(op, "Unsupported binary operator.")
89
+
90
+ def _logical_right(self, expression, operator):
91
+ value = self._evaluate(expression)
92
+ self._require_bool(value, operator)
93
+ return value
94
+
95
+ def _require_number(self, value, token) -> None:
96
+ if type(value) not in (int, float):
97
+ self._runtime_error(token, "Arithmetic operators require numeric operands.")
98
+
99
+ def _require_bool(self, value, token) -> None:
100
+ if type(value) is not bool:
101
+ self._runtime_error(token, "Logical operators require boolean operands.")
102
+
103
+ def _runtime_error(self, token, message):
104
+ raise RuntimeNyxError(f"[NYX:L{token.line}:C{token.column}] {message}")
@@ -0,0 +1,144 @@
1
+ """Lexer for the first NYX language specification."""
2
+ from .errors import LexError
3
+ from .tokens import Token, TokenType
4
+
5
+
6
+ _KEYWORDS = {
7
+ "let": TokenType.LET,
8
+ "print": TokenType.PRINT,
9
+ "true": TokenType.TRUE,
10
+ "false": TokenType.FALSE,
11
+ "null": TokenType.NULL,
12
+ "and": TokenType.AND,
13
+ "or": TokenType.OR,
14
+ "not": TokenType.NOT,
15
+ }
16
+
17
+
18
+ class Lexer:
19
+ def __init__(self, source: str):
20
+ self.source = source
21
+ self.tokens: list[Token] = []
22
+ self.start = 0
23
+ self.current = 0
24
+ self.line = 1
25
+ self.column = 1
26
+ self.start_line = 1
27
+ self.start_column = 1
28
+
29
+ def scan_tokens(self) -> list[Token]:
30
+ while not self._at_end():
31
+ self.start = self.current
32
+ self.start_line = self.line
33
+ self.start_column = self.column
34
+ self._scan_token()
35
+ self.tokens.append(Token(TokenType.EOF, "", None, self.line, self.column))
36
+ return self.tokens
37
+
38
+ def _at_end(self) -> bool:
39
+ return self.current >= len(self.source)
40
+
41
+ def _advance(self) -> str:
42
+ char = self.source[self.current]
43
+ self.current += 1
44
+ if char == "\n":
45
+ self.line += 1
46
+ self.column = 1
47
+ else:
48
+ self.column += 1
49
+ return char
50
+
51
+ def _peek(self) -> str:
52
+ return "\0" if self._at_end() else self.source[self.current]
53
+
54
+ def _peek_next(self) -> str:
55
+ return "\0" if self.current + 1 >= len(self.source) else self.source[self.current + 1]
56
+
57
+ def _match(self, expected: str) -> bool:
58
+ if self._at_end() or self.source[self.current] != expected:
59
+ return False
60
+ self._advance()
61
+ return True
62
+
63
+ def _add(self, token_type: TokenType, literal: object = None) -> None:
64
+ self.tokens.append(Token(token_type, self.source[self.start:self.current], literal,
65
+ self.start_line, self.start_column))
66
+
67
+ def _scan_token(self) -> None:
68
+ char = self._advance()
69
+ single = {
70
+ "+": TokenType.PLUS, "-": TokenType.MINUS, "*": TokenType.STAR,
71
+ "/": TokenType.SLASH, "%": TokenType.PERCENT,
72
+ "(": TokenType.LEFT_PAREN, ")": TokenType.RIGHT_PAREN,
73
+ ";": TokenType.SEMICOLON,
74
+ }
75
+ if char in single:
76
+ self._add(single[char])
77
+ elif char == "=":
78
+ self._add(TokenType.EQUAL_EQUAL if self._match("=") else TokenType.EQUAL)
79
+ elif char == "!":
80
+ if self._match("="):
81
+ self._add(TokenType.BANG_EQUAL)
82
+ else:
83
+ self._error("Use 'not' for logical negation; bare '!' is not supported.")
84
+ elif char == "<":
85
+ self._add(TokenType.LESS_EQUAL if self._match("=") else TokenType.LESS)
86
+ elif char == ">":
87
+ self._add(TokenType.GREATER_EQUAL if self._match("=") else TokenType.GREATER)
88
+ elif char in " \r\t":
89
+ return
90
+ elif char == "\n":
91
+ return
92
+ elif char == "#":
93
+ while self._peek() not in ("\n", "\0"):
94
+ self._advance()
95
+ elif char == '"':
96
+ self._string()
97
+ elif char.isdigit():
98
+ self._number()
99
+ elif char.isalpha() or char == "_":
100
+ self._identifier()
101
+ else:
102
+ self._error(f"Unexpected character {char!r}.")
103
+
104
+ def _string(self) -> None:
105
+ value = []
106
+ while self._peek() != '"' and not self._at_end():
107
+ if self._peek() == "\n":
108
+ self._error("String literals cannot span multiple lines.")
109
+ if self._peek() == "\\":
110
+ self._advance()
111
+ escaped = self._advance() if not self._at_end() else "\0"
112
+ translations = {"n": "\n", "t": "\t", '"': '"', "\\": "\\"}
113
+ if escaped not in translations:
114
+ self._error(f"Unsupported escape sequence \\{escaped}.")
115
+ value.append(translations[escaped])
116
+ else:
117
+ value.append(self._advance())
118
+ if self._at_end():
119
+ self._error("Unterminated string literal.")
120
+ self._advance()
121
+ self._add(TokenType.STRING, "".join(value))
122
+
123
+ def _number(self) -> None:
124
+ while self._peek().isdigit():
125
+ self._advance()
126
+ is_float = False
127
+ if self._peek() == "." and self._peek_next().isdigit():
128
+ is_float = True
129
+ self._advance()
130
+ while self._peek().isdigit():
131
+ self._advance()
132
+ raw = self.source[self.start:self.current]
133
+ self._add(TokenType.FLOAT if is_float else TokenType.INTEGER,
134
+ float(raw) if is_float else int(raw))
135
+
136
+ def _identifier(self) -> None:
137
+ while self._peek().isalnum() or self._peek() == "_":
138
+ self._advance()
139
+ text = self.source[self.start:self.current]
140
+ self._add(_KEYWORDS.get(text, TokenType.IDENTIFIER),
141
+ {"true": True, "false": False, "null": None}.get(text))
142
+
143
+ def _error(self, message: str) -> None:
144
+ raise LexError(f"[NYX:L{self.start_line}:C{self.start_column}] {message}")
@@ -0,0 +1,129 @@
1
+ """Recursive-descent parser for NYX."""
2
+ from .ast_nodes import Binary, Grouping, LetStatement, Literal, PrintStatement, Unary, Variable
3
+ from .errors import ParseError
4
+ from .tokens import Token, TokenType
5
+
6
+
7
+ class Parser:
8
+ def __init__(self, tokens: list[Token]):
9
+ self.tokens = tokens
10
+ self.current = 0
11
+
12
+ def parse(self) -> list[object]:
13
+ statements = []
14
+ while not self._check(TokenType.EOF):
15
+ statements.append(self._statement())
16
+ return statements
17
+
18
+ def _statement(self):
19
+ if self._match(TokenType.LET):
20
+ name = self._consume(TokenType.IDENTIFIER, "Expected a variable name after 'let'.")
21
+ self._consume(TokenType.EQUAL, "Expected '=' after the variable name.")
22
+ value = self._expression()
23
+ self._consume(TokenType.SEMICOLON, "Expected ';' after the declaration.")
24
+ return LetStatement(name, value)
25
+ if self._match(TokenType.PRINT):
26
+ self._consume(TokenType.LEFT_PAREN, "Expected '(' after 'print'.")
27
+ value = self._expression()
28
+ self._consume(TokenType.RIGHT_PAREN, "Expected ')' after the value.")
29
+ self._consume(TokenType.SEMICOLON, "Expected ';' after the print statement.")
30
+ return PrintStatement(value)
31
+ token = self._peek()
32
+ self._error(token, "Expected a statement: 'let' or 'print'.")
33
+
34
+ def _expression(self):
35
+ return self._or()
36
+
37
+ def _or(self):
38
+ expr = self._and()
39
+ while self._match(TokenType.OR):
40
+ op = self._previous()
41
+ expr = Binary(expr, op, self._and())
42
+ return expr
43
+
44
+ def _and(self):
45
+ expr = self._equality()
46
+ while self._match(TokenType.AND):
47
+ op = self._previous()
48
+ expr = Binary(expr, op, self._equality())
49
+ return expr
50
+
51
+ def _equality(self):
52
+ expr = self._comparison()
53
+ while self._match(TokenType.EQUAL_EQUAL, TokenType.BANG_EQUAL):
54
+ op = self._previous()
55
+ expr = Binary(expr, op, self._comparison())
56
+ return expr
57
+
58
+ def _comparison(self):
59
+ expr = self._term()
60
+ while self._match(TokenType.LESS, TokenType.LESS_EQUAL, TokenType.GREATER,
61
+ TokenType.GREATER_EQUAL):
62
+ op = self._previous()
63
+ expr = Binary(expr, op, self._term())
64
+ return expr
65
+
66
+ def _term(self):
67
+ expr = self._factor()
68
+ while self._match(TokenType.PLUS, TokenType.MINUS):
69
+ op = self._previous()
70
+ expr = Binary(expr, op, self._factor())
71
+ return expr
72
+
73
+ def _factor(self):
74
+ expr = self._unary()
75
+ while self._match(TokenType.STAR, TokenType.SLASH, TokenType.PERCENT):
76
+ op = self._previous()
77
+ expr = Binary(expr, op, self._unary())
78
+ return expr
79
+
80
+ def _unary(self):
81
+ if self._match(TokenType.NOT, TokenType.MINUS, TokenType.PLUS):
82
+ op = self._previous()
83
+ return Unary(op, self._unary())
84
+ return self._primary()
85
+
86
+ def _primary(self):
87
+ if self._match(TokenType.FALSE):
88
+ return Literal(False)
89
+ if self._match(TokenType.TRUE):
90
+ return Literal(True)
91
+ if self._match(TokenType.NULL):
92
+ return Literal(None)
93
+ if self._match(TokenType.INTEGER, TokenType.FLOAT, TokenType.STRING):
94
+ return Literal(self._previous().literal)
95
+ if self._match(TokenType.IDENTIFIER):
96
+ return Variable(self._previous())
97
+ if self._match(TokenType.LEFT_PAREN):
98
+ expr = self._expression()
99
+ self._consume(TokenType.RIGHT_PAREN, "Expected ')' after expression.")
100
+ return Grouping(expr)
101
+ self._error(self._peek(), "Expected a literal, variable or parenthesized expression.")
102
+
103
+ def _match(self, *types: TokenType) -> bool:
104
+ if any(self._check(token_type) for token_type in types):
105
+ self._advance()
106
+ return True
107
+ return False
108
+
109
+ def _consume(self, token_type: TokenType, message: str) -> Token:
110
+ if self._check(token_type):
111
+ return self._advance()
112
+ self._error(self._peek(), message)
113
+
114
+ def _check(self, token_type: TokenType) -> bool:
115
+ return self._peek().type == token_type
116
+
117
+ def _advance(self) -> Token:
118
+ if not self._check(TokenType.EOF):
119
+ self.current += 1
120
+ return self._previous()
121
+
122
+ def _peek(self) -> Token:
123
+ return self.tokens[self.current]
124
+
125
+ def _previous(self) -> Token:
126
+ return self.tokens[self.current - 1]
127
+
128
+ def _error(self, token: Token, message: str):
129
+ raise ParseError(f"[NYX:L{token.line}:C{token.column}] {message}")
@@ -0,0 +1,43 @@
1
+ """Token model for the NYX language frontend."""
2
+ from dataclasses import dataclass
3
+ from enum import Enum, auto
4
+
5
+
6
+ class TokenType(Enum):
7
+ LET = auto()
8
+ PRINT = auto()
9
+ TRUE = auto()
10
+ FALSE = auto()
11
+ NULL = auto()
12
+ AND = auto()
13
+ OR = auto()
14
+ NOT = auto()
15
+ IDENTIFIER = auto()
16
+ INTEGER = auto()
17
+ FLOAT = auto()
18
+ STRING = auto()
19
+ PLUS = auto()
20
+ MINUS = auto()
21
+ STAR = auto()
22
+ SLASH = auto()
23
+ PERCENT = auto()
24
+ EQUAL = auto()
25
+ EQUAL_EQUAL = auto()
26
+ BANG_EQUAL = auto()
27
+ LESS = auto()
28
+ LESS_EQUAL = auto()
29
+ GREATER = auto()
30
+ GREATER_EQUAL = auto()
31
+ LEFT_PAREN = auto()
32
+ RIGHT_PAREN = auto()
33
+ SEMICOLON = auto()
34
+ EOF = auto()
35
+
36
+
37
+ @dataclass(frozen=True, slots=True)
38
+ class Token:
39
+ type: TokenType
40
+ lexeme: str
41
+ literal: object
42
+ line: int
43
+ column: int
@@ -0,0 +1,71 @@
1
+ import pytest
2
+
3
+ from nyx import run
4
+ from nyx.errors import LexError, ParseError, RuntimeNyxError
5
+ from nyx.lexer import Lexer
6
+ from nyx.tokens import TokenType
7
+
8
+
9
+ def execute(source):
10
+ output = []
11
+ run(source, output=output.append)
12
+ return output
13
+
14
+
15
+ def test_lexer_recognizes_keywords_and_numbers():
16
+ tokens = Lexer('let value = 12.5; print(value);').scan_tokens()
17
+ assert [t.type for t in tokens[:4]] == [
18
+ TokenType.LET, TokenType.IDENTIFIER, TokenType.EQUAL, TokenType.FLOAT
19
+ ]
20
+
21
+
22
+ def test_declaration_arithmetic_and_print():
23
+ assert execute('let x = 2 + 3 * 4; print(x);') == [14]
24
+
25
+
26
+ def test_operator_precedence_and_grouping():
27
+ assert execute('print((2 + 3) * 4);') == [20]
28
+
29
+
30
+ def test_boolean_logic_and_comparison():
31
+ assert execute('print(10 > 3 and not false);') == [True]
32
+
33
+
34
+ def test_string_and_null_literals():
35
+ assert execute('let message = "hello\\nworld"; print(message); print(null);') == [
36
+ "hello\nworld", None
37
+ ]
38
+
39
+
40
+ def test_comments_are_ignored():
41
+ assert execute('# comment\nprint(7); # trailing comment') == [7]
42
+
43
+
44
+ def test_undefined_variable_is_reported():
45
+ with pytest.raises(RuntimeNyxError, match="Undefined variable"):
46
+ execute('print(missing);')
47
+
48
+
49
+ def test_duplicate_declaration_is_rejected():
50
+ with pytest.raises(RuntimeNyxError, match="already declared"):
51
+ execute('let x = 1; let x = 2;')
52
+
53
+
54
+ def test_division_by_zero_is_reported():
55
+ with pytest.raises(RuntimeNyxError, match="Division by zero"):
56
+ execute('print(1 / 0);')
57
+
58
+
59
+ def test_strict_boolean_types():
60
+ with pytest.raises(RuntimeNyxError, match="boolean operands"):
61
+ execute('print(1 and true);')
62
+
63
+
64
+ def test_invalid_character_is_reported():
65
+ with pytest.raises(LexError, match="NYX:L1:C1"):
66
+ Lexer("@").scan_tokens()
67
+
68
+
69
+ def test_missing_semicolon_is_reported():
70
+ with pytest.raises(ParseError, match="Expected ';'"):
71
+ execute('print(1)')