@designliquido/delegua 1.16.2 → 1.16.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/umd/delegua.js CHANGED
@@ -557,6 +557,13 @@ class AnalisadorSemantico extends analisador_semantico_base_1.AnalisadorSemantic
557
557
  visitarExpressaoTipoDe(expressao) {
558
558
  return this.verificarTipoDe(expressao.valor);
559
559
  }
560
+ /**
561
+ * Método recursivo para verificar o tipo de um construto, usado principalmente para validar
562
+ * o uso de `tipoDe` e `falhar()`.
563
+ * @param {Construto} valor O construto a ser avaliado.
564
+ * @returns {Promise<any>} O tipo do construto, ou `Promise.resolve()` se o tipo não puder ser
565
+ * determinado neste estágio da análise.
566
+ */
560
567
  verificarTipoDe(valor) {
561
568
  switch (valor.constructor) {
562
569
  case construtos_1.Agrupamento:
@@ -576,6 +583,13 @@ class AnalisadorSemantico extends analisador_semantico_base_1.AnalisadorSemantic
576
583
  visitarExpressaoFalhar(expressao) {
577
584
  return this.verificarFalhar(expressao.explicacao);
578
585
  }
586
+ /**
587
+ * Método recursivo para verificar se um construto passado para `falhar()` é válido, ou seja, se é
588
+ * do tipo texto ou pode ser avaliado como texto.
589
+ * @param {Construto} valor O construto a ser avaliado.
590
+ * @returns {Promise<any>} O tipo do construto, ou `Promise.resolve()` se o tipo não puder ser
591
+ * determinado neste estágio da análise.
592
+ */
579
593
  verificarFalhar(valor) {
580
594
  if (valor instanceof construtos_1.Binario) {
581
595
  this.verificarFalhar(valor.direita);
@@ -612,9 +626,7 @@ class AnalisadorSemantico extends analisador_semantico_base_1.AnalisadorSemantic
612
626
  }
613
627
  }
614
628
  visitarChamadaPorArgumentoReferenciaFuncao(argumentoReferenciaFuncao, argumentos) {
615
- const variavelCorrespondente =
616
- // this.variaveis[argumentoReferenciaFuncao.simboloFuncao.lexema].valor;
617
- this.gerenciadorEscopos.buscar(argumentoReferenciaFuncao.simboloFuncao.lexema)?.valor;
629
+ const variavelCorrespondente = this.gerenciadorEscopos.buscar(argumentoReferenciaFuncao.simboloFuncao.lexema)?.valor;
618
630
  if (!variavelCorrespondente) {
619
631
  return;
620
632
  }
@@ -761,14 +773,6 @@ class AnalisadorSemantico extends analisador_semantico_base_1.AnalisadorSemantic
761
773
  }
762
774
  }
763
775
  }
764
- /* if (valor.imutavel) {
765
- this.erro(simboloAlvo, `Constante ${simboloAlvo.lexema} não pode ser modificada.`);
766
- return Promise.resolve();
767
- } else {
768
- if (this.variaveis[simboloAlvo.lexema]) {
769
- this.variaveis[simboloAlvo.lexema].valor = expressao.valor;
770
- }
771
- } */
772
776
  return Promise.resolve();
773
777
  }
774
778
  async visitarDeclaracaoDeExpressao(declaracao) {
@@ -19950,6 +19954,7 @@ class InterpretadorBase {
19950
19954
  case construtos_1.AcessoMetodoOuPropriedade:
19951
19955
  case construtos_1.AcessoIndiceVariavel:
19952
19956
  case construtos_1.Dicionario:
19957
+ case construtos_1.Leia:
19953
19958
  case construtos_1.Literal:
19954
19959
  case construtos_1.Vetor:
19955
19960
  return '';
@@ -28976,7 +28981,7 @@ __exportStar(require("./tradutor-assembly-risc-v"), exports);
28976
28981
  __exportStar(require("./tradutor-webassembly"), exports);
28977
28982
  __exportStar(require("./tradutor-assembly-x64"), exports);
28978
28983
  __exportStar(require("./tradutor-assemblyscript"), exports);
28979
- __exportStar(require("./tradutor-calango"), exports);
28984
+ __exportStar(require("./tradutor-reverso-calango"), exports);
28980
28985
  __exportStar(require("./tradutor-elixir"), exports);
28981
28986
  __exportStar(require("./tradutor-javascript"), exports);
28982
28987
  __exportStar(require("./tradutor-mermaidjs"), exports);
@@ -28987,7 +28992,7 @@ __exportStar(require("./tradutor-reverso-python"), exports);
28987
28992
  __exportStar(require("./tradutor-reverso-tenda"), exports);
28988
28993
  __exportStar(require("./tradutor-ruby"), exports);
28989
28994
 
28990
- },{"./tradutor-assembly-arm":241,"./tradutor-assembly-risc-v":242,"./tradutor-assembly-x64":243,"./tradutor-assemblyscript":244,"./tradutor-calango":245,"./tradutor-elixir":246,"./tradutor-javascript":247,"./tradutor-mermaidjs":248,"./tradutor-portugol-ipt":249,"./tradutor-python":250,"./tradutor-reverso-javascript":251,"./tradutor-reverso-python":252,"./tradutor-reverso-tenda":253,"./tradutor-ruby":254,"./tradutor-webassembly":255}],233:[function(require,module,exports){
28995
+ },{"./tradutor-assembly-arm":241,"./tradutor-assembly-risc-v":242,"./tradutor-assembly-x64":243,"./tradutor-assemblyscript":244,"./tradutor-elixir":245,"./tradutor-javascript":246,"./tradutor-mermaidjs":247,"./tradutor-portugol-ipt":248,"./tradutor-python":249,"./tradutor-reverso-calango":250,"./tradutor-reverso-javascript":251,"./tradutor-reverso-python":252,"./tradutor-reverso-tenda":253,"./tradutor-ruby":254,"./tradutor-webassembly":255}],233:[function(require,module,exports){
28991
28996
  "use strict";
28992
28997
  Object.defineProperty(exports, "__esModule", { value: true });
28993
28998
  exports.ArestaFluxograma = void 0;
@@ -44975,61 +44980,6 @@ exports.TradutorAssemblyScript = TradutorAssemblyScript;
44975
44980
 
44976
44981
  },{"../construtos":62,"../declaracoes":110,"../tipos-de-simbolos/delegua":224}],245:[function(require,module,exports){
44977
44982
  "use strict";
44978
- Object.defineProperty(exports, "__esModule", { value: true });
44979
- exports.TradutorCalango = void 0;
44980
- class TradutorCalango {
44981
- constructor() {
44982
- this.indentacao = 0;
44983
- this.dicionarioConstrutos = {
44984
- FormatacaoEscrita: this.traduzirConstrutoFormatacaoEscrita.bind(this),
44985
- Literal: this.traduzirConstrutoLiteral.bind(this),
44986
- };
44987
- this.dicionarioDeclaracoes = {
44988
- Escreva: this.traduzirDeclaracaoEscreva.bind(this),
44989
- EscrevaMesmaLinha: this.traduzirDeclaracaoEscrevaMesmaLinha.bind(this),
44990
- };
44991
- }
44992
- traduzirConstrutoFormatacaoEscrita(formatacaoEscrita) {
44993
- const avaliacaoExpressao = this.dicionarioConstrutos[formatacaoEscrita.expressao.constructor.name](formatacaoEscrita.expressao);
44994
- return `${avaliacaoExpressao}`;
44995
- }
44996
- traduzirConstrutoLiteral(literal) {
44997
- if (typeof literal.valor === 'string')
44998
- return `'${literal.valor}'`;
44999
- return String(literal.valor);
45000
- }
45001
- traduzirDeclaracaoEscreva(declaracaoEscreva) {
45002
- let resultado = 'escreva(';
45003
- for (const argumento of declaracaoEscreva.argumentos) {
45004
- const valor = this.dicionarioConstrutos[argumento.constructor.name](argumento);
45005
- resultado += valor + ', ';
45006
- }
45007
- resultado = resultado.slice(0, -2);
45008
- resultado += ')';
45009
- return resultado;
45010
- }
45011
- traduzirDeclaracaoEscrevaMesmaLinha(declaracaoEscreva) {
45012
- let resultado = 'escreva(';
45013
- for (const argumento of declaracaoEscreva.argumentos) {
45014
- const valor = this.dicionarioConstrutos[argumento.constructor.name](argumento);
45015
- resultado += valor + ', ';
45016
- }
45017
- resultado = resultado.slice(0, -2);
45018
- resultado += ')';
45019
- return resultado;
45020
- }
45021
- traduzir(declaracoes) {
45022
- let resultado = '';
45023
- for (const declaracao of declaracoes) {
45024
- resultado += `${this.dicionarioDeclaracoes[declaracao.constructor.name](declaracao)} \n`;
45025
- }
45026
- return resultado;
45027
- }
45028
- }
45029
- exports.TradutorCalango = TradutorCalango;
45030
-
45031
- },{}],246:[function(require,module,exports){
45032
- "use strict";
45033
44983
  var __importDefault = (this && this.__importDefault) || function (mod) {
45034
44984
  return (mod && mod.__esModule) ? mod : { "default": mod };
45035
44985
  };
@@ -45979,7 +45929,7 @@ class TradutorElixir {
45979
45929
  }
45980
45930
  exports.TradutorElixir = TradutorElixir;
45981
45931
 
45982
- },{"../tipos-de-simbolos/delegua":224}],247:[function(require,module,exports){
45932
+ },{"../tipos-de-simbolos/delegua":224}],246:[function(require,module,exports){
45983
45933
  "use strict";
45984
45934
  var __importDefault = (this && this.__importDefault) || function (mod) {
45985
45935
  return (mod && mod.__esModule) ? mod : { "default": mod };
@@ -46771,7 +46721,7 @@ class TradutorJavaScript {
46771
46721
  }
46772
46722
  exports.TradutorJavaScript = TradutorJavaScript;
46773
46723
 
46774
- },{"../construtos":62,"../declaracoes":110,"../tipos-de-simbolos/delegua":224}],248:[function(require,module,exports){
46724
+ },{"../construtos":62,"../declaracoes":110,"../tipos-de-simbolos/delegua":224}],247:[function(require,module,exports){
46775
46725
  "use strict";
46776
46726
  var __importDefault = (this && this.__importDefault) || function (mod) {
46777
46727
  return (mod && mod.__esModule) ? mod : { "default": mod };
@@ -47595,7 +47545,7 @@ class TradutorMermaidJs {
47595
47545
  }
47596
47546
  exports.TradutorMermaidJs = TradutorMermaidJs;
47597
47547
 
47598
- },{"../construtos":62,"../declaracoes":110,"../tipos-de-simbolos/delegua":224,"./mermaid":234}],249:[function(require,module,exports){
47548
+ },{"../construtos":62,"../declaracoes":110,"../tipos-de-simbolos/delegua":224,"./mermaid":234}],248:[function(require,module,exports){
47599
47549
  "use strict";
47600
47550
  Object.defineProperty(exports, "__esModule", { value: true });
47601
47551
  exports.TradutorPortugolIpt = void 0;
@@ -47657,7 +47607,7 @@ class TradutorPortugolIpt {
47657
47607
  }
47658
47608
  exports.TradutorPortugolIpt = TradutorPortugolIpt;
47659
47609
 
47660
- },{"../avaliador-sintatico/dialetos":17,"../lexador/dialetos":194}],250:[function(require,module,exports){
47610
+ },{"../avaliador-sintatico/dialetos":17,"../lexador/dialetos":194}],249:[function(require,module,exports){
47661
47611
  "use strict";
47662
47612
  var __importDefault = (this && this.__importDefault) || function (mod) {
47663
47613
  return (mod && mod.__esModule) ? mod : { "default": mod };
@@ -48342,7 +48292,359 @@ class TradutorPython {
48342
48292
  }
48343
48293
  exports.TradutorPython = TradutorPython;
48344
48294
 
48345
- },{"../construtos":62,"../declaracoes":110,"../tipos-de-simbolos/delegua":224}],251:[function(require,module,exports){
48295
+ },{"../construtos":62,"../declaracoes":110,"../tipos-de-simbolos/delegua":224}],250:[function(require,module,exports){
48296
+ "use strict";
48297
+ var __importDefault = (this && this.__importDefault) || function (mod) {
48298
+ return (mod && mod.__esModule) ? mod : { "default": mod };
48299
+ };
48300
+ Object.defineProperty(exports, "__esModule", { value: true });
48301
+ exports.TradutorReversoCalango = void 0;
48302
+ const calango_1 = __importDefault(require("../tipos-de-simbolos/calango"));
48303
+ class TradutorReversoCalango {
48304
+ constructor() {
48305
+ this.indentacao = 0;
48306
+ this.dicionarioConstrutos = {
48307
+ AcessoIndiceVariavel: this.traduzirConstrutoAcessoIndiceVariavel.bind(this),
48308
+ Agrupamento: this.traduzirConstrutoAgrupamento.bind(this),
48309
+ AtribuicaoPorIndice: this.traduzirConstrutoAtribuicaoPorIndice.bind(this),
48310
+ Atribuir: this.traduzirConstrutoAtribuir.bind(this),
48311
+ Binario: this.traduzirConstrutoBinario.bind(this),
48312
+ Chamada: this.traduzirConstrutoChamada.bind(this),
48313
+ FormatacaoEscrita: this.traduzirConstrutoFormatacaoEscrita.bind(this),
48314
+ FuncaoConstruto: this.traduzirConstrutoFuncao.bind(this),
48315
+ Leia: this.traduzirConstrutoLeia.bind(this),
48316
+ Literal: this.traduzirConstrutoLiteral.bind(this),
48317
+ Logico: this.traduzirConstrutoLogico.bind(this),
48318
+ Unario: this.traduzirConstrutoUnario.bind(this),
48319
+ Variavel: this.traduzirConstrutoVariavel.bind(this),
48320
+ Vetor: this.traduzirConstrutoVetor.bind(this),
48321
+ };
48322
+ this.dicionarioDeclaracoes = {
48323
+ Bloco: this.traduzirDeclaracaoBloco.bind(this),
48324
+ Enquanto: this.traduzirDeclaracaoEnquanto.bind(this),
48325
+ Escolha: this.traduzirDeclaracaoEscolha.bind(this),
48326
+ Escreva: this.traduzirDeclaracaoEscreva.bind(this),
48327
+ EscrevaMesmaLinha: this.traduzirDeclaracaoEscrevaMesmaLinha.bind(this),
48328
+ Expressao: this.traduzirDeclaracaoExpressao.bind(this),
48329
+ Fazer: this.traduzirDeclaracaoFazer.bind(this),
48330
+ FuncaoDeclaracao: this.traduzirDeclaracaoFuncao.bind(this),
48331
+ Para: this.traduzirDeclaracaoPara.bind(this),
48332
+ Retorna: this.traduzirDeclaracaoRetorna.bind(this),
48333
+ Se: this.traduzirDeclaracaoSe.bind(this),
48334
+ Sustar: this.traduzirDeclaracaoSustar.bind(this),
48335
+ Var: this.traduzirDeclaracaoVar.bind(this),
48336
+ };
48337
+ }
48338
+ traduzirSimboloOperador(simbolo) {
48339
+ switch (simbolo?.tipo) {
48340
+ case calango_1.default.ADICAO:
48341
+ return '+';
48342
+ case calango_1.default.SUBTRACAO:
48343
+ return '-';
48344
+ case calango_1.default.MULTIPLICACAO:
48345
+ return '*';
48346
+ case calango_1.default.DIVISAO:
48347
+ return '/';
48348
+ case calango_1.default.DIVISAO_INTEIRA:
48349
+ return '\\';
48350
+ case calango_1.default.MODULO:
48351
+ return '%';
48352
+ case calango_1.default.EXPONENCIACAO:
48353
+ return '^';
48354
+ case calango_1.default.IGUAL:
48355
+ case calango_1.default.IGUAL_IGUAL:
48356
+ return '==';
48357
+ case calango_1.default.IGUAL_ATRIBUICAO:
48358
+ return '=';
48359
+ case calango_1.default.DIFERENTE:
48360
+ return '!=';
48361
+ case calango_1.default.MAIOR:
48362
+ return '>';
48363
+ case calango_1.default.MAIOR_IGUAL:
48364
+ return '>=';
48365
+ case calango_1.default.MENOR:
48366
+ return '<';
48367
+ case calango_1.default.MENOR_IGUAL:
48368
+ return '<=';
48369
+ case calango_1.default.E:
48370
+ return 'e';
48371
+ case calango_1.default.OU:
48372
+ return 'ou';
48373
+ case calango_1.default.NEGACAO:
48374
+ return 'nao';
48375
+ default:
48376
+ return simbolo?.lexema || '';
48377
+ }
48378
+ }
48379
+ traduzirQualquer(elemento) {
48380
+ if (!elemento) {
48381
+ return '';
48382
+ }
48383
+ const nomeConstrutor = elemento.constructor.name;
48384
+ if (this.dicionarioDeclaracoes.hasOwnProperty(nomeConstrutor)) {
48385
+ return this.dicionarioDeclaracoes[nomeConstrutor](elemento);
48386
+ }
48387
+ if (this.dicionarioConstrutos.hasOwnProperty(nomeConstrutor)) {
48388
+ return this.dicionarioConstrutos[nomeConstrutor](elemento);
48389
+ }
48390
+ throw new Error(`Elemento não suportado pelo tradutor Calango reverso: ${nomeConstrutor}`);
48391
+ }
48392
+ traduzirParametro(parametro) {
48393
+ const nome = parametro?.nome?.lexema;
48394
+ const tipo = parametro?.tipoDado;
48395
+ if (!nome) {
48396
+ return '';
48397
+ }
48398
+ if (!tipo || tipo === 'qualquer') {
48399
+ return nome;
48400
+ }
48401
+ return `${nome}: ${tipo}`;
48402
+ }
48403
+ logicaComumBlocoEscopo(declaracoes) {
48404
+ let resultado = '{\n';
48405
+ this.indentacao += 4;
48406
+ for (const declaracaoOuConstruto of declaracoes || []) {
48407
+ const traducao = this.traduzirQualquer(declaracaoOuConstruto);
48408
+ if (!traducao) {
48409
+ continue;
48410
+ }
48411
+ resultado += `${' '.repeat(this.indentacao)}${traducao}\n`;
48412
+ }
48413
+ this.indentacao -= 4;
48414
+ resultado += `${' '.repeat(this.indentacao)}}`;
48415
+ return resultado;
48416
+ }
48417
+ traduzirConstrutoAcessoIndiceVariavel(acessoIndiceVariavel) {
48418
+ const entidade = this.traduzirQualquer(acessoIndiceVariavel.entidadeChamada);
48419
+ const indice = this.traduzirQualquer(acessoIndiceVariavel.indice);
48420
+ return `${entidade}[${indice}]`;
48421
+ }
48422
+ traduzirConstrutoAgrupamento(agrupamento) {
48423
+ return `(${this.traduzirQualquer(agrupamento.expressao)})`;
48424
+ }
48425
+ traduzirConstrutoAtribuicaoPorIndice(atribuicao) {
48426
+ const objeto = this.traduzirQualquer(atribuicao.objeto);
48427
+ const indice = this.traduzirQualquer(atribuicao.indice);
48428
+ const valor = this.traduzirQualquer(atribuicao.valor);
48429
+ return `${objeto}[${indice}] = ${valor}`;
48430
+ }
48431
+ traduzirConstrutoAtribuir(atribuir) {
48432
+ let alvo = this.traduzirQualquer(atribuir.alvo);
48433
+ if (atribuir.indice) {
48434
+ alvo += `[${this.traduzirQualquer(atribuir.indice)}]`;
48435
+ }
48436
+ const operador = atribuir.simboloOperador
48437
+ ? this.traduzirSimboloOperador(atribuir.simboloOperador)
48438
+ : '=';
48439
+ const valor = this.traduzirQualquer(atribuir.valor);
48440
+ return `${alvo} ${operador} ${valor}`;
48441
+ }
48442
+ traduzirConstrutoBinario(binario) {
48443
+ const esquerda = this.traduzirQualquer(binario.esquerda);
48444
+ const direita = this.traduzirQualquer(binario.direita);
48445
+ const operador = this.traduzirSimboloOperador(binario.operador);
48446
+ return `${esquerda} ${operador} ${direita}`;
48447
+ }
48448
+ traduzirConstrutoChamada(chamada) {
48449
+ const entidade = this.traduzirQualquer(chamada.entidadeChamada);
48450
+ const argumentos = (chamada.argumentos || []).map((argumento) => this.traduzirQualquer(argumento));
48451
+ return `${entidade}(${argumentos.join(', ')})`;
48452
+ }
48453
+ traduzirConstrutoFormatacaoEscrita(formatacaoEscrita) {
48454
+ const avaliacaoExpressao = this.traduzirQualquer(formatacaoEscrita.expressao);
48455
+ return `${avaliacaoExpressao}`;
48456
+ }
48457
+ traduzirConstrutoFuncao(funcaoConstruto) {
48458
+ const parametros = (funcaoConstruto.parametros || [])
48459
+ .map((parametro) => this.traduzirParametro(parametro))
48460
+ .filter((p) => p)
48461
+ .join(', ');
48462
+ let resultado = `funcao(${parametros}) `;
48463
+ resultado += this.logicaComumBlocoEscopo(funcaoConstruto.corpo);
48464
+ return resultado;
48465
+ }
48466
+ traduzirConstrutoLeia(leia) {
48467
+ const argumentos = (leia.argumentos || []).map((argumento) => this.traduzirQualquer(argumento));
48468
+ return `leia(${argumentos.join(', ')})`;
48469
+ }
48470
+ traduzirConstrutoLiteral(literal) {
48471
+ if (typeof literal.valor === 'string') {
48472
+ const valorEscapado = literal.valor.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
48473
+ return `'${valorEscapado}'`;
48474
+ }
48475
+ if (literal.valor === null || literal.valor === undefined) {
48476
+ return 'nulo';
48477
+ }
48478
+ if (typeof literal.valor === 'boolean') {
48479
+ return literal.valor ? 'verdadeiro' : 'falso';
48480
+ }
48481
+ return String(literal.valor);
48482
+ }
48483
+ traduzirConstrutoLogico(logico) {
48484
+ const esquerda = this.traduzirQualquer(logico.esquerda);
48485
+ const direita = this.traduzirQualquer(logico.direita);
48486
+ const operador = this.traduzirSimboloOperador(logico.operador);
48487
+ return `${esquerda} ${operador} ${direita}`;
48488
+ }
48489
+ traduzirConstrutoUnario(unario) {
48490
+ const operador = this.traduzirSimboloOperador(unario.operador);
48491
+ const operando = this.traduzirQualquer(unario.operando);
48492
+ if (unario.incidenciaOperador === 'DEPOIS') {
48493
+ return `${operando}${operador}`;
48494
+ }
48495
+ if (operador === 'nao') {
48496
+ return `${operador} ${operando}`;
48497
+ }
48498
+ return `${operador}${operando}`;
48499
+ }
48500
+ traduzirConstrutoVariavel(variavel) {
48501
+ return variavel.simbolo.lexema;
48502
+ }
48503
+ traduzirConstrutoVetor(vetor) {
48504
+ const elementos = (vetor.elementos || []).map((elemento) => this.traduzirQualquer(elemento));
48505
+ return `[${elementos.join(', ')}]`;
48506
+ }
48507
+ traduzirDeclaracaoBloco(bloco) {
48508
+ return this.logicaComumBlocoEscopo(bloco.declaracoes);
48509
+ }
48510
+ traduzirDeclaracaoEnquanto(declaracaoEnquanto) {
48511
+ const condicao = this.traduzirQualquer(declaracaoEnquanto.condicao);
48512
+ const corpo = this.traduzirDeclaracaoBloco(declaracaoEnquanto.corpo);
48513
+ return `enquanto (${condicao}) ${corpo}`;
48514
+ }
48515
+ traduzirDeclaracaoEscolha(declaracaoEscolha) {
48516
+ const expressao = this.traduzirQualquer(declaracaoEscolha.identificadorOuLiteral);
48517
+ let resultado = `escolha (${expressao}) {\n`;
48518
+ this.indentacao += 4;
48519
+ for (const caminho of declaracaoEscolha.caminhos || []) {
48520
+ for (const condicao of caminho.condicoes || []) {
48521
+ resultado += `${' '.repeat(this.indentacao)}caso ${this.traduzirQualquer(condicao)}:\n`;
48522
+ }
48523
+ this.indentacao += 4;
48524
+ for (const declaracao of caminho.declaracoes || []) {
48525
+ const traducao = this.traduzirQualquer(declaracao);
48526
+ if (traducao) {
48527
+ resultado += `${' '.repeat(this.indentacao)}${traducao}\n`;
48528
+ }
48529
+ }
48530
+ this.indentacao -= 4;
48531
+ }
48532
+ if (declaracaoEscolha.caminhoPadrao) {
48533
+ resultado += `${' '.repeat(this.indentacao)}padrao:\n`;
48534
+ this.indentacao += 4;
48535
+ for (const declaracao of declaracaoEscolha.caminhoPadrao.declaracoes || []) {
48536
+ const traducao = this.traduzirQualquer(declaracao);
48537
+ if (traducao) {
48538
+ resultado += `${' '.repeat(this.indentacao)}${traducao}\n`;
48539
+ }
48540
+ }
48541
+ this.indentacao -= 4;
48542
+ }
48543
+ this.indentacao -= 4;
48544
+ resultado += `${' '.repeat(this.indentacao)}}`;
48545
+ return resultado;
48546
+ }
48547
+ traduzirDeclaracaoEscreva(declaracaoEscreva) {
48548
+ let resultado = 'escreva(';
48549
+ for (const argumento of declaracaoEscreva.argumentos) {
48550
+ const valor = this.traduzirQualquer(argumento);
48551
+ resultado += valor + ', ';
48552
+ }
48553
+ if (declaracaoEscreva.argumentos.length > 0) {
48554
+ resultado = resultado.slice(0, -2);
48555
+ }
48556
+ resultado += ')';
48557
+ return resultado;
48558
+ }
48559
+ traduzirDeclaracaoEscrevaMesmaLinha(declaracaoEscreva) {
48560
+ let resultado = 'escreva(';
48561
+ for (const argumento of declaracaoEscreva.argumentos) {
48562
+ const valor = this.traduzirQualquer(argumento);
48563
+ resultado += valor + ', ';
48564
+ }
48565
+ if (declaracaoEscreva.argumentos.length > 0) {
48566
+ resultado = resultado.slice(0, -2);
48567
+ }
48568
+ resultado += ')';
48569
+ return resultado;
48570
+ }
48571
+ traduzirDeclaracaoExpressao(expressao) {
48572
+ return this.traduzirQualquer(expressao.expressao);
48573
+ }
48574
+ traduzirDeclaracaoFazer(fazer) {
48575
+ const corpo = this.traduzirDeclaracaoBloco(fazer.caminhoFazer);
48576
+ const condicao = this.traduzirQualquer(fazer.condicaoEnquanto);
48577
+ return `fazer ${corpo} enquanto (${condicao})`;
48578
+ }
48579
+ traduzirDeclaracaoFuncao(declaracaoFuncao) {
48580
+ const parametros = (declaracaoFuncao.funcao.parametros || [])
48581
+ .map((parametro) => this.traduzirParametro(parametro))
48582
+ .filter((p) => p)
48583
+ .join(', ');
48584
+ const tipoRetorno = declaracaoFuncao.tipo && declaracaoFuncao.tipo !== 'qualquer' && declaracaoFuncao.tipo !== 'vazio'
48585
+ ? `: ${declaracaoFuncao.tipo}`
48586
+ : '';
48587
+ let resultado = `funcao ${declaracaoFuncao.simbolo.lexema}(${parametros})${tipoRetorno} `;
48588
+ resultado += this.logicaComumBlocoEscopo(declaracaoFuncao.funcao.corpo);
48589
+ return resultado;
48590
+ }
48591
+ traduzirDeclaracaoPara(declaracaoPara) {
48592
+ let inicializador = '';
48593
+ if (Array.isArray(declaracaoPara.inicializador)) {
48594
+ inicializador = declaracaoPara.inicializador
48595
+ .map((declaracao) => this.traduzirQualquer(declaracao))
48596
+ .join(', ');
48597
+ }
48598
+ else if (declaracaoPara.inicializador) {
48599
+ inicializador = this.traduzirQualquer(declaracaoPara.inicializador);
48600
+ }
48601
+ const condicao = this.traduzirQualquer(declaracaoPara.condicao);
48602
+ const incremento = this.traduzirQualquer(declaracaoPara.incrementar);
48603
+ const corpo = this.traduzirDeclaracaoBloco(declaracaoPara.corpo);
48604
+ return `para (${inicializador}; ${condicao}; ${incremento}) ${corpo}`;
48605
+ }
48606
+ traduzirDeclaracaoRetorna(retorna) {
48607
+ if (!retorna.valor) {
48608
+ return 'retorna';
48609
+ }
48610
+ return `retorna ${this.traduzirQualquer(retorna.valor)}`;
48611
+ }
48612
+ traduzirDeclaracaoSe(declaracaoSe) {
48613
+ const condicao = this.traduzirQualquer(declaracaoSe.condicao);
48614
+ const caminhoEntao = this.traduzirQualquer(declaracaoSe.caminhoEntao);
48615
+ let resultado = `se (${condicao}) ${caminhoEntao}`;
48616
+ const caminhosSeSenao = declaracaoSe.caminhosSeSenao || [];
48617
+ for (const caminhoSeSenao of caminhosSeSenao) {
48618
+ resultado += ` senao se (${this.traduzirQualquer(caminhoSeSenao.condicao)}) ${this.traduzirQualquer(caminhoSeSenao.caminho)}`;
48619
+ }
48620
+ if (declaracaoSe.caminhoSenao) {
48621
+ resultado += ` senao ${this.traduzirQualquer(declaracaoSe.caminhoSenao)}`;
48622
+ }
48623
+ return resultado;
48624
+ }
48625
+ traduzirDeclaracaoSustar(_sustar) {
48626
+ return 'sustar';
48627
+ }
48628
+ traduzirDeclaracaoVar(declaracaoVar) {
48629
+ if (!declaracaoVar.inicializador) {
48630
+ return `var ${declaracaoVar.simbolo.lexema}`;
48631
+ }
48632
+ return `var ${declaracaoVar.simbolo.lexema} = ${this.traduzirQualquer(declaracaoVar.inicializador)}`;
48633
+ }
48634
+ traduzir(declaracoes) {
48635
+ const linhas = [];
48636
+ for (const declaracao of declaracoes) {
48637
+ const traducao = this.traduzirQualquer(declaracao);
48638
+ if (traducao) {
48639
+ linhas.push(traducao);
48640
+ }
48641
+ }
48642
+ return linhas.join('\n');
48643
+ }
48644
+ }
48645
+ exports.TradutorReversoCalango = TradutorReversoCalango;
48646
+
48647
+ },{"../tipos-de-simbolos/calango":222}],251:[function(require,module,exports){
48346
48648
  "use strict";
48347
48649
  Object.defineProperty(exports, "__esModule", { value: true });
48348
48650
  exports.TradutorReversoJavaScript = void 0;
@@ -48742,75 +49044,632 @@ exports.TradutorReversoJavaScript = TradutorReversoJavaScript;
48742
49044
  Object.defineProperty(exports, "__esModule", { value: true });
48743
49045
  exports.TradutorReversoPython = void 0;
48744
49046
  const antlr4ts_1 = require("antlr4ts");
48745
- const python3_parser_1 = require("./python/python3-parser");
48746
- const ParseTreeWalker_1 = require("antlr4ts/tree/ParseTreeWalker");
49047
+ const AbstractParseTreeVisitor_1 = require("antlr4ts/tree/AbstractParseTreeVisitor");
48747
49048
  const python3_lexer_1 = require("./python/python3-lexer");
49049
+ const python3_parser_1 = require("./python/python3-parser");
48748
49050
  /**
48749
49051
  * Tradutor reverso de Python para Delégua.
48750
- * Utiliza o ecossistema do ANTLR para percorrer código em
49052
+ * Utiliza o visitor do ANTLR para percorrer a árvore sintática em
48751
49053
  * Python e traduzir para Delégua.
48752
49054
  */
48753
- class TradutorReversoPython {
48754
- /**
48755
- * Aqui é preciso contar se o contexto tem filhos.
48756
- * alguns casos em que este código é executado mais
48757
- * de uma vez por algum motivo.
48758
- * @param ctx O contexto da atribuição.
48759
- */
48760
- enterSimple_assign(ctx) {
48761
- if (ctx.childCount > 0) {
48762
- this.resultado += ' = ';
49055
+ class TradutorReversoPython extends AbstractParseTreeVisitor_1.AbstractParseTreeVisitor {
49056
+ constructor() {
49057
+ super(...arguments);
49058
+ // Funções globais Python Delégua
49059
+ this.mapeamentoFuncoes = {
49060
+ print: 'escreva',
49061
+ input: 'leia',
49062
+ len: 'tamanho',
49063
+ int: 'inteiro',
49064
+ float: 'real',
49065
+ str: 'texto',
49066
+ bool: 'logico',
49067
+ type: 'tipoDe',
49068
+ range: 'intervalo',
49069
+ abs: 'absoluto',
49070
+ round: 'arredondar',
49071
+ min: 'minimo',
49072
+ max: 'maximo',
49073
+ sum: 'somar',
49074
+ };
49075
+ // Métodos de instância Python → Delégua
49076
+ this.mapeamentoMetodos = {
49077
+ // Lista / vetor
49078
+ append: 'adicionar',
49079
+ pop: 'removerUltimo',
49080
+ reverse: 'inverter',
49081
+ sort: 'ordenar',
49082
+ clear: 'limpar',
49083
+ // Texto / string
49084
+ upper: 'maiusculo',
49085
+ lower: 'minusculo',
49086
+ strip: 'aparar',
49087
+ lstrip: 'aparar',
49088
+ rstrip: 'aparar',
49089
+ split: 'dividir',
49090
+ join: 'juntar',
49091
+ startswith: 'iniciaCom',
49092
+ endswith: 'terminaCom',
49093
+ replace: 'substituir',
49094
+ find: 'encontrar',
49095
+ count: 'contar',
49096
+ // Dicionário
49097
+ keys: 'chaves',
49098
+ values: 'valores',
49099
+ items: 'itens',
49100
+ };
49101
+ }
49102
+ defaultResult() {
49103
+ return '';
49104
+ }
49105
+ aggregateResult(aggregate, nextResult) {
49106
+ return aggregate + nextResult;
49107
+ }
49108
+ visitTerminal(node) {
49109
+ return node.text;
49110
+ }
49111
+ visitFile_input(ctx) {
49112
+ return ctx.stmt().map((s) => this.visit(s)).join('\n');
49113
+ }
49114
+ visitSimple_stmt(ctx) {
49115
+ return ctx.small_stmt().map((s) => this.visit(s)).join('; ');
49116
+ }
49117
+ visitExpr_stmt(ctx) {
49118
+ const lhs = this.visit(ctx.testlist_star_expr());
49119
+ const simpleAssign = ctx.simple_assign();
49120
+ if (simpleAssign && simpleAssign.childCount > 0) {
49121
+ const rhs = this.visitSimple_assign(simpleAssign);
49122
+ // Atribuições a atributos (a.b = x) ou índices (a[i] = x) não usam 'var'
49123
+ const prefixo = lhs.includes('.') || lhs.includes('[') ? '' : 'var ';
49124
+ return `${prefixo}${lhs} = ${rhs}`;
49125
+ }
49126
+ if (ctx.augassign()) {
49127
+ const op = this.visitAugassign(ctx.augassign());
49128
+ const testlist = ctx.testlist();
49129
+ const yieldExpr = ctx.yield_expr();
49130
+ const rhs = testlist
49131
+ ? this.visit(testlist)
49132
+ : yieldExpr
49133
+ ? this.visit(yieldExpr)
49134
+ : '';
49135
+ return `${lhs} ${op} ${rhs}`;
49136
+ }
49137
+ return lhs;
49138
+ }
49139
+ visitSimple_assign(ctx) {
49140
+ const exprs = ctx.testlist_star_expr();
49141
+ return this.visit(exprs[exprs.length - 1]);
49142
+ }
49143
+ visitAugassign(ctx) {
49144
+ if (ctx.ADD_ASSIGN())
49145
+ return '+=';
49146
+ if (ctx.SUB_ASSIGN())
49147
+ return '-=';
49148
+ if (ctx.MULT_ASSIGN())
49149
+ return '*=';
49150
+ if (ctx.DIV_ASSIGN())
49151
+ return '/=';
49152
+ if (ctx.MOD_ASSIGN())
49153
+ return '%=';
49154
+ if (ctx.AND_ASSIGN())
49155
+ return '&=';
49156
+ if (ctx.OR_ASSIGN())
49157
+ return '|=';
49158
+ if (ctx.XOR_ASSIGN())
49159
+ return '^=';
49160
+ if (ctx.LEFT_SHIFT_ASSIGN())
49161
+ return '<<=';
49162
+ if (ctx.RIGHT_SHIFT_ASSIGN())
49163
+ return '>>=';
49164
+ if (ctx.POWER_ASSIGN())
49165
+ return '**=';
49166
+ if (ctx.IDIV_ASSIGN())
49167
+ return '//=';
49168
+ return ctx.text;
49169
+ }
49170
+ visitTestlist_star_expr(ctx) {
49171
+ return ctx.test().map((t) => this.visit(t)).join(', ');
49172
+ }
49173
+ visitTestlist(ctx) {
49174
+ return ctx.test().map((t) => this.visit(t)).join(', ');
49175
+ }
49176
+ visitTest(ctx) {
49177
+ const orTests = ctx.or_test();
49178
+ if (orTests.length === 1)
49179
+ return this.visit(orTests[0]);
49180
+ const lambdef = ctx.lambdef();
49181
+ if (lambdef)
49182
+ return this.visit(lambdef);
49183
+ // Expressão ternária (a if cond else b) — implementada em fase futura
49184
+ return this.visitChildren(ctx);
49185
+ }
49186
+ visitOr_test(ctx) {
49187
+ return ctx.and_test().map((t) => this.visit(t)).join(' ou ');
49188
+ }
49189
+ visitAnd_test(ctx) {
49190
+ return ctx.not_test().map((t) => this.visit(t)).join(' e ');
49191
+ }
49192
+ visitNot_test(ctx) {
49193
+ if (ctx.NOT()) {
49194
+ return `nao ${this.visit(ctx.not_test())}`;
49195
+ }
49196
+ const comp = ctx.comparison();
49197
+ if (comp)
49198
+ return this.visit(comp);
49199
+ return this.visitChildren(ctx);
49200
+ }
49201
+ visitComparison(ctx) {
49202
+ const exprs = ctx.expr();
49203
+ if (exprs.length === 1)
49204
+ return this.visit(exprs[0]);
49205
+ const ops = ctx.comp_op();
49206
+ let resultado = this.visit(exprs[0]);
49207
+ for (let i = 0; i < ops.length; i++) {
49208
+ resultado += ` ${this.visitComp_op(ops[i])} ${this.visit(exprs[i + 1])}`;
48763
49209
  }
49210
+ return resultado;
48764
49211
  }
48765
- /**
48766
- * Aparentemente é o melhor lugar para escrever quebras de linha.
48767
- * @param ctx Contexto da instrução.
48768
- */
48769
- exitStmt(ctx) {
48770
- this.resultado += ctx.stop.text;
49212
+ visitComp_op(ctx) {
49213
+ if (ctx.LESS_THAN())
49214
+ return '<';
49215
+ if (ctx.GREATER_THAN())
49216
+ return '>';
49217
+ if (ctx.EQUALS())
49218
+ return '==';
49219
+ if (ctx.GT_EQ())
49220
+ return '>=';
49221
+ if (ctx.LT_EQ())
49222
+ return '<=';
49223
+ if (ctx.NOT_EQ_1() || ctx.NOT_EQ_2())
49224
+ return '!=';
49225
+ if (ctx.NOT() && ctx.IN())
49226
+ return 'nao em';
49227
+ if (ctx.IN())
49228
+ return 'em';
49229
+ if (ctx.NOT() && ctx.IS())
49230
+ return '!=';
49231
+ if (ctx.IS())
49232
+ return '==';
49233
+ return ctx.text;
49234
+ }
49235
+ visitArith_expr(ctx) {
49236
+ const termos = ctx.term();
49237
+ if (termos.length === 1)
49238
+ return this.visit(termos[0]);
49239
+ let resultado = this.visit(termos[0]);
49240
+ let idx = 1;
49241
+ for (let i = 1; i < ctx.childCount; i++) {
49242
+ const texto = ctx.getChild(i).text;
49243
+ if (texto === '+' || texto === '-') {
49244
+ resultado += ` ${texto} ${this.visit(termos[idx++])}`;
49245
+ }
49246
+ }
49247
+ return resultado;
48771
49248
  }
48772
- enterExpr_stmt(ctx) {
48773
- // console.log(ctx.start.text);
49249
+ visitTerm(ctx) {
49250
+ const fatores = ctx.factor();
49251
+ if (fatores.length === 1)
49252
+ return this.visit(fatores[0]);
49253
+ let resultado = this.visit(fatores[0]);
49254
+ let idx = 1;
49255
+ for (let i = 1; i < ctx.childCount; i++) {
49256
+ const texto = ctx.getChild(i).text;
49257
+ if (['*', '/', '%', '//', '@'].includes(texto)) {
49258
+ resultado += ` ${texto} ${this.visit(fatores[idx++])}`;
49259
+ }
49260
+ }
49261
+ return resultado;
48774
49262
  }
48775
- enterExpr(ctx) {
48776
- switch (ctx.start.text) {
48777
- case 'input':
48778
- this.resultado += 'leia(';
48779
- break;
48780
- case 'print':
48781
- this.resultado += 'escreva(';
48782
- break;
48783
- default:
48784
- this.resultado += ctx.start.text;
48785
- break;
49263
+ visitFactor(ctx) {
49264
+ if (ctx.ADD())
49265
+ return `+${this.visit(ctx.factor())}`;
49266
+ if (ctx.MINUS())
49267
+ return `-${this.visit(ctx.factor())}`;
49268
+ if (ctx.NOT_OP())
49269
+ return `~${this.visit(ctx.factor())}`;
49270
+ return this.visit(ctx.power());
49271
+ }
49272
+ visitPower(ctx) {
49273
+ const base = this.visit(ctx.atom_expr());
49274
+ if (ctx.POWER()) {
49275
+ return `${base} ** ${this.visit(ctx.factor())}`;
49276
+ }
49277
+ return base;
49278
+ }
49279
+ visitAtom_expr(ctx) {
49280
+ const textoAtomo = this.visit(ctx.atom());
49281
+ const trailers = ctx.trailer();
49282
+ if (trailers.length === 0)
49283
+ return textoAtomo;
49284
+ // Chamada de função simples: nome(args)
49285
+ if (trailers.length === 1 && trailers[0].OPEN_PAREN()) {
49286
+ const nomeFuncao = this.mapeamentoFuncoes[textoAtomo] ?? textoAtomo;
49287
+ const arglist = trailers[0].arglist();
49288
+ const args = arglist ? this.visit(arglist) : '';
49289
+ return `${nomeFuncao}(${args})`;
49290
+ }
49291
+ // Chamada de método: obj.metodo(args) → dois trailers: .nome e (args)
49292
+ if (trailers.length === 2 &&
49293
+ trailers[0].DOT() &&
49294
+ trailers[0].NAME() &&
49295
+ trailers[1].OPEN_PAREN()) {
49296
+ const nomeMetodoPython = trailers[0].NAME().text;
49297
+ const arglist = trailers[1].arglist();
49298
+ const args = arglist ? this.visit(arglist) : '';
49299
+ // join é invertido: sep.join(iteravel) → iteravel.juntar(sep)
49300
+ if (nomeMetodoPython === 'join') {
49301
+ return `${args}.juntar(${textoAtomo})`;
49302
+ }
49303
+ const nomeMetodoDelégua = this.mapeamentoMetodos[nomeMetodoPython] ?? nomeMetodoPython;
49304
+ return `${textoAtomo}.${nomeMetodoDelégua}(${args})`;
49305
+ }
49306
+ // Fallback: acesso a atributo, índice ou chamadas encadeadas
49307
+ let resultado = textoAtomo;
49308
+ for (const trailer of trailers) {
49309
+ resultado += this.visitTrailer(trailer);
48786
49310
  }
49311
+ return resultado;
48787
49312
  }
48788
- exitExpr(ctx) {
48789
- switch (ctx.start.text) {
48790
- case 'input':
48791
- case 'print':
48792
- this.resultado += ')';
49313
+ visitTrailer(ctx) {
49314
+ if (ctx.DOT() && ctx.NAME()) {
49315
+ return `.${ctx.NAME().text}`;
49316
+ }
49317
+ if (ctx.OPEN_BRACK()) {
49318
+ const subscriptlist = ctx.subscriptlist();
49319
+ const conteudo = subscriptlist ? this.visit(subscriptlist) : '';
49320
+ return `[${conteudo}]`;
49321
+ }
49322
+ if (ctx.OPEN_PAREN()) {
49323
+ const arglist = ctx.arglist();
49324
+ const args = arglist ? this.visit(arglist) : '';
49325
+ return `(${args})`;
49326
+ }
49327
+ return ctx.text;
49328
+ }
49329
+ visitAtom(ctx) {
49330
+ const nome = ctx.NAME();
49331
+ if (nome)
49332
+ return nome.text === 'self' ? 'isto' : nome.text;
49333
+ const numero = ctx.NUMBER();
49334
+ if (numero)
49335
+ return numero.text;
49336
+ if (ctx.TRUE())
49337
+ return 'verdadeiro';
49338
+ if (ctx.FALSE())
49339
+ return 'falso';
49340
+ if (ctx.NONE())
49341
+ return 'nulo';
49342
+ const strings = ctx.STRING();
49343
+ if (strings.length > 0)
49344
+ return strings.map((s) => s.text).join(' ');
49345
+ if (ctx.OPEN_PAREN()) {
49346
+ const testlistComp = ctx.testlist_comp();
49347
+ if (testlistComp) {
49348
+ // Tupla com vírgula → vetor em Delégua
49349
+ if (testlistComp.COMMA().length > 0) {
49350
+ return `[${this.visitTestlist_comp(testlistComp)}]`;
49351
+ }
49352
+ return `(${this.visitTestlist_comp(testlistComp)})`;
49353
+ }
49354
+ return '()';
49355
+ }
49356
+ if (ctx.OPEN_BRACK()) {
49357
+ const testlistComp = ctx.testlist_comp();
49358
+ if (testlistComp) {
49359
+ // Compreensão de lista: resultado já é um vetor, não envolve em []
49360
+ if (testlistComp.comp_for()) {
49361
+ return this.visitTestlist_comp(testlistComp);
49362
+ }
49363
+ return `[${this.visitTestlist_comp(testlistComp)}]`;
49364
+ }
49365
+ return '[]';
49366
+ }
49367
+ if (ctx.OPEN_BRACE()) {
49368
+ const dictorsetmaker = ctx.dictorsetmaker();
49369
+ if (dictorsetmaker)
49370
+ return `{${this.visitDictorsetmaker(dictorsetmaker)}}`;
49371
+ return '{}';
49372
+ }
49373
+ return ctx.text;
49374
+ }
49375
+ visitArglist(ctx) {
49376
+ return ctx.argument().map((a) => this.visit(a)).join(', ');
49377
+ }
49378
+ visitArgument(ctx) {
49379
+ const testes = ctx.test();
49380
+ if (testes.length === 1 && !ctx.ASSIGN()) {
49381
+ return this.visit(testes[0]);
49382
+ }
49383
+ // Argumento nomeado: nome=valor
49384
+ if (testes.length === 2 && ctx.ASSIGN()) {
49385
+ return `${this.visit(testes[0])} = ${this.visit(testes[1])}`;
49386
+ }
49387
+ return this.visitChildren(ctx);
49388
+ }
49389
+ visitTestlist_comp(ctx) {
49390
+ const compFor = ctx.comp_for();
49391
+ if (compFor) {
49392
+ return this.traduzirCompreensao(ctx.test(0), compFor);
49393
+ }
49394
+ return ctx.test().map((t) => this.visit(t)).join(', ');
49395
+ }
49396
+ traduzirCompreensao(exprCtx, compFor) {
49397
+ const variavel = this.visit(compFor.exprlist());
49398
+ const iteravel = this.visit(compFor.or_test());
49399
+ const expr = this.visit(exprCtx);
49400
+ const compIter = compFor.comp_iter();
49401
+ const compIf = compIter?.comp_if();
49402
+ if (compIf) {
49403
+ const cond = this.visitChildren(compIf.test_nocond());
49404
+ return `filtrarPor(${iteravel}, funcao(${variavel}) { retorna ${cond} }).mapear(funcao(${variavel}) { retorna ${expr} })`;
49405
+ }
49406
+ return `${iteravel}.mapear(funcao(${variavel}) { retorna ${expr} })`;
49407
+ }
49408
+ visitLambdef(ctx) {
49409
+ const varargslist = ctx.varargslist();
49410
+ const params = varargslist ? this.visitVarargslist(varargslist) : '';
49411
+ const corpo = this.visit(ctx.test());
49412
+ return `funcao(${params}) { retorna ${corpo} }`;
49413
+ }
49414
+ visitVarargslist(ctx) {
49415
+ const params = [];
49416
+ for (let i = 0; i < ctx.childCount;) {
49417
+ const texto = ctx.getChild(i).text;
49418
+ if (texto === ',') {
49419
+ i++;
49420
+ continue;
49421
+ }
49422
+ if (texto === '*' || texto === '**')
48793
49423
  break;
48794
- default:
49424
+ const nomeParam = texto;
49425
+ if (i + 1 < ctx.childCount && ctx.getChild(i + 1).text === '=') {
49426
+ const valorPadrao = this.visit(ctx.getChild(i + 2));
49427
+ params.push(`${nomeParam} = ${valorPadrao}`);
49428
+ i += 3;
49429
+ }
49430
+ else {
49431
+ params.push(nomeParam);
49432
+ i++;
49433
+ }
49434
+ }
49435
+ return params.join(', ');
49436
+ }
49437
+ visitDictorsetmaker(ctx) {
49438
+ const tests = ctx.test();
49439
+ if (ctx.COLON().length > 0) {
49440
+ // Dicionário: testes alternados como chave/valor
49441
+ const pares = [];
49442
+ for (let i = 0; i + 1 < tests.length; i += 2) {
49443
+ pares.push(`${this.visit(tests[i])}: ${this.visit(tests[i + 1])}`);
49444
+ }
49445
+ return pares.join(', ');
49446
+ }
49447
+ // Conjunto (set) — representado como lista em Delégua
49448
+ return tests.map((t) => this.visit(t)).join(', ');
49449
+ }
49450
+ visitSubscriptlist(ctx) {
49451
+ return ctx.subscript().map((s) => this.visitSubscript(s)).join(', ');
49452
+ }
49453
+ visitSubscript(ctx) {
49454
+ const tests = ctx.test();
49455
+ if (!ctx.COLON()) {
49456
+ // Índice simples
49457
+ return tests.length > 0 ? this.visit(tests[0]) : '';
49458
+ }
49459
+ // Fatia: [inicio]:fim → inicio..fim
49460
+ // Se o primeiro filho é ':', não há início (ex: texto[:3])
49461
+ const temInicio = ctx.childCount > 0 && ctx.getChild(0).text !== ':';
49462
+ const inicio = temInicio ? this.visit(tests[0]) : '';
49463
+ const fimIdx = temInicio ? 1 : 0;
49464
+ const fim = tests.length > fimIdx ? this.visit(tests[fimIdx]) : '';
49465
+ return `${inicio}..${fim}`;
49466
+ }
49467
+ // Retorna as linhas já indentadas de um bloco, sem os colchetes externos.
49468
+ visitLinhasCorpo(ctx) {
49469
+ const linhas = [];
49470
+ const simpleStmt = ctx.simple_stmt();
49471
+ if (simpleStmt) {
49472
+ linhas.push(` ${this.visit(simpleStmt)}`);
49473
+ }
49474
+ else {
49475
+ for (const stmt of ctx.stmt()) {
49476
+ const traduzido = this.visit(stmt);
49477
+ for (const linha of traduzido.split('\n')) {
49478
+ linhas.push(` ${linha}`);
49479
+ }
49480
+ }
49481
+ }
49482
+ return linhas;
49483
+ }
49484
+ // Traduz um bloco indentado (suite) para o corpo entre chaves de Delégua.
49485
+ visitCorpo(ctx) {
49486
+ return `{\n${this.visitLinhasCorpo(ctx).join('\n')}\n}`;
49487
+ }
49488
+ visitTry_stmt(ctx) {
49489
+ const corpoTente = this.visitCorpo(ctx.suite(0));
49490
+ let resultado = `tente ${corpoTente}`;
49491
+ const excepts = ctx.except_clause();
49492
+ if (excepts.length > 0) {
49493
+ // Detecta alias do erro na primeira cláusula except com `as nome`
49494
+ const alias = excepts.find((e) => e.NAME())?.NAME()?.text;
49495
+ // Junta todos os corpos except num único bloco pegue
49496
+ const todasLinhas = [];
49497
+ for (let i = 0; i < excepts.length; i++) {
49498
+ todasLinhas.push(...this.visitLinhasCorpo(ctx.suite(i + 1)));
49499
+ }
49500
+ const corpoPegue = `{\n${todasLinhas.join('\n')}\n}`;
49501
+ resultado += alias ? ` pegue (${alias}) ${corpoPegue}` : ` pegue ${corpoPegue}`;
49502
+ }
49503
+ // Índice da suite do else/finally começa após as suites de except
49504
+ let suiteIdx = 1 + excepts.length;
49505
+ if (ctx.ELSE()) {
49506
+ suiteIdx++; // else não tem equivalente em Delégua — ignora
49507
+ }
49508
+ if (ctx.FINALLY()) {
49509
+ resultado += ` finalmente ${this.visitCorpo(ctx.suite(suiteIdx))}`;
49510
+ }
49511
+ return resultado;
49512
+ }
49513
+ visitRaise_stmt(ctx) {
49514
+ const tests = ctx.test();
49515
+ if (tests.length === 0)
49516
+ return 'levante';
49517
+ return `levante ${this.visit(tests[0])}`;
49518
+ }
49519
+ visitWith_stmt(ctx) {
49520
+ const linhasCorpo = this.visitLinhasCorpo(ctx.suite());
49521
+ // Apenas itens com `as` podem ser traduzidos para `tendo...como`
49522
+ const itemsComAs = ctx.with_item().filter((item) => item.expr());
49523
+ if (itemsComAs.length === 0) {
49524
+ // Nenhum item com `as`: traduz apenas o corpo, sem tendo
49525
+ return linhasCorpo.map((l) => l.trimStart()).join('\n');
49526
+ }
49527
+ return this.construirTendo(itemsComAs, 0, linhasCorpo);
49528
+ }
49529
+ // Constrói blocos `tendo` aninhados para cada item do `with`.
49530
+ // Items sem `as` são ignorados (Delégua exige um identificador).
49531
+ construirTendo(items, i, linhas) {
49532
+ if (i >= items.length) {
49533
+ return `{\n${linhas.join('\n')}\n}`;
49534
+ }
49535
+ const item = items[i];
49536
+ const varExpr = item.expr();
49537
+ const expr = this.visit(item.test());
49538
+ if (!varExpr) {
49539
+ // Sem `as`: sem variável para ligar — pula este item
49540
+ return this.construirTendo(items, i + 1, linhas);
49541
+ }
49542
+ const nomeVar = this.visit(varExpr);
49543
+ // Para múltiplos itens, o próximo nível é indentado dentro deste bloco
49544
+ let linhasInternas;
49545
+ if (i + 1 < items.length) {
49546
+ const blocoInterno = this.construirTendo(items, i + 1, linhas);
49547
+ linhasInternas = blocoInterno.split('\n').map((l) => ` ${l}`);
49548
+ }
49549
+ else {
49550
+ linhasInternas = linhas;
49551
+ }
49552
+ return `tendo ${expr} como ${nomeVar} {\n${linhasInternas.join('\n')}\n}`;
49553
+ }
49554
+ visitIf_stmt(ctx) {
49555
+ const testes = ctx.test();
49556
+ const suites = ctx.suite();
49557
+ const elifs = ctx.ELIF();
49558
+ // Primeiro bloco: se (cond) { ... }
49559
+ let resultado = `se (${this.visit(testes[0])}) ${this.visitCorpo(suites[0])}`;
49560
+ // Blocos elif: senão se (cond) { ... }
49561
+ for (let i = 0; i < elifs.length; i++) {
49562
+ resultado += ` senão se (${this.visit(testes[i + 1])}) ${this.visitCorpo(suites[i + 1])}`;
49563
+ }
49564
+ // Bloco else: senão { ... }
49565
+ if (ctx.ELSE()) {
49566
+ resultado += ` senão ${this.visitCorpo(suites[suites.length - 1])}`;
49567
+ }
49568
+ return resultado;
49569
+ }
49570
+ visitWhile_stmt(ctx) {
49571
+ const cond = this.visit(ctx.test());
49572
+ const corpo = this.visitCorpo(ctx.suite(0));
49573
+ return `enquanto (${cond}) ${corpo}`;
49574
+ }
49575
+ visitFor_stmt(ctx) {
49576
+ const variavel = this.visit(ctx.exprlist());
49577
+ const iteravel = this.visit(ctx.testlist());
49578
+ const corpo = this.visitCorpo(ctx.suite(0));
49579
+ return `para cada ${variavel} em ${iteravel} ${corpo}`;
49580
+ }
49581
+ visitBreak_stmt(_ctx) {
49582
+ return 'sustar';
49583
+ }
49584
+ visitContinue_stmt(_ctx) {
49585
+ return 'continua';
49586
+ }
49587
+ visitReturn_stmt(ctx) {
49588
+ const testlist = ctx.testlist();
49589
+ if (testlist)
49590
+ return `retorna ${this.visit(testlist)}`;
49591
+ return 'retorna';
49592
+ }
49593
+ visitTfpdef(ctx) {
49594
+ // Ignora anotação de tipo (: Tipo) — retorna apenas o nome
49595
+ return ctx.NAME().text;
49596
+ }
49597
+ visitTypedargslist(ctx) {
49598
+ const params = [];
49599
+ for (let i = 0; i < ctx.childCount;) {
49600
+ const filho = ctx.getChild(i);
49601
+ const texto = filho.text;
49602
+ if (texto === ',') {
49603
+ i++;
49604
+ continue;
49605
+ }
49606
+ // Para em *args ou **kwargs — suporte básico suficiente para fase 4
49607
+ if (texto === '*' || texto === '**')
48795
49608
  break;
49609
+ const nomeParam = this.visit(filho); // → visitTfpdef → NAME
49610
+ if (nomeParam === 'self') {
49611
+ i++;
49612
+ continue;
49613
+ } // Remove self
49614
+ // Verifica se há valor padrão: tfpdef '=' test
49615
+ if (i + 1 < ctx.childCount && ctx.getChild(i + 1).text === '=') {
49616
+ const valorPadrao = this.visit(ctx.getChild(i + 2));
49617
+ params.push(`${nomeParam} = ${valorPadrao}`);
49618
+ i += 3;
49619
+ }
49620
+ else {
49621
+ params.push(nomeParam);
49622
+ i++;
49623
+ }
48796
49624
  }
49625
+ return params.join(', ');
49626
+ }
49627
+ visitParameters(ctx) {
49628
+ const argslist = ctx.typedargslist();
49629
+ if (!argslist)
49630
+ return '';
49631
+ return this.visitTypedargslist(argslist);
49632
+ }
49633
+ visitFuncdef(ctx) {
49634
+ const nomePython = ctx.NAME().text;
49635
+ const params = this.visitParameters(ctx.parameters());
49636
+ const corpo = this.visitCorpo(ctx.suite());
49637
+ if (nomePython === '__init__') {
49638
+ return `construtor(${params}) ${corpo}`;
49639
+ }
49640
+ return `funcao ${nomePython}(${params}) ${corpo}`;
49641
+ }
49642
+ visitClassdef(ctx) {
49643
+ const nome = ctx.NAME().text;
49644
+ const arglist = ctx.arglist();
49645
+ const heranca = arglist ? ` herda ${this.visit(arglist)}` : '';
49646
+ const corpo = this.visitCorpo(ctx.suite());
49647
+ return `classe ${nome}${heranca} ${corpo}`;
49648
+ }
49649
+ visitDecorated(ctx) {
49650
+ // Ignora decoradores — traduz apenas o funcdef ou classdef subjacente
49651
+ const funcdef = ctx.funcdef();
49652
+ if (funcdef)
49653
+ return this.visitFuncdef(funcdef);
49654
+ const classdef = ctx.classdef();
49655
+ if (classdef)
49656
+ return this.visitClassdef(classdef);
49657
+ return this.visitChildren(ctx);
48797
49658
  }
48798
49659
  traduzir(codigo) {
48799
- this.inputStream = antlr4ts_1.CharStreams.fromString(codigo);
48800
- this.lexer = new python3_lexer_1.Python3Lexer(this.inputStream);
48801
- this.tokenStream = new antlr4ts_1.CommonTokenStream(this.lexer);
48802
- this.parser = new python3_parser_1.Python3Parser(this.tokenStream);
48803
- this.resultado = '';
48804
- // Aqui achei três bons pontos de entrada:
48805
- // single_input, file_input e eval_input. O que funcionou melhor foi o file_input.
48806
- let tree = this.parser.file_input();
48807
- ParseTreeWalker_1.ParseTreeWalker.DEFAULT.walk(this, tree);
48808
- return this.resultado;
49660
+ // O lexer Python3 do ANTLR exige NEWLINE ao final de cada instrução.
49661
+ const codigoNormalizado = codigo.endsWith('\n') ? codigo : codigo + '\n';
49662
+ const inputStream = antlr4ts_1.CharStreams.fromString(codigoNormalizado);
49663
+ const lexer = new python3_lexer_1.Python3Lexer(inputStream);
49664
+ const tokenStream = new antlr4ts_1.CommonTokenStream(lexer);
49665
+ const parser = new python3_parser_1.Python3Parser(tokenStream);
49666
+ const tree = parser.file_input();
49667
+ return this.visit(tree);
48809
49668
  }
48810
49669
  }
48811
49670
  exports.TradutorReversoPython = TradutorReversoPython;
48812
49671
 
48813
- },{"./python/python3-lexer":239,"./python/python3-parser":240,"antlr4ts":371,"antlr4ts/tree/ParseTreeWalker":390}],253:[function(require,module,exports){
49672
+ },{"./python/python3-lexer":239,"./python/python3-parser":240,"antlr4ts":371,"antlr4ts/tree/AbstractParseTreeVisitor":389}],253:[function(require,module,exports){
48814
49673
  "use strict";
48815
49674
  var __importDefault = (this && this.__importDefault) || function (mod) {
48816
49675
  return (mod && mod.__esModule) ? mod : { "default": mod };
@@ -55532,7 +56391,7 @@ __decorate([
55532
56391
  exports.Parser = Parser;
55533
56392
 
55534
56393
  }).call(this)}).call(this,require('_process'))
55535
- },{"./Decorators":269,"./DefaultErrorStrategy":270,"./Lexer":277,"./ProxyParserErrorListener":287,"./Recognizer":289,"./Token":294,"./atn/ATNDeserializationOptions":305,"./atn/ATNDeserializer":306,"./atn/ParseInfo":342,"./atn/ParserATNSimulator":343,"./atn/ProfilingATNSimulator":352,"./misc/IntegerStack":380,"./misc/Utils":388,"./tree/ErrorNode":389,"./tree/TerminalNode":392,"./tree/pattern/ParseTreePatternMatcher":397,"_process":471}],283:[function(require,module,exports){
56394
+ },{"./Decorators":269,"./DefaultErrorStrategy":270,"./Lexer":277,"./ProxyParserErrorListener":287,"./Recognizer":289,"./Token":294,"./atn/ATNDeserializationOptions":305,"./atn/ATNDeserializer":306,"./atn/ParseInfo":342,"./atn/ParserATNSimulator":343,"./atn/ProfilingATNSimulator":352,"./misc/IntegerStack":380,"./misc/Utils":388,"./tree/ErrorNode":390,"./tree/TerminalNode":392,"./tree/pattern/ParseTreePatternMatcher":397,"_process":471}],283:[function(require,module,exports){
55536
56395
  "use strict";
55537
56396
  /*!
55538
56397
  * Copyright 2016 The ANTLR Project. All rights reserved.
@@ -56249,7 +57108,7 @@ __decorate([
56249
57108
  ], ParserRuleContext.prototype, "sourceInterval", null);
56250
57109
  exports.ParserRuleContext = ParserRuleContext;
56251
57110
 
56252
- },{"./Decorators":269,"./RuleContext":290,"./misc/Interval":381,"./tree/ErrorNode":389,"./tree/TerminalNode":392}],286:[function(require,module,exports){
57111
+ },{"./Decorators":269,"./RuleContext":290,"./misc/Interval":381,"./tree/ErrorNode":390,"./tree/TerminalNode":392}],286:[function(require,module,exports){
56253
57112
  "use strict";
56254
57113
  /*!
56255
57114
  * Copyright 2016 The ANTLR Project. All rights reserved.
@@ -72153,6 +73012,151 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
72153
73012
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
72154
73013
  return c > 3 && r && Object.defineProperty(target, key, r), r;
72155
73014
  };
73015
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
73016
+ return function (target, key) { decorator(target, key, paramIndex); }
73017
+ };
73018
+ Object.defineProperty(exports, "__esModule", { value: true });
73019
+ exports.AbstractParseTreeVisitor = void 0;
73020
+ const Decorators_1 = require("../Decorators");
73021
+ class AbstractParseTreeVisitor {
73022
+ /**
73023
+ * {@inheritDoc}
73024
+ *
73025
+ * The default implementation calls {@link ParseTree#accept} on the
73026
+ * specified tree.
73027
+ */
73028
+ visit(tree) {
73029
+ return tree.accept(this);
73030
+ }
73031
+ /**
73032
+ * {@inheritDoc}
73033
+ *
73034
+ * The default implementation initializes the aggregate result to
73035
+ * {@link #defaultResult defaultResult()}. Before visiting each child, it
73036
+ * calls {@link #shouldVisitNextChild shouldVisitNextChild}; if the result
73037
+ * is `false` no more children are visited and the current aggregate
73038
+ * result is returned. After visiting a child, the aggregate result is
73039
+ * updated by calling {@link #aggregateResult aggregateResult} with the
73040
+ * previous aggregate result and the result of visiting the child.
73041
+ *
73042
+ * The default implementation is not safe for use in visitors that modify
73043
+ * the tree structure. Visitors that modify the tree should override this
73044
+ * method to behave properly in respect to the specific algorithm in use.
73045
+ */
73046
+ visitChildren(node) {
73047
+ let result = this.defaultResult();
73048
+ let n = node.childCount;
73049
+ for (let i = 0; i < n; i++) {
73050
+ if (!this.shouldVisitNextChild(node, result)) {
73051
+ break;
73052
+ }
73053
+ let c = node.getChild(i);
73054
+ let childResult = c.accept(this);
73055
+ result = this.aggregateResult(result, childResult);
73056
+ }
73057
+ return result;
73058
+ }
73059
+ /**
73060
+ * {@inheritDoc}
73061
+ *
73062
+ * The default implementation returns the result of
73063
+ * {@link #defaultResult defaultResult}.
73064
+ */
73065
+ visitTerminal(node) {
73066
+ return this.defaultResult();
73067
+ }
73068
+ /**
73069
+ * {@inheritDoc}
73070
+ *
73071
+ * The default implementation returns the result of
73072
+ * {@link #defaultResult defaultResult}.
73073
+ */
73074
+ visitErrorNode(node) {
73075
+ return this.defaultResult();
73076
+ }
73077
+ /**
73078
+ * Aggregates the results of visiting multiple children of a node. After
73079
+ * either all children are visited or {@link #shouldVisitNextChild} returns
73080
+ * `false`, the aggregate value is returned as the result of
73081
+ * {@link #visitChildren}.
73082
+ *
73083
+ * The default implementation returns `nextResult`, meaning
73084
+ * {@link #visitChildren} will return the result of the last child visited
73085
+ * (or return the initial value if the node has no children).
73086
+ *
73087
+ * @param aggregate The previous aggregate value. In the default
73088
+ * implementation, the aggregate value is initialized to
73089
+ * {@link #defaultResult}, which is passed as the `aggregate` argument
73090
+ * to this method after the first child node is visited.
73091
+ * @param nextResult The result of the immediately preceeding call to visit
73092
+ * a child node.
73093
+ *
73094
+ * @returns The updated aggregate result.
73095
+ */
73096
+ aggregateResult(aggregate, nextResult) {
73097
+ return nextResult;
73098
+ }
73099
+ /**
73100
+ * This method is called after visiting each child in
73101
+ * {@link #visitChildren}. This method is first called before the first
73102
+ * child is visited; at that point `currentResult` will be the initial
73103
+ * value (in the default implementation, the initial value is returned by a
73104
+ * call to {@link #defaultResult}. This method is not called after the last
73105
+ * child is visited.
73106
+ *
73107
+ * The default implementation always returns `true`, indicating that
73108
+ * `visitChildren` should only return after all children are visited.
73109
+ * One reason to override this method is to provide a "short circuit"
73110
+ * evaluation option for situations where the result of visiting a single
73111
+ * child has the potential to determine the result of the visit operation as
73112
+ * a whole.
73113
+ *
73114
+ * @param node The {@link RuleNode} whose children are currently being
73115
+ * visited.
73116
+ * @param currentResult The current aggregate result of the children visited
73117
+ * to the current point.
73118
+ *
73119
+ * @returns `true` to continue visiting children. Otherwise return
73120
+ * `false` to stop visiting children and immediately return the
73121
+ * current aggregate result from {@link #visitChildren}.
73122
+ */
73123
+ shouldVisitNextChild(node, currentResult) {
73124
+ return true;
73125
+ }
73126
+ }
73127
+ __decorate([
73128
+ Decorators_1.Override,
73129
+ __param(0, Decorators_1.NotNull)
73130
+ ], AbstractParseTreeVisitor.prototype, "visit", null);
73131
+ __decorate([
73132
+ Decorators_1.Override,
73133
+ __param(0, Decorators_1.NotNull)
73134
+ ], AbstractParseTreeVisitor.prototype, "visitChildren", null);
73135
+ __decorate([
73136
+ Decorators_1.Override,
73137
+ __param(0, Decorators_1.NotNull)
73138
+ ], AbstractParseTreeVisitor.prototype, "visitTerminal", null);
73139
+ __decorate([
73140
+ Decorators_1.Override,
73141
+ __param(0, Decorators_1.NotNull)
73142
+ ], AbstractParseTreeVisitor.prototype, "visitErrorNode", null);
73143
+ __decorate([
73144
+ __param(0, Decorators_1.NotNull)
73145
+ ], AbstractParseTreeVisitor.prototype, "shouldVisitNextChild", null);
73146
+ exports.AbstractParseTreeVisitor = AbstractParseTreeVisitor;
73147
+
73148
+ },{"../Decorators":269}],390:[function(require,module,exports){
73149
+ "use strict";
73150
+ /*!
73151
+ * Copyright 2016 The ANTLR Project. All rights reserved.
73152
+ * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information.
73153
+ */
73154
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
73155
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
73156
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
73157
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
73158
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
73159
+ };
72156
73160
  Object.defineProperty(exports, "__esModule", { value: true });
72157
73161
  exports.ErrorNode = void 0;
72158
73162
  // ConvertTo-TS run at 2016-10-04T11:26:47.4646355-07:00
@@ -72177,112 +73181,7 @@ __decorate([
72177
73181
  ], ErrorNode.prototype, "accept", null);
72178
73182
  exports.ErrorNode = ErrorNode;
72179
73183
 
72180
- },{"../Decorators":269,"./TerminalNode":392}],390:[function(require,module,exports){
72181
- "use strict";
72182
- /*!
72183
- * Copyright 2016 The ANTLR Project. All rights reserved.
72184
- * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information.
72185
- */
72186
- Object.defineProperty(exports, "__esModule", { value: true });
72187
- exports.ParseTreeWalker = void 0;
72188
- const ErrorNode_1 = require("./ErrorNode");
72189
- const TerminalNode_1 = require("./TerminalNode");
72190
- const RuleNode_1 = require("./RuleNode");
72191
- class ParseTreeWalker {
72192
- /**
72193
- * Performs a walk on the given parse tree starting at the root and going down recursively
72194
- * with depth-first search. On each node, {@link ParseTreeWalker#enterRule} is called before
72195
- * recursively walking down into child nodes, then
72196
- * {@link ParseTreeWalker#exitRule} is called after the recursive call to wind up.
72197
- * @param listener The listener used by the walker to process grammar rules
72198
- * @param t The parse tree to be walked on
72199
- */
72200
- walk(listener, t) {
72201
- let nodeStack = [];
72202
- let indexStack = [];
72203
- let currentNode = t;
72204
- let currentIndex = 0;
72205
- while (currentNode) {
72206
- // pre-order visit
72207
- if (currentNode instanceof ErrorNode_1.ErrorNode) {
72208
- if (listener.visitErrorNode) {
72209
- listener.visitErrorNode(currentNode);
72210
- }
72211
- }
72212
- else if (currentNode instanceof TerminalNode_1.TerminalNode) {
72213
- if (listener.visitTerminal) {
72214
- listener.visitTerminal(currentNode);
72215
- }
72216
- }
72217
- else {
72218
- this.enterRule(listener, currentNode);
72219
- }
72220
- // Move down to first child, if exists
72221
- if (currentNode.childCount > 0) {
72222
- nodeStack.push(currentNode);
72223
- indexStack.push(currentIndex);
72224
- currentIndex = 0;
72225
- currentNode = currentNode.getChild(0);
72226
- continue;
72227
- }
72228
- // No child nodes, so walk tree
72229
- do {
72230
- // post-order visit
72231
- if (currentNode instanceof RuleNode_1.RuleNode) {
72232
- this.exitRule(listener, currentNode);
72233
- }
72234
- // No parent, so no siblings
72235
- if (nodeStack.length === 0) {
72236
- currentNode = undefined;
72237
- currentIndex = 0;
72238
- break;
72239
- }
72240
- // Move to next sibling if possible
72241
- let last = nodeStack[nodeStack.length - 1];
72242
- currentIndex++;
72243
- currentNode = currentIndex < last.childCount ? last.getChild(currentIndex) : undefined;
72244
- if (currentNode) {
72245
- break;
72246
- }
72247
- // No next sibling, so move up
72248
- currentNode = nodeStack.pop();
72249
- currentIndex = indexStack.pop();
72250
- } while (currentNode);
72251
- }
72252
- }
72253
- /**
72254
- * Enters a grammar rule by first triggering the generic event {@link ParseTreeListener#enterEveryRule}
72255
- * then by triggering the event specific to the given parse tree node
72256
- * @param listener The listener responding to the trigger events
72257
- * @param r The grammar rule containing the rule context
72258
- */
72259
- enterRule(listener, r) {
72260
- let ctx = r.ruleContext;
72261
- if (listener.enterEveryRule) {
72262
- listener.enterEveryRule(ctx);
72263
- }
72264
- ctx.enterRule(listener);
72265
- }
72266
- /**
72267
- * Exits a grammar rule by first triggering the event specific to the given parse tree node
72268
- * then by triggering the generic event {@link ParseTreeListener#exitEveryRule}
72269
- * @param listener The listener responding to the trigger events
72270
- * @param r The grammar rule containing the rule context
72271
- */
72272
- exitRule(listener, r) {
72273
- let ctx = r.ruleContext;
72274
- ctx.exitRule(listener);
72275
- if (listener.exitEveryRule) {
72276
- listener.exitEveryRule(ctx);
72277
- }
72278
- }
72279
- }
72280
- exports.ParseTreeWalker = ParseTreeWalker;
72281
- (function (ParseTreeWalker) {
72282
- ParseTreeWalker.DEFAULT = new ParseTreeWalker();
72283
- })(ParseTreeWalker = exports.ParseTreeWalker || (exports.ParseTreeWalker = {}));
72284
-
72285
- },{"./ErrorNode":389,"./RuleNode":391,"./TerminalNode":392}],391:[function(require,module,exports){
73184
+ },{"../Decorators":269,"./TerminalNode":392}],391:[function(require,module,exports){
72286
73185
  "use strict";
72287
73186
  /*!
72288
73187
  * Copyright 2016 The ANTLR Project. All rights reserved.
@@ -72630,7 +73529,7 @@ __decorate([
72630
73529
  ], Trees, "getRootOfSubtreeEnclosingRegion", null);
72631
73530
  exports.Trees = Trees;
72632
73531
 
72633
- },{"../CommonToken":265,"../Decorators":269,"../Parser":282,"../ParserRuleContext":285,"../Token":294,"../atn/ATN":302,"../misc/Utils":388,"./ErrorNode":389,"./RuleNode":391,"./TerminalNode":392}],394:[function(require,module,exports){
73532
+ },{"../CommonToken":265,"../Decorators":269,"../Parser":282,"../ParserRuleContext":285,"../Token":294,"../atn/ATN":302,"../misc/Utils":388,"./ErrorNode":390,"./RuleNode":391,"./TerminalNode":392}],394:[function(require,module,exports){
72634
73533
  "use strict";
72635
73534
  /*!
72636
73535
  * Copyright 2016 The ANTLR Project. All rights reserved.