From 2929db43c2dd094e09baba4733e92b80433718d3 Mon Sep 17 00:00:00 2001 From: Arigadam Date: Sun, 11 Oct 2026 13:56:26 +0300 Subject: [PATCH] Create UBASIC_API.md --- UBASIC_API.md | 272 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 272 insertions(+) create mode 100644 UBASIC_API.md diff --git a/UBASIC_API.md b/UBASIC_API.md new file mode 100644 index 0000000..c18a852 --- /dev/null +++ b/UBASIC_API.md @@ -0,0 +1,272 @@ +# uBASIC API Reference + +uBASIC is a tiny, non-interactive BASIC interpreter written in C by Adam Dunkels. It is meant to be embedded in a host application as a small scripting language. + +This reference describes uBASIC **with `ubasic-embed.patch` applied**. Differences from upstream are marked with *(patch)*. + +- Upstream: https://github.com/adamdunkels/ubasic +- License: BSD 3-clause +- Files: `ubasic.c/.h` (interpreter), `tokenizer.c/.h` (lexer), `vartype.h` (value type) + +--- + +## Quick start + +```c +#include "ubasic.h" + +static const char program[] = + "10 for i = 1 to 3\n" + "20 print i\n" + "30 next i\n" + "40 end\n"; + +int main(void) +{ + ubasic_init(program); + do { + ubasic_run(); /* executes one program line */ + } while (!ubasic_finished()); + + if (ubasic_error() != UBASIC_OK) { + fprintf(stderr, "error: %s\n", ubasic_error_message()); + } + return 0; +} +``` + +Build: `cc -o app app.c ubasic.c tokenizer.c` + +--- + +## Types + +### `VARIABLE_TYPE` + +Defined in `vartype.h`. The type of every BASIC value (variables, expression results, PEEK/POKE arguments). + +| Version | Definition | Range | +|---|---|---| +| Upstream | `char` | -128..127 | +| Patched *(patch)* | `int32_t` | -2^31..2^31-1 | + +Change it to suit your target (for example `int16_t` on a small microcontroller). + +### `peek_func` + +```c +typedef VARIABLE_TYPE (*peek_func)(VARIABLE_TYPE addr); +``` + +Called by the `PEEK` statement. Returns the value stored at `addr`. + +### `poke_func` + +```c +typedef void (*poke_func)(VARIABLE_TYPE addr, VARIABLE_TYPE value); +``` + +Called by the `POKE` statement. + +--- + +## Functions + +### `ubasic_init` + +```c +void ubasic_init(const char *program); +``` + +Resets the interpreter and loads `program`. + +- The string is **not copied**. It must stay valid and unmodified while the program runs. +- Every line, including the last one, must end with `\n`. +- Every line must start with a line number. +- Clears the PEEK/POKE callbacks to `NULL` *(patch)*, resets all variables to 0 *(patch)*, and clears the error state *(patch)*. + +### `ubasic_init_peek_poke` + +```c +void ubasic_init_peek_poke(const char *program, peek_func peek, poke_func poke); +``` + +Same as `ubasic_init`, and also registers the callbacks used by `PEEK` and `POKE`. Either callback may be `NULL`; using the matching statement then raises `UBASIC_ERR_NO_CALLBACK` *(patch)*. + +Upstream defines this function in `ubasic.c` but does not declare it in `ubasic.h`. The patch adds the declaration. + +### `ubasic_run` + +```c +void ubasic_run(void); +``` + +Executes **one program line** and returns. Call it repeatedly, for example once per frame, to interleave BASIC execution with the host's main loop. + +Does nothing if the program has already finished or failed. + +### `ubasic_finished` + +```c +int ubasic_finished(void); +``` + +Returns non-zero when the program has ended: an `END` statement ran, the end of the program text was reached, or an error occurred *(patch)*. + +### `ubasic_get_variable` + +```c +VARIABLE_TYPE ubasic_get_variable(int varnum); +``` + +Returns the value of a BASIC variable. `0` is `a`, `1` is `b`, ... `25` is `z`. Returns 0 for an out-of-range index. + +### `ubasic_set_variable` + +```c +void ubasic_set_variable(int varnum, VARIABLE_TYPE value); +``` + +Sets a BASIC variable from C. Out-of-range indexes are ignored. Use it to pass input (joystick state, time, etc.) into the program before calling `ubasic_run`. + +### `ubasic_error` *(patch)* + +```c +int ubasic_error(void); +``` + +Returns the error code of the last failure, or `UBASIC_OK` (0). + +### `ubasic_error_message` *(patch)* + +```c +const char *ubasic_error_message(void); +``` + +Returns a static, human-readable description of the current error code (`"no error"` if none). + +--- + +## Error codes *(patch)* + +Upstream calls `exit(1)` on any error. The patched version stops the program, sets an error code, and makes `ubasic_finished()` return non-zero. + +| Code | Meaning | +|---|---| +| `UBASIC_OK` | No error | +| `UBASIC_ERR_SYNTAX` | Syntax error, unknown statement, unterminated string literal | +| `UBASIC_ERR_DIV_ZERO` | Division or modulo by zero | +| `UBASIC_ERR_STACK` | GOSUB or FOR stack overflow, or `RETURN` without `GOSUB` | +| `UBASIC_ERR_NO_LINE` | `GOTO`/`GOSUB` to a line number that does not exist | +| `UBASIC_ERR_NO_CALLBACK` | `PEEK`/`POKE` used with no callback registered | + +--- + +## Language reference + +### Program format + +```basic +10 let a = 42 +20 print a +30 end +``` + +- Line numbers are required. Lines are normally written in ascending order. +- Keywords are lowercase only. +- Spaces between tokens are optional in most places. + +### Variables + +- 26 variables, named by a single lowercase letter `a`-`z`. +- Integer only. No strings, floats, or arrays. +- Variables must not be named like a keyword prefix, because keywords are matched by prefix. + +### Numbers + +Decimal integer literals of up to 5 digits (0-99999). There is no unary minus; write `0 - x`. + +### Operators + +Listed from highest to lowest precedence. + +| Operators | Meaning | +|---|---| +| `( )` | Grouping | +| `*` `/` `%` | Multiply, divide, modulo | +| `+` `-` `&` `\|` | Add, subtract, bitwise AND, bitwise OR | +| `<` `>` `=` | Comparison (result is 1 or 0). Used in `IF` only | + +`<=`, `>=`, `<>` are not supported. `&` and `|` are bitwise and sit at the same level as `+` and `-`. + +### Statements + +| Statement | Description | +|---|---| +| `LET v = expr` | Assign. The word `LET` is optional | +| `PRINT item [, item] [; item]` | Print to stdout. Items are `"string"`, a variable, a number, or a parenthesized expression. `,` prints a space, `;` prints nothing. A newline is always appended | +| `IF rel THEN stmt [ELSE stmt]` | Conditional. `stmt` is a single statement on the same line | +| `FOR v = a TO b` | Start a loop. The step is always +1 | +| `NEXT v` | End of the loop for `v` | +| `GOTO n` | Jump to line `n` | +| `GOSUB n` | Call the subroutine at line `n` | +| `RETURN` | Return from the subroutine | +| `PEEK addr, v` | `v = peek(addr)`, via the registered `peek_func` | +| `POKE addr, value` | Calls `poke(addr, value)`, via the registered `poke_func` | +| `REM text` | Comment to the end of the line | +| `END` | Stop the program | + +`CALL` is tokenized but not implemented. Using it is a syntax error. + +### Limits + +Compile-time constants in `ubasic.c` and `tokenizer.c`. + +| Constant | Value | Meaning | +|---|---|---| +| `MAX_VARNUM` | 26 | Number of variables | +| `MAX_GOSUB_STACK_DEPTH` | 10 | Nested `GOSUB` depth | +| `MAX_FOR_STACK_DEPTH` | 4 | Nested `FOR` depth | +| `MAX_STRINGLEN` | 40 | Max length of a string literal in `PRINT` | +| `MAX_NUMLEN` | 6 | Max digits in a numeric literal, plus one | + +--- + +## Embedding example: PEEK/POKE as a hardware interface + +```c +#include "ubasic.h" + +static VARIABLE_TYPE memory[256]; + +static VARIABLE_TYPE my_peek(VARIABLE_TYPE addr) +{ + return memory[addr & 0xff]; +} + +static void my_poke(VARIABLE_TYPE addr, VARIABLE_TYPE value) +{ + memory[addr & 0xff] = value; + /* e.g. addr 0..99 -> screen cells, addr 100 -> sound register */ +} + +void run_script(const char *src) +{ + ubasic_init_peek_poke(src, my_peek, my_poke); + while (!ubasic_finished()) { + ubasic_set_variable(0, read_joystick()); /* variable a = input */ + ubasic_run(); + render_frame(memory); + } +} +``` + +--- + +## Notes and limitations + +- **Single instance.** All interpreter state is global. Only one program can run at a time, and the interpreter is not thread-safe or reentrant. +- **Output.** `PRINT` writes directly to stdout with `printf`. Replace `print_statement` in `ubasic.c` to redirect output to your own console. +- **Line index.** The first jump to a line scans the program; later jumps use a heap-allocated linked list (`malloc`). It is freed on `ubasic_init`. +- **Error recovery.** The patch uses `setjmp`/`longjmp` inside `ubasic_run`. After an error the program cannot be resumed; call `ubasic_init` again. +- **No input.** There is no `INPUT` statement. Pass data in with `ubasic_set_variable` or `PEEK`.