@designliquido/delegua 0.9.2 → 0.9.4

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 (244) hide show
  1. package/bin/delegua +1 -1
  2. package/bin/delegua.cmd +1 -1
  3. package/bin/package.json +3 -3
  4. package/coverage/lcov-report/sorter.js +4 -4
  5. package/coverage/lcov-report/sorter.js.map +1 -1
  6. package/execucao.d.ts +1 -0
  7. package/execucao.js +29 -0
  8. package/execucao.js.map +1 -0
  9. package/fontes/avaliador-sintatico/avaliador-sintatico-base.d.ts +1 -1
  10. package/fontes/avaliador-sintatico/avaliador-sintatico-base.js +108 -105
  11. package/fontes/avaliador-sintatico/avaliador-sintatico-base.js.map +1 -1
  12. package/fontes/avaliador-sintatico/avaliador-sintatico.d.ts +1 -1
  13. package/fontes/avaliador-sintatico/avaliador-sintatico.js +244 -256
  14. package/fontes/avaliador-sintatico/avaliador-sintatico.js.map +1 -1
  15. package/fontes/avaliador-sintatico/dialetos/avaliador-sintatico-birl.d.ts +20 -0
  16. package/fontes/avaliador-sintatico/dialetos/avaliador-sintatico-birl.js +68 -0
  17. package/fontes/avaliador-sintatico/dialetos/avaliador-sintatico-birl.js.map +1 -0
  18. package/fontes/avaliador-sintatico/dialetos/avaliador-sintatico-egua-classico.d.ts +1 -1
  19. package/fontes/avaliador-sintatico/dialetos/avaliador-sintatico-egua-classico.js +227 -236
  20. package/fontes/avaliador-sintatico/dialetos/avaliador-sintatico-egua-classico.js.map +1 -1
  21. package/fontes/avaliador-sintatico/dialetos/avaliador-sintatico-eguap.d.ts +1 -1
  22. package/fontes/avaliador-sintatico/dialetos/avaliador-sintatico-eguap.js +247 -257
  23. package/fontes/avaliador-sintatico/dialetos/avaliador-sintatico-eguap.js.map +1 -1
  24. package/fontes/avaliador-sintatico/dialetos/avaliador-sintatico-visualg.d.ts +3 -0
  25. package/fontes/avaliador-sintatico/dialetos/avaliador-sintatico-visualg.js +192 -131
  26. package/fontes/avaliador-sintatico/dialetos/avaliador-sintatico-visualg.js.map +1 -1
  27. package/fontes/avaliador-sintatico/erro-avaliador-sintatico.js +6 -24
  28. package/fontes/avaliador-sintatico/erro-avaliador-sintatico.js.map +1 -1
  29. package/fontes/bibliotecas/biblioteca-global.js +206 -367
  30. package/fontes/bibliotecas/biblioteca-global.js.map +1 -1
  31. package/fontes/bibliotecas/importar-biblioteca.js +28 -29
  32. package/fontes/bibliotecas/importar-biblioteca.js.map +1 -1
  33. package/fontes/bibliotecas/primitivas-texto.js +9 -22
  34. package/fontes/bibliotecas/primitivas-texto.js.map +1 -1
  35. package/fontes/bibliotecas/primitivas-vetor.js +12 -14
  36. package/fontes/bibliotecas/primitivas-vetor.js.map +1 -1
  37. package/fontes/construtos/acesso-indice-variavel.js +6 -50
  38. package/fontes/construtos/acesso-indice-variavel.js.map +1 -1
  39. package/fontes/construtos/acesso-metodo.js +6 -50
  40. package/fontes/construtos/acesso-metodo.js.map +1 -1
  41. package/fontes/construtos/agrupamento.js +6 -50
  42. package/fontes/construtos/agrupamento.js.map +1 -1
  43. package/fontes/construtos/atribuicao-sobrescrita.js +6 -50
  44. package/fontes/construtos/atribuicao-sobrescrita.js.map +1 -1
  45. package/fontes/construtos/atribuir.js +6 -50
  46. package/fontes/construtos/atribuir.js.map +1 -1
  47. package/fontes/construtos/binario.js +6 -50
  48. package/fontes/construtos/binario.js.map +1 -1
  49. package/fontes/construtos/chamada.js +6 -50
  50. package/fontes/construtos/chamada.js.map +1 -1
  51. package/fontes/construtos/definir-valor.js +6 -50
  52. package/fontes/construtos/definir-valor.js.map +1 -1
  53. package/fontes/construtos/dicionario.js +6 -50
  54. package/fontes/construtos/dicionario.js.map +1 -1
  55. package/fontes/construtos/funcao.d.ts +2 -2
  56. package/fontes/construtos/funcao.js +6 -47
  57. package/fontes/construtos/funcao.js.map +1 -1
  58. package/fontes/construtos/isto.js +6 -47
  59. package/fontes/construtos/isto.js.map +1 -1
  60. package/fontes/construtos/literal.js +6 -47
  61. package/fontes/construtos/literal.js.map +1 -1
  62. package/fontes/construtos/logico.js +6 -50
  63. package/fontes/construtos/logico.js.map +1 -1
  64. package/fontes/construtos/super.js +6 -47
  65. package/fontes/construtos/super.js.map +1 -1
  66. package/fontes/construtos/unario.js +6 -50
  67. package/fontes/construtos/unario.js.map +1 -1
  68. package/fontes/construtos/variavel.js +6 -47
  69. package/fontes/construtos/variavel.js.map +1 -1
  70. package/fontes/construtos/vetor.js +6 -50
  71. package/fontes/construtos/vetor.js.map +1 -1
  72. package/fontes/declaracoes/bloco.js +9 -70
  73. package/fontes/declaracoes/bloco.js.map +1 -1
  74. package/fontes/declaracoes/classe.js +11 -72
  75. package/fontes/declaracoes/classe.js.map +1 -1
  76. package/fontes/declaracoes/continua.js +8 -65
  77. package/fontes/declaracoes/continua.js.map +1 -1
  78. package/fontes/declaracoes/declaracao.js +6 -47
  79. package/fontes/declaracoes/declaracao.js.map +1 -1
  80. package/fontes/declaracoes/enquanto.js +10 -71
  81. package/fontes/declaracoes/enquanto.js.map +1 -1
  82. package/fontes/declaracoes/escolha.js +11 -72
  83. package/fontes/declaracoes/escolha.js.map +1 -1
  84. package/fontes/declaracoes/escreva.js +9 -70
  85. package/fontes/declaracoes/escreva.js.map +1 -1
  86. package/fontes/declaracoes/expressao.js +9 -70
  87. package/fontes/declaracoes/expressao.js.map +1 -1
  88. package/fontes/declaracoes/fazer.js +10 -71
  89. package/fontes/declaracoes/fazer.js.map +1 -1
  90. package/fontes/declaracoes/funcao.js +10 -68
  91. package/fontes/declaracoes/funcao.js.map +1 -1
  92. package/fontes/declaracoes/importar.js +10 -71
  93. package/fontes/declaracoes/importar.js.map +1 -1
  94. package/fontes/declaracoes/leia.js +9 -70
  95. package/fontes/declaracoes/leia.js.map +1 -1
  96. package/fontes/declaracoes/para.js +12 -73
  97. package/fontes/declaracoes/para.js.map +1 -1
  98. package/fontes/declaracoes/retorna.js +10 -71
  99. package/fontes/declaracoes/retorna.js.map +1 -1
  100. package/fontes/declaracoes/se.js +12 -73
  101. package/fontes/declaracoes/se.js.map +1 -1
  102. package/fontes/declaracoes/sustar.js +8 -65
  103. package/fontes/declaracoes/sustar.js.map +1 -1
  104. package/fontes/declaracoes/tente.js +12 -73
  105. package/fontes/declaracoes/tente.js.map +1 -1
  106. package/fontes/declaracoes/var.js +10 -71
  107. package/fontes/declaracoes/var.js.map +1 -1
  108. package/fontes/delegua.js +125 -206
  109. package/fontes/delegua.js.map +1 -1
  110. package/fontes/depuracao/cyrb53.js +3 -4
  111. package/fontes/depuracao/cyrb53.js.map +1 -1
  112. package/fontes/depuracao/servidor-depuracao.js +125 -209
  113. package/fontes/depuracao/servidor-depuracao.js.map +1 -1
  114. package/fontes/espaco-variaveis.js +3 -4
  115. package/fontes/espaco-variaveis.js.map +1 -1
  116. package/fontes/estruturas/chamavel.js +6 -9
  117. package/fontes/estruturas/chamavel.js.map +1 -1
  118. package/fontes/estruturas/classe-padrao.js +17 -35
  119. package/fontes/estruturas/classe-padrao.js.map +1 -1
  120. package/fontes/estruturas/delegua-classe.d.ts +2 -2
  121. package/fontes/estruturas/delegua-classe.js +21 -39
  122. package/fontes/estruturas/delegua-classe.js.map +1 -1
  123. package/fontes/estruturas/delegua-funcao.js +48 -114
  124. package/fontes/estruturas/delegua-funcao.js.map +1 -1
  125. package/fontes/estruturas/funcao-padrao.js +13 -75
  126. package/fontes/estruturas/funcao-padrao.js.map +1 -1
  127. package/fontes/estruturas/metodo-primitiva.js +11 -39
  128. package/fontes/estruturas/metodo-primitiva.js.map +1 -1
  129. package/fontes/estruturas/modulo.js +6 -7
  130. package/fontes/estruturas/modulo.js.map +1 -1
  131. package/fontes/estruturas/objeto-delegua-classe.d.ts +3 -3
  132. package/fontes/estruturas/objeto-delegua-classe.js +12 -13
  133. package/fontes/estruturas/objeto-delegua-classe.js.map +1 -1
  134. package/fontes/estruturas/objeto-padrao.js +9 -11
  135. package/fontes/estruturas/objeto-padrao.js.map +1 -1
  136. package/fontes/excecoes/erro-em-tempo-de-execucao.js +8 -26
  137. package/fontes/excecoes/erro-em-tempo-de-execucao.js.map +1 -1
  138. package/fontes/importador/importador.js +21 -22
  139. package/fontes/importador/importador.js.map +1 -1
  140. package/fontes/interfaces/avaliador-sintatico-interface.d.ts +1 -1
  141. package/fontes/interfaces/parametro-interface.d.ts +1 -1
  142. package/fontes/interpretador/dialetos/egua-classico.js +592 -1019
  143. package/fontes/interpretador/dialetos/egua-classico.js.map +1 -1
  144. package/fontes/interpretador/inferenciador.js +1 -1
  145. package/fontes/interpretador/inferenciador.js.map +1 -1
  146. package/fontes/interpretador/interpretador-com-depuracao.js +186 -336
  147. package/fontes/interpretador/interpretador-com-depuracao.js.map +1 -1
  148. package/fontes/interpretador/interpretador.js +706 -1175
  149. package/fontes/interpretador/interpretador.js.map +1 -1
  150. package/fontes/interpretador/pilha-escopos-execucao.js +52 -57
  151. package/fontes/interpretador/pilha-escopos-execucao.js.map +1 -1
  152. package/fontes/lexador/dialetos/lexador-birl.d.ts +6 -19
  153. package/fontes/lexador/dialetos/lexador-birl.js +157 -49
  154. package/fontes/lexador/dialetos/lexador-birl.js.map +1 -1
  155. package/fontes/lexador/dialetos/lexador-egua-classico.js +43 -46
  156. package/fontes/lexador/dialetos/lexador-egua-classico.js.map +1 -1
  157. package/fontes/lexador/dialetos/lexador-eguap.js +59 -63
  158. package/fontes/lexador/dialetos/lexador-eguap.js.map +1 -1
  159. package/fontes/lexador/dialetos/lexador-visualg.js +45 -54
  160. package/fontes/lexador/dialetos/lexador-visualg.js.map +1 -1
  161. package/fontes/lexador/dialetos/palavras-reservadas/birl.d.ts +14 -1
  162. package/fontes/lexador/dialetos/palavras-reservadas/birl.js +18 -1
  163. package/fontes/lexador/dialetos/palavras-reservadas/birl.js.map +1 -1
  164. package/fontes/lexador/dialetos/palavras-reservadas/egua-classico.js +1 -1
  165. package/fontes/lexador/dialetos/palavras-reservadas/egua-classico.js.map +1 -1
  166. package/fontes/lexador/dialetos/palavras-reservadas/visualg.d.ts +24 -0
  167. package/fontes/lexador/dialetos/palavras-reservadas/visualg.js +25 -1
  168. package/fontes/lexador/dialetos/palavras-reservadas/visualg.js.map +1 -1
  169. package/fontes/lexador/lexador-base-linha-unica.d.ts +1 -1
  170. package/fontes/lexador/lexador-base-linha-unica.js +28 -29
  171. package/fontes/lexador/lexador-base-linha-unica.js.map +1 -1
  172. package/fontes/lexador/lexador.js +53 -57
  173. package/fontes/lexador/lexador.js.map +1 -1
  174. package/fontes/lexador/palavras-reservadas.js +1 -1
  175. package/fontes/lexador/palavras-reservadas.js.map +1 -1
  176. package/fontes/lexador/simbolo.js +5 -6
  177. package/fontes/lexador/simbolo.js.map +1 -1
  178. package/fontes/quebras/index.js +11 -42
  179. package/fontes/quebras/index.js.map +1 -1
  180. package/fontes/resolvedor/dialetos/egua-classico.js +143 -144
  181. package/fontes/resolvedor/dialetos/egua-classico.js.map +1 -1
  182. package/fontes/resolvedor/erro-resolvedor.js +6 -24
  183. package/fontes/resolvedor/erro-resolvedor.js.map +1 -1
  184. package/fontes/resolvedor/pilha-escopos.js +11 -12
  185. package/fontes/resolvedor/pilha-escopos.js.map +1 -1
  186. package/fontes/tipos-de-simbolos/birl.d.ts +7 -0
  187. package/fontes/tipos-de-simbolos/birl.js +20 -12
  188. package/fontes/tipos-de-simbolos/birl.js.map +1 -1
  189. package/fontes/tipos-de-simbolos/comum.d.ts +2 -0
  190. package/fontes/tipos-de-simbolos/comum.js +2 -0
  191. package/fontes/tipos-de-simbolos/comum.js.map +1 -1
  192. package/fontes/tipos-de-simbolos/visualg.d.ts +9 -0
  193. package/fontes/tipos-de-simbolos/visualg.js +9 -0
  194. package/fontes/tipos-de-simbolos/visualg.js.map +1 -1
  195. package/index.d.ts +5 -1
  196. package/index.js +18 -25
  197. package/index.js.map +1 -1
  198. package/jest.config.js +9 -47
  199. package/jest.config.js.map +1 -1
  200. package/package.json +3 -3
  201. package/testes/__mocks__/estatistica.js +1 -1
  202. package/testes/__mocks__/estatistica.js.map +1 -1
  203. package/testes/__mocks__/fisica.js +1 -1
  204. package/testes/__mocks__/fisica.js.map +1 -1
  205. package/testes/__mocks__/matematica.js +1 -1
  206. package/testes/__mocks__/matematica.js.map +1 -1
  207. package/testes/avaliador-sintatico.test.js +27 -27
  208. package/testes/avaliador-sintatico.test.js.map +1 -1
  209. package/testes/biblioteca-global.test.js +197 -440
  210. package/testes/biblioteca-global.test.js.map +1 -1
  211. package/testes/birl/avaliador-sintatico.test.d.ts +1 -0
  212. package/testes/birl/avaliador-sintatico.test.js +18 -0
  213. package/testes/birl/avaliador-sintatico.test.js.map +1 -0
  214. package/testes/birl/lexador.test.d.ts +1 -0
  215. package/testes/birl/lexador.test.js +31 -0
  216. package/testes/birl/lexador.test.js.map +1 -0
  217. package/testes/delegua.test.js +7 -7
  218. package/testes/delegua.test.js.map +1 -1
  219. package/testes/egua-classico/avaliador-sintatico.test.js +14 -14
  220. package/testes/egua-classico/avaliador-sintatico.test.js.map +1 -1
  221. package/testes/egua-classico/delegua.test.js +5 -5
  222. package/testes/egua-classico/delegua.test.js.map +1 -1
  223. package/testes/egua-classico/interpretador.test.js +180 -396
  224. package/testes/egua-classico/interpretador.test.js.map +1 -1
  225. package/testes/egua-classico/lexador.test.js +23 -23
  226. package/testes/egua-classico/lexador.test.js.map +1 -1
  227. package/testes/egua-classico/resolvedor.test.js +12 -12
  228. package/testes/egua-classico/resolvedor.test.js.map +1 -1
  229. package/testes/eguap/avaliador-sintatico.test.js +11 -11
  230. package/testes/eguap/avaliador-sintatico.test.js.map +1 -1
  231. package/testes/eguap/interpretador.test.js +189 -405
  232. package/testes/eguap/interpretador.test.js.map +1 -1
  233. package/testes/eguap/lexador.test.js +18 -18
  234. package/testes/eguap/lexador.test.js.map +1 -1
  235. package/testes/interpretador.test.js +431 -908
  236. package/testes/interpretador.test.js.map +1 -1
  237. package/testes/lexador.test.js +42 -42
  238. package/testes/lexador.test.js.map +1 -1
  239. package/testes/visualg/avaliador-sintatico.test.js +23 -23
  240. package/testes/visualg/avaliador-sintatico.test.js.map +1 -1
  241. package/testes/visualg/interpretador.test.js +16 -61
  242. package/testes/visualg/interpretador.test.js.map +1 -1
  243. package/testes/visualg/lexador.test.js +15 -15
  244. package/testes/visualg/lexador.test.js.map +1 -1
@@ -22,69 +22,31 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
- var __generator = (this && this.__generator) || function (thisArg, body) {
35
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
36
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
37
- function verb(n) { return function (v) { return step([n, v]); }; }
38
- function step(op) {
39
- if (f) throw new TypeError("Generator is already executing.");
40
- while (_) try {
41
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
42
- if (y = 0, t) op = [op[0] & 2, t.value];
43
- switch (op[0]) {
44
- case 0: case 1: t = op; break;
45
- case 4: _.label++; return { value: op[1], done: false };
46
- case 5: _.label++; y = op[1]; op = [0]; continue;
47
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
48
- default:
49
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
50
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
51
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
52
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
53
- if (t[2]) _.ops.pop();
54
- _.trys.pop(); continue;
55
- }
56
- op = body.call(thisArg, _);
57
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
58
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
59
- }
60
- };
61
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
62
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
63
27
  };
64
28
  Object.defineProperty(exports, "__esModule", { value: true });
65
29
  exports.Interpretador = void 0;
66
- var caminho = __importStar(require("path"));
67
- var browser_process_hrtime_1 = __importDefault(require("browser-process-hrtime"));
68
- var espaco_variaveis_1 = require("../espaco-variaveis");
69
- var biblioteca_global_1 = __importDefault(require("../bibliotecas/biblioteca-global"));
70
- var importar_biblioteca_1 = __importDefault(require("../bibliotecas/importar-biblioteca"));
71
- var excecoes_1 = require("../excecoes");
72
- var estruturas_1 = require("../estruturas");
73
- var pilha_escopos_execucao_1 = require("./pilha-escopos-execucao");
74
- var quebras_1 = require("../quebras");
75
- var inferenciador_1 = require("./inferenciador");
76
- var metodo_primitiva_1 = require("../estruturas/metodo-primitiva");
77
- var primitivas_texto_1 = __importDefault(require("../bibliotecas/primitivas-texto"));
78
- var primitivas_vetor_1 = __importDefault(require("../bibliotecas/primitivas-vetor"));
79
- var delegua_1 = __importDefault(require("../tipos-de-simbolos/delegua"));
30
+ const caminho = __importStar(require("path"));
31
+ const browser_process_hrtime_1 = __importDefault(require("browser-process-hrtime"));
32
+ const espaco_variaveis_1 = require("../espaco-variaveis");
33
+ const biblioteca_global_1 = __importDefault(require("../bibliotecas/biblioteca-global"));
34
+ const importar_biblioteca_1 = __importDefault(require("../bibliotecas/importar-biblioteca"));
35
+ const excecoes_1 = require("../excecoes");
36
+ const estruturas_1 = require("../estruturas");
37
+ const pilha_escopos_execucao_1 = require("./pilha-escopos-execucao");
38
+ const quebras_1 = require("../quebras");
39
+ const inferenciador_1 = require("./inferenciador");
40
+ const metodo_primitiva_1 = require("../estruturas/metodo-primitiva");
41
+ const primitivas_texto_1 = __importDefault(require("../bibliotecas/primitivas-texto"));
42
+ const primitivas_vetor_1 = __importDefault(require("../bibliotecas/primitivas-vetor"));
43
+ const delegua_1 = __importDefault(require("../tipos-de-simbolos/delegua"));
80
44
  /**
81
45
  * O Interpretador visita todos os elementos complexos gerados pelo avaliador sintático (_parser_),
82
46
  * e de fato executa a lógica de programação descrita no código.
83
47
  */
84
- var Interpretador = /** @class */ (function () {
85
- function Interpretador(importador, diretorioBase, performance, funcaoDeRetorno) {
86
- if (performance === void 0) { performance = false; }
87
- if (funcaoDeRetorno === void 0) { funcaoDeRetorno = null; }
48
+ class Interpretador {
49
+ constructor(importador, diretorioBase, performance = false, funcaoDeRetorno = null) {
88
50
  this.funcaoDeRetorno = null;
89
51
  this.interfaceDeEntrada = null;
90
52
  this.resultadoInterpretador = [];
@@ -97,7 +59,7 @@ var Interpretador = /** @class */ (function () {
97
59
  this.erros = [];
98
60
  this.declaracoes = [];
99
61
  this.pilhaEscoposExecucao = new pilha_escopos_execucao_1.PilhaEscoposExecucao();
100
- var escopoExecucao = {
62
+ const escopoExecucao = {
101
63
  declaracoes: [],
102
64
  declaracaoAtual: 0,
103
65
  ambiente: new espaco_variaveis_1.EspacoVariaveis(),
@@ -111,129 +73,95 @@ var Interpretador = /** @class */ (function () {
111
73
  * @param expressao Expressão do tipo Leia
112
74
  * @returns Promise com o resultado da leitura.
113
75
  */
114
- Interpretador.prototype.visitarExpressaoLeia = function (expressao) {
115
- return __awaiter(this, void 0, void 0, function () {
116
- var mensagem;
117
- var _this = this;
118
- return __generator(this, function (_a) {
119
- mensagem = expressao.argumentos && expressao.argumentos[0] ? expressao.argumentos[0].valor : '';
120
- return [2 /*return*/, new Promise(function (resolucao) {
121
- return _this.interfaceEntradaSaida.question(mensagem, function (resposta) {
122
- resolucao(resposta);
123
- });
124
- })];
125
- });
126
- });
127
- };
76
+ async visitarExpressaoLeia(expressao) {
77
+ const mensagem = expressao.argumentos && expressao.argumentos[0] ? expressao.argumentos[0].valor : '';
78
+ return new Promise(resolucao => this.interfaceEntradaSaida.question(mensagem, (resposta) => {
79
+ resolucao(resposta);
80
+ }));
81
+ }
128
82
  /**
129
83
  * Retira a interpolação de um texto.
130
84
  * @param {texto} texto O texto
131
85
  * @param {any[]} variaveis A lista de variaveis interpoladas
132
86
  * @returns O texto com o valor das variaveis.
133
87
  */
134
- Interpretador.prototype.retirarInterpolacao = function (texto, variaveis) {
135
- var _this = this;
136
- var valoresVariaveis = variaveis.map(function (v) { return ({
137
- valorResolvido: _this.pilhaEscoposExecucao.obterVariavelPorNome(v.variavel),
88
+ retirarInterpolacao(texto, variaveis) {
89
+ const valoresVariaveis = variaveis.map((v) => ({
90
+ valorResolvido: this.pilhaEscoposExecucao.obterVariavelPorNome(v.variavel),
138
91
  variavel: v.variavel,
139
- }); });
140
- var textoFinal = texto;
141
- valoresVariaveis.forEach(function (elemento) {
142
- var valorFinal = elemento.valorResolvido.hasOwnProperty('valor')
92
+ }));
93
+ let textoFinal = texto;
94
+ valoresVariaveis.forEach((elemento) => {
95
+ const valorFinal = elemento.valorResolvido.hasOwnProperty('valor')
143
96
  ? elemento.valorResolvido.valor
144
97
  : elemento.valorResolvido;
145
98
  textoFinal = textoFinal.replace('${' + elemento.variavel + '}', valorFinal);
146
99
  });
147
100
  return textoFinal;
148
- };
101
+ }
149
102
  /**
150
103
  * Busca variáveis interpoladas.
151
104
  * @param {texto} textoOriginal O texto original com as variáveis interpoladas.
152
105
  * @returns Uma lista de variáveis interpoladas.
153
106
  */
154
- Interpretador.prototype.buscarVariaveisInterpolacao = function (textoOriginal) {
155
- var _this = this;
156
- var variaveis = textoOriginal.match(this.regexInterpolacao);
157
- return variaveis.map(function (s) {
158
- var nomeVariavel = s.replace(/[\$\{\}]*/g, '');
107
+ buscarVariaveisInterpolacao(textoOriginal) {
108
+ const variaveis = textoOriginal.match(this.regexInterpolacao);
109
+ return variaveis.map((s) => {
110
+ const nomeVariavel = s.replace(/[\$\{\}]*/g, '');
159
111
  return {
160
112
  variavel: nomeVariavel,
161
- valor: _this.pilhaEscoposExecucao.obterVariavelPorNome(nomeVariavel),
113
+ valor: this.pilhaEscoposExecucao.obterVariavelPorNome(nomeVariavel),
162
114
  };
163
115
  });
164
- };
165
- Interpretador.prototype.visitarExpressaoLiteral = function (expressao) {
116
+ }
117
+ visitarExpressaoLiteral(expressao) {
166
118
  if (this.regexInterpolacao.test(expressao.valor)) {
167
- var variaveis = this.buscarVariaveisInterpolacao(expressao.valor);
119
+ const variaveis = this.buscarVariaveisInterpolacao(expressao.valor);
168
120
  return this.retirarInterpolacao(expressao.valor, variaveis);
169
121
  }
170
122
  return expressao.valor;
171
- };
172
- Interpretador.prototype.avaliar = function (expressao) {
173
- return __awaiter(this, void 0, void 0, function () {
174
- return __generator(this, function (_a) {
175
- switch (_a.label) {
176
- case 0: return [4 /*yield*/, expressao.aceitar(this)];
177
- case 1:
178
- // Descomente o código abaixo quando precisar detectar expressões undefined ou nulas.
179
- // Por algum motivo o depurador do VSCode não funciona direito aqui
180
- // com breakpoint condicional.
181
- /* if (expressao === null || expressao === undefined) {
182
- console.log('Aqui');
183
- } */
184
- return [2 /*return*/, _a.sent()];
185
- }
186
- });
187
- });
188
- };
189
- Interpretador.prototype.visitarExpressaoAgrupamento = function (expressao) {
190
- return __awaiter(this, void 0, void 0, function () {
191
- return __generator(this, function (_a) {
192
- switch (_a.label) {
193
- case 0: return [4 /*yield*/, this.avaliar(expressao.expressao)];
194
- case 1: return [2 /*return*/, _a.sent()];
195
- }
196
- });
197
- });
198
- };
199
- Interpretador.prototype.eVerdadeiro = function (objeto) {
123
+ }
124
+ async avaliar(expressao) {
125
+ // Descomente o código abaixo quando precisar detectar expressões undefined ou nulas.
126
+ // Por algum motivo o depurador do VSCode não funciona direito aqui
127
+ // com breakpoint condicional.
128
+ /* if (expressao === null || expressao === undefined) {
129
+ console.log('Aqui');
130
+ } */
131
+ return await expressao.aceitar(this);
132
+ }
133
+ async visitarExpressaoAgrupamento(expressao) {
134
+ return await this.avaliar(expressao.expressao);
135
+ }
136
+ eVerdadeiro(objeto) {
200
137
  if (objeto === null)
201
138
  return false;
202
139
  if (typeof objeto === 'boolean')
203
140
  return Boolean(objeto);
204
141
  return true;
205
- };
206
- Interpretador.prototype.verificarOperandoNumero = function (operador, operando) {
142
+ }
143
+ verificarOperandoNumero(operador, operando) {
207
144
  if (typeof operando === 'number' || operando.tipo === 'número')
208
145
  return;
209
146
  throw new excecoes_1.ErroEmTempoDeExecucao(operador, 'Operando precisa ser um número.', Number(operador.linha));
210
- };
211
- Interpretador.prototype.visitarExpressaoUnaria = function (expressao) {
212
- return __awaiter(this, void 0, void 0, function () {
213
- var direita, valor;
214
- return __generator(this, function (_a) {
215
- switch (_a.label) {
216
- case 0: return [4 /*yield*/, this.avaliar(expressao.direita)];
217
- case 1:
218
- direita = _a.sent();
219
- valor = direita.hasOwnProperty('valor') ?
220
- direita.valor :
221
- direita;
222
- switch (expressao.operador.tipo) {
223
- case delegua_1.default.SUBTRACAO:
224
- this.verificarOperandoNumero(expressao.operador, valor);
225
- return [2 /*return*/, -valor];
226
- case delegua_1.default.NEGACAO:
227
- return [2 /*return*/, !this.eVerdadeiro(valor)];
228
- case delegua_1.default.BIT_NOT:
229
- return [2 /*return*/, ~valor];
230
- }
231
- return [2 /*return*/, null];
232
- }
233
- });
234
- });
235
- };
236
- Interpretador.prototype.eIgual = function (esquerda, direita) {
147
+ }
148
+ async visitarExpressaoUnaria(expressao) {
149
+ const direita = await this.avaliar(expressao.direita);
150
+ const valor = direita.hasOwnProperty('valor') ?
151
+ direita.valor :
152
+ direita;
153
+ switch (expressao.operador.tipo) {
154
+ case delegua_1.default.SUBTRACAO:
155
+ this.verificarOperandoNumero(expressao.operador, valor);
156
+ return -valor;
157
+ case delegua_1.default.NEGACAO:
158
+ return !this.eVerdadeiro(valor);
159
+ case delegua_1.default.BIT_NOT:
160
+ return ~valor;
161
+ }
162
+ return null;
163
+ }
164
+ eIgual(esquerda, direita) {
237
165
  if (esquerda === null && direita === null)
238
166
  return true;
239
167
  if (esquerda === null)
@@ -248,7 +176,7 @@ var Interpretador = /** @class */ (function () {
248
176
  return esquerda.valor === direita.valor;
249
177
  }
250
178
  return esquerda === direita;
251
- };
179
+ }
252
180
  /**
253
181
  * Verifica se operandos são números, que podem ser tanto variáveis puras do JavaScript
254
182
  * (neste caso, `number`), ou podem ser variáveis de Delégua com inferência (`VariavelInterface`).
@@ -257,13 +185,13 @@ var Interpretador = /** @class */ (function () {
257
185
  * @param esquerda O operando esquerdo.
258
186
  * @returns Se ambos os operandos são números ou não.
259
187
  */
260
- Interpretador.prototype.verificarOperandosNumeros = function (operador, direita, esquerda) {
261
- var tipoDireita = direita.tipo
188
+ verificarOperandosNumeros(operador, direita, esquerda) {
189
+ const tipoDireita = direita.tipo
262
190
  ? direita.tipo
263
191
  : typeof direita === 'number'
264
192
  ? 'número'
265
193
  : String(NaN);
266
- var tipoEsquerda = esquerda.tipo
194
+ const tipoEsquerda = esquerda.tipo
267
195
  ? esquerda.tipo
268
196
  : typeof esquerda === 'number'
269
197
  ? 'número'
@@ -271,609 +199,376 @@ var Interpretador = /** @class */ (function () {
271
199
  if (tipoDireita === 'número' && tipoEsquerda === 'número')
272
200
  return;
273
201
  throw new excecoes_1.ErroEmTempoDeExecucao(operador, 'Operadores precisam ser números.', operador.linha);
274
- };
275
- Interpretador.prototype.visitarExpressaoBinaria = function (expressao) {
276
- return __awaiter(this, void 0, void 0, function () {
277
- var esquerda, direita, valorEsquerdo, valorDireito, tipoEsquerdo, tipoDireito, erro_1;
278
- return __generator(this, function (_a) {
279
- switch (_a.label) {
280
- case 0:
281
- _a.trys.push([0, 3, , 4]);
282
- return [4 /*yield*/, this.avaliar(expressao.esquerda)];
283
- case 1:
284
- esquerda = _a.sent();
285
- return [4 /*yield*/, this.avaliar(expressao.direita)];
286
- case 2:
287
- direita = _a.sent();
288
- valorEsquerdo = (esquerda === null || esquerda === void 0 ? void 0 : esquerda.hasOwnProperty('valor'))
289
- ? esquerda.valor
290
- : esquerda;
291
- valorDireito = (direita === null || direita === void 0 ? void 0 : direita.hasOwnProperty('valor'))
292
- ? direita.valor
293
- : direita;
294
- tipoEsquerdo = (esquerda === null || esquerda === void 0 ? void 0 : esquerda.hasOwnProperty('tipo'))
295
- ? esquerda.tipo
296
- : (0, inferenciador_1.inferirTipoVariavel)(esquerda);
297
- tipoDireito = (direita === null || direita === void 0 ? void 0 : direita.hasOwnProperty('tipo'))
298
- ? direita.tipo
299
- : (0, inferenciador_1.inferirTipoVariavel)(direita);
300
- switch (expressao.operador.tipo) {
301
- case delegua_1.default.EXPONENCIACAO:
302
- this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
303
- return [2 /*return*/, Math.pow(valorEsquerdo, valorDireito)];
304
- case delegua_1.default.MAIOR:
305
- this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
306
- return [2 /*return*/, Number(valorEsquerdo) > Number(valorDireito)];
307
- case delegua_1.default.MAIOR_IGUAL:
308
- this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
309
- return [2 /*return*/, Number(valorEsquerdo) >= Number(valorDireito)];
310
- case delegua_1.default.MENOR:
311
- this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
312
- return [2 /*return*/, Number(valorEsquerdo) < Number(valorDireito)];
313
- case delegua_1.default.MENOR_IGUAL:
314
- this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
315
- return [2 /*return*/, Number(valorEsquerdo) <= Number(valorDireito)];
316
- case delegua_1.default.SUBTRACAO:
317
- case delegua_1.default.MENOS_IGUAL:
318
- this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
319
- return [2 /*return*/, Number(valorEsquerdo) - Number(valorDireito)];
320
- case delegua_1.default.ADICAO:
321
- case delegua_1.default.MAIS_IGUAL:
322
- if (tipoEsquerdo === 'número' && tipoDireito === 'número') {
323
- return [2 /*return*/, Number(valorEsquerdo) + Number(valorDireito)];
324
- }
325
- else {
326
- return [2 /*return*/, String(valorEsquerdo) + String(valorDireito)];
327
- }
328
- case delegua_1.default.DIVISAO:
329
- case delegua_1.default.DIVISAO_IGUAL:
330
- this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
331
- return [2 /*return*/, Number(valorEsquerdo) / Number(valorDireito)];
332
- case delegua_1.default.MULTIPLICACAO:
333
- case delegua_1.default.MULTIPLICACAO_IGUAL:
334
- this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
335
- return [2 /*return*/, Number(valorEsquerdo) * Number(valorDireito)];
336
- case delegua_1.default.MODULO:
337
- case delegua_1.default.MODULO_IGUAL:
338
- this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
339
- return [2 /*return*/, Number(valorEsquerdo) % Number(valorDireito)];
340
- case delegua_1.default.BIT_AND:
341
- this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
342
- return [2 /*return*/, Number(valorEsquerdo) & Number(valorDireito)];
343
- case delegua_1.default.BIT_XOR:
344
- this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
345
- return [2 /*return*/, Number(valorEsquerdo) ^ Number(valorDireito)];
346
- case delegua_1.default.BIT_OR:
347
- this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
348
- return [2 /*return*/, Number(valorEsquerdo) | Number(valorDireito)];
349
- case delegua_1.default.MENOR_MENOR:
350
- this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
351
- return [2 /*return*/, Number(valorEsquerdo) << Number(valorDireito)];
352
- case delegua_1.default.MAIOR_MAIOR:
353
- this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
354
- return [2 /*return*/, Number(valorEsquerdo) >> Number(valorDireito)];
355
- case delegua_1.default.DIFERENTE:
356
- return [2 /*return*/, !this.eIgual(valorEsquerdo, valorDireito)];
357
- case delegua_1.default.IGUAL_IGUAL:
358
- return [2 /*return*/, this.eIgual(valorEsquerdo, valorDireito)];
359
- }
360
- return [3 /*break*/, 4];
361
- case 3:
362
- erro_1 = _a.sent();
363
- return [2 /*return*/, Promise.reject(erro_1)];
364
- case 4: return [2 /*return*/];
365
- }
366
- });
367
- });
368
- };
202
+ }
203
+ async visitarExpressaoBinaria(expressao) {
204
+ try {
205
+ const esquerda = await this.avaliar(expressao.esquerda);
206
+ const direita = await this.avaliar(expressao.direita);
207
+ const valorEsquerdo = (esquerda === null || esquerda === void 0 ? void 0 : esquerda.hasOwnProperty('valor'))
208
+ ? esquerda.valor
209
+ : esquerda;
210
+ const valorDireito = (direita === null || direita === void 0 ? void 0 : direita.hasOwnProperty('valor'))
211
+ ? direita.valor
212
+ : direita;
213
+ const tipoEsquerdo = (esquerda === null || esquerda === void 0 ? void 0 : esquerda.hasOwnProperty('tipo'))
214
+ ? esquerda.tipo
215
+ : (0, inferenciador_1.inferirTipoVariavel)(esquerda);
216
+ const tipoDireito = (direita === null || direita === void 0 ? void 0 : direita.hasOwnProperty('tipo'))
217
+ ? direita.tipo
218
+ : (0, inferenciador_1.inferirTipoVariavel)(direita);
219
+ switch (expressao.operador.tipo) {
220
+ case delegua_1.default.EXPONENCIACAO:
221
+ this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
222
+ return Math.pow(valorEsquerdo, valorDireito);
223
+ case delegua_1.default.MAIOR:
224
+ this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
225
+ return Number(valorEsquerdo) > Number(valorDireito);
226
+ case delegua_1.default.MAIOR_IGUAL:
227
+ this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
228
+ return Number(valorEsquerdo) >= Number(valorDireito);
229
+ case delegua_1.default.MENOR:
230
+ this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
231
+ return Number(valorEsquerdo) < Number(valorDireito);
232
+ case delegua_1.default.MENOR_IGUAL:
233
+ this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
234
+ return Number(valorEsquerdo) <= Number(valorDireito);
235
+ case delegua_1.default.SUBTRACAO:
236
+ case delegua_1.default.MENOS_IGUAL:
237
+ this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
238
+ return Number(valorEsquerdo) - Number(valorDireito);
239
+ case delegua_1.default.ADICAO:
240
+ case delegua_1.default.MAIS_IGUAL:
241
+ if (tipoEsquerdo === 'número' && tipoDireito === 'número') {
242
+ return Number(valorEsquerdo) + Number(valorDireito);
243
+ }
244
+ else {
245
+ return String(valorEsquerdo) + String(valorDireito);
246
+ }
247
+ case delegua_1.default.DIVISAO:
248
+ case delegua_1.default.DIVISAO_IGUAL:
249
+ this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
250
+ return Number(valorEsquerdo) / Number(valorDireito);
251
+ case delegua_1.default.MULTIPLICACAO:
252
+ case delegua_1.default.MULTIPLICACAO_IGUAL:
253
+ this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
254
+ return Number(valorEsquerdo) * Number(valorDireito);
255
+ case delegua_1.default.MODULO:
256
+ case delegua_1.default.MODULO_IGUAL:
257
+ this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
258
+ return Number(valorEsquerdo) % Number(valorDireito);
259
+ case delegua_1.default.BIT_AND:
260
+ this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
261
+ return Number(valorEsquerdo) & Number(valorDireito);
262
+ case delegua_1.default.BIT_XOR:
263
+ this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
264
+ return Number(valorEsquerdo) ^ Number(valorDireito);
265
+ case delegua_1.default.BIT_OR:
266
+ this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
267
+ return Number(valorEsquerdo) | Number(valorDireito);
268
+ case delegua_1.default.MENOR_MENOR:
269
+ this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
270
+ return Number(valorEsquerdo) << Number(valorDireito);
271
+ case delegua_1.default.MAIOR_MAIOR:
272
+ this.verificarOperandosNumeros(expressao.operador, esquerda, direita);
273
+ return Number(valorEsquerdo) >> Number(valorDireito);
274
+ case delegua_1.default.DIFERENTE:
275
+ return !this.eIgual(valorEsquerdo, valorDireito);
276
+ case delegua_1.default.IGUAL_IGUAL:
277
+ return this.eIgual(valorEsquerdo, valorDireito);
278
+ }
279
+ }
280
+ catch (erro) {
281
+ return Promise.reject(erro);
282
+ }
283
+ }
369
284
  /**
370
285
  * Executa uma chamada de função, método ou classe.
371
286
  * @param expressao A expressão chamada.
372
287
  * @returns O resultado da chamada.
373
288
  */
374
- Interpretador.prototype.visitarExpressaoDeChamada = function (expressao) {
375
- return __awaiter(this, void 0, void 0, function () {
376
- var variavelEntidadeChamada, entidadeChamada, argumentos, i, _a, _b, argumentosResolvidos, _i, _c, argumento, valorResolvido, parametros, diferenca, i, novosArgumentos, erro_2;
377
- return __generator(this, function (_d) {
378
- switch (_d.label) {
379
- case 0:
380
- _d.trys.push([0, 11, , 12]);
381
- return [4 /*yield*/, this.avaliar(expressao.entidadeChamada)];
382
- case 1:
383
- variavelEntidadeChamada = _d.sent();
384
- entidadeChamada = variavelEntidadeChamada.hasOwnProperty('valor')
385
- ? variavelEntidadeChamada.valor
386
- : variavelEntidadeChamada;
387
- argumentos = [];
388
- i = 0;
389
- _d.label = 2;
390
- case 2:
391
- if (!(i < expressao.argumentos.length)) return [3 /*break*/, 5];
392
- _b = (_a = argumentos).push;
393
- return [4 /*yield*/, this.avaliar(expressao.argumentos[i])];
394
- case 3:
395
- _b.apply(_a, [_d.sent()]);
396
- _d.label = 4;
397
- case 4:
398
- i++;
399
- return [3 /*break*/, 2];
400
- case 5:
401
- if (!(entidadeChamada instanceof estruturas_1.Chamavel)) {
402
- return [2 /*return*/, Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.parentese, 'Só pode chamar função ou classe.', expressao.linha))];
403
- }
404
- if (!(entidadeChamada instanceof metodo_primitiva_1.MetodoPrimitiva)) return [3 /*break*/, 10];
405
- argumentosResolvidos = [];
406
- _i = 0, _c = expressao.argumentos;
407
- _d.label = 6;
408
- case 6:
409
- if (!(_i < _c.length)) return [3 /*break*/, 9];
410
- argumento = _c[_i];
411
- return [4 /*yield*/, this.avaliar(argumento)];
412
- case 7:
413
- valorResolvido = _d.sent();
414
- argumentosResolvidos.push(valorResolvido.hasOwnProperty('valor')
415
- ? valorResolvido.valor
416
- : valorResolvido);
417
- _d.label = 8;
418
- case 8:
419
- _i++;
420
- return [3 /*break*/, 6];
421
- case 9: return [2 /*return*/, entidadeChamada.chamar(argumentosResolvidos)];
422
- case 10:
423
- parametros = void 0;
424
- if (entidadeChamada instanceof estruturas_1.DeleguaFuncao) {
425
- parametros = entidadeChamada.declaracao.parametros;
426
- }
427
- else if (entidadeChamada instanceof estruturas_1.DeleguaClasse) {
428
- parametros = entidadeChamada.metodos.inicializacao
429
- ? entidadeChamada.metodos.inicializacao.declaracao.parametros
430
- : [];
431
- }
432
- else {
433
- parametros = [];
434
- }
435
- // Completar os parâmetros não preenchidos com nulos.
436
- if (argumentos.length < entidadeChamada.aridade()) {
437
- diferenca = entidadeChamada.aridade() - argumentos.length;
438
- for (i = 0; i < diferenca; i++) {
439
- argumentos.push(null);
440
- }
441
- }
442
- else {
443
- if (parametros &&
444
- parametros.length > 0 &&
445
- parametros[parametros.length - 1].tipo === 'estrela') {
446
- novosArgumentos = argumentos.slice(0, parametros.length - 1);
447
- novosArgumentos.push(argumentos.slice(parametros.length - 1, argumentos.length));
448
- argumentos = novosArgumentos;
449
- }
450
- }
451
- if (entidadeChamada instanceof estruturas_1.FuncaoPadrao) {
452
- try {
453
- return [2 /*return*/, entidadeChamada.chamar(argumentos, expressao.entidadeChamada.nome)];
454
- }
455
- catch (erro) {
456
- this.erros.push(erro);
457
- }
458
- }
459
- return [2 /*return*/, entidadeChamada.chamar(this, argumentos)];
460
- case 11:
461
- erro_2 = _d.sent();
462
- console.log(erro_2);
463
- return [3 /*break*/, 12];
464
- case 12: return [2 /*return*/];
289
+ async visitarExpressaoDeChamada(expressao) {
290
+ try {
291
+ const variavelEntidadeChamada = await this.avaliar(expressao.entidadeChamada);
292
+ const entidadeChamada = variavelEntidadeChamada.hasOwnProperty('valor')
293
+ ? variavelEntidadeChamada.valor
294
+ : variavelEntidadeChamada;
295
+ let argumentos = [];
296
+ for (let i = 0; i < expressao.argumentos.length; i++) {
297
+ argumentos.push(await this.avaliar(expressao.argumentos[i]));
298
+ }
299
+ if (!(entidadeChamada instanceof estruturas_1.Chamavel)) {
300
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.parentese, 'Só pode chamar função ou classe.', expressao.linha));
301
+ }
302
+ if (entidadeChamada instanceof metodo_primitiva_1.MetodoPrimitiva) {
303
+ const argumentosResolvidos = [];
304
+ for (const argumento of expressao.argumentos) {
305
+ const valorResolvido = await this.avaliar(argumento);
306
+ argumentosResolvidos.push(valorResolvido.hasOwnProperty('valor')
307
+ ? valorResolvido.valor
308
+ : valorResolvido);
465
309
  }
466
- });
467
- });
468
- };
310
+ return entidadeChamada.chamar(argumentosResolvidos);
311
+ }
312
+ let parametros;
313
+ if (entidadeChamada instanceof estruturas_1.DeleguaFuncao) {
314
+ parametros = entidadeChamada.declaracao.parametros;
315
+ }
316
+ else if (entidadeChamada instanceof estruturas_1.DeleguaClasse) {
317
+ parametros = entidadeChamada.metodos.inicializacao
318
+ ? entidadeChamada.metodos.inicializacao.declaracao.parametros
319
+ : [];
320
+ }
321
+ else {
322
+ parametros = [];
323
+ }
324
+ // Completar os parâmetros não preenchidos com nulos.
325
+ if (argumentos.length < entidadeChamada.aridade()) {
326
+ const diferenca = entidadeChamada.aridade() - argumentos.length;
327
+ for (let i = 0; i < diferenca; i++) {
328
+ argumentos.push(null);
329
+ }
330
+ }
331
+ else {
332
+ if (parametros &&
333
+ parametros.length > 0 &&
334
+ parametros[parametros.length - 1].tipo === 'estrela') {
335
+ const novosArgumentos = argumentos.slice(0, parametros.length - 1);
336
+ novosArgumentos.push(argumentos.slice(parametros.length - 1, argumentos.length));
337
+ argumentos = novosArgumentos;
338
+ }
339
+ }
340
+ if (entidadeChamada instanceof estruturas_1.FuncaoPadrao) {
341
+ try {
342
+ return entidadeChamada.chamar(argumentos, expressao.entidadeChamada.nome);
343
+ }
344
+ catch (erro) {
345
+ this.erros.push(erro);
346
+ }
347
+ }
348
+ return entidadeChamada.chamar(this, argumentos);
349
+ }
350
+ catch (erro) {
351
+ console.log(erro);
352
+ }
353
+ }
469
354
  /**
470
355
  * Execução de uma expressão de atribuição.
471
356
  * @param expressao A expressão.
472
357
  * @returns O valor atribuído.
473
358
  */
474
- Interpretador.prototype.visitarExpressaoDeAtribuicao = function (expressao) {
475
- return __awaiter(this, void 0, void 0, function () {
476
- var valor;
477
- return __generator(this, function (_a) {
478
- switch (_a.label) {
479
- case 0: return [4 /*yield*/, this.avaliar(expressao.valor)];
480
- case 1:
481
- valor = _a.sent();
482
- this.pilhaEscoposExecucao.atribuirVariavel(expressao.simbolo, valor);
483
- return [2 /*return*/, valor];
484
- }
485
- });
486
- });
487
- };
488
- Interpretador.prototype.procurarVariavel = function (simbolo) {
359
+ async visitarExpressaoDeAtribuicao(expressao) {
360
+ const valor = await this.avaliar(expressao.valor);
361
+ this.pilhaEscoposExecucao.atribuirVariavel(expressao.simbolo, valor);
362
+ return valor;
363
+ }
364
+ procurarVariavel(simbolo) {
489
365
  return this.pilhaEscoposExecucao.obterVariavel(simbolo);
490
- };
491
- Interpretador.prototype.visitarExpressaoDeVariavel = function (expressao) {
366
+ }
367
+ visitarExpressaoDeVariavel(expressao) {
492
368
  return this.procurarVariavel(expressao.simbolo);
493
- };
494
- Interpretador.prototype.visitarDeclaracaoDeExpressao = function (declaracao) {
495
- return __awaiter(this, void 0, void 0, function () {
496
- return __generator(this, function (_a) {
497
- switch (_a.label) {
498
- case 0: return [4 /*yield*/, this.avaliar(declaracao.expressao)];
499
- case 1: return [2 /*return*/, _a.sent()];
500
- }
501
- });
502
- });
503
- };
504
- Interpretador.prototype.visitarExpressaoLogica = function (expressao) {
505
- return __awaiter(this, void 0, void 0, function () {
506
- var esquerda, direita;
507
- return __generator(this, function (_a) {
508
- switch (_a.label) {
509
- case 0: return [4 /*yield*/, this.avaliar(expressao.esquerda)];
510
- case 1:
511
- esquerda = _a.sent();
512
- if (!(expressao.operador.tipo === delegua_1.default.EM)) return [3 /*break*/, 3];
513
- return [4 /*yield*/, this.avaliar(expressao.direita)];
514
- case 2:
515
- direita = _a.sent();
516
- if (Array.isArray(direita) || typeof direita === 'string') {
517
- return [2 /*return*/, direita.includes(esquerda)];
518
- }
519
- else if (direita.constructor === Object) {
520
- return [2 /*return*/, esquerda in direita];
521
- }
522
- else {
523
- throw new excecoes_1.ErroEmTempoDeExecucao(esquerda, "Tipo de chamada inválida com 'em'.", expressao.linha);
524
- }
525
- _a.label = 3;
526
- case 3:
527
- // se um estado for verdadeiro, retorna verdadeiro
528
- if (expressao.operador.tipo === delegua_1.default.OU) {
529
- if (this.eVerdadeiro(esquerda))
530
- return [2 /*return*/, esquerda];
531
- }
532
- // se um estado for falso, retorna falso
533
- if (expressao.operador.tipo === delegua_1.default.E) {
534
- if (!this.eVerdadeiro(esquerda))
535
- return [2 /*return*/, esquerda];
536
- }
537
- return [4 /*yield*/, this.avaliar(expressao.direita)];
538
- case 4: return [2 /*return*/, _a.sent()];
539
- }
540
- });
541
- });
542
- };
369
+ }
370
+ async visitarDeclaracaoDeExpressao(declaracao) {
371
+ return await this.avaliar(declaracao.expressao);
372
+ }
373
+ async visitarExpressaoLogica(expressao) {
374
+ const esquerda = await this.avaliar(expressao.esquerda);
375
+ if (expressao.operador.tipo === delegua_1.default.EM) {
376
+ const direita = await this.avaliar(expressao.direita);
377
+ if (Array.isArray(direita) || typeof direita === 'string') {
378
+ return direita.includes(esquerda);
379
+ }
380
+ else if (direita.constructor === Object) {
381
+ return esquerda in direita;
382
+ }
383
+ else {
384
+ throw new excecoes_1.ErroEmTempoDeExecucao(esquerda, "Tipo de chamada inválida com 'em'.", expressao.linha);
385
+ }
386
+ }
387
+ // se um estado for verdadeiro, retorna verdadeiro
388
+ if (expressao.operador.tipo === delegua_1.default.OU) {
389
+ if (this.eVerdadeiro(esquerda))
390
+ return esquerda;
391
+ }
392
+ // se um estado for falso, retorna falso
393
+ if (expressao.operador.tipo === delegua_1.default.E) {
394
+ if (!this.eVerdadeiro(esquerda))
395
+ return esquerda;
396
+ }
397
+ return await this.avaliar(expressao.direita);
398
+ }
543
399
  /**
544
400
  * Executa uma expressão Se, que tem uma condição, pode ter um bloco
545
401
  * Senão, e múltiplos blocos Senão-se.
546
402
  * @param declaracao A declaração Se.
547
403
  * @returns O resultado da avaliação do bloco cuja condição é verdadeira.
548
404
  */
549
- Interpretador.prototype.visitarExpressaoSe = function (declaracao) {
550
- return __awaiter(this, void 0, void 0, function () {
551
- var _a, i, atual, _b;
552
- return __generator(this, function (_c) {
553
- switch (_c.label) {
554
- case 0:
555
- _a = this.eVerdadeiro;
556
- return [4 /*yield*/, this.avaliar(declaracao.condicao)];
557
- case 1:
558
- if (!_a.apply(this, [_c.sent()])) return [3 /*break*/, 3];
559
- return [4 /*yield*/, this.executar(declaracao.caminhoEntao)];
560
- case 2: return [2 /*return*/, _c.sent()];
561
- case 3:
562
- i = 0;
563
- _c.label = 4;
564
- case 4:
565
- if (!(i < declaracao.caminhosSeSenao.length)) return [3 /*break*/, 8];
566
- atual = declaracao.caminhosSeSenao[i];
567
- _b = this.eVerdadeiro;
568
- return [4 /*yield*/, this.avaliar(atual.condicao)];
569
- case 5:
570
- if (!_b.apply(this, [_c.sent()])) return [3 /*break*/, 7];
571
- return [4 /*yield*/, this.executar(atual.caminho)];
572
- case 6: return [2 /*return*/, _c.sent()];
573
- case 7:
574
- i++;
575
- return [3 /*break*/, 4];
576
- case 8:
577
- if (!(declaracao.caminhoSenao !== null)) return [3 /*break*/, 10];
578
- return [4 /*yield*/, this.executar(declaracao.caminhoSenao)];
579
- case 9: return [2 /*return*/, _c.sent()];
580
- case 10: return [2 /*return*/, null];
581
- }
582
- });
583
- });
584
- };
585
- Interpretador.prototype.visitarExpressaoPara = function (declaracao) {
586
- return __awaiter(this, void 0, void 0, function () {
587
- var retornoExecucao, _a, _b, erro_3;
588
- return __generator(this, function (_c) {
589
- switch (_c.label) {
590
- case 0:
591
- if (!(declaracao.inicializador !== null)) return [3 /*break*/, 2];
592
- return [4 /*yield*/, this.avaliar(declaracao.inicializador)];
593
- case 1:
594
- _c.sent();
595
- _c.label = 2;
596
- case 2:
597
- if (!!(retornoExecucao instanceof quebras_1.Quebra)) return [3 /*break*/, 11];
598
- _a = declaracao.condicao !== null;
599
- if (!_a) return [3 /*break*/, 4];
600
- _b = this.eVerdadeiro;
601
- return [4 /*yield*/, this.avaliar(declaracao.condicao)];
602
- case 3:
603
- _a = !_b.apply(this, [_c.sent()]);
604
- _c.label = 4;
605
- case 4:
606
- if (_a) {
607
- return [3 /*break*/, 11];
608
- }
609
- _c.label = 5;
610
- case 5:
611
- _c.trys.push([5, 7, , 8]);
612
- return [4 /*yield*/, this.executar(declaracao.corpo)];
613
- case 6:
614
- retornoExecucao = _c.sent();
615
- return [3 /*break*/, 8];
616
- case 7:
617
- erro_3 = _c.sent();
618
- return [2 /*return*/, Promise.reject(erro_3)];
619
- case 8:
620
- if (!(declaracao.incrementar !== null)) return [3 /*break*/, 10];
621
- return [4 /*yield*/, this.avaliar(declaracao.incrementar)];
622
- case 9:
623
- _c.sent();
624
- _c.label = 10;
625
- case 10: return [3 /*break*/, 2];
626
- case 11: return [2 /*return*/, null];
627
- }
628
- });
629
- });
630
- };
631
- Interpretador.prototype.visitarExpressaoFazer = function (declaracao) {
632
- return __awaiter(this, void 0, void 0, function () {
633
- var retornoExecucao, erro_4, _a, _b;
634
- return __generator(this, function (_c) {
635
- switch (_c.label) {
636
- case 0:
637
- _c.trys.push([0, 2, , 3]);
638
- return [4 /*yield*/, this.executar(declaracao.caminhoFazer)];
639
- case 1:
640
- retornoExecucao = _c.sent();
641
- return [3 /*break*/, 3];
642
- case 2:
643
- erro_4 = _c.sent();
644
- return [2 /*return*/, Promise.reject(erro_4)];
645
- case 3:
646
- _a = !(retornoExecucao instanceof quebras_1.Quebra);
647
- if (!_a) return [3 /*break*/, 5];
648
- _b = this.eVerdadeiro;
649
- return [4 /*yield*/, this.avaliar(declaracao.condicaoEnquanto)];
650
- case 4:
651
- _a = _b.apply(this, [_c.sent()]);
652
- _c.label = 5;
653
- case 5:
654
- if (_a) return [3 /*break*/, 0];
655
- _c.label = 6;
656
- case 6: return [2 /*return*/];
657
- }
658
- });
659
- });
660
- };
661
- Interpretador.prototype.visitarExpressaoEscolha = function (declaracao) {
662
- return __awaiter(this, void 0, void 0, function () {
663
- var condicaoEscolha, caminhos, caminhoPadrao, encontrado, i, caminho_1, j, erro_5, erro_6;
664
- return __generator(this, function (_a) {
665
- switch (_a.label) {
666
- case 0: return [4 /*yield*/, this.avaliar(declaracao.identificadorOuLiteral)];
667
- case 1:
668
- condicaoEscolha = _a.sent();
669
- caminhos = declaracao.caminhos;
670
- caminhoPadrao = declaracao.caminhoPadrao;
671
- encontrado = false;
672
- _a.label = 2;
673
- case 2:
674
- _a.trys.push([2, 14, , 15]);
675
- i = 0;
676
- _a.label = 3;
677
- case 3:
678
- if (!(i < caminhos.length)) return [3 /*break*/, 11];
679
- caminho_1 = caminhos[i];
680
- j = 0;
681
- _a.label = 4;
682
- case 4:
683
- if (!(j < caminho_1.condicoes.length)) return [3 /*break*/, 10];
684
- return [4 /*yield*/, this.avaliar(caminho_1.condicoes[j])];
685
- case 5:
686
- if (!((_a.sent()) === condicaoEscolha)) return [3 /*break*/, 9];
405
+ async visitarExpressaoSe(declaracao) {
406
+ if (this.eVerdadeiro(await this.avaliar(declaracao.condicao))) {
407
+ return await this.executar(declaracao.caminhoEntao);
408
+ }
409
+ for (let i = 0; i < declaracao.caminhosSeSenao.length; i++) {
410
+ const atual = declaracao.caminhosSeSenao[i];
411
+ if (this.eVerdadeiro(await this.avaliar(atual.condicao))) {
412
+ return await this.executar(atual.caminho);
413
+ }
414
+ }
415
+ if (declaracao.caminhoSenao !== null) {
416
+ return await this.executar(declaracao.caminhoSenao);
417
+ }
418
+ return null;
419
+ }
420
+ async visitarExpressaoPara(declaracao) {
421
+ if (declaracao.inicializador !== null) {
422
+ await this.avaliar(declaracao.inicializador);
423
+ }
424
+ let retornoExecucao;
425
+ while (!(retornoExecucao instanceof quebras_1.Quebra)) {
426
+ if (declaracao.condicao !== null &&
427
+ !this.eVerdadeiro(await this.avaliar(declaracao.condicao))) {
428
+ break;
429
+ }
430
+ try {
431
+ retornoExecucao = await this.executar(declaracao.corpo);
432
+ }
433
+ catch (erro) {
434
+ return Promise.reject(erro);
435
+ }
436
+ if (declaracao.incrementar !== null) {
437
+ await this.avaliar(declaracao.incrementar);
438
+ }
439
+ }
440
+ return null;
441
+ }
442
+ async visitarExpressaoFazer(declaracao) {
443
+ let retornoExecucao;
444
+ do {
445
+ try {
446
+ retornoExecucao = await this.executar(declaracao.caminhoFazer);
447
+ }
448
+ catch (erro) {
449
+ return Promise.reject(erro);
450
+ }
451
+ } while (!(retornoExecucao instanceof quebras_1.Quebra) &&
452
+ this.eVerdadeiro(await this.avaliar(declaracao.condicaoEnquanto)));
453
+ }
454
+ async visitarExpressaoEscolha(declaracao) {
455
+ const condicaoEscolha = await this.avaliar(declaracao.identificadorOuLiteral);
456
+ const caminhos = declaracao.caminhos;
457
+ const caminhoPadrao = declaracao.caminhoPadrao;
458
+ let encontrado = false;
459
+ try {
460
+ for (let i = 0; i < caminhos.length; i++) {
461
+ const caminho = caminhos[i];
462
+ for (let j = 0; j < caminho.condicoes.length; j++) {
463
+ if (await this.avaliar(caminho.condicoes[j]) === condicaoEscolha) {
687
464
  encontrado = true;
688
- _a.label = 6;
689
- case 6:
690
- _a.trys.push([6, 8, , 9]);
691
- return [4 /*yield*/, this.executarBloco(caminho_1.declaracoes)];
692
- case 7:
693
- _a.sent();
694
- return [3 /*break*/, 9];
695
- case 8:
696
- erro_5 = _a.sent();
697
- return [2 /*return*/, Promise.reject(erro_5)];
698
- case 9:
699
- j++;
700
- return [3 /*break*/, 4];
701
- case 10:
702
- i++;
703
- return [3 /*break*/, 3];
704
- case 11:
705
- if (!(caminhoPadrao !== null && encontrado === false)) return [3 /*break*/, 13];
706
- return [4 /*yield*/, this.executarBloco(caminhoPadrao.declaracoes)];
707
- case 12:
708
- _a.sent();
709
- _a.label = 13;
710
- case 13: return [3 /*break*/, 15];
711
- case 14:
712
- erro_6 = _a.sent();
713
- throw erro_6;
714
- case 15: return [2 /*return*/];
715
- }
716
- });
717
- });
718
- };
719
- Interpretador.prototype.visitarExpressaoTente = function (declaracao) {
720
- return __awaiter(this, void 0, void 0, function () {
721
- var sucesso, erro_7;
722
- return __generator(this, function (_a) {
723
- switch (_a.label) {
724
- case 0:
725
- _a.trys.push([0, , 10, 13]);
726
- sucesso = true;
727
- _a.label = 1;
728
- case 1:
729
- _a.trys.push([1, 3, , 7]);
730
- return [4 /*yield*/, this.executarBloco(declaracao.caminhoTente)];
731
- case 2:
732
- _a.sent();
733
- return [3 /*break*/, 7];
734
- case 3:
735
- erro_7 = _a.sent();
736
- sucesso = false;
737
- if (!(declaracao.caminhoPegue !== null)) return [3 /*break*/, 5];
738
- return [4 /*yield*/, this.executarBloco(declaracao.caminhoPegue)];
739
- case 4:
740
- _a.sent();
741
- return [3 /*break*/, 6];
742
- case 5:
743
- this.erros.push(erro_7);
744
- _a.label = 6;
745
- case 6: return [3 /*break*/, 7];
746
- case 7:
747
- if (!(sucesso && declaracao.caminhoSenao !== null)) return [3 /*break*/, 9];
748
- return [4 /*yield*/, this.executarBloco(declaracao.caminhoSenao)];
749
- case 8:
750
- _a.sent();
751
- _a.label = 9;
752
- case 9: return [3 /*break*/, 13];
753
- case 10:
754
- if (!(declaracao.caminhoFinalmente !== null)) return [3 /*break*/, 12];
755
- return [4 /*yield*/, this.executarBloco(declaracao.caminhoFinalmente)];
756
- case 11:
757
- _a.sent();
758
- _a.label = 12;
759
- case 12: return [7 /*endfinally*/];
760
- case 13: return [2 /*return*/];
761
- }
762
- });
763
- });
764
- };
765
- Interpretador.prototype.visitarExpressaoEnquanto = function (declaracao) {
766
- return __awaiter(this, void 0, void 0, function () {
767
- var retornoExecucao, _a, _b, erro_8;
768
- return __generator(this, function (_c) {
769
- switch (_c.label) {
770
- case 0:
771
- _a = !(retornoExecucao instanceof quebras_1.Quebra);
772
- if (!_a) return [3 /*break*/, 2];
773
- _b = this.eVerdadeiro;
774
- return [4 /*yield*/, this.avaliar(declaracao.condicao)];
775
- case 1:
776
- _a = _b.apply(this, [_c.sent()]);
777
- _c.label = 2;
778
- case 2:
779
- if (!_a) return [3 /*break*/, 7];
780
- _c.label = 3;
781
- case 3:
782
- _c.trys.push([3, 5, , 6]);
783
- return [4 /*yield*/, this.executar(declaracao.corpo)];
784
- case 4:
785
- retornoExecucao = _c.sent();
786
- return [3 /*break*/, 6];
787
- case 5:
788
- erro_8 = _c.sent();
789
- throw erro_8;
790
- case 6: return [3 /*break*/, 0];
791
- case 7: return [2 /*return*/, null];
792
- }
793
- });
794
- });
795
- };
796
- Interpretador.prototype.visitarExpressaoImportar = function (declaracao) {
797
- return __awaiter(this, void 0, void 0, function () {
798
- var caminhoRelativo, caminhoTotal, nomeArquivo, conteudoImportacao, retornoInterpretador, funcoesChamaveis, eDicionario, novoModulo, chaves, i;
799
- return __generator(this, function (_a) {
800
- switch (_a.label) {
801
- case 0: return [4 /*yield*/, this.avaliar(declaracao.caminho)];
802
- case 1:
803
- caminhoRelativo = _a.sent();
804
- caminhoTotal = caminho.join(this.diretorioBase, caminhoRelativo);
805
- nomeArquivo = caminho.basename(caminhoTotal);
806
- if (!caminhoTotal.endsWith('.egua') &&
807
- !caminhoTotal.endsWith('.delegua')) {
808
- try {
809
- return [2 /*return*/, (0, importar_biblioteca_1.default)(caminhoRelativo)];
810
- }
811
- catch (erro) {
812
- this.erros.push(erro);
813
- return [2 /*return*/, null];
814
- }
465
+ try {
466
+ await this.executarBloco(caminho.declaracoes);
815
467
  }
816
- conteudoImportacao = this.importador.importar(caminhoRelativo);
817
- retornoInterpretador = this.interpretar(conteudoImportacao.retornoAvaliadorSintatico.declaracoes, true);
818
- funcoesChamaveis = this.pilhaEscoposExecucao.obterTodasDeleguaFuncao();
819
- eDicionario = function (objeto) { return objeto.constructor === Object; };
820
- if (eDicionario(funcoesChamaveis)) {
821
- novoModulo = new estruturas_1.DeleguaModulo();
822
- chaves = Object.keys(funcoesChamaveis);
823
- for (i = 0; i < chaves.length; i++) {
824
- novoModulo.componentes[chaves[i]] = funcoesChamaveis[chaves[i]];
825
- }
826
- return [2 /*return*/, novoModulo];
468
+ catch (erro) {
469
+ return Promise.reject(erro);
827
470
  }
828
- return [2 /*return*/, funcoesChamaveis];
471
+ }
829
472
  }
830
- });
831
- });
832
- };
473
+ }
474
+ if (caminhoPadrao !== null && encontrado === false) {
475
+ await this.executarBloco(caminhoPadrao.declaracoes);
476
+ }
477
+ }
478
+ catch (erro) {
479
+ throw erro;
480
+ }
481
+ }
482
+ async visitarExpressaoTente(declaracao) {
483
+ try {
484
+ let sucesso = true;
485
+ try {
486
+ await this.executarBloco(declaracao.caminhoTente);
487
+ }
488
+ catch (erro) {
489
+ sucesso = false;
490
+ if (declaracao.caminhoPegue !== null) {
491
+ await this.executarBloco(declaracao.caminhoPegue);
492
+ }
493
+ else {
494
+ this.erros.push(erro);
495
+ }
496
+ }
497
+ if (sucesso && declaracao.caminhoSenao !== null) {
498
+ await this.executarBloco(declaracao.caminhoSenao);
499
+ }
500
+ }
501
+ finally {
502
+ if (declaracao.caminhoFinalmente !== null)
503
+ await this.executarBloco(declaracao.caminhoFinalmente);
504
+ }
505
+ }
506
+ async visitarExpressaoEnquanto(declaracao) {
507
+ let retornoExecucao;
508
+ while (!(retornoExecucao instanceof quebras_1.Quebra) &&
509
+ this.eVerdadeiro(await this.avaliar(declaracao.condicao))) {
510
+ try {
511
+ retornoExecucao = await this.executar(declaracao.corpo);
512
+ }
513
+ catch (erro) {
514
+ throw erro;
515
+ }
516
+ }
517
+ return null;
518
+ }
519
+ async visitarExpressaoImportar(declaracao) {
520
+ const caminhoRelativo = await this.avaliar(declaracao.caminho);
521
+ const caminhoTotal = caminho.join(this.diretorioBase, caminhoRelativo);
522
+ const nomeArquivo = caminho.basename(caminhoTotal);
523
+ if (!caminhoTotal.endsWith('.egua') &&
524
+ !caminhoTotal.endsWith('.delegua')) {
525
+ try {
526
+ return (0, importar_biblioteca_1.default)(caminhoRelativo);
527
+ }
528
+ catch (erro) {
529
+ this.erros.push(erro);
530
+ return null;
531
+ }
532
+ }
533
+ const conteudoImportacao = this.importador.importar(caminhoRelativo);
534
+ const retornoInterpretador = this.interpretar(conteudoImportacao.retornoAvaliadorSintatico.declaracoes, true);
535
+ const funcoesChamaveis = this.pilhaEscoposExecucao.obterTodasDeleguaFuncao();
536
+ const eDicionario = (objeto) => objeto.constructor === Object;
537
+ if (eDicionario(funcoesChamaveis)) {
538
+ const novoModulo = new estruturas_1.DeleguaModulo();
539
+ const chaves = Object.keys(funcoesChamaveis);
540
+ for (let i = 0; i < chaves.length; i++) {
541
+ novoModulo.componentes[chaves[i]] = funcoesChamaveis[chaves[i]];
542
+ }
543
+ return novoModulo;
544
+ }
545
+ return funcoesChamaveis;
546
+ }
833
547
  /**
834
548
  * Execução de uma escrita na saída configurada, que pode ser `console` (padrão) ou
835
549
  * alguma função para escrever numa página Web.
836
550
  * @param declaracao A declaração.
837
551
  * @returns Sempre nulo, por convenção de visita.
838
552
  */
839
- Interpretador.prototype.visitarExpressaoEscreva = function (declaracao) {
840
- return __awaiter(this, void 0, void 0, function () {
841
- var valor, _i, _a, argumento, resultadoAvaliacao, formatoTexto, erro_9;
842
- return __generator(this, function (_b) {
843
- switch (_b.label) {
844
- case 0:
845
- _b.trys.push([0, 5, , 6]);
846
- valor = void 0;
847
- _i = 0, _a = declaracao.argumentos;
848
- _b.label = 1;
849
- case 1:
850
- if (!(_i < _a.length)) return [3 /*break*/, 4];
851
- argumento = _a[_i];
852
- return [4 /*yield*/, this.avaliar(argumento)];
853
- case 2:
854
- resultadoAvaliacao = _b.sent();
855
- valor = (resultadoAvaliacao === null || resultadoAvaliacao === void 0 ? void 0 : resultadoAvaliacao.hasOwnProperty('valor'))
856
- ? resultadoAvaliacao.valor
857
- : resultadoAvaliacao;
858
- _b.label = 3;
859
- case 3:
860
- _i++;
861
- return [3 /*break*/, 1];
862
- case 4:
863
- formatoTexto = this.paraTexto(valor);
864
- // Por enquanto `escreva` não devolve resultado no interpretador.
865
- // this.resultadoInterpretador.push(formatoTexto);
866
- this.funcaoDeRetorno(formatoTexto);
867
- return [2 /*return*/, null];
868
- case 5:
869
- erro_9 = _b.sent();
870
- this.erros.push(erro_9);
871
- return [3 /*break*/, 6];
872
- case 6: return [2 /*return*/];
873
- }
874
- });
875
- });
876
- };
553
+ async visitarExpressaoEscreva(declaracao) {
554
+ try {
555
+ let valor;
556
+ for (const argumento of declaracao.argumentos) {
557
+ const resultadoAvaliacao = await this.avaliar(argumento);
558
+ valor = (resultadoAvaliacao === null || resultadoAvaliacao === void 0 ? void 0 : resultadoAvaliacao.hasOwnProperty('valor'))
559
+ ? resultadoAvaliacao.valor
560
+ : resultadoAvaliacao;
561
+ }
562
+ const formatoTexto = this.paraTexto(valor);
563
+ // Por enquanto `escreva` não devolve resultado no interpretador.
564
+ // this.resultadoInterpretador.push(formatoTexto);
565
+ this.funcaoDeRetorno(formatoTexto);
566
+ return null;
567
+ }
568
+ catch (erro) {
569
+ this.erros.push(erro);
570
+ }
571
+ }
877
572
  /**
878
573
  * Empilha declarações na pilha de escopos de execução, cria um novo ambiente e
879
574
  * executa as declarações empilhadas.
@@ -883,386 +578,265 @@ var Interpretador = /** @class */ (function () {
883
578
  * @param declaracoes Um vetor de declaracoes a ser executado.
884
579
  * @param ambiente O ambiente de execução quando houver, como parâmetros, argumentos, etc.
885
580
  */
886
- Interpretador.prototype.executarBloco = function (declaracoes, ambiente) {
887
- return __awaiter(this, void 0, void 0, function () {
888
- var escopoExecucao, retornoUltimoEscopo;
889
- return __generator(this, function (_a) {
890
- switch (_a.label) {
891
- case 0:
892
- escopoExecucao = {
893
- declaracoes: declaracoes,
894
- declaracaoAtual: 0,
895
- ambiente: ambiente || new espaco_variaveis_1.EspacoVariaveis(),
896
- };
897
- this.pilhaEscoposExecucao.empilhar(escopoExecucao);
898
- return [4 /*yield*/, this.executarUltimoEscopo()];
899
- case 1:
900
- retornoUltimoEscopo = _a.sent();
901
- if (retornoUltimoEscopo instanceof excecoes_1.ErroEmTempoDeExecucao) {
902
- return [2 /*return*/, Promise.reject(retornoUltimoEscopo)];
903
- }
904
- return [2 /*return*/, retornoUltimoEscopo];
905
- }
906
- });
907
- });
908
- };
909
- Interpretador.prototype.visitarExpressaoBloco = function (declaracao) {
910
- return __awaiter(this, void 0, void 0, function () {
911
- return __generator(this, function (_a) {
912
- switch (_a.label) {
913
- case 0: return [4 /*yield*/, this.executarBloco(declaracao.declaracoes)];
914
- case 1: return [2 /*return*/, _a.sent()];
915
- }
916
- });
917
- });
918
- };
581
+ async executarBloco(declaracoes, ambiente) {
582
+ const escopoExecucao = {
583
+ declaracoes: declaracoes,
584
+ declaracaoAtual: 0,
585
+ ambiente: ambiente || new espaco_variaveis_1.EspacoVariaveis(),
586
+ };
587
+ this.pilhaEscoposExecucao.empilhar(escopoExecucao);
588
+ const retornoUltimoEscopo = await this.executarUltimoEscopo();
589
+ if (retornoUltimoEscopo instanceof excecoes_1.ErroEmTempoDeExecucao) {
590
+ return Promise.reject(retornoUltimoEscopo);
591
+ }
592
+ return retornoUltimoEscopo;
593
+ }
594
+ async visitarExpressaoBloco(declaracao) {
595
+ return await this.executarBloco(declaracao.declaracoes);
596
+ }
919
597
  /**
920
598
  * Executa expressão de definição de variável.
921
599
  * @param declaracao A declaração Var
922
600
  * @returns Sempre retorna nulo.
923
601
  */
924
- Interpretador.prototype.visitarExpressaoVar = function (declaracao) {
925
- return __awaiter(this, void 0, void 0, function () {
926
- var valorOuOutraVariavel, valorFinal;
927
- return __generator(this, function (_a) {
928
- switch (_a.label) {
929
- case 0:
930
- valorOuOutraVariavel = null;
931
- if (!(declaracao.inicializador !== null)) return [3 /*break*/, 2];
932
- return [4 /*yield*/, this.avaliar(declaracao.inicializador)];
933
- case 1:
934
- valorOuOutraVariavel = _a.sent();
935
- _a.label = 2;
936
- case 2:
937
- valorFinal = null;
938
- if (valorOuOutraVariavel !== null && valorOuOutraVariavel !== undefined) {
939
- valorFinal = valorOuOutraVariavel.hasOwnProperty('valor')
940
- ? valorOuOutraVariavel.valor
941
- : valorOuOutraVariavel;
942
- }
943
- this.pilhaEscoposExecucao.definirVariavel(declaracao.simbolo.lexema, valorFinal);
944
- return [2 /*return*/, null];
945
- }
946
- });
947
- });
948
- };
949
- Interpretador.prototype.visitarExpressaoContinua = function (declaracao) {
602
+ async visitarExpressaoVar(declaracao) {
603
+ let valorOuOutraVariavel = null;
604
+ if (declaracao.inicializador !== null) {
605
+ valorOuOutraVariavel = await this.avaliar(declaracao.inicializador);
606
+ }
607
+ let valorFinal = null;
608
+ if (valorOuOutraVariavel !== null && valorOuOutraVariavel !== undefined) {
609
+ valorFinal = valorOuOutraVariavel.hasOwnProperty('valor')
610
+ ? valorOuOutraVariavel.valor
611
+ : valorOuOutraVariavel;
612
+ }
613
+ this.pilhaEscoposExecucao.definirVariavel(declaracao.simbolo.lexema, valorFinal);
614
+ return null;
615
+ }
616
+ visitarExpressaoContinua(declaracao) {
950
617
  return new quebras_1.ContinuarQuebra();
951
- };
952
- Interpretador.prototype.visitarExpressaoSustar = function (declaracao) {
618
+ }
619
+ visitarExpressaoSustar(declaracao) {
953
620
  return new quebras_1.SustarQuebra();
954
- };
955
- Interpretador.prototype.visitarExpressaoRetornar = function (declaracao) {
956
- return __awaiter(this, void 0, void 0, function () {
957
- var valor;
958
- return __generator(this, function (_a) {
959
- switch (_a.label) {
960
- case 0:
961
- valor = null;
962
- if (!(declaracao.valor != null)) return [3 /*break*/, 2];
963
- return [4 /*yield*/, this.avaliar(declaracao.valor)];
964
- case 1:
965
- valor = _a.sent();
966
- _a.label = 2;
967
- case 2: return [2 /*return*/, new quebras_1.RetornoQuebra(valor)];
968
- }
969
- });
970
- });
971
- };
972
- Interpretador.prototype.visitarExpressaoDeleguaFuncao = function (expressao) {
621
+ }
622
+ async visitarExpressaoRetornar(declaracao) {
623
+ let valor = null;
624
+ if (declaracao.valor != null)
625
+ valor = await this.avaliar(declaracao.valor);
626
+ return new quebras_1.RetornoQuebra(valor);
627
+ }
628
+ visitarExpressaoDeleguaFuncao(expressao) {
973
629
  return new estruturas_1.DeleguaFuncao(null, expressao);
974
- };
975
- Interpretador.prototype.visitarExpressaoAtribuicaoSobrescrita = function (expressao) {
976
- return __awaiter(this, void 0, void 0, function () {
977
- var promises, objeto, indice, valor;
978
- return __generator(this, function (_a) {
979
- switch (_a.label) {
980
- case 0: return [4 /*yield*/, Promise.all([
981
- this.avaliar(expressao.objeto),
982
- this.avaliar(expressao.indice),
983
- this.avaliar(expressao.valor)
984
- ])];
985
- case 1:
986
- promises = _a.sent();
987
- objeto = promises[0];
988
- indice = promises[1];
989
- valor = promises[2];
990
- objeto = objeto.hasOwnProperty('valor') ? objeto.valor : objeto;
991
- indice = indice.hasOwnProperty('valor') ? indice.valor : indice;
992
- if (Array.isArray(objeto)) {
993
- if (indice < 0 && objeto.length !== 0) {
994
- while (indice < 0) {
995
- indice += objeto.length;
996
- }
997
- }
998
- while (objeto.length < indice) {
999
- objeto.push(null);
1000
- }
1001
- objeto[indice] = valor;
1002
- }
1003
- else if (objeto.constructor === Object ||
1004
- objeto instanceof estruturas_1.ObjetoDeleguaClasse ||
1005
- objeto instanceof estruturas_1.DeleguaFuncao ||
1006
- objeto instanceof estruturas_1.DeleguaClasse ||
1007
- objeto instanceof estruturas_1.DeleguaModulo) {
1008
- objeto[indice] = valor;
1009
- }
1010
- else {
1011
- return [2 /*return*/, Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.objeto.nome, 'Somente listas, dicionários, classes e objetos podem ser mudados por sobrescrita.', expressao.linha))];
1012
- }
1013
- return [2 /*return*/];
630
+ }
631
+ async visitarExpressaoAtribuicaoSobrescrita(expressao) {
632
+ const promises = await Promise.all([
633
+ this.avaliar(expressao.objeto),
634
+ this.avaliar(expressao.indice),
635
+ this.avaliar(expressao.valor)
636
+ ]);
637
+ let objeto = promises[0];
638
+ let indice = promises[1];
639
+ const valor = promises[2];
640
+ objeto = objeto.hasOwnProperty('valor') ? objeto.valor : objeto;
641
+ indice = indice.hasOwnProperty('valor') ? indice.valor : indice;
642
+ if (Array.isArray(objeto)) {
643
+ if (indice < 0 && objeto.length !== 0) {
644
+ while (indice < 0) {
645
+ indice += objeto.length;
1014
646
  }
1015
- });
1016
- });
1017
- };
1018
- Interpretador.prototype.visitarExpressaoAcessoIndiceVariavel = function (expressao) {
1019
- return __awaiter(this, void 0, void 0, function () {
1020
- var variavelObjeto, objeto, indice, valorIndice;
1021
- return __generator(this, function (_a) {
1022
- switch (_a.label) {
1023
- case 0: return [4 /*yield*/, this.avaliar(expressao.entidadeChamada)];
1024
- case 1:
1025
- variavelObjeto = _a.sent();
1026
- objeto = variavelObjeto.hasOwnProperty('valor')
1027
- ? variavelObjeto.valor
1028
- : variavelObjeto;
1029
- return [4 /*yield*/, this.avaliar(expressao.indice)];
1030
- case 2:
1031
- indice = _a.sent();
1032
- valorIndice = indice.hasOwnProperty('valor') ? indice.valor : indice;
1033
- if (Array.isArray(objeto)) {
1034
- if (!Number.isInteger(valorIndice)) {
1035
- return [2 /*return*/, Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Somente inteiros podem ser usados para indexar um vetor.', expressao.linha))];
1036
- }
1037
- if (valorIndice < 0 && objeto.length !== 0) {
1038
- while (valorIndice < 0) {
1039
- valorIndice += objeto.length;
1040
- }
1041
- }
1042
- if (valorIndice >= objeto.length) {
1043
- return [2 /*return*/, Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Índice do vetor fora do intervalo.', expressao.linha))];
1044
- }
1045
- return [2 /*return*/, objeto[valorIndice]];
1046
- }
1047
- else if (objeto.constructor === Object ||
1048
- objeto instanceof estruturas_1.ObjetoDeleguaClasse ||
1049
- objeto instanceof estruturas_1.DeleguaFuncao ||
1050
- objeto instanceof estruturas_1.DeleguaClasse ||
1051
- objeto instanceof estruturas_1.DeleguaModulo) {
1052
- return [2 /*return*/, objeto[valorIndice] || null];
1053
- }
1054
- else if (typeof objeto === 'string') {
1055
- if (!Number.isInteger(valorIndice)) {
1056
- return [2 /*return*/, Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Somente inteiros podem ser usados para indexar um vetor.', expressao.linha))];
1057
- }
1058
- if (valorIndice < 0 && objeto.length !== 0) {
1059
- while (valorIndice < 0) {
1060
- valorIndice += objeto.length;
1061
- }
1062
- }
1063
- if (valorIndice >= objeto.length) {
1064
- return [2 /*return*/, Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Índice fora do tamanho.', expressao.linha))];
1065
- }
1066
- return [2 /*return*/, objeto.charAt(valorIndice)];
1067
- }
1068
- else {
1069
- return [2 /*return*/, Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.entidadeChamada.nome, 'Somente listas, dicionários, classes e objetos podem ser mudados por sobrescrita.', expressao.linha))];
1070
- }
1071
- return [2 /*return*/];
647
+ }
648
+ while (objeto.length < indice) {
649
+ objeto.push(null);
650
+ }
651
+ objeto[indice] = valor;
652
+ }
653
+ else if (objeto.constructor === Object ||
654
+ objeto instanceof estruturas_1.ObjetoDeleguaClasse ||
655
+ objeto instanceof estruturas_1.DeleguaFuncao ||
656
+ objeto instanceof estruturas_1.DeleguaClasse ||
657
+ objeto instanceof estruturas_1.DeleguaModulo) {
658
+ objeto[indice] = valor;
659
+ }
660
+ else {
661
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.objeto.nome, 'Somente listas, dicionários, classes e objetos podem ser mudados por sobrescrita.', expressao.linha));
662
+ }
663
+ }
664
+ async visitarExpressaoAcessoIndiceVariavel(expressao) {
665
+ const variavelObjeto = await this.avaliar(expressao.entidadeChamada);
666
+ const objeto = variavelObjeto.hasOwnProperty('valor')
667
+ ? variavelObjeto.valor
668
+ : variavelObjeto;
669
+ const indice = await this.avaliar(expressao.indice);
670
+ let valorIndice = indice.hasOwnProperty('valor') ? indice.valor : indice;
671
+ if (Array.isArray(objeto)) {
672
+ if (!Number.isInteger(valorIndice)) {
673
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Somente inteiros podem ser usados para indexar um vetor.', expressao.linha));
674
+ }
675
+ if (valorIndice < 0 && objeto.length !== 0) {
676
+ while (valorIndice < 0) {
677
+ valorIndice += objeto.length;
1072
678
  }
1073
- });
1074
- });
1075
- };
1076
- Interpretador.prototype.visitarExpressaoDefinirValor = function (expressao) {
1077
- return __awaiter(this, void 0, void 0, function () {
1078
- var objeto, valor;
1079
- return __generator(this, function (_a) {
1080
- switch (_a.label) {
1081
- case 0: return [4 /*yield*/, this.avaliar(expressao.objeto)];
1082
- case 1:
1083
- objeto = _a.sent();
1084
- if (!(objeto instanceof estruturas_1.ObjetoDeleguaClasse) &&
1085
- objeto.constructor !== Object) {
1086
- return [2 /*return*/, Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.objeto.nome, 'Somente instâncias e dicionários podem possuir campos.', expressao.linha))];
1087
- }
1088
- return [4 /*yield*/, this.avaliar(expressao.valor)];
1089
- case 2:
1090
- valor = _a.sent();
1091
- if (objeto instanceof estruturas_1.ObjetoDeleguaClasse) {
1092
- objeto.set(expressao.nome, valor);
1093
- return [2 /*return*/, valor];
1094
- }
1095
- else if (objeto.constructor === Object) {
1096
- objeto[expressao.simbolo.lexema] = valor;
1097
- }
1098
- return [2 /*return*/];
679
+ }
680
+ if (valorIndice >= objeto.length) {
681
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Índice do vetor fora do intervalo.', expressao.linha));
682
+ }
683
+ return objeto[valorIndice];
684
+ }
685
+ else if (objeto.constructor === Object ||
686
+ objeto instanceof estruturas_1.ObjetoDeleguaClasse ||
687
+ objeto instanceof estruturas_1.DeleguaFuncao ||
688
+ objeto instanceof estruturas_1.DeleguaClasse ||
689
+ objeto instanceof estruturas_1.DeleguaModulo) {
690
+ return objeto[valorIndice] || null;
691
+ }
692
+ else if (typeof objeto === 'string') {
693
+ if (!Number.isInteger(valorIndice)) {
694
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Somente inteiros podem ser usados para indexar um vetor.', expressao.linha));
695
+ }
696
+ if (valorIndice < 0 && objeto.length !== 0) {
697
+ while (valorIndice < 0) {
698
+ valorIndice += objeto.length;
1099
699
  }
1100
- });
1101
- });
1102
- };
1103
- Interpretador.prototype.visitarExpressaoFuncao = function (declaracao) {
1104
- var funcao = new estruturas_1.DeleguaFuncao(declaracao.simbolo.lexema, declaracao.funcao);
700
+ }
701
+ if (valorIndice >= objeto.length) {
702
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.simboloFechamento, 'Índice fora do tamanho.', expressao.linha));
703
+ }
704
+ return objeto.charAt(valorIndice);
705
+ }
706
+ else {
707
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.entidadeChamada.nome, 'Somente listas, dicionários, classes e objetos podem ser mudados por sobrescrita.', expressao.linha));
708
+ }
709
+ }
710
+ async visitarExpressaoDefinirValor(expressao) {
711
+ const variavelObjeto = await this.avaliar(expressao.objeto);
712
+ const objeto = variavelObjeto.hasOwnProperty('valor')
713
+ ? variavelObjeto.valor
714
+ : variavelObjeto;
715
+ if (!(objeto instanceof estruturas_1.ObjetoDeleguaClasse) &&
716
+ objeto.constructor !== Object) {
717
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.objeto.nome, 'Somente instâncias e dicionários podem possuir campos.', expressao.linha));
718
+ }
719
+ const valor = await this.avaliar(expressao.valor);
720
+ if (objeto instanceof estruturas_1.ObjetoDeleguaClasse) {
721
+ objeto.definir(expressao.nome, valor);
722
+ return valor;
723
+ }
724
+ else if (objeto.constructor === Object) {
725
+ objeto[expressao.simbolo.lexema] = valor;
726
+ }
727
+ }
728
+ visitarExpressaoFuncao(declaracao) {
729
+ const funcao = new estruturas_1.DeleguaFuncao(declaracao.simbolo.lexema, declaracao.funcao);
1105
730
  this.pilhaEscoposExecucao.definirVariavel(declaracao.simbolo.lexema, funcao);
1106
- };
731
+ }
1107
732
  /**
1108
733
  * Executa uma declaração de classe.
1109
734
  * @param declaracao A declaração de classe.
1110
735
  * @returns Sempre retorna nulo, por ser requerido pelo contrato de visita.
1111
736
  */
1112
- Interpretador.prototype.visitarExpressaoClasse = function (declaracao) {
1113
- return __awaiter(this, void 0, void 0, function () {
1114
- var superClasse, variavelSuperClasse, metodos, definirMetodos, i, metodoAtual, eInicializador, funcao, deleguaClasse;
1115
- return __generator(this, function (_a) {
1116
- switch (_a.label) {
1117
- case 0:
1118
- superClasse = null;
1119
- if (!(declaracao.superClasse !== null)) return [3 /*break*/, 2];
1120
- return [4 /*yield*/, this.avaliar(declaracao.superClasse)];
1121
- case 1:
1122
- variavelSuperClasse = _a.sent();
1123
- superClasse = variavelSuperClasse.valor;
1124
- if (!(superClasse instanceof estruturas_1.DeleguaClasse)) {
1125
- throw new excecoes_1.ErroEmTempoDeExecucao(declaracao.superClasse.nome, 'SuperClasse precisa ser uma classe.', declaracao.linha);
1126
- }
1127
- _a.label = 2;
1128
- case 2:
1129
- this.pilhaEscoposExecucao.definirVariavel(declaracao.simbolo.lexema, null);
1130
- if (declaracao.superClasse !== null) {
1131
- this.pilhaEscoposExecucao.definirVariavel('super', superClasse);
1132
- }
1133
- metodos = {};
1134
- definirMetodos = declaracao.metodos;
1135
- for (i = 0; i < declaracao.metodos.length; i++) {
1136
- metodoAtual = definirMetodos[i];
1137
- eInicializador = metodoAtual.simbolo.lexema === 'construtor';
1138
- funcao = new estruturas_1.DeleguaFuncao(metodoAtual.simbolo.lexema, metodoAtual.funcao, undefined, eInicializador);
1139
- metodos[metodoAtual.simbolo.lexema] = funcao;
1140
- }
1141
- deleguaClasse = new estruturas_1.DeleguaClasse(declaracao.simbolo.lexema, superClasse, metodos);
1142
- // TODO: Recolocar isso se for necessário.
1143
- /* if (superClasse !== null) {
1144
- this.ambiente = this.ambiente.enclosing;
1145
- } */
1146
- this.pilhaEscoposExecucao.atribuirVariavel(declaracao.simbolo, deleguaClasse);
1147
- return [2 /*return*/, null];
1148
- }
1149
- });
1150
- });
1151
- };
737
+ async visitarExpressaoClasse(declaracao) {
738
+ let superClasse = null;
739
+ if (declaracao.superClasse !== null) {
740
+ const variavelSuperClasse = await this.avaliar(declaracao.superClasse);
741
+ superClasse = variavelSuperClasse.valor;
742
+ if (!(superClasse instanceof estruturas_1.DeleguaClasse)) {
743
+ throw new excecoes_1.ErroEmTempoDeExecucao(declaracao.superClasse.nome, 'SuperClasse precisa ser uma classe.', declaracao.linha);
744
+ }
745
+ }
746
+ this.pilhaEscoposExecucao.definirVariavel(declaracao.simbolo.lexema, null);
747
+ if (declaracao.superClasse !== null) {
748
+ this.pilhaEscoposExecucao.definirVariavel('super', superClasse);
749
+ }
750
+ const metodos = {};
751
+ const definirMetodos = declaracao.metodos;
752
+ for (let i = 0; i < declaracao.metodos.length; i++) {
753
+ const metodoAtual = definirMetodos[i];
754
+ const eInicializador = metodoAtual.simbolo.lexema === 'construtor';
755
+ const funcao = new estruturas_1.DeleguaFuncao(metodoAtual.simbolo.lexema, metodoAtual.funcao, undefined, eInicializador);
756
+ metodos[metodoAtual.simbolo.lexema] = funcao;
757
+ }
758
+ const deleguaClasse = new estruturas_1.DeleguaClasse(declaracao.simbolo.lexema, superClasse, metodos);
759
+ // TODO: Recolocar isso se for necessário.
760
+ /* if (superClasse !== null) {
761
+ this.ambiente = this.ambiente.enclosing;
762
+ } */
763
+ this.pilhaEscoposExecucao.atribuirVariavel(declaracao.simbolo, deleguaClasse);
764
+ return null;
765
+ }
1152
766
  /**
1153
767
  * Executa um acesso a método, normalmente de um objeto de classe.
1154
768
  * @param expressao A expressão de acesso.
1155
769
  * @returns O resultado da execução.
1156
770
  */
1157
- Interpretador.prototype.visitarExpressaoAcessoMetodo = function (expressao) {
1158
- return __awaiter(this, void 0, void 0, function () {
1159
- var variavelObjeto, objeto, metodoDePrimitivaTexto, metodoDePrimitivaVetor;
1160
- return __generator(this, function (_a) {
1161
- switch (_a.label) {
1162
- case 0: return [4 /*yield*/, this.avaliar(expressao.objeto)];
1163
- case 1:
1164
- variavelObjeto = _a.sent();
1165
- objeto = variavelObjeto === null || variavelObjeto === void 0 ? void 0 : variavelObjeto.valor;
1166
- if (objeto instanceof estruturas_1.ObjetoDeleguaClasse) {
1167
- return [2 /*return*/, objeto.get(expressao.simbolo) || null];
1168
- }
1169
- if (objeto.constructor === Object) {
1170
- return [2 /*return*/, objeto[expressao.simbolo.lexema] || null];
1171
- }
1172
- if (objeto instanceof estruturas_1.DeleguaModulo) {
1173
- return [2 /*return*/, objeto.componentes[expressao.simbolo.lexema] || null];
1174
- }
1175
- switch (variavelObjeto.tipo) {
1176
- case 'texto':
1177
- metodoDePrimitivaTexto = primitivas_texto_1.default[expressao.simbolo.lexema];
1178
- if (metodoDePrimitivaTexto) {
1179
- return [2 /*return*/, new metodo_primitiva_1.MetodoPrimitiva(objeto, metodoDePrimitivaTexto)];
1180
- }
1181
- break;
1182
- case 'vetor':
1183
- metodoDePrimitivaVetor = primitivas_vetor_1.default[expressao.simbolo.lexema];
1184
- if (metodoDePrimitivaVetor) {
1185
- return [2 /*return*/, new metodo_primitiva_1.MetodoPrimitiva(objeto, metodoDePrimitivaVetor)];
1186
- }
1187
- break;
1188
- }
1189
- return [2 /*return*/, Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.nome, 'Você só pode acessar métodos do objeto e dicionários.', expressao.linha))];
1190
- }
1191
- });
1192
- });
1193
- };
1194
- Interpretador.prototype.visitarExpressaoIsto = function (expressao) {
1195
- return this.procurarVariavel(expressao.palavraChave);
1196
- };
1197
- Interpretador.prototype.visitarExpressaoDicionario = function (expressao) {
1198
- return __awaiter(this, void 0, void 0, function () {
1199
- var dicionario, i, promises;
1200
- return __generator(this, function (_a) {
1201
- switch (_a.label) {
1202
- case 0:
1203
- dicionario = {};
1204
- i = 0;
1205
- _a.label = 1;
1206
- case 1:
1207
- if (!(i < expressao.chaves.length)) return [3 /*break*/, 4];
1208
- return [4 /*yield*/, Promise.all([
1209
- this.avaliar(expressao.chaves[i]),
1210
- this.avaliar(expressao.valores[i])
1211
- ])];
1212
- case 2:
1213
- promises = _a.sent();
1214
- dicionario[promises[0]] = promises[1];
1215
- _a.label = 3;
1216
- case 3:
1217
- i++;
1218
- return [3 /*break*/, 1];
1219
- case 4: return [2 /*return*/, dicionario];
771
+ async visitarExpressaoAcessoMetodo(expressao) {
772
+ const variavelObjeto = await this.avaliar(expressao.objeto);
773
+ const objeto = variavelObjeto.hasOwnProperty('valor')
774
+ ? variavelObjeto.valor
775
+ : variavelObjeto;
776
+ if (objeto instanceof estruturas_1.ObjetoDeleguaClasse) {
777
+ return objeto.obter(expressao.simbolo) || null;
778
+ }
779
+ if (objeto.constructor === Object) {
780
+ return objeto[expressao.simbolo.lexema] || null;
781
+ }
782
+ if (objeto instanceof estruturas_1.DeleguaModulo) {
783
+ return objeto.componentes[expressao.simbolo.lexema] || null;
784
+ }
785
+ switch (variavelObjeto.tipo) {
786
+ case 'texto':
787
+ const metodoDePrimitivaTexto = primitivas_texto_1.default[expressao.simbolo.lexema];
788
+ if (metodoDePrimitivaTexto) {
789
+ return new metodo_primitiva_1.MetodoPrimitiva(objeto, metodoDePrimitivaTexto);
1220
790
  }
1221
- });
1222
- });
1223
- };
1224
- Interpretador.prototype.visitarExpressaoVetor = function (expressao) {
1225
- return __awaiter(this, void 0, void 0, function () {
1226
- var valores, i, _a, _b;
1227
- return __generator(this, function (_c) {
1228
- switch (_c.label) {
1229
- case 0:
1230
- valores = [];
1231
- i = 0;
1232
- _c.label = 1;
1233
- case 1:
1234
- if (!(i < expressao.valores.length)) return [3 /*break*/, 4];
1235
- _b = (_a = valores).push;
1236
- return [4 /*yield*/, this.avaliar(expressao.valores[i])];
1237
- case 2:
1238
- _b.apply(_a, [_c.sent()]);
1239
- _c.label = 3;
1240
- case 3:
1241
- i++;
1242
- return [3 /*break*/, 1];
1243
- case 4: return [2 /*return*/, valores];
791
+ break;
792
+ case 'vetor':
793
+ const metodoDePrimitivaVetor = primitivas_vetor_1.default[expressao.simbolo.lexema];
794
+ if (metodoDePrimitivaVetor) {
795
+ return new metodo_primitiva_1.MetodoPrimitiva(objeto, metodoDePrimitivaVetor);
1244
796
  }
1245
- });
1246
- });
1247
- };
797
+ break;
798
+ }
799
+ return Promise.reject(new excecoes_1.ErroEmTempoDeExecucao(expressao.nome, 'Você só pode acessar métodos do objeto e dicionários.', expressao.linha));
800
+ }
801
+ visitarExpressaoIsto(expressao) {
802
+ return this.procurarVariavel(expressao.palavraChave);
803
+ }
804
+ async visitarExpressaoDicionario(expressao) {
805
+ const dicionario = {};
806
+ for (let i = 0; i < expressao.chaves.length; i++) {
807
+ const promises = await Promise.all([
808
+ this.avaliar(expressao.chaves[i]),
809
+ this.avaliar(expressao.valores[i])
810
+ ]);
811
+ dicionario[promises[0]] = promises[1];
812
+ }
813
+ return dicionario;
814
+ }
815
+ async visitarExpressaoVetor(expressao) {
816
+ const valores = [];
817
+ for (let i = 0; i < expressao.valores.length; i++) {
818
+ valores.push(await this.avaliar(expressao.valores[i]));
819
+ }
820
+ return valores;
821
+ }
1248
822
  // TODO: Após remoção do Resolvedor, simular casos que usem 'super' e 'isto'.
1249
- Interpretador.prototype.visitarExpressaoSuper = function (expressao) {
1250
- var superClasse = this.pilhaEscoposExecucao.obterVariavelPorNome('super');
1251
- var objeto = this.pilhaEscoposExecucao.obterVariavelPorNome('isto');
1252
- var metodo = superClasse.valor.encontrarMetodo(expressao.metodo.lexema);
823
+ visitarExpressaoSuper(expressao) {
824
+ const superClasse = this.pilhaEscoposExecucao.obterVariavelPorNome('super');
825
+ const objeto = this.pilhaEscoposExecucao.obterVariavelPorNome('isto');
826
+ const metodo = superClasse.valor.encontrarMetodo(expressao.metodo.lexema);
1253
827
  if (metodo === undefined) {
1254
828
  throw new excecoes_1.ErroEmTempoDeExecucao(expressao.metodo, 'Método chamado indefinido.', expressao.linha);
1255
829
  }
1256
830
  return metodo.definirInstancia(objeto.valor);
1257
- };
1258
- Interpretador.prototype.paraTexto = function (objeto) {
831
+ }
832
+ paraTexto(objeto) {
1259
833
  if (objeto === null || objeto === undefined)
1260
834
  return 'nulo';
1261
835
  if (typeof objeto === 'boolean') {
1262
836
  return objeto ? 'verdadeiro' : 'falso';
1263
837
  }
1264
838
  if (objeto instanceof Date) {
1265
- var formato = Intl.DateTimeFormat('pt', {
839
+ const formato = Intl.DateTimeFormat('pt', {
1266
840
  dateStyle: 'full',
1267
841
  timeStyle: 'full',
1268
842
  });
@@ -1275,33 +849,23 @@ var Interpretador = /** @class */ (function () {
1275
849
  if (typeof objeto === 'object')
1276
850
  return JSON.stringify(objeto);
1277
851
  return objeto.toString();
1278
- };
852
+ }
1279
853
  /**
1280
854
  * Efetivamente executa uma declaração.
1281
855
  * @param declaracao A declaração a ser executada.
1282
856
  * @param mostrarResultado Se resultado deve ser mostrado ou não. Normalmente usado
1283
857
  * pelo modo LAIR.
1284
858
  */
1285
- Interpretador.prototype.executar = function (declaracao, mostrarResultado) {
1286
- if (mostrarResultado === void 0) { mostrarResultado = false; }
1287
- return __awaiter(this, void 0, void 0, function () {
1288
- var resultado;
1289
- return __generator(this, function (_a) {
1290
- switch (_a.label) {
1291
- case 0: return [4 /*yield*/, declaracao.aceitar(this)];
1292
- case 1:
1293
- resultado = _a.sent();
1294
- if (mostrarResultado) {
1295
- this.funcaoDeRetorno(this.paraTexto(resultado));
1296
- }
1297
- if (resultado || typeof resultado === 'boolean') {
1298
- this.resultadoInterpretador.push(this.paraTexto(resultado));
1299
- }
1300
- return [2 /*return*/, resultado];
1301
- }
1302
- });
1303
- });
1304
- };
859
+ async executar(declaracao, mostrarResultado = false) {
860
+ const resultado = await declaracao.aceitar(this);
861
+ if (mostrarResultado) {
862
+ this.funcaoDeRetorno(this.paraTexto(resultado));
863
+ }
864
+ if (resultado || typeof resultado === 'boolean') {
865
+ this.resultadoInterpretador.push(this.paraTexto(resultado));
866
+ }
867
+ return resultado;
868
+ }
1305
869
  /**
1306
870
  * Executa o último escopo empilhado no topo na pilha de escopos do interpretador.
1307
871
  * Esse método pega exceções, mas apenas as devolve.
@@ -1312,45 +876,27 @@ var Interpretador = /** @class */ (function () {
1312
876
  * @param manterAmbiente Se verdadeiro, ambiente do topo da pilha de escopo é copiado para o ambiente imediatamente abaixo.
1313
877
  * @returns O resultado da execução do escopo, se houver.
1314
878
  */
1315
- Interpretador.prototype.executarUltimoEscopo = function (manterAmbiente) {
1316
- if (manterAmbiente === void 0) { manterAmbiente = false; }
1317
- return __awaiter(this, void 0, void 0, function () {
1318
- var ultimoEscopo, retornoExecucao, erro_10, escopoAnterior;
1319
- return __generator(this, function (_a) {
1320
- switch (_a.label) {
1321
- case 0:
1322
- ultimoEscopo = this.pilhaEscoposExecucao.topoDaPilha();
1323
- _a.label = 1;
1324
- case 1:
1325
- _a.trys.push([1, 6, 7, 8]);
1326
- retornoExecucao = void 0;
1327
- _a.label = 2;
1328
- case 2:
1329
- if (!(!(retornoExecucao instanceof quebras_1.Quebra) &&
1330
- ultimoEscopo.declaracaoAtual < ultimoEscopo.declaracoes.length)) return [3 /*break*/, 5];
1331
- return [4 /*yield*/, this.executar(ultimoEscopo.declaracoes[ultimoEscopo.declaracaoAtual])];
1332
- case 3:
1333
- retornoExecucao = _a.sent();
1334
- _a.label = 4;
1335
- case 4:
1336
- ultimoEscopo.declaracaoAtual++;
1337
- return [3 /*break*/, 2];
1338
- case 5: return [2 /*return*/, retornoExecucao];
1339
- case 6:
1340
- erro_10 = _a.sent();
1341
- return [2 /*return*/, Promise.reject(erro_10)];
1342
- case 7:
1343
- this.pilhaEscoposExecucao.removerUltimo();
1344
- if (manterAmbiente) {
1345
- escopoAnterior = this.pilhaEscoposExecucao.topoDaPilha();
1346
- escopoAnterior.ambiente.valores = Object.assign(escopoAnterior.ambiente.valores, ultimoEscopo.ambiente.valores);
1347
- }
1348
- return [7 /*endfinally*/];
1349
- case 8: return [2 /*return*/];
1350
- }
1351
- });
1352
- });
1353
- };
879
+ async executarUltimoEscopo(manterAmbiente = false) {
880
+ const ultimoEscopo = this.pilhaEscoposExecucao.topoDaPilha();
881
+ try {
882
+ let retornoExecucao;
883
+ for (; !(retornoExecucao instanceof quebras_1.Quebra) &&
884
+ ultimoEscopo.declaracaoAtual < ultimoEscopo.declaracoes.length; ultimoEscopo.declaracaoAtual++) {
885
+ retornoExecucao = await this.executar(ultimoEscopo.declaracoes[ultimoEscopo.declaracaoAtual]);
886
+ }
887
+ return retornoExecucao;
888
+ }
889
+ catch (erro) {
890
+ return Promise.reject(erro);
891
+ }
892
+ finally {
893
+ this.pilhaEscoposExecucao.removerUltimo();
894
+ if (manterAmbiente) {
895
+ const escopoAnterior = this.pilhaEscoposExecucao.topoDaPilha();
896
+ escopoAnterior.ambiente.valores = Object.assign(escopoAnterior.ambiente.valores, ultimoEscopo.ambiente.valores);
897
+ }
898
+ }
899
+ }
1354
900
  /**
1355
901
  * Interpretação sem depurador, com medição de performance.
1356
902
  * Método que efetivamente inicia o processo de interpretação.
@@ -1359,52 +905,37 @@ var Interpretador = /** @class */ (function () {
1359
905
  * pelo modo REPL (LEIA).
1360
906
  * @returns Um objeto com o resultado da interpretação.
1361
907
  */
1362
- Interpretador.prototype.interpretar = function (declaracoes, manterAmbiente) {
1363
- if (manterAmbiente === void 0) { manterAmbiente = false; }
1364
- return __awaiter(this, void 0, void 0, function () {
1365
- var escopoExecucao, inicioInterpretacao, retornoOuErro, erro_11, deltaInterpretacao, retorno;
1366
- return __generator(this, function (_a) {
1367
- switch (_a.label) {
1368
- case 0:
1369
- this.erros = [];
1370
- escopoExecucao = {
1371
- declaracoes: declaracoes,
1372
- declaracaoAtual: 0,
1373
- ambiente: new espaco_variaveis_1.EspacoVariaveis(),
1374
- };
1375
- this.pilhaEscoposExecucao.empilhar(escopoExecucao);
1376
- inicioInterpretacao = (0, browser_process_hrtime_1.default)();
1377
- _a.label = 1;
1378
- case 1:
1379
- _a.trys.push([1, 3, 4, 5]);
1380
- return [4 /*yield*/, this.executarUltimoEscopo(manterAmbiente)];
1381
- case 2:
1382
- retornoOuErro = _a.sent();
1383
- if (retornoOuErro instanceof excecoes_1.ErroEmTempoDeExecucao) {
1384
- this.erros.push(retornoOuErro);
1385
- }
1386
- return [3 /*break*/, 5];
1387
- case 3:
1388
- erro_11 = _a.sent();
1389
- this.erros.push(erro_11);
1390
- return [3 /*break*/, 5];
1391
- case 4:
1392
- if (this.performance) {
1393
- deltaInterpretacao = (0, browser_process_hrtime_1.default)(inicioInterpretacao);
1394
- console.log("[Interpretador] Tempo para interpreta\u00E7ao: ".concat(deltaInterpretacao[0] * 1e9 + deltaInterpretacao[1], "ns"));
1395
- }
1396
- retorno = {
1397
- erros: this.erros,
1398
- resultado: this.resultadoInterpretador,
1399
- };
1400
- this.resultadoInterpretador = [];
1401
- return [2 /*return*/, retorno];
1402
- case 5: return [2 /*return*/];
1403
- }
1404
- });
1405
- });
1406
- };
1407
- return Interpretador;
1408
- }());
908
+ async interpretar(declaracoes, manterAmbiente = false) {
909
+ this.erros = [];
910
+ const escopoExecucao = {
911
+ declaracoes: declaracoes,
912
+ declaracaoAtual: 0,
913
+ ambiente: new espaco_variaveis_1.EspacoVariaveis(),
914
+ };
915
+ this.pilhaEscoposExecucao.empilhar(escopoExecucao);
916
+ const inicioInterpretacao = (0, browser_process_hrtime_1.default)();
917
+ try {
918
+ const retornoOuErro = await this.executarUltimoEscopo(manterAmbiente);
919
+ if (retornoOuErro instanceof excecoes_1.ErroEmTempoDeExecucao) {
920
+ this.erros.push(retornoOuErro);
921
+ }
922
+ }
923
+ catch (erro) {
924
+ this.erros.push(erro);
925
+ }
926
+ finally {
927
+ if (this.performance) {
928
+ const deltaInterpretacao = (0, browser_process_hrtime_1.default)(inicioInterpretacao);
929
+ console.log(`[Interpretador] Tempo para interpretaçao: ${deltaInterpretacao[0] * 1e9 + deltaInterpretacao[1]}ns`);
930
+ }
931
+ const retorno = {
932
+ erros: this.erros,
933
+ resultado: this.resultadoInterpretador,
934
+ };
935
+ this.resultadoInterpretador = [];
936
+ return retorno;
937
+ }
938
+ }
939
+ }
1409
940
  exports.Interpretador = Interpretador;
1410
941
  //# sourceMappingURL=interpretador.js.map