Skip to content

Commit

Permalink
feat(RppRunner): add eval function to evaluate statements, refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
aadhithya committed May 16, 2022
1 parent 24263bc commit 38cb454
Showing 1 changed file with 36 additions and 7 deletions.
43 changes: 36 additions & 7 deletions rajinipp/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@

import os
import sys
import warnings
from pathlib import Path

from loguru import logger

from .lexer import Lexer
from .parser.parser import Parser
from .parser.parser import LineParser, ParserBase, ProgramParser
from .utils import read_yml


Expand All @@ -21,9 +22,29 @@ class RppRunner:
"""

def __init__(self) -> None:

yml_path = os.path.join(Path(__file__).parent, "token.yml")
self.tokens_dict = read_yml(yml_path)

self.__pgm_parser = self.__init_parser(ProgramParser)

# * we ignore warnings related to unused tokens.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
logger.warning(
"LineParser supports only a subset of rajini++ features."
)
self.__line_parser = self.__init_parser(LineParser)

def __init_parser(self, Parser: ParserBase):
parser = Parser(list(self.tokens_dict.keys()))
parser.parse()
return parser.get_parser()

def __eval(self, parser, code):
parsed_tokens = parser.parse(self.tokenize(code))
return parsed_tokens.eval()

def tokenize(self, code: str):
"""
tokenize tokenizes the input code.
Expand All @@ -38,7 +59,7 @@ def tokenize(self, code: str):
tokens = lexer.lex(code)
return tokens

def exec(self, code: str, log_level: str = "ERROR"):
def exec(self, code: str, log_level: str = "INFO"):
"""
exec executes a copmplete rajini++ program.
Expand All @@ -48,12 +69,20 @@ def exec(self, code: str, log_level: str = "ERROR"):
"""
logger.remove()
logger.add(sys.stderr, level=log_level)
self.__eval(self.__pgm_parser, code)

parser = Parser(list(self.tokens_dict.keys()))
parser.parse()
def eval(self, code_line: str):
"""
eval evaluates a rajini++ statement.
parser = parser.get_parser()
**NOTE**: eval supports only a subset of rajini++ features.
parsed_tokens = parser.parse(self.tokenize(code))
Args:
code_line (str): rajini++ statement to evaluate.
parsed_tokens.eval()
Returns:
_type_: output of the evaluation.
"""
logger.remove()
logger.add(sys.stderr, level="ERROR")
return self.__eval(self.__line_parser, code_line)

0 comments on commit 38cb454

Please sign in to comment.