| 124 | } |
| 125 | |
| 126 | compileToRPN(expr) { |
| 127 | // Use type guards for safe property access |
| 128 | if (isBoxedSymbol(expr)) return expr.symbol; |
| 129 | if (isBoxedNumber(expr)) return expr.re.toString(); |
| 130 | |
| 131 | const op = expr.operator; |
| 132 | |
| 133 | // Only access ops if this is a function expression |
| 134 | if (!isBoxedFunction(expr)) return expr.toString(); |
| 135 | |
| 136 | const args = expr.ops; |
| 137 | |
| 138 | // Compile arguments first (postorder traversal) |
| 139 | const compiledArgs = args.map((arg) => this.compileToRPN(arg)); |
| 140 | |
| 141 | // Map operators to RPN commands |
| 142 | const opMap = { |
| 143 | Add: '+', |
| 144 | Subtract: '-', |
| 145 | Multiply: '*', |
| 146 | Divide: '/', |
| 147 | Power: '^', |
| 148 | Sin: 'SIN', |
| 149 | Cos: 'COS', |
| 150 | Sqrt: 'SQRT', |
| 151 | }; |
| 152 | |
| 153 | const rpnOp = opMap[op] || op; |
| 154 | |
| 155 | // In RPN: operands first, then operator |
| 156 | return `${compiledArgs.join(' ')} ${rpnOp}`; |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | const rpnTarget = new RPNTarget(); |