Expression Parser

Converting mathematical expressions to Romasm assembly

Overview

The Romasm Expression Parser (calcengine/romasm-expression-parser.js) converts mathematical expressions like "2+2" or "sin(30)" into Romasm assembly code that can be executed by the VM.

Supported Expressions

Arithmetic Operations

  • + - Addition
  • - - Subtraction
  • * - Multiplication
  • / - Division
  • ^ - Exponentiation (power)

Examples:

"2+2"      → ADD R0, R1
"5*3"      → MUL R0, R1
"10/2"     → DIV R0, R1
"2^8"      → CALL power

Functions

  • sin(x) - Sine
  • cos(x) - Cosine
  • tan(x) - Tangent
  • sqrt(x) - Square root
  • exp(x) - Exponential
  • ln(x) - Natural logarithm

Examples:

"sin(30)"  → CALL sin
"sqrt(25)" → CALL sqrt
"exp(1)"   → CALL exp

Parentheses

Parentheses are supported for grouping:

"(2+3)*4"  → Evaluates 2+3 first, then multiplies by 4
"sin(30+10)" → Evaluates 30+10, then takes sine

Numbers

Integers and decimals are supported:

"42"       → Integer
"3.14"     → Decimal (converted to scaled integer)

How It Works

Step 1: Tokenization

The expression is broken down into tokens (numbers, operators, functions, parentheses):

"2+3*4" → ["2", "+", "3", "*", "4"]

Step 2: Parsing

Tokens are parsed into an abstract syntax tree (AST) respecting operator precedence:

"2+3*4" → 
  +
 / \
2   *
   / \
  3   4

Step 3: Code Generation

The AST is converted to Romasm assembly instructions:

LOAD R0, 3
LOAD R1, 4
MUL R0, R1    ; 3*4 = 12
LOAD R1, 2
ADD R0, R1    ; 12+2 = 14

Usage in Calculator

In the Romasm Calculator's "calculator" mode, you can enter expressions directly:

  • Type an expression like "2+2"
  • Press ENTER
  • The parser converts it to Romasm
  • The result is calculated and displayed

Limitations

Current Limitations

  • No variables (only constants and function calls)
  • Limited function set (extensible)
  • Fixed-point arithmetic scaling

Related Documentation