@designliquido/delegua-node 1.3.15 → 1.3.17

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.
Files changed (60) hide show
  1. package/bin/package.json +11 -11
  2. package/delegua.d.ts +21 -21
  3. package/delegua.js +74 -74
  4. package/delegua.js.map +1 -1
  5. package/depuracao/index.d.ts +1 -1
  6. package/depuracao/index.js +17 -17
  7. package/depuracao/servidor-depuracao.d.ts +41 -42
  8. package/depuracao/servidor-depuracao.d.ts.map +1 -1
  9. package/depuracao/servidor-depuracao.js +297 -297
  10. package/depuracao/servidor-depuracao.js.map +1 -1
  11. package/execucao.d.ts +1 -1
  12. package/execucao.js +48 -48
  13. package/execucao.js.map +1 -1
  14. package/formatadores/index.d.ts +6 -6
  15. package/formatadores/index.js +57 -57
  16. package/formatadores/index.js.map +1 -1
  17. package/importador/importador-javascript.d.ts +15 -15
  18. package/importador/importador-javascript.js +62 -62
  19. package/importador/importador-javascript.js.map +1 -1
  20. package/importador/importador.d.ts +28 -28
  21. package/importador/importador.js +81 -81
  22. package/importador/importador.js.map +1 -1
  23. package/importador/index.d.ts +2 -2
  24. package/importador/index.js +18 -18
  25. package/importador/retorno-importador.d.ts +9 -9
  26. package/importador/retorno-importador.js +2 -2
  27. package/index.d.ts +3 -3
  28. package/index.js +19 -19
  29. package/interfaces/delegua-interface.d.ts +6 -6
  30. package/interfaces/delegua-interface.js +2 -2
  31. package/interfaces/importador-interface.d.ts +8 -8
  32. package/interfaces/importador-interface.js +2 -2
  33. package/interfaces/index.d.ts +2 -2
  34. package/interfaces/index.js +18 -18
  35. package/interfaces/nucleo-execucao-interface.d.ts +12 -12
  36. package/interfaces/nucleo-execucao-interface.js +2 -2
  37. package/interpretador/index.d.ts +1 -1
  38. package/interpretador/index.js +17 -17
  39. package/interpretador/interpretador-com-depuracao-importacao.d.ts +15 -15
  40. package/interpretador/interpretador-com-depuracao-importacao.js +76 -76
  41. package/interpretador/interpretador-com-depuracao-importacao.js.map +1 -1
  42. package/interpretador/interpretador.d.ts +19 -19
  43. package/interpretador/interpretador.js +80 -80
  44. package/interpretador/interpretador.js.map +1 -1
  45. package/interpretador/mecanismo-importacao-bibliotecas.d.ts +2 -2
  46. package/interpretador/mecanismo-importacao-bibliotecas.js +131 -132
  47. package/interpretador/mecanismo-importacao-bibliotecas.js.map +1 -1
  48. package/lexador/lexador-json.d.ts +20 -20
  49. package/lexador/lexador-json.js +64 -64
  50. package/lexador/lexador-json.js.map +1 -1
  51. package/nucleo-comum.d.ts +12 -12
  52. package/nucleo-comum.js +48 -48
  53. package/nucleo-comum.js.map +1 -1
  54. package/nucleo-execucao.d.ts +72 -72
  55. package/nucleo-execucao.js +358 -358
  56. package/nucleo-execucao.js.map +1 -1
  57. package/nucleo-traducao.d.ts +36 -36
  58. package/nucleo-traducao.js +127 -127
  59. package/nucleo-traducao.js.map +1 -1
  60. package/package.json +11 -11
@@ -1,359 +1,359 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.NucleoExecucao = void 0;
30
- const caminho = __importStar(require("path"));
31
- const readline = __importStar(require("readline"));
32
- const chalk_1 = __importDefault(require("chalk"));
33
- const json_colorizer_1 = __importDefault(require("json-colorizer"));
34
- const avaliador_sintatico_1 = require("@designliquido/delegua/avaliador-sintatico");
35
- const dialetos_1 = require("@designliquido/delegua/avaliador-sintatico/dialetos");
36
- const dialetos_2 = require("@designliquido/delegua/interpretador/dialetos");
37
- const lexador_1 = require("@designliquido/delegua/lexador");
38
- const dialetos_3 = require("@designliquido/delegua/lexador/dialetos");
39
- const lexador_2 = require("@designliquido/birl/lexador");
40
- const avaliador_sintatico_2 = require("@designliquido/birl/avaliador-sintatico");
41
- const interpretador_1 = require("@designliquido/birl/interpretador");
42
- // Aparentemente o Jest não trabalha bem com barreling de pacotes externos,
43
- // então cada importação precisa ser feita separadamente.
44
- const lexador_3 = require("@designliquido/mapler/lexador");
45
- const avaliador_sintatico_3 = require("@designliquido/mapler/avaliador-sintatico");
46
- const resolvedor_1 = require("@designliquido/mapler/resolvedor");
47
- const interpretador_2 = require("@designliquido/mapler/interpretador");
48
- const lexador_4 = require("@designliquido/portugol-studio/lexador");
49
- const avaliador_sintatico_4 = require("@designliquido/portugol-studio/avaliador-sintatico");
50
- const interpretador_3 = require("@designliquido/portugol-studio/interpretador");
51
- const avaliador_sintatico_5 = require("@designliquido/potigol/avaliador-sintatico");
52
- const interpretador_4 = require("@designliquido/potigol/interpretador");
53
- const lexador_5 = require("@designliquido/potigol/lexador");
54
- const lexador_6 = require("@designliquido/visualg/lexador");
55
- const avaliador_sintatico_6 = require("@designliquido/visualg/avaliador-sintatico");
56
- const interpretador_5 = require("@designliquido/visualg/interpretador");
57
- const importador_1 = require("./importador");
58
- const depuracao_1 = require("./depuracao");
59
- const formatadores_1 = require("./formatadores");
60
- const lexador_json_1 = require("./lexador/lexador-json");
61
- const interpretador_6 = require("./interpretador");
62
- const interpretador_com_depuracao_importacao_1 = require("./interpretador/interpretador-com-depuracao-importacao");
63
- const nucleo_comum_1 = require("./nucleo-comum");
64
- class NucleoExecucao extends nucleo_comum_1.NucleoComum {
65
- constructor(versao, funcaoDeRetorno = null, funcaoDeRetornoMesmaLinha = null, funcaoLimpaTela = null) {
66
- super();
67
- this.dialetos = {
68
- birl: "BIRL",
69
- delegua: "padrão",
70
- delégua: "padrão",
71
- egua: "Égua",
72
- égua: "Égua",
73
- mapler: "Mapler",
74
- pitugues: "Pituguês",
75
- pituguês: "Pituguês",
76
- potigol: "Potigol",
77
- "portugol-studio": "Portugol Studio",
78
- visualg: "VisuAlg",
79
- };
80
- this.versao = versao;
81
- this.arquivosAbertos = {};
82
- this.conteudoArquivosAbertos = {};
83
- this.funcaoDeRetorno = funcaoDeRetorno || console.log;
84
- // `process.stdout.write.bind(process.stdout)` é necessário por causa de
85
- // https://stackoverflow.com/questions/28874665/node-js-cannot-read-property-defaultencoding-of-undefined
86
- this.funcaoDeRetornoMesmaLinha =
87
- funcaoDeRetornoMesmaLinha ||
88
- process.stdout.write.bind(process.stdout);
89
- this.funcaoLimpaTela = funcaoLimpaTela || this.funcaoLimpaTelaPadrao;
90
- }
91
- funcaoLimpaTelaPadrao() {
92
- process.stdout.write("\x1Bc");
93
- }
94
- configurarDialeto(dialeto = "delegua", performance = false, depurador = false) {
95
- this.dialeto = dialeto;
96
- this.modoDepuracao = depurador;
97
- switch (dialeto) {
98
- case "birl":
99
- this.lexador = new lexador_2.LexadorBirl();
100
- this.avaliadorSintatico = new avaliador_sintatico_2.AvaliadorSintaticoBirl();
101
- this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
102
- this.interpretador = new interpretador_1.InterpretadorBirl(process.cwd(), this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha);
103
- break;
104
- case "egua":
105
- if (depurador) {
106
- throw new Error("Dialeto " + dialeto + " não suporta depuração.");
107
- }
108
- this.lexador = new dialetos_3.LexadorEguaClassico();
109
- this.avaliadorSintatico = new dialetos_1.AvaliadorSintaticoEguaClassico();
110
- this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
111
- this.interpretador = new dialetos_2.InterpretadorEguaClassico(process.cwd());
112
- break;
113
- case "mapler":
114
- this.lexador = new lexador_3.LexadorMapler();
115
- this.avaliadorSintatico = new avaliador_sintatico_3.AvaliadorSintaticoMapler();
116
- this.resolvedor = new resolvedor_1.ResolvedorMapler();
117
- this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
118
- this.interpretador = depurador
119
- ? new interpretador_2.InterpretadorMaplerComDepuracao(process.cwd(), this.funcaoDeRetorno)
120
- : new interpretador_2.InterpretadorMapler(process.cwd(), false, this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha);
121
- break;
122
- case "pitugues":
123
- case "pituguês":
124
- this.lexador = new dialetos_3.LexadorPitugues();
125
- this.avaliadorSintatico = new dialetos_1.AvaliadorSintaticoPitugues();
126
- this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
127
- this.interpretador = depurador
128
- ? new interpretador_com_depuracao_importacao_1.InterpretadorComDepuracaoImportacao(this.importador, process.cwd(), this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha)
129
- : new interpretador_6.Interpretador(this.importador, process.cwd(), performance, this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha);
130
- break;
131
- case "portugol-ipt":
132
- this.lexador = new dialetos_3.LexadorPortugolIpt();
133
- this.avaliadorSintatico = new dialetos_1.AvaliadorSintaticoPortugolIpt();
134
- this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
135
- this.interpretador = depurador
136
- ? new dialetos_2.InterpretadorPortugolIpt(process.cwd(), this.funcaoDeRetornoMesmaLinha, this.funcaoDeRetornoMesmaLinha)
137
- : new dialetos_2.InterpretadorPortugolIpt(process.cwd(), this.funcaoDeRetornoMesmaLinha, this.funcaoDeRetornoMesmaLinha);
138
- break;
139
- case "portugol-studio":
140
- this.lexador = new lexador_4.LexadorPortugolStudio();
141
- this.avaliadorSintatico =
142
- new avaliador_sintatico_4.AvaliadorSintaticoPortugolStudio();
143
- this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
144
- this.interpretador = depurador
145
- ? new interpretador_3.InterpretadorPortugolStudioComDepuracao(process.cwd(), this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha, this.funcaoLimpaTela)
146
- : new interpretador_3.InterpretadorPortugolStudio(process.cwd(), performance, this.funcaoDeRetorno, this.funcaoLimpaTela);
147
- break;
148
- case "potigol":
149
- this.lexador = new lexador_5.LexadorPotigol();
150
- this.avaliadorSintatico = new avaliador_sintatico_5.AvaliadorSintaticoPotigol();
151
- this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
152
- this.interpretador = depurador
153
- ? new interpretador_4.InterpretadorPotigolComDepuracao(process.cwd(), this.funcaoDeRetorno, this.funcaoDeRetorno)
154
- : new interpretador_4.InterpretadorPotigol(process.cwd(), performance, this.funcaoDeRetorno);
155
- break;
156
- case "visualg":
157
- this.lexador = new lexador_6.LexadorVisuAlg();
158
- this.avaliadorSintatico = new avaliador_sintatico_6.AvaliadorSintaticoVisuAlg();
159
- this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
160
- this.interpretador = depurador
161
- ? new interpretador_5.InterpretadorVisuAlgComDepuracao(process.cwd(), this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha, this.funcaoLimpaTela)
162
- : new interpretador_5.InterpretadorVisuAlg(process.cwd(), false, this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha, this.funcaoLimpaTela);
163
- break;
164
- default:
165
- this.lexador = new lexador_1.Lexador(performance);
166
- this.avaliadorSintatico = new avaliador_sintatico_1.AvaliadorSintatico(performance);
167
- this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
168
- this.interpretador = depurador
169
- ? new interpretador_com_depuracao_importacao_1.InterpretadorComDepuracaoImportacao(this.importador, process.cwd(), this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha)
170
- : new interpretador_6.Interpretador(this.importador, process.cwd(), performance, this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha);
171
- break;
172
- }
173
- if (depurador) {
174
- this.iniciarDepuracao();
175
- }
176
- }
177
- async executarCodigoComoArgumento(codigo) {
178
- const retornoLexador = this.lexador.mapear([codigo], -1);
179
- const retornoAvaliadorSintatico = this.avaliadorSintatico.analisar(retornoLexador, -1);
180
- const { erros } = await this.executar({
181
- conteudoArquivo: [codigo],
182
- nomeArquivo: "",
183
- hashArquivo: -1,
184
- retornoLexador: retornoLexador,
185
- retornoAvaliadorSintatico: retornoAvaliadorSintatico,
186
- });
187
- if (erros.length > 0)
188
- process.exit(70); // Código com exceções não tratadas
189
- }
190
- /**
191
- * Execução por arquivo.
192
- * @param caminhoRelativoArquivo O caminho no sistema operacional do arquivo a ser aberto.
193
- */
194
- async carregarEExecutarArquivo(caminhoRelativoArquivo) {
195
- const caminhoAbsolutoPrimeiroArquivo = caminho.resolve(caminhoRelativoArquivo);
196
- const novoDiretorioBase = caminho.dirname(caminhoAbsolutoPrimeiroArquivo);
197
- this.importador.diretorioBase = novoDiretorioBase;
198
- this.interpretador.diretorioBase = novoDiretorioBase;
199
- const retornoImportador = this.importador.importar(caminhoRelativoArquivo, true);
200
- if (this.afericaoErros(retornoImportador)) {
201
- process.exit(65); // Código para erro de avaliação antes da execução
202
- }
203
- let errosExecucao = {
204
- lexador: [],
205
- avaliadorSintatico: [],
206
- interpretador: [],
207
- };
208
- // Se a interface de entrada e saída ainda não está definida, definimos agora.
209
- // A interface pode ser definida por um teste unitário antes da execução
210
- // aqui, por exemplo.
211
- let interfaceLeitura;
212
- if (!this.interpretador.interfaceEntradaSaida) {
213
- interfaceLeitura = readline.createInterface({
214
- input: process.stdin,
215
- output: process.stdout,
216
- prompt: "\n> ",
217
- });
218
- this.interpretador.interfaceEntradaSaida = interfaceLeitura;
219
- }
220
- if (this.modoDepuracao) {
221
- let declaracoes = retornoImportador.retornoAvaliadorSintatico.declaracoes;
222
- if (this.resolvedor) {
223
- declaracoes = await this.resolvedor.resolver(declaracoes);
224
- }
225
- try {
226
- this.interpretador.prepararParaDepuracao(declaracoes);
227
- }
228
- catch (erro) {
229
- console.error(chalk_1.default.red(`[Erro de execução]`) +
230
- ` Dialeto ${this.dialeto} não suporta depuração.`);
231
- }
232
- }
233
- else {
234
- const { erros } = await this.executar(retornoImportador);
235
- errosExecucao = erros;
236
- }
237
- if (interfaceLeitura &&
238
- (interfaceLeitura instanceof readline.Interface ||
239
- interfaceLeitura.hasOwnProperty("close"))) {
240
- interfaceLeitura.close();
241
- }
242
- if (errosExecucao.length > 0)
243
- process.exitCode = 70; // Código com exceções não tratadas
244
- return;
245
- }
246
- /**
247
- * LAIR (Leia-Avalie-Imprima-Repita) é o modo em que Delégua executa em modo console,
248
- * ou seja, esperando como entrada linhas de código fornecidas pelo usuário.
249
- */
250
- async iniciarLairDelegua() {
251
- const lexadorJson = new lexador_json_1.LexadorJson();
252
- const formatadorJson = new formatadores_1.FormatadorJson();
253
- this.funcaoDeRetorno(`Usando dialeto: ${this.dialetos[this.dialeto]}`);
254
- this.funcaoDeRetorno(`Console da Linguagem Delégua v${this.versao}`);
255
- this.funcaoDeRetorno("Pressione Ctrl + C para sair");
256
- const interfaceLeitura = readline.createInterface({
257
- input: process.stdin,
258
- output: process.stdout,
259
- prompt: "\ndelegua> ",
260
- });
261
- const isto = this;
262
- this.interpretador.interfaceEntradaSaida = interfaceLeitura;
263
- interfaceLeitura.prompt();
264
- interfaceLeitura.on("line", async (linha) => {
265
- const { resultado } = await isto.executarUmaLinha(linha);
266
- if (resultado && resultado.length) {
267
- const resultadoLexacao = lexadorJson.getTokens(resultado[0]);
268
- const resultadoFormatacao = formatadorJson.formatar(resultadoLexacao);
269
- isto.funcaoDeRetorno((0, json_colorizer_1.default)(resultadoFormatacao));
270
- }
271
- interfaceLeitura.prompt();
272
- });
273
- }
274
- /**
275
- * A execução do código de fato.
276
- * @param retornoImportador Dados retornados do Importador, como o retorno do Lexador, do Avaliador
277
- * Sintático e respectivos erros.
278
- * @param manterAmbiente Indicação se ambiente deve ser mantido ou não. Normalmente verdadeiro
279
- * para LAIR, falso para execução por arquivo.
280
- * @returns Um objeto com o resultado da execução.
281
- */
282
- async executar(retornoImportador, manterAmbiente = false) {
283
- var _a, _b;
284
- let declaracoes = retornoImportador.retornoAvaliadorSintatico.declaracoes;
285
- if (this.resolvedor) {
286
- declaracoes = await this.resolvedor.resolver(declaracoes);
287
- }
288
- const retornoInterpretador = await this.interpretador.interpretar(declaracoes, manterAmbiente);
289
- if (retornoInterpretador.erros.length > 0) {
290
- for (const erroInterpretador of retornoInterpretador.erros) {
291
- if (erroInterpretador.hasOwnProperty("simbolo")) {
292
- this.erroEmTempoDeExecucao(erroInterpretador);
293
- }
294
- else {
295
- if (erroInterpretador.hasOwnProperty("erroInterno")) {
296
- const erroEmJavaScript = erroInterpretador;
297
- console.error(chalk_1.default.red(`[Linha: ${erroEmJavaScript.linha}] Erro em JavaScript: `) + `${(_a = erroEmJavaScript.erroInterno) === null || _a === void 0 ? void 0 : _a.message}`);
298
- console.error(chalk_1.default.red(`Pilha de execução: `) +
299
- `${(_b = erroEmJavaScript.erroInterno) === null || _b === void 0 ? void 0 : _b.stack}`);
300
- }
301
- else {
302
- console.error(chalk_1.default.red(`Erro em JavaScript: `) +
303
- JSON.stringify(erroInterpretador));
304
- }
305
- }
306
- }
307
- }
308
- return {
309
- erros: retornoInterpretador.erros,
310
- resultado: retornoInterpretador.resultado,
311
- };
312
- }
313
- /**
314
- * Executa uma linha. Usado pelo modo LAIR e pelo servidor de depuração, quando recebe um comando 'avaliar'.
315
- * @param linha A linha a ser avaliada.
316
- * @returns O resultado da execução, com os retornos e respectivos erros, se houverem.
317
- */
318
- async executarUmaLinha(linha) {
319
- const retornoLexador = this.lexador.mapear([linha], -1);
320
- const retornoAvaliadorSintatico = this.avaliadorSintatico.analisar(retornoLexador, -1);
321
- if (this.afericaoErros({
322
- retornoLexador,
323
- retornoAvaliadorSintatico,
324
- })) {
325
- return { resultado: [] };
326
- }
327
- return await this.executar({
328
- retornoLexador,
329
- retornoAvaliadorSintatico,
330
- }, true);
331
- }
332
- /**
333
- * Instancia um servidor de depuração, normalmente recebendo requisições na porta 7777.
334
- */
335
- iniciarDepuracao() {
336
- this.servidorDepuracao = new depuracao_1.ServidorDepuracao(this);
337
- this.servidorDepuracao.iniciarServidorDepuracao();
338
- this.interpretador.finalizacaoDaExecucao =
339
- this.finalizarDepuracao.bind(this);
340
- }
341
- /**
342
- * Pede ao servidor de depuração que finalize a execução.
343
- * Se não for feito, o servidor de depuração mantém um _stream_ aberto e nunca finaliza.
344
- * Mais informações: https://stackoverflow.com/a/47456805/1314276
345
- */
346
- finalizarDepuracao() {
347
- if (this.servidorDepuracao) {
348
- this.servidorDepuracao.finalizarServidorDepuracao();
349
- }
350
- }
351
- erroEmTempoDeExecucao(erro) {
352
- var _a;
353
- const linha = ((_a = erro === null || erro === void 0 ? void 0 : erro.simbolo) === null || _a === void 0 ? void 0 : _a.linha) || (erro === null || erro === void 0 ? void 0 : erro.linha);
354
- const mensagem = (erro === null || erro === void 0 ? void 0 : erro.mensagem) || (erro === null || erro === void 0 ? void 0 : erro.message);
355
- console.error(chalk_1.default.red(`Erro: [Linha: ${linha}]`) + ` ${mensagem}`);
356
- }
357
- }
358
- exports.NucleoExecucao = NucleoExecucao;
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.NucleoExecucao = void 0;
30
+ const caminho = __importStar(require("path"));
31
+ const readline = __importStar(require("readline"));
32
+ const chalk_1 = __importDefault(require("chalk"));
33
+ const json_colorizer_1 = __importDefault(require("json-colorizer"));
34
+ const avaliador_sintatico_1 = require("@designliquido/delegua/avaliador-sintatico");
35
+ const dialetos_1 = require("@designliquido/delegua/avaliador-sintatico/dialetos");
36
+ const dialetos_2 = require("@designliquido/delegua/interpretador/dialetos");
37
+ const lexador_1 = require("@designliquido/delegua/lexador");
38
+ const dialetos_3 = require("@designliquido/delegua/lexador/dialetos");
39
+ const lexador_2 = require("@designliquido/birl/lexador");
40
+ const avaliador_sintatico_2 = require("@designliquido/birl/avaliador-sintatico");
41
+ const interpretador_1 = require("@designliquido/birl/interpretador");
42
+ // Aparentemente o Jest não trabalha bem com barreling de pacotes externos,
43
+ // então cada importação precisa ser feita separadamente.
44
+ const lexador_3 = require("@designliquido/mapler/lexador");
45
+ const avaliador_sintatico_3 = require("@designliquido/mapler/avaliador-sintatico");
46
+ const resolvedor_1 = require("@designliquido/mapler/resolvedor");
47
+ const interpretador_2 = require("@designliquido/mapler/interpretador");
48
+ const lexador_4 = require("@designliquido/portugol-studio/lexador");
49
+ const avaliador_sintatico_4 = require("@designliquido/portugol-studio/avaliador-sintatico");
50
+ const interpretador_3 = require("@designliquido/portugol-studio/interpretador");
51
+ const avaliador_sintatico_5 = require("@designliquido/potigol/avaliador-sintatico");
52
+ const interpretador_4 = require("@designliquido/potigol/interpretador");
53
+ const lexador_5 = require("@designliquido/potigol/lexador");
54
+ const lexador_6 = require("@designliquido/visualg/lexador");
55
+ const avaliador_sintatico_6 = require("@designliquido/visualg/avaliador-sintatico");
56
+ const interpretador_5 = require("@designliquido/visualg/interpretador");
57
+ const importador_1 = require("./importador");
58
+ const depuracao_1 = require("./depuracao");
59
+ const formatadores_1 = require("./formatadores");
60
+ const lexador_json_1 = require("./lexador/lexador-json");
61
+ const interpretador_6 = require("./interpretador");
62
+ const interpretador_com_depuracao_importacao_1 = require("./interpretador/interpretador-com-depuracao-importacao");
63
+ const nucleo_comum_1 = require("./nucleo-comum");
64
+ class NucleoExecucao extends nucleo_comum_1.NucleoComum {
65
+ constructor(versao, funcaoDeRetorno = null, funcaoDeRetornoMesmaLinha = null, funcaoLimpaTela = null) {
66
+ super();
67
+ this.dialetos = {
68
+ birl: "BIRL",
69
+ delegua: "padrão",
70
+ delégua: "padrão",
71
+ egua: "Égua",
72
+ égua: "Égua",
73
+ mapler: "Mapler",
74
+ pitugues: "Pituguês",
75
+ pituguês: "Pituguês",
76
+ potigol: "Potigol",
77
+ "portugol-studio": "Portugol Studio",
78
+ visualg: "VisuAlg",
79
+ };
80
+ this.versao = versao;
81
+ this.arquivosAbertos = {};
82
+ this.conteudoArquivosAbertos = {};
83
+ this.funcaoDeRetorno = funcaoDeRetorno || console.log;
84
+ // `process.stdout.write.bind(process.stdout)` é necessário por causa de
85
+ // https://stackoverflow.com/questions/28874665/node-js-cannot-read-property-defaultencoding-of-undefined
86
+ this.funcaoDeRetornoMesmaLinha =
87
+ funcaoDeRetornoMesmaLinha ||
88
+ process.stdout.write.bind(process.stdout);
89
+ this.funcaoLimpaTela = funcaoLimpaTela || this.funcaoLimpaTelaPadrao;
90
+ }
91
+ funcaoLimpaTelaPadrao() {
92
+ process.stdout.write("\x1Bc");
93
+ }
94
+ configurarDialeto(dialeto = "delegua", performance = false, depurador = false) {
95
+ this.dialeto = dialeto;
96
+ this.modoDepuracao = depurador;
97
+ switch (dialeto) {
98
+ case "birl":
99
+ this.lexador = new lexador_2.LexadorBirl();
100
+ this.avaliadorSintatico = new avaliador_sintatico_2.AvaliadorSintaticoBirl();
101
+ this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
102
+ this.interpretador = new interpretador_1.InterpretadorBirl(process.cwd(), this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha);
103
+ break;
104
+ case "egua":
105
+ if (depurador) {
106
+ throw new Error("Dialeto " + dialeto + " não suporta depuração.");
107
+ }
108
+ this.lexador = new dialetos_3.LexadorEguaClassico();
109
+ this.avaliadorSintatico = new dialetos_1.AvaliadorSintaticoEguaClassico();
110
+ this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
111
+ this.interpretador = new dialetos_2.InterpretadorEguaClassico(process.cwd());
112
+ break;
113
+ case "mapler":
114
+ this.lexador = new lexador_3.LexadorMapler();
115
+ this.avaliadorSintatico = new avaliador_sintatico_3.AvaliadorSintaticoMapler();
116
+ this.resolvedor = new resolvedor_1.ResolvedorMapler();
117
+ this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
118
+ this.interpretador = depurador
119
+ ? new interpretador_2.InterpretadorMaplerComDepuracao(process.cwd(), this.funcaoDeRetorno)
120
+ : new interpretador_2.InterpretadorMapler(process.cwd(), false, this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha);
121
+ break;
122
+ case "pitugues":
123
+ case "pituguês":
124
+ this.lexador = new dialetos_3.LexadorPitugues();
125
+ this.avaliadorSintatico = new dialetos_1.AvaliadorSintaticoPitugues();
126
+ this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
127
+ this.interpretador = depurador
128
+ ? new interpretador_com_depuracao_importacao_1.InterpretadorComDepuracaoImportacao(this.importador, process.cwd(), this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha)
129
+ : new interpretador_6.Interpretador(this.importador, process.cwd(), performance, this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha);
130
+ break;
131
+ case "portugol-ipt":
132
+ this.lexador = new dialetos_3.LexadorPortugolIpt();
133
+ this.avaliadorSintatico = new dialetos_1.AvaliadorSintaticoPortugolIpt();
134
+ this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
135
+ this.interpretador = depurador
136
+ ? new dialetos_2.InterpretadorPortugolIpt(process.cwd(), this.funcaoDeRetornoMesmaLinha, this.funcaoDeRetornoMesmaLinha)
137
+ : new dialetos_2.InterpretadorPortugolIpt(process.cwd(), this.funcaoDeRetornoMesmaLinha, this.funcaoDeRetornoMesmaLinha);
138
+ break;
139
+ case "portugol-studio":
140
+ this.lexador = new lexador_4.LexadorPortugolStudio();
141
+ this.avaliadorSintatico =
142
+ new avaliador_sintatico_4.AvaliadorSintaticoPortugolStudio();
143
+ this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
144
+ this.interpretador = depurador
145
+ ? new interpretador_3.InterpretadorPortugolStudioComDepuracao(process.cwd(), this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha, this.funcaoLimpaTela)
146
+ : new interpretador_3.InterpretadorPortugolStudio(process.cwd(), performance, this.funcaoDeRetorno, this.funcaoLimpaTela);
147
+ break;
148
+ case "potigol":
149
+ this.lexador = new lexador_5.LexadorPotigol();
150
+ this.avaliadorSintatico = new avaliador_sintatico_5.AvaliadorSintaticoPotigol();
151
+ this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
152
+ this.interpretador = depurador
153
+ ? new interpretador_4.InterpretadorPotigolComDepuracao(process.cwd(), this.funcaoDeRetorno, this.funcaoDeRetorno)
154
+ : new interpretador_4.InterpretadorPotigol(process.cwd(), performance, this.funcaoDeRetorno);
155
+ break;
156
+ case "visualg":
157
+ this.lexador = new lexador_6.LexadorVisuAlg();
158
+ this.avaliadorSintatico = new avaliador_sintatico_6.AvaliadorSintaticoVisuAlg();
159
+ this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
160
+ this.interpretador = depurador
161
+ ? new interpretador_5.InterpretadorVisuAlgComDepuracao(process.cwd(), this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha, this.funcaoLimpaTela)
162
+ : new interpretador_5.InterpretadorVisuAlg(process.cwd(), false, this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha, this.funcaoLimpaTela);
163
+ break;
164
+ default:
165
+ this.lexador = new lexador_1.Lexador(performance);
166
+ this.avaliadorSintatico = new avaliador_sintatico_1.AvaliadorSintatico(performance);
167
+ this.importador = new importador_1.Importador(this.lexador, this.avaliadorSintatico, this.arquivosAbertos, this.conteudoArquivosAbertos, depurador);
168
+ this.interpretador = depurador
169
+ ? new interpretador_com_depuracao_importacao_1.InterpretadorComDepuracaoImportacao(this.importador, process.cwd(), this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha)
170
+ : new interpretador_6.Interpretador(this.importador, process.cwd(), performance, this.funcaoDeRetorno, this.funcaoDeRetornoMesmaLinha);
171
+ break;
172
+ }
173
+ if (depurador) {
174
+ this.iniciarDepuracao();
175
+ }
176
+ }
177
+ async executarCodigoComoArgumento(codigo) {
178
+ const retornoLexador = this.lexador.mapear([codigo], -1);
179
+ const retornoAvaliadorSintatico = this.avaliadorSintatico.analisar(retornoLexador, -1);
180
+ const { erros } = await this.executar({
181
+ conteudoArquivo: [codigo],
182
+ nomeArquivo: "",
183
+ hashArquivo: -1,
184
+ retornoLexador: retornoLexador,
185
+ retornoAvaliadorSintatico: retornoAvaliadorSintatico,
186
+ });
187
+ if (erros.length > 0)
188
+ process.exit(70); // Código com exceções não tratadas
189
+ }
190
+ /**
191
+ * Execução por arquivo.
192
+ * @param caminhoRelativoArquivo O caminho no sistema operacional do arquivo a ser aberto.
193
+ */
194
+ async carregarEExecutarArquivo(caminhoRelativoArquivo) {
195
+ const caminhoAbsolutoPrimeiroArquivo = caminho.resolve(caminhoRelativoArquivo);
196
+ const novoDiretorioBase = caminho.dirname(caminhoAbsolutoPrimeiroArquivo);
197
+ this.importador.diretorioBase = novoDiretorioBase;
198
+ this.interpretador.diretorioBase = novoDiretorioBase;
199
+ const retornoImportador = this.importador.importar(caminhoRelativoArquivo, true);
200
+ if (this.afericaoErros(retornoImportador)) {
201
+ process.exit(65); // Código para erro de avaliação antes da execução
202
+ }
203
+ let errosExecucao = {
204
+ lexador: [],
205
+ avaliadorSintatico: [],
206
+ interpretador: [],
207
+ };
208
+ // Se a interface de entrada e saída ainda não está definida, definimos agora.
209
+ // A interface pode ser definida por um teste unitário antes da execução
210
+ // aqui, por exemplo.
211
+ let interfaceLeitura;
212
+ if (!this.interpretador.interfaceEntradaSaida) {
213
+ interfaceLeitura = readline.createInterface({
214
+ input: process.stdin,
215
+ output: process.stdout,
216
+ prompt: "\n> ",
217
+ });
218
+ this.interpretador.interfaceEntradaSaida = interfaceLeitura;
219
+ }
220
+ if (this.modoDepuracao) {
221
+ let declaracoes = retornoImportador.retornoAvaliadorSintatico.declaracoes;
222
+ if (this.resolvedor) {
223
+ declaracoes = await this.resolvedor.resolver(declaracoes);
224
+ }
225
+ try {
226
+ this.interpretador.prepararParaDepuracao(declaracoes);
227
+ }
228
+ catch (erro) {
229
+ console.error(chalk_1.default.red(`[Erro de execução]`) +
230
+ ` Dialeto ${this.dialeto} não suporta depuração.`);
231
+ }
232
+ }
233
+ else {
234
+ const { erros } = await this.executar(retornoImportador);
235
+ errosExecucao = erros;
236
+ }
237
+ if (interfaceLeitura &&
238
+ (interfaceLeitura instanceof readline.Interface ||
239
+ interfaceLeitura.hasOwnProperty("close"))) {
240
+ interfaceLeitura.close();
241
+ }
242
+ if (errosExecucao.length > 0)
243
+ process.exitCode = 70; // Código com exceções não tratadas
244
+ return;
245
+ }
246
+ /**
247
+ * LAIR (Leia-Avalie-Imprima-Repita) é o modo em que Delégua executa em modo console,
248
+ * ou seja, esperando como entrada linhas de código fornecidas pelo usuário.
249
+ */
250
+ async iniciarLairDelegua() {
251
+ const lexadorJson = new lexador_json_1.LexadorJson();
252
+ const formatadorJson = new formatadores_1.FormatadorJson();
253
+ this.funcaoDeRetorno(`Usando dialeto: ${this.dialetos[this.dialeto]}`);
254
+ this.funcaoDeRetorno(`Console da Linguagem Delégua v${this.versao}`);
255
+ this.funcaoDeRetorno("Pressione Ctrl + C para sair");
256
+ const interfaceLeitura = readline.createInterface({
257
+ input: process.stdin,
258
+ output: process.stdout,
259
+ prompt: "\ndelegua> ",
260
+ });
261
+ const isto = this;
262
+ this.interpretador.interfaceEntradaSaida = interfaceLeitura;
263
+ interfaceLeitura.prompt();
264
+ interfaceLeitura.on("line", async (linha) => {
265
+ const { resultado } = await isto.executarUmaLinha(linha);
266
+ if (resultado && resultado.length) {
267
+ const resultadoLexacao = lexadorJson.getTokens(resultado[0]);
268
+ const resultadoFormatacao = formatadorJson.formatar(resultadoLexacao);
269
+ isto.funcaoDeRetorno((0, json_colorizer_1.default)(resultadoFormatacao));
270
+ }
271
+ interfaceLeitura.prompt();
272
+ });
273
+ }
274
+ /**
275
+ * A execução do código de fato.
276
+ * @param retornoImportador Dados retornados do Importador, como o retorno do Lexador, do Avaliador
277
+ * Sintático e respectivos erros.
278
+ * @param manterAmbiente Indicação se ambiente deve ser mantido ou não. Normalmente verdadeiro
279
+ * para LAIR, falso para execução por arquivo.
280
+ * @returns Um objeto com o resultado da execução.
281
+ */
282
+ async executar(retornoImportador, manterAmbiente = false) {
283
+ var _a, _b;
284
+ let declaracoes = retornoImportador.retornoAvaliadorSintatico.declaracoes;
285
+ if (this.resolvedor) {
286
+ declaracoes = await this.resolvedor.resolver(declaracoes);
287
+ }
288
+ const retornoInterpretador = await this.interpretador.interpretar(declaracoes, manterAmbiente);
289
+ if (retornoInterpretador.erros.length > 0) {
290
+ for (const erroInterpretador of retornoInterpretador.erros) {
291
+ if (erroInterpretador.hasOwnProperty("simbolo")) {
292
+ this.erroEmTempoDeExecucao(erroInterpretador);
293
+ }
294
+ else {
295
+ if (erroInterpretador.hasOwnProperty("erroInterno")) {
296
+ const erroEmJavaScript = erroInterpretador;
297
+ console.error(chalk_1.default.red(`[Linha: ${erroEmJavaScript.linha}] Erro em JavaScript: `) + `${(_a = erroEmJavaScript.erroInterno) === null || _a === void 0 ? void 0 : _a.message}`);
298
+ console.error(chalk_1.default.red(`Pilha de execução: `) +
299
+ `${(_b = erroEmJavaScript.erroInterno) === null || _b === void 0 ? void 0 : _b.stack}`);
300
+ }
301
+ else {
302
+ console.error(chalk_1.default.red(`Erro em JavaScript: `) +
303
+ JSON.stringify(erroInterpretador));
304
+ }
305
+ }
306
+ }
307
+ }
308
+ return {
309
+ erros: retornoInterpretador.erros,
310
+ resultado: retornoInterpretador.resultado,
311
+ };
312
+ }
313
+ /**
314
+ * Executa uma linha. Usado pelo modo LAIR e pelo servidor de depuração, quando recebe um comando 'avaliar'.
315
+ * @param linha A linha a ser avaliada.
316
+ * @returns O resultado da execução, com os retornos e respectivos erros, se houverem.
317
+ */
318
+ async executarUmaLinha(linha) {
319
+ const retornoLexador = this.lexador.mapear([linha], -1);
320
+ const retornoAvaliadorSintatico = this.avaliadorSintatico.analisar(retornoLexador, -1);
321
+ if (this.afericaoErros({
322
+ retornoLexador,
323
+ retornoAvaliadorSintatico,
324
+ })) {
325
+ return { resultado: [] };
326
+ }
327
+ return await this.executar({
328
+ retornoLexador,
329
+ retornoAvaliadorSintatico,
330
+ }, true);
331
+ }
332
+ /**
333
+ * Instancia um servidor de depuração, normalmente recebendo requisições na porta 7777.
334
+ */
335
+ iniciarDepuracao() {
336
+ this.servidorDepuracao = new depuracao_1.ServidorDepuracao(this);
337
+ this.servidorDepuracao.iniciarServidorDepuracao();
338
+ this.interpretador.finalizacaoDaExecucao =
339
+ this.finalizarDepuracao.bind(this);
340
+ }
341
+ /**
342
+ * Pede ao servidor de depuração que finalize a execução.
343
+ * Se não for feito, o servidor de depuração mantém um _stream_ aberto e nunca finaliza.
344
+ * Mais informações: https://stackoverflow.com/a/47456805/1314276
345
+ */
346
+ finalizarDepuracao() {
347
+ if (this.servidorDepuracao) {
348
+ this.servidorDepuracao.finalizarServidorDepuracao();
349
+ }
350
+ }
351
+ erroEmTempoDeExecucao(erro) {
352
+ var _a;
353
+ const linha = ((_a = erro === null || erro === void 0 ? void 0 : erro.simbolo) === null || _a === void 0 ? void 0 : _a.linha) || (erro === null || erro === void 0 ? void 0 : erro.linha);
354
+ const mensagem = (erro === null || erro === void 0 ? void 0 : erro.mensagem) || (erro === null || erro === void 0 ? void 0 : erro.message);
355
+ console.error(chalk_1.default.red(`Erro: [Linha: ${linha}]`) + ` ${mensagem}`);
356
+ }
357
+ }
358
+ exports.NucleoExecucao = NucleoExecucao;
359
359
  //# sourceMappingURL=nucleo-execucao.js.map