@designliquido/visualg 0.3.1 → 0.3.3

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 (84) hide show
  1. package/analisador-semantico/analisador-semantico-visualg.d.ts +37 -37
  2. package/analisador-semantico/analisador-semantico-visualg.js +235 -235
  3. package/analisador-semantico/analisador-semantico-visualg.js.map +1 -1
  4. package/analisador-semantico/index.d.ts +1 -1
  5. package/analisador-semantico/index.js +17 -17
  6. package/analisador-semantico/pilha-variaveis.d.ts +20 -20
  7. package/analisador-semantico/pilha-variaveis.js +25 -25
  8. package/avaliador-sintatico/avaliador-sintatico-visualg.d.ts +105 -105
  9. package/avaliador-sintatico/avaliador-sintatico-visualg.d.ts.map +1 -1
  10. package/avaliador-sintatico/avaliador-sintatico-visualg.js +876 -876
  11. package/avaliador-sintatico/avaliador-sintatico-visualg.js.map +1 -1
  12. package/avaliador-sintatico/index.d.ts +1 -1
  13. package/avaliador-sintatico/index.js +17 -17
  14. package/avaliador-sintatico/parametro-visualg.d.ts +7 -7
  15. package/avaliador-sintatico/parametro-visualg.js +2 -2
  16. package/bibliotecas/caracteres.d.ts +10 -10
  17. package/bibliotecas/caracteres.js +43 -44
  18. package/bibliotecas/caracteres.js.map +1 -1
  19. package/bibliotecas/index.d.ts +2 -2
  20. package/bibliotecas/index.js +18 -18
  21. package/bibliotecas/numerica.d.ts +20 -20
  22. package/bibliotecas/numerica.js +82 -83
  23. package/bibliotecas/numerica.js.map +1 -1
  24. package/construtos/index.d.ts +1 -1
  25. package/construtos/index.js +17 -17
  26. package/construtos/limpa-tela.d.ts +8 -8
  27. package/construtos/limpa-tela.js +13 -13
  28. package/formatador/escopo-formatacao.d.ts +5 -5
  29. package/formatador/escopo-formatacao.js +2 -2
  30. package/formatador/formatador.d.ts +102 -102
  31. package/formatador/formatador.js +684 -684
  32. package/formatador/formatador.js.map +1 -1
  33. package/formatador/index.d.ts +1 -1
  34. package/formatador/index.js +17 -17
  35. package/formatador/pilha-escopos-formatacao.d.ts +11 -11
  36. package/formatador/pilha-escopos-formatacao.js +32 -32
  37. package/index.d.ts +9 -9
  38. package/index.js +25 -25
  39. package/interfaces/index.d.ts +2 -2
  40. package/interfaces/index.js +18 -18
  41. package/interfaces/interpretador-visualg-interface.d.ts +8 -6
  42. package/interfaces/interpretador-visualg-interface.d.ts.map +1 -1
  43. package/interfaces/interpretador-visualg-interface.js +2 -2
  44. package/interfaces/visitante-visualg-interface.d.ts +5 -5
  45. package/interfaces/visitante-visualg-interface.js +2 -2
  46. package/interpretador/comum.d.ts +54 -48
  47. package/interpretador/comum.d.ts.map +1 -1
  48. package/interpretador/comum.js +682 -604
  49. package/interpretador/comum.js.map +1 -1
  50. package/interpretador/index.d.ts +3 -3
  51. package/interpretador/index.js +19 -19
  52. package/interpretador/inferenciador.d.ts +2 -2
  53. package/interpretador/inferenciador.js +34 -35
  54. package/interpretador/inferenciador.js.map +1 -1
  55. package/interpretador/interpretador-visualg-com-depuracao.d.ts +69 -68
  56. package/interpretador/interpretador-visualg-com-depuracao.d.ts.map +1 -1
  57. package/interpretador/interpretador-visualg-com-depuracao.js +254 -251
  58. package/interpretador/interpretador-visualg-com-depuracao.js.map +1 -1
  59. package/interpretador/interpretador-visualg.d.ts +71 -70
  60. package/interpretador/interpretador-visualg.d.ts.map +1 -1
  61. package/interpretador/interpretador-visualg.js +226 -224
  62. package/interpretador/interpretador-visualg.js.map +1 -1
  63. package/interpretador/pilha-escopos-execucao-visualg.d.ts +39 -39
  64. package/interpretador/pilha-escopos-execucao-visualg.d.ts.map +1 -1
  65. package/interpretador/pilha-escopos-execucao-visualg.js +207 -207
  66. package/interpretador/pilha-escopos-execucao-visualg.js.map +1 -1
  67. package/lexador/index.d.ts +1 -1
  68. package/lexador/index.js +17 -17
  69. package/lexador/lexador-visualg.d.ts +20 -20
  70. package/lexador/lexador-visualg.js +231 -231
  71. package/lexador/lexador-visualg.js.map +1 -1
  72. package/lexador/palavras-reservadas.d.ts +77 -77
  73. package/lexador/palavras-reservadas.js +84 -84
  74. package/lexador/palavras-reservadas.js.map +1 -1
  75. package/package.json +4 -4
  76. package/tipos-de-dados.d.ts +10 -10
  77. package/tipos-de-dados.js +11 -11
  78. package/tipos-de-simbolos/lexico-regular.d.ts +85 -85
  79. package/tipos-de-simbolos/lexico-regular.js +86 -86
  80. package/tradutores/index.d.ts +1 -1
  81. package/tradutores/index.js +17 -17
  82. package/tradutores/tradutor-reverso-visualg.d.ts +53 -53
  83. package/tradutores/tradutor-reverso-visualg.js +263 -263
  84. package/tradutores/tradutor-reverso-visualg.js.map +1 -1
@@ -1,605 +1,683 @@
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.visitarExpressaoLeia = exports.visitarExpressaoFormatacaoEscrita = exports.visitarDeclaracaoAleatorio = exports.visitarExpressaoAtribuicaoPorIndicesMatriz = exports.visitarExpressaoAcessoElementoMatriz = exports.resolverIncrementoPara = exports.visitarExpressaoLogica = exports.visitarExpressaoBinaria = exports.visitarExpressaoAtribuicaoPorIndice = exports.visitarExpressaoAcessoIndiceVariavel = exports.atribuirVariavel = exports.visitarDeclaracaoInicioAlgoritmo = exports.visitarDeclaracaoClasse = exports.visitarDeclaracaoCabecalhoPrograma = exports.carregarBibliotecaGlobalNumerica = exports.carregarBibliotecaGlobalCaracter = void 0;
30
- const construtos_1 = require("@designliquido/delegua/construtos");
31
- const declaracoes_1 = require("@designliquido/delegua/declaracoes");
32
- const lexador_1 = require("@designliquido/delegua/lexador");
33
- const excecoes_1 = require("@designliquido/delegua/excecoes");
34
- const estruturas_1 = require("@designliquido/delegua/estruturas");
35
- const inferenciador_1 = require("./inferenciador");
36
- const lexico_regular_1 = __importDefault(require("../tipos-de-simbolos/lexico-regular"));
37
- const bibliotecaCaracteres = __importStar(require("../bibliotecas/caracteres"));
38
- const bibliotecaNumerica = __importStar(require("../bibliotecas/numerica"));
39
- function carregarBibliotecaGlobalCaracter(pilhaEscoposExecucao) {
40
- pilhaEscoposExecucao.definirVariavel('asc', new estruturas_1.FuncaoPadrao(1, bibliotecaCaracteres.asc));
41
- pilhaEscoposExecucao.definirVariavel('carac', new estruturas_1.FuncaoPadrao(1, bibliotecaCaracteres.carac));
42
- pilhaEscoposExecucao.definirVariavel('caracpnum', new estruturas_1.FuncaoPadrao(1, bibliotecaCaracteres.caracpnum));
43
- pilhaEscoposExecucao.definirVariavel('compr', new estruturas_1.FuncaoPadrao(1, bibliotecaCaracteres.compr));
44
- pilhaEscoposExecucao.definirVariavel('copia', new estruturas_1.FuncaoPadrao(3, bibliotecaCaracteres.copia));
45
- pilhaEscoposExecucao.definirVariavel('maiusc', new estruturas_1.FuncaoPadrao(1, bibliotecaCaracteres.maiusc));
46
- pilhaEscoposExecucao.definirVariavel('minusc', new estruturas_1.FuncaoPadrao(1, bibliotecaCaracteres.minusc));
47
- pilhaEscoposExecucao.definirVariavel('numpcarac', new estruturas_1.FuncaoPadrao(1, bibliotecaCaracteres.numpcarac));
48
- pilhaEscoposExecucao.definirVariavel('pos', new estruturas_1.FuncaoPadrao(2, bibliotecaCaracteres.pos));
49
- }
50
- exports.carregarBibliotecaGlobalCaracter = carregarBibliotecaGlobalCaracter;
51
- function carregarBibliotecaGlobalNumerica(pilhaEscoposExecucao) {
52
- pilhaEscoposExecucao.definirVariavel('abs', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.abs));
53
- pilhaEscoposExecucao.definirVariavel('arccos', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.arccos));
54
- pilhaEscoposExecucao.definirVariavel('arcsen', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.arcsen));
55
- pilhaEscoposExecucao.definirVariavel('arctan', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.arctan));
56
- pilhaEscoposExecucao.definirVariavel('cos', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.cos));
57
- pilhaEscoposExecucao.definirVariavel('cotan', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.cotan));
58
- pilhaEscoposExecucao.definirVariavel('exp', new estruturas_1.FuncaoPadrao(2, bibliotecaNumerica.exp));
59
- pilhaEscoposExecucao.definirVariavel('grauprad', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.grauprad));
60
- pilhaEscoposExecucao.definirVariavel('int', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.int));
61
- pilhaEscoposExecucao.definirVariavel('log', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.log));
62
- pilhaEscoposExecucao.definirVariavel('logn', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.logn));
63
- pilhaEscoposExecucao.definirVariavel('pi', new estruturas_1.FuncaoPadrao(0, bibliotecaNumerica.pi));
64
- pilhaEscoposExecucao.definirVariavel('quad', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.quad));
65
- pilhaEscoposExecucao.definirVariavel('radpgrau', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.radpgrau));
66
- pilhaEscoposExecucao.definirVariavel('raizq', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.raizq));
67
- pilhaEscoposExecucao.definirVariavel('rand', new estruturas_1.FuncaoPadrao(0, bibliotecaNumerica.rand));
68
- pilhaEscoposExecucao.definirVariavel('randi', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.randi));
69
- pilhaEscoposExecucao.definirVariavel('sen', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.sen));
70
- pilhaEscoposExecucao.definirVariavel('tan', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.tan));
71
- }
72
- exports.carregarBibliotecaGlobalNumerica = carregarBibliotecaGlobalNumerica;
73
- async function visitarDeclaracaoCabecalhoPrograma(interpretador, declaracao) {
74
- return Promise.resolve();
75
- }
76
- exports.visitarDeclaracaoCabecalhoPrograma = visitarDeclaracaoCabecalhoPrograma;
77
- /**
78
- * Uma declaração de "classe" no VisuAlg nada mais é que a definição de um registro.
79
- * Não há propriedades e não há herança. Por isso usamos uma versão simplificada
80
- * da implementação original de Delégua.
81
- * @param declaracao A declaração de registro.
82
- * @returns Sempre retorna nulo, por ser requerido pelo contrato de visita.
83
- */
84
- async function visitarDeclaracaoClasse(interpretador, declaracao) {
85
- const metodos = {};
86
- if (declaracao.metodos.length > 0) {
87
- const declaracaoConstrutor = declaracao.metodos[0];
88
- const funcao = new estruturas_1.DeleguaFuncao('construtor', declaracaoConstrutor.funcao, undefined, true);
89
- metodos['construtor'] = funcao;
90
- }
91
- const deleguaClasse = new estruturas_1.DeleguaClasse(declaracao.simbolo, undefined, metodos, declaracao.propriedades);
92
- interpretador.pilhaEscoposExecucao.definirConstante(declaracao.simbolo.lexema, deleguaClasse);
93
- interpretador.tiposConhecidos.push(declaracao.simbolo.lexema);
94
- return null;
95
- }
96
- exports.visitarDeclaracaoClasse = visitarDeclaracaoClasse;
97
- async function visitarDeclaracaoInicioAlgoritmo(interpretador, declaracao) {
98
- return Promise.resolve();
99
- }
100
- exports.visitarDeclaracaoInicioAlgoritmo = visitarDeclaracaoInicioAlgoritmo;
101
- function converterValor(valor, tipo) {
102
- switch (tipo) {
103
- case 'inteiro':
104
- return parseInt(valor);
105
- case 'lógico':
106
- return Boolean(valor);
107
- case 'número':
108
- case 'real':
109
- return Number(valor);
110
- case 'texto':
111
- return String(valor);
112
- default:
113
- return valor;
114
- }
115
- }
116
- async function atribuirVariavel(interpretador, expressao, valor) {
117
- if (expressao instanceof construtos_1.Variavel) {
118
- interpretador.pilhaEscoposExecucao.atribuirVariavel(expressao.simbolo, valor);
119
- return;
120
- }
121
- if (expressao instanceof construtos_1.AcessoIndiceVariavel) {
122
- const promises = await Promise.all([
123
- interpretador.avaliar(expressao.entidadeChamada),
124
- interpretador.avaliar(expressao.indice),
125
- ]);
126
- let alvo = promises[0];
127
- let indice = promises[1];
128
- let valorAlvo;
129
- let valorIndice;
130
- if (alvo.hasOwnProperty('valor')) {
131
- valorAlvo = alvo.valor;
132
- }
133
- else {
134
- valorAlvo = alvo;
135
- }
136
- if (indice.hasOwnProperty('valor')) {
137
- valorIndice = indice.valor;
138
- }
139
- else {
140
- valorIndice = indice;
141
- }
142
- const subtipo = String(alvo.tipo).replace('[]', '');
143
- const valorResolvido = converterValor(valor, subtipo);
144
- if (valorAlvo instanceof construtos_1.Vetor) {
145
- valorAlvo.valores[valorIndice] = valorResolvido;
146
- }
147
- else {
148
- valorAlvo[valorIndice] = valorResolvido;
149
- }
150
- return;
151
- }
152
- if (expressao instanceof construtos_1.AcessoMetodoOuPropriedade) {
153
- // Há apenas duas possibilidades aqui:
154
- // 1. A entidade é uma variável
155
- // 2. A entidade é um elemento de um vetor.
156
- let referenciaVariavel;
157
- let tipoBaseVariavel;
158
- if (expressao.objeto instanceof construtos_1.AcessoIndiceVariavel) {
159
- referenciaVariavel = await interpretador.avaliar(expressao.objeto.entidadeChamada);
160
- tipoBaseVariavel = referenciaVariavel.tipo.replace('[]', '');
161
- }
162
- else {
163
- referenciaVariavel = await interpretador.avaliar(expressao.objeto);
164
- tipoBaseVariavel = referenciaVariavel.tipo;
165
- }
166
- // A única forma de o avaliador sintático gerar uma expressão do tipo
167
- // `AcessoMetodoOuPropriedade` é se o `objeto` é um registro.
168
- // Portanto, temos que pesquisar aqui o tipo da propriedade.
169
- const tipoRelacionado = interpretador.pilhaEscoposExecucao.obterVariavelPorNome(tipoBaseVariavel);
170
- const valorTipoRelacionado = tipoRelacionado.hasOwnProperty('valor') ? tipoRelacionado.valor : tipoRelacionado;
171
- const propriedadeRelacionada = valorTipoRelacionado.propriedades.find(p => p.nome.lexema === expressao.simbolo.lexema);
172
- if (!propriedadeRelacionada) {
173
- throw new excecoes_1.ErroEmTempoDeExecucao(expressao.simbolo, `Propriedade "${expressao.simbolo.lexema}" não existe no tipo ${valorTipoRelacionado.simboloOriginal.lexema}.`);
174
- }
175
- let variavelObjeto = await interpretador.avaliar(expressao.objeto);
176
- const valorVariavelObjeto = variavelObjeto.hasOwnProperty('valor') ? variavelObjeto.valor : variavelObjeto;
177
- let valorConvertido = converterValor(valor, propriedadeRelacionada.tipo);
178
- valorVariavelObjeto.definir(expressao.simbolo, valorConvertido);
179
- }
180
- }
181
- exports.atribuirVariavel = atribuirVariavel;
182
- async function avaliar(interpretador, expressao) {
183
- return await expressao.aceitar(interpretador);
184
- }
185
- function eIgual(esquerda, direita) {
186
- if (esquerda === null && direita === null)
187
- return true;
188
- if (esquerda === null)
189
- return false;
190
- return esquerda === direita;
191
- }
192
- function eVerdadeiro(objeto) {
193
- if (objeto === null)
194
- return false;
195
- if (typeof objeto === 'boolean')
196
- return Boolean(objeto);
197
- if (objeto.hasOwnProperty('valor')) {
198
- return Boolean(objeto.valor);
199
- }
200
- return true;
201
- }
202
- function verificarOperandosNumeros(operador, direita, esquerda) {
203
- const tipoDireita = direita.tipo ? direita.tipo : typeof direita === 'number' ? 'número' : String(NaN);
204
- const tipoEsquerda = esquerda.tipo ? esquerda.tipo : typeof esquerda === 'number' ? 'número' : String(NaN);
205
- const tiposNumericos = ['inteiro', 'numero', 'número', 'real'];
206
- if (tiposNumericos.includes(tipoDireita.toLowerCase()) && tiposNumericos.includes(tipoEsquerda.toLowerCase()))
207
- return;
208
- throw new excecoes_1.ErroEmTempoDeExecucao(operador, 'Operadores precisam ser números.', operador.linha);
209
- }
210
- async function visitarExpressaoAcessoIndiceVariavel(interpretador, expressao) {
211
- const promises = await Promise.all([
212
- interpretador.avaliar(expressao.entidadeChamada),
213
- interpretador.avaliar(expressao.indice)
214
- ]);
215
- const variavelObjeto = promises[0];
216
- const indice = promises[1];
217
- const objeto = variavelObjeto.hasOwnProperty('valor') ? variavelObjeto.valor : variavelObjeto;
218
- let valorIndice = indice.hasOwnProperty('valor') ? indice.valor : indice;
219
- if (Array.isArray(objeto)) {
220
- if (!Number.isInteger(valorIndice)) {
221
- return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Somente inteiros podem ser usados para indexar um vetor.', expressao.linha));
222
- }
223
- if (valorIndice < 0 && objeto.length !== 0) {
224
- while (valorIndice < 0) {
225
- valorIndice += objeto.length;
226
- }
227
- }
228
- if (valorIndice >= objeto.length) {
229
- return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Índice do vetor fora do intervalo.', expressao.linha));
230
- }
231
- return objeto[valorIndice];
232
- }
233
- if (objeto instanceof construtos_1.Vetor) {
234
- return objeto.valores[valorIndice];
235
- }
236
- if (objeto.constructor === Object ||
237
- objeto instanceof estruturas_1.ObjetoDeleguaClasse ||
238
- objeto instanceof estruturas_1.DeleguaFuncao ||
239
- objeto instanceof estruturas_1.DeleguaClasse) {
240
- return objeto[valorIndice] || null;
241
- }
242
- if (typeof objeto === 'string') {
243
- if (!Number.isInteger(valorIndice)) {
244
- return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Somente inteiros podem ser usados para indexar um vetor.', expressao.linha));
245
- }
246
- if (valorIndice < 0 && objeto.length !== 0) {
247
- while (valorIndice < 0) {
248
- valorIndice += objeto.length;
249
- }
250
- }
251
- if (valorIndice >= objeto.length) {
252
- return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Índice fora do tamanho.', expressao.linha));
253
- }
254
- return objeto.charAt(valorIndice);
255
- }
256
- return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.entidadeChamada.nome, 'Somente listas, dicionários, classes e objetos podem ter seus valores indexados.', expressao.linha));
257
- }
258
- exports.visitarExpressaoAcessoIndiceVariavel = visitarExpressaoAcessoIndiceVariavel;
259
- async function visitarExpressaoAtribuicaoPorIndice(interpretador, expressao) {
260
- const promises = await Promise.all([
261
- interpretador.avaliar(expressao.objeto),
262
- interpretador.avaliar(expressao.indice),
263
- interpretador.avaliar(expressao.valor),
264
- ]);
265
- let objeto = promises[0];
266
- let indice = promises[1];
267
- const valor = promises[2];
268
- objeto = objeto.hasOwnProperty('valor') ? objeto.valor : objeto;
269
- indice = indice.hasOwnProperty('valor') ? indice.valor : indice;
270
- if (Array.isArray(objeto)) {
271
- if (indice < 0 && objeto.length !== 0) {
272
- while (indice < 0) {
273
- indice += objeto.length;
274
- }
275
- }
276
- while (objeto.length < indice) {
277
- objeto.push(null);
278
- }
279
- objeto[indice] = valor;
280
- }
281
- else if (objeto instanceof construtos_1.Vetor) {
282
- objeto.valores[indice] = valor;
283
- }
284
- else if (objeto.constructor === Object ||
285
- objeto instanceof estruturas_1.ObjetoDeleguaClasse ||
286
- objeto instanceof estruturas_1.DeleguaFuncao ||
287
- objeto instanceof estruturas_1.DeleguaClasse) {
288
- objeto[indice] = valor;
289
- }
290
- else {
291
- return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.objeto.nome, 'Somente listas, dicionários, classes e objetos podem ser mudados por sobrescrita.', expressao.linha));
292
- }
293
- }
294
- exports.visitarExpressaoAtribuicaoPorIndice = visitarExpressaoAtribuicaoPorIndice;
295
- /**
296
- * Método de visita de expressão binária.
297
- * Reintroduzido pelas particularidades do VisuAlg.
298
- * @param expressao A expressão binária.
299
- * @returns O resultado da resolução da expressão.
300
- */
301
- async function visitarExpressaoBinaria(interpretador, expressao) {
302
- try {
303
- const promises = await Promise.all([
304
- avaliar(interpretador, expressao.esquerda),
305
- avaliar(interpretador, expressao.direita),
306
- ]);
307
- const esquerda = promises[0];
308
- const direita = promises[1];
309
- let valorEsquerdo = (esquerda === null || esquerda === void 0 ? void 0 : esquerda.hasOwnProperty('valor')) ? esquerda.valor : esquerda;
310
- let valorDireito = (direita === null || direita === void 0 ? void 0 : direita.hasOwnProperty('valor')) ? direita.valor : direita;
311
- // No VisuAlg, uma variável pode resolver para função porque funções não precisam ter parênteses.
312
- // Esta parte evita o problema.
313
- if (valorEsquerdo && valorEsquerdo.hasOwnProperty('funcao')) {
314
- valorEsquerdo = valorEsquerdo.funcao();
315
- }
316
- if (valorDireito && valorDireito.hasOwnProperty('funcao')) {
317
- valorDireito = valorDireito.funcao();
318
- }
319
- const tipoEsquerdo = (esquerda === null || esquerda === void 0 ? void 0 : esquerda.hasOwnProperty('tipo')) ? esquerda.tipo : (0, inferenciador_1.inferirTipoVariavel)(esquerda);
320
- const tipoDireito = (direita === null || direita === void 0 ? void 0 : direita.hasOwnProperty('tipo')) ? direita.tipo : (0, inferenciador_1.inferirTipoVariavel)(direita);
321
- switch (expressao.operador.tipo) {
322
- case lexico_regular_1.default.EXPONENCIACAO:
323
- verificarOperandosNumeros(expressao.operador, esquerda, direita);
324
- return Math.pow(valorEsquerdo, valorDireito);
325
- case lexico_regular_1.default.MAIOR:
326
- verificarOperandosNumeros(expressao.operador, esquerda, direita);
327
- return Number(valorEsquerdo) > Number(valorDireito);
328
- case lexico_regular_1.default.MAIOR_IGUAL:
329
- verificarOperandosNumeros(expressao.operador, esquerda, direita);
330
- return Number(valorEsquerdo) >= Number(valorDireito);
331
- case lexico_regular_1.default.MENOR:
332
- verificarOperandosNumeros(expressao.operador, esquerda, direita);
333
- return Number(valorEsquerdo) < Number(valorDireito);
334
- case lexico_regular_1.default.MENOR_IGUAL:
335
- verificarOperandosNumeros(expressao.operador, esquerda, direita);
336
- return Number(valorEsquerdo) <= Number(valorDireito);
337
- case lexico_regular_1.default.SUBTRACAO:
338
- verificarOperandosNumeros(expressao.operador, esquerda, direita);
339
- return Number(valorEsquerdo) - Number(valorDireito);
340
- case lexico_regular_1.default.ADICAO:
341
- let tiposNumericos = ['inteiro', 'numero', 'número', 'real'];
342
- if (tiposNumericos.includes(tipoEsquerdo.toLowerCase()) &&
343
- tiposNumericos.includes(tipoDireito.toLowerCase())) {
344
- return Number(valorEsquerdo) + Number(valorDireito);
345
- }
346
- else {
347
- return String(valorEsquerdo) + String(valorDireito);
348
- }
349
- case lexico_regular_1.default.DIVISAO:
350
- verificarOperandosNumeros(expressao.operador, esquerda, direita);
351
- return Number(valorEsquerdo) / Number(valorDireito);
352
- case lexico_regular_1.default.DIVISAO_INTEIRA:
353
- verificarOperandosNumeros(expressao.operador, esquerda, direita);
354
- return Math.floor(Number(valorEsquerdo) / Number(valorDireito));
355
- case lexico_regular_1.default.MULTIPLICACAO:
356
- if (tipoEsquerdo === 'texto' || tipoDireito === 'texto') {
357
- // Sem ambos os valores resolvem como texto, multiplica normal.
358
- // Se apenas um resolve como texto, o outro repete o
359
- // texto n vezes, sendo n o valor do outro.
360
- if (tipoEsquerdo === 'texto' && tipoDireito === 'texto') {
361
- return Number(valorEsquerdo) * Number(valorDireito);
362
- }
363
- if (tipoEsquerdo === 'texto') {
364
- return valorEsquerdo.repeat(Number(valorDireito));
365
- }
366
- return valorDireito.repeat(Number(valorEsquerdo));
367
- }
368
- return Number(valorEsquerdo) * Number(valorDireito);
369
- case lexico_regular_1.default.MODULO:
370
- verificarOperandosNumeros(expressao.operador, esquerda, direita);
371
- return Number(valorEsquerdo) % Number(valorDireito);
372
- case lexico_regular_1.default.DIFERENTE:
373
- return !eIgual(valorEsquerdo, valorDireito);
374
- case lexico_regular_1.default.IGUAL:
375
- return eIgual(valorEsquerdo, valorDireito);
376
- }
377
- }
378
- catch (erro) {
379
- return Promise.reject(erro);
380
- }
381
- }
382
- exports.visitarExpressaoBinaria = visitarExpressaoBinaria;
383
- async function visitarExpressaoLogica(interpretador, expressao) {
384
- const esquerda = await avaliar(interpretador, expressao.esquerda);
385
- // se um estado for verdadeiro, retorna verdadeiro
386
- if (expressao.operador.tipo === lexico_regular_1.default.OU) {
387
- if (eVerdadeiro(esquerda))
388
- return esquerda;
389
- }
390
- // se a primeira variável é verdadeiro, retorna a segunda invertida
391
- if (expressao.operador.tipo === lexico_regular_1.default.XOU) {
392
- const valorDireito = await avaliar(interpretador, expressao.direita);
393
- return eVerdadeiro(esquerda) !== eVerdadeiro(valorDireito);
394
- }
395
- // se um estado for falso, retorna falso
396
- if (expressao.operador.tipo === lexico_regular_1.default.E) {
397
- if (!eVerdadeiro(esquerda))
398
- return esquerda;
399
- }
400
- return await avaliar(interpretador, expressao.direita);
401
- }
402
- exports.visitarExpressaoLogica = visitarExpressaoLogica;
403
- /* Isso existe porque o laço `para` do VisuAlg pode ter o passo positivo ou negativo
404
- * dependendo dos operandos de início e fim, que só são possíveis de determinar
405
- * em tempo de execução.
406
- * Quando um dos operandos é uma variável, tanto a condição do laço quanto o
407
- * passo são considerados indefinidos aqui.
408
- */
409
- async function resolverIncrementoPara(interpretador, declaracao) {
410
- if (declaracao.resolverIncrementoEmExecucao) {
411
- const promises = await Promise.all([
412
- avaliar(interpretador, declaracao.condicao.esquerda),
413
- avaliar(interpretador, declaracao.condicao.direita),
414
- ]);
415
- const operandoEsquerdo = promises[0];
416
- const operandoDireito = promises[1];
417
- const valorAtualEsquerdo = operandoEsquerdo.hasOwnProperty('valor') ? operandoEsquerdo.valor : operandoEsquerdo;
418
- const valorAtualDireito = operandoDireito.hasOwnProperty('valor') ? operandoDireito.valor : operandoDireito;
419
- if (valorAtualEsquerdo < valorAtualDireito) {
420
- declaracao.condicao.operador = new lexador_1.Simbolo(lexico_regular_1.default.MENOR_IGUAL, '', '', Number(declaracao.linha), declaracao.hashArquivo);
421
- declaracao.incrementar.condicaoPara.operador = new lexador_1.Simbolo(lexico_regular_1.default.MENOR, '', '', Number(declaracao.linha), declaracao.hashArquivo);
422
- declaracao.incrementar.incremento.expressao.valor.direita = new construtos_1.Literal(declaracao.hashArquivo, Number(declaracao.linha), 1);
423
- }
424
- else {
425
- declaracao.condicao.operador = new lexador_1.Simbolo(lexico_regular_1.default.MAIOR_IGUAL, '', '', Number(declaracao.linha), declaracao.hashArquivo);
426
- declaracao.incrementar.condicaoPara.operador = new lexador_1.Simbolo(lexico_regular_1.default.MAIOR, '', '', Number(declaracao.linha), declaracao.hashArquivo);
427
- declaracao.incrementar.incremento.expressao.valor.direita = new construtos_1.Unario(declaracao.hashArquivo, new lexador_1.Simbolo(lexico_regular_1.default.SUBTRACAO, '-', undefined, declaracao.linha, declaracao.hashArquivo), new construtos_1.Literal(declaracao.hashArquivo, Number(declaracao.linha), 1), 'ANTES');
428
- }
429
- }
430
- }
431
- exports.resolverIncrementoPara = resolverIncrementoPara;
432
- async function visitarExpressaoAcessoElementoMatriz(interpretador, expressao) {
433
- const promises = await Promise.all([
434
- avaliar(interpretador, expressao.entidadeChamada),
435
- avaliar(interpretador, expressao.indicePrimario),
436
- avaliar(interpretador, expressao.indiceSecundario),
437
- ]);
438
- const variavelObjeto = promises[0];
439
- const indicePrimario = promises[1];
440
- const indiceSecundario = promises[2];
441
- const objeto = variavelObjeto.hasOwnProperty('valor') ? variavelObjeto.valor : variavelObjeto;
442
- let valorIndicePrimario = indicePrimario.hasOwnProperty('valor') ? indicePrimario.valor : indicePrimario;
443
- let valorIndiceSecundario = indiceSecundario.hasOwnProperty('valor') ? indiceSecundario.valor : indiceSecundario;
444
- if (!Number.isInteger(valorIndicePrimario) || !Number.isInteger(valorIndiceSecundario)) {
445
- return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Somente inteiros podem ser usados para indexar um vetor.', expressao.linha));
446
- }
447
- if (Array.isArray(objeto)) {
448
- if (valorIndicePrimario < 0 && objeto.length !== 0) {
449
- while (valorIndicePrimario < 0) {
450
- valorIndicePrimario += objeto.length;
451
- }
452
- }
453
- if (valorIndiceSecundario < 0 && objeto.length !== 0) {
454
- while (valorIndiceSecundario < 0) {
455
- valorIndiceSecundario += objeto.length;
456
- }
457
- }
458
- if (valorIndicePrimario >= objeto.length || valorIndiceSecundario >= objeto.length) {
459
- return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Índice do vetor fora do intervalo.', expressao.linha));
460
- }
461
- return objeto[valorIndicePrimario][valorIndiceSecundario];
462
- }
463
- if (objeto instanceof construtos_1.Vetor) {
464
- return objeto.valores[valorIndicePrimario][valorIndiceSecundario];
465
- }
466
- return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.entidadeChamada.valor, 'Somente listas, dicionários, classes e objetos podem ser mudados por sobrescrita.', expressao.linha));
467
- }
468
- exports.visitarExpressaoAcessoElementoMatriz = visitarExpressaoAcessoElementoMatriz;
469
- async function visitarExpressaoAtribuicaoPorIndicesMatriz(interpretador, expressao) {
470
- const promises = await Promise.all([
471
- avaliar(interpretador, expressao.objeto),
472
- avaliar(interpretador, expressao.indicePrimario),
473
- avaliar(interpretador, expressao.indiceSecundario),
474
- avaliar(interpretador, expressao.valor),
475
- ]);
476
- let objeto = promises[0];
477
- let indicePrimario = promises[1];
478
- let indiceSecundario = promises[2];
479
- const valor = promises[3];
480
- objeto = objeto.hasOwnProperty('valor') ? objeto.valor : objeto;
481
- indicePrimario = indicePrimario.hasOwnProperty('valor') ? indicePrimario.valor : indicePrimario;
482
- indiceSecundario = indiceSecundario.hasOwnProperty('valor') ? indiceSecundario.valor : indiceSecundario;
483
- if (Array.isArray(objeto)) {
484
- if (indicePrimario < 0 && objeto.length !== 0) {
485
- while (indicePrimario < 0) {
486
- indicePrimario += objeto.length;
487
- }
488
- }
489
- if (indiceSecundario < 0 && objeto.length !== 0) {
490
- while (indiceSecundario < 0) {
491
- indiceSecundario += objeto.length;
492
- }
493
- }
494
- while (objeto.length < indicePrimario || objeto.length < indiceSecundario) {
495
- objeto.push(null);
496
- }
497
- objeto[indicePrimario][indiceSecundario] = valor;
498
- return Promise.resolve();
499
- }
500
- if (objeto instanceof construtos_1.Vetor) {
501
- objeto.valores[indicePrimario][indiceSecundario] = valor;
502
- return Promise.resolve();
503
- }
504
- return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.objeto.nome, 'Somente listas, dicionários, classes e objetos podem ser mudados por sobrescrita.', expressao.linha));
505
- }
506
- exports.visitarExpressaoAtribuicaoPorIndicesMatriz = visitarExpressaoAtribuicaoPorIndicesMatriz;
507
- async function encontrarLeiaNoAleatorio(interpretador, declaracao, menorNumero, maiorNumero) {
508
- if ('declaracoes' in declaracao) {
509
- // Se a declaração tiver um campo 'declaracoes', ela é um Bloco
510
- const declaracoes = declaracao.declaracoes;
511
- for (const subDeclaracao of declaracoes) {
512
- encontrarLeiaNoAleatorio(interpretador, subDeclaracao, menorNumero, maiorNumero);
513
- }
514
- }
515
- else if (declaracao instanceof declaracoes_1.Leia) {
516
- // Se encontrarmos um Leia, podemos efetuar as operações imediatamente
517
- for (const argumento of declaracao.argumentos) {
518
- const arg1 = await interpretador.avaliar(argumento);
519
- const tipoDe = arg1.tipo || (0, inferenciador_1.inferirTipoVariavel)(arg1);
520
- const valor = tipoDe === 'texto' ? palavraAleatoriaCom5Digitos() : gerarNumeroAleatorio(menorNumero, maiorNumero);
521
- atribuirVariavel(interpretador, argumento, valor);
522
- }
523
- }
524
- }
525
- function gerarNumeroAleatorio(min, max) {
526
- return Math.floor(Math.random() * (max - min) + min);
527
- }
528
- function palavraAleatoriaCom5Digitos() {
529
- const caracteres = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
530
- let palavra = '';
531
- for (let i = 0; i < 5; i++) {
532
- const indiceAleatorio = Math.floor(Math.random() * caracteres.length);
533
- palavra += caracteres.charAt(indiceAleatorio);
534
- }
535
- return palavra;
536
- }
537
- async function visitarDeclaracaoAleatorio(interpretador, expressao) {
538
- let retornoExecucao;
539
- try {
540
- let menorNumero = 0;
541
- let maiorNumero = 100;
542
- if (expressao.argumentos) {
543
- menorNumero = Math.min(expressao.argumentos.min, expressao.argumentos.max);
544
- maiorNumero = Math.max(expressao.argumentos.min, expressao.argumentos.max);
545
- }
546
- for (let corpoDeclaracao of expressao.corpo.declaracoes) {
547
- encontrarLeiaNoAleatorio(interpretador, corpoDeclaracao, menorNumero, maiorNumero);
548
- retornoExecucao = await interpretador.executar(corpoDeclaracao, false);
549
- }
550
- }
551
- catch (error) {
552
- interpretador.erros.push({
553
- erroInterno: error,
554
- linha: expressao.linha,
555
- hashArquivo: expressao.hashArquivo,
556
- });
557
- return Promise.reject(error);
558
- }
559
- return retornoExecucao;
560
- }
561
- exports.visitarDeclaracaoAleatorio = visitarDeclaracaoAleatorio;
562
- /**
563
- * Formata uma saída de acordo com o número e espaços e casas decimais solicitados.
564
- * @param declaracao A declaração de formatação de escrita.
565
- * @returns {string} A saída formatada como texto e os respectivos parâmetros aplicados.
566
- */
567
- async function visitarExpressaoFormatacaoEscrita(interpretador, declaracao) {
568
- let resultado = '';
569
- const conteudo = await interpretador.avaliar(declaracao.expressao);
570
- const valorConteudo = (conteudo === null || conteudo === void 0 ? void 0 : conteudo.hasOwnProperty('valor')) ? conteudo.valor : conteudo;
571
- const tipoConteudo = conteudo.hasOwnProperty('tipo') ? conteudo.tipo : typeof conteudo;
572
- resultado = valorConteudo;
573
- if (['real', 'inteiro'].includes(tipoConteudo) && declaracao.casasDecimais > 0) {
574
- resultado = valorConteudo.toLocaleString('pt', { minimumFractionDigits: declaracao.casasDecimais });
575
- }
576
- if (declaracao.espacos > 0) {
577
- resultado = ' '.repeat(declaracao.espacos) + resultado;
578
- }
579
- return resultado;
580
- }
581
- exports.visitarExpressaoFormatacaoEscrita = visitarExpressaoFormatacaoEscrita;
582
- /**
583
- * Customização da leitura de dados de entrada.
584
- * A interrupção da execução para leitura de dados do usuário
585
- * ocorre quando o modo aleatório não está habilitado.
586
- * @param interpretador A instância do interpretador.
587
- * @param expressao A expressão `Leia`
588
- * @param mensagemPrompt A mensagem de prompt. Normalmente é o último conteúdo da função `escreva()`
589
- * ou ainda `escreval()`, e é usada em prompts Web, como por exemplo `window.prompt`.
590
- */
591
- async function visitarExpressaoLeia(interpretador, expressao, mensagemPrompt) {
592
- // Verifica se a leitura deve ser interrompida antes de prosseguir
593
- if (!expressao.eParaInterromper) {
594
- for (let argumento of expressao.argumentos) {
595
- const promessaLeitura = () => new Promise((resolucao) => interpretador.interfaceEntradaSaida.question(interpretador.deveEscreverPrompt ? mensagemPrompt : '', (resposta) => {
596
- mensagemPrompt = '> ';
597
- resolucao(resposta);
598
- }));
599
- const valorLido = await promessaLeitura();
600
- await atribuirVariavel(interpretador, argumento, valorLido);
601
- }
602
- }
603
- }
604
- exports.visitarExpressaoLeia = visitarExpressaoLeia;
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.carregarBibliotecaGlobalCaracter = carregarBibliotecaGlobalCaracter;
30
+ exports.carregarBibliotecaGlobalNumerica = carregarBibliotecaGlobalNumerica;
31
+ exports.visitarDeclaracaoCabecalhoPrograma = visitarDeclaracaoCabecalhoPrograma;
32
+ exports.visitarDeclaracaoClasse = visitarDeclaracaoClasse;
33
+ exports.visitarDeclaracaoInicioAlgoritmo = visitarDeclaracaoInicioAlgoritmo;
34
+ exports.atribuirVariavel = atribuirVariavel;
35
+ exports.visitarDeclaracaoVar = visitarDeclaracaoVar;
36
+ exports.visitarExpressaoAcessoIndiceVariavel = visitarExpressaoAcessoIndiceVariavel;
37
+ exports.visitarExpressaoAtribuicaoPorIndice = visitarExpressaoAtribuicaoPorIndice;
38
+ exports.visitarExpressaoBinaria = visitarExpressaoBinaria;
39
+ exports.visitarExpressaoLogica = visitarExpressaoLogica;
40
+ exports.resolverIncrementoPara = resolverIncrementoPara;
41
+ exports.visitarExpressaoAcessoElementoMatriz = visitarExpressaoAcessoElementoMatriz;
42
+ exports.visitarExpressaoAtribuicaoPorIndicesMatriz = visitarExpressaoAtribuicaoPorIndicesMatriz;
43
+ exports.visitarDeclaracaoAleatorio = visitarDeclaracaoAleatorio;
44
+ exports.visitarExpressaoFormatacaoEscrita = visitarExpressaoFormatacaoEscrita;
45
+ exports.visitarExpressaoLeia = visitarExpressaoLeia;
46
+ const construtos_1 = require("@designliquido/delegua/construtos");
47
+ const declaracoes_1 = require("@designliquido/delegua/declaracoes");
48
+ const lexador_1 = require("@designliquido/delegua/lexador");
49
+ const excecoes_1 = require("@designliquido/delegua/excecoes");
50
+ const estruturas_1 = require("@designliquido/delegua/estruturas");
51
+ const inferenciador_1 = require("./inferenciador");
52
+ const lexico_regular_1 = __importDefault(require("../tipos-de-simbolos/lexico-regular"));
53
+ const bibliotecaCaracteres = __importStar(require("../bibliotecas/caracteres"));
54
+ const bibliotecaNumerica = __importStar(require("../bibliotecas/numerica"));
55
+ function carregarBibliotecaGlobalCaracter(pilhaEscoposExecucao) {
56
+ pilhaEscoposExecucao.definirVariavel('asc', new estruturas_1.FuncaoPadrao(1, bibliotecaCaracteres.asc));
57
+ pilhaEscoposExecucao.definirVariavel('carac', new estruturas_1.FuncaoPadrao(1, bibliotecaCaracteres.carac));
58
+ pilhaEscoposExecucao.definirVariavel('caracpnum', new estruturas_1.FuncaoPadrao(1, bibliotecaCaracteres.caracpnum));
59
+ pilhaEscoposExecucao.definirVariavel('compr', new estruturas_1.FuncaoPadrao(1, bibliotecaCaracteres.compr));
60
+ pilhaEscoposExecucao.definirVariavel('copia', new estruturas_1.FuncaoPadrao(3, bibliotecaCaracteres.copia));
61
+ pilhaEscoposExecucao.definirVariavel('maiusc', new estruturas_1.FuncaoPadrao(1, bibliotecaCaracteres.maiusc));
62
+ pilhaEscoposExecucao.definirVariavel('minusc', new estruturas_1.FuncaoPadrao(1, bibliotecaCaracteres.minusc));
63
+ pilhaEscoposExecucao.definirVariavel('numpcarac', new estruturas_1.FuncaoPadrao(1, bibliotecaCaracteres.numpcarac));
64
+ pilhaEscoposExecucao.definirVariavel('pos', new estruturas_1.FuncaoPadrao(2, bibliotecaCaracteres.pos));
65
+ }
66
+ function carregarBibliotecaGlobalNumerica(pilhaEscoposExecucao) {
67
+ pilhaEscoposExecucao.definirVariavel('abs', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.abs));
68
+ pilhaEscoposExecucao.definirVariavel('arccos', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.arccos));
69
+ pilhaEscoposExecucao.definirVariavel('arcsen', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.arcsen));
70
+ pilhaEscoposExecucao.definirVariavel('arctan', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.arctan));
71
+ pilhaEscoposExecucao.definirVariavel('cos', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.cos));
72
+ pilhaEscoposExecucao.definirVariavel('cotan', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.cotan));
73
+ pilhaEscoposExecucao.definirVariavel('exp', new estruturas_1.FuncaoPadrao(2, bibliotecaNumerica.exp));
74
+ pilhaEscoposExecucao.definirVariavel('grauprad', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.grauprad));
75
+ pilhaEscoposExecucao.definirVariavel('int', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.int));
76
+ pilhaEscoposExecucao.definirVariavel('log', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.log));
77
+ pilhaEscoposExecucao.definirVariavel('logn', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.logn));
78
+ pilhaEscoposExecucao.definirVariavel('pi', new estruturas_1.FuncaoPadrao(0, bibliotecaNumerica.pi));
79
+ pilhaEscoposExecucao.definirVariavel('quad', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.quad));
80
+ pilhaEscoposExecucao.definirVariavel('radpgrau', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.radpgrau));
81
+ pilhaEscoposExecucao.definirVariavel('raizq', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.raizq));
82
+ pilhaEscoposExecucao.definirVariavel('rand', new estruturas_1.FuncaoPadrao(0, bibliotecaNumerica.rand));
83
+ pilhaEscoposExecucao.definirVariavel('randi', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.randi));
84
+ pilhaEscoposExecucao.definirVariavel('sen', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.sen));
85
+ pilhaEscoposExecucao.definirVariavel('tan', new estruturas_1.FuncaoPadrao(1, bibliotecaNumerica.tan));
86
+ }
87
+ async function visitarDeclaracaoCabecalhoPrograma(interpretador, declaracao) {
88
+ return Promise.resolve();
89
+ }
90
+ /**
91
+ * Uma declaração de "classe" no VisuAlg nada mais é que a definição de um registro.
92
+ * Não há propriedades e não há herança. Por isso usamos uma versão simplificada
93
+ * da implementação original de Delégua.
94
+ * @param declaracao A declaração de registro.
95
+ * @returns Sempre retorna nulo, por ser requerido pelo contrato de visita.
96
+ */
97
+ async function visitarDeclaracaoClasse(interpretador, declaracao) {
98
+ const metodos = {};
99
+ if (declaracao.metodos.length > 0) {
100
+ const declaracaoConstrutor = declaracao.metodos[0];
101
+ const funcao = new estruturas_1.DeleguaFuncao('construtor', declaracaoConstrutor.funcao, undefined, true);
102
+ metodos['construtor'] = funcao;
103
+ }
104
+ const descritorTipoClasse = new estruturas_1.DescritorTipoClasse(declaracao.simbolo, undefined, metodos, declaracao.propriedades);
105
+ interpretador.pilhaEscoposExecucao.definirConstante(declaracao.simbolo.lexema, descritorTipoClasse);
106
+ interpretador.tiposConhecidos.push(declaracao.simbolo.lexema);
107
+ return null;
108
+ }
109
+ async function visitarDeclaracaoInicioAlgoritmo(interpretador, declaracao) {
110
+ return Promise.resolve();
111
+ }
112
+ function converterValor(valor, tipo) {
113
+ switch (tipo) {
114
+ case 'inteiro':
115
+ return parseInt(valor);
116
+ case 'lógico':
117
+ return Boolean(valor);
118
+ case 'número':
119
+ case 'real':
120
+ return Number(valor);
121
+ case 'texto':
122
+ return String(valor);
123
+ default:
124
+ return valor;
125
+ }
126
+ }
127
+ async function atribuirVariavel(interpretador, expressao, valor) {
128
+ if (expressao instanceof construtos_1.Variavel) {
129
+ interpretador.pilhaEscoposExecucao.atribuirVariavel(expressao.simbolo, valor);
130
+ return;
131
+ }
132
+ if (expressao instanceof construtos_1.AcessoElementoMatriz) {
133
+ const promises = await Promise.all([
134
+ avaliar(interpretador, expressao.indicePrimario),
135
+ avaliar(interpretador, expressao.indiceSecundario),
136
+ avaliar(interpretador, expressao.entidadeChamada),
137
+ ]);
138
+ let indicePrimario = promises[0];
139
+ let indiceSecundario = promises[1];
140
+ let entidadeChamada = promises[2];
141
+ entidadeChamada = entidadeChamada.hasOwnProperty('valor') ? entidadeChamada.valor : entidadeChamada;
142
+ indicePrimario = indicePrimario.hasOwnProperty('valor') ? indicePrimario.valor : indicePrimario;
143
+ indiceSecundario = indiceSecundario.hasOwnProperty('valor') ? indiceSecundario.valor : indiceSecundario;
144
+ if (Array.isArray(entidadeChamada)) {
145
+ if (indicePrimario < 0 && entidadeChamada.length !== 0) {
146
+ while (indicePrimario < 0) {
147
+ indicePrimario += entidadeChamada.length;
148
+ }
149
+ }
150
+ if (indiceSecundario < 0 && entidadeChamada.length !== 0) {
151
+ while (indiceSecundario < 0) {
152
+ indiceSecundario += entidadeChamada.length;
153
+ }
154
+ }
155
+ while (entidadeChamada.length < indicePrimario || entidadeChamada.length < indiceSecundario) {
156
+ entidadeChamada.push(null);
157
+ }
158
+ entidadeChamada[indicePrimario][indiceSecundario] = valor;
159
+ return Promise.resolve();
160
+ }
161
+ if (entidadeChamada instanceof construtos_1.Vetor) {
162
+ const primeiraDimensao = entidadeChamada.valores[indicePrimario];
163
+ const tipoElementar = primeiraDimensao.tipo.replace('[]', '');
164
+ primeiraDimensao.valores[indiceSecundario] = converterValor(valor, tipoElementar);
165
+ return Promise.resolve();
166
+ }
167
+ }
168
+ if (expressao instanceof construtos_1.AcessoIndiceVariavel) {
169
+ const promises = await Promise.all([
170
+ interpretador.avaliar(expressao.entidadeChamada),
171
+ interpretador.avaliar(expressao.indice),
172
+ ]);
173
+ let alvo = promises[0];
174
+ let indice = promises[1];
175
+ let valorAlvo;
176
+ let valorIndice;
177
+ if (alvo.hasOwnProperty('valor')) {
178
+ valorAlvo = alvo.valor;
179
+ }
180
+ else {
181
+ valorAlvo = alvo;
182
+ }
183
+ if (indice.hasOwnProperty('valor')) {
184
+ valorIndice = indice.valor;
185
+ }
186
+ else {
187
+ valorIndice = indice;
188
+ }
189
+ const subtipo = String(alvo.tipo).replace('[]', '');
190
+ const valorResolvido = converterValor(valor, subtipo);
191
+ if (valorAlvo instanceof construtos_1.Vetor) {
192
+ valorAlvo.valores[valorIndice] = valorResolvido;
193
+ }
194
+ else {
195
+ valorAlvo[valorIndice] = valorResolvido;
196
+ }
197
+ return;
198
+ }
199
+ if (expressao instanceof construtos_1.AcessoMetodoOuPropriedade) {
200
+ // Há apenas duas possibilidades aqui:
201
+ // 1. A entidade é uma variável
202
+ // 2. A entidade é um elemento de um vetor.
203
+ let referenciaVariavel;
204
+ let tipoBaseVariavel;
205
+ if (expressao.objeto instanceof construtos_1.AcessoIndiceVariavel) {
206
+ referenciaVariavel = await interpretador.avaliar(expressao.objeto.entidadeChamada);
207
+ tipoBaseVariavel = referenciaVariavel.tipo.replace('[]', '');
208
+ }
209
+ else {
210
+ referenciaVariavel = await interpretador.avaliar(expressao.objeto);
211
+ tipoBaseVariavel = referenciaVariavel.tipo;
212
+ }
213
+ // A única forma de o avaliador sintático gerar uma expressão do tipo
214
+ // `AcessoMetodoOuPropriedade` é se o `objeto` é um registro.
215
+ // Portanto, temos que pesquisar aqui o tipo da propriedade.
216
+ const tipoRelacionado = interpretador.pilhaEscoposExecucao.obterVariavelPorNome(tipoBaseVariavel);
217
+ const descritorTipoRelacionado = tipoRelacionado.hasOwnProperty('valor')
218
+ ? tipoRelacionado.valor
219
+ : tipoRelacionado;
220
+ const propriedadeRelacionada = descritorTipoRelacionado.propriedades.find((p) => p.nome.lexema === expressao.simbolo.lexema);
221
+ if (!propriedadeRelacionada) {
222
+ throw new excecoes_1.ErroEmTempoDeExecucao(expressao.simbolo, `Propriedade "${expressao.simbolo.lexema}" não existe no tipo ${descritorTipoRelacionado.simboloOriginal.lexema}.`);
223
+ }
224
+ let variavelObjeto = await interpretador.avaliar(expressao.objeto);
225
+ const valorVariavelObjeto = variavelObjeto.hasOwnProperty('valor')
226
+ ? variavelObjeto.valor
227
+ : variavelObjeto;
228
+ let valorConvertido = converterValor(valor, propriedadeRelacionada.tipo);
229
+ valorVariavelObjeto.definir(expressao.simbolo, valorConvertido);
230
+ }
231
+ }
232
+ async function avaliar(interpretador, expressao) {
233
+ return await expressao.aceitar(interpretador);
234
+ }
235
+ function eIgual(esquerda, direita) {
236
+ if (esquerda === null && direita === null)
237
+ return true;
238
+ if (esquerda === null)
239
+ return false;
240
+ return esquerda === direita;
241
+ }
242
+ function eVerdadeiro(objeto) {
243
+ if (objeto === null)
244
+ return false;
245
+ if (typeof objeto === 'boolean')
246
+ return Boolean(objeto);
247
+ if (objeto.hasOwnProperty('valor')) {
248
+ return Boolean(objeto.valor);
249
+ }
250
+ return true;
251
+ }
252
+ function verificarOperandosNumeros(operador, direita, esquerda) {
253
+ const tipoDireita = direita.tipo ? direita.tipo : typeof direita === 'number' ? 'número' : String(NaN);
254
+ const tipoEsquerda = esquerda.tipo ? esquerda.tipo : typeof esquerda === 'number' ? 'número' : String(NaN);
255
+ const tiposNumericos = ['inteiro', 'numero', 'número', 'real'];
256
+ if (tiposNumericos.includes(tipoDireita.toLowerCase()) && tiposNumericos.includes(tipoEsquerda.toLowerCase()))
257
+ return;
258
+ throw new excecoes_1.ErroEmTempoDeExecucao(operador, 'Operadores precisam ser números.', operador.linha);
259
+ }
260
+ function inicializacaoVetorOuMatriz(vetor, valorPadrao, tipoVetor) {
261
+ vetor.tipo = tipoVetor;
262
+ for (let i = 0; i < vetor.valores.length; i++) {
263
+ if (vetor.valores[i] instanceof construtos_1.Vetor) {
264
+ inicializacaoVetorOuMatriz(vetor.valores[i], valorPadrao, tipoVetor);
265
+ }
266
+ else {
267
+ vetor.valores[i] = valorPadrao;
268
+ }
269
+ }
270
+ }
271
+ /**
272
+ * Executa expressão de definição de variável.
273
+ * @param declaracao A declaração Var
274
+ * @returns Sempre retorna nulo.
275
+ */
276
+ async function visitarDeclaracaoVar(interpretador, declaracao) {
277
+ let valorFinal = await interpretador.avaliacaoDeclaracaoVarOuConst(declaracao);
278
+ const tipoInferido = declaracao.tipo;
279
+ if (String(declaracao.tipo).includes('[]')) {
280
+ switch (declaracao.tipo) {
281
+ case 'caracter[]':
282
+ case 'caractere[]': // TODO: Reduzir para 'caracter' na análise sintática.
283
+ case 'texto[]':
284
+ inicializacaoVetorOuMatriz(valorFinal, '', tipoInferido);
285
+ break;
286
+ case 'inteiro[]':
287
+ case 'real[]':
288
+ inicializacaoVetorOuMatriz(valorFinal, 0, tipoInferido);
289
+ break;
290
+ }
291
+ }
292
+ interpretador.pilhaEscoposExecucao.definirVariavel(declaracao.simbolo.lexema, valorFinal, tipoInferido);
293
+ return null;
294
+ }
295
+ async function visitarExpressaoAcessoIndiceVariavel(interpretador, expressao) {
296
+ const promises = await Promise.all([
297
+ interpretador.avaliar(expressao.entidadeChamada),
298
+ interpretador.avaliar(expressao.indice),
299
+ ]);
300
+ const variavelObjeto = promises[0];
301
+ const indice = promises[1];
302
+ const objeto = variavelObjeto.hasOwnProperty('valor') ? variavelObjeto.valor : variavelObjeto;
303
+ let valorIndice = indice.hasOwnProperty('valor') ? indice.valor : indice;
304
+ if (Array.isArray(objeto)) {
305
+ if (!Number.isInteger(valorIndice)) {
306
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Somente inteiros podem ser usados para indexar um vetor.', expressao.linha));
307
+ }
308
+ if (valorIndice < 0 && objeto.length !== 0) {
309
+ while (valorIndice < 0) {
310
+ valorIndice += objeto.length;
311
+ }
312
+ }
313
+ if (valorIndice >= objeto.length) {
314
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Índice do vetor fora do intervalo.', expressao.linha));
315
+ }
316
+ return objeto[valorIndice];
317
+ }
318
+ if (objeto instanceof construtos_1.Vetor) {
319
+ return objeto.valores[valorIndice];
320
+ }
321
+ if (objeto.constructor === Object ||
322
+ objeto instanceof estruturas_1.ObjetoDeleguaClasse ||
323
+ objeto instanceof estruturas_1.DeleguaFuncao ||
324
+ objeto instanceof estruturas_1.DescritorTipoClasse) {
325
+ return objeto[valorIndice] || null;
326
+ }
327
+ if (typeof objeto === 'string') {
328
+ if (!Number.isInteger(valorIndice)) {
329
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Somente inteiros podem ser usados para indexar um vetor.', expressao.linha));
330
+ }
331
+ if (valorIndice < 0 && objeto.length !== 0) {
332
+ while (valorIndice < 0) {
333
+ valorIndice += objeto.length;
334
+ }
335
+ }
336
+ if (valorIndice >= objeto.length) {
337
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Índice fora do tamanho.', expressao.linha));
338
+ }
339
+ return objeto.charAt(valorIndice);
340
+ }
341
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.entidadeChamada.nome, 'Somente listas, dicionários, classes e objetos podem ter seus valores indexados.', expressao.linha));
342
+ }
343
+ async function visitarExpressaoAtribuicaoPorIndice(interpretador, expressao) {
344
+ const promises = await Promise.all([
345
+ interpretador.avaliar(expressao.objeto),
346
+ interpretador.avaliar(expressao.indice),
347
+ interpretador.avaliar(expressao.valor),
348
+ ]);
349
+ let objeto = promises[0];
350
+ let indice = promises[1];
351
+ const valor = promises[2];
352
+ objeto = objeto.hasOwnProperty('valor') ? objeto.valor : objeto;
353
+ indice = indice.hasOwnProperty('valor') ? indice.valor : indice;
354
+ if (Array.isArray(objeto)) {
355
+ if (indice < 0 && objeto.length !== 0) {
356
+ while (indice < 0) {
357
+ indice += objeto.length;
358
+ }
359
+ }
360
+ while (objeto.length < indice) {
361
+ objeto.push(null);
362
+ }
363
+ objeto[indice] = valor;
364
+ }
365
+ else if (objeto instanceof construtos_1.Vetor) {
366
+ objeto.valores[indice] = valor;
367
+ }
368
+ else if (objeto.constructor === Object ||
369
+ objeto instanceof estruturas_1.ObjetoDeleguaClasse ||
370
+ objeto instanceof estruturas_1.DeleguaFuncao ||
371
+ objeto instanceof estruturas_1.DescritorTipoClasse) {
372
+ objeto[indice] = valor;
373
+ }
374
+ else {
375
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.objeto.nome, 'Somente listas, dicionários, classes e objetos podem ser mudados por sobrescrita.', expressao.linha));
376
+ }
377
+ }
378
+ /**
379
+ * Método de visita de expressão binária.
380
+ * Reintroduzido pelas particularidades do VisuAlg.
381
+ * @param expressao A expressão binária.
382
+ * @returns O resultado da resolução da expressão.
383
+ */
384
+ async function visitarExpressaoBinaria(interpretador, expressao) {
385
+ try {
386
+ const promises = await Promise.all([
387
+ avaliar(interpretador, expressao.esquerda),
388
+ avaliar(interpretador, expressao.direita),
389
+ ]);
390
+ const esquerda = promises[0];
391
+ const direita = promises[1];
392
+ let valorEsquerdo = (esquerda === null || esquerda === void 0 ? void 0 : esquerda.hasOwnProperty('valor')) ? esquerda.valor : esquerda;
393
+ let valorDireito = (direita === null || direita === void 0 ? void 0 : direita.hasOwnProperty('valor')) ? direita.valor : direita;
394
+ // No VisuAlg, uma variável pode resolver para função porque funções não precisam ter parênteses.
395
+ // Esta parte evita o problema.
396
+ if (valorEsquerdo && valorEsquerdo.hasOwnProperty('funcao')) {
397
+ valorEsquerdo = valorEsquerdo.funcao();
398
+ }
399
+ if (valorDireito && valorDireito.hasOwnProperty('funcao')) {
400
+ valorDireito = valorDireito.funcao();
401
+ }
402
+ const tipoEsquerdo = (esquerda === null || esquerda === void 0 ? void 0 : esquerda.hasOwnProperty('tipo')) ? esquerda.tipo : (0, inferenciador_1.inferirTipoVariavel)(esquerda);
403
+ const tipoDireito = (direita === null || direita === void 0 ? void 0 : direita.hasOwnProperty('tipo')) ? direita.tipo : (0, inferenciador_1.inferirTipoVariavel)(direita);
404
+ switch (expressao.operador.tipo) {
405
+ case lexico_regular_1.default.EXPONENCIACAO:
406
+ verificarOperandosNumeros(expressao.operador, esquerda, direita);
407
+ return Math.pow(valorEsquerdo, valorDireito);
408
+ case lexico_regular_1.default.MAIOR:
409
+ verificarOperandosNumeros(expressao.operador, esquerda, direita);
410
+ return Number(valorEsquerdo) > Number(valorDireito);
411
+ case lexico_regular_1.default.MAIOR_IGUAL:
412
+ verificarOperandosNumeros(expressao.operador, esquerda, direita);
413
+ return Number(valorEsquerdo) >= Number(valorDireito);
414
+ case lexico_regular_1.default.MENOR:
415
+ verificarOperandosNumeros(expressao.operador, esquerda, direita);
416
+ return Number(valorEsquerdo) < Number(valorDireito);
417
+ case lexico_regular_1.default.MENOR_IGUAL:
418
+ verificarOperandosNumeros(expressao.operador, esquerda, direita);
419
+ return Number(valorEsquerdo) <= Number(valorDireito);
420
+ case lexico_regular_1.default.SUBTRACAO:
421
+ verificarOperandosNumeros(expressao.operador, esquerda, direita);
422
+ return Number(valorEsquerdo) - Number(valorDireito);
423
+ case lexico_regular_1.default.ADICAO:
424
+ let tiposNumericos = ['inteiro', 'numero', 'número', 'real'];
425
+ if (tiposNumericos.includes(tipoEsquerdo.toLowerCase()) &&
426
+ tiposNumericos.includes(tipoDireito.toLowerCase())) {
427
+ return Number(valorEsquerdo) + Number(valorDireito);
428
+ }
429
+ else {
430
+ return String(valorEsquerdo) + String(valorDireito);
431
+ }
432
+ case lexico_regular_1.default.DIVISAO:
433
+ verificarOperandosNumeros(expressao.operador, esquerda, direita);
434
+ return Number(valorEsquerdo) / Number(valorDireito);
435
+ case lexico_regular_1.default.DIVISAO_INTEIRA:
436
+ verificarOperandosNumeros(expressao.operador, esquerda, direita);
437
+ return Math.floor(Number(valorEsquerdo) / Number(valorDireito));
438
+ case lexico_regular_1.default.MULTIPLICACAO:
439
+ if (tipoEsquerdo === 'texto' || tipoDireito === 'texto') {
440
+ // Sem ambos os valores resolvem como texto, multiplica normal.
441
+ // Se apenas um resolve como texto, o outro repete o
442
+ // texto n vezes, sendo n o valor do outro.
443
+ if (tipoEsquerdo === 'texto' && tipoDireito === 'texto') {
444
+ return Number(valorEsquerdo) * Number(valorDireito);
445
+ }
446
+ if (tipoEsquerdo === 'texto') {
447
+ return valorEsquerdo.repeat(Number(valorDireito));
448
+ }
449
+ return valorDireito.repeat(Number(valorEsquerdo));
450
+ }
451
+ return Number(valorEsquerdo) * Number(valorDireito);
452
+ case lexico_regular_1.default.MODULO:
453
+ verificarOperandosNumeros(expressao.operador, esquerda, direita);
454
+ return Number(valorEsquerdo) % Number(valorDireito);
455
+ case lexico_regular_1.default.DIFERENTE:
456
+ return !eIgual(valorEsquerdo, valorDireito);
457
+ case lexico_regular_1.default.IGUAL:
458
+ return eIgual(valorEsquerdo, valorDireito);
459
+ }
460
+ }
461
+ catch (erro) {
462
+ return Promise.reject(erro);
463
+ }
464
+ }
465
+ async function visitarExpressaoLogica(interpretador, expressao) {
466
+ const esquerda = await avaliar(interpretador, expressao.esquerda);
467
+ // se um estado for verdadeiro, retorna verdadeiro
468
+ if (expressao.operador.tipo === lexico_regular_1.default.OU) {
469
+ if (eVerdadeiro(esquerda))
470
+ return esquerda;
471
+ }
472
+ // se a primeira variável é verdadeiro, retorna a segunda invertida
473
+ if (expressao.operador.tipo === lexico_regular_1.default.XOU) {
474
+ const valorDireito = await avaliar(interpretador, expressao.direita);
475
+ return eVerdadeiro(esquerda) !== eVerdadeiro(valorDireito);
476
+ }
477
+ // se um estado for falso, retorna falso
478
+ if (expressao.operador.tipo === lexico_regular_1.default.E) {
479
+ if (!eVerdadeiro(esquerda))
480
+ return esquerda;
481
+ }
482
+ return await avaliar(interpretador, expressao.direita);
483
+ }
484
+ /* Isso existe porque o laço `para` do VisuAlg pode ter o passo positivo ou negativo
485
+ * dependendo dos operandos de início e fim, que só são possíveis de determinar
486
+ * em tempo de execução.
487
+ * Quando um dos operandos é uma variável, tanto a condição do laço quanto o
488
+ * passo são considerados indefinidos aqui.
489
+ */
490
+ async function resolverIncrementoPara(interpretador, declaracao) {
491
+ if (declaracao.resolverIncrementoEmExecucao) {
492
+ const promises = await Promise.all([
493
+ avaliar(interpretador, declaracao.condicao.esquerda),
494
+ avaliar(interpretador, declaracao.condicao.direita),
495
+ ]);
496
+ const operandoEsquerdo = promises[0];
497
+ const operandoDireito = promises[1];
498
+ const valorAtualEsquerdo = operandoEsquerdo.hasOwnProperty('valor') ? operandoEsquerdo.valor : operandoEsquerdo;
499
+ const valorAtualDireito = operandoDireito.hasOwnProperty('valor') ? operandoDireito.valor : operandoDireito;
500
+ if (valorAtualEsquerdo < valorAtualDireito) {
501
+ declaracao.condicao.operador = new lexador_1.Simbolo(lexico_regular_1.default.MENOR_IGUAL, '', '', Number(declaracao.linha), declaracao.hashArquivo);
502
+ declaracao.incrementar.condicaoPara.operador = new lexador_1.Simbolo(lexico_regular_1.default.MENOR, '', '', Number(declaracao.linha), declaracao.hashArquivo);
503
+ declaracao.incrementar.incremento.expressao.valor.direita = new construtos_1.Literal(declaracao.hashArquivo, Number(declaracao.linha), 1);
504
+ }
505
+ else {
506
+ declaracao.condicao.operador = new lexador_1.Simbolo(lexico_regular_1.default.MAIOR_IGUAL, '', '', Number(declaracao.linha), declaracao.hashArquivo);
507
+ declaracao.incrementar.condicaoPara.operador = new lexador_1.Simbolo(lexico_regular_1.default.MAIOR, '', '', Number(declaracao.linha), declaracao.hashArquivo);
508
+ declaracao.incrementar.incremento.expressao.valor.direita = new construtos_1.Unario(declaracao.hashArquivo, new lexador_1.Simbolo(lexico_regular_1.default.SUBTRACAO, '-', undefined, declaracao.linha, declaracao.hashArquivo), new construtos_1.Literal(declaracao.hashArquivo, Number(declaracao.linha), 1), 'ANTES');
509
+ }
510
+ }
511
+ }
512
+ async function visitarExpressaoAcessoElementoMatriz(interpretador, expressao) {
513
+ const promises = await Promise.all([
514
+ avaliar(interpretador, expressao.entidadeChamada),
515
+ avaliar(interpretador, expressao.indicePrimario),
516
+ avaliar(interpretador, expressao.indiceSecundario),
517
+ ]);
518
+ const variavelObjeto = promises[0];
519
+ const indicePrimario = promises[1];
520
+ const indiceSecundario = promises[2];
521
+ const objeto = variavelObjeto.hasOwnProperty('valor') ? variavelObjeto.valor : variavelObjeto;
522
+ let valorIndicePrimario = indicePrimario.hasOwnProperty('valor') ? indicePrimario.valor : indicePrimario;
523
+ let valorIndiceSecundario = indiceSecundario.hasOwnProperty('valor') ? indiceSecundario.valor : indiceSecundario;
524
+ if (!Number.isInteger(valorIndicePrimario) || !Number.isInteger(valorIndiceSecundario)) {
525
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Somente inteiros podem ser usados para indexar um vetor.', expressao.linha));
526
+ }
527
+ if (Array.isArray(objeto)) {
528
+ if (valorIndicePrimario < 0 && objeto.length !== 0) {
529
+ while (valorIndicePrimario < 0) {
530
+ valorIndicePrimario += objeto.length;
531
+ }
532
+ }
533
+ if (valorIndiceSecundario < 0 && objeto.length !== 0) {
534
+ while (valorIndiceSecundario < 0) {
535
+ valorIndiceSecundario += objeto.length;
536
+ }
537
+ }
538
+ if (valorIndicePrimario >= objeto.length || valorIndiceSecundario >= objeto.length) {
539
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Índice do vetor fora do intervalo.', expressao.linha));
540
+ }
541
+ return objeto[valorIndicePrimario][valorIndiceSecundario];
542
+ }
543
+ if (objeto instanceof construtos_1.Vetor) {
544
+ const vetorPrimario = objeto.valores[valorIndicePrimario];
545
+ return vetorPrimario.valores[valorIndiceSecundario];
546
+ }
547
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.entidadeChamada.valor, 'Somente listas, dicionários, classes e objetos podem ser mudados por sobrescrita.', expressao.linha));
548
+ }
549
+ async function visitarExpressaoAtribuicaoPorIndicesMatriz(interpretador, expressao) {
550
+ const promises = await Promise.all([
551
+ avaliar(interpretador, expressao.objeto),
552
+ avaliar(interpretador, expressao.indicePrimario),
553
+ avaliar(interpretador, expressao.indiceSecundario),
554
+ avaliar(interpretador, expressao.valor),
555
+ ]);
556
+ let objeto = promises[0];
557
+ let indicePrimario = promises[1];
558
+ let indiceSecundario = promises[2];
559
+ const valor = promises[3];
560
+ objeto = objeto.hasOwnProperty('valor') ? objeto.valor : objeto;
561
+ indicePrimario = indicePrimario.hasOwnProperty('valor') ? indicePrimario.valor : indicePrimario;
562
+ indiceSecundario = indiceSecundario.hasOwnProperty('valor') ? indiceSecundario.valor : indiceSecundario;
563
+ if (Array.isArray(objeto)) {
564
+ if (indicePrimario < 0 && objeto.length !== 0) {
565
+ while (indicePrimario < 0) {
566
+ indicePrimario += objeto.length;
567
+ }
568
+ }
569
+ if (indiceSecundario < 0 && objeto.length !== 0) {
570
+ while (indiceSecundario < 0) {
571
+ indiceSecundario += objeto.length;
572
+ }
573
+ }
574
+ while (objeto.length < indicePrimario || objeto.length < indiceSecundario) {
575
+ objeto.push(null);
576
+ }
577
+ objeto[indicePrimario][indiceSecundario] = valor;
578
+ return Promise.resolve();
579
+ }
580
+ if (objeto instanceof construtos_1.Vetor) {
581
+ const primeiraDimensao = objeto.valores[indicePrimario];
582
+ const tipoElementar = primeiraDimensao.tipo.replace('[]', '');
583
+ primeiraDimensao.valores[indiceSecundario] = converterValor(valor, tipoElementar);
584
+ return Promise.resolve();
585
+ }
586
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.objeto.nome, 'Somente listas, dicionários, classes e objetos podem ser mudados por sobrescrita.', expressao.linha));
587
+ }
588
+ async function encontrarLeiaNoAleatorio(interpretador, declaracao, menorNumero, maiorNumero) {
589
+ if ('declaracoes' in declaracao) {
590
+ // Se a declaração tiver um campo 'declaracoes', ela é um Bloco
591
+ const declaracoes = declaracao.declaracoes;
592
+ for (const subDeclaracao of declaracoes) {
593
+ encontrarLeiaNoAleatorio(interpretador, subDeclaracao, menorNumero, maiorNumero);
594
+ }
595
+ }
596
+ else if (declaracao instanceof declaracoes_1.Leia) {
597
+ // Se encontrarmos um Leia, podemos efetuar as operações imediatamente
598
+ for (const argumento of declaracao.argumentos) {
599
+ const arg1 = await interpretador.avaliar(argumento);
600
+ const tipoDe = arg1.tipo || (0, inferenciador_1.inferirTipoVariavel)(arg1);
601
+ const valor = tipoDe === 'texto' ? palavraAleatoriaCom5Digitos() : gerarNumeroAleatorio(menorNumero, maiorNumero);
602
+ atribuirVariavel(interpretador, argumento, valor);
603
+ }
604
+ }
605
+ }
606
+ function gerarNumeroAleatorio(min, max) {
607
+ return Math.floor(Math.random() * (max - min) + min);
608
+ }
609
+ function palavraAleatoriaCom5Digitos() {
610
+ const caracteres = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
611
+ let palavra = '';
612
+ for (let i = 0; i < 5; i++) {
613
+ const indiceAleatorio = Math.floor(Math.random() * caracteres.length);
614
+ palavra += caracteres.charAt(indiceAleatorio);
615
+ }
616
+ return palavra;
617
+ }
618
+ async function visitarDeclaracaoAleatorio(interpretador, expressao) {
619
+ let retornoExecucao;
620
+ try {
621
+ let menorNumero = 0;
622
+ let maiorNumero = 100;
623
+ if (expressao.argumentos) {
624
+ menorNumero = Math.min(expressao.argumentos.min, expressao.argumentos.max);
625
+ maiorNumero = Math.max(expressao.argumentos.min, expressao.argumentos.max);
626
+ }
627
+ for (let corpoDeclaracao of expressao.corpo.declaracoes) {
628
+ encontrarLeiaNoAleatorio(interpretador, corpoDeclaracao, menorNumero, maiorNumero);
629
+ retornoExecucao = await interpretador.executar(corpoDeclaracao, false);
630
+ }
631
+ }
632
+ catch (error) {
633
+ interpretador.erros.push({
634
+ erroInterno: error,
635
+ linha: expressao.linha,
636
+ hashArquivo: expressao.hashArquivo,
637
+ });
638
+ return Promise.reject(error);
639
+ }
640
+ return retornoExecucao;
641
+ }
642
+ /**
643
+ * Formata uma saída de acordo com o número e espaços e casas decimais solicitados.
644
+ * @param declaracao A declaração de formatação de escrita.
645
+ * @returns {string} A saída formatada como texto e os respectivos parâmetros aplicados.
646
+ */
647
+ async function visitarExpressaoFormatacaoEscrita(interpretador, declaracao) {
648
+ let resultado = '';
649
+ const conteudo = await interpretador.avaliar(declaracao.expressao);
650
+ const valorConteudo = (conteudo === null || conteudo === void 0 ? void 0 : conteudo.hasOwnProperty('valor')) ? conteudo.valor : conteudo;
651
+ const tipoConteudo = (conteudo === null || conteudo === void 0 ? void 0 : conteudo.hasOwnProperty('tipo')) ? conteudo.tipo : typeof conteudo;
652
+ resultado = valorConteudo;
653
+ if (['real', 'inteiro'].includes(tipoConteudo) && declaracao.casasDecimais > 0) {
654
+ resultado = valorConteudo.toLocaleString('pt', { minimumFractionDigits: declaracao.casasDecimais });
655
+ }
656
+ if (declaracao.espacos > 0) {
657
+ resultado = ' '.repeat(declaracao.espacos) + resultado;
658
+ }
659
+ return resultado;
660
+ }
661
+ /**
662
+ * Customização da leitura de dados de entrada.
663
+ * A interrupção da execução para leitura de dados do usuário
664
+ * ocorre quando o modo aleatório não está habilitado.
665
+ * @param interpretador A instância do interpretador.
666
+ * @param expressao A expressão `Leia`
667
+ * @param mensagemPrompt A mensagem de prompt. Normalmente é o último conteúdo da função `escreva()`
668
+ * ou ainda `escreval()`, e é usada em prompts Web, como por exemplo `window.prompt`.
669
+ */
670
+ async function visitarExpressaoLeia(interpretador, expressao, mensagemPrompt) {
671
+ // Verifica se a leitura deve ser interrompida antes de prosseguir
672
+ if (!expressao.eParaInterromper) {
673
+ for (let argumento of expressao.argumentos) {
674
+ const promessaLeitura = () => new Promise((resolucao) => interpretador.interfaceEntradaSaida.question(interpretador.deveEscreverPrompt ? mensagemPrompt : '', (resposta) => {
675
+ mensagemPrompt = '> ';
676
+ resolucao(resposta);
677
+ }));
678
+ const valorLido = await promessaLeitura();
679
+ await atribuirVariavel(interpretador, argumento, valorLido);
680
+ }
681
+ }
682
+ }
605
683
  //# sourceMappingURL=comum.js.map