예제 #1
0
    def done(self, res):
        if res == QDialog.Accepted:
            name = self.ui.txtVariable.text().strip()
            parsed = parse(name)

            if not isinstance(parsed, (IdentifierNode, ArrayAccessNode)):
                box = msg_box_error(translate(
                    "Algo",
                    "Invalid assignment target (must be either variable or array item): {name}"
                ).format(name=name),
                                    parent=self)
                box.exec_()
                return

            if self.ui.cbxHasValue.isChecked():
                p = try_parse(self.ui.txtValue.text(), self)

                if p is None:
                    return

                self.expr = p
            else:
                self.expr = None

            self.varname = parsed
            self.ok = True

        super(AlgoInputStmt, self).done(res)
예제 #2
0
def parse_expr(expr: str) -> AstNode:
    """Fixes it to match the Turing syntax and parses it."""
    lut = {"Math.PI": "pi", "&&": "&", "||": "|"}

    for k, v in lut.items():
        expr = expr.replace(k, v)

    return parse(expr)
예제 #3
0
파일: alg_gfunc.py 프로젝트: noirHck/Turing
    def done(self, res):
        if res == QDialog.Accepted:
            name = self.ui.txtVariable.text()
            parsed = parse(name)

            if not isinstance(parsed, IdentifierNode):
                box = msg_box_error(translate("Algo",
                                              "Invalid variable name: {name}").format(
                    name=name), parent=self)
                box.exec_()
                return

            self.f_variable = name

            p = try_parse(self.ui.txtFunction.text(), self)

            if p is None:
                return

            self.f_function = p

            p = try_parse(self.ui.txtStart.text(), self)

            if p is None:
                return

            self.f_start = p

            p = try_parse(self.ui.txtEnd.text(), self)

            if p is None:
                return

            self.f_end = p

            p = try_parse(self.ui.txtStep.text(), self)

            if p is None:
                return

            self.f_step = p

            p = try_parse(self.ui.txtColor.text(), self)

            if p is None:
                return

            self.f_color = p

            self.ok = True

        super(AlgoGFuncStmt, self).done(res)
예제 #4
0
def to_stmt(elem: ElementTree) -> Optional[Union[BaseStmt, CodeBlock]]:
    """Converts an Algobox XML element to a Turing statement."""
    if elem.tag == "description":
        value = elem.attrib["texte"]

        if not value:
            return None

        return [
            CommentStmt(x)
            for x in elem.attrib["texte"].replace("\r\n", "\n").split("\n")
        ]

    if elem.tag == "repere":
        if elem.attrib["repetat"] == "inactif":
            return None

        xmin, xmax, ymin, ymax, xgrad, ygrad = elem.attrib["repcode"].split(
            "#")

        return GWindowStmt(parse_expr(xmin), parse_expr(xmax),
                           parse_expr(ymin), parse_expr(ymax),
                           parse_expr(xgrad), parse_expr(ygrad))

    if elem.tag == "fonction":
        if elem.attrib["fctetat"] == "inactif":
            return None

        return AssignStmt(
            IdentifierNode("F1"),
            LambdaNode(["x"], parse_expr(elem.attrib["fctcode"])))

    if elem.tag == "item":
        code, *args = elem.attrib["code"].split("#")
        code = int(code)
        children = []

        if len(list(elem)) != 0:
            for e in elem:
                s = to_stmt(e)

                if s is None:
                    continue

                if builtins.type(s) == list:
                    children.extend(s)
                else:
                    children.append(s)

        if code == 1:  # VARIABLE
            type, varname = args

            value = None

            if type == "NOMBRE":
                value = NumberNode(0)
            elif type == "CHAINE":
                value = StringNode("")
            elif type == "LISTE":
                value = ListNode([])

            if value is None:
                raise ValueError(
                    translate(
                        "Algobox",
                        "Unknown variable type: {type}").format(type=type))

            return AssignStmt(IdentifierNode(varname), value)

        elif code == 2:  # LIRE
            varname, index = args

            if index == "pasliste":
                return InputStmt(IdentifierNode(varname))

            return InputStmt(
                ArrayAccessNode(IdentifierNode(varname), parse(index)))

        elif code == 3:  # AFFICHER
            varname, newline, index = args

            if index == "pasliste":
                return DisplayStmt(IdentifierNode(varname), bool(int(newline)))

            return DisplayStmt(
                ArrayAccessNode(IdentifierNode(varname), parse(index)),
                bool(int(newline)))

        elif code == 4:  # MESSAGE
            message, newline = args

            return DisplayStmt(StringNode(message), bool(int(newline)))

        elif code == 5:  # AFFECTATION
            varname, value, index = args

            if index == "pasliste":
                return AssignStmt(IdentifierNode(varname), parse_expr(value))

            return AssignStmt(
                ArrayAccessNode(IdentifierNode(varname), parse_expr(index)),
                parse_expr(value))

        elif code == 6:  # SI
            condition = args[0]

            if isinstance(children[-1], ElseStmt):
                return [
                    IfStmt(parse_expr(condition), children[:-1]), children[-1]
                ]

            return IfStmt(parse_expr(condition), children)

        elif code == 7:  # DEBUT_SI
            return None

        elif code == 8:  # FIN_SI
            return None

        elif code == 9:  # SINON
            return ElseStmt(children)

        elif code == 10:  # DEBUT_SINON
            return None

        elif code == 11:  # FIN_SINON
            return None

        elif code == 12:  # POUR
            varname, begin, end = args

            return ForStmt(varname, parse_expr(begin), parse_expr(end),
                           children)

        elif code == 13:  # DEBUT_POUR
            return None

        elif code == 14:  # FIN_POUR
            return None

        elif code == 15:  # TANT_QUE
            condition = args[0]

            return WhileStmt(parse_expr(condition), children)

        elif code == 16:  # DEBUT_TANT_QUE
            return None

        elif code == 17:  # FIN_TANT_QUE
            return None

        elif code == 18:  # PAUSE
            return BreakStmt()

        elif code == 19:  # COMMENTAIRE
            value = args[0]

            return CommentStmt(value)

        elif code == 20:  # AFFICHERCALCUL
            calcul, newline = args

            return DisplayStmt(parse_expr(calcul), bool(int(newline)))

        elif code == 50:  # POINT
            x, y, color = args

            return GPointStmt(parse_expr(x), parse_expr(y),
                              StringNode(get_color(color)))

        elif code == 51:  # SEGMENT
            start_x, start_y, end_x, end_y, color = args

            return GLineStmt(parse_expr(start_x), parse_expr(start_y),
                             parse_expr(end_x), parse_expr(end_y),
                             StringNode(get_color(color)))

        elif code == 52:  # EFFACE
            return GClearStmt()

        elif code == 100:  # VARIABLES
            return children

        elif code == 101:  # DEBUT_ALGO
            return children

        elif code == 102:  # FIN_ALGO
            return None

        elif code == 103:  # autres
            pass

        elif code == 200:  # FONCTIONS_UTILISEES
            return children

        elif code == 201:  # FONCTION
            name, params = args

            return FuncStmt(name, [x.strip() for x in params.split(",")],
                            children)

        elif code == 202:  # VARIABLES_FONCTION
            return children

        elif code == 203:  # DEBUT_FONCTION
            return None

        elif code == 204:  # FIN_FONCTION:
            return None

        elif code == 205:  # RENVOYER_FONCTION
            value = args[0]

            return ReturnStmt(parse_expr(value))

        elif code == 206:  # APPELER_FONCTION
            expr = args[0]

            return CallStmt.from_node(parse_expr(expr))

        else:
            print("unknown type %d" % code)
            return None

        print("unimpl type %d" % code)
예제 #5
0
        entry
    ) & 0xFFFF  # Checksum = lower 16-bits of the sum of all bytes in data

    file = struct.pack("<8s 3s 42s H",
                       b"**TI83F*",  # Signature
                       b"\x1A\x0A\x0A",  # 2nd signature
                       b"Turing rocks!",  # Comment
                       len(entry)) \
           + entry \
           + struct.pack("<H", checksum)

    return file


algo = [
    ForStmt("i", parse("1"), parse("16"), [
        IfStmt(parse("i % 15 == 0"), [DisplayStmt(parse("\"FizzBuzz\""))]),
        ElseStmt([
            IfStmt(parse("i % 3 == 0"), [DisplayStmt(parse("\"Fizz\""))]),
            ElseStmt([
                IfStmt(parse("i % 5 == 0"), [DisplayStmt(parse("\"Buzz\""))]),
                ElseStmt([DisplayStmt(parse("i"))])
            ])
        ]),
    ])
]

arr = ["%02X" % x for x in package("DEADBEEF", binify(convert_block(algo)))]
print(arr)
print("".join(arr))
예제 #6
0
파일: __tests__.py 프로젝트: noirHck/Turing
# -*- coding: utf-8 -*-

from algo.stmts import *
from algo.worker import Worker
from maths.parser import quick_parse as parse
from tests.framework import expect

tests = [
    ([
        AssignStmt(parse("sum"), parse("0")),
        InputStmt(parse("N")),
        ForStmt("i", parse("1"), parse("N"),
                [AssignStmt(parse("sum"), parse("sum + i"))]),
        DisplayStmt(parse("\"Result=\" + sum"))
    ], "5", ["Variable N = 5", "Result=15"]),
    ([
        ForStmt(
            "i", parse("1"), parse("3"),
            [ForStmt("i", parse("1"), parse("3"), [DisplayStmt(parse("i"))])])
    ], "", [
        "1",
        "2",
        "3",
        "1",
        "2",
        "3",
        "1",
        "2",
        "3",
    ]),
    ([