An interpreter for College Board's specified pseudocode for the AP Computer Science Principles Exam.

Overview

College Board Pseudocode Interpreter

A playground for this interpreter is up on my website.

This project is a mostly-functioning interpreter for College Board's pseudocode specified on the AP Computer Science Principles Exam reference sheet. It's implemented in JavaScript for a simple web playground. The interpreter is a simple tree walker which walks an AST generated by a recursive descent parser.

Making this was heavily inspired by Robert Nystron's book Crafting Interpreters after I implemented Lox in TypeScript.

TODO

  • The INPUT native procedure isn't implemented yet, but it should be simple to make a nice interface for it since the interpreter already uses async/await.
  • A robot simulation and procedure implementations need to be implemented.
  • If I feel like it, I might make a procedure without a return statement output a void value rather than null. void would be unassignable or unusable to prevent the use of that type.
  • There might be bugs that need fixing; this wasn't tested extensively.

Completed

  • Errors are thrown in the console, but they should appear in the UI. ...Actually, error handling is just really bad in general, so that needs to be fixed.
  • Binary operations don't check for operand types; this is bad because some undefined operations mean that programs can escape into unallowed types like strings because of JavaScript's type casting.

Sample Code

Shown below are a few sample programs in the style of code on the APCSP Exam.

Recursive fibbonacci numbers
PROCEDURE Fibonacci (n)
{
  IF (n ≤ 1)
  {
    RETURN (n)
  }
  RETURN (Fibonacci (n - 1) + Fibonacci (n - 2))
}

i ← 1
REPEAT 10 TIMES
{
  DISPLAY (Fibonacci (i))
  i ← i + 1
}
Factorial numbers with a list and for-each
list ← [1, 1]

REPEAT 10 TIMES
{
  length ← LENGTH (list)
  next ← list[length] * length
  APPEND (list, next)
}

FOR EACH number IN list
{
  DISPLAY (number)
}
Closures
PROCEDURE Add (x)
{
  PROCEDURE AddX (y)
  {
    RETURN (x + y)
  }
  RETURN (AddX)
}

Add5 ← Add (5)

DISPLAY (Add5 (10))

Weird Quirks

This language has a lot of really weird aspects:

  1. When a list is assigned to a variable, it's specified that it's a "copy" of the original list, not a reference to the original list. That means that assigning a list to a new variable is equivalent to copying the original list. This is really weird since it doesn't say the same thing for procedure parameters, so there is a difference in the way they behave.
  2. Lists are 1-indexed. This is terrible.
  3. There are no comments; good luck trying to figure out what's happening.

Operator Precedence

Operators Associativity Description
Right Assignment
OR Left Logical OR
AND Left Logical AND
NOT Right Logical NOT
=, Left Equality
<, , >, Left Comparison
+, - Left Addition
*, /, MOD Left Multiplication
- Right Unary Negation
..(..), ..[..] Left Calls or Indexes
(...) Left Parentheses

Additions

There are a few additions to the original reference sheet in this implementation. These include but are not necessarily limited to:

  1. Strings aren't specified on the reference sheet, but on practice exam questions they use string literals, so I've gone ahead and added minimal support for strings. String literals are multi-line, there aren't escape sequences, and strings can only start and end with ". They can be concatenated, and adding strings with other types will cast those types to their string variants. Strings can be indexed (with 1-indexing to be consistent with lists) but can't be modified since they should act immutable. The LENGTH procedure will return the length of a string. This pretty fun because strings make it possible to write programs to interpret esoteric languages like Brainf*ck.
  2. The comparison operators <, , >, and don't have specified types they should compare, so I was relatively lenient by allowing comparisons between two strings or two lists. Comparing two strings gives the same result as comparing two strings in JavaScript (their alphabetical order). Comparing lists will compare their length.
  3. AND and OR don't have a specified precendece on the reference sheet, but in most languages, OR has a lower precedence than AND, so that was added to the grammar.
  4. The College Board doesn't specify that logical operators should short-circuit, but it's logical that they should.
  5. College Board doesn't say anything about variable scoping and assignment, so I went with block-scoping. When an assignment expression is used, if the variable on the left-hand side is not already declared, it is declared in the current block. If the variable already exists in a parent scope, then that variable is used. This way, the only way to shadow a variable is through procedure parameters.
  6. It's never specified what type of values can be RETURNed, so everything is allowed. Allowing procedures to be returned has the side effect of adding closures.
  7. College Board doesn't define a behavior for displaying lists or procedures from the DISPLAY procedure, so there were a few arbitrary decisions to support this.
  8. There is very little written on errors; the only error specified is index out of bounds for lists. Therefore, this interpreter is relatively lenient with truthiness, and all arithmetic and comparison operations only allow number operands.
  9. The three list procedures, INSERT, APPEND, and REMOVE, don't have a return value specified, so this interpreter returns the list after modification. The DISPLAY procedure returns the displayed value.
  10. It's never specified what a procedure without a return statement should output, so this implementation returns null. This behavior might change in the future.
  11. Newlines don't have any meaning in the grammar; the end of an expression is the end of the statement. That means that code such as:
a ← 1 b ← 1

is equivalent to:

a ← 1
b ← 1

This has some implications for writing code, because it's possible to write write code like:

a ← 1
(4 + 5)

which looks like it should be two separate statements, but is actually equivalent to:

a ← 1(4 + 5)

which is clearly an error.

Grammar

This is a slightly more formalized version of the grammar from the official reference sheet.

program         : statements ;

statements      : statement* ;

block           : "{" statements "}" ;

statement       : exprStmt
                | procedureStmt
                | ifStmt
                | repeatStmt
                | forEachStmt
                | returnStmt ;

exprStmt        : expr ;

ifStmt          : "IF" "(" expr ")" block ( "else" block )? ;

repeatStmt      : "REPEAT" "UNTIL" "(" expr ")" block
                | "REPEAT" expr "TIMES" block ;

forEachStmt     : "FOR" "EACH" ID "IN" expr block ;

procedureStmt   : "PROCEDURE" ID "(" params? ")" block ;

params          : ID ( "," ID )* ;

returnStmt      : "RETURN" "(" expr ")" ;

expr            : ( ID | ( call "[" expr "]" ) ) ( "←" expr )
                | or ;

or              : and ( "OR" and )* ;

and             : not ( "AND" not )* ;

not             : ( "NOT" )? equality ;

equality        : comparison ( ( "=" | "≠" ) comparison )* ;

comparison      : arithmetic ( ( ">" | "≥" | "<" | "≤" ) arithmetic )* ;

arithmetic      : term ( ( "+" | "-" ) term )* ;

term            : factor ( ( "*" | "/" | "MOD" ) factor )* ;

factor          : ( "-" )? call ;

call            : primary ( ( "(" exprList? ")" ) | ( "[" expr "]" ) )* ;

primary         : NUMBER
                | ID
                | STRING
                | "[" exprList? "]"
                | "(" expr ")" ;

exprList        : expr ( "," expr )* ;

NUMBER          : DIGIT+ ;
ID              : ALPHA ( ALPHA | DIGIT )* ;
STRING          : '"' [^"]* '"' ;

DIGIT           : [0-9] ;
ALPHA           : [a-zA-Z_] ;
You might also like...

Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

May 3, 2022

A browser-based Piet editor/interpreter

A browser-based Piet editor/interpreter Features An interpreter that fully conforms to the Piet specification Code editor with a palette with command

Nov 22, 2022

Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

Jan 3, 2023

A Typescript assembly(ish) interpreter with a nice web UI

Assembly-Online Example Fibonacci Program MOV R0, #1 MOV R1, #1 fib: MOV R2, R0 ADD R0, R0, R1 MOV R1, R2 B print CMP R0, #40 BGT exit B fib exit: \ I

May 23, 2022

A simple tap test runner that can be used by any javascript interpreter.

just-tap A simple tap test runner that can be used in any client/server javascript app. Installation npm install --save-dev just-tap Usage import cre

Nov 7, 2022

A complete guide for learning Object Oriented Programming Pillars, SOLID Principles and Design Patterns with TypeScript!

A complete guide for learning Object Oriented Programming Pillars, SOLID Principles and Design Patterns with TypeScript!

Object Oriented Programming Expert With TypeScript This repository is a complete guide and tutorial for the principles and techniques of object-orient

Dec 29, 2022

Playground for studying design patterns, solid principles, GoF, testing and more with TypeScript

TypeScript design patterns study Playground for studying design patterns, solid principles, GoF, testing and more with TypeScript Index TypeScript des

Dec 9, 2022

Semantic is a UI component framework based around useful principles from natural language.

Semantic is a UI component framework based around useful principles from natural language.

Semantic UI Semantic is a UI framework designed for theming. Key Features 50+ UI elements 3000 + CSS variables 3 Levels of variable inheritance (simil

Jan 7, 2023

NewsStation is a news app which can be used to grab daily news bites. If you are interested in news whether politics, business, entertainment, general, health, science, sports and technology news NewsStation is for you!

NewsStation is a news app which can be used to grab daily news bites. If you are interested in news whether politics, business, entertainment, general, health, science, sports and technology news NewsStation is for you!

This is a NewsStation WebApp Project Using News API NewsStation is a news app which can be used to grab daily news bites. If you are interested in new

Feb 7, 2022
Comments
  • Bump minimist from 1.2.5 to 1.2.6

    Bump minimist from 1.2.5 to 1.2.6

    Bumps minimist from 1.2.5 to 1.2.6.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 1
  • My life is forever changed

    My life is forever changed

    Ever since I saw this repo, I can't stop writing collegeboard pseudocode. It started off as a minor addiction, I would code in it for 5 hours a day, but now it has gone too far. I rewrote the entire linux kernel and recreated every algorithm ever created in this amazing language. I love collegeboard so much as they are a very non corrupt non money hungry organization. This language has changed my life. I left my romantic partner just so I could go and live in an upstate new york apartment and fantasize about my time with this language. This language has made it so I will never touch grass again. Please send help.

    Sincerely, Mlon Eusk

    opened by jayaram-karthik 1
Papers from the computer science community to read and discuss.

Papers We Love (PWL) is a community built around reading, discussing and learning more about academic computer science papers. This repository serves

Papers We Love 66.8k Dec 31, 2022
A custom element that aims to make it easier to embed Spring '83 boards

<spring-board> element A custom element that makes it simple to embed Spring '83 boards! Usage If you are using <spring-board> in a client-side framew

Ryan Murphy 11 Jan 1, 2023
Vanilla Javascript plugin for manage kanban boards

jKanban Javascript plugin for Kanban boards jKanban allow you to create and manage Kanban Board in your project! Please try out the live demo! Install

Riccardo Tartaglia 898 Jan 3, 2023
This is college project in which me and my team create a website that provide the tools for basic text modification and add todos also we add blog init.

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Ayush 4 Jun 9, 2022
College project done for the CG Artwork lecture in 2022. Used HTML for the indexes and mainly JavaScript (using to THREE.js). Ended with the final A grade (17.3 in scale grade).

CG Artwork Project 2022 This project was done by a group of 3 in 2022 with an educational purpose for the CG Artwork lecture in Instituto Superior Téc

filipe_neves 3 Sep 19, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Detect the executable python interpreter cmd in $PATH.

detect-python-interpreter Detect the executable python interpreter cmd in $PATH. Installation $ npm install --save detect-python-interpreter Usage con

Khaidi Chu 2 Apr 12, 2022
A Brainf*ck interpreter built in the TypeScript type system.

Brainf*ck Interpreter in the TypeScript type system Just another thing that no one asked for. Why? I love messing with the TypeScript type system. Som

Carter Snook 55 Dec 17, 2022