Esempio n. 1
0
def run_repl():
    repl = Context()
    first_prompt = ": "
    second_prompt = "| "
    lines = []
    index = 0
    while True:
        if not lines:
            prompt = str(index)
            prompt = "$" + prompt
            line = input(prompt + first_prompt)
            if line:
                if line == "Exit":
                    return
                else:
                    lines.append(line)
        else:
            prompt = " " * len(str(index)) + " "
            line = input(prompt + second_prompt)
            if line:
                lines.append(line)
            else:
                print("\033[A                             \033[A")
                try:
                    ast = ParseNode.parse("\n".join(lines))
                    value = ast.evaluate(repl)
                    name = Value("$" + str(index), "ValueName")
                    print(name.value + " = " + value.__str__())
                    index += 1
                    repl.set(name, value)
                except EvaluationError as e:
                    print("EvaluationError: " + e.__str__())
                lines = []
Esempio n. 2
0
    def __init__(self, tab_indexes, tabs, tab_buttons, element_buttons,
                 command_label, prefs):
        self.tab_indexes = tab_indexes
        self.tabs = tabs
        self.tab_buttons = tab_buttons
        self.element_buttons = element_buttons
        self.active_type = None
        self.command_label = command_label
        self.command_label.label.width = 100
        self.command_label.label.multiline = True
        self.prefs = prefs
        hotkey_index = 0
        self.hotkeys = {}
        self.burl_context = Context()
        self.burl_context.parse_eval("LoadModule composition")
        for module in self.prefs.modules:
            self.burl_context.parse_eval("LoadModule " + module)
        self.burl_cursor = None

        for row in range(min(self.prefs.card_rows,
                             len(CommandCard.card_keys))):
            for column in range(
                    min(self.prefs.card_columns,
                        len(CommandCard.card_keys[row]))):
                self.hotkeys[CommandCard.card_keys[row][column]] = hotkey_index
                hotkey_index += 1

        for element_type, index in self.tab_indexes.items():
            if index == 0:
                self.change_tab(element_type)
                break

        self.update_cursor()
        self.command_label.label.text = str(self.burl_cursor)
        self.command_label.label.font_size = self.command_label.label.font_size
Esempio n. 3
0
def make_context(parent=None,
                 values=None,
                 definitions=None,
                 types=None,
                 evaluations=None,
                 modules=None,
                 temp_parent=None,
                 load_core=True):
    context = Context(parent=temp_parent or parent,
                      values=values,
                      definitions=definitions,
                      types=types,
                      load_core=load_core)

    for evaluation in evaluations or []:
        parsed = ParseNode.parse(evaluation[1])
        element = parsed.evaluate(context).value
        if isinstance(element, Literal):
            element.value = evaluation[0]
        elif isinstance(element, Builtin):
            element.func = evaluation[0]

    if temp_parent:
        context.parent = parent

    return context
Esempio n. 4
0
def workspace():
    test = Context()
    test.definitions['AddOne'] = Definition('AddOne',
                                            'Number',
                                            [Parameter('value', 'Number')],
                                            context=test,
                                            code="""
Sum 1 Get value
	""")

    ast = ParseNode.parse("""
Define AddTwo Number
	Parameter value Number
	Sum one one Get value""")
    print(ast)
    ast.evaluate(test)
    print(test.definitions.keys())

    ast = ParseNode.parse("""
SetLocal hi
	Sum 1 1
SetLocal hi
	AddOne Get hi
Define AddThree Number
	Parameter value Number
	Sum 3 Get value
SetLocal hi
	AddThree Get hi
If Some Compare 1 > 2 False
	Get hi
	Sum
		-1
		Get hi""")
    print(ast)
    print(ast.evaluate(test).value)
Esempio n. 5
0
def run_module(module, function, args=[]):
    context = Context()
    ast = ParseNode.parse("""
LoadModule %s
%s %s""" % (module, function, " ".join(args)))
    try:
        result = ast.evaluate(context)
        if result.element_type == "ValueName" and result.value == function:
            # will throw an error if the function doesn't exist
            context.get_definition(function)
        print(result)
    except EvaluationError as e:
        print("EvaluationError: %s" % (e.__str__()))
Esempio n. 6
0
def load_module(context, path, name):
    if not name:
        name = os.path.basename(path)
        if name.endswith('.burl'):
            name = name[:-5]
    name = name or os.path.splitext()
    if name in context.module_references:
        if name == 'core':
            return context.module_references['core']
        raise EvaluationError("Cannot load module with name " + name +
                              ", another module with this name already exists")

    module = ModuleDictionary.instance().get_module(path)
    if module:
        context.module_references[name] = module
        return module.value
    try:
        with open(path) as f:
            module_context = Context()
            value = ParseNode.parse(f.read()).evaluate(module_context)
            module = Module(path, context=module_context, value=value)
            ModuleDictionary.instance().add_module(module)
            context.module_references[path] = module
            return module.value
    except (OSError, FileNotFoundError):
        raise EvaluationError("Could not find module with path " + path)
    except EvaluationError as e:
        raise EvaluationError("Parsing module failed at path " + path + "\n" +
                              e.__str__())
Esempio n. 7
0
 def evaluate(self, context, unevaluated_arguments):
     args = self.evaluate_arguments(context, unevaluated_arguments)
     values = {}
     for param, arg in zip(self.parameters, args):
         values[param.name] = arg
     child_context = Context(context, values=values)
     return self.evaluator.evaluate(child_context)
Esempio n. 8
0
    def run(self):
        Test.total += 1
        context = Context()

        try:
            if self.code:
                ast = ParseNode.parse(self.code)
                result = ast.evaluate(context)
            else:
                result = self.func()
            if result and result.value == self.expected_value:
                print("Success: %s" % self.name)
                Test.success += 1
            else:
                print("  Wrong: %s, Expected: %s, Got: %s" %
                      (self.name, str(self.expected_value), result.__str__()))
                Test.wrong += 1
        except EvaluationError as e:
            print("  Error: %s - %s" % (self.name, e.__str__()))
            Test.error += 1
Esempio n. 9
0
class CommandCard():
    # rmf todo: configurable keys, common keyboard layouts
    card_keys = [
        [
            key._1,
            key._2,
            key._3,
            key._4,
            key._5,
        ],
        [
            key.Q,
            key.W,
            key.E,
            key.R,
            key.T,
        ],
        [
            key.A,
            key.S,
            key.D,
            key.F,
            key.G,
        ],
        [
            key.Z,
            key.X,
            key.C,
            key.V,
            key.B,
        ],
    ]

    def __init__(self, tab_indexes, tabs, tab_buttons, element_buttons,
                 command_label, prefs):
        self.tab_indexes = tab_indexes
        self.tabs = tabs
        self.tab_buttons = tab_buttons
        self.element_buttons = element_buttons
        self.active_type = None
        self.command_label = command_label
        self.command_label.label.width = 100
        self.command_label.label.multiline = True
        self.prefs = prefs
        hotkey_index = 0
        self.hotkeys = {}
        self.burl_context = Context()
        self.burl_context.parse_eval("LoadModule composition")
        for module in self.prefs.modules:
            self.burl_context.parse_eval("LoadModule " + module)
        self.burl_cursor = None

        for row in range(min(self.prefs.card_rows,
                             len(CommandCard.card_keys))):
            for column in range(
                    min(self.prefs.card_columns,
                        len(CommandCard.card_keys[row]))):
                self.hotkeys[CommandCard.card_keys[row][column]] = hotkey_index
                hotkey_index += 1

        for element_type, index in self.tab_indexes.items():
            if index == 0:
                self.change_tab(element_type)
                break

        self.update_cursor()
        self.command_label.label.text = str(self.burl_cursor)
        self.command_label.label.font_size = self.command_label.label.font_size

    def change_tab(self, element_type):
        self.tabs.set_active_tab(self.tab_indexes[element_type])
        self.active_type = element_type
        # disable element_buttons that aren't allowed

    def append_element(self, element, element_type):
        self.element_buttons['Meta']['Skip'].enable()
        if element_type == 'Meta':
            if element == 'Execute':
                result = self.burl_context.parse_eval(
                    "Evaluate Cursor.GetEvalNode Get cursor")
                print(result)
                self.burl_cursor = None
            elif element == 'Skip':
                success = self.burl_cursor.value.increment_path_to_open_parameter(
                    force_one=True)
                if not success:
                    self.element_buttons['Meta']['Skip'].disable()
            elif element == 'Cancel':
                self.burl_cursor = None
        else:
            self.burl_context.parse_eval(
                "Cursor.InsertArgument Get cursor Quote " + element)
        self.update_cursor()

        self.command_label.label.text = str(self.burl_cursor)
        self.command_label.label.font_size = self.command_label.label.font_size

    def on_key_press(self, symbol, modifiers):
        if modifiers:
            return False
        if symbol not in self.hotkeys:
            return False
        if self.active_type not in self.prefs.exposed_elements:
            return False
        index = self.hotkeys[symbol]
        if index >= len(self.prefs.exposed_elements[self.active_type]):
            return False
        element = self.prefs.exposed_elements[self.active_type][index]
        element_button = self.element_buttons[self.active_type][element]
        element_button.try_press()
        return True

    def update_cursor(self):
        if self.burl_cursor is None:
            self.burl_cursor = self.burl_context.parse_eval(
                "Set cursor Cursor.Make Quote " + self.prefs.root_node)

        options = self.burl_context.parse_eval(
            "Cursor.GetAllowedArgumentTypes Get cursor")
        if not options.value:
            # rmf todo: reset cursor
            return

        min_type = None
        allowed_types = {o.value for o in options.value}
        for element_type, type_button in self.tab_buttons.items():
            if element_type in allowed_types or element_type == 'Meta':
                type_button.enable()
                if element_type != 'Meta' and (min_type is None or
                                               self.tab_indexes[element_type] <
                                               self.tab_indexes[min_type]):
                    min_type = element_type
            else:
                type_button.disable()

        if min_type is None:
            min_type = 'Meta'
        self.change_tab(min_type)
Esempio n. 10
0
def run_compose(compose_lines=None):
    # todo: can we split cursor and active_tab into their own context separate from the cursor evaluation?
    repl = Context()
    ParseNode.parse("LoadModule composition").evaluate(repl)
    prompt = ": "
    cursor = None
    active_tab = None
    tabs = frozenset()
    force_update_active_tab = False
    line_index = 0

    def maybe_print(s):
        if compose_lines is None or len(compose_lines) < line_index:
            print(s)

    value = None
    while True:
        print(chr(27) + "[2J" + chr(27) + "[H", end="")
        if cursor is None:
            cursor = repl.parse_eval("Set cursor Cursor.Make Quote Sequence")
            active_tab = Value("Any", "Type")
            repl.set(Value("active_tab", "ValueName"), active_tab)
            tabs = repl.parse_eval("AllTypes")
            tabs = [t.value for t in tabs.value]

        options = repl.parse_eval("Cursor.GetAllowedArgumentTypes Get cursor")
        if not options.value:  # None or empty frozenset
            maybe_print("No open parameter at cursor")
            elements = []
            value_names = []
        else:
            maybe_print("Allowed Types: " +
                        " ".join([o.value for o in options.value]))
            if force_update_active_tab or (
                    active_tab != "Any" and options.value is not None
                    and active_tab not in options.value
                    and Value('Any', 'Type') not in options.value):
                active_tab = next(iter(options.value))
                repl.set(Value("active_tab", "ValueName"), active_tab)
                force_update_active_tab = False

            elements = repl.parse_eval("DefinitionsOfType Get active_tab")
            elements = [e.value for e in elements.value]
            value_names = repl.parse_eval("ValuesOfType Get active_tab")
            value_names = [n.value for n in value_names.value]

        maybe_print("### Meta ###")
        maybe_print("   Exit Eval Skip Tab <type>")

        maybe_print("### Tabs ###")
        maybe_print("   " + " ".join(tabs))

        if options.value:
            if elements:
                maybe_print("### Elements (%s) ###" % active_tab.value)
                maybe_print("   " + " ".join(elements))
            if value_names:
                maybe_print("### Values (%s) ###" % active_tab.value)
                maybe_print("   " + " ".join(value_names))

        maybe_print("### Command ###")
        maybe_print(cursor.value)

        try:
            if compose_lines is not None and len(compose_lines) > line_index:
                line = compose_lines[line_index]
                line_index += 1
            else:
                line = input(prompt)
            if line == "Exit":
                break
            if line == "Eval":
                try:
                    value = repl.parse_eval(
                        "Evaluate Cursor.GetEvalNode Get cursor")
                    maybe_print(value)
                    cursor = None
                    force_update_active_tab = True
                except EvaluationError as e:
                    maybe_print(e)
            elif line == "Skip":
                success = cursor.value.increment_path_to_open_parameter(
                    force_one=True)
                force_update_active_tab = True
                if not success:
                    maybe_print("Cursor could not skip")

            elif line.startswith("Tab "):
                tab = Value(line.split()[-1], "Type")
                if options.value is None or (tab not in options.value
                                             and Value("Any", "Type")
                                             not in options.value):
                    maybe_print("Cursor does not allow values of type %s" %
                                tab.value)
                elif repl.is_known_type(tab.value):
                    active_tab = tab
                    repl.set(Value("active_tab", "ValueName"), active_tab)
                else:
                    maybe_print("Uknown Type " + tab.value +
                                " has no elements")

            elif line in elements:
                repl.parse_eval("Cursor.InsertArgument Get cursor Quote " +
                                line)
                force_update_active_tab = True
            elif line in value_names:
                repl.parse_eval("Cursor.InsertArgument Get cursor Quote Get " +
                                line)
                force_update_active_tab = True
            elif active_tab.value == "ValueName":
                repl.parse_eval("Cursor.InsertArgument Get cursor Quote " +
                                line)
                force_update_active_tab = True
            elif active_tab.value == "Type":
                if repl.is_known_type(line):
                    repl.parse_eval("Cursor.InsertArgument Get cursor Quote " +
                                    line)
                    force_update_active_tab = True
                else:
                    maybe_print("Uknown Type " + line)
            elif active_tab.value == "Number":
                repl.parse_eval("Cursor.InsertArgument Get cursor Quote " +
                                line)
                force_update_active_tab = True
        except EvaluationError as e:
            print("EvaluationError: " + e.__str__())

        if compose_lines is not None and line_index == len(compose_lines):
            return value