lucidaflow 1.0.8__tar.gz → 1.2.2__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.

Potentially problematic release.


This version of lucidaflow might be problematic. Click here for more details.

Files changed (33) hide show
  1. lucidaflow-1.2.2/PKG-INFO +125 -0
  2. lucidaflow-1.2.2/README.md +105 -0
  3. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/pyproject.toml +1 -1
  4. lucidaflow-1.2.2/src/lucidaflow/__main__.py +14 -0
  5. lucidaflow-1.2.2/src/lucidaflow/cli.py +100 -0
  6. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow/lib/dado.py +34 -34
  7. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow/lib/json.py +45 -45
  8. lucidaflow-1.2.2/src/lucidaflow/lib/math.py +54 -0
  9. lucidaflow-1.2.2/src/lucidaflow/lib/media.py +61 -0
  10. lucidaflow-1.2.2/src/lucidaflow/lib/parser_patch.py +24 -0
  11. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow/lib/web.py +35 -35
  12. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow/lucida_analyzer.py +1043 -1043
  13. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow/lucida_ast.py +320 -320
  14. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow/lucida_errors.py +25 -25
  15. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow/lucida_interpreter.py +821 -821
  16. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow/lucida_lexer.py +248 -248
  17. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow/lucida_parser.py +583 -583
  18. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow/lucida_stdlib.py +255 -249
  19. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow/lucida_symbols.py +176 -176
  20. lucidaflow-1.2.2/src/lucidaflow.egg-info/PKG-INFO +125 -0
  21. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow.egg-info/SOURCES.txt +4 -0
  22. lucidaflow-1.0.8/PKG-INFO +0 -1625
  23. lucidaflow-1.0.8/README.md +0 -1605
  24. lucidaflow-1.0.8/src/lucidaflow/cli.py +0 -86
  25. lucidaflow-1.0.8/src/lucidaflow.egg-info/PKG-INFO +0 -1625
  26. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/LICENSE +0 -0
  27. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/setup.cfg +0 -0
  28. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow/__init__.py +0 -0
  29. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow/lib/__init__.py +0 -0
  30. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow.egg-info/dependency_links.txt +0 -0
  31. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow.egg-info/entry_points.txt +0 -0
  32. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow.egg-info/requires.txt +0 -0
  33. {lucidaflow-1.0.8 → lucidaflow-1.2.2}/src/lucidaflow.egg-info/top_level.txt +0 -0
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.4
2
+ Name: lucidaflow
3
+ Version: 1.2.2
4
+ Summary: Uma linguagem de script moderna, extensível e com tipagem gradual, implementada em Python.
5
+ Author-email: Marco Lago <marconeed2@gmail.com>
6
+ Project-URL: Homepage, https://github.com/marconeed/Lucida-Flow
7
+ Project-URL: Issues, https://github.com/marconeed/Lucida-Flow/issues
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Topic :: Software Development :: Interpreters
12
+ Classifier: Topic :: Software Development :: Compilers
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: numpy
17
+ Requires-Dist: pysine
18
+ Requires-Dist: requests
19
+ Dynamic: license-file
20
+
21
+ [Volume 1: O Manual de Referência](https://www.amazon.com.br/dp/B0FJ1HYJN8)
22
+
23
+ [Volume 2: Construindo Aplicações Gráficas](https://www.amazon.com.br/dp/B0FLJ8PNYJ)
24
+
25
+ [Lucida-Flow Support - Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=SoteroApps.lucidaflow-support)
26
+
27
+ [Lucida-Flow - pypi org](https://pypi.org/project/lucidaflow)
28
+
29
+ [Lucida-Flow - GitHub](https://github.com/marconeed/Lucida-Flow)
30
+
31
+ [Sponsor](https://github.com/sponsors/marconeed)
32
+
33
+ ______________________________________________________________________________________________
34
+
35
+ ## Usando o Terminal:
36
+
37
+ OBS:
38
+
39
+ Faça download do repositorio Lucida-Flow em uma pasta usando o terminal Windows ou o terminal do VScode:
40
+
41
+ ```
42
+ git clone https://github.com/marconeed/Lucida-Flow
43
+ cd Lucida-Flow
44
+ ```
45
+
46
+ OBS:
47
+
48
+ Baixe as dependencias usando o terminal Windows ou o terminal do VScode:
49
+
50
+ ```pip install requests```
51
+
52
+ OBS:
53
+
54
+ Para criar programas com interface grafica precisamos criar 2 arquivos o:
55
+
56
+ O arquivo .py contendo os codigos para desenhar a interface grafica
57
+
58
+ O arquivo .lf contendo os codigos da logica do programa
59
+
60
+ Os 2 arquivos precisam estar na raiz da linguagem de programação, onde fica todo o codigo da linguagem, ou você pode colocar em outros locais, mais tera que referenciar nos 2 arquivos as pastas onde estão as importações de que os 2 arquivos precisam para funcionar
61
+
62
+ a linguagem contem codigos das guis usadas no livro, estão na raiz do projeto em uma pasta chamada gui, basta colocar as que for usar na raiz junto ao arquivo .lf. Se quiser deixar onde esta precisa mudar o caminho das importações dos 2 arquivos.
63
+
64
+ OBS:
65
+
66
+ Para executar basta colocar esse comando usando o terminal Windows ou o terminal do VScode na pasta onde esta os arquivos e lembrar de refenciar o arquivo .lf na nome-do-arquivo-gui_host.py:
67
+
68
+ ```python main.py nome_arquivo.lf```
69
+
70
+ ```python nome-do-arquivo-gui_host.py```
71
+
72
+
73
+ ## Usando o VS code:
74
+
75
+ OBS:
76
+
77
+ Faça download da estensão da linguagem para VS code
78
+
79
+ ```https://marketplace.visualstudio.com/items?itemName=SoteroApps.lucidaflow-support```
80
+
81
+ OBS:
82
+
83
+ Baixe as dependencias usando o terminal Windows ou o terminal do VScode:
84
+
85
+ ```pip install requests```
86
+
87
+ OBS:
88
+
89
+ A extensão funciona para auxiliar na contrução do codigo com sugestões e constução da sytanxe sublinhando as palavras, fica melhor programar no VS code
90
+
91
+ O VS code suporta executar o codigo direto nele nome_arquivo.lf, mais para porgramas de interface grafica tera que usar o terminal do VS code para dar o comando para executar. o comando é o mesmo ```python nome-do-arquivo-gui_host.py```
92
+
93
+
94
+ ## Usando o pypi org:
95
+
96
+ OBS:
97
+
98
+ Faça download da linguagem na pypi org
99
+
100
+ ```https://pypi.org/project/lucidaflow```
101
+
102
+ ```pip install lucidaflow```
103
+
104
+ OBS:
105
+
106
+ Usando a linguagem dessa forma você elimina a necessidade dos arquivos da linguagem estar na mesma pasta para funcionar, basta cria uma pasta vazia com o .lf e executar, ou nome-do-arquivo-gui_host.py + .lf e executar se for com interface grafica. Para executar o comando é ```python -m lucidaflow nome_arquivo.lf``` ou ```python nome-do-arquivo-gui_host.py```
107
+
108
+ Usar dessa forma combinado com o VS code e a extensão funciona para auxiliar na contrução do codigo com sugestões e constução da sytanxe sublinhando as palavras, fica melhor programar no VS code
109
+
110
+ Para executar no terminal Windows basta abrir o terminal windows na pasta onde esta o .lf e digitar ```python -m lucidaflow nome-do-arquivo.lf```, ou abrir o terminal windows na pasta onde esta o gui.py e digitar ```python nome-do-arquivo-gui_host.py`` se for com interface grafica
111
+
112
+ Para executar no VS code basta apertar play para arquivos .lf. Para arquivo .lf e gui.py precisa ser usado o terminal do VS code ```python nome-do-arquivo-gui_host.py```
113
+
114
+
115
+ ## Ativar o REPL (em qualquer pasta do computador):
116
+
117
+ transformar a sua linguagem numa ferramenta de linha de comando profissional
118
+
119
+ ```python -m lucidaflow.cli```
120
+
121
+ __________________________________________________________________________________________________________________________________________
122
+
123
+ ## Apoie o Projeto
124
+
125
+ A Lucida-Flow é um projeto independente e de código aberto. Se você gosta da linguagem e quer ver o seu desenvolvimento continuar, considere [tornar-se um patrocinador no GitHub Sponsors](https://github.com/sponsors/marconeed)! O seu apoio é fundamental para a manutenção e evolução do projeto.
@@ -0,0 +1,105 @@
1
+ [Volume 1: O Manual de Referência](https://www.amazon.com.br/dp/B0FJ1HYJN8)
2
+
3
+ [Volume 2: Construindo Aplicações Gráficas](https://www.amazon.com.br/dp/B0FLJ8PNYJ)
4
+
5
+ [Lucida-Flow Support - Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=SoteroApps.lucidaflow-support)
6
+
7
+ [Lucida-Flow - pypi org](https://pypi.org/project/lucidaflow)
8
+
9
+ [Lucida-Flow - GitHub](https://github.com/marconeed/Lucida-Flow)
10
+
11
+ [Sponsor](https://github.com/sponsors/marconeed)
12
+
13
+ ______________________________________________________________________________________________
14
+
15
+ ## Usando o Terminal:
16
+
17
+ OBS:
18
+
19
+ Faça download do repositorio Lucida-Flow em uma pasta usando o terminal Windows ou o terminal do VScode:
20
+
21
+ ```
22
+ git clone https://github.com/marconeed/Lucida-Flow
23
+ cd Lucida-Flow
24
+ ```
25
+
26
+ OBS:
27
+
28
+ Baixe as dependencias usando o terminal Windows ou o terminal do VScode:
29
+
30
+ ```pip install requests```
31
+
32
+ OBS:
33
+
34
+ Para criar programas com interface grafica precisamos criar 2 arquivos o:
35
+
36
+ O arquivo .py contendo os codigos para desenhar a interface grafica
37
+
38
+ O arquivo .lf contendo os codigos da logica do programa
39
+
40
+ Os 2 arquivos precisam estar na raiz da linguagem de programação, onde fica todo o codigo da linguagem, ou você pode colocar em outros locais, mais tera que referenciar nos 2 arquivos as pastas onde estão as importações de que os 2 arquivos precisam para funcionar
41
+
42
+ a linguagem contem codigos das guis usadas no livro, estão na raiz do projeto em uma pasta chamada gui, basta colocar as que for usar na raiz junto ao arquivo .lf. Se quiser deixar onde esta precisa mudar o caminho das importações dos 2 arquivos.
43
+
44
+ OBS:
45
+
46
+ Para executar basta colocar esse comando usando o terminal Windows ou o terminal do VScode na pasta onde esta os arquivos e lembrar de refenciar o arquivo .lf na nome-do-arquivo-gui_host.py:
47
+
48
+ ```python main.py nome_arquivo.lf```
49
+
50
+ ```python nome-do-arquivo-gui_host.py```
51
+
52
+
53
+ ## Usando o VS code:
54
+
55
+ OBS:
56
+
57
+ Faça download da estensão da linguagem para VS code
58
+
59
+ ```https://marketplace.visualstudio.com/items?itemName=SoteroApps.lucidaflow-support```
60
+
61
+ OBS:
62
+
63
+ Baixe as dependencias usando o terminal Windows ou o terminal do VScode:
64
+
65
+ ```pip install requests```
66
+
67
+ OBS:
68
+
69
+ A extensão funciona para auxiliar na contrução do codigo com sugestões e constução da sytanxe sublinhando as palavras, fica melhor programar no VS code
70
+
71
+ O VS code suporta executar o codigo direto nele nome_arquivo.lf, mais para porgramas de interface grafica tera que usar o terminal do VS code para dar o comando para executar. o comando é o mesmo ```python nome-do-arquivo-gui_host.py```
72
+
73
+
74
+ ## Usando o pypi org:
75
+
76
+ OBS:
77
+
78
+ Faça download da linguagem na pypi org
79
+
80
+ ```https://pypi.org/project/lucidaflow```
81
+
82
+ ```pip install lucidaflow```
83
+
84
+ OBS:
85
+
86
+ Usando a linguagem dessa forma você elimina a necessidade dos arquivos da linguagem estar na mesma pasta para funcionar, basta cria uma pasta vazia com o .lf e executar, ou nome-do-arquivo-gui_host.py + .lf e executar se for com interface grafica. Para executar o comando é ```python -m lucidaflow nome_arquivo.lf``` ou ```python nome-do-arquivo-gui_host.py```
87
+
88
+ Usar dessa forma combinado com o VS code e a extensão funciona para auxiliar na contrução do codigo com sugestões e constução da sytanxe sublinhando as palavras, fica melhor programar no VS code
89
+
90
+ Para executar no terminal Windows basta abrir o terminal windows na pasta onde esta o .lf e digitar ```python -m lucidaflow nome-do-arquivo.lf```, ou abrir o terminal windows na pasta onde esta o gui.py e digitar ```python nome-do-arquivo-gui_host.py`` se for com interface grafica
91
+
92
+ Para executar no VS code basta apertar play para arquivos .lf. Para arquivo .lf e gui.py precisa ser usado o terminal do VS code ```python nome-do-arquivo-gui_host.py```
93
+
94
+
95
+ ## Ativar o REPL (em qualquer pasta do computador):
96
+
97
+ transformar a sua linguagem numa ferramenta de linha de comando profissional
98
+
99
+ ```python -m lucidaflow.cli```
100
+
101
+ __________________________________________________________________________________________________________________________________________
102
+
103
+ ## Apoie o Projeto
104
+
105
+ A Lucida-Flow é um projeto independente e de código aberto. Se você gosta da linguagem e quer ver o seu desenvolvimento continuar, considere [tornar-se um patrocinador no GitHub Sponsors](https://github.com/sponsors/marconeed)! O seu apoio é fundamental para a manutenção e evolução do projeto.
@@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"
6
6
 
7
7
  [project]
8
8
  name = "lucidaflow"
9
- version = "1.0.8" # Aumentei a versão para a nova publicação
9
+ version = "1.2.2" # Aumentei a versão para a nova publicação
10
10
  authors = [
11
11
  { name="Marco Lago", email="marconeed2@gmail.com" },
12
12
  ]
@@ -0,0 +1,14 @@
1
+ # src/lucidaflow/__main__.py
2
+ import sys
3
+ from lucidaflow.cli import run_file, start_repl
4
+
5
+ def main():
6
+ # Se um nome de arquivo foi passado, executa o arquivo
7
+ if len(sys.argv) > 1:
8
+ run_file(sys.argv[1])
9
+ # Se não, entra no modo REPL
10
+ else:
11
+ start_repl()
12
+
13
+ if __name__ == "__main__":
14
+ main()
@@ -0,0 +1,100 @@
1
+ # main.py (Versão Final)
2
+
3
+ import sys
4
+ from lucidaflow.lucida_lexer import Lexer
5
+ from lucidaflow.lucida_parser import Parser
6
+ from lucidaflow.lucida_analyzer import SemanticAnalyzer
7
+ from lucidaflow.lucida_interpreter import Interpreter
8
+ from lucidaflow.lucida_errors import LucidaError
9
+ from lucidaflow.lucida_ast import ProgramNode # Import necessário para o "truque" do REPL
10
+ from lucidaflow.lib.parser_patch import apply_patch
11
+ apply_patch()
12
+
13
+ # --- Função para executar um trecho de código ---
14
+ def run_code(source_code, analyzer, interpreter):
15
+ """Função auxiliar que executa as 4 fases da linguagem."""
16
+ # Fases 1 e 2: Lexer e Parser são sempre novos
17
+ lexer = Lexer(source_code)
18
+ parser = Parser(lexer)
19
+ ast = parser.parse()
20
+
21
+ # Fases 3 e 4: Analyzer e Interpreter são reutilizados para manter o estado
22
+ analyzer.visit(ast)
23
+ result = interpreter.visit(ast)
24
+ return result
25
+
26
+ # --- Função para o modo REPL ---
27
+ def start_repl():
28
+ print("Lucida-Flow REPL v1.0")
29
+ print("Digite 'exit' ou 'sair' para terminar.")
30
+
31
+ # Criamos as instâncias FORA do loop para manter o estado (variáveis, etc.)
32
+ analyzer = SemanticAnalyzer()
33
+ interpreter = Interpreter()
34
+
35
+ # Truque para inicializar as tabelas de símbolos do analisador
36
+ # antes de receber o primeiro input.
37
+ analyzer.visit(ProgramNode([]))
38
+
39
+ while True:
40
+ try:
41
+ # 1. READ (Ler)
42
+ line = input("lf> ")
43
+ if line.strip().lower() in ('exit', 'sair'):
44
+ break
45
+
46
+ if not line.strip():
47
+ continue
48
+
49
+ # 2. EVAL & PRINT (Avaliar e Imprimir)
50
+ result = run_code(line, analyzer, interpreter)
51
+
52
+ # Imprime o resultado da expressão, se houver um
53
+ if result is not None:
54
+ print(result)
55
+
56
+ # Captura erros sem quebrar o REPL
57
+ except LucidaError as e:
58
+ print(e)
59
+ except Exception as e:
60
+ # Para erros inesperados do Python, mostra o traceback para nos ajudar
61
+ import traceback
62
+ print("--- ERRO DE SISTEMA NO REPL ---")
63
+ traceback.print_exc()
64
+
65
+ # --- Função para executar um ficheiro ---
66
+ def run_file(filename):
67
+ print(f"--- Lendo código do arquivo: {filename} ---")
68
+ try:
69
+ with open(filename, 'r', encoding='utf-8') as f:
70
+ source_code = f.read()
71
+
72
+ # Para execução de ficheiro, criamos instâncias novas a cada vez
73
+ analyzer = SemanticAnalyzer()
74
+ interpreter = Interpreter()
75
+ run_code(source_code, analyzer, interpreter)
76
+
77
+ print("\n--- Execução Concluída ---")
78
+
79
+ except FileNotFoundError:
80
+ print(f"\nERRO: O arquivo '{filename}' não foi encontrado.")
81
+ except LucidaError as e:
82
+ print(f"\n--- OCORREU UM ERRO NA LUCIDA-FLOW ---")
83
+ print(e)
84
+ except Exception as e:
85
+ print(f"\n--- OCORREU UM ERRO INESPERADO NO SISTEMA ---")
86
+ import traceback
87
+ traceback.print_exc()
88
+
89
+
90
+ # --- Ponto de Entrada Principal ---
91
+ def main():
92
+ # Se um nome de arquivo foi passado, executa o arquivo
93
+ if len(sys.argv) > 1:
94
+ run_file(sys.argv[1])
95
+ # Se não, entra no modo REPL
96
+ else:
97
+ start_repl()
98
+
99
+ if __name__ == "__main__":
100
+ main()
@@ -1,35 +1,35 @@
1
- # lib/dado.py
2
- import random
3
- from lucidaflow.lucida_symbols import VarSymbol, BuiltInFunctionSymbol, ScopedSymbolTable, BuiltInTypeSymbol
4
-
5
- # --- Lógica de Runtime ---
6
- def lf_d6(args):
7
- return random.randint(1, 6)
8
-
9
- def lf_rolar_entre(args):
10
- if len(args) != 2: raise TypeError("rolar_entre() espera 2 argumentos (min, max)")
11
- min_val, max_val = int(args[0]), int(args[1])
12
- return random.randint(min_val, max_val)
13
-
14
- NATIVE_DADO_MODULE = {
15
- 'd6': lf_d6,
16
- 'rolar_entre': lf_rolar_entre,
17
- }
18
-
19
- # --- Descrição Semântica ---
20
- def register_semantics():
21
- int_type = BuiltInTypeSymbol('int')
22
- module_scope = ScopedSymbolTable(scope_name='dado', scope_level=2)
23
- module_scope.define(BuiltInFunctionSymbol(name='d6', params=[], return_type=int_type))
24
-
25
- # --- A DEFINIÇÃO QUE PROVAVELMENTE FALTA ---
26
- module_scope.define(
27
- BuiltInFunctionSymbol(
28
- name='rolar_entre',
29
- params=[VarSymbol('min', int_type), VarSymbol('max', int_type)],
30
- return_type=int_type
31
- )
32
- )
33
- # -----------------------------------------
34
-
1
+ # lib/dado.py
2
+ import random
3
+ from lucidaflow.lucida_symbols import VarSymbol, BuiltInFunctionSymbol, ScopedSymbolTable, BuiltInTypeSymbol
4
+
5
+ # --- Lógica de Runtime ---
6
+ def lf_d6(args):
7
+ return random.randint(1, 6)
8
+
9
+ def lf_rolar_entre(args):
10
+ if len(args) != 2: raise TypeError("rolar_entre() espera 2 argumentos (min, max)")
11
+ min_val, max_val = int(args[0]), int(args[1])
12
+ return random.randint(min_val, max_val)
13
+
14
+ NATIVE_DADO_MODULE = {
15
+ 'd6': lf_d6,
16
+ 'rolar_entre': lf_rolar_entre,
17
+ }
18
+
19
+ # --- Descrição Semântica ---
20
+ def register_semantics():
21
+ int_type = BuiltInTypeSymbol('int')
22
+ module_scope = ScopedSymbolTable(scope_name='dado', scope_level=2)
23
+ module_scope.define(BuiltInFunctionSymbol(name='d6', params=[], return_type=int_type))
24
+
25
+ # --- A DEFINIÇÃO QUE PROVAVELMENTE FALTA ---
26
+ module_scope.define(
27
+ BuiltInFunctionSymbol(
28
+ name='rolar_entre',
29
+ params=[VarSymbol('min', int_type), VarSymbol('max', int_type)],
30
+ return_type=int_type
31
+ )
32
+ )
33
+ # -----------------------------------------
34
+
35
35
  return module_scope
@@ -1,46 +1,46 @@
1
- # lib/json.py
2
- import json
3
- from lucidaflow.lucida_symbols import VarSymbol, BuiltInFunctionSymbol, ScopedSymbolTable, BuiltInTypeSymbol
4
-
5
- # --- PARTE 1: Lógica de Runtime ---
6
-
7
- def lf_json_parse(args):
8
- if len(args) != 1: raise TypeError("parse() espera 1 argumento (a string JSON)")
9
- try:
10
- return json.loads(args[0])
11
- except json.JSONDecodeError as e:
12
- raise ValueError(f"String JSON inválida: {e}")
13
-
14
- def lf_json_stringify(args):
15
- obj_to_stringify = args[0]
16
- indent = int(args[1]) if len(args) > 1 else None
17
- return json.dumps(obj_to_stringify, indent=indent, ensure_ascii=False)
18
-
19
- NATIVE_JSON_MODULE = {
20
- "parse": lf_json_parse,
21
- "stringify": lf_json_stringify,
22
- }
23
-
24
- # --- PARTE 2: Descrição Semântica ---
25
-
26
- def register_semantics():
27
- string_type = BuiltInTypeSymbol('string')
28
- int_type = BuiltInTypeSymbol('int')
29
- any_type = BuiltInTypeSymbol('any')
30
-
31
- module_scope = ScopedSymbolTable(scope_name='json', scope_level=2)
32
- module_scope.define(
33
- BuiltInFunctionSymbol(
34
- name='parse',
35
- params=[VarSymbol('json_string', string_type)],
36
- return_type=any_type
37
- )
38
- )
39
- module_scope.define(
40
- BuiltInFunctionSymbol(
41
- name='stringify',
42
- params=[VarSymbol('objeto', any_type), VarSymbol('indent', int_type, is_optional=True)],
43
- return_type=string_type
44
- )
45
- )
1
+ # lib/json.py
2
+ import json
3
+ from lucidaflow.lucida_symbols import VarSymbol, BuiltInFunctionSymbol, ScopedSymbolTable, BuiltInTypeSymbol
4
+
5
+ # --- PARTE 1: Lógica de Runtime ---
6
+
7
+ def lf_json_parse(args):
8
+ if len(args) != 1: raise TypeError("parse() espera 1 argumento (a string JSON)")
9
+ try:
10
+ return json.loads(args[0])
11
+ except json.JSONDecodeError as e:
12
+ raise ValueError(f"String JSON inválida: {e}")
13
+
14
+ def lf_json_stringify(args):
15
+ obj_to_stringify = args[0]
16
+ indent = int(args[1]) if len(args) > 1 else None
17
+ return json.dumps(obj_to_stringify, indent=indent, ensure_ascii=False)
18
+
19
+ NATIVE_JSON_MODULE = {
20
+ "parse": lf_json_parse,
21
+ "stringify": lf_json_stringify,
22
+ }
23
+
24
+ # --- PARTE 2: Descrição Semântica ---
25
+
26
+ def register_semantics():
27
+ string_type = BuiltInTypeSymbol('string')
28
+ int_type = BuiltInTypeSymbol('int')
29
+ any_type = BuiltInTypeSymbol('any')
30
+
31
+ module_scope = ScopedSymbolTable(scope_name='json', scope_level=2)
32
+ module_scope.define(
33
+ BuiltInFunctionSymbol(
34
+ name='parse',
35
+ params=[VarSymbol('json_string', string_type)],
36
+ return_type=any_type
37
+ )
38
+ )
39
+ module_scope.define(
40
+ BuiltInFunctionSymbol(
41
+ name='stringify',
42
+ params=[VarSymbol('objeto', any_type), VarSymbol('indent', int_type, is_optional=True)],
43
+ return_type=string_type
44
+ )
45
+ )
46
46
  return module_scope
@@ -0,0 +1,54 @@
1
+ # lib/math.py
2
+ from lucidaflow.lucida_symbols import VarSymbol, BuiltInFunctionSymbol, ScopedSymbolTable, BuiltInTypeSymbol
3
+ import math
4
+
5
+ # --- PARTE 1: LÓGICA DE RUNTIME ---
6
+
7
+ def lf_soma(args):
8
+ if len(args) != 2: raise TypeError("soma() espera 2 argumentos.")
9
+ return float(args[0]) + float(args[1])
10
+
11
+ def lf_sub(args):
12
+ if len(args) != 2: raise TypeError("sub() espera 2 argumentos.")
13
+ return float(args[0]) - float(args[1])
14
+
15
+ def lf_mult(args):
16
+ if len(args) != 2: raise TypeError("mult() espera 2 argumentos.")
17
+ return float(args[0]) * float(args[1])
18
+
19
+ def lf_div(args):
20
+ if len(args) != 2: raise TypeError("div() espera 2 argumentos.")
21
+ if float(args[1]) == 0: raise ZeroDivisionError("Divisão por zero.")
22
+ return float(args[0]) / float(args[1])
23
+
24
+ def lf_pot(args):
25
+ if len(args) != 2: raise TypeError("pot() espera 2 argumentos.")
26
+ return float(args[0]) ** float(args[1])
27
+
28
+
29
+ # O dicionário que o Interpreter irá usar
30
+ NATIVE_MATH_MODULE = {
31
+ "soma": lf_soma,
32
+ "sub": lf_sub,
33
+ "mult": lf_mult,
34
+ "div": lf_div,
35
+ "pot": lf_pot,
36
+ "pi": math.pi,
37
+ }
38
+
39
+ # --- PARTE 2: DESCRIÇÃO SEMÂNTICA ---
40
+
41
+ def register_semantics():
42
+ float_type = BuiltInTypeSymbol('float')
43
+ any_type = BuiltInTypeSymbol('any')
44
+
45
+ module_scope = ScopedSymbolTable(scope_name='math', scope_level=2)
46
+
47
+ module_scope.define(VarSymbol('pi', float_type))
48
+ module_scope.define(BuiltInFunctionSymbol('soma', params=[VarSymbol('a', any_type), VarSymbol('b', any_type)], return_type=float_type))
49
+ module_scope.define(BuiltInFunctionSymbol('sub', params=[VarSymbol('a', any_type), VarSymbol('b', any_type)], return_type=float_type))
50
+ module_scope.define(BuiltInFunctionSymbol('mult', params=[VarSymbol('a', any_type), VarSymbol('b', any_type)], return_type=float_type))
51
+ module_scope.define(BuiltInFunctionSymbol('div', params=[VarSymbol('a', any_type), VarSymbol('b', any_type)], return_type=float_type))
52
+ module_scope.define(BuiltInFunctionSymbol('pot', params=[VarSymbol('a', any_type), VarSymbol('b', any_type)], return_type=float_type))
53
+
54
+ return module_scope
@@ -0,0 +1,61 @@
1
+ # lib/media.py
2
+ import pygame
3
+ from lucidaflow.lucida_symbols import VarSymbol, BuiltInFunctionSymbol, ScopedSymbolTable, BuiltInTypeSymbol
4
+
5
+ # Inicializa o mixer do Pygame uma vez
6
+ pygame.mixer.init()
7
+
8
+ # --- Funções de Runtime ---
9
+ def lf_media_carregar(args):
10
+ pygame.mixer.music.load(str(args[0]))
11
+ return None
12
+
13
+ def lf_media_tocar(args):
14
+ pygame.mixer.music.play()
15
+ return None
16
+
17
+ def lf_media_pausar(args):
18
+ pygame.mixer.music.pause()
19
+ return None
20
+
21
+ def lf_media_continuar(args):
22
+ pygame.mixer.music.unpause()
23
+ return None
24
+
25
+ def lf_media_parar(args):
26
+ pygame.mixer.music.stop()
27
+ return None
28
+
29
+ def lf_media_definir_volume(args):
30
+ # Volume é de 0.0 a 1.0
31
+ volume = float(args[0])
32
+ pygame.mixer.music.set_volume(volume)
33
+ return None
34
+
35
+ def lf_media_esta_a_tocar(args):
36
+ return pygame.mixer.music.get_busy()
37
+
38
+ NATIVE_MEDIA_MODULE = {
39
+ "carregar": lf_media_carregar,
40
+ "tocar": lf_media_tocar,
41
+ "pausar": lf_media_pausar,
42
+ "continuar": lf_media_continuar,
43
+ "parar": lf_media_parar,
44
+ "definir_volume": lf_media_definir_volume,
45
+ "esta_a_tocar": lf_media_esta_a_tocar,
46
+ }
47
+
48
+ # --- Descrição Semântica ---
49
+ def register_semantics():
50
+ string_type = BuiltInTypeSymbol('string'); float_type = BuiltInTypeSymbol('float')
51
+ bool_type = BuiltInTypeSymbol('bool'); null_type = BuiltInTypeSymbol('null')
52
+
53
+ scope = ScopedSymbolTable(scope_name='media', scope_level=2)
54
+ scope.define(BuiltInFunctionSymbol('carregar', params=[VarSymbol('caminho', string_type)], return_type=null_type))
55
+ scope.define(BuiltInFunctionSymbol('tocar', params=[], return_type=null_type))
56
+ scope.define(BuiltInFunctionSymbol('pausar', params=[], return_type=null_type))
57
+ scope.define(BuiltInFunctionSymbol('continuar', params=[], return_type=null_type))
58
+ scope.define(BuiltInFunctionSymbol('parar', params=[], return_type=null_type))
59
+ scope.define(BuiltInFunctionSymbol('definir_volume', params=[VarSymbol('volume', float_type)], return_type=null_type))
60
+ scope.define(BuiltInFunctionSymbol('esta_a_tocar', params=[], return_type=bool_type))
61
+ return scope
@@ -0,0 +1,24 @@
1
+ # lib/parser_patch.py
2
+ from lucidaflow.lucida_parser import Parser
3
+
4
+ def apply_patch():
5
+ """
6
+ Esta função aplica um "remendo" em tempo de execução na classe Parser
7
+ para corrigir a assinatura do método de erro.
8
+ """
9
+ print("-> Aplicando patch no Parser...")
10
+
11
+ # 1. Guardamos a função de erro original
12
+ original_error_method = Parser.error
13
+
14
+ # 2. Definimos uma nova função de erro que aceita o argumento 'token'
15
+ def novo_metodo_de_erro(self, msg="Sintaxe inválida", token=None):
16
+ # Esta nova função simplesmente chama a original da forma que ela espera
17
+ token_to_report = token if token else self.current_token
18
+ detailed_msg = f'{msg} (token: {token_to_report})'
19
+ # A chamada à função original precisa de ser feita com o 'self' correto
20
+ original_error_method(self, detailed_msg)
21
+
22
+ # 3. Substituímos a função de erro antiga da classe Parser pela nossa nova versão
23
+ Parser.error = novo_metodo_de_erro
24
+ print("-> Patch do Parser aplicado com sucesso!")