def execute(self,
                operands: List[Expression],
                frame: Frame,
                gui_holder: Holder,
                eval_operands=True):
        new_frame = Frame(self.name,
                          self.frame if self.lexically_scoped else frame)

        if eval_operands and self.evaluates_operands:
            operands = evaluate_all(operands, frame,
                                    gui_holder.expression.children[1:])

        if self.var_param:
            verify_min_callable_length(self, len(self.params), len(operands))
        else:
            verify_exact_callable_length(self, len(self.params), len(operands))

        if len(self.body) > 1:
            body = [Pair(Symbol("begin"), make_list(self.body))]
        else:
            body = self.body

        for param, value in zip(self.params, operands):
            new_frame.assign(param, value)

        if self.var_param:
            new_frame.assign(self.var_param,
                             make_list(operands[len(self.params):]))

        out = None
        gui_holder.expression.set_entries([
            VisualExpression(expr, gui_holder.expression.display_value)
            for expr in body
        ])

        gui_holder.apply()

        for i, expression in enumerate(body):
            out = evaluate(expression,
                           new_frame,
                           gui_holder.expression.children[i],
                           self.evaluates_operands and i == len(body) - 1,
                           log_stack=len(self.body) == 1)

        new_frame.assign(return_symbol, out)

        if not self.evaluates_operands:
            gui_holder.expression.set_entries(
                [VisualExpression(out, gui_holder.expression.display_value)])
            out = evaluate(out, frame, gui_holder.expression.children[i], True)

        return out
Пример #2
0
def get_expression(buffer: TokenBuffer) -> Union[(Expression, None)]:
    token = buffer.pop_next_token()
    if (token is None):
        return None
    elif (token in ('(', '[')):
        return get_rest_of_list(buffer, (')' if (token == '(') else ']'))
    elif (token == "'"):
        return make_list([Symbol('quote'), get_expression(buffer)])
    elif (token == ','):
        if (buffer.get_next_token() == '@'):
            buffer.pop_next_token()
            return make_list(
                [Symbol('unquote-splicing'),
                 get_expression(buffer)])
        else:
            return make_list([Symbol('unquote'), get_expression(buffer)])
    elif (token == '`'):
        return make_list([Symbol('quasiquote'), get_expression(buffer)])
    elif (token == '.'):
        if logger.dotted:
            raise ParseError(''.join(
                ["Unexpected token: '", '{}'.format(token), "'"]))
        else:
            return make_list([Symbol('variadic'), get_expression(buffer)])
    elif (token == '"'):
        return get_string(buffer)
    elif (token in SPECIALS):
        raise ParseError(''.join(
            ["Unexpected token: '", '{}'.format(token), "'"]))
    elif is_number(token.value):
        try:
            return Number(int(token.value))
        except ValueError:
            return Number(float(token.value))
    elif ((token == '#t') or (token.value.lower() == 'true')):
        return SingletonTrue
    elif ((token == '#f') or (token.value.lower() == 'false')):
        return SingletonFalse
    elif (token == 'nil'):
        return Nil
    elif is_str(token.value):
        return Symbol(token.value.lower())
    else:
        raise ParseError(''.join(
            ["Unexpected token: '", '{}'.format(token), "'"]))
    def quasiquote_evaluate(cls, expr: Expression, frame: Frame, gui_holder: Holder, splicing=False):
        is_well_formed = False

        if isinstance(expr, Pair):
            try:
                lst = pair_to_list(expr)
            except OperandDeduceError:
                pass
            else:
                is_well_formed = not any(map(
                    lambda x: isinstance(x, Symbol) and x.value in ["unquote", "quasiquote", "unquote-splicing"], lst))

        visual_expression = gui_holder.expression
        if not is_well_formed:
            visual_expression.children[2:] = []

        if isinstance(expr, Pair):
            if isinstance(expr.first, Symbol) and expr.first.value in ("unquote", "unquote-splicing"):
                if expr.first.value == "unquote-splicing" and not splicing:
                    raise OperandDeduceError("Unquote-splicing must be in list template.")
                gui_holder.evaluate()
                verify_exact_callable_length(expr.first, 1, len(pair_to_list(expr)) - 1)
                out = evaluate(expr.rest.first, frame, visual_expression.children[1])
                visual_expression.value = out
                gui_holder.complete()
                return out
            elif isinstance(expr.first, Symbol) and expr.first.value == "quasiquote":
                visual_expression.value = expr
                gui_holder.complete()
                return expr
            else:
                if is_well_formed:
                    out = []
                    for sub_expr, holder in zip(pair_to_list(expr), visual_expression.children):
                        splicing = isinstance(sub_expr, Pair) and isinstance(sub_expr.first, Symbol) \
                                and sub_expr.first.value == "unquote-splicing"
                        evaluated = Quasiquote.quasiquote_evaluate(sub_expr, frame, holder, splicing)
                        if splicing:
                            if not isinstance(evaluated, (Pair, NilType)):
                                raise TypeMismatchError(f"Can only splice lists, not {evaluated}.")
                            out.extend(pair_to_list(evaluated))
                        else:
                            out.append(evaluated)
                    out = make_list(out)
                else:
                    if not logger.dotted:
                        raise OperandDeduceError(f"{expr} is an ill-formed quasiquotation.")
                    out = Pair(Quasiquote.quasiquote_evaluate(expr.first, frame, visual_expression.children[0]),
                               Quasiquote.quasiquote_evaluate(expr.rest, frame, visual_expression.children[1]))
                visual_expression.value = out
                gui_holder.complete()
                return out
        else:
            visual_expression.value = expr
            gui_holder.complete()
            return expr
Пример #4
0
def get_expression(buffer: TokenBuffer) -> Union[Expression, None]:
    token = buffer.pop_next_token()
    if token is None:
        return None
    elif token in ("(", "["):
        return get_rest_of_list(buffer, ")" if token == "(" else "]")
    elif token == "'":
        return make_list([Symbol("quote"), get_expression(buffer)])
    elif token == ",":
        if buffer.get_next_token() == "@":
            buffer.pop_next_token()
            return make_list(
                [Symbol("unquote-splicing"),
                 get_expression(buffer)])
        else:
            return make_list([Symbol("unquote"), get_expression(buffer)])
    elif token == "`":
        return make_list([Symbol("quasiquote"), get_expression(buffer)])
    elif token == ".":
        if logger.dotted:
            raise ParseError(f"Unexpected token: '{token}'")
        else:
            return make_list([Symbol("variadic"), get_expression(buffer)])
    elif token == "\"":
        return get_string(buffer)
    elif token in SPECIALS:
        raise ParseError(f"Unexpected token: '{token}'")
    elif is_number(token.value):
        try:
            return Number(int(token.value))
        except ValueError:
            return Number(float(token.value))
    elif token == "#t" or token.value.lower() == "true":
        return SingletonTrue
    elif token == "#f" or token.value.lower() == "false":
        return SingletonFalse
    elif token == "nil":
        return Nil
    elif is_str(token.value):
        return Symbol(token.value.lower())
    else:
        raise ParseError(f"Unexpected token: '{token}'")
Пример #5
0
def side_menu():
    db = con()
    user_id = session.get("user_id")

    # select all data from users table

    semesters = db.execute("SELECT * FROM semesters WHERE user_id=?",
                           (user_id, ))

    sub_sem_list = make_list(semesters)
    return dict(sub_sem_list=sub_sem_list)
 def execute(self, operands: List[Expression], frame: Frame, gui_holder: Holder, eval_operands=True):
     verify_exact_callable_length(self, 1, len(operands))
     if eval_operands:
         operands = evaluate_all(operands, frame, gui_holder.expression.children[1:])
     if not isinstance(operands[0], String):
         raise OperandDeduceError(f"Load expected a String, received {operands[0]}.")
     if logger.fragile:
         raise IrreversibleOperationError()
     from os import listdir
     from os.path import join
     directory = operands[0].value
     try:
         targets = sorted(listdir(directory))
         targets = [join(directory, target) for target in targets if target.endswith(".scm")]
         exprs = [make_list([Symbol("load"), make_list([Symbol("quote"), Symbol(x[:-4])])]) for x in targets]
         equiv = make_list([Symbol("begin-noexcept")] + exprs)
         gui_holder.expression.set_entries([equiv])
         gui_holder.apply()
         return evaluate(equiv, frame, gui_holder.expression.children[0], True)
     except Exception as e:
         raise SchemeError(e)
Пример #7
0
 def execute_evaluated(self, operands: List[Expression],
                       frame: Frame) -> Expression:
     if (len(operands) == 0):
         return Nil
     out = []
     for operand in operands[:(-1)]:
         if ((not isinstance(operand, Pair)) and (operand is not Nil)):
             raise OperandDeduceError(''.join([
                 'Expected operand to be valid list, not ',
                 '{}'.format(operand)
             ]))
         out.extend(pair_to_list(operand))
     try:
         last = operands[(-1)]
         if (not isinstance(last, Pair)):
             raise OperandDeduceError()
         last = pair_to_list(last)
     except OperandDeduceError:
         return make_list(out, operands[(-1)])
     else:
         out.extend(last)
         return make_list(out)
Пример #8
0
def index():
    """ gets all the data from database and display"""
    db = con()
    user_id = session.get("user_id")
    #"INSERT INTO users(first_name, last_name, email) VALUES ('Sandipa', 'Rijal', '*****@*****.**')"
    #table ="CREATE TABLE subjects (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, semester_id INTEGER, user_id INTEGER, FOREIGN KEY (user_id) REFERENCES users(id))"

    # select all data from users table
    user = db.execute("SELECT * FROM users WHERE id =?", (user_id, ))
    semesters = db.execute("SELECT * FROM semesters WHERE user_id=?",
                           (user_id, ))

    sub_sem_list = make_list(semesters)

    # return the template index
    return render_template("index.html")
Пример #9
0
def get_rest_of_list(buffer: TokenBuffer, end_paren: str) -> Expression:
    out = []
    last = Nil
    while True:
        next = buffer.get_next_token()
        if next == end_paren:
            buffer.pop_next_token()
            break
        elif logger.dotted and next == ".":
            buffer.pop_next_token()
            last = get_expression(buffer)
            if buffer.pop_next_token() != end_paren:
                raise ParseError(
                    f"Only one expression may follow a dot in a dotted list.")
            break
        expr = get_expression(buffer)
        out.append(expr)
    out = make_list(out, last)
    return out
Пример #10
0
 def quasiquote_evaluate(cls,
                         expr: Expression,
                         frame: Frame,
                         gui_holder: Holder,
                         splicing=False):
     is_well_formed = False
     if isinstance(expr, Pair):
         try:
             lst = pair_to_list(expr)
         except OperandDeduceError:
             pass
         else:
             is_well_formed = (not any(
                 map((lambda x:
                      (isinstance(x, Symbol) and
                       (x.value in
                        ['unquote', 'quasiquote', 'unquote-splicing']))),
                     lst)))
     visual_expression = VisualExpression(expr)
     gui_holder.link_visual(visual_expression)
     if (not is_well_formed):
         visual_expression.children[2:] = []
     if isinstance(expr, Pair):
         if (isinstance(expr.first, Symbol)
                 and (expr.first.value in ('unquote', 'unquote-splicing'))):
             if ((expr.first.value == 'unquote-splicing')
                     and (not splicing)):
                 raise OperandDeduceError(
                     'Unquote-splicing must be in list template.')
             gui_holder.evaluate()
             verify_exact_callable_length(expr.first, 1,
                                          (len(pair_to_list(expr)) - 1))
             out = evaluate(expr.rest.first, frame,
                            visual_expression.children[1])
             visual_expression.value = out
             gui_holder.complete()
             return out
         elif (isinstance(expr.first, Symbol)
               and (expr.first.value == 'quasiquote')):
             visual_expression.value = expr
             gui_holder.complete()
             return expr
         else:
             if is_well_formed:
                 out = []
                 for (sub_expr, holder) in zip(pair_to_list(expr),
                                               visual_expression.children):
                     splicing = (isinstance(sub_expr, Pair)
                                 and isinstance(sub_expr.first, Symbol)
                                 and (sub_expr.first.value
                                      == 'unquote-splicing'))
                     evaluated = Quasiquote.quasiquote_evaluate(
                         sub_expr, frame, holder, splicing)
                     if splicing:
                         if (not isinstance(evaluated, (Pair, NilType))):
                             raise TypeMismatchError(''.join([
                                 'Can only splice lists, not ',
                                 '{}'.format(evaluated), '.'
                             ]))
                         out.extend(pair_to_list(evaluated))
                     else:
                         out.append(evaluated)
                 out = make_list(out)
             else:
                 if (not logger.dotted):
                     raise OperandDeduceError(''.join([
                         '{}'.format(expr),
                         ' is an ill-formed quasiquotation.'
                     ]))
                 out = Pair(
                     Quasiquote.quasiquote_evaluate(
                         expr.first, frame, visual_expression.children[0]),
                     Quasiquote.quasiquote_evaluate(
                         expr.rest, frame, visual_expression.children[1]))
             visual_expression.value = out
             gui_holder.complete()
             return out
     else:
         visual_expression.value = expr
         gui_holder.complete()
         return expr
Пример #11
0
 def execute_evaluated(self, operands: List[Expression],
                       frame: Frame) -> Expression:
     return make_list(operands)