diff --git a/src/dsvm_make_bytecode.py b/src/dsvm_make_bytecode.py index 39399bd..9a84d27 100644 --- a/src/dsvm_make_bytecode.py +++ b/src/dsvm_make_bytecode.py @@ -590,9 +590,6 @@ def make_dsb_with_exception(program_listing, should_print=False, remove_unused_f post_pp_listing = rdict["dspp_listing_with_indent_level"] pyout = dsvm_ds2py.run_all(post_pp_listing) rdict["ds2py_listing"] = pyout - if should_print: - save_lines_to_file(post_pp_listing, "ppds.txt") - save_lines_to_file(pyout, "pyds.py") source = dsline_to_source(pyout) try: my_tree = ast.parse(source, mode="exec") @@ -605,6 +602,12 @@ def make_dsb_with_exception(program_listing, should_print=False, remove_unused_f error_line_str = e.text, ) return comp_result + if should_print: + save_lines_to_file(post_pp_listing, "pgmlst0_preprocessed.txt") + save_lines_to_file(pyout, "pgmlst1_unoptimized.py") + optimized_filename = "pgmlst2_optimized.py" + with open(optimized_filename, "w") as file: + file.write(ast.unparse(my_tree)) symtable_root = symtable.symtable(source, filename="ds2py", compile_type="exec") rdict["root_assembly_list"] = [] rdict["root_assembly_list"].append(dsvm_instruction(OP_VMVER, payload=DS_VM_VERSION)) diff --git a/src/dsvm_optimizer.py b/src/dsvm_optimizer.py index dc38169..212ed81 100644 --- a/src/dsvm_optimizer.py +++ b/src/dsvm_optimizer.py @@ -26,7 +26,6 @@ def optimize_pass(instruction_list, arg_and_var_dict): i += 2 continue - # PUSHC16 0 -> PUSH0 if current_instr.opcode in pushc_instructions and current_instr.payload == 0: optimized_list.append(dsvm_instruction(opcode=OP_PUSH0, label=current_instr.label, comment=current_instr.comment)) i += 1 @@ -61,16 +60,11 @@ def replace_dummy_with_drop_from_context_dict(ctx_dict): for key in ctx_dict['func_assembly_dict']: replace_dummy_with_drop(ctx_dict['func_assembly_dict'][key]) +""" +Performs dead function elimination and constant folding +Only on operators unaffected by `_UNSIGNED_MODE` +""" def optimize_ast(tree, remove_unused_func=True): - """ - Main entry point to optimize the duckyScript AST. - - Args: - tree (ast.AST): The AST to optimize. - remove_unused_func (bool): If True, performs Dead Code Elimination - on functions. Default is True. - """ - # --- Step 1: Reachability Analysis (Conditional) --- live_funcs = set() @@ -83,10 +77,8 @@ def optimize_ast(tree, remove_unused_func=True): } # Queue for BFS/DFS traversal. Start with the "Main" body. - # "Main" consists of all nodes in the module that AREN'T FunctionDefs. worklist = [node for node in tree.body if not isinstance(node, ast.FunctionDef)] - # Helper to find all function calls within a list of nodes def get_calls_from_nodes(nodes): calls = [] for node in nodes: @@ -110,7 +102,7 @@ def optimize_ast(tree, remove_unused_func=True): class DuckyOptimizer(ast.NodeTransformer): def visit_FunctionDef(self, node): - # 1. Dead Code Elimination (Controlled by flag) + # 1. Dead Code Elimination if remove_unused_func and node.name not in live_funcs: return None return self.generic_visit(node) @@ -119,26 +111,60 @@ def optimize_ast(tree, remove_unused_func=True): # Optimize children first self.generic_visit(node) - # 2. Constant Folding (Runs regardless of flag) + # 2. Constant Folding for Binary Operators if isinstance(node.left, ast.Constant) and isinstance(node.right, ast.Constant): - if isinstance(node.left.value, (int, float)) and isinstance(node.right.value, (int, float)): + if isinstance(node.left.value, int) and isinstance(node.right.value, int): try: - val = self._apply_op(node.op, node.left.value, node.right.value) - return ast.Constant(value=val) + val = self._apply_bin_op(node.op, node.left.value, node.right.value) + # Check if optimization was possible (val is not None) + if val is not None: + return ast.Constant(value=int(val)) except (ZeroDivisionError, OverflowError): pass return node - def _apply_op(self, op, left, right): + def visit_Compare(self, node): + # Optimize children first + self.generic_visit(node) + + # 3. Constant Folding for Comparisons + if len(node.ops) == 1 and len(node.comparators) == 1: + left = node.left + right = node.comparators[0] + op = node.ops[0] + + if isinstance(left, ast.Constant) and isinstance(right, ast.Constant): + if isinstance(left.value, int) and isinstance(right.value, int): + try: + val = self._apply_cmp_op(op, left.value, right.value) + if val is not None: + return ast.Constant(value=int(val)) + except Exception: + pass + return node + + def visit_BoolOp(self, node): + self.generic_visit(node) + # Constant Folding for Logical Operators + if all(isinstance(v, ast.Constant) for v in node.values): + raw_values = [v.value for v in node.values] + final_val = 0 + if isinstance(node.op, ast.And): + final_val = 1 if all(raw_values) else 0 + elif isinstance(node.op, ast.Or): + final_val = 1 if any(raw_values) else 0 + return ast.Constant(value=final_val) + return node + + # --- Operator Mapping Helpers --- + + def _apply_bin_op(self, op, left, right): ops = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, - ast.Div: operator.floordiv, - ast.Mod: operator.mod, ast.Pow: operator.pow, ast.LShift: operator.lshift, - ast.RShift: operator.rshift, ast.BitOr: operator.or_, ast.BitXor: operator.xor, ast.BitAnd: operator.and_, @@ -146,7 +172,17 @@ def optimize_ast(tree, remove_unused_func=True): op_type = type(op) if op_type in ops: return ops[op_type](left, right) - raise NotImplementedError + return None + + def _apply_cmp_op(self, op, left, right): + ops = { + ast.Eq: operator.eq, + ast.NotEq: operator.ne, + } + op_type = type(op) + if op_type in ops: + return ops[op_type](left, right) + return None optimizer = DuckyOptimizer() new_tree = optimizer.visit(tree) diff --git a/src/duck_objs.py b/src/duck_objs.py index 7b750da..9364c45 100644 --- a/src/duck_objs.py +++ b/src/duck_objs.py @@ -204,6 +204,6 @@ def import_profile_single(root_dir_path): return this_profile class dp_global_settings: - def __init__(self, user_header_line_list=None, stdlib_line_list=None): + def __init__(self, user_header_line_list=[], stdlib_line_list=[]): self.user_header_line_list = user_header_line_list self.stdlib_line_list = stdlib_line_list \ No newline at end of file diff --git a/src/duckypad_config.py b/src/duckypad_config.py index e08b775..14aa230 100644 --- a/src/duckypad_config.py +++ b/src/duckypad_config.py @@ -902,7 +902,7 @@ def save_everything(save_path, dp_obj): user_header_file_path = os.path.join(save_path, user_header_dot_txt) print("user_header_file_path:", user_header_file_path) - if this_global_setting.user_header_line_list is not None: + if len(this_global_setting.user_header_line_list): user_header_file = open(user_header_file_path, "w") user_header_file.writelines((line + '\n' for line in this_global_setting.user_header_line_list)) user_header_file.close() @@ -2097,9 +2097,9 @@ def repeat_func(): root.after(500, repeat_func) -THIS_DUCKYPAD.device_type = THIS_DUCKYPAD.dp24 -select_root_folder("sample_dp24", is_dir_for_dp24=True) -edit_header_button_click(this_global_setting) +# THIS_DUCKYPAD.device_type = THIS_DUCKYPAD.dp24 +# select_root_folder("sample_dp24", is_dir_for_dp24=True) +# edit_header_button_click(this_global_setting) # connect_button_click() # export_profile_click() # import_profile_click()