diff options
author | Iván Ávalos <avalos@disroot.org> | 2022-11-25 12:11:08 -0600 |
---|---|---|
committer | Iván Ávalos <avalos@disroot.org> | 2022-11-25 12:11:08 -0600 |
commit | eb4a3019bc0251e5b2b8229679e3c65d61d55336 (patch) | |
tree | f6b2a89dd35374272bd671933bfe87da4a587215 /compilador/parse/base.py | |
parent | 6b4e9a4e95eb511c194200e38ee323091dc5d7d2 (diff) | |
download | javanol-eb4a3019bc0251e5b2b8229679e3c65d61d55336.tar.gz javanol-eb4a3019bc0251e5b2b8229679e3c65d61d55336.tar.bz2 javanol-eb4a3019bc0251e5b2b8229679e3c65d61d55336.zip |
Buen progreso, pero se cicla
Diffstat (limited to 'compilador/parse/base.py')
-rw-r--r-- | compilador/parse/base.py | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/compilador/parse/base.py b/compilador/parse/base.py new file mode 100644 index 0000000..a8f6f8a --- /dev/null +++ b/compilador/parse/base.py @@ -0,0 +1,60 @@ +from enum import Enum +from tabla import LexToken, TablaLex, tokens +from arbol import Arbol, Nodo +from shared import Control +from pprint import pprint +from errors import Error +from typing import NoReturn +from more_itertools import seekable + +from tabla import TablaLex, Token +from errors import Error + +class BaseParser: + def __init__(self, iterador: seekable): + self.iterador: seekable = iterador + + ''' Requires the next token to have a matching ltok. Returns that + token, or an error. ''' + def want(self, *want: Token) -> (LexToken | Error): + tok: LexToken = self.lex() + if len(want) == 0: + return tok + for w in want: + if tok.tipo == w: + return tok + + return Error.syntax(tok.tipo, want, tok.numlinea) + + ''' Looks for a matching ltok from the lexer, and if not present, + unlexes the token and returns void. If found, the token is + consumed from the lexer and is returned. ''' + def _try(self, *want: Token) -> (LexToken | NoReturn): + tok: LexToken = self.lex() + if len(want) == 0: + return tok + for w in want: + if tok.tipo == w: + return tok + self.unlex() + + ''' Looks for a matching ltok from the lexer, unlexes the token, + and returns it; or void if it was not an ltok. ''' + def peek(self, *want: Token) -> (LexToken | NoReturn): + tok: LexToken = self.iterador.peek() + if len(want) == 0: + return tok + for w in want: + if tok.tipo == w: + return tok + + def lex(self): + return next(self.iterador) + + def unlex(self): + self.iterador.seek(-1) + + ''' Returns a syntax error if cond is false and void otherwise ''' + def synassert(self, cond: bool, msg: str) -> (Error | NoReturn): + if not cond: + return Error(msg = msg) |