Skip to content

Commit

Permalink
feat(parser.py): add line parser to parse statements, refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
aadhithya committed May 16, 2022
1 parent f69ffc0 commit 24263bc
Showing 1 changed file with 37 additions and 5 deletions.
42 changes: 37 additions & 5 deletions rajinipp/parser/parser.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from abc import abstractclassmethod
from typing import List

from loguru import logger
from rply import ParserGenerator

from ..ast.base import Expression, Print
from ..ast.blocks import MainBlock
from .atom_parser import AtomParser
from .cond_parser import ConditionalParser
Expand All @@ -13,7 +15,7 @@
from .var_parser import VariableParser


class Parser:
class ParserBase:
def __init__(self, tokens: List[str]) -> None:
self.pg = ParserGenerator(
tokens=tokens,
Expand All @@ -38,11 +40,10 @@ def __init__(self, tokens: List[str]) -> None:
]

def parse(self):
@self.pg.production("main : PGM_START statements PGM_END")
def main(p):
logger.debug("Parser --> main")
return MainBlock(p[1])
pass

def init_parsers(self):
"""initialize other parsers"""
# * Add all other parsers.
for parser in self.parsers:
parser.parse(self.pg)
Expand All @@ -52,4 +53,35 @@ def error(token):
raise ValueError(token)

def get_parser(self):
"""builds and returns parser"""
return self.pg.build()


class ProgramParser(ParserBase):
def parse(self):
@self.pg.production("main : PGM_START statements PGM_END")
def main(p):
logger.debug("Parser --> main")
return MainBlock(p[1])

self.init_parsers()


class LineParser(ParserBase):
def __init__(self, tokens: List[str]) -> None:
super().__init__(tokens)
# * remove StatementParser. We will build our own here.
self.parsers.pop(0)
# * remove ConditionalParser. Line Parser will not support it yet.
self.parsers.pop(3)

def parse(self):
@self.pg.production("statement : PRINT printexprs SEMI_COLON")
def print_stmt(p):
return Print(p[1])

@self.pg.production("statement : expression SEMI_COLON")
def expr_stms(p):
return Expression(p[0])

self.init_parsers()

0 comments on commit 24263bc

Please sign in to comment.