Exemple #1
0
class Assign:
    def __init__(self):
        self.id = None
        self.expr = None

    #Simple parsing for Assign
    def parse(self):
        self.id = Id()
        self.id.parse(TokList.getIdOrConst())
        TokList.nextToken()
        TokList.match('ASSIGN', 'assign')
        self.expr = Expr()
        self.expr.parse()
        TokList.match('SEMICOLON', 'assign')

    #Simple printing for Assign
    def print(self):
        TokList.printIndent()
        self.id.print()
        print(':=', end='')
        self.expr.print()
        print(';')

    #Executor that determines value of an expression and then sets that value to the respective Id
    def exec(self):
        val = self.expr.exec()
        self.id.setValue(val)
Exemple #2
0
def Vector(*args):
    '''Create a Vector expression.'''
    # if the input is a numpy array, put it into a ConstantVectorExpr

    if len(args)==1:
        x = args[0]
    else:
        x = args

    if isinstance(x, ndarray):
        order = len(x.shape)
        if order != 1:
            raise ValueError('Non-vector input [{}] to Vector()'.format(x))
        if len(x) <= 1:
            raise ValueError('1D input [{}] to Vector()'.format(x))
        return ConstantVector(x)

    # if the input is a 1D list or tuple:
    #   (*) Form a ConstantVectorExpr if all the elements are constants
    #   (*) Form a VectorExpr otherwise
    if isinstance(x, (list, tuple, AggExpr)):
        allConsts = True
        elems = []
        if len(x) == 1:
            raise ValueError('Impossible to convert a 1D object to a vector')

        for x_i in x:

            if isinstance(x_i, Number):
                elems.append(x_i)
            elif isinstance(x_i, Expr):
                if not isinstance(x_i.shape(), ScalarShape):
                    raise ValueError('Vector() element not scalar: [{}]'.format(x_i))
                if not x_i.isConstant():
                    allConsts = False
                    elems.append(x_i)
                else:
                    elems.append(Expr._convertToExpr(x_i.data()))
            else:
                raise ValueError('Vector() input neither number nor expr: [{}]'.format(x_i))

        if allConsts:
            return ConstantVectorExpr(array(elems))
        else:
            exprElems = []
            for e in elems:
                exprElems.append(Expr._convertToExpr(e))
            return AggedVectorExpr(exprElems)

    # If the input is a tensor, this won't work
    if isinstance(x, Expr) and isinstance(x.shape(), TensorShape):
        raise ValueError('impossible to convert a tensor to a vector')

    # If the input is a scalar, this won't work
    if isinstance(x, Expr) and isinstance(x.shape(), ScalarShape):
        raise ValueError('pointless to convert a scalar to a vector')

    # Don't know what this input is
    raise ValueError('bad input {} to Vector()')
Exemple #3
0
 def __init__(self, name, arg):
     assert (Expr._convertibleToExpr(arg))
     expr = Expr._convertToExpr(arg)
     if not isinstance(expr.shape(), ScalarShape):
         raise ValueError(
             'UnivariateFuncExpr ctor: non-scalar arg [{}]'.format(expr))
     super().__init__(expr, expr.shape())
     self._name = name
Exemple #4
0
 def parse(self):
     self.id = Id()
     self.id.parse(TokList.getIdOrConst())
     TokList.nextToken()
     TokList.match('ASSIGN', 'assign')
     self.expr = Expr()
     self.expr.parse()
     TokList.match('SEMICOLON', 'assign')
Exemple #5
0
 def parse(self):
     self.const = Const()
     self.const.parse(TokList.getIdOrConst())
     TokList.nextToken()
     if TokList.currentToken() == 'COMMA':
         self.constList = ConstList()
         self.constList.parse()
     TokList.match('COLON', 'case line')
     self.expr = Expr()
     self.expr.parse()
     self.caseLineFollow = CaseLineFollow()
     self.caseLineFollow.parse()
Exemple #6
0
    def test_AggIter(self):
        x = Coordinate(0)
        a = np.array([1, 2, 3])
        a2 = Expr._convertToExpr(a)
        c = 1
        c2 = Expr._convertToExpr(c)
        L = AggExpr(c, x, a)
        tup = (c2, x, a2)
        same = True
        for e1, e2 in zip(L, tup):
            same = same and (e1.sameas(e2))

        assert (same)
Exemple #7
0
 def parse(self):
     TokList.match('CASE','case')
     self.id = Id()
     self.id.parse(TokList.getIdOrConst())
     TokList.nextToken()
     TokList.match('OF','case')
     self.case_line = CaseLine()
     self.case_line.parse()
     TokList.match('ELSE','case')
     self.expr = Expr()
     self.expr.parse()
     TokList.match('END','case')
     TokList.match('SEMICOLON','case')
Exemple #8
0
 def __init__(self, dir, name=None):
     super().__init__()
     self._dir = dir
     if name == None:
         self._name = Expr._dirName(dir)
     else:
         self._name = name
Exemple #9
0
 def parse(self):
     self.leftExpr = Expr()
     self.leftExpr.parse()
     if TokList.checkTok('EQUAL'):
         self.checkValue = '='
         TokList.nextToken()
     elif TokList.checkTok('LESSTHAN'):
         self.checkValue = '<'
         TokList.nextToken()
     elif TokList.checkTok('LESSTHANEQUAL'):
         self.checkValue = '<='
         TokList.nextToken()
     else:
         print('Error: improper syntax for comparator')
         exit()
     self.rightExpr = Expr()
     self.rightExpr.parse()
Exemple #10
0
    def __call__(self, arg):

        # Make sure the type makes sense
        if not Expr._convertibleToExpr(arg):
            raise TypeError('diff op [{}] cannot accept type [{}]'.format(
                self, arg))

        f = Expr._convertToExpr(arg)

        # Make sure the operator and input are consistent
        if not self.acceptShape(f.shape()):
            raise TypeError('diff op [{}] cannot accept argument [{}]'.format(
                self, f))

        # Form the diff op expression
        if isinstance(f, SymbolicFunctionBase):
            return DiffOpOnFunction(self, f)
        return DiffOp(self, f)
Exemple #11
0
  def init_deklarator(self, inherited_type):
    curr_line = self.lines._iter
    pprint("# init_deklarator")
    pprint(self.lines.get_line())

    if self.check_expressions(["<izravni_deklarator>"]):
      tmp = self.izravni_deklarator(inherited_type)
      if self.terminate: return tmp
      expr, num = tmp
      if expr.is_const:
        return self.parse_error(curr_line)
    elif self.check_expressions(["<izravni_deklarator>", "OP_PRIDRUZI", "<inicijalizator>"]):
      global currLabel
      tmp = self.izravni_deklarator(inherited_type)
      if self.terminate: return tmp
      expr, num = tmp
      self.assert_leaf("OP_PRIDRUZI")
      tmp = self.inicijalizator()
      outputCode.addCommandToFunction(currFunction, 'LOAD {}, ({})'.format('R' + str(currRegister), currLabel))
      currLabel = None
      if self.terminate: return tmp
      expr2, num2 = tmp
      if not expr.is_array and not expr2.is_function:
        if not expr == expr2:
          return self.parse_error(curr_line)
      if not expr.is_array and expr2.is_function:
        if not expr == expr2.get_return_type():
          return self.parse_error(curr_line)
      elif expr.is_array:
        if not num >= num2:
          return self.parse_error(curr_line)
        if type(expr2) is list:
          _expr = Expr(expr)
          _expr.is_array = False
          for e in expr2:
            if not e == _expr:
              return self.parse_error(curr_line)
        else:
          if not expr2 == expr:
            return self.parse_error(curr_line)
    else:
      return self.parse_error(curr_line)
Exemple #12
0
class Case:
    def __init__(self):
        self.case_line = None
        self.expr = None
        self.id = None
    #Simple parse of the case statement
    def parse(self):
        TokList.match('CASE','case')
        self.id = Id()
        self.id.parse(TokList.getIdOrConst())
        TokList.nextToken()
        TokList.match('OF','case')
        self.case_line = CaseLine()
        self.case_line.parse()
        TokList.match('ELSE','case')
        self.expr = Expr()
        self.expr.parse()
        TokList.match('END','case')
        TokList.match('SEMICOLON','case')
    #Printing with proper indentation manipulation and new line printings
    def print(self):
        TokList.printIndent()
        print('case ', end='')
        self.id.print()
        print(' of')
        TokList.increaseIndent()
        TokList.printIndent()
        self.case_line.print()
        #Necessary for new line printings
        print()
        TokList.printIndent()
        print('else ', end='')
        self.expr.print()
        print()
        TokList.decreaseIndent()
        TokList.printIndent()
        print('end;')
    #Recursive execution based on values in the case line.  Id value is passed in to all versions of case
    def exec(self):
        if not (self.case_line.exec(self.id)):
            self.id.setValue(self.expr.exec())
Exemple #13
0
class Out:
    def __init__(self):
        self.expr = None

    #Simple parsing for output statement
    def parse(self):
        TokList.match('OUTPUT', 'output')
        self.expr = Expr()
        self.expr.parse()
        TokList.match('SEMICOLON', 'output')

    #Simple printing
    def print(self):
        TokList.printIndent()
        print('output ', end='')
        self.expr.print()
        print(';')

    #Execution that prints the values returned by the expression evaluation
    def exec(self):
        print(self.expr.exec())
  def init_deklarator(self, inherited_type):
    curr_line = self.lines._iter
    pprint("# init_deklarator")
    pprint(self.lines.get_line())

    if self.check_expressions(["<izravni_deklarator>"]):
      tmp = self.izravni_deklarator(inherited_type)
      if self.terminate: return tmp
      expr, num = tmp
      if expr.is_const:
        return self.parse_error(curr_line)
    elif self.check_expressions(["<izravni_deklarator>", "OP_PRIDRUZI", "<inicijalizator>"]):
      tmp = self.izravni_deklarator(inherited_type)
      if self.terminate: return tmp
      expr, num = tmp
      self.assert_leaf("OP_PRIDRUZI")
      tmp = self.inicijalizator()
      if self.terminate: return tmp
      expr2, num2 = tmp
      if not expr.is_array and not expr2.is_function:
        if not expr == expr2:
          return self.parse_error(curr_line)
      if not expr.is_array and expr2.is_function:
        if not expr == expr2.get_return_type():
          return self.parse_error(curr_line)
      elif expr.is_array:
        if not num >= num2:
          return self.parse_error(curr_line)
        if type(expr2) is list:
          _expr = Expr(expr)
          _expr.is_array = False
          for e in expr2:
            if not e == _expr:
              return self.parse_error(curr_line)
        else:
          if not expr2 == expr:
            return self.parse_error(curr_line)
    else:
      return self.parse_error(curr_line)
class TestExpr(unittest.TestCase):
  expr = None

  expressions = lambda: (
      ('2 + 3',             '5'),
      ('2 - 3',             '-1'),
      ('2 * 3',             '6'),
      ('4 / 2',             '2.0'),
      ('2 + 3 * 4',         '14'),
      ('2 + 3 * 4 + 5',     '19'),
      ('4 + 2 * 5 / 2 - 6', '3.0'),
      ('4 / 2 * 2 + 9 - 1', '12.0')
  )

  def setUp(self):
      self.expr = Expr()

  def tearDown(self):
      self.expr = None

  @data_provider(expressions)
  def test_expr_eval_string(self, expr, expected):
      self.assertEqual(self.expr.eval_string(expr), expected + '\n', 'expr=' + expr)
Exemple #16
0
class CaseLine:
    def __init__(self):
        self.const = None
        self.constList = None
        self.expr = None
        self.caseLineFollow = None

    #Parsing for CaseLine based on the homework
    def parse(self):
        self.const = Const()
        self.const.parse(TokList.getIdOrConst())
        TokList.nextToken()
        if TokList.currentToken() == 'COMMA':
            self.constList = ConstList()
            self.constList.parse()
        TokList.match('COLON', 'case line')
        self.expr = Expr()
        self.expr.parse()
        self.caseLineFollow = CaseLineFollow()
        self.caseLineFollow.parse()

    #Simple printing
    def print(self):
        self.const.print()
        if self.constList is not None:
            self.constList.print()
        print(':', end='')
        self.expr.print()
        self.caseLineFollow.print()

    #Exectuion that returns a boolean based on idValue and constants given
    def exec(self, caseId):
        if self.const.exec() == caseId.getValue():
            caseId.setValue(self.expr.exec())
            return True
        if self.constList is not None:
            if self.constList.exec(caseId):
                caseId.setValue(self.expr.exec())
                return True
        if self.caseLineFollow.exec(caseId):
            return True
        return False
Exemple #17
0
__author__ = 'srtoosnye'
# -*- coding: utf-8 -*-
from Expr import Expr
from calculate import calculate
import data
import sys

conn = data.link_to_mysql()
cursor = conn.cursor()
data.create_table(cursor)
expr = raw_input('请输入表达式:')
if data.is_used_data(cursor, expr):
    sys.exit()

s = Expr(expr)
s.check_value()
s.opt_value()

data.store_result(cursor, calculate(s.get_postfix()), expr)
conn.commit()
conn.close()
Exemple #18
0
 def parse(self):
     TokList.match('OUTPUT', 'output')
     self.expr = Expr()
     self.expr.parse()
     TokList.match('SEMICOLON', 'output')
Exemple #19
0
 def print_ast(self, expression: Expr.Expr):
     return expression.accept(self)
Exemple #20
0
def AstPrinter(top_token:Expr.Expr):
    display = top_token.accept(PrintVisitor())
    print(display)
Exemple #21
0
 def evaluate(self, expr: Expr.Expr) -> object:
     """ Evaluates the value of an expression """
     return expr.accept(self)
Exemple #22
0
 def evaluate(self, client: Expr.Expr) -> object:
     return client.accept(self)
Exemple #23
0
 def evaluate(self, expr : Expr.Expr):
     return expr.accept(self)
# License: MIT

import sys

from Expr import Expr


if __name__ == '__main__':
    expr = Expr()

    if len(sys.argv) > 1:
        print(expr.eval_file(sys.argv[1]))
    else:
        print(expr.eval_string(sys.stdin.readline()))
Exemple #25
0
class Cmpr:
    def __init__(self):
        self.rightExpr = None
        self.leftExpr = None
        self.checkValue = None

    #Parsing to determine kind of comparator.  Checks for middle comparison while returning an error if none are given.
    def parse(self):
        self.leftExpr = Expr()
        self.leftExpr.parse()
        if TokList.checkTok('EQUAL'):
            self.checkValue = '='
            TokList.nextToken()
        elif TokList.checkTok('LESSTHAN'):
            self.checkValue = '<'
            TokList.nextToken()
        elif TokList.checkTok('LESSTHANEQUAL'):
            self.checkValue = '<='
            TokList.nextToken()
        else:
            print('Error: improper syntax for comparator')
            exit()
        self.rightExpr = Expr()
        self.rightExpr.parse()

    #Simple printing
    def print(self):
        self.leftExpr.print()
        print(self.checkValue, end='')
        self.rightExpr.print()

    #Executor based on results gained while parsing
    def exec(self):
        if self.checkValue == '=':
            return self.leftExpr.exec() == self.rightExpr.exec()
        elif self.checkValue == '<':
            return self.leftExpr.exec() < self.rightExpr.exec()
        elif self.checkValue == '<=':
            return self.leftExpr.exec() <= self.rightExpr.exec()
  def postfiks_izraz(self):
    curr_line = self.lines._iter
    pprint("# postfiks_izraz")
    pprint(self.lines.get_line())

    if self.check_expressions(["<postfiks_izraz>", "L_UGL_ZAGRADA", "<izraz>", "D_UGL_ZAGRADA"]):
      expr = self.postfiks_izraz()
      _expr = Expr(expr)
      if not _expr.is_array:
        return self.parse_error(curr_line)
      ## We are accessing an element of this array so the return type is not array
      _expr.is_array = False
      self.assert_leaf("L_UGL_ZAGRADA")
      if not self.izraz() == Expr("INT"):
        return self.parse_error(curr_line)
      self.assert_leaf("D_UGL_ZAGRADA")
      if _expr.is_const:
        return _expr
      else:
        return _expr.set_to_lexpr()
    elif self.check_expressions(["<postfiks_izraz>", "L_ZAGRADA", "D_ZAGRADA"]):
      expr = self.postfiks_izraz()
      self.assert_leaf("L_ZAGRADA")
      self.assert_leaf("D_ZAGRADA")
      if not expr.is_function or not expr.is_function_from([Expr("VOID")]):
        return self.parse_error(curr_line)
      ret = expr.get_return_type()
      if len(ret) != 1:
        raise Exception("This should not happen")
      else:
        return ret[0]
    elif self.check_expressions(["<postfiks_izraz>", "L_ZAGRADA", "<lista_argumenata>", "D_ZAGRADA"]):
      expr = self.postfiks_izraz()
      self.assert_leaf("L_ZAGRADA")
      expr2 = self.lista_argumenata()
      self.assert_leaf("D_ZAGRADA")
      if not expr.is_function or not expr.is_function_from(expr2):
        return self.parse_error(curr_line)
      ret = expr.get_return_type()
      if len(ret) != 1:
        raise Exception("This should not happen")
      else:
        return ret[0]
    elif self.check_expressions(["<postfiks_izraz>", "OP_INC"]):
      expr = self.postfiks_izraz()
      self.assert_leaf("OP_INC")
      if not expr.is_lexpr or not expr == Expr("INT"):
        return self.parse_error(curr_line)
      else:
        return Expr("INT")
    elif self.check_expressions(["<postfiks_izraz>", "OP_DEC"]):
      expr = self.postfiks_izraz()
      self.assert_leaf("OP_DEC")
      if not expr.is_lexpr or not expr == Expr("INT"):
        return self.parse_error(curr_line)
      else:
        return Expr("INT")
    elif self.check_expressions(["<primarni_izraz>"]):
      return self.primarni_izraz()
    else:
      return self.parse_error(curr_line)
 def setUp(self):
     self.expr = Expr()
Exemple #28
0
 def __init__(self, name):
     Expr.__init__(self, name)
Exemple #29
0
 def print(self, expr: Expr.Expr) -> str:
     return expr.accept(self)