Overview
The ExpresionesParser class is automatically generated by ANTLR 4.13.1 from Expresiones.g. It consumes the token stream produced by the lexer and constructs an Abstract Syntax Tree (AST) representing the program’s structure.
This is generated code. Modify the syntactic rules in Expresiones.g and regenerate using ANTLR, rather than editing ExpresionesParser.py directly.
Class Definition
From ExpresionesParser.py:49-115:
class ExpresionesParser ( Parser ):
grammarFileName = "Expresiones.g"
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate (atn.decisionToState) ]
sharedContextCache = PredictionContextCache()
Location: ~/workspace/source/ExpresionesParser.py:49
Parser Rules
The parser implements 7 grammar rules with corresponding constants:
RULE_root = 0
RULE_instrucciones = 1
RULE_bloque = 2
RULE_declaracion = 3
RULE_asignacion = 4
RULE_condicion = 5
RULE_expr = 6
ruleNames = [ "root" , "instrucciones" , "bloque" , "declaracion" , "asignacion" ,
"condicion" , "expr" ]
Location: ExpresionesParser.py:71-80
Grammar Rules and AST Construction
1. Root Rule (Program Entry)
Grammar Definition (Expresiones.g:4):
root : PROGRAMA LLAVE_IZQ instrucciones+ LLAVE_DER EOF # Prog ;
Parser Method (ExpresionesParser.py:166-200):
def root ( self ):
localctx = ExpresionesParser.RootContext( self , self ._ctx, self .state)
self .enterRule(localctx, 0 , self . RULE_root )
self ._la = 0 # Token type
try :
localctx = ExpresionesParser.ProgContext( self , localctx)
self .enterOuterAlt(localctx, 1 )
self .state = 14
self .match(ExpresionesParser. PROGRAMA )
self .state = 15
self .match(ExpresionesParser. LLAVE_IZQ )
self .state = 17
self ._errHandler.sync( self )
_la = self ._input.LA( 1 )
while True :
self .state = 16
self .instrucciones()
self .state = 19
self ._errHandler.sync( self )
_la = self ._input.LA( 1 )
if not ((((_la) & ~ 0x 3f ) == 0 and (( 1 << _la) & 16777236 ) != 0 )):
break
self .state = 21
self .match(ExpresionesParser. LLAVE_DER )
self .state = 22
self .match(ExpresionesParser. EOF )
except RecognitionException as re:
localctx.exception = re
self ._errHandler.reportError( self , re)
self ._errHandler.recover( self , re)
finally :
self .exitRule()
return localctx
Context Class (ExpresionesParser.py:137-162):
class ProgContext ( RootContext ):
def __init__ ( self , parser , ctx :ParserRuleContext):
super (). __init__ (parser)
self .copyFrom(ctx)
def PROGRAMA ( self ):
return self .getToken(ExpresionesParser. PROGRAMA , 0 )
def LLAVE_IZQ ( self ):
return self .getToken(ExpresionesParser. LLAVE_IZQ , 0 )
def LLAVE_DER ( self ):
return self .getToken(ExpresionesParser. LLAVE_DER , 0 )
def EOF ( self ):
return self .getToken(ExpresionesParser. EOF , 0 )
def instrucciones ( self , i : int = None ):
if i is None :
return self .getTypedRuleContexts(ExpresionesParser.InstruccionesContext)
else :
return self .getTypedRuleContext(ExpresionesParser.InstruccionesContext,i)
def accept ( self , visitor :ParseTreeVisitor):
if hasattr ( visitor, "visitProg" ):
return visitor.visitProg( self )
else :
return visitor.visitChildren( self )
Example: Parsing a Program
Input: AST Structure: ProgContext
├── PROGRAMA('program')
├── LLAVE_IZQ('{')
├── InstruccionesContext (InstrDeclContext)
│ └── DeclaracionContext
│ ├── TIPO('int')
│ ├── ID('x')
│ ├── ASIGNACION('=')
│ └── ExprContext (NumeroContext)
│ └── NUMERO('10')
├── LLAVE_DER('}')
└── EOF
2. Instrucciones Rule (Instructions)
Grammar Definition (Expresiones.g:6-10):
instrucciones
: declaracion PUNTO_COMA #InstrDecl
| asignacion PUNTO_COMA #InstrAsig
| SI PAR_IZQ condicion PAR_DER bloque (SINO bloque)? #InstrIf
;
This rule has three alternatives, each creating a different context:
InstrDeclContext (Declaration Instruction)
From ExpresionesParser.py:239-255:
class InstrDeclContext ( InstruccionesContext ):
def __init__ ( self , parser , ctx :ParserRuleContext):
super (). __init__ (parser)
self .copyFrom(ctx)
def declaracion ( self ):
return self .getTypedRuleContext(ExpresionesParser.DeclaracionContext, 0 )
def PUNTO_COMA ( self ):
return self .getToken(ExpresionesParser. PUNTO_COMA , 0 )
def accept ( self , visitor :ParseTreeVisitor):
if hasattr ( visitor, "visitInstrDecl" ):
return visitor.visitInstrDecl( self )
else :
return visitor.visitChildren( self )
InstrAsigContext (Assignment Instruction)
From ExpresionesParser.py:220-236:
class InstrAsigContext ( InstruccionesContext ):
def __init__ ( self , parser , ctx :ParserRuleContext):
super (). __init__ (parser)
self .copyFrom(ctx)
def asignacion ( self ):
return self .getTypedRuleContext(ExpresionesParser.AsignacionContext, 0 )
def PUNTO_COMA ( self ):
return self .getToken(ExpresionesParser. PUNTO_COMA , 0 )
def accept ( self , visitor :ParseTreeVisitor):
if hasattr ( visitor, "visitInstrAsig" ):
return visitor.visitInstrAsig( self )
else :
return visitor.visitChildren( self )
InstrIfContext (Conditional Instruction)
From ExpresionesParser.py:258-286:
class InstrIfContext ( InstruccionesContext ):
def __init__ ( self , parser , ctx :ParserRuleContext):
super (). __init__ (parser)
self .copyFrom(ctx)
def SI ( self ):
return self .getToken(ExpresionesParser. SI , 0 )
def PAR_IZQ ( self ):
return self .getToken(ExpresionesParser. PAR_IZQ , 0 )
def condicion ( self ):
return self .getTypedRuleContext(ExpresionesParser.CondicionContext, 0 )
def PAR_DER ( self ):
return self .getToken(ExpresionesParser. PAR_DER , 0 )
def bloque ( self , i : int = None ):
if i is None :
return self .getTypedRuleContexts(ExpresionesParser.BloqueContext)
else :
return self .getTypedRuleContext(ExpresionesParser.BloqueContext,i)
def SINO ( self ):
return self .getToken(ExpresionesParser. SINO , 0 )
def accept ( self , visitor :ParseTreeVisitor):
if hasattr ( visitor, "visitInstrIf" ):
return visitor.visitInstrIf( self )
else :
return visitor.visitChildren( self )
3. Bloque Rule (Code Block)
Grammar Definition (Expresiones.g:12):
bloque : LLAVE_IZQ instrucciones* LLAVE_DER ;
Parser Method (ExpresionesParser.py:383-410):
def bloque ( self ):
localctx = ExpresionesParser.BloqueContext( self , self ._ctx, self .state)
self .enterRule(localctx, 4 , self . RULE_bloque )
self ._la = 0 # Token type
try :
self .enterOuterAlt(localctx, 1 )
self .state = 41
self .match(ExpresionesParser. LLAVE_IZQ )
self .state = 45
self ._errHandler.sync( self )
_la = self ._input.LA( 1 )
while (((_la) & ~ 0x 3f ) == 0 and (( 1 << _la) & 16777236 ) != 0 ):
self .state = 42
self .instrucciones()
self .state = 47
self ._errHandler.sync( self )
_la = self ._input.LA( 1 )
self .state = 48
self .match(ExpresionesParser. LLAVE_DER )
except RecognitionException as re:
localctx.exception = re
self ._errHandler.reportError( self , re)
self ._errHandler.recover( self , re)
finally :
self .exitRule()
return localctx
4. Declaracion Rule (Variable Declaration)
Grammar Definition (Expresiones.g:14):
declaracion : TIPO ID (ASIGNACION expr)? ;
Parser Method (ExpresionesParser.py:445-472):
def declaracion ( self ):
localctx = ExpresionesParser.DeclaracionContext( self , self ._ctx, self .state)
self .enterRule(localctx, 6 , self . RULE_declaracion )
self ._la = 0 # Token type
try :
self .enterOuterAlt(localctx, 1 )
self .state = 50
self .match(ExpresionesParser. TIPO )
self .state = 51
self .match(ExpresionesParser. ID )
self .state = 54
self ._errHandler.sync( self )
_la = self ._input.LA( 1 )
if _la == 10 : # ASIGNACION token
self .state = 52
self .match(ExpresionesParser. ASIGNACION )
self .state = 53
self .expr( 0 )
except RecognitionException as re:
localctx.exception = re
self ._errHandler.reportError( self , re)
self ._errHandler.recover( self , re)
finally :
self .exitRule()
return localctx
Examples: Parsing Declarations
Example 1: Declaration without initialization AST: DeclaracionContext with TIPO('int') and ID('x'), no ASIGNACION or expr Example 2: Declaration with initialization AST: DeclaracionContext with TIPO('float'), ID('y'), ASIGNACION('='), and ExprContext (NumeroContext(‘3.14’))
5. Asignacion Rule (Variable Assignment)
Grammar Definition (Expresiones.g:16):
asignacion : ID ASIGNACION expr ;
Parser Method (ExpresionesParser.py:504-522):
def asignacion ( self ):
localctx = ExpresionesParser.AsignacionContext( self , self ._ctx, self .state)
self .enterRule(localctx, 8 , self . RULE_asignacion )
try :
self .enterOuterAlt(localctx, 1 )
self .state = 56
self .match(ExpresionesParser. ID )
self .state = 57
self .match(ExpresionesParser. ASIGNACION )
self .state = 58
self .expr( 0 )
except RecognitionException as re:
localctx.exception = re
self ._errHandler.reportError( self , re)
self ._errHandler.recover( self , re)
finally :
self .exitRule()
return localctx
6. Condicion Rule (Conditional Expression)
Grammar Definition (Expresiones.g:18-24):
condicion
: condicion O_LOGICO condicion #Logica
| condicion Y_LOGICO condicion #Logica
| NO_LOGICO condicion #NotLogica
| expr op=(MAYOR | MENOR | IGUAL | MAYOR_IGUAL | MENOR_IGUAL | DIFERENTE) expr #Relacional
| PAR_IZQ condicion PAR_DER #ParentesisCond
;
This is a left-recursive rule that generates four context types:
RelacionalContext (Relational Comparison)
From ExpresionesParser.py:541-571:
class RelacionalContext ( CondicionContext ):
def __init__ ( self , parser , ctx :ParserRuleContext):
super (). __init__ (parser)
self .op = None # Token - stores the comparison operator
self .copyFrom(ctx)
def expr ( self , i : int = None ):
if i is None :
return self .getTypedRuleContexts(ExpresionesParser.ExprContext)
else :
return self .getTypedRuleContext(ExpresionesParser.ExprContext,i)
def MAYOR ( self ):
return self .getToken(ExpresionesParser. MAYOR , 0 )
def MENOR ( self ):
return self .getToken(ExpresionesParser. MENOR , 0 )
def IGUAL ( self ):
return self .getToken(ExpresionesParser. IGUAL , 0 )
def MAYOR_IGUAL ( self ):
return self .getToken(ExpresionesParser. MAYOR_IGUAL , 0 )
def MENOR_IGUAL ( self ):
return self .getToken(ExpresionesParser. MENOR_IGUAL , 0 )
def DIFERENTE ( self ):
return self .getToken(ExpresionesParser. DIFERENTE , 0 )
def accept ( self , visitor :ParseTreeVisitor):
if hasattr ( visitor, "visitRelacional" ):
return visitor.visitRelacional( self )
else :
return visitor.visitChildren( self )
LogicaContext (Logical Operations)
From ExpresionesParser.py:614-635:
class LogicaContext ( CondicionContext ):
def __init__ ( self , parser , ctx :ParserRuleContext):
super (). __init__ (parser)
self .copyFrom(ctx)
def condicion ( self , i : int = None ):
if i is None :
return self .getTypedRuleContexts(ExpresionesParser.CondicionContext)
else :
return self .getTypedRuleContext(ExpresionesParser.CondicionContext,i)
def O_LOGICO ( self ):
return self .getToken(ExpresionesParser. O_LOGICO , 0 )
def Y_LOGICO ( self ):
return self .getToken(ExpresionesParser. Y_LOGICO , 0 )
def accept ( self , visitor :ParseTreeVisitor):
if hasattr ( visitor, "visitLogica" ):
return visitor.visitLogica( self )
else :
return visitor.visitChildren( self )
7. Expr Rule (Arithmetic Expression)
Grammar Definition (Expresiones.g:26-31):
expr: expr (MULT | DIV) expr #Aritmetica
| expr (SUMA | RESTA) expr #Aritmetica
| NUMERO #Numero
| ID #Variable
| PAR_IZQ expr PAR_DER #ParentesisExpr
;
Left-recursive rule with operator precedence (multiplication/division bind tighter than addition/subtraction).
AritmeticaContext (Arithmetic Operations)
From ExpresionesParser.py:794-819:
class AritmeticaContext ( ExprContext ):
def __init__ ( self , parser , ctx :ParserRuleContext):
super (). __init__ (parser)
self .copyFrom(ctx)
def expr ( self , i : int = None ):
if i is None :
return self .getTypedRuleContexts(ExpresionesParser.ExprContext)
else :
return self .getTypedRuleContext(ExpresionesParser.ExprContext,i)
def MULT ( self ):
return self .getToken(ExpresionesParser. MULT , 0 )
def DIV ( self ):
return self .getToken(ExpresionesParser. DIV , 0 )
def SUMA ( self ):
return self .getToken(ExpresionesParser. SUMA , 0 )
def RESTA ( self ):
return self .getToken(ExpresionesParser. RESTA , 0 )
def accept ( self , visitor :ParseTreeVisitor):
if hasattr ( visitor, "visitAritmetica" ):
return visitor.visitAritmetica( self )
else :
return visitor.visitChildren( self )
NumeroContext (Number Literal)
From ExpresionesParser.py:762-775:
class NumeroContext ( ExprContext ):
def __init__ ( self , parser , ctx :ParserRuleContext):
super (). __init__ (parser)
self .copyFrom(ctx)
def NUMERO ( self ):
return self .getToken(ExpresionesParser. NUMERO , 0 )
def accept ( self , visitor :ParseTreeVisitor):
if hasattr ( visitor, "visitNumero" ):
return visitor.visitNumero( self )
else :
return visitor.visitChildren( self )
VariableContext (Variable Reference)
From ExpresionesParser.py:778-791:
class VariableContext ( ExprContext ):
def __init__ ( self , parser , ctx :ParserRuleContext):
super (). __init__ (parser)
self .copyFrom(ctx)
def ID ( self ):
return self .getToken(ExpresionesParser. ID , 0 )
def accept ( self , visitor :ParseTreeVisitor):
if hasattr ( visitor, "visitVariable" ):
return visitor.visitVariable( self )
else :
return visitor.visitChildren( self )
Operator Precedence
The parser enforces correct operator precedence through the grammar structure:
Highest Precedence: Parentheses
(expr) - Forces evaluation order
High Precedence: Multiplication/Division
expr (MULT | DIV) expr - Parsed with precedence level 5
Medium Precedence: Addition/Subtraction
expr (SUMA | RESTA) expr - Parsed with precedence level 4
Low Precedence: Relational Operators
expr op expr where op is >, <, ==, etc.
Lower Precedence: Logical NOT
! condicion - Unary negation
Lowest Precedence: Logical AND/OR
condicion && condicion (precedence 4), condicion || condicion (precedence 5)
Example: Expression Parsing with Precedence
Input: AST Structure: AsignacionContext
├── ID('y')
├── ASIGNACION('=')
└── AritmeticaContext (SUMA)
├── NumeroContext('2')
├── SUMA('+')
└── AritmeticaContext (MULT)
├── NumeroContext('3')
├── MULT('*')
└── NumeroContext('4')
The multiplication is parsed first (higher precedence), then the addition.
Error Recovery
The parser includes error recovery mechanisms in every rule:
except RecognitionException as re:
localctx.exception = re
self ._errHandler.reportError( self , re)
self ._errHandler.recover( self , re)
finally :
self .exitRule()
return localctx
When a syntax error occurs:
The exception is caught
Error is reported with position information
Parser attempts recovery by skipping tokens
Parsing continues if possible
For custom error handling, implement a custom ErrorListener and attach it to the parser instance.
Parser Constructor
From ExpresionesParser.py:111-115:
def __init__ ( self , input :TokenStream, output :TextIO = sys.stdout):
super (). __init__ ( input , output)
self .checkVersion( "4.13.1" )
self ._interp = ParserATNSimulator( self , self .atn, self .decisionsToDFA, self .sharedContextCache)
self ._predicates = None
input : Token stream from lexer
output : Output stream for parser messages
_interp : ATN simulator that executes parser rules