示例#1
0
    def _run(self, interpreter: Interpreter):
        try_clause = interpreter.stack_pop().get_value()
        else_clause = interpreter.stack_pop().get_value()
        exception = interpreter.stack_pop().get_value()

        try:
            try_clause(interpreter)
        except exception:
            else_clause(interpreter)
示例#2
0
    def run(self, interpreter: Interpreter):
        """Runs all subtokens, then itself"""
        if self._sorted_tokens is None:
            self._sorted_tokens = sorted(
                [x for x in self.tokens if x.functional], key=lambda x: x.run_order
            )

        for token in self._sorted_tokens:
            interpreter.run(token)  # type: ignore
        self._run(interpreter)
示例#3
0
    def run(self, interpreter: Interpreter):
        if self.collection is None:
            interpreter.run(self.tokens[-1])
            self.collection = interpreter.stack_pop().get_value()

        try:
            collection_value = self.collection[self._index]
        except IndexError:
            self.reset()
            raise exceptions.BreakIterationException(self) from None
        except TypeError:
            raise exceptions.TypeException(
                f"Cannot iterate through value of type {self.collection.__class__.__name__}!",
                token=self,
            ) from None

        value = self.TOKEN_FACTORY.create_any_value(value=collection_value)
        interpreter.stack_append(value)
        self._index += 1

        # ignore collection (last token), as it was previously run
        for token in self.tokens[:-1]:
            interpreter.run(token)

        # append it again, this value can be consumed by optional for-each
        # condition, or needs to be thrown away by for-each loop if no condition
        interpreter.stack_append(value)
示例#4
0
    def _run(self, interpreter: Interpreter):
        collection = interpreter.stack_pop()
        try:
            list_ = list(collection.get_value())
        except TypeError:
            raise exceptions.TypeException(
                f"Value of type {collection.get_value().__class__.__name__} is not iterable!"
            ) from None

        function = interpreter.stack_pop()
        # some functions dont have inputs
        if (not function.inputs or not function.inputs.value
                or not len(function.inputs.value) == 1):
            raise exceptions.TypeException(
                "Apply function should expect one input!")

        interpreter.add_stack()
        variable = function.inputs.value[0]
        interpreter.set_variable(variable.name, variable)
        for i, value in enumerate(list_):
            variable.value = value
            try:
                function.get_value()(interpreter)
            except TypeError:
                raise exceptions.TypeException(
                    f"Cannot call variable of type {function.get_value().__class__.__name__}!"
                ) from None
            except exceptions.ReturnException:
                pass
            collection.value[i] = interpreter.stack_pop().get_value(
            )  # return value
        interpreter.remove_stack()
示例#5
0
 def _run(self, interpreter: Interpreter):
     variable = interpreter.stack_pop()
     value = interpreter.stack_pop()
     try:
         self.do_operation(variable, value)  # pylint: disable=no-member
     except TypeError:
         type_ = lambda x: x.get_value().__class__.__name__
         raise exceptions.TypeException(
             f"Unsupported operation for types {type_(variable)} and {type_(value)}!",
             token=self,
         ) from None
示例#6
0
    def _run(self, interpreter: Interpreter):
        collection_variable = interpreter.stack_pop()
        collection: List[Any] = collection_variable.get_value()
        value = interpreter.stack_pop().get_value()

        try:
            collection.append(value)
        except AttributeError:
            raise exceptions.TypeException(
                f"Cannot append value to type {collection.__class__.__name__}!",
                token=self,
            ) from None
示例#7
0
 def _run(self, interpreter: Interpreter):
     index = interpreter.stack_pop().get_value()
     parent_value = interpreter.stack_pop().get_value()
     value = interpreter.stack_pop()
     try:
         parent_value[index] = value.get_value()
     except TypeError:
         raise exceptions.TypeException(
             f"Value of type {parent_value.__class__.__name__} cannot be indexed!"
         ) from None
     except IndexError:
         raise exceptions.ValueException("Index out of range!") from None
示例#8
0
    def _run(self, interpreter: Interpreter):
        collection = interpreter.stack_pop().get_value()

        try:
            len_ = len(collection)
        except TypeError:
            raise exceptions.TypeException(
                f"Value of type {collection.__class__.__name__} has no length!",
                token=self,
            ) from None

        length = self.TOKEN_FACTORY.create_value(len_)
        interpreter.stack_append(length)
示例#9
0
    def run(self, interpreter: Interpreter):
        interpreter.run(self.tokens[-1])
        clause_function = interpreter.stack_pop().get_value()
        condition = self.tokens[0]
        while True:
            condition.run(interpreter)
            if not interpreter.stack_pop().get_value():
                break

            try:
                clause_function(interpreter)
            except exceptions.BreakIterationException:
                break
示例#10
0
        def inner(interpreter: Interpreter):
            args = []
            for x in range(function.__code__.co_argcount):
                try:
                    args.append(interpreter.get_variable(x).get_value())
                except exceptions.UndefinedVariableException:
                    break

            try:
                return_value = function(*args)
            except TypeError as exc:
                raise exceptions.RunTimeException(token=self) from exc
            interpreter.stack_append(
                self.TOKEN_FACTORY.create_any_value(return_value))
示例#11
0
    def _run(self, interpreter: Interpreter):
        collection: List[Any] = interpreter.stack_pop().get_value()
        value = interpreter.stack_pop().get_value()

        try:
            collection.remove(value)
        except AttributeError:
            raise exceptions.TypeException(
                f"Cannot remove value from type {collection.__class__.__name__}!",
                token=self,
            ) from None
        except ValueError:
            raise exceptions.ValueException("Value not in collection!",
                                            token=self) from None
示例#12
0
    def run(self, interpreter: Interpreter):
        interpreter.run(self.tokens[0])
        collection = interpreter.stack_pop().get_value()

        for value in collection:
            result = self._get_condition_result(value, interpreter)
            if self._check_if_should_break(result):  # pylint: disable=no-member
                condition_value = not self.initial_condition_value
                break
        else:
            condition_value = self.initial_condition_value

        result = self.TOKEN_FACTORY.create_value(condition_value)
        interpreter.stack_append(result)
示例#13
0
    def _run(self, interpreter: Interpreter):
        value = interpreter.stack_pop().get_value()
        if not isinstance(value, str):
            raise exceptions.TypeException(
                f"Value of type {value.__class__.__name__} is not a valid file identifier!"
            )

        try:
            with open(value, "r", encoding="utf-8") as file:
                content = file.read()
        except:
            raise exceptions.FileNotFoundException(
                f"File {value} cannot be read!") from None

        interpreter.stack_append(self.TOKEN_FACTORY.create_value(content))
示例#14
0
    def _run(self, interpreter: Interpreter):
        try:
            collection = interpreter.stack_pop()
        except exceptions.EmptyStackError:
            self.raise_syntax_exception()

        interpreter.stack_append(collection)

        try:
            len_ = len(collection.get_value())
        except TypeError:
            raise exceptions.TypeException(
                f"Value of type {collection.__class__.__name__} has no length!"
            ) from None

        interpreter.stack_append(self.TOKEN_FACTORY.create_value(len_))
示例#15
0
    def _run(self, interpreter: Interpreter):
        variable = interpreter.stack_pop()
        collection = interpreter.stack_pop().get_value()
        index = interpreter.stack_pop().get_value()

        try:
            variable.value = collection[index]
        except IndexError:
            raise exceptions.ValueException(
                f"Collection index {index} out of range!") from None
        except TypeError:
            raise exceptions.TypeException(
                f"Cannot index value of type {collection.__class__.__name__}!"
            ) from None

        interpreter.set_variable(variable.name, variable)
示例#16
0
    def run(self, interpreter: Interpreter):
        while True:
            try:
                for token in self.tokens:
                    interpreter.run(token)
            except exceptions.BreakIterationException:
                break

            clause = interpreter.stack_pop()
            try:
                if self._check_condition(interpreter):
                    clause.get_value()(interpreter)
            except exceptions.SkipElementException:
                pass
            except exceptions.BreakIterationException:
                break
示例#17
0
    def _run(self, interpreter: Interpreter):
        variable = interpreter.stack_pop()
        collection_variable: List[Any] = interpreter.stack_pop()
        collection = collection_variable.get_value()

        try:
            variable.value = collection.pop()
        except AttributeError:
            raise exceptions.TypeException(
                f"Cannot pop from type {collection.__class__.__name__}!",
                token=self) from None
        except IndexError:
            raise exceptions.ValueException(
                "Cannot pop from empty collection!", token=self) from None

        interpreter.set_variable(variable.name, variable)
示例#18
0
 def _run(self, interpreter: Interpreter):
     value = interpreter.stack_pop()
     try:
         value.value = round(value.value)
     except TypeError:
         raise exceptions.TypeException(
             f"Cannot round value of type {value.value.__class__.__name__}!"
         ) from None
示例#19
0
 def _run(self, interpreter: Interpreter):
     collection: List[Any] = interpreter.stack_pop().get_value()
     try:
         collection.reverse()
     except AttributeError:
         raise exceptions.TypeException(
             f"Cannot reverse value of type {collection.__class__.__name__}!"
         ) from None
示例#20
0
 def _run(self, interpreter: Interpreter):
     value: List[Any] = interpreter.stack_pop().get_value()
     try:
         value.sort()
     except AttributeError:
         raise exceptions.TypeException(
             f"Cannot sort value of type {value.__class__.__name__}"
         ) from None
示例#21
0
    def _run(self, interpreter: Interpreter):
        mode = "w"
        if self.has_all_optionals:
            interpreter.stack_pop()
            mode = "a"

        filename = interpreter.stack_pop().get_value()
        if not isinstance(filename, str):
            raise exceptions.TypeException(
                f"Value of type {filename.__class__.__name__} is not a valid file identifier!"
            )

        value = interpreter.stack_pop().get_value()
        try:
            with open(filename, mode=mode, encoding="utf-8") as file:
                file.write(value)
        except Exception as exc:
            raise exceptions.RunTimeException(
                f"Failed to read file {filename}!") from exc
示例#22
0
    def _import_python_module(self, interpreter: Interpreter,
                              filename: str) -> None:
        module = importlib.import_module(os.path.splitext(filename)[0])
        interpreter.add_stack()
        for name, value in module.__dict__.items():
            if name.startswith("_"):
                continue

            variable = self.TOKEN_FACTORY.create_variable(name)
            if callable(value):
                variable.inputs = self.TOKEN_FACTORY.create_iterable_value(
                    value=[
                        self.TOKEN_FACTORY.create_variable(x)
                        for x in range(value.__code__.co_argcount)
                    ])
                value = self._wrap_python_callable(value)
            variable.value = value
            interpreter.set_variable(name, variable)
            interpreter.set_variable("it", variable)
示例#23
0
    def _run(self, interpreter: Interpreter):
        end_index = interpreter.stack_pop().get_value()
        collection = interpreter.stack_pop().get_value()
        start_index = interpreter.stack_pop().get_value()
        if not isinstance(start_index, int):
            raise exceptions.ValueException(
                f"Wrong index of type {start_index.__class__.__name__}!"
            ) from None

        try:
            subcollection = collection[start_index:end_index]
        except TypeError:
            raise exceptions.TypeException(
                f"Value of type {collection.__class__.__name__} cannot be indexed!"
            ) from None
        except IndexError:
            raise exceptions.ValueException("Index out of range!") from None

        interpreter.stack_append(
            self.TOKEN_FACTORY.create_iterable_value(subcollection))
示例#24
0
    def _run(self, interpreter: Interpreter):
        try:
            variable = interpreter.get_variable(self.value)
        except exceptions.UndefinedVariableException:
            variable = self.TOKEN_FACTORY.create_variable(self.value)

        if self.has_all_optionals:
            default_value = interpreter.stack_pop()
            variable.value = default_value.get_value()
            interpreter.set_variable(variable.name, variable)

        interpreter.stack_append(variable)
        interpreter.set_variable("it", variable)
示例#25
0
    def run(self, interpreter: Interpreter):
        interpreter.run(self.tokens[-1])
        collection = interpreter.stack_pop().get_value()

        try:
            collection_value = collection[self.RETURN_TOKEN_INDEX]
        except IndexError:
            raise exceptions.ValueException(
                "Cannot extract value from empty collection!") from None
        except TypeError:
            raise exceptions.TypeException(
                f"Cannot extract from value of type {collection.__class__.__name__}!",
            ) from None

        value = self.TOKEN_FACTORY.create_any_value(collection_value)
        interpreter.stack_append(value)
        # ignore collection (last token), as it was previously run
        for token in self.tokens[:-1]:
            interpreter.run(token)

        # append it again, previous stack append gets consumed by IN token
        interpreter.stack_append(value)
示例#26
0
    def _import_tokens(self, interpreter: Interpreter, filename: str) -> None:
        if self.TOKEN_COMPILER is not None:
            try:
                tokens = self.TOKEN_COMPILER.read_compiled_file(filename)
            except self.TOKEN_COMPILER.exception:
                tokens = self._construct_tokens(filename)
        else:
            tokens = self._construct_tokens(filename)

        interpreter.add_stack()
        for token in tokens:
            interpreter.init(token)

        with path.ChangeDir(os.path.dirname(filename)):
            for token in tokens:
                interpreter.run(token)
示例#27
0
    def run(self, interpreter: Interpreter):
        interpreter.run(self.tokens[0])
        import_variables = interpreter.stack_pop().value
        filename = self.tokens[-1].value

        import_ = (self._import_python_module
                   if filename.endswith(".py") else self._import_tokens)
        try:
            import_(interpreter, filename)
        except (FileNotFoundError, ModuleNotFoundError):
            raise exceptions.ImportException(
                f"Failed to import because file could not be found: {filename}",
                token=self,
            ) from None

        variables: List[Variable] = []
        for import_variable in import_variables:

            try:
                variable = interpreter.get_variable(import_variable.name)
            except AttributeError:
                type_ = import_variable.value.__class__.__name__
                raise exceptions.ValueException(
                    f"Cannot import: value of type {type_} is not a variable!"
                ) from None

            if variable.get_qualifier("private"):
                raise exceptions.ImportException(
                    f"Could not import private variable {variable.name} from module {filename}!",
                    token=self,
                ) from None
            variables.append(variable)
        interpreter.remove_stack()

        for variable in variables:
            interpreter.set_variable(variable.name, variable)
示例#28
0
 def _run(self, interpreter: Interpreter):
     variable: Variable = interpreter.stack_pop()  # type: ignore
     value = interpreter.stack_pop()
     variable.value = value.get_value()
     interpreter.set_variable(variable.name, variable)
示例#29
0
 def init(self, interpreter: Interpreter):
     """Initialises all subtokens, then itself"""
     for token in self.tokens:
         if token.functional:
             interpreter.init(token)  # type: ignore
     self._init(interpreter)
示例#30
0
 def _check_condition(self, interpreter: Interpreter) -> bool:
     value = interpreter.stack_pop()
     if not self.has_all_optionals:
         return True
     return value.get_value()