---
title: "StepCode"
year: "2023"
motto: "Programming Language"
description: "StepCode is a pseudo-code language for writing step-by-step instructions. It is designed to be easy to read and write, and to be easily converted to other languages. Implemented using ANTLR4."
stack: ["javascript", "typescript", "nodejs", "java"]
website: "https://www.npmjs.com/package/stepcode"
url: "https://rolandoandrade.me/projects/stepcode/"
author: "Rolando Andrade"
---

# StepCode

> Programming Language

StepCode is a pseudo-code language for writing step-by-step instructions. It is designed to be easy to read and write, and to be easily converted to other languages. Implemented using ANTLR4.

Year: 2023. Stack: javascript, typescript, nodejs, java. Website: https://www.npmjs.com/package/stepcode

Repositories:

- [github](https://github.com/RolandoAndrade/stepcode)

Teaching programming is harder than it looks. Students fight syntax errors and cryptic compiler messages. Worse, there is a gap between thinking through a problem and writing code that works. I wanted to close that gap.

StepCode started as a personal project while I was teaching Algorithms and Programming. We used pseudocode in class because it lets students focus on logic instead of language quirks. But pseudocode on paper cannot run. Students had no way to test their ideas.

So I built an interpreter that runs pseudocode directly in the browser.

## Pseudocode in two languages

StepCode is a pseudocode language inspired by PSeInt, a popular tool for teaching programming in Latin America. It accepts both Spanish and English keywords. You can write `SI` or `IF`, `MIENTRAS` or `WHILE`. That makes it easier for Spanish speaking students who are just starting.

Here is a simple program that greets the user. Press the play button, type your name and press Enter:

[StepCode greeting example](https://stepcode.letsbuildsolutions.com/embed#code=Xc49CoRADIbhfk7xbeq5gcUW7i4WFoIniJqFwMwEMnp_wZ_G-uGFd3CbpRpGTttiAQA-8teijmJ5ckFr2dDyIoWbw791dp3UQQetgpQ4c33T6b3IHT-DzhJHULw4gl7UhJ-W4dwIOw&profile=es&name=Saludo)

The interpreter handles variables, loops, conditionals, arrays, functions and procedures. It even supports passing parameters by reference. Everything runs in JavaScript, so it works in any browser with nothing to install.

## Lexer, parser, interpreter

An interpreter for a programming language has three main parts:

1. The lexer splits the source code into tokens, the small pieces like words and symbols.
2. The parser arranges the tokens into a tree called an Abstract Syntax Tree (AST).
3. The interpreter walks that tree and runs the code.

![How StepCode turns pseudocode into a running program, one stage at a time.](https://storage.rolandoandrade.me/blog/stepcode-pipeline.webp)

I used ANTLR4 to generate the lexer and the parser. ANTLR4 is a parser generator. You give it a grammar file, and it writes the parsing code for you. You write the grammar rules once, and ANTLR4 does the rest.

## The grammar file

The grammar file defines two things: what tokens look like, and how they combine into valid programs.

Tokens are the basic building blocks: keywords, operators, numbers and strings. Here is how I defined the bilingual keywords:

```
IF: 'SI' | 'IF';
WHILE: 'WHILE' | 'MIENTRAS';
PROGRAM: 'PROCESO' | 'ALGORITMO' | 'PROGRAM';
```

ANTLR4 treats every alternative as the same token. The grammar is also case insensitive, so `if`, `IF` and `If` all work.

Parser rules describe how tokens fit together. A program has a main block and optional subprograms:

```
program: directives* subprogram* main subprogram* EOF;
main: programHeading block ENDPROGRAM;
```

An if statement looks like this in the grammar:

```
ifStatement: IF expression THEN compoundStatement (elifStatement | elseStatement?) ENDIF;
```

The grammar supports all the control structures you would expect. `FOR` loops with optional step values. `WHILE` loops. `REPEAT/UNTIL` loops. `CASE` statements for choosing between many branches.

## Walking the tree with visitors

ANTLR4 generates a base visitor class with an empty method for each grammar rule. A visitor is an object that visits each node of the tree and decides what to do with it. I extended that class and wrote the logic for each node type.

The interpreter uses async/await everywhere. That matters for input and output. When the code calls `LEER` (read input), the interpreter has to wait for the user. Running everything asynchronously keeps the browser responsive while it waits.

Here is the visitor for the if statement:

```typescript
visitIfStatement = async (ctx: IfStatementContext) => {
  const expression = await this.visit(ctx.expression())
  if (expression.value) {
    return await this.visit(ctx.compoundStatement())
  } else {
    if (ctx.elifStatement()) {
      return await this.visit(ctx.elifStatement())
    }
    if (ctx.elseStatement()) {
      return await this.visit(ctx.elseStatement())
    }
  }
}
```

It evaluates the condition first. If the condition is true, it visits the then block. If not, it checks for an else if block or an else block.

## Scopes and the call stack

Variables live in a symbol table, built as a `Map`. Each variable stores its type and value. When the interpreter enters a function or procedure, it pushes a new scope onto a call stack. Local variables stay separate from global ones.

The call stack is limited to 100 frames to catch runaway recursion. Without that limit, an infinite loop would hang the browser.

## Passing by reference

StepCode supports passing arguments by reference, and that was tricky to build. When a parameter is marked `POR REFERENCIA` (by reference), changes inside the function change the original variable.

The interpreter stores a reference to the original variable's entry in the symbol table instead of copying its value. Array elements are even harder. The reference has to remember which array and which index to change.

## Built in functions

The interpreter includes common functions for text and math:

- `LONGITUD` / `LENGTH`: string or array length
- `SUBCADENA` / `SUBSTRING`: extract part of a string
- `MAYUSCULAS` / `UPPER`: convert to uppercase
- `MINUSCULAS` / `LOWER`: convert to lowercase
- `TRUNCAR` / `TRUNC`: remove decimal part
- `REDONDEAR` / `ROUND`: round to nearest integer
- `ALEATORIO` / `RANDOM`: random number
- `CONVERTIRANUMERO` / `TONUM`: parse string to number
- `CONVERTIRATEXTO` / `TOSTR`: convert to string

Every function works with its Spanish name and its English name.

## Input and output through events

Input and output go through an event bus. That keeps the interpreter independent from any specific interface. The interpreter sends events for output and listens for input responses.

```typescript
eventBus.on('output-request', (message: string) => {
  console.log(message);
});

eventBus.on('input-request', (resolve: (s: string) => void) => {
  // Get input from user, then call resolve(input)
});
```

The same interpreter can run in different places. A terminal app, a web page or a test suite can all plug into the event bus.

## Arrays that start at 1

Arrays in StepCode start at index 1 by default, like most pseudocode. A directive switches them to start at 0 if you need it:

```
$arrays@stepcode
Proceso Test
    Definir a Como Entero;
    Dimension a[5];
    a[0] <- 10;
FinProceso
```

The `DIMENSION` statement creates arrays. Arrays with more than one dimension work too. Underneath, the interpreter creates nested JavaScript arrays.

## Clear error messages

The parser catches syntax errors: missing semicolons, unbalanced parentheses and unknown keywords. ANTLR4 gives the line and column for each error message.

Runtime errors needed custom handling. When the interpreter hits a problem like an undefined variable, a type mismatch or a stack overflow, it throws a `StepCodeError` with the location.

## The hardest parts

Getting scope right was the hardest part. Variables inside a function must not leak outside. Passing by reference has to change the original. Nested function calls each need their own clean scope.

Ambiguity in the ANTLR4 grammar caused trouble too. Expression parsing needs careful precedence rules. Does `2 + 3 * 4` equal 14 or 20? The structure of the grammar decides, and a mistake causes subtle bugs.

The bilingual design created some token conflicts. A few Spanish words overlapped with English in unexpected ways. I restructured parts of the grammar to remove the ambiguity.

## Why students can use it

StepCode fills a specific need. Students write pseudocode and run it. They get immediate feedback on their logic. They can debug step by step.

The bilingual support makes it more accessible. Learning programming is hard enough without fighting a foreign language at the same time.

Because it runs in the browser, there is no setup. No installs, no environment configuration, no requests to IT support. You open a web page and start coding.

## Using StepCode

Install it from npm:

```bash
npm install stepcode
```

Then interpret code:

```typescript
import { interpret, EventBus } from 'stepcode';

const eventBus = new EventBus();

eventBus.on('output-request', (message: string) => {
  console.log(message);
});

await interpret({
  code: `Proceso HolaMundo
      Escribir "Hola mundo";
  FinProceso`,
  eventBus
});
```

The `validate` function checks the syntax without running the code:

```typescript
import { validate } from 'stepcode';

const errors = validate(`Proceso Test
    Escribir "Missing semicolon"
FinProceso`);
```

## Lessons from building a language

Building a programming language taught me more about parsers and interpreters than any textbook. I now understand why certain design decisions matter. Why scope rules exist. Why type systems help.

It also showed me that tools matter for learning. Giving students a way to run their pseudocode made a real difference in my classes.

[Book a call with Rolando](https://rolandoandrade.me/pricing/)
