Skip to content

Repository files navigation

GitGem

BASIC++ Interpreter

Version 6.5.2

I don't care what you do with my code, just don't take my code and sell it and/or don't take my code, modify my code, and sell it. This code is not for sale.

I do encourage you to fork this into your own implementation. Everything you need is right there in the source.


Abstract

BASIC++ v6.5.2 ships with a configurable 6-level security sandbox, a virtual device layer, a plugin system, a native code transpiler/compiler (bppc), and 1034 synchronized documentation files (docs/ Markdown and help/ Plaintext).

Designed for small memory footprints, strict C17 portability (-std=c17), and readable source code. Runs on Windows 11, Linux, FreeDOS, and embedded microcontrollers. Suitable for embedded systems, legacy hardware, and as a teaching tool for interpreter design (tokenization, non-recursive AST evaluation, virtual machines, and environment management).

Standalone Legacy Interpreters

Alongside the main BASIC++ interpreter, the repository includes five fully self-contained, single-file legacy interpreters at standalone/. These are preserved as highly portable, freestanding C89 (ANSI) / C90 (ISO) educational and historical references:

  • 1964.c: Original Dartmouth BASIC 1964 interpreter.
  • level1.c: TRS-80 Level I BASIC 1977 interpreter.
  • woz.c: Apple II Integer BASIC 1977 interpreter by Steve Wozniak.
  • cbm.c: Commodore PET / 64 BASIC v2.0 1977 interpreter.
  • tinybasic.c: Palo Alto Tiny BASIC 1976 interpreter by Dr. Li-Chen Wang.

1. Interpreter Editions & Targets (v6.5.2)

BASIC++ is distributed in three decoupled compilation executables, allowing it to scale from modern graphical workstations down to resource-constrained microcontrollers:

1.1 baspp / baspp.exe (Flagship Desktop Edition)

Standard Console & SDL Combined. GW-BASIC / QBASIC style (> prompt with Ok status). Delay-loads SDL2.dll on demand for SCREEN/graphics commands. Default memory pool: 640 MB (671088640L bytes).

1.2 bpp / bpp.exe (Lite REPL Edition)

Headless interactive REPL optimized for terminal environments and IoT. Apple II / Commodore style (] prompt with Ready. status). Default memory pool: 384 MB (402653184L bytes). Excludes SDL2 graphics, BGI canvas drawing, SDL audio, TUI editor multiplexer, and segmented memory (vmem).

1.3 bs / bs.exe (Batch Script Runner)

Headless non-interactive batch script runner optimized for PowerShell, Bash, CGI pipelines, and automated jobs. Default memory pool: 64 MB (67108864L bytes). Zero banner, zero prompt, zero REPL iterations.

1.4 bppc / bppc.exe (Compiler & Transpiler)

Separate build target that transpiles BASIC source to clean C17 or appends bytecode directly to a C17 VM stub.


3. Built-in Development Environments (IDEs)

BASIC++ features four natively embedded text editors, accessible via command-line switches, ensuring cross-platform development capabilities without relying on external host tools:

  • --edit (MS-DOS EDIT Clone): A robust, menu-driven IDE featuring a drop-down menu system, dynamic syntax rendering, and dual-mode (Color/Monochrome) support.
  • --vi (vi Clone): A modal editor faithfully replicating classic vi commands (Normal/Insert/Visual modes, yank, put, delete).
  • --ws (WordStar Clone): A classic WordStar-compatible editor, utilizing historic ^K control block sequences.
  • --edlin (EDLIN Clone): A line-oriented REPL editor for low-bandwidth terminals or headless environments.

Universal Editor Features: All embedded editors feature seamless integration with modern operating systems:

  • Universal Syntax Highlighting Toggle: Press F10 (or o in EDLIN) in any editor to instantly toggle dynamic color syntax highlighting.
  • CUA Visual Selection: Native Shift+Arrows text highlighting.
  • OS Clipboard Integration: Deep integration with the host OS clipboard (Windows/SDL2) using legacy CUA hotkeys (Ctrl+Ins for Copy, Shift+Del for Cut, Shift+Ins for Paste) without colliding with standard IDE or vi/WordStar commands.

2. Core Features

The interpreter provides a comprehensive implementation of BASIC with a union-mode parser that accepts a comprehensive keyword set covering standard BASIC features by default.

2.1 Data Types

BASIC++ supports three fundamental data types:

  • Integers — 32-bit signed (long), providing a range of −2,147,483,648 to +2,147,483,647. All integer division is truncating (e.g., 7 / 3 evaluates to 2).
  • Floating-point — Double-precision IEEE 754 (double), activated via numeric literals containing a decimal point (e.g., 3.14) or via configuration. Supports the full suite of transcendental functions: SIN, COS, TAN, ATN, SQR, LOG, EXP.
  • Strings — Variable-length character sequences up to 255 characters, managed via a pooled allocator. String variables are denoted by the $ suffix (e.g., A$, NAME$).

2.2 Variable Storage

The variable system provides three tiers of storage:

TierCapacityScopeDescription
Single-letter26 numeric (AZ), 26 string (A$Z$)GlobalDirect array-index lookup, zero overhead
Named variablesUp to 256 identifiers, 31 characters maxGlobalHash-based lookup (e.g., SCORE, PLAYER_NAME$)
DIM arraysUp to 64 arrays, 2 dimensions max, 8,192 total elementsGlobalRow-major flat pool, supports numeric and string arrays

All variables are initialized to zero (numeric) or empty string (string) upon RUN. The CLEAR command resets all variable storage without affecting the stored program.

2.3 Parser

Expression evaluation in both the interpreter and C transpiler is conducted via an iterative, stack-based Shunting-Yard precedence parser with correct mathematical operator precedence:

^ (highest — exponentiation)
- (unary), NOT (negation)
*, /, \ (multiply, divide, integer-divide)
MOD (modulo)
+, - (add, subtract, string concatenation)
=, <>, <, >, <=, >= (comparison)
AND (bitwise/logical AND)
OR, XOR (bitwise/logical OR, exclusive OR)
EQV, IMP (equivalence, implication — lowest)

Sub-expressions encapsulated in parentheses and function arguments are evaluated iteratively using dedicated operand and operator stacks, avoiding host C language recursion limit dependencies. The parser supports both line-numbered program mode and unnumbered direct (immediate) mode execution.

2.4 Implemented Directives

The interpreter implements over 430 keywords spanning the following categories:

Data I/O:PRINT, PRINT USING, LPRINT, INPUT, LINE INPUT, READ, DATA, RESTORE, WRITE

Assignment:LET (optional), SWAP, CONST

Program Flow & Multitasking:GOTO, GOSUB, RETURN, IF...THEN...ELSE, FOR...NEXT, WHILE...WEND, DO...LOOP, SELECT CASE, ON...GOTO, ON...GOSUB, EXIT, TASK

Subroutines & Functions:SUB...END SUB, FUNCTION...END FUNCTION, CALL, DEF FN, SHARED, STATIC

Arrays & Matrices:DIM, REDIM, ERASE, OPTION BASE, MAT READ, MAT PRINT, MAT arithmetic (+, -, *), MAT ZER, MAT CON, MAT IDN, MAT TRN, MAT INV

File I/O:OPEN, CLOSE, INPUT #, PRINT #, LINE INPUT #, WRITE #, GET, PUT, SEEK, LOF, LOC, EOF, FIELD, LSET, RSET

Error Handling:ON ERROR GOTO, RESUME, RESUME NEXT, ERR, ERL, ERROR

String Functions:LEN, LEFT$, RIGHT$, MID$, ASC, CHR$, VAL, STR$, INSTR, LCASE$, UCASE$, LTRIM$, RTRIM$, SPACE$, STRING$, HEX$, OCT$

Graphics & Sound:SCREEN, PSET, PRESET, LINE, CIRCLE, DRAW, PAINT, PALETTE, COLOR, SOUND, PLAY, BEEP

Screen & Console:CLS, LOCATE, WIDTH, CSRLIN, POS, INKEY$, KEY

User-Defined Types:TYPE...END TYPE, typed variable fields, arrays of records

System & Shell:SHELL, SHELL$(), EXEC, ENVIRON, ENVIRON$(), CHDIR, MKDIR, RMDIR, KILL, NAME, FILES

Memory:PEEK, POKE, PEEKB, POKEB, DEF SEG, VARPTR, FRE

Environment:NEW, RUN, LIST, SAVE, LOAD, MERGE, CHAIN, RENUM, DELETE, AUTO, EDIT, VARS, VER, HELP, CATALOG, DIR, BYE

Debugging & Unit Testing:TRON, TROFF, BREAK, CONT, TRACE, BACKTRACE, INFO, DEBUG, DUMP, CHECK, VERIFY, TEST, ASSERT, ENDTEST, SELFTEST

Security:SECURITY LEVEL, SECURITY REPORT

Extensibility:ALIAS, MODULE, OPTION STRICT, COMPILE

2.5 Environment Directives

A distinct set of directives, which operate at the "edit" level outside stored programs, are provided for managing the runtime environment:

CommandFunction
RUN [line]Execute program (optionally from a specific line)
LIST [range/search]Display stored program lines or search patterns
NEWClear program memory and variables
SAVE "filename"Persist program to disk
LOAD "filename"Retrieve program from disk
MERGE "filename"Merge file into current program
RENUM [start [, step]]Renumber program lines
DELETE n1-n2Delete a range of program lines
AUTO [start [, step]]Automatic line numbering mode
EDIT lineEdit a specific program line
SELFTESTRun built-in diagnostic test suite
VERDisplay version, copyright, and build date
HELP [keyword]Display help for a command or topic
BYEExit the interpreter to the OS prompt

2.6 Input/Output Operations

The core implementation provides multiple output pathways:

  • PRINT — Output to the primary console (standard output) with support for string literals, numeric expressions, format specifiers (, zone-based, ; packed), and PRINT USING for formatted output with template strings.
  • LPRINT — Redirects output to the error device (lprint.out), simulating a physical line printer.
  • File I/O — Full GW-BASIC/QBasic-compatible file operations supporting sequential (INPUT, OUTPUT, APPEND), random-access (RANDOM), and binary (BINARY) modes across 8 simultaneous file channels (#1 through #8).
  • Shell integrationSHELL "command" for synchronous execution, SHELL$("command") for output capture, pipe (|) and redirect (>, >>) operators.

2.7 Program Serialization & Execution Formats

BASIC++ supports four execution and storage profiles to enable portable and secure distribution of BASIC applications:

  • Source Code (.BAS) — Human-readable, byte-for-byte preserved plain text BASIC source code. Correct formatting, whitespace, and case choices are maintained.
  • Compiled VM Bytecode (.BPP) — Platform-independent bytecode format containing serialized VM instructions, string pools, line number maps, and ON jump tables. Features VM major version validation and payload CRC-16 integrity checks. If the adjacent .BAS source file is missing, it runs in orphaned execution mode where interactive LISTing and line editing are blocked.
  • Portable Libraries (.BPL) — Pre-compiled bytecode modules with export tables. Supports XOR-obfuscation (0x5A) of source code representation on disk for proprietary/obfuscated library imports.
  • Execution Archives (.EXE/.BPE) — Self-contained chunk-based containers bundling metadata (META), dependencies (DEPS), source code (SRC_), compiled bytecode (BYTE), and combined signatures (SIGN) for direct cross-platform execution.

4. Security Sandboxing

BASIC++ includes a three-tier security model that controls access to sensitive operations. This is critical for environments where untrusted BASIC programs may be executed (e.g., BBS systems, educational labs, online services).

4.1 Security Levels

LevelNameFile ReadFile WriteShellNetwork
0OPEN
1STANDARD
2RESTRICTED
SECURITY LEVEL 2 ' Lock down to restricted mode
SECURITY REPORT  ' Display current security posture

5. Architecture

5.1 Source File Organization

The interpreter is organized into 363 compilation units, strictly organized by subsystem:

DirectoryPurpose
source/core/Boot sequence, REPL loop, memory pools, value system, errors, shutdown
source/lexer/Tokenizer with 430-keyword table, alias language parsing
source/parser/Recursive-descent parser, expression evaluation, direct execution dispatch
source/runtime/Runtime state, call stack, AST execution, FOR/NEXT/WHILE frames
source/io/Sequential, random-access, binary file I/O, networking
source/virtual/Virtual device layer, Virtual Machine formalization, VDev API
source/functions/Function registry, built-ins, user-defined functions (DEF FN)
source/codegen/C code generator, AST processing, archive builder for transpiler
source/standalone/Legacy standalone emulators (TinyBASIC, Level I, Apple II, 1964)
source/modules/Extensible plugin system (JIT, USB, UPnP, Edlin, vi, WordStar, etc.)
source/help/Interactive help system and documentation generation
source/memory/Virtual memory maps (MSDOS, C64, Atari, Apple, ZX), RAMBANKs
source/graphics/Graphics framebuffer (320x200, 16 colors) and shape rendering
source/config/Configuration options, settings overrides, program scope
source/progmgmt/Program commands, token detokenizer (GW-BASIC)
source/config.hMaster compile-time constants, dimensions, and structural limits

5.2 Memory Layout

All interpreter memory is defined by static, fixed-size pools. Dimensions are established at compile-time via #define constants in config.h, ensuring a predictable and verifiable memory footprint.

Memory AreaConstantDefault SizeDescription
Program StorageMAX_PROGRAM_LINES4,096 linesStored BASIC program lines
Program PoolPROGRAM_MEMORY_SIZE64 KBRaw program text storage
Variable PoolVARIABLE_MEMORY_SIZE64 KBVariable and array storage
Scratch PoolSCRATCH_MEMORY_SIZE64 KBTemporary token/expression buffers
String PoolMAX_STRING_POOL32 KBRuntime string allocations
Array ElementsMAX_ARRAY_ELEMENTS8,192Flat pool shared across all arrays
Virtual MemoryMAX_MEM_SEGMENT64 KBPEEK/POKE address space
Call StackMAX_STACK_DEPTH256 levelsGOSUB, FOR/NEXT, SUB/FUNCTION frames
File ChannelsMAX_FILE_CHANNELS8Simultaneous open files
Graphics PoolGRAPHICS_MEMORY_SIZE4 MBDynamic sprite, page, and font cache

5.3 Adjustment of Memory Allocations

Alterations to these memory limitations are effectuated by modifying the appropriate #define pre-processor constants within config.h. Subsequent recompilation of the interpreter is mandatory for such changes to take effect. This compile-time configuration is a deliberate design choice, precluding runtime memory negotiation. This approach ensures that the interpreter's resource requirements are fixed and verifiable, a critical attribute for high-reliability systems, embedded applications, or legacy operating systems where dynamic memory management is complex or unreliable.

5.4 Segmented Virtual Memory (RAMBANKs) & Multitasking

BASIC++ implements a high-performance Segmented Virtual Memory system (RAMBANKs) and a multitasking process system:

  • RAMBANKs: Supports up to 254 virtual memory banks (1MB each) dynamically mapped into a resident bank pool (max 8 resident banks) utilizing a Least Recently Used (LRU) page eviction algorithm and disk swapping. Page swap data is obfuscated using XOR encryption according to the active security sandbox level.
  • Multitasking: Spawns concurrent background worker tasks (TASK("filename")) running on native OS threads (Win32 threads or POSIX threads) with transparent fallback schedulers using cooperative statement-level slicing on the main interpreter loop.
  • Memory Controls: Provides the unified BANK command family (BANK LIST, BANK n SHARED/PRIVATE, BANK n CLEAR, BANK n STATUS, BANK n switch, BANK COPY fast bulk copy, and BANK FILL fast bulk fill) under thread-safe mutex synchronization constraints.
  • Process synchronization: Supports join/waits (TASK WAIT pid), process termination (TASK KILL pid), and process lifecycle queries (TASK(pid) status function).

6. Compilation

The C source code is designed for high portability and is compilable on any system featuring a standards-compliant C compiler. No external libraries, package managers, or build frameworks are required.

6.1 Quick Build

# Windows (MSVC — from Developer Command Prompt)
cl /TC /W3 /O2 /Fe:basicpp.exe *.c
# Linux / macOS (GCC or Clang)
gcc -O2 -o basicpp *.c -lm
clang -O2 -o basicpp *.c -lm
# FreeDOS (OpenWatcom)
wcc -ml -0 -za -wx *.c
wlink name basicpp.exe file *.obj

6.2 Compilation for Portability and Size (Recommended)

gcc -Wall -Os -o basicpp *.c -lm

This incantation invokes the compiler with -Wall to enable all high-priority warnings, a best practice for identifying potential portability issues or unsafe code. Crucially, it uses -Os, which instructs the compiler to optimize specifically for the size of the resulting executable binary. This optimization level is often the primary concern in memory-constrained systems, such as the target embedded environments.

6.3 Compilation for Execution Speed

gcc -Wall -O2 -o basicpp *.c -lm

This command uses the -O2 flag, enabling a more aggressive set of optimization passes (such as loop unrolling and function inlining) focused on increasing execution velocity. This may come at the cost of a slightly larger binary file. This build is suitable for desktop systems where performance is prioritized over footprint.

6.4 Compilation for Debugging (Symbolic Inclusion)

gcc -Wall -g -O0 -DDEBUG -o basicpp *.c -lm

This command utilizes the -g flag to include debugging symbols (such as DWARF) within the final executable. The -DDEBUG flag enables debug-mode assertions and verbose diagnostics within the interpreter. This symbolic information is essential for using a debugger (such as GDB) to trace program execution, inspect variables, and analyze the call stack.

6.5 Using the Makefile

A Makefile is provided for incremental builds:

make # GCC release build (default)
make debug # GCC debug build with symbols
make msvc # MSVC build (from VS command prompt)
make watcom # OpenWatcom build (FreeDOS)
make clean # Remove build artifacts

7. Operational Use

The interpreter operates via a standard REPL (Read-Evaluate-Print Loop) interface. This interface provides two distinct contexts for operation: Direct Mode and Program Mode.

7.1 Direct Mode

The direct, or "immediate," execution context is invoked when directives are entered without a preceding line number. Such directives are evaluated and executed immediately upon entry. This mode is principally utilized for testing, debugging, performing calculations, or inspecting variable state.

> PRINT 10 + 5
15
> A = 42 : PRINT A * 2
84

7.2 Program Mode

The "stored program" context is invoked when directives are entered with a preceding line number. Such lines are not executed; instead, they are inserted into the Program Storage array, maintained in sorted order by line number.

> 10 PRINT "Hello"
> 20 GOTO 10

7.3 Deferred Mode (Edlin)

While BASIC++ defaults to an Immediate Mode REPL (Direct Mode), it also natively supports a Deferred Mode workflow (similar to QBASIC or modern IDEs) via the built-in screen editor. In Deferred Mode, statements are not evaluated or executed line-by-line as they are typed. Instead, you write your entire program within a text buffer offline. Once the program is fully written, it is passed to the host engine in a single batch for execution.

To invoke Deferred Mode, launch the interpreter with the --edlin (or --edit) flag:

> basicpp-console.exe --edlin

Once inside the editor, you may use the x command to execute the entire buffer as a BASIC++ program.

By default, decimal line numbers must be between 1 and LINE_NUMBER_MAX (65529).

BASIC++ also supports hexadecimal, octal, and binary line numbers. These line numbers are allowed to go up to 4294967295 (32-bit unsigned):

  • Hexadecimal: Prefixed with &H/&h or 0x/0X (e.g., &H10 PRINT or 0x10 PRINT stores under line number 16).
  • Octal: Prefixed with &O/&o, 0o/0O, or a bare & followed by octal digits (e.g., &O10 PRINT or &10 PRINT stores under line number 8).
  • Binary: Prefixed with &B/&b or 0b/0B (e.g., &B10 PRINT or 0b10 PRINT stores under line number 2).

When listed using LIST, the original prefix format and base are preserved exactly as entered by the programmer. Directives that reference line numbers (such as GOTO, GOSUB, RESTORE, and DELETE) can use any base representation in their expressions (e.g., GOTO &H10).

> 10 PRINT "Hello, World!"
> 20 FOR I = 1 TO 5
> 30 PRINT I; " ";
> 40 NEXT I
> 50 END
> LIST
10 PRINT "Hello, World!"
20 FOR I = 1 TO 5
30 PRINT I; " ";
40 NEXT I
50 END
> RUN
Hello, World!
1 2 3 4 5

7.4 Command-Line Switches

The interpreter executable supports several switches when launched from the command line:

  • -q / --quiet — Quiet mode; suppresses the startup banner and prompts.
  • -c "command" — Run the specified BASIC command in batch mode and exit.
  • -r "file.bas" — Load and run the specified BASIC script file and exit.
  • --list "file.bas" — Load the specified program, print its source code listing, and exit.
  • --dry-run "file.bas" — Load the specified program in debug/step-by-step mode with File I/O disabled.
  • --edit — Start the interpreter in full-screen editor mode.
  • --edlin [file] — Start the interpreter in line-editor mode (runs edlin), optionally loading the specified file.
  • --log [filename] — Enable session logging. Saves boot phase diagnostics and runtime warnings/trace to the specified file. If no filename is provided, a dynamic name like [script]-yyyy-mm-dd-hh-mm-ss.LOG is generated.
  • --out [filename] — Echo all console program output and keyboard inputs to the specified file. If no filename is provided, a dynamic name like [script]-yyyy-mm-dd-hh-mm-ss.OUT is generated, using the same timestamp as the log file.
  • --clean-up / --cleanup — Sweep intermediate files (logs, object files, stub modules, etc.) in the workspace, but preserve the most recently modified .LOG file and .OUT file.
  • --full-clean-up / --full-cleanup — Sweep all intermediate files including all .LOG and .OUT files.

7.5 Program Execution

The RUN directive initiates sequential execution of the stored program. This directive first clears Variable Storage and the Call Stack to a zeroed state, ensuring that the program executes in a clean, predictable environment. Execution begins at the lowest extant line number. The BYE command exits the interpreter entirely, returning control to the operating system.

7.6 Built-In Diagnostics (SELFTEST)

The interpreter includes a formal self-test diagnostic suite. By running the command:

SELFTEST

or launching the binaries from the host shell:

basicpp-console.exe -c "SELFTEST"

the interpreter executes a series of exhaustive subtests:

  1. Lexer — Verifies tokenization correctness.
  2. Value System — Tests integer, double-precision float operations, and type coercion.
  3. String Pool — Introspects bump-allocator usage and bounds.
  4. Function Registry — Asserts that all built-in library functions are properly registered.
  5. Memory Pool — Validates scratch memory allocation watermarks.
  6. Parser Precedence — Checks recursive-descent math precedence rules.
  7. Loop Control Flow — Exercises FOR/NEXT loop evaluation.
  8. VFS File I/O — Runs sequential line writes and inputs.
  9. Device Aliases — Confirms that device mappings (e.g. SCRN: -> CON:) resolve.
  10. Graphics/SDL2 — Assesses compiled vs. linked SDL versions, queries renderer features (VSync, hardware acceleration, maximum texture sizes), monitor resolutions, active drivers, and audio synthesis devices.

In Console/text-only builds, SELFTEST dynamically boots the SDL2 engine on-demand to verify graphical and audio capabilities, cleaning up all SDL window and audio threads immediately after the check completes. When run in conjunction with --log, all diagnostic metadata is written in-depth to the active session log.


8. Halting Non-Terminating Execution

In the event a BASIC program enters a non-terminating loop, which is a common possibility given the GOTO directive, execution may be interrupted by two mechanisms:

  1. Ctrl+C (SIGINT) — Issuing an interrupt signal from the controlling terminal. The host operating system will halt the interpreter process and return control to the command shell.
  2. STOP / BREAK — If placed within a program, the STOP statement suspends execution and enters direct mode, allowing inspection of variables. Execution may be resumed with CONT. The BREAK command sets breakpoints for the interactive debugger.

9. Virtual Device Layer

BASIC++ abstracts all I/O through a virtual device (VDev) interface, enabling portability across operating systems and hardware configurations without modifying the core interpreter.

9.1 Built-In Devices

DeviceIDFunction
Consoledev_conPrimary screen output and keyboard input
Errordev_errError/diagnostic output (stderr)
Filedev_fileFile I/O channels (#1 through #8)
Printerdev_lptLPRINT output device

9.2 Virtual Memory Maps

The MEMMAP system provides pre-configured virtual address spaces that emulate classic platforms:

MEMMAP "C64" ' Commodore 64 memory layout
MEMMAP "MSDOS" ' IBM PC / MS-DOS layout
MEMMAP "APPLE2" ' Apple II memory map
MEMMAP "ATARI8" ' Atari 400/800 layout
MEMMAP "ZX" ' ZX Spectrum layout

9.3 Graphics Framebuffer

A 320×200, 16-color virtual framebuffer is provided, matching QBasic SCREEN 1. Graphics are rendered to the terminal using Unicode half-block characters.


10. Module System

The module system provides C-level code extensibility. Modules add new keywords, functions, and hardware abstractions to the interpreter.

10.1 Built-In Modules

ModuleDescription
STDLIBStandard library — core mathematical and string functions
USBUSB HID (gamepads, joysticks) and USB serial (FTDI, CH340, Arduino)

10.2 Creating External Modules

External modules follow the ModuleInterface contract: an init(), shutdown(), and keyword registration via funcreg_override(). See External_Modules.txt for the complete API specification.


11. Transpiler

BASIC++ includes a powerful External Compilation Suite (bppc and trans):

  • trans (Transpiler): Converts stored .BAS programs and bytecode into standalone C17, Python 3, Free Pascal, or Fortran source code with strict, no-dependency translation rules.
  • bppc (Compiler Orchestrator): Invokes trans and automatically orchestrates external C compilers (MSVC, Watcom, GCC) to compile C17/Python stubs into native executables. It also supports zero-toolchain standalone compilation (--target standalone) which prepends native host/cross-platform interpreter runner binaries to packaged BPE payloads for portable execution.
  • detok (Detokenizer): Converts legacy proprietary binary formats (GW-BASIC, QBASIC) into plaintext .BAS for compilation.
10PRINT"Hello, World!"20END
COMPILE "hello" ' Generates hello.c

12. Future Expansion Trajectory

The architecture is explicitly provisioned for future expansion. The following classifications for extensibility have been identified:

12.1 Addons

This classification is designated for the most advanced extensibility, involving the incorporation of inline foreign language code. This system would provide meta-directives (e.g., $LANG: C) to allow a user to embed, compile, and link source code from other languages, such as Assembly, Pascal, or C, directly within a BASIC program file. This represents the ultimate goal of a mixed-language development environment, likely implemented via a transpiler and external compiler-chaining.

12.2 Merge

This classification refers to functionality for BASIC source code amalgamation, specifically the MERGE directive. This system maintains strict compliance with the behavioral standards of ECMA-55 (Minimal BASIC), ECMA-116 (Full BASIC), and/or QBasic/QuickBASIC. Its function is to load a BASIC program file from storage and combine it with the program already resident in memory, with lines from the incoming file overwriting any pre-existing lines with identical numbers. This is the foundational pillar for user-level code sharing.

12.3 Modules

This classification defines the primary system for C-level code extensibility. A "Module" is a compiled C-code entity that adds new keywords and syntactic features to the interpreter. This system is responsible for language syntax modification, enabling the creation of specific feature sets (e.g., adding a GRAPHICS module to provide PSET and LINE, or a SOUND module to provide PLAY). This is the mechanism by which the interpreter evolves from "Core" to "Full" BASIC.

12.4 Plugins

This classification defines a specialized subset of Modules. A "Plugin" is a C-code module designated for low-level hardware mapping, system emulation, and direct memory interfacing. A Plugin functions as a "driver," abstracting the hardware. For example, a SOUND Module (Section 12.3) provides the SOUND keyword, but it calls a SOUND Plugin (e.g., pc_speaker.plugin for DOS or oss.plugin for Linux) to actually generate the audio. This architectural separation of semantics (Module) from implementation (Plugin) is the key to achieving cross-platform portability for hardware-dependent features.


13. Documentation

A comprehensive documentation suite of 774 reference manuals and tutorials (including Markdown formats) is included:

DocumentSubject
Users_Guide.txtGetting started, environment, commands
Programmers_Guide.txtComplete language reference
How_To_Compile.txtBuilding from source on all platforms
Quick_Reference.txtAlphabetical keyword reference card
Self_Programming.txtMeta-programming and self-modification
Scripting_Functions.txtShell integration, pipes, redirects
Using_Aliases.txtKeyword remapping with ALIAS
Arrays_And_Matrices.txtDIM, REDIM, MAT operations, sorting
File_IO.txtSequential, random-access, binary files
flowchart.txtVisual flowcharts and architecture diagrams
Advanced_DEF.txtDEF FN, FUNCTION/SUB, closures
External_Modules.txtModules, plug-ins, system services
Error_Handling.txtON ERROR, RESUME, ERR, ERL
Graphics_Sound.txtSCREEN, DRAW, LINE, SOUND, PLAY
Debugging.txtTRON, TROFF, STOP, CONT, BREAK
Security.txtSandboxing and trust levels
Secure_Coding.txtWriting safe and defensive BASIC++ code
Virtual_Devices.txtVDev system, INP, OUT, custom devices
Virtual_Machines.txtVirtual machines, consoles, terminals
Virtual_Filesystem.txtSafe local file access
Virtual_Network.txtTCP, UDP, TLS, Telnet, SSH, FTP, IRC, HTTP
Virtual_Memory_RAMBANKs.mdSegmented virtual memory and bank swapping
Multitasking_Systems.mdMultitasking scheduler and task control
USB_Devices.txtUSB HID and serial device support
Compiling_BASIC_Programs.txtTranspile BASIC to native executables
Memory_Maps.txtCreating and using MEMMAP presets
Systems_Programming.txtBare-metal execution, drivers, OS design
User_Defined_Types.txtTYPE...END TYPE, records, typed fields
Screen_And_Console.txtLOCATE, COLOR, CLS, WIDTH, PRINT USING
Subroutines_And_Functions.txtGOSUB, SUB/FUNCTION, DEF FN, CALL
String_Handling.txtString functions, pool architecture
Internals_And_Architecture.txtBoot sequence, memory, parser pipeline

14. Example Session

BASIC++ Standard 5.0.5
@COPYLEFT ALL WRONGS RESERVED
Jul 10 2026
Ready.
> 10 INPUT "Your name"; N$
> 20 PRINT "Hello, "; N$; "!"
> 30 FOR I = 1 TO 3
> 40 PRINT I; " Mississippi..."
> 50 NEXT I
> 60 END
> RUN
Your name? World
Hello, World!
1 Mississippi...
2 Mississippi...
3 Mississippi...
> SAVE "hello.bas"
> BYE
Goodbye.

15. Project Statistics

MetricValue
Source files222 .c + 141 .h
Lines of code~121,000
Keywords430
Documentation files774
External dependenciesZero
C standardC17
License@COPYLEFT ALL WRONGS RESERVED

Last updated: 2026-07-10 (Universal Color Scheme Integration & Directory Cleanup)

BASIC++ — Because the world needed one more BASIC interpreter.

About

Core Integer BASIC

Resources

Security policy

Stars

2 stars

Watchers

1 watching

Forks

Releases

Used by

Contributors

Languages