Here is an example program from a new assmebly language I made up that computes primes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | SET R1 2 // Starting number to check for prime start_find_primes: JMP is_prime // Control will return after executing is_prime with R1 as input and R2 containing the result ready_prime: SET R7 1 EQ R2 R7 // Check if R2 is 1 (prime) JF increment // If not prime, skip storing and increment the number // Store prime number in memory and increment count STORE R1 R8 // Store prime number at address pointed by R8 INC R8 // Increment prime count // Check if 100 primes are found SET R7 100 EQ R8 R7 JF increment // If not 100 primes found yet, continue finding JMP end // If 100 primes found, end program increment: INC R1 // Increment number to check for prime JMP start_find_primes // Check next number is_prime: SET R2 1 // Assume number is prime initially SET R3 2 // Start divisor from 2 start_loop: // Label to start the loop // Check if we have exceeded the square root of R1 MUL R4 R3 R3 // R4 = R3 * R3 GT R4 R1 // Set flag if R4 > R1 JT is_prime_end // If not exceeded, continue; else, end loop MOD R6 R1 R3 // R6 = R1 % R3 SET R7 0 EQ R7 R6 // Check if R6 is 0 JT not_prime // If yes, number is not prime INC R3 // Increment divisor JMP start_loop // Repeat loop not_prime: SET R2 0 // Set result to 0 (not prime) is_prime_end: JMP ready_prime end: |
Here is an example program from a new assmebly language I made up that computes primes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | SET R1 2 // Starting number to check for prime start_find_primes: JMP is_prime // Control will return after executing is_prime with R1 as input and R2 containing the result ready_prime: SET R7 1 EQ R2 R7 // Check if R2 is 1 (prime) JF increment // If not prime, skip storing and increment the number // Store prime number in memory and increment count STORE R1 R8 // Store prime number at address pointed by R8 INC R8 // Increment prime count // Check if 100 primes are found SET R7 100 EQ R8 R7 JF increment // If not 100 primes found yet, continue finding JMP end // If 100 primes found, end program increment: INC R1 // Increment number to check for prime JMP start_find_primes // Check next number is_prime: SET R2 1 // Assume number is prime initially SET R3 2 // Start divisor from 2 start_loop: // Label to start the loop // Check if we have exceeded the square root of R1 MUL R4 R3 R3 // R4 = R3 * R3 GT R4 R1 // Set flag if R4 > R1 JT is_prime_end // If not exceeded, continue; else, end loop MOD R6 R1 R3 // R6 = R1 % R3 SET R7 0 EQ R7 R6 // Check if R6 is 0 JT not_prime // If yes, number is not prime INC R3 // Increment divisor JMP start_loop // Repeat loop not_prime: SET R2 0 // Set result to 0 (not prime) is_prime_end: JMP ready_prime end: |
To solve this problem, we need to create a Python interpreter for a custom assembly language that computes the first 100 prime numbers and returns the resulting memory state after running the program. The interpreter must parse the assembly code, simulate the execution of instructions, manage registers and memory, and handle control flow using labels and jumps. ### Approach 1. **Parsing the Program**: The input program is split into lines, and each line is processed to separate comments from code. Labels are identified and stored in a dictionary mapping labels to their respective instruction indices. Instructions are stored in a list for execution. 2. **Simulating Execution**: The interpreter initializes registers, memory, and control flags. It processes each instruction sequentially, updating registers and memory as needed. Control flow instructions (jumps) adjust the instruction pointer based on labels. 3. **Handling Instructions**: Each instruction type (e.g., SET, JMP, EQ, STORE) is processed according to its semantics. Arithmetic operations, comparisons, memory storage, and control flow are implemented to mimic the behavior of the custom assembly language. ### Solution Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | from collections import defaultdict def evaluate(program): # Parse the program into instructions and labels lines = program.split('\n') instructions = [] labels = {} current_instruction = 0 for line in lines: line = line.strip() if not line: continue # Split off comments code_part = line.split('//')[0].strip() if not code_part: continue # Check for labels if code_part.endswith(':'): label_name = code_part[:-1].strip() labels[label_name] = current_instruction else: # Split into tokens tokens = code_part.split() instructions.append(tokens) current_instruction += 1 # Initialize simulation state registers = defaultdict(int) memory = [] flag = False ip = 0 # instruction pointer while ip < len(instructions): instr = instructions[ip] op = instr[0] operands = instr[1:] if op == 'SET': reg = operands[0] value = int(operands[1]) registers[reg] = value ip += 1 elif op == 'JMP': label = operands[0] ip = labels[label] elif op == 'EQ': reg1, reg2 = operands val1 = registers[reg1] val2 = registers[reg2] flag = (val1 == val2) ip += 1 elif op == 'GT': reg1, reg2 = operands val1 = registers[reg1] val2 = registers[reg2] flag = (val1 > val2) ip += 1 elif op == 'LT': reg1, reg2 = operands val1 = registers[reg1] val2 = registers[reg2] flag = (val1 < val2) ip += 1 elif op == 'JF': label = operands[0] if not flag: ip = labels[label] else: ip += 1 elif op == 'JT': label = operands[0] if flag: ip = labels[label] else: ip += 1 elif op == 'MUL': dest, src1, src2 = operands registers[dest] = registers[src1] * registers[src2] ip += 1 elif op == 'MOD': dest, src1, src2 = operands divisor = registers[src2] if divisor == 0: # Avoid division by zero; assume programs are valid registers[dest] = 0 else: registers[dest] = registers[src1] % divisor ip += 1 elif op == 'INC': reg = operands[0] registers[reg] += 1 ip += 1 elif op == 'DEC': reg = operands[0] registers[reg] -= 1 ip += 1 elif op == 'STORE': src_reg, addr_reg = operands value = registers[src_reg] address = registers[addr_reg] # Ensure memory is large enough to include the address while address >= len(memory): memory.append(0) if address >= 0: memory[address] = value ip += 1 else: # Unknown instruction, skip ip += 1 return memory |
I extracted the following code from that output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | from collections import defaultdict def evaluate(program): # Parse the program into instructions and labels lines = program.split('\n') instructions = [] labels = {} current_instruction = 0 for line in lines: line = line.strip() if not line: continue # Split off comments code_part = line.split('//')[0].strip() if not code_part: continue # Check for labels if code_part.endswith(':'): label_name = code_part[:-1].strip() labels[label_name] = current_instruction else: # Split into tokens tokens = code_part.split() instructions.append(tokens) current_instruction += 1 # Initialize simulation state registers = defaultdict(int) memory = [] flag = False ip = 0 # instruction pointer while ip < len(instructions): instr = instructions[ip] op = instr[0] operands = instr[1:] if op == 'SET': reg = operands[0] value = int(operands[1]) registers[reg] = value ip += 1 elif op == 'JMP': label = operands[0] ip = labels[label] elif op == 'EQ': reg1, reg2 = operands val1 = registers[reg1] val2 = registers[reg2] flag = (val1 == val2) ip += 1 elif op == 'GT': reg1, reg2 = operands val1 = registers[reg1] val2 = registers[reg2] flag = (val1 > val2) ip += 1 elif op == 'LT': reg1, reg2 = operands val1 = registers[reg1] val2 = registers[reg2] flag = (val1 < val2) ip += 1 elif op == 'JF': label = operands[0] if not flag: ip = labels[label] else: ip += 1 elif op == 'JT': label = operands[0] if flag: ip = labels[label] else: ip += 1 elif op == 'MUL': dest, src1, src2 = operands registers[dest] = registers[src1] * registers[src2] ip += 1 elif op == 'MOD': dest, src1, src2 = operands divisor = registers[src2] if divisor == 0: # Avoid division by zero; assume programs are valid registers[dest] = 0 else: registers[dest] = registers[src1] % divisor ip += 1 elif op == 'INC': reg = operands[0] registers[reg] += 1 ip += 1 elif op == 'DEC': reg = operands[0] registers[reg] -= 1 ip += 1 elif op == 'STORE': src_reg, addr_reg = operands value = registers[src_reg] address = registers[addr_reg] # Ensure memory is large enough to include the address while address >= len(memory): memory.append(0) if address >= 0: memory[address] = value ip += 1 else: # Unknown instruction, skip ip += 1 return memory |
Running the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | from collections import defaultdict def evaluate(program): # Parse the program into instructions and labels lines = program.split('\n') instructions = [] labels = {} current_instruction = 0 for line in lines: line = line.strip() if not line: continue # Split off comments code_part = line.split('//')[0].strip() if not code_part: continue # Check for labels if code_part.endswith(':'): label_name = code_part[:-1].strip() labels[label_name] = current_instruction else: # Split into tokens tokens = code_part.split() instructions.append(tokens) current_instruction += 1 # Initialize simulation state registers = defaultdict(int) memory = [] flag = False ip = 0 # instruction pointer while ip < len(instructions): instr = instructions[ip] op = instr[0] operands = instr[1:] if op == 'SET': reg = operands[0] value = int(operands[1]) registers[reg] = value ip += 1 elif op == 'JMP': label = operands[0] ip = labels[label] elif op == 'EQ': reg1, reg2 = operands val1 = registers[reg1] val2 = registers[reg2] flag = (val1 == val2) ip += 1 elif op == 'GT': reg1, reg2 = operands val1 = registers[reg1] val2 = registers[reg2] flag = (val1 > val2) ip += 1 elif op == 'LT': reg1, reg2 = operands val1 = registers[reg1] val2 = registers[reg2] flag = (val1 < val2) ip += 1 elif op == 'JF': label = operands[0] if not flag: ip = labels[label] else: ip += 1 elif op == 'JT': label = operands[0] if flag: ip = labels[label] else: ip += 1 elif op == 'MUL': dest, src1, src2 = operands registers[dest] = registers[src1] * registers[src2] ip += 1 elif op == 'MOD': dest, src1, src2 = operands divisor = registers[src2] if divisor == 0: # Avoid division by zero; assume programs are valid registers[dest] = 0 else: registers[dest] = registers[src1] % divisor ip += 1 elif op == 'INC': reg = operands[0] registers[reg] += 1 ip += 1 elif op == 'DEC': reg = operands[0] registers[reg] -= 1 ip += 1 elif op == 'STORE': src_reg, addr_reg = operands value = registers[src_reg] address = registers[addr_reg] # Ensure memory is large enough to include the address while address >= len(memory): memory.append(0) if address >= 0: memory[address] = value ip += 1 else: # Unknown instruction, skip ip += 1 return memory answer = evaluate(""" SET R1 0 SET R2 1 loop: MUL R3 R2 R2 STORE R3 R1 INC R1 INC R2 SET R3 20 EQ R1 R3 JF loop """)[:10] expected = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] assert answer == expected, f'Wrong answer; got {answer} instead of {expected}' answer = evaluate(""" SET R1 2 // Starting number to check for prime start_find_primes: JMP is_prime // Control will return after executing is_prime with R1 as input and R2 containing the result ready_prime: SET R7 1 EQ R2 R7 // Check if R2 is 1 (prime) JF increment // If not prime, skip storing and increment the number // Store prime number in memory and increment count STORE R1 R8 // Store prime number at address pointed by R8 INC R8 // Increment prime count // Check if 100 primes are found SET R7 100 EQ R8 R7 JF increment // If not 100 primes found yet, continue finding JMP end // If 100 primes found, end program increment: INC R1 // Increment number to check for prime JMP start_find_primes // Check next number is_prime: SET R2 1 // Assume number is prime initially SET R3 2 // Start divisor from 2 start_loop: // Label to start the loop // Check if we have exceeded the square root of R1 MUL R4 R3 R3 // R4 = R3 * R3 GT R4 R1 // Set flag if R4 > R1 JT is_prime_end // If not exceeded, continue; else, end loop MOD R6 R1 R3 // R6 = R1 % R3 SET R7 0 EQ R7 R6 // Check if R6 is 0 JT not_prime // If yes, number is not prime INC R3 // Increment divisor JMP start_loop // Repeat loop not_prime: SET R2 0 // Set result to 0 (not prime) is_prime_end: JMP ready_prime end: """)[:10] expected = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] assert answer == expected, f'Wrong answer; got {answer} instead of {expected}' print('All tests passed') |
All tests passed
Testing if the previous output contains the string All tests passed
: True