def _parse_TEST_tag(self, node: Node) -> None: try: if eval(node.arg(0), self.context): self._parse_children(node.children[1].children) else: self._parse_children(node.children[2].children) except Exception: print(node.display(color=False)) raise
def _parse_EVAL_tag(self, node: Node): args, kw = self._parse_options(node) if self.context.get("ALL_FLOATS"): self.flags["floats"] = True for arg in args: if arg.isdigit(): self.flags["round"] = int(arg) elif arg == ".": self.flags["."] = True elif arg in ("floats", "float"): self.flags["floats"] = True elif arg == "str": self.flags["str"] = True else: raise ValueError("Unknown flag: " + repr(arg)) # XXX: support options round, float, (sympy, python,) select and rand code = node.arg(0) assert isinstance(code, str), type(code) try: txt = self._eval_and_format_python_expr(code) except Exception: print("ERROR: Can't evaluate this: " + repr(code)) raise # Tags must be cleared *before* calling .write(txt), since .write(txt) # add '+', '-' and '\times ' before txt if corresponding flags are set, # and ._eval_and_format_python_expr() has already do this. self.flags.clear() self.write(txt)
def _parse_ASSERT_tag(self, node: Node): code = node.arg(0) test = eval(code, self.context) if not test: print("Error in assertion (NUM=%s):" % self.NUM) print("***") print(code) print("***") assert test
def _pick_and_parse_children(self, node: Node, children: List = None, target: str = "ITEM", **kw): # Choose only one between all the #ITEM sections inside a #PICK block. # Note that they may be some text or nodes before first #ITEM, # if so they should be left unmodified at their original position. if children is None: children = node.children if not children: return i = self._child_index(children, target) items = children[i:] for item in items: if not (isinstance(item, Node) and item.name == target): log = [ "This is current structure:", node.display(), rf"\n{item!r} is not an {target!r} node !", ] raise RuntimeError("\n".join(log)) item = randfunc.randchoice(items) self._parse_children(children[:i] + [item], **kw)
def _parse_PRINT_tag(self, node: Node) -> None: print(node.arg(0))
def _parse_CALL_tag(self, node: Node): """Calling a macro.""" name = node.arg(0) if name not in self.macros: raise NameError(f"Error: MACRO {name!r} undefined.") self._parse_children(self.macros[name])
def _parse_MACRO_tag(self, node: Node): name = node.arg(0) self.macros[name] = node.children[1:]
def _parse_IMPORT_tag(self, node: Node): exec("from %s import *" % node.arg(0), self.context)
def _parse_CASE_tag(self, node: Node): test = eval(node.arg(0), self.context) == self.NUM if test: self._parse_children(node.children[1:]) return test
def _parse_IFNUM_tag(self, node: Node): if eval(node.arg(0), self.context) == self.NUM: self._parse_children(node.children[1].children)