Added basic implementation for Python code evaluation

This commit is contained in:
2019-11-07 17:18:07 +01:00
parent b818c992ec
commit 448ebc696a
18 changed files with 501 additions and 156 deletions
+32
View File
@@ -0,0 +1,32 @@
from core.concept import ReturnValueConcept, ErrorConcept
from evaluators.BaseEvaluator import BaseEvaluator
from parsers.PythonParser import PythonNode
import ast
from core.sheerka import ReturnValue, Sheerka
import logging
log = logging.getLogger(__name__)
class PythonEvaluator(BaseEvaluator):
def __init__(self):
super().__init__("Python Evaluator", 50)
def matches(self, context, items):
return len(items) == 1 and isinstance(items[0].value, PythonNode)
def eval(self, context, items):
sheerka = context.sheerka
node = items[0].value
if isinstance(node.ast, ast.Expression):
try:
log.debug("Evaluating python expression")
compiled = compile(node.ast, "<string>", "eval")
evaluated = eval(compiled, {}, {"sheerka": context.sheerka})
concept = sheerka.new(ReturnValueConcept.NAME, body=evaluated)
return ReturnValue(self.name, True, concept)
except Exception as error:
error = sheerka.new(ErrorConcept.NAME, body=error)
return ReturnValue(self.name, False, error)
else:
raise NotImplementedError()