This commit is contained in:
Alvin-Zilverstand committed 2026-10-06 23:09:37 +02:00
1 parent 472df35261
commit 96cd1ac97d
21 files changed
+11805 -3954

No files matched your search

+3
View File
@@ -1,2 +1,5 @@
build/
__pycache__/
bob-files.b16
bob-files.b16.tmp
+212
View File
@@ -0,0 +1,212 @@
# Expanding C support
The active goal is to implement all C that can reasonably run on bob16. This
is unfinished. Successful subset tests are not proof of a complete C compiler.
Both the host compiler and shell cc/go workflow must be covered before claiming
the goal complete. Existing programs and the nano-like editor must keep working.
## Work required
- Define and test a consistent target ABI: character/integer widths, signed and
unsigned conversions/promotions, pointer arithmetic, alignment, aggregate
layouts, calling conventions, floating-point and wider integer representations.
- Expand declarations: complete declarators, typedefs, qualifiers, storage
classes, lexical scopes/shadowing, prototypes, function pointers and variadics.
- Expand types: unsigned/signed integer variants, enums, structs/unions, nested
arrays/pointers and supported floating-point types with software operations.
- Expand expressions: sizeof, conditional/comma operators, full lvalue/type
checking, aggregate access, casts, constant expressions and proper conversions.
- Expand statements: switch/case/default, labels/goto and all loop forms with
correct nesting, scope and break/continue behavior.
- Expand initialization: strings, aggregates, nested/designated initializers,
zero initialization, inferred bounds and relocation of address constants.
- Support translation units/linkage and preprocessing/includes/macros, supplying
target headers rather than reusing incompatible host ABI declarations.
- Supply feasible standard library services, including strings/memory, numeric
conversion, formatted console/file I/O, allocation and mathematical helpers.
Specify unavailable external facilities explicitly rather than accepting them
with incorrect behavior.
- Make the shell workflow use the expanded compiler. Current kernel code nearly
fills its reserved region; compiler/storage architecture and resource limits
need revisiting instead of silently accepting unsupported source.
- Add positive, negative and semantic native-execution tests for each feature,
preserving source/output files after failed compilation and program faults.
## Verified additions
The host compiler now implements do/while, including continue to the condition
and break to the loop exit. Local fixed-array initializer lists initialize the
listed elements and zero the remainder; excess elements are rejected.
`host_compiler_and_runtime` executes these features natively and prints bob!.
Conditional ?: selects exactly one branch; comma expressions preserve left-to-
right sequencing while argument and initializer separators remain distinct.
Sizeof handles current scalar/pointer types, declared arrays and string literals
without evaluating its operand; void operands are rejected. It still needs the
full type model (including pointers to arrays, aggregates and qualified types).
Native tests exercise nested conditionals, skipped side effects, comma-based
for-loop steps, argument separators, zero-filled arrays, do-loop control and
unevaluated sizeof increments. Negative tests reject excess initializers, void
sizeof and malformed conditional expressions. These additions are not yet
implemented in the resident compiler; the full goal remains active.
Block locals now activate at their declaration, can shadow outer locals,
parameters and globals, and expire at block exit. For-declaration scope ends
after its loop. Tests reject duplicate locals/parameters, use before declaration
and out-of-scope names. Frame allocation is fixed per function and includes all
block declarations, so jumps do not require runtime stack adjustment.
Function-scoped labels/goto support forward/backward transfers, including
separate functions with the same label name. Missing/duplicate labels fail
before output files are written. Native tests exercise these transfers.
Switch/case/default now emit native dispatch, preserve fall-through and evaluate
the controlling expression once. A separate break-context stack distinguishes
loop/switch breaks from continues to enclosing loops. Nested switch labels are
collected independently. Duplicate cases/defaults and labels outside switches
are rejected; continue without an enclosing loop is rejected.
Integer constant expressions now fold arithmetic, bitwise, shift, comparison,
logical and conditional operators using the current 16-bit model. Zero divisors
and invalid shift counts fail compilation. Native tests cover folded bounds,
initializers/cases and nested dispatch. The regression suite passes 289 checks.
## Resident workflow remains required
The shell cc/go compiler is still the original small native compiler. The host
compiler additions above do not satisfy that part of the goal. The supplied
kernel occupies 36,009 of its available 36,096 words, program files hold 511
words, and the machine has 65,536 word addresses. Supporting substantially larger
native programs and a larger compiler requires revisiting code/data placement,
file storage, loading/relocation and compiler resources. Those changes must
preserve native execution, user sources, existing editor behavior and recovery.
Full types, aggregates, linkage, preprocessing/headers and library services
remain required; the goal is not complete.
## Array/string improvements
The host compiler preserves explicit string lengths through tokenization,
concatenation, constant pooling and emission. Embedded zero characters no
longer truncate literals or cause distinct literals to share incorrect data.
Sizeof uses the complete literal length rather than strlen.
Array bounds can be inferred from initializer lists or character strings.
Character string initialization supports zero-filled padding and the standard
exact-text-size case without a terminator. Undersized arrays, uninitialized
unsized arrays and string initialization of integer arrays are rejected.
Native tests cover global/local inferred arrays, embedded-zero literals,
concatenation, deduplication, padding, exact-size initialization and sizeof.
299 regression checks pass; the kernel rebuilds at the same 36,009 words.
These features remain host-side until the resident compiler architecture and
full type/declarator model are expanded.
## Declaration and relocation improvements
File, block and for declarations now support comma-separated declarators.
Each name starts from the shared base type and applies its own pointer stars,
array bounds and initializer; groups do not introduce an extra block scope.
Tests cover mixed scalar/pointer/array declarations, initialization order,
for-loop scope and same-scope duplicate rejection.
Global scalar pointers can initialize from string literals, addresses of global
objects, array decay/element addresses and constant offsets for current word
element types. Data relocations retain their addend through code compaction.
Native tests verify relocated pointers, embedded-zero string offsets and writes
through global pointers. Reading another global pointer's runtime value is not
accepted as a static address constant. Full declarators, compatible-type checks
and aggregate pointer scaling remain required.
## Function declaration improvements
The host parser retains file-scope prototypes instead of discarding them.
Validation rejects conflicting return kinds, parameter kinds/counts, parameter
initializers and object/function name collisions. Empty old-style declarations
remain unspecified and can precede a typed definition. Unused declarations do
not need a definition; called functions still need native code in this unit.
One-dimensional array parameters (sized or unsized) adjust to pointers, consume
one argument word and report pointer size under sizeof. Tests exercise repeated
compatible declarations, forward calls, array traversal, returning a passed
pointer and negative declaration conflicts. Full pointee, qualifier, promotion
and old-style compatibility checks require the richer type model.
Negative compiler tests also verify that rejected source preserves both prior
BASM and binary output files.
## Derived type foundation
The host compiler now interns pointer and array descriptors carrying element
type, indirection depth and array bound. Pointer declaration/definition checks
distinguish int*, char*, void* and additional indirection. Array parameters
adjust to pointers to their actual element type rather than a generic pointer.
Array objects retain their element type separately from frame/storage size.
Sizeof uses expression type inference for addresses, dereferences, subscripts,
calls, assignments, comma expressions and conditionals. Tests verify *&array
retains the array bound, comma/conditional array operands decay to pointers,
and pointer-array dereferences retain their pointee type without evaluation.
Invalid void dereferences and non-pointer subscripts/dereferences in sizeof
are rejected. Signature tests reject differing pointee kinds and depths.
431 regression checks pass and the kernel still rebuilds at 36,009 words.
This is a foundation rather than a complete type checker. Qualifiers, all
declarator forms, aggregate/wide/floating types, arithmetic conversions,
and constraints on ordinary evaluated expressions still need
implementation. The resident compiler and standard library work also remain.
## Multidimensional arrays and aggregate initialization
The host compiler retains all array dimensions, adjusts array parameters to
pointers to rows, and uses recursive storage sizes for frames, data and sizeof.
Pointer arithmetic, increments, compound addition/subtraction and pointer
differences scale by the pointee size. Array assignment/increment, incompatible
pointer subtraction, pointer-plus-pointer and void pointer arithmetic are rejected.
Initializer parsing recursively flattens nested braces into storage order,
zero-fills omitted subobjects, supports brace elision and infers an omitted outer
bound. Character-array rows accept strings, including braced strings, exact-size
strings without a terminator and padded strings. Global pointer arrays and nested
element addresses retain relocations through code compaction. Scalar braces are
accepted. Struct/union aggregates remain unfinished.
Native tests exercise three-dimensional arrays, row traversal and differences,
local/global nested initialization, partial rows, inferred bounds, strings,
pointer-array relocations and reversed subscripts in static addresses. Rejection
tests cover excess nested elements, excess string initializers, invalid dimensions
and oversized objects. All 503 regression checks pass; kernel compilation remains
36,009 words. These additions are host compiler features: they do not expand the
resident cc/go parser yet. Full C remains an active, incomplete objective.
## Array designated initializers
The host compiler now parses constant array designators, including chained
multidimensional selections. Initialization resumes after the selected subobject;
later entries replace earlier values, omitted elements stay zero and the highest
initialized element determines an omitted outer bound. Recursive initializer
parsing builds a storage-indexed representation before emitting native code.
Pointer designations preserve static relocations and local runtime expressions.
Native tests cover forward/backward selection, continuation, duplicate selection,
partial row replacement, strings, inferred arrays and local/global pointer arrays.
Rejection tests cover negative/out-of-range indices, excess designator depth,
nonconstant indices, scalar designators and missing equals. The 543 regression
checks pass and the kernel rebuild remains 36,009 words. This is still a host
compiler feature; resident parsing, struct member designators and the rest of the
full-C roadmap remain incomplete. Initializer nesting has a 64-level resource
limit, and objects retain their 4096-word storage limit.
## Recursive object and abstract declarators
Object/parameter declarators now collect derived operators outward from the name
and apply them in reverse order to the base type. Parenthesized declarations
therefore distinguish arrays of pointers from pointers to arrays, including
multidimensional rows and arrays of row pointers. Grouped ordinary names and
unnamed row-pointer parameters work through the same parser. Abstract type names
in casts and sizeof also use this model. Sizeof array type names now emits the
full word count instead of assuming every type occupies one word.
Pointers to incomplete arrays are representable without giving the incomplete
type a fictitious size. Sizeof that pointee and arithmetic requiring its size
reject. Arrays of void, incomplete inner arrays, array casts and conflicting
row-pointer declarations reject. Native tests exercise row-pointer globals,
parameters, local traversal, nested pointers, casts and array/pointer sizeof.
All 583 regression checks pass; the kernel rebuild stays at 36,009 words.
The parser limits grouping to 32 levels, derived operators to 64 and dimensions
to 16. Function declarator suffixes still use the earlier direct-function parser;
function pointers and functions returning array pointers remain to implement.
Qualifier semantics, compatible incomplete-type merging, the resident compiler
architecture, remaining C types and the standard library are also incomplete.
+140 -11
View File
@@ -33,24 +33,48 @@ the supplied image directly. The welcome message points to `help` and `go bob.c`
| `delete name` | Permanently remove a RAM file and free its slot |
| `read name` | Print a text file |
| `write name bob!` | Create or replace a one-line text file |
| `edit name` | Open an existing text file or create one in the line editor |
| `edit name` | Open/create text in the full-screen editor (Windows console) |
| `cc bob.c bob` | Compile a C source file inside the emulator |
| `cc bob.c` | Compile to the default program file `app` |
| `go bob.c` | Compile to `app` and run only if compilation succeeds |
| `go bob.c bob` | Compile and run with an explicit output name |
| `save` | Save all files to a host snapshot |
| `restore yes` | Validate/load that snapshot, replacing the RAM files |
| `load name 0x4001 ...` | Store raw bob16 machine words as a program file |
| `run name` | Load a binary program into reserved RAM, execute, return |
| `halt` | Stop the emulator |
Command lines hold up to 127 characters. Longer lines are completely consumed
and rejected so their tail cannot become another command. Input is terminated
and handles CRLF, backspace and EOF. Decimal values are signed 16-bit; hex values
cover all 16-bit bit patterns. Addresses are word addresses.
and handles CRLF, backspace and EOF. Decimal input accepts -32768..65535;
positive values above 32767 represent their 16-bit bit pattern. Hex accepts
0x0000..0xFFFF. Addresses are word addresses; allocation sizes must be positive.
## Shell keys
In a native Windows console, the shell supplies editing and redraw itself:
| Key | Action |
| --- | --- |
| Up / Down | Browse the four most recent nonempty commands; Down restores the draft |
| Left / Right | Move within the command |
| Home / End or Ctrl+A / Ctrl+E | Move to the start/end |
| Backspace / Delete | Remove before/at the cursor |
| Ctrl+U | Clear the line |
| Tab | Complete a unique command or filename; list ambiguous matches |
| Ctrl+D / Ctrl+Z | End input |
Completion operates on the word at the end of the line. Type more characters
when matches are ambiguous. History is session-only, includes failed commands,
and skips consecutive duplicates. `edit` opens its own full-screen view in a
Windows console. Redirected input emits no
redraw or candidate lists. Other terminals use ordinary input; full interactive
key handling currently targets the native Windows console.
The RAM filesystem has eight slots, names up to 23 characters and content up
to 511 words per file. A character occupies one word. `bob.c` occupies one slot
initially. Files and allocations are lost on exit; disk persistence is not
implemented. Allocation is a zeroing bump allocator with no freeing. `poke` is
initially. Unsaved files and allocations are lost on exit. Use `save` to retain
files between sessions. Allocation is a zeroing bump allocator with no freeing. `poke` is
restricted to heap RAM so it cannot corrupt the shell.
Copy and rename refuse to overwrite an existing destination. Choose a new
@@ -64,8 +88,67 @@ leaves an existing output intact and `go` does not run that old program.
Diagnostics report the first detected error's character offset, line and
column (one based); the location can be just after the token that caused it.
## Keep files between sessions
Run from the repository directory, then enter:
```text
write note bob!
go bob.c
save
halt
```
Start the emulator again, enter `kernel.basm` (or use `--os`), and enter
`restore yes`, then `read note` or `run app`. Restore is explicit; startup does
not automatically replace the supplied `bob.c` or other RAM files.
The default snapshot is `bob-files.b16` in the emulator's working directory.
`save` replaces the previous snapshot, first writing `bob-files.b16.tmp` and
then replacing the destination. Keep a copy of the snapshot for older versions.
Set the host environment variable `BOB16_STORAGE` to choose another file path;
the parent directory must already exist. Messages mention this override.
Restoring replaces **all** RAM files; use `save` first if current files matter.
An invalid, truncated, corrupt or unreadable snapshot leaves RAM unchanged.
The snapshot includes text and program files, not heap allocations or history.
Native programs contain kernel helper addresses. If the kernel image differs
from the one used to save, restore keeps text and omits binary programs.
Run `go SOURCE` to compile them again. BASM and binary boots of the same kernel
share the same identity. Guest programs cannot invoke the storage service.
## Edit existing files
In a native Windows console, `edit name` opens a nano-like, non-modal view:
type directly into the file and use the arrow keys to move. The title shows the
filename and `*` when modified; the bottom row lists shortcuts. The view scrolls
vertically and horizontally to keep the cursor visible.
| Key | Effect |
| --- | --- |
| Ctrl+O | Save to the RAM filesystem and continue editing |
| Ctrl+X | Exit; if modified, ask whether to save |
| Y / N at the exit prompt | Save and exit / discard and exit |
| Ctrl+C at the exit prompt | Cancel and continue editing |
| Ctrl+Z | Toggle undo/redo of the last insertion or deletion |
| Arrows | Move through characters and lines |
| Home / End or Ctrl+A / Ctrl+E | Move to the start/end of the current line |
| Backspace / Delete | Delete before/at the cursor |
| Enter | Insert a newline |
| Tab | Insert a space |
For example, enter `edit bob.c`, move to the text you want to change, type,
then press Ctrl+O and Ctrl+X. Enter `go bob.c` at the shell to compile/run it.
There are no insert/command modes or colon commands in this view. A failed
save keeps changes in the editor. The file limit remains 511 characters;
additional input is rejected without truncating existing text. Ctrl+D follows
the same safe exit path as Ctrl+X. Saves are to RAM; use shell `save` for disk.
### Scripted/other-terminal fallback
For redirected input or terminals without native Windows console support,
the original line interface remains available for scripts:
`edit name` loads the current text, displays numbered lines and opens `edit>`.
Typing ordinary text appends a line; existing content is retained. The editor
uses a scratch buffer, so opening a file does not immediately change it.
@@ -89,7 +172,8 @@ then `:wq` changes the existing source rather than recreating it from scratch.
Each edit line has the same 127-character input limit as the shell. Oversize
changes and invalid line numbers are rejected while the editor remains open.
EOF discards unsaved changes. Binary program files cannot be opened as text.
The editor is a line editor, not a full-screen terminal application.
This fallback is a line editor. Interactive Windows sessions use the full-screen
view described above.
## Compile C inside bob16
@@ -169,10 +253,13 @@ what fits in a single command line; use the resident compiler for larger program
| Word addresses | Use |
| --- | --- |
| `0x0000..0x00FF` | Boot ROM and reserved return sentinel |
| `0x0300..0x8FFF` | Kernel code, globals, strings and editor/compiler buffers |
| `0x0100..0x01FF` | Shell and fallback editor input buffers |
| `0x0300..0x8FFF` | Kernel code, globals and strings |
| `0x9000..0xBFFF` | Loaded program, variables and downward program stack |
| `0xC000..0xDFFF` | 8,192-word heap |
| `0xE000..0xEFFF` | Kernel stack, growing down from `0xF000` |
| `0xE000..0xE3FF` | Shared editor/compiler scratch (never used concurrently) |
| `0xE400..0xE5FF` | Four-command shell history |
| `0xE600..0xEFFF` | Kernel stack, growing down from `0xF000` |
| `0xF000..0xFFFF` | Eight file-content buffers; protected from program writes |
There are no interrupts, multitasking or hardware memory protection. The write
@@ -207,9 +294,51 @@ the bob16 code generation. The host compiler supports a broader subset:
signed ints/chars, word pointers and casts, fixed arrays, constant global
initialization, functions and recursion, assignments/compound assignments,
arithmetic/bitwise/shift operators, short-circuit logic, comparisons,
increment/decrement, if, while, for, break, continue and returns.
Shadowing, structs, typedefs, unsigned types, floating point, function pointers,
sizeof, variadics, local array initialization and standard headers are unsupported.
increment/decrement, if, while, do/while, for, break, continue, function-scoped
labels/goto and returns. Blocks permit shadowing; for-loop declarations have
loop scope. Duplicate declarations in the same scope are rejected.
Switch/case/default support fall-through, nesting and break; continue targets
the surrounding loop. Integer constant expressions support arithmetic, bitwise,
comparison, logical and conditional operators in bounds/initializers/case labels.
Invalid constant division and shifts are rejected.
Comma-separated declarations work at file/block scope and in for initializers;
each declarator has its own pointer stars and array bounds. Global pointer
initializers can reference strings, global objects and array elements, with
constant offsets scaled to their pointee size. Nested element addresses and
arrays of pointers use relocations as well.
File-scope function prototypes are retained and checked against definitions for
the current scalar/character/pointer kinds and parameter counts. Array parameters
adjust to pointers to their element or row type; the outer bound may be omitted.
Unused prototypes need no definition. Pointer descriptors distinguish current
pointee kinds and indirection depth in prototype checks. Qualifier compatibility,
complete expression checking and linking external definitions remain incomplete.
Multidimensional arrays support indexing, row pointers, scaled pointer arithmetic,
increments and pointer differences. Objects are limited to 4096 words and 16
dimensions. Global/local initializer lists accept nested braces and brace
elision, with omitted elements zero-filled. Excess initializers are rejected.
Array designators such as `[3] = 7` and `[1][2] = 9` select elements; subsequent
entries continue after the selected subobject. Later initializers replace earlier
values for the same elements. Designators also support pointer arrays and inferred
outer bounds. Indices must be constant and within the array bounds. Initializer
braces are limited to 64 nested levels.
Initialized arrays may omit their outer bound. Character arrays accept string
initializers, with inferred bounds or zero-filled padding. A bound equal to the
text length omits the terminator; character-array rows may initialize from
strings, with or without braces. String literals and concatenation preserve
embedded zero characters, including their contribution to sizeof.
Conditional `?:` and comma expressions preserve branch/sequence behavior.
`sizeof` handles the current word-sized scalar/pointer types, declared arrays
and string literals without evaluating its operand; void operands are rejected.
Structs, typedefs, unsigned types, floating point, function pointers,
Variadics and standard headers are unsupported. `sizeof` tracks array/pointer
expression types, including *&array and array decay in comma/conditional
expressions. Recursive object declarators support grouped names, pointers to
arrays such as `int (*rows)[3]`, and arrays of those pointers. Abstract declarators
in casts and sizeof support these forms too; sizeof array type names uses the
complete storage size. Pointers to incomplete arrays can be declared, but their
pointee has no size for sizeof or arithmetic. Declarators have limits of 32
parenthesis levels and 64 derived types. Function pointer declarators, functions
returning pointers to arrays, and complete C type checking remain unsupported.
Host tools themselves use ordinary host C types.
To compile another standalone guest source from the repository root:
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+9991 -3842
View File
File diff suppressed because it is too large. Load diff
+34 -2
View File
@@ -23,8 +23,31 @@ the next read reports EOF. The host terminal supplies line editing and echo.
The low-level `bob_putc(int)` sends the low eight bits to stdout. `bob_getc()`
returns 0..255 or -1 at EOF. `bob_puts()` adds a newline; use print for prompts.
`bob_key()` (trap 8) reads a key: -1 EOF, byte character, or 256/257 up/down,
258/259 left/right, 260/261 home/end, 262 delete. Windows console input uses
unbuffered keys, converts Enter to newline, and treats Ctrl+D as EOF.
Ctrl+Z is an ordinary control character: shell EOF, full-screen editor undo.
Redirected input uses getchar. `bob_terminal()` (trap 9) returns 1 only when
both input/output are native Windows console handles; otherwise 0. Shell
history, completion and editing are guest code in `kernel/input.c`. ANSI key
sequences in redirected regression fixtures exercise the same guest actions.
`bob_columns()` (trap 10) reports the console buffer width, or 80 as fallback.
The shell scrolls a long input line horizontally to keep redraw within it.
## Strings, memory and allocation
The kernel-only `bob_snapshot(int *descriptor, int operation)` is trap 7.
Operation 0 saves; 1 restores. The four-word descriptor contains pointers to
the 192-word names table, then eight-word length, kind and used tables. File
contents occupy the fixed `0xF000..0xFFFF` region. Descriptors can be on the
kernel stack; tables must be disjoint and below `0x9000`. The host validates
metadata, payload checksum and complete file length before committing a restore.
Returns 0 on success, 1 when restored binaries were omitted because the kernel
changed, -1 for storage errors, -2 for invalid data and -3 for invalid arguments.
Invocation by a supervised program faults and restores the shell. The default
host path is `bob-files.b16`; `BOB16_STORAGE` overrides it. See `C_OS.md` for the
user-facing save/restore workflow.
| Function | Contract |
| --- | --- |
| `int strlen(char *text)` | Count words before the zero terminator |
@@ -50,10 +73,19 @@ are 0..7. These routines are internal kernel APIs; callers must check slots.
Failed size/name validation does not overwrite an existing file. Edits start
with the existing file contents in a scratch buffer and commit on :w, :wq or a
single dot line. :q or EOF discards changes since the most recent save. Oversize
single dot line. :q protects unsaved changes; :q! or EOF discards them. Oversize
changes are rejected without modifying the current buffer.
Resident compilation similarly commits output only after successful parsing and
code generation. Storage is volatile and disappears when bob.exe stops.
code generation. RAM contents disappear when bob.exe stops; save snapshots files for explicit restore in another session.
Interactive `edit` uses native `kernel/nano.c`: direct insertion, cursor motion,
Ctrl+O save, Ctrl+X safe exit with Y/N/Cancel, and Ctrl+Z one-change undo/redo.
The legacy colon-command interface is only a redirected/unsupported-terminal
fallback. Both share `0xE000..0xE1FF` text and `0xE200..0xE3FF` undo scratch.
Resident compilation reuses these regions for code/names/tokens/loop chains;
it must not run concurrently with editing. History uses `0xE400..0xE5FF`, with
kernel stack reserved at `0xE600..0xEFFF`. Input buffers are `0x0100..0x01FF`.
`bob_rows()` (trap 11) reports visible console height, with a 25-row fallback.
## Program execution
+5
View File
@@ -7,4 +7,9 @@ void bob_gets(char *buffer, int capacity);
void bob_halt(void);
int bob_getc(void);
int bob_run(int entry);
int bob_snapshot(int *descriptor, int operation);
int bob_key(void);
int bob_terminal(void);
int bob_columns(void);
int bob_rows(void);
#endif
+6 -5
View File
@@ -28,11 +28,12 @@
char *cc_source;
int cc_token;
int cc_value;
char cc_text[64];
#define cc_text ((char *)0xe380)
int cc_error;
int cc_position;
int cc_code[511];
char cc_names[384];
/* Editor and compiler run separately, so they share reserved scratch RAM. */
#define cc_code ((int *)0xe000)
#define cc_names ((char *)0xe200)
int cc_variables;
int cc_error_offset;
int cc_depth;
@@ -171,8 +172,8 @@ int cc_shift_left(int a, int b) { return a << b; }
int cc_shift_right(int a, int b) { return a >> b; }
int cc_truth(int a) { return !!a; }
int cc_loop_depth;
int cc_break_chain[16];
int cc_continue_chain[16];
#define cc_break_chain ((int *)0xe3c0)
#define cc_continue_chain ((int *)0xe3d0)
int cc_precedence(int op) {
if (op == TOKEN_OR) return 1;
+17 -1
View File
@@ -3,6 +3,20 @@ int file_lengths[8];
int file_kinds[8];
int file_used[8];
void file_snapshot(int operation) {
int descriptor[4]; int result;
descriptor[0] = (int)file_names; descriptor[1] = (int)file_lengths;
descriptor[2] = (int)file_kinds; descriptor[3] = (int)file_used;
result = bob_snapshot(descriptor, operation);
if (result == -1) println("Storage unavailable. Check bob-files.b16 location/permissions (or BOB16_STORAGE).");
else if (result < 0) println("Invalid saved files; RAM files unchanged.");
else if (operation == 0) println("Files saved to bob-files.b16 (or BOB16_STORAGE).");
else {
println("Files restored; previous RAM files replaced.");
if (result == 1) println("Kernel changed: old programs omitted. Compile restored C sources again.");
}
}
char *file_name(int slot) { return file_names + slot * NAME_WORDS; }
/* The upper 4096 words are reserved for file contents, above the kernel stack.
Supervised programs cannot write this region. */
@@ -14,9 +28,10 @@ int file_find(char *name) {
return -1;
}
int file_slot(char *name) {
int slot; int length;
int slot; int length; int i;
length = strlen(name);
if (length == 0 || length >= NAME_WORDS) return -1;
for (i = 0; i < length; i++) if (name[i] < 33 || name[i] > 126) return -1;
slot = file_find(name);
if (slot >= 0) return slot;
for (slot = 0; slot < FILE_COUNT; slot++) {
@@ -52,6 +67,7 @@ void file_list(void) {
}
}
if (!count) println("No files.");
print("Used "); print_dec(count); println("/8 slots; limit 511 words per file. delete frees a slot.");
}
void file_manage(char *operation, char *name, char *destination) {
int slot; int target;
+124
View File
@@ -0,0 +1,124 @@
/* Native shell editing; history is stored before command tokenization. */
#define shell_history ((char *)0xe400)
int history_count;
int input_length;
int input_cursor;
int input_echo;
void input_redraw(void) {
int i; int width; int start; int end;
if (!input_echo) return;
width = bob_columns() - 6; if (width < 1) width = 1;
start = 0; if (input_cursor >= width) start = input_cursor - width + 1;
end = start + width; if (end > input_length) end = input_length;
print("\r\033[2Kbob> ");
for (i = start; i < end; i++) bob_putc(command_line[i]);
for (i = input_cursor; i < end; i++) print("\033[D");
}
int input_key(void) {
int key; int next;
key = bob_key();
if (key != 27) return key;
if (input_echo) return 0;
if (bob_key() != '[') return 0;
next = bob_key();
if (next == 'A') return 256;
if (next == 'B') return 257;
if (next == 'D') return 258;
if (next == 'C') return 259;
if (next == 'H') return 260;
if (next == 'F') return 261;
if (next == '3' && bob_key() == '~') return 262;
return 0;
}
int input_matches(char *candidate, int start, int count) {
int i;
for (i = 0; i < count; i++)
if (!candidate[i] || candidate[i] != command_line[start + i]) return 0;
return 1;
}
void input_complete(void) {
int start; int count; int matches; int i; int length; char *words; char candidate[24]; char selected[24];
start = input_cursor;
while (start && command_line[start - 1] != ' ') start--;
count = input_cursor - start; matches = 0;
if (input_cursor != input_length) return;
if (!start) {
words = "help echo clear mem halt list ls dir read write edit load run cc go copy rename delete alloc peek poke save restore";
while (*words) {
length = 0;
while (*words && *words != ' ') candidate[length++] = *words++;
candidate[length] = 0; if (*words) words++;
if (input_matches(candidate, start, count)) {
matches++; memcpy(selected, candidate, length + 1);
if (input_echo) { if (matches == 1) bob_putc('\n'); print(candidate); print(" "); }
}
}
} else {
for (i = 0; i < FILE_COUNT; i++) {
if (file_used[i] && input_matches(file_name(i), start, count)) {
matches++; memcpy(selected, file_name(i), strlen(file_name(i)) + 1);
if (input_echo) { if (matches == 1) bob_putc('\n'); print(selected); print(" "); }
}
}
}
if (matches == 1) {
length = strlen(selected);
if (start + length < 128) {
memcpy(command_line + start, selected, length + 1);
input_length = start + length; input_cursor = input_length;
}
}
if (input_echo && matches) bob_putc('\n');
input_redraw();
}
int shell_read_line(void) {
int key; int i; int truncated; int browsing; char draft[128];
input_length = 0; input_cursor = 0; truncated = 0; browsing = history_count;
input_echo = bob_terminal(); command_line[0] = 0; draft[0] = 0;
while (1) {
key = input_key();
if (key == 26) key = -1;
if (key == -1 || key == '\n') break;
if (key == '\r' || key == 0) continue;
if (key == 256 || key == 257) {
if (browsing == history_count) memcpy(draft, command_line, input_length + 1);
if (key == 256 && browsing) browsing--;
if (key == 257 && browsing < history_count) browsing++;
if (browsing == history_count) memcpy(command_line, draft, strlen(draft) + 1);
else memcpy(command_line, shell_history + browsing * 128, strlen(shell_history + browsing * 128) + 1);
input_length = strlen(command_line); input_cursor = input_length;
} else if (key == 258) { if (input_cursor) input_cursor--; }
else if (key == 259) { if (input_cursor < input_length) input_cursor++; }
else if (key == 260 || key == 1) input_cursor = 0;
else if (key == 261 || key == 5) input_cursor = input_length;
else if (key == 21) { input_length = 0; input_cursor = 0; command_line[0] = 0; }
else if (key == 9) { input_complete(); continue; }
else if (key == 262 || key == '\b' || key == 127) {
if (key != 262 && input_cursor) input_cursor--;
else if (key != 262) continue;
if (input_cursor < input_length) {
for (i = input_cursor; i < input_length; i++) command_line[i] = command_line[i + 1];
input_length--;
}
} else if (key >= 32 && key <= 255) {
if (input_length == 127) truncated = 1;
else {
for (i = input_length; i >= input_cursor; i--) command_line[i + 1] = command_line[i];
command_line[input_cursor++] = key; input_length++;
}
}
input_redraw();
}
if (input_echo) bob_putc('\n');
if (truncated) return -1;
if (key == -1 && !input_length) return -2;
if (input_length && (history_count == 0 || strcmp(command_line, shell_history + (history_count - 1) * 128))) {
if (history_count == 4) {
for (i = 0; i < 384; i++) shell_history[i] = shell_history[i + 128];
history_count = 3;
}
memcpy(shell_history + history_count * 128, command_line, input_length + 1); history_count++;
}
return input_length;
}
+3 -1
View File
@@ -3,6 +3,8 @@
#include "files.c"
#include "compiler.c"
#include "shell.c"
#include "input.c"
#include "nano.c"
int main(void) {
int length; char *sample;
@@ -13,7 +15,7 @@ int main(void) {
file_write("bob.c", sample, strlen(sample), 0);
while (1) {
print("bob> ");
length = read_line(command_line, 128);
length = shell_read_line();
if (length == -2) { bob_putc('\n'); return 0; }
if (length < 0) println("Command too long.");
else shell_command(command_line);
+95
View File
@@ -0,0 +1,95 @@
/* Full-screen, non-modal editor for an interactive Windows console. */
int nano_cursor;
int nano_width;
void nano_text(char *text) {
int i;
for (i = 0; text[i] && i < nano_width - 1; i++) bob_putc(text[i]);
}
void nano_position(int row, int column) {
print("\033["); print_dec(row); bob_putc(';'); print_dec(column); bob_putc('H');
}
int nano_start(int position) {
while (position && edit_buffer[position - 1] != '\n') position--;
return position;
}
int nano_finish(int position) {
while (position < editor_length && edit_buffer[position] != '\n') position++;
return position;
}
void nano_draw(char *name, char *message) {
int rows; int width; int top; int position; int line; int row; int column; int left; int i;
rows = bob_rows(); width = bob_columns();
nano_width = width;
if (rows < 5) rows = 5;
column = nano_cursor - nano_start(nano_cursor); left = 0;
if (column >= width - 1) left = column - width + 2;
top = nano_start(nano_cursor);
for (i = 0; i < rows - 5 && top; i++) top = nano_start(top - 1);
print("\033[?25l\033[2J\033[H"); print("bob edit: "); print(name);
if (editor_changed(name)) print(" *");
position = top; row = 2; line = 2;
while (row < rows - 1) {
nano_position(row, 1); i = 0;
while (position < editor_length && edit_buffer[position] != '\n') {
if (i >= left && i - left < width - 1) {
if (edit_buffer[position] >= 32) bob_putc(edit_buffer[position]);
else bob_putc(' ');
}
i++; position++;
}
if (nano_cursor >= top && nano_cursor <= position) line = row;
if (position >= editor_length) break;
position++; top = position; row++;
}
nano_position(rows - 1, 1); nano_text(message);
nano_position(rows, 1); nano_text("^O Save ^X Exit ^Z Undo Arrows Move");
nano_position(line, column - left + 1); print("\033[?25h");
}
void nano_edit(char *name) {
int key; int start; int end; int column; int i; int temporary; char text[2]; char *message;
nano_cursor = 0; message = "Ctrl+O saves; Ctrl+X exits.";
while (1) {
nano_draw(name, message); key = input_key(); message = "";
if (key == -1) key = 24;
if (key == 24) {
if (!editor_changed(name)) break;
nano_draw(name, "Save? Y=yes N=discard ^C=cancel");
key = input_key();
if (key == 'n' || key == 'N') break;
if ((key == 'y' || key == 'Y') && editor_save(name)) break;
continue;
}
if (key == 15) {
if (editor_save(name)) message = "Saved to RAM; shell save for disk.";
else message = "Save failed; changes kept.";
} else if (key == 26 && editor_has_undo) {
end = editor_length; if (editor_undo_length > end) end = editor_undo_length;
for (i = 0; i <= end; i++) {
temporary = edit_buffer[i]; edit_buffer[i] = edit_undo[i]; edit_undo[i] = temporary;
}
temporary = editor_length; editor_length = editor_undo_length; editor_undo_length = temporary;
if (nano_cursor > editor_length) nano_cursor = editor_length;
message = "Undo/redo applied.";
} else if (key == 258) { if (nano_cursor) nano_cursor--; }
else if (key == 259) { if (nano_cursor < editor_length) nano_cursor++; }
else if (key == 260 || key == 1) nano_cursor = nano_start(nano_cursor);
else if (key == 261 || key == 5) nano_cursor = nano_finish(nano_cursor);
else if (key == 256 || key == 257) {
start = nano_start(nano_cursor); column = nano_cursor - start;
if (key == 256 && start) start = nano_start(start - 1);
if (key == 257) { end = nano_finish(start); if (end < editor_length) start = end + 1; }
end = nano_finish(start); nano_cursor = start + column;
if (nano_cursor > end) nano_cursor = end;
} else {
start = nano_cursor; end = start; text[0] = 0; text[1] = 0;
if (key == '\b' || key == 127) { if (!start) continue; start--; }
else if (key == 262) { if (end == editor_length) continue; end++; }
else if (key == '\n' || key == 9 || (key >= 32 && key < 256)) {
text[0] = key; if (key == 9) text[0] = ' ';
} else continue;
if (editor_replace(start, end, text, 0)) nano_cursor = start + strlen(text);
else message = "Full: 511 chars. Delete text first.";
}
}
print("\033[2J\033[H");
}
+30 -16
View File
@@ -1,12 +1,12 @@
char command_line[128];
char edit_line[128];
char edit_buffer[512];
char edit_undo[512];
#define command_line ((char *)0x100)
#define edit_line ((char *)0x180)
#define edit_buffer ((char *)0xe000)
#define edit_undo ((char *)0xe200)
int editor_length;
int editor_undo_length;
int editor_has_undo;
char *arguments;
int program_length;
void nano_edit(char *name);
char *next_arg(void) {
char *start;
@@ -33,6 +33,9 @@ int parse_number(char *text) {
if (base == 16) {
if (digits == 4) return 0;
number = number * 16 + digit;
} else if (!negative) {
if (number < 0 || number > 6553 || (number == 6553 && digit > 5)) return 0;
number = number * 10 + digit;
} else {
limit = 7; if (negative) limit = 8;
if (number < -3276 || (number == -3276 && digit > limit)) return 0;
@@ -44,7 +47,7 @@ int parse_number(char *text) {
number_ok = 1;
if (base == 16) { if (negative) return -number; return number; }
if (negative) return number;
return -number;
return number;
}
int editor_line(int line) {
int i; int current;
@@ -119,6 +122,7 @@ void edit_file(char *name) {
memcpy(edit_buffer, file_content(slot), editor_length);
}
edit_buffer[editor_length] = 0;
if (bob_terminal()) { nano_edit(name); return; }
println("Editor: text appends; :p lists; :i N TEXT inserts; :r N TEXT replaces.");
println(":d N deletes; :u undo/redo; :w saves; :q quits; :q! discards; . saves/quits.");
println(":p N shows one line. :q protects unsaved edits; :wq also saves/quits.");
@@ -198,7 +202,6 @@ void run_file(char *name) {
program = (int *)PROGRAM_BASE;
memset(program, 0, PROGRAM_WORDS);
memcpy(program, file_content(slot), file_lengths[slot]);
program_length = file_lengths[slot];
status = bob_run(PROGRAM_BASE);
if (status == -2) println("Program fault; shell restored.");
else if (status == -3) println("Program timed out; shell restored.");
@@ -208,16 +211,19 @@ void memory_status(void) {
print("Heap "); print_hex(HEAP_BASE); print(".."); print_hex(0xdfff);
print("; free "); print_dec(HEAP_WORDS - heap_used); println(" words");
print("Programs "); print_hex(PROGRAM_BASE); print(".."); print_hex(0xbfff); println("");
println("Files: 8 slots, 511 words each; stack above 0xE000.");
println("Files: 8 slots, 511 words each; stack above 0xE600.");
}
void command_help(char *name) {
if (strcmp(name, "edit") == 0) println("edit NAME: open text; ordinary lines append. :p or :p N views; :i N TEXT inserts; :r N TEXT replaces; :d N deletes; :u undo/redo; :w saves; :q quits safely; :q! discards; . saves/quits.");
if (strcmp(name, "save") == 0 || strcmp(name, "restore") == 0) {
println("save: snapshot all files to bob-files.b16 in the working directory (or BOB16_STORAGE). restore yes: replace RAM files with that snapshot. Save current work first. Changed kernels restore text only; recompile programs."); return;
}
if (strcmp(name, "edit") == 0) println("edit NAME: type/arrows; Ctrl+O saves, Ctrl+X exits, Ctrl+Z undo/redo. Unsaved exit asks Y/N. Redirected input uses the line editor; see C_OS.md.");
else if (strcmp(name, "cc") == 0 || strcmp(name, "go") == 0)
println("cc SOURCE [OUTPUT]: compile C; output defaults to app. go SOURCE [OUTPUT] also runs on success. Example: go bob.c. One int main(void); no includes. Use edit SOURCE to fix errors.");
else if (strcmp(name, "write") == 0) println("write NAME TEXT: create/replace a text file. Example: write note bob! Names: 1..23 characters without spaces; 8 file slots, 511 words each. Use edit for multiple lines.");
else if (strcmp(name, "read") == 0) println("read NAME: print text. Example: read bob.c. Use ls to see names; run executes program files.");
else if (strcmp(name, "ls") == 0 || strcmp(name, "dir") == 0 || strcmp(name, "list") == 0)
println("ls / dir / list: show names, lengths and text/program kinds. Files are in RAM and lost on exit.");
println("ls / dir / list: show names, lengths and text/program kinds. Files are in RAM; save keeps them between sessions.");
else if (strcmp(name, "copy") == 0 || strcmp(name, "rename") == 0 || strcmp(name, "delete") == 0)
println("copy OLD NEW | rename OLD NEW | delete NAME. Example: copy bob.c backup.c. Destinations must be new. Copy needs a free slot; rename does not. Delete is permanent.");
else if (strcmp(name, "run") == 0) println("run NAME: execute a compiled/loaded program. Example: cc bob.c bob, then run bob. Exit shows return value; faults/timeouts restore the shell.");
@@ -228,7 +234,7 @@ void command_help(char *name) {
println("alloc WORDS: allocate/zero 1..8192 heap words, print start address; no free. Example: alloc 16. mem shows remaining heap and memory regions.");
else if (strcmp(name, "echo") == 0) println("echo TEXT: print text. Example: echo bob!");
else if (strcmp(name, "clear") == 0) println("clear: clear an ANSI-capable terminal; does not remove files.");
else if (strcmp(name, "halt") == 0) println("halt: stop emulator. RAM files and allocations are lost; read important files before quitting.");
else if (strcmp(name, "halt") == 0) println("halt: stop emulator. Unsaved RAM files and allocations are lost; use save before quitting.");
else if (strcmp(name, "help") == 0) println("help: list commands. help COMMAND: show usage and an example. Try help edit or help go.");
else println("No help for that command. Type help for available names.");
}
@@ -247,6 +253,14 @@ void shell_command(char *line) {
println("cc/go default output: app. Try go bob.c to compile and print bob!");
println("Use hex addresses. poke is limited to heap RAM.");
println("Type help COMMAND for usage/examples. Try help edit or help go.");
println("save | restore yes (replaces RAM files); help save for storage details.");
println("Shell keys: Up/Down history; Tab completion; Ctrl+U clears (Windows console).");
} else if (strcmp(command, "save") == 0) {
if (*next_arg()) println("Usage: save (all RAM files)");
else file_snapshot(0);
} else if (strcmp(command, "restore") == 0) {
if (strcmp(next_arg(), "yes") || *next_arg()) println("restore yes replaces all RAM files. Use save first to keep current work.");
else file_snapshot(1);
} else if (strcmp(command, "echo") == 0) println(remaining_args());
else if (strcmp(command, "clear") == 0) print("\033[2J\033[H");
else if (strcmp(command, "mem") == 0) memory_status();
@@ -265,7 +279,7 @@ void shell_command(char *line) {
else println(file_content(value));
} else if (strcmp(command, "write") == 0) {
name = next_arg(); text = remaining_args();
if (file_write(name, text, strlen(text), 0) < 0) println("Cannot write file.");
if (file_write(name, text, strlen(text), 0) < 0) println("Cannot write file. Names: 1..23 printable characters; 8 slots. Use ls or help write.");
else println("Saved.");
} else if (strcmp(command, "edit") == 0) edit_file(next_arg());
else if (strcmp(command, "load") == 0) { name = next_arg(); load_words(name); }
@@ -278,17 +292,17 @@ void shell_command(char *line) {
if (value && strcmp(command, "go") == 0) run_file(text);
} else if (strcmp(command, "alloc") == 0) {
value = parse_number(next_arg());
if (!number_ok) { println("Invalid allocation size."); return; }
if (!number_ok) { println("Invalid allocation size. Use 1..8192 words; mem shows available space."); return; }
pointer = alloc(value);
if (!pointer) println("Allocation failed.");
if (!pointer) println("Allocation failed. Use a positive size within free space; see mem. No free command.");
else { print_hex((int)pointer); bob_putc('\n'); }
} else if (strcmp(command, "peek") == 0 || strcmp(command, "poke") == 0) {
address = parse_number(next_arg());
if (!number_ok) { println("Invalid address."); return; }
if (!number_ok) { println("Invalid address. Use hex 0x0000..0xFFFF or decimal 0..65535."); return; }
pointer = (int *)address;
if (strcmp(command, "poke") == 0) {
value = parse_number(next_arg());
if (!number_ok) { println("Invalid value."); return; }
if (!number_ok) { println("Invalid value. Use -32768..65535 or 0x0000..0xFFFF."); return; }
if (address >= 0 || address < -16384 || address >= -8192) {
println("poke is limited to 0xC000..0xDFFF."); return;
}
+72
View File
@@ -118,6 +118,7 @@
/* Kernel disk exposed to the guest boot ROM through trap 4. */
static uint16_t bootDisk[0x10000];
static uint16_t bootWords;
static uint16_t bootOrigin;
static bool bootMode;
static bool programMode;
static bool programDone;
@@ -138,6 +139,49 @@ static unsigned readWord(FILE *file) {
}
static void bootImage(const char *path);
#ifdef _WIN32
static DWORD originalInputMode;
static bool rawInputStarted;
static void restoreInputMode(void) {
if(rawInputStarted)SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE),originalInputMode);
}
#endif
static int terminalAvailable(void) {
#ifdef _WIN32
DWORD inputMode,outputMode;
return GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE),&inputMode) &&
GetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE),&outputMode);
#else
return 0;
#endif
}
static int terminalKey(void) {
fflush(stdout);
#ifdef _WIN32
if(terminalAvailable()) {
HANDLE input=GetStdHandle(STD_INPUT_HANDLE);DWORD mode,count;INPUT_RECORD record;
GetConsoleMode(input,&mode);
if(!rawInputStarted){originalInputMode=mode;rawInputStarted=true;atexit(restoreInputMode);}
SetConsoleMode(input,mode&~ENABLE_PROCESSED_INPUT);
int key=0;
while(ReadConsoleInputA(input,&record,1,&count) && count) {
if(record.EventType!=KEY_EVENT || !record.Event.KeyEvent.bKeyDown)continue;
key=(unsigned char)record.Event.KeyEvent.uChar.AsciiChar;
if(!key) switch(record.Event.KeyEvent.wVirtualKeyCode) {
case VK_UP:key=256;break;case VK_DOWN:key=257;break;
case VK_LEFT:key=258;break;case VK_RIGHT:key=259;break;
case VK_HOME:key=260;break;case VK_END:key=261;break;
case VK_DELETE:key=262;break;default:break;
}
if(key)break;
}
if(key==13)return '\n';
if(key==4)return -1;
return key;
}
#endif
return getchar();
}
typedef uint16_t ureg_t;
typedef int16_t reg_t;
@@ -191,6 +235,7 @@ struct ram_t {
ureg_t mar;
reg_t mdr;
} ram;
#include "storage.c"
void cpuCycle(void);
@@ -450,6 +495,26 @@ void execute() {
case 6:
cpu.regFile[0] = (int16_t)runProgram((uint16_t)cpu.regFile[0]);
break;
case 7:
if(programMode)machineFault();
cpu.regFile[0]=(int16_t)snapshotService((uint16_t)cpu.regFile[0],cpu.regFile[1]);
break;
case 8:
cpu.regFile[0]=(int16_t)terminalKey();
break;
case 9:
cpu.regFile[0]=(int16_t)terminalAvailable();
break;
case 10:
case 11:
cpu.regFile[0]=((cpu.ir>>8)&15)==10?80:25;
#ifdef _WIN32
{
CONSOLE_SCREEN_BUFFER_INFO info;
if(GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),&info))cpu.regFile[0]=((cpu.ir>>8)&15)==10?info.dwSize.X:info.srWindow.Bottom-info.srWindow.Top+1;
}
#endif
break;
default:
machineFault();
}
@@ -1053,6 +1118,7 @@ static void bootImage(const char *path) {
}
fclose(file);
bootWords = (uint16_t)words;
bootOrigin = (uint16_t)origin;
bootMode = true;
memset(&cpu, 0, sizeof(cpu));
memset(&ram, 0, sizeof(ram));
@@ -1085,6 +1151,12 @@ int main(int argc, char** argv) {
}
}
uint16_t identityWords[0x8d00];
for(unsigned i=0;i<0x8d00;i++) {
unsigned address=0x300+i;
identityWords[i]=bootMode?(address>=bootOrigin && address<bootOrigin+bootWords?bootDisk[address-bootOrigin]:0):(uint16_t)ram.memory[address];
}
kernelIdentity=snapshotHash(identityWords,0x8d00);
unsigned long cycles = 0;
while (true) {
if (maxCycles && cycles++ >= maxCycles) { fprintf(stderr, "CPU cycle limit reached\n"); return 2; }
+80
View File
@@ -0,0 +1,80 @@
/* Included by main.c after ram is defined. Durable file device; guest owns shell. */
enum { SNAP_WORDS = 4312 };
static uint32_t kernelIdentity;
static uint32_t snapshotHash(const uint16_t *words, unsigned count) {
uint32_t hash=2166136261u;
for(unsigned i=0;i<count;i++) {
hash=(hash^(words[i]&255))*16777619u;
hash=(hash^(words[i]>>8))*16777619u;
}
return hash;
}
static int snapshotValid(const uint16_t *words) {
for(unsigned i=0;i<8;i++) {
unsigned length=words[192+i],kind=words[200+i],used=words[208+i];
if(used>1 || kind>1 || length>511)return 0;
if(!used)continue;
const uint16_t *name=words+i*24;unsigned n=0;
while(n<24 && name[n]) {if(name[n]<33 || name[n]>126)return 0;n++;}
if(!n || n==24 || words[216+i*512+length])return 0;
if(!kind)for(unsigned k=0;k<length;k++)if(!words[216+i*512+k] || words[216+i*512+k]>255)return 0;
for(unsigned j=0;j<i;j++)if(words[208+j]) {
unsigned k=0;while(k<24 && name[k]==words[j*24+k] && name[k])k++;
if(k<24 && name[k]==words[j*24+k])return 0;
}
}
return 1;
}
static int snapshotService(unsigned descriptor, int operation) {
if(programMode || descriptor<0x300 || descriptor+4>0xf000)return -3;
unsigned addresses[4],sizes[4]={192,8,8,8};
for(unsigned i=0;i<4;i++) {
addresses[i]=(uint16_t)ram.memory[descriptor+i];
if(addresses[i]<0x300 || addresses[i]+sizes[i]>0x9000)return -3;
for(unsigned j=0;j<i;j++)if(addresses[i]<addresses[j]+sizes[j] && addresses[j]<addresses[i]+sizes[i])return -3;
}
const char *path=getenv("BOB16_STORAGE");if(!path || !*path)path="bob-files.b16";
uint16_t words[SNAP_WORDS];unsigned position=0;
if(operation==0) {
for(unsigned i=0;i<4;i++)for(unsigned j=0;j<sizes[i];j++)words[position++]=(uint16_t)ram.memory[addresses[i]+j];
for(unsigned i=0;i<4096;i++)words[position++]=(uint16_t)ram.memory[0xf000+i];
if(!snapshotValid(words))return -2;
size_t size=strlen(path)+5;char *temporary=malloc(size);if(!temporary)return -1;
snprintf(temporary,size,"%s.tmp",path);
FILE *file=fopen(temporary,"wb");if(!file){free(temporary);return -1;}
uint32_t hash=snapshotHash(words,SNAP_WORDS);
unsigned char header[16]={'B','1','6','S',1,0,0,0};
for(unsigned i=0;i<4;i++){header[8+i]=(unsigned char)(kernelIdentity>>(8*i));header[12+i]=(unsigned char)(hash>>(8*i));}
int okay=fwrite(header,1,16,file)==16;
for(unsigned i=0;i<SNAP_WORDS;i++)if(fputc(words[i]&255,file)==EOF || fputc(words[i]>>8,file)==EOF)okay=0;
if(fclose(file))okay=0;
if(okay) {
#ifdef _WIN32
okay=MoveFileExA(temporary,path,MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH)!=0;
#else
okay=rename(temporary,path)==0;
#endif
}
if(!okay)remove(temporary);
free(temporary);return okay?0:-1;
}
if(operation!=1)return -3;
FILE *file=fopen(path,"rb");if(!file)return -1;
unsigned char header[16];int valid=fread(header,1,16,file)==16;
for(unsigned i=0;i<SNAP_WORDS;i++) {
int lo=fgetc(file),hi=fgetc(file);if(lo==EOF || hi==EOF){valid=0;break;}
words[i]=(uint16_t)(lo|(hi<<8));
}
if(fgetc(file)!=EOF)valid=0;
fclose(file);
if(!valid || memcmp(header,"B16S\1\0\0\0",8))return -2;
uint32_t identity=0,hash=0;
for(unsigned i=0;i<4;i++){identity|=(uint32_t)header[8+i]<<(8*i);hash|=(uint32_t)header[12+i]<<(8*i);}
if(hash!=snapshotHash(words,SNAP_WORDS) || !snapshotValid(words))return -2;
int changed=identity!=kernelIdentity;
if(changed)for(unsigned i=0;i<8;i++)if(words[200+i])words[208+i]=0;
position=0;
for(unsigned i=0;i<4;i++)for(unsigned j=0;j<sizes[i];j++)ram.memory[addresses[i]+j]=(int16_t)words[position++];
for(unsigned i=0;i<4096;i++)ram.memory[0xf000+i]=(int16_t)words[position++];
return changed?1:0;
}
+60 -1
View File
@@ -24,6 +24,10 @@ captured for assertions; no guest examples print hello world.
| File copy/rename/delete | `kernel/files.c` | `file_management` checks text and native programs, destination collision protection, full storage, slot reuse, names and malformed arguments |
| Compile and run workflow | `kernel/compiler.c`, `kernel/shell.c` | `compile_workflow` checks default/explicit outputs, source preservation, line diagnostics and no stale execution on errors |
| Startup/help/editor usability | `main.c`, `kernel/kernel.c`, `kernel/shell.c` | `usability` boots via --os, runs bob.c, exercises per-command help, unsaved quit protection, explicit discard, line navigation and undo/redo |
| Persistent files | `storage.c`, trap 7, `kernel/files.c` | `persistence` checks explicit replacement, restart with text/programs, BASM/binary identity, checksum/metadata/truncation rejection with RAM preservation, changed-kernel text recovery, unavailable storage and program denial |
| Shell editing/history/completion | `kernel/input.c`, traps 8/9 | `shell_editing` feeds key sequences for history limits/drafts, cursor edits, deletion, unique/ambiguous completion and overlong input recovery; redirected output has no redraw |
| Native Windows console | `tests/test_console.c` | 16 checks use a hidden, test-owned console and real Windows key events to verify redraw, cursor edits, recall, completion, narrow width, maximum input and recovery after truncation |
| Number/storage feedback | `kernel/shell.c`, `kernel/files.c` | `shell_editing` checks unsigned decimal addresses/values, overflow rejection, invalid sizes and used-slot totals |
`basm_route` additionally starts the supplied emulator at its ordinary filename
prompt, passes `kernel.basm`, compiles/runs bob.c and checks return to the shell.
@@ -32,4 +36,59 @@ binary images and verifies rejection before boot.
These checks establish this starter's functionality, not conformance to all of C
or isolation between processes. The resident compiler is a documented subset;
RAM storage is volatile, allocation has no free, and multitasking is absent.
Files are volatile until save, allocation has no free, and multitasking is absent.
## UX goal completion audit
Final delivery was rebuilt with `build.exe --test`: 231 regression assertions
and 28 real Windows console assertions pass on the delivered `bob.exe`.
The generated kernel is 36,009 words at `0x0300`, ending below `0x9000`.
| Goal requirement | Verified evidence |
| --- | --- |
| 1. Simple startup/welcome | `usability` boots --os; `basm_route` boots kernel.basm through the original prompt; welcome offers help/go |
| 2. History/editing/completion/prompts | `shell_editing` and `test_console.c` verify four-entry recall, drafts, insertion/deletion, cursor movement, unique/ambiguous completion, redirected input, narrow redraw and input limits |
| 3. Discoverable help/errors/examples | Help lists commands and keys; command_help covers every shell command; `usability` exercises help and unknown names; tests cover recovery advice |
| 4. Editor navigation/undo/save/discard/loss protection | `editor_and_aliases` and `usability` verify numbered lines, :p N, changes, undo/redo, save, safe :q, explicit :q! and rejected invalid edits; documented EOF behavior |
| 5. Files/details/limits | `file_management` verifies copy/rename/delete for text/programs, collision rejection, full-table rename, slot reuse; ls/dir show kinds/lengths/used slots |
| 6. C workflow/diagnostics/examples | `compile_workflow` verifies defaults, go, source preservation, first-error line/column and no stale execution; supplied bob.c prints bob! |
| 7. Number/address feedback/protection | Signed/raw decimal and hex limits, overflow, protected poke and allocation feedback checked in console/allocator/shell_editing cases |
| 8. Persistent save/load | `persistence` verifies save/restore across sessions, storage location override, RAM preservation on failure, binary compatibility and text recovery after kernel change |
| 9. EOF/malformed/oversized/fault recovery | Input, editor, compiler, boot-image and program-recovery tests verify bounds/EOF/faults/timeouts while retaining the shell or unrelated files as applicable |
| 10. Docs/tutorial | C_OS.md supplies startup, keys, command/editor references, go bob.c and restart/save tutorial; API and this audit describe contracts/limits |
| 11. Native verification/delivery/cleanup | Build regenerates bob.exe, C tools, kernel.basm/B16K; complete C suites pass; temporary staged binaries, fixtures and logs removed after verification |
Interactive shell keys target native Windows console handles. Completion
operates at the line end and undo retains one edit. Full C is not claimed.
## Nano-like editor update
Interactive `edit` now runs `kernel/nano.c`, with direct typing, two-dimensional
cursor movement, scrolling, visible shortcuts, Ctrl+O save, Ctrl+X safe exit,
Y/N/Cancel and Ctrl+Z undo/redo. Redirected tests retain the line fallback.
The extended native console suite checks multiline insertion/navigation,
save/exit, confirmation, cancellation, discard, undo/redo, 511-character limits
and full-slot save failure without losing edits. Shared scratch/history were
relocated into reserved RAM; all compiler and fallback regression cases still
run against the resulting kernel.
## Host C compiler expansion
The current OS/compiler regression suite passes 503 checks. New native programs
cover multidimensional storage and sizeof, row pointer scaling, nested/partial
initializers, character-array rows and static nested address/pointer-array
relocations. Negative cases verify malformed or excessive initialization is
rejected while preserving earlier output files. These checks cover the host
compiler additions; the resident compiler retains its documented smaller subset.
The generated kernel remains 36,009 words.
Array-designator additions bring the regression suite to 543 checks. Tests execute
native bob16 programs using selected scalar/row/pointer elements, inferred bounds,
continuation and replacement. Malformed and out-of-bounds designators must reject
without replacing previously generated BASM or binary files.
Recursive object/abstract declarators bring the suite to 583 checks. Native tests
exercise pointer-to-array parameters/globals/locals, arrays of row pointers,
grouped names, casts and sizeof array type names. Rejections verify incomplete
pointee sizing/arithmetic, arrays of void, invalid casts and incompatible row
pointer declarations. Kernel compilation still produces 36,009 words.
+116
View File
@@ -0,0 +1,116 @@
/* Native Windows console integration, using a hidden test-owned console. */
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef BOB_VERIFY
#define BOB "build\\bob-next.exe --os"
#else
#define BOB "bob.exe --os"
#endif
static HANDLE input,output,child;
static int checks;
static void fail(const char *message) {
if(child)TerminateProcess(child,1);
FreeConsole();fprintf(stderr,"Console check failed: %s (%lu)\n",message,GetLastError());exit(1);
}
static void check(int condition,const char *message) {checks++;if(!condition)fail(message);}
static char screen[65536];
static void capture(void) {
CONSOLE_SCREEN_BUFFER_INFO info;DWORD read;
if(!GetConsoleScreenBufferInfo(output,&info))fail("screen info");
unsigned size=(unsigned)info.dwSize.X*info.dwSize.Y;
if(size>=sizeof(screen))size=sizeof(screen)-1;
COORD start={0,0};
if(!ReadConsoleOutputCharacterA(output,screen,size,start,&read))fail("screen capture");
unsigned out=0,width=(unsigned)info.dwSize.X;
for(unsigned i=0;i<read;i+=width) {
unsigned end=i+width;if(end>read)end=read;
while(end>i && screen[end-1]==' ')end--;
memmove(screen+out,screen+i,end-i);out+=end-i;screen[out++]='\n';
}
screen[out]=0;
}
static int lines(const char *text) {
capture();int count=0;size_t length=strlen(text);
for(char *p=screen;*p;) {
char *end=strchr(p,'\n');if(!end)break;
if((size_t)(end-p)==length && !memcmp(p,text,length))count++;
p=end+1;
}
return count;
}
static void wait_text(const char *text) {
for(int i=0;i<200;i++){capture();if(strstr(screen,text))return;Sleep(10);}
FILE *file=fopen("build/console-screen.txt","wb");if(file){fputs(screen,file);fclose(file);}
fail(text);
}
static void wait_lines(const char *text,int count) {
for(int i=0;i<200;i++){if(lines(text)>=count){checks++;return;}Sleep(10);}
fail("expected output line");
}
static void key(WORD vk,char character) {
INPUT_RECORD records[2]={0};DWORD written;
records[0].EventType=KEY_EVENT;records[0].Event.KeyEvent.bKeyDown=TRUE;
records[0].Event.KeyEvent.wRepeatCount=1;records[0].Event.KeyEvent.wVirtualKeyCode=vk;
records[0].Event.KeyEvent.wVirtualScanCode=(WORD)MapVirtualKeyA(vk,MAPVK_VK_TO_VSC);
records[0].Event.KeyEvent.uChar.AsciiChar=character;
records[1]=records[0];records[1].Event.KeyEvent.bKeyDown=FALSE;
if(!WriteConsoleInputA(input,records,2,&written) || written!=2)fail("key injection");
}
static void type(const char *text) {
for(;*text;text++) {
WORD vk=*text=='\n'?VK_RETURN:*text=='\t'?VK_TAB:(WORD)(VkKeyScanA(*text)&255);
key(vk,*text=='\n'?'\r':*text);
}
}
int main(void) {
HANDLE oldIn=GetStdHandle(STD_INPUT_HANDLE),oldOut=GetStdHandle(STD_OUTPUT_HANDLE),oldErr=GetStdHandle(STD_ERROR_HANDLE);
STARTUPINFOA startup={0};PROCESS_INFORMATION process={0};startup.cb=sizeof(startup);
startup.dwFlags=STARTF_USESHOWWINDOW;startup.wShowWindow=SW_HIDE;
char command[]=BOB;
check(CreateProcessA(NULL,command,NULL,NULL,FALSE,CREATE_NEW_CONSOLE,NULL,NULL,&startup,&process),"create hidden console emulator");
child=process.hProcess;CloseHandle(process.hThread);FreeConsole();
int attached=0;for(int i=0;i<200 && !attached;i++){attached=AttachConsole(process.dwProcessId);if(!attached)Sleep(10);}
check(attached,"attach test-owned console");
input=CreateFileA("CONIN$",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);
output=CreateFileA("CONOUT$",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);
check(input!=INVALID_HANDLE_VALUE && output!=INVALID_HANDLE_VALUE,"console handles");
wait_text("bob>");int count=lines("bob!");
type("echo bb!");key(VK_LEFT,0);key(VK_LEFT,0);type("o\n");wait_lines("bob!",++count);
key(VK_UP,0);type("\n");wait_lines("bob!",++count);
type("rea\t bo\t\n");wait_text("int main(void)");checks++;
type("g\t bo\t\n");wait_text("Compiled ");wait_lines("bob!",++count);wait_text("Exit 0");checks++;
type("xxecho bob!");key(VK_HOME,0);key(VK_DELETE,0);key(VK_DELETE,0);key(VK_END,0);type("\n");wait_lines("bob!",++count);
type("wrong");key('U',21);type("echo bob!\n");wait_lines("bob!",++count);
SMALL_RECT window={0,0,39,19};COORD dimensions={40,200};
check(SetConsoleWindowInfo(output,TRUE,&window) && SetConsoleScreenBufferSize(output,dimensions),"narrow console");
type("echo bob!");for(int i=0;i<118;i++)type(" ");type("\n");wait_lines("bob!",++count);
for(int i=0;i<128;i++){type("x");}
type("\n");wait_text("Command too long.");checks++;
type("echo bob!\n");wait_lines("bob!",++count);
type("edit note\n");wait_text("bob edit: note");wait_text("^O Save");checks++;
type("bb!");key(VK_LEFT,0);key(VK_LEFT,0);type("o");key(VK_END,0);type("\nbob!");
key('O',15);wait_text("Saved to RAM");checks++;
key('X',24);type("read note\n");wait_lines("bob!",2);
type("edit note\n");wait_text("bob edit: note");type("x");key('X',24);wait_text("Save? Y=yes");checks++;
key('C',3);wait_text("bob edit: note *");key('Z',26);wait_text("Undo/redo applied.");checks++;
key('Z',26);key('X',24);type("nread note\n");wait_lines("bob!",2);
type("edit note\n");wait_text("bob edit: note");key(VK_DOWN,0);key(VK_HOME,0);key(VK_DELETE,0);type("b");key('X',24);
type("echo bob!\n");wait_lines("bob!",1);
type("edit fresh\n");wait_text("bob edit: fresh");type("bob!");key('X',24);wait_text("Save? Y=yes");
type("yread fresh\n");wait_lines("bob!",1);
type("edit limit\n");wait_text("bob edit: limit");
for(int i=0;i<512;i++){type("b");}
wait_text("Full: 511 chars.");checks++;
key('O',15);wait_text("Saved to RAM");key('X',24);type("ls\n");wait_text("limit 511 chars (text)");checks++;
type("write a bob!\nwrite b bob!\nwrite c bob!\nedit extra\n");wait_text("bob edit: extra");
type("bob!");key('O',15);wait_text("Save failed; changes kept.");checks++;
key('X',24);wait_text("Save? Y=yes");type("y");wait_text("bob edit: extra *");
key('X',24);type("nls\n");wait_text("Used 8/8 slots");checks++;
type("halt\n");check(WaitForSingleObject(child,5000)==WAIT_OBJECT_0,"console halt");
DWORD exitCode;check(GetExitCodeProcess(child,&exitCode) && exitCode==0,"console exit status");
CloseHandle(input);CloseHandle(output);CloseHandle(child);child=NULL;FreeConsole();
SetStdHandle(STD_INPUT_HANDLE,oldIn);SetStdHandle(STD_OUTPUT_HANDLE,oldOut);SetStdHandle(STD_ERROR_HANDLE,oldErr);
printf("bob!\n%d native console checks passed.\n",checks);return 0;
}
+287 -2
View File
@@ -64,7 +64,7 @@ static void allocator_and_files(void) {
contains(output,"Saved.");contains(output,"bob!\n\n");contains(output,"note 5 chars (text)");free(output);
output=shell("poke 0xc000 33\nalloc 4\npeek 0xc000\nalloc 4\nmem\nhalt\n");
contains(output,"0xC000: 0x0000 (0)");contains(output,"bob> 0xC004\n");contains(output,"free 8184 words");free(output);
output=shell("write abcdefghijklmnopqrstuvwx bob!\nalloc 32768\npoke 0xdfff 0xffff\npeek 0xdfff\nhalt\n");
output=shell("write abcdefghijklmnopqrstuvwx bob!\nalloc 65536\npoke 0xdfff 0xffff\npeek 0xdfff\nhalt\n");
contains(output,"Cannot write file.");contains(output,"Invalid allocation size.");contains(output,"0xDFFF: 0xFFFF (-1)");free(output);
char large[800];strcpy(large,"write note bob!\nedit note\n");
size_t n=strlen(large);
@@ -135,6 +135,139 @@ static void program_loading_and_recovery(void) {
contains(output,"Program fault; shell restored.");contains(output,"bob> bob!\n");free(output);
}
static void host_compiler_and_runtime(void) {
guest("#include \"bob.h\"\nint matrix[2][3]={{1,2,3},{4,5,6}}; "
"int (*rows)[3]=matrix;int (*whole)[2][3]=&matrix;int (*incomplete)[]=(int (*)[])matrix; "
"int (*selected[2])[3]={&matrix[1],matrix}; "
"int sum(int (*p)[3]);int sum(int p[][3]){return (*p)[0]+p[1][2];} "
"int main(void){int (scalar)=7;int (*local)[3]=rows;int * (pointers[2])={&scalar,&matrix[1][1]}; "
"if(sizeof(int[2][3])!=6 || sizeof(int (*)[3])!=1 || sizeof(int *[2])!=2 || sizeof(incomplete)!=1)return 1; "
"if(sizeof(*whole)!=6 || sizeof(*rows)!=3 || (*whole)[1][2]!=6)return 2; "
"if(sum(local)!=7 || (*selected[0])[1]!=5 || *pointers[0]!=7 || *pointers[1]!=5)return 3; "
"local++;if((*local)[0]!=4 || local-rows!=1)return 4; "
"if(((int (*)[3])matrix)[1][1]!=5)return 5;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint values[3]={1,2,3}; "
"int *selected[][2]={[1][1]=&values[2],[0]={values,&values[1]},[1][1]=values}; "
"char *messages[]={[2]=\"bob!\",[0]=\"other\"}; "
"int main(void){int *local[3]={[2]=&values[1],[0]=values}; "
"if(sizeof(selected)!=4 || selected[1][0]!=0 || *selected[1][1]!=1 || *selected[0][1]!=2)return 1; "
"if(local[1]!=0 || *local[2]!=2 || messages[1]!=0)return 2;bob_puts(messages[2]);return 0;}");
guest("#include \"bob.h\"\nint sparse[]={[5]=6,[1]=2,3,[5]=7}; "
"int matrix[][3]={[2][1]=8,9,[0]={1,2},[1][2]=6}; "
"char words[3][5]={[2]=\"bob!\",[0]={\"bob!\"}}; "
"int main(void){int local[5]={[3]=4,[1]=2,3,[3]=8}; "
"int rows[2][3]={[1]={4,5,6},[1][1]=9,[0][2]=3}; "
"if(sizeof(sparse)!=6 || sparse[0]!=0 || sparse[1]!=2 || sparse[2]!=3 || sparse[5]!=7)return 1; "
"if(sizeof(matrix)!=9 || matrix[0][2]!=0 || matrix[1][2]!=6 || matrix[2][2]!=9)return 2; "
"if(local[0]!=0 || local[2]!=3 || local[3]!=8 || local[4]!=0)return 3; "
"if(rows[0][2]!=3 || rows[1][0]!=4 || rows[1][1]!=9 || rows[1][2]!=6)return 4; "
"if(words[1][0]!=0 || words[0][3]!='!')return 5;bob_puts(words[2]);return 0;}");
guest("#include \"bob.h\"\nint numbers[2][2]={{1,2},{3,4}}; "
"int *pointers[][2]={{&numbers[0][0],numbers[1]},{&numbers[1][1]}}; "
"char *messages[]={\"bob!\",\"no\"}; "
"int main(void){if(*pointers[0][0]!=1 || pointers[0][1][1]!=4 || *pointers[1][0]!=4 || pointers[1][1]!=0)return 1; "
"bob_puts(messages[0]);return 0;}");
guest("#include \"bob.h\"\nint cube[2][2][3]={{{1,2,3},{4,5,6}},{{7,8,9},{10,11,12}}}; "
"int *nested=&cube[1][1][2],*row=cube[1][0],*reversed=&2[1[cube][1]]; "
"int *indirect=&*(&cube[0][1][1]),*offset=cube[1][1]+1; "
"int main(void){if(*nested!=12 || row[2]!=9 || *reversed!=12 || *indirect!=5 || *offset!=11)return 1; "
"*nested=42;if(cube[1][1][2]!=42)return 2;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint matrix[][3]={{1},{2,3},{4,5,6}}; "
"int cube[2][2][2]={{{1},{2,3}},{{4,5},{6}}}; "
"char words[][5]={\"bob!\",{\"bob!\"}};char exact[4]={\"bob!\"}; "
"int main(void){int local[][2]={{7},{8,9}};int mixed[2][2]={1,2,{3}}; "
"int scalar={42};char inferred[]={\"bob!\"}; "
"if(sizeof(matrix)!=9 || matrix[0][1]!=0 || matrix[1][1]!=3 || matrix[2][2]!=6)return 1; "
"if(cube[0][0][1]!=0 || cube[0][1][1]!=3 || cube[1][1][1]!=0)return 2; "
"if(local[0][1]!=0 || local[1][1]!=9 || mixed[1][1]!=0 || scalar!=42)return 3; "
"if(sizeof(words)!=10 || words[0][4]!=0 || words[1][3]!='!' || exact[3]!='!')return 4; "
"if(sizeof(inferred)!=5)return 5;bob_puts(inferred);return 0;}");
guest("#include \"bob.h\"\nint matrix[2][3]={1,2,3,4,5,6};int inferred[][2]={7,8,9}; "
"int sum(int rows[][3]);int sum(int rows[9][3]){int s=0; "
"if(sizeof(rows)!=1 || sizeof(*rows)!=3)return 100; "
"for(int i=0;i<2;i++)for(int j=0;j<3;j++)s+=rows[i][j];return s;} "
"int walk(int rows[][3]){int *first=*rows++;if(first[2]!=3 || (*rows)[0]!=4)return 100; "
"rows-=1;rows+=1;return (*--rows)[1];} "
"int main(void){int local[2][2];local[1][1]=8; "
"if(sizeof(matrix)!=6 || sizeof(matrix[0])!=3 || sizeof(inferred)!=4 || inferred[1][1]!=0)return 1; "
"if(sum(matrix)!=21 || walk(matrix)!=2 || local[1][1]!=8)return 2; "
"if((&matrix[1]-&matrix[0])!=1 || (&matrix[0]-&matrix[1])!=-1)return 3; "
"if(((&matrix+1)-&matrix)!=1 || *(*(matrix+1)+2)!=6)return 4; "
"bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint main(void){int a[4];int *p[2];int x=0; "
"if(sizeof(*&a)!=4 || sizeof((*&a)[2])!=1 || sizeof(1[a])!=1)return 1; "
"if(sizeof(p)!=2 || sizeof(*p)!=1 || sizeof(**p)!=1)return 2; "
"if(sizeof((x++,a))!=1 || sizeof(1?a:a)!=1 || x!=0)return 3; "
"bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint read(int **);char *same(char *);int *object(int *); "
"int read(int **p){return **p;}char *same(char a[]){return a;} "
"int *object(int *a){return a;} "
"int x=7;int *p=&x;int **q=&p; "
"int main(void){char word[]=\"bob!\"; "
"if(read(q)!=7 || *object(p)!=7 || sizeof(int**)!=1)return 1; "
"bob_puts(same(word));return 0;}");
guest("#include \"bob.h\"\nint sum(int [],int); int sum(int *values,int count); "
"int old();int unused(int);char *text(char []); "
"int main(void){int a[]={2,3,4};char word[]=\"bob!\"; "
"if(sum(a,3)!=9 || old(7)!=7)return 1;bob_puts(text(word));return 0;} "
"int sum(int values[10],int count){int result=0; "
"if(sizeof(values)!=1)return 100;for(int i=0;i<count;i++)result+=values[i];return result;} "
"int old(int x){return x;}char *text(char word[]){return word;}");
guest("#include \"bob.h\"\nint x=7;int *p=&x;int data[]={3,4,5}; "
"int *middle=&data[1],*last=data+2,*also=1+data;char *message=\"bob!\"; "
"char *part=\"a\\0x\"+2; "
"int main(void){if(*p!=7 || *middle!=4 || *last!=5 || *also!=4 || *part!='x')return 1; "
"*p=9;if(x!=9)return 2;bob_puts(message);return 0;}");
guest("#include \"bob.h\"\nint global=5, other=6, *pointer; char word[]=\"bob!\", pad[7]=\"bob!\"; "
"int main(void){int x=2,*p=&x,y=x+3,a[]={7,8};char text[]=\"bob!\",*s=text; "
"int total=0;pointer=&global;*pointer=9; "
"for(int i=0,j=3;i<3;i++,j--){total+=i+j;} "
"{int x=4,y=x+1; if(y!=5)return 1;} "
"if(x!=2 || *p!=2 || y!=5 || a[1]!=8 || total!=9 || global!=9 || other!=6)return 2; "
"if(s[3]!='!' || pad[6]!=0)return 3;bob_puts(word);return 0;}");
guest("#include \"bob.h\"\nchar global[]=\"bob!\"; int values[]={3,4,5}; "
"int main(void){char text[]=\"bo\\0b!\" \"x\";char padded[8]=\"bob!\"; "
"char exact[4]=\"bob!\";char *a=\"a\\0x\";char *b=\"a\\0y\"; "
"int local[]={8,9}; "
"if(sizeof(global)!=5 || sizeof(values)!=3 || values[2]!=5)return 1; "
"if(sizeof(text)!=7 || text[2]!=0 || text[3]!='b' || text[5]!='x' || text[6]!=0)return 2; "
"if(sizeof(\"a\\0x\" \"b\")!=5 || a[2]!='x' || b[2]!='y')return 3; "
"if(sizeof(exact)!=4 || exact[3]!='!' || padded[7]!=0 || local[1]!=9)return 4; "
"bob_puts(global);return 0;}");
guest("#include \"bob.h\"\nint table[2+2]={1+2,8/2,1<<3}; "
"int main(void){int x=0;int sum=0;switch(++x){default:sum=99;break; "
"case 1:sum=2;case 2:sum+=3;break;}if(sum!=5 || x!=1)return 1; "
"switch(9){case 0:sum=0;break;default:sum=7;}if(sum!=7)return 2; "
"for(x=0;x<4;x++){switch(x){case 1:continue;case 2:break; "
"default:switch(x){case 3:sum+=10;break;default:sum++;} }sum++;} "
"if(sum!=21 || table[0]!=3 || table[1]!=4 || table[2]!=8 || table[3]!=0)return 3; "
"switch(4){case 1+3:sum++;break;default:return 4;} "
"switch(99){} if(sum!=22)return 5; bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint f(void){goto done;return 8;done:return 3;} "
"int main(void){int x=0;again:x++;if(x<3)goto again;goto done;return 1; "
"done:if(x!=3 || f()!=3)return 2;{int y=4;goto inside;return 3; "
"inside:if(y!=4)return 4;} bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint x=11; int f(int x){int total=x; "
"{int x=7; total+=x;} {int x=8;total+=x;} return total+x;} "
"int main(void){int x=2;int total=0; {int x=3; {int x=4; total+=x;} total+=x;} "
"if(x!=2 || total!=7 || f(5)!=25) return 1; "
"for(int x=0;x<3;x++){int total=x; if(total!=x)return 2;} "
"if(x!=2 || total!=7)return 3; bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint pair(int a,int b){return a*10+b;} "
"int main(void){int x=0;int y=0;int a[4]={1}; "
"int n=1?7:++x; if(n!=7 || x) return 1; "
"n=0?++x:1?8:9; if(n!=8 || x) return 2; "
"n=0||1?3:4; if(n!=3) return 3; "
"n=(x=2,++x,x+4); if(n!=7 || x!=3) return 4; "
"if(pair((x=1,x+1),3)!=23 || x!=1) return 5; "
"for(x=0,y=0;x<3;x++,y+=2){} if(y!=6) return 6; "
"if(sizeof(int)!=1 || sizeof(char)!=1 || sizeof(int*)!=1 || sizeof(a)!=4) return 7; "
"if(sizeof(\"bob!\")!=5 || sizeof(++x)!=1 || x!=3) return 8; "
"n=1?(x=5,x+1):0; if(n!=6 || x!=5) return 9; "
"bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint main(void) { int i=0; int calls=0; int a[4]={7,8}; "
"do { i++; if(i==2) continue; calls++; if(i==4) break; } while(i<10); "
"if(i!=4 || calls!=3 || a[0]!=7 || a[1]!=8 || a[2]!=0 || a[3]!=0) return 1; "
"do { calls++; } while(0); if(calls!=4) return 2; bob_puts(\"bob!\"); return 0; }");
guest("#include \"runtime.h\"\n#include \"runtime.c\"\n"
"int sum(int n) { if (n == 0) return 0; return n + sum(n - 1); }\n"
"int main(void) { int data[4]; int other[4]; int *p; int i; "
@@ -201,6 +334,158 @@ static void usability(void) {
output=read_text("build/check.out");contains(output,"bob16 OS:");contains(output,"bob!\nExit 0");
not_contains(output,"Enter filename");free(output);
}
static void storage_path(const char *path) {
#ifdef _WIN32
check(_putenv_s("BOB16_STORAGE",path)==0,"set snapshot fixture path");
#else
check(setenv("BOB16_STORAGE",path,1)==0,"set snapshot fixture path");
#endif
}
static void snapshot_mutate(int offset, int rehash) {
FILE *file=fopen("build/snapshot.b16","rb");if(!file)fail("snapshot missing");
unsigned char bytes[8640];size_t count=fread(bytes,1,sizeof(bytes),file);fclose(file);
check(count==8640,"snapshot exact size");bytes[offset]^=(offset==401?2:1);
if(rehash) {
uint32_t hash=2166136261u;
for(size_t i=16;i<count;i++)hash=(hash^bytes[i])*16777619u;
for(unsigned i=0;i<4;i++)bytes[12+i]=(unsigned char)(hash>>(8*i));
}
file=fopen("build/snapshot.b16","wb");if(!file)fail("snapshot mutate");
check(fwrite(bytes,1,count,file)==count,"snapshot fixture write");fclose(file);
}
static void persistence(void) {
storage_path("build/snapshot.b16");remove("build/snapshot.b16");
char *output=shell("write note bob!\ncc bob.c saved\nsave\nwrite note changed\nrestore\nread note\nrestore yes\nread note\nrun saved\nhalt\n");
contains(output,"Files saved to");contains(output,"restore yes replaces all RAM files.");
contains(output,"bob> changed\n");contains(output,"Files restored;");contains(output,"bob> bob!\nExit 0");free(output);
output=shell("restore yes\nread note\nrun saved\nhalt\n");
contains(output,"Files restored;");contains(output,"bob> bob!\nExit 0");free(output);
write_text("build/check.in","kernel.basm\nrestore yes\nrun saved\nhalt\n");
check(system(BOB " < build/check.in > build/check.out 2> build/check.err")==0,"snapshot BASM restart");
output=read_text("build/check.out");contains(output,"bob> bob!\nExit 0");not_contains(output,"Kernel changed:");free(output);
/* A checksum failure, valid-checksum metadata failure and truncation must
leave an unrelated current file available in the same shell. */
snapshot_mutate(448,0);
output=shell("write current bob!\nrestore yes\nread current\nhalt\n");
contains(output,"Invalid saved files; RAM files unchanged.");contains(output,"bob> bob!\n");free(output);
output=shell("save\nhalt\n");free(output);
snapshot_mutate(401,1); /* length[0] high byte -> out of range */
output=shell("write current bob!\nrestore yes\nread current\nhalt\n");
contains(output,"Invalid saved files; RAM files unchanged.");contains(output,"bob> bob!\n");free(output);
write_text("build/snapshot.b16","B16S");
output=shell("write current bob!\nrestore yes\nread current\nhalt\n");
contains(output,"Invalid saved files; RAM files unchanged.");contains(output,"bob> bob!\n");free(output);
output=shell("write note bob!\ncc bob.c saved\nsave\nhalt\n");free(output);
snapshot_mutate(8,0); /* kernel identity is separate from payload checksum */
output=shell("restore yes\nread note\nrun saved\ngo bob.c\nhalt\n");
contains(output,"Kernel changed: old programs omitted.");contains(output,"Program not found.");contains(output,"bob!\nExit 0");free(output);
storage_path("build/no-such-directory/snapshot.b16");
output=shell("write note bob!\nsave\nrestore yes\nread note\nhalt\n");
contains(output,"Storage unavailable.");contains(output,"bob> bob!\n");free(output);
storage_path("build/snapshot.b16");
output=shell("load blocked 0xf700 0xe000\nrun blocked\necho bob!\nhalt\n");
contains(output,"Program fault; shell restored.");contains(output,"bob> bob!\n");free(output);
storage_path("");
}
static void shell_editing(void) {
char *output=shell("echo bob!\n\033[A\n\033[A\033[Becho bob!\ncle\t\nrea\t bo\t\nwrite backup bob!\nread ba\t\nread b\t\necho bb!\033[D\033[Do\nxxecho bob!\033[H\033[3~\033[3~\nwrong\025echo bob!\nabc\001\033[3~\033[3~\033[3~echo bob!\005\nhalt\n");
contains(output,"\033[2J\033[H");
contains(output,"int main(void) { println(\"bob!\"); return 0; }");
contains(output,"File not found."); /* read b is ambiguous: no completion */
int markers=0;for(char *p=output;(p=strstr(p,"bob> bob!\n"))!=NULL;p+=10)markers++;
check(markers==8,"history, insertion, delete, home/end and clear line");free(output);
/* History keeps four commands and does not mutate recalled entries. */
output=shell("echo 1\necho 2\necho 3\necho 4\necho bob!\n\033[A\033[A\033[A\033[A\033[A\n\033[A\033[F\b\b\b\b\b\b\025echo bob!\nhalt\n");
contains(output,"bob> 2\n");contains(output,"bob> bob!\n");free(output);
char long_command[512];memset(long_command,'x',128);strcpy(long_command+128,"\t\033[A\necho bob!\nhalt\n");
output=shell(long_command);contains(output,"Command too long.");contains(output,"bob> bob!\n");free(output);
output=shell("poke 49152 65535\npeek 49152\npeek 65535\npeek 65536\npoke 49152 -32769\nalloc 32768\nls\nhalt\n");
contains(output,"0xC000: 0xFFFF (-1)");contains(output,"0xFFFF:");
contains(output,"Invalid address. Use hex");contains(output,"Invalid value. Use");
contains(output,"Allocation failed. Use a positive size");contains(output,"Used 1/8 slots");free(output);
}
static void host_language_rejections(void) {
const char *sources[]={
"void a[2];int main(void){return 0;}",
"int a[2][];int main(void){return 0;}",
"int main(void){return sizeof(int[]);}",
"int main(void){int (*p)[];return sizeof(*p);}",
"int main(void){int (*p)[];p++;return 0;}",
"int main(void){return sizeof(int[3][]);}",
"int main(void){return (int[2])1;}",
"int f(int (*)[2]);int f(int (*p)[3]){return 0;}int main(void){return 0;}",
"int (*a)[3];int (*a)[2];int main(void){return 0;}",
"int a[2]={[2]=1};int main(void){return 0;}",
"int a[2]={[-1]=1};int main(void){return 0;}",
"int a[2][3]={[0][3]=1};int main(void){return 0;}",
"int a[2]={[0][0]=1};int main(void){return 0;}",
"int a={[0]=1};int main(void){return 0;}",
"int a[]={[4096]=1};int main(void){return 0;}",
"int main(void){int n=1;int a[2]={[n]=1};return 0;}",
"int a[2]={[1] 1};int main(void){return 0;}",
"int a[2][2]={{1,2,3},{4}};int main(void){return 0;}",
"int a[1][2]={{1},{2}};int main(void){return 0;}",
"int main(void){int a[2][2]={{1},{2,3,4}};return 0;}",
"char a[4]={\"bob!\",1};int main(void){return 0;}",
"char a[1][3]={\"bob!\"};int main(void){return 0;}",
"int main(void){int a[1]={1,2};return 0;}",
"int main(void){return sizeof(void);}",
"void f(void){} int main(void){return sizeof(f());}",
"int main(void){return 1 ? 2;}",
"int main(void){return sizeof((void)0);}",
"int main(void){goto missing;return 0;}",
"int main(void){same:;same:return 0;}",
"int main(void){int x=1;int x=2;return x;}",
"int f(int x){int x=2;return x;} int main(void){return f(1);}",
"int main(void){{int x=1;}return x;}",
"int main(void){return x;int x=1;}",
"int main(void){for(int x=0;x<1;x++){}return x;}",
"int f(int x,int x){return x;}int main(void){return f(1,2);}",
"int main(void){switch(1){case 1:;case 1:return 0;}}",
"int main(void){switch(1){default:;default:return 0;}}",
"int main(void){case 1:return 0;}",
"int main(void){switch(1){default:continue;}return 0;}",
"int a[1/0];int main(void){return 0;}",
"int a[1<<16];int main(void){return 0;}",
"int main(void){char text[3]=\"bob!\";return 0;}",
"int main(void){int text[]=\"bob!\";return 0;}",
"int main(void){char text[];return 0;}",
"int main(void){int x=1,x=2;return x;}",
"int x=1,x=2;int main(void){return x;}",
"int x;int *p=&x[1];int main(void){return 0;}",
"int x;int *p=&x;int *q=p;int main(void){return 0;}",
"int f(int);char f(int x){return x;}int main(void){return 0;}",
"int f(int,int);int f(int x){return x;}int main(void){return 0;}",
"int f(char);int f(int x){return x;}int main(void){return 0;}",
"int f(int);int f(int,int);int main(void){return 0;}",
"int f(int x=1){return x;}int main(void){return 0;}",
"int f;int f(void){return 0;}int main(void){return 0;}",
"int f(int*);int f(char *p){return 0;}int main(void){return 0;}",
"int f(int**);int f(int *p){return 0;}int main(void){return 0;}",
"char *f(void);int *f(void){return 0;}int main(void){return 0;}",
"int f(char []);int f(int *p){return 0;}int main(void){return 0;}",
"int main(void){void *p;return sizeof(*p);}",
"int main(void){int x;return sizeof(*x);}",
"int main(void){int x;return sizeof(x[0]);}",
"int main(void){int a[2][];return 0;}",
"int main(void){int a[4096][2];return 0;}",
"int main(void){int a[2],b[2];return (int)(a+b);}",
"int main(void){int a[2];a=0;return 0;}",
"int main(void){int a[2];a++;return 0;}",
"int main(void){int a[4096][4096];return 0;}",
"int main(void){int a[2],b[2];return sizeof(a+b);}",
"int main(void){void *p;return sizeof(p+1);}",
"int main(void){int a[2];return sizeof(a[a]);}"
};
for(unsigned i=0;i<sizeof(sources)/sizeof(sources[0]);i++) {
write_text("build/check.c",sources[i]);
write_text("build/check.basm","bob!\n");write_text("build/check.b16","bob!\n");
check(system("gcc -E -P -nostdinc -undef -I kernel build/check.c -o build/check.i > build/compiler.log 2>&1")==0,"language rejection preprocessing");
check(system(COMPILER " build/check.i build/check.basm build/check.b16 > build/compiler.log 2>&1")!=0,"invalid C must fail compilation");
char *prior=read_text("build/check.basm");check(!strcmp(prior,"bob!\n"),"failed compile preserves BASM output");free(prior);
prior=read_text("build/check.b16");check(!strcmp(prior,"bob!\n"),"failed compile preserves binary output");free(prior);
}
}
static void image_validation(void) {
FILE *in=fopen("build/kernel.b16","rb");if(!in)fail("kernel image missing");
FILE *out=fopen("build/bad.b16","wb");if(!out)fail("bad image fixture");int ch;long count=0;
@@ -219,6 +504,6 @@ static void basm_route(void) {
int main(void) {
console_and_commands();input_bounds();allocator_and_files();resident_compiler();
compiler_extensions();editor_and_aliases();
program_loading_and_recovery();host_compiler_and_runtime();file_management();compile_workflow();usability();image_validation();basm_route();
program_loading_and_recovery();host_compiler_and_runtime();host_language_rejections();file_management();compile_workflow();usability();persistence();shell_editing();image_validation();basm_route();
printf("bob!\n%d checks passed.\n",checks);return 0;
}
+526 -73
View File
@@ -12,12 +12,33 @@ enum { T_ID=256, T_NUM, T_STR, T_EQ, T_NE, T_LE, T_GE, T_AND, T_OR,
T_MODEQ, T_ANDEQ, T_OREQ, T_XOREQ };
enum { N_NUM=1, N_STR, N_ID, N_BINARY, N_UNARY, N_ASSIGN, N_CALL, N_INDEX,
N_BLOCK, N_DECL, N_IF, N_WHILE, N_FOR, N_RETURN, N_BREAK, N_CONTINUE,
N_EMPTY, N_CAST, N_FUNCTION };
N_EMPTY, N_CAST, N_FUNCTION, N_DO, N_CONDITIONAL, N_SIZEOF, N_LABEL, N_GOTO,
N_SWITCH, N_CASE, N_DECL_GROUP, N_PROTOTYPE };
typedef struct Node Node;
struct Node { int kind, op, value, type, count; char *name; Node *a,*b,*c,*d,*next; };
typedef struct { int type, number, line; char *text; } Token;
static Token tokens[65536];
static int ntokens, at;
static int parsing_parameter;
/* Interned pointer descriptors retain pointee type and indirection depth.
Primitive IDs remain int=0, void=3, char=4; array objects still use kind 2. */
typedef struct { int kind,base,count; } PointerType;
static PointerType pointer_types[4096];
static int npointer_types;
static int derived_type(int kind,int base,int count) {
for(int i=0;i<npointer_types;i++)if(pointer_types[i].kind==kind && pointer_types[i].base==base && pointer_types[i].count==count)return 16+i;
if(npointer_types==4096){fprintf(stderr,"bobcc: too many pointer types\n");exit(1);}
pointer_types[npointer_types]=(PointerType){kind,base,count};return 16+npointer_types++;
}
static int pointer_to(int base) {return derived_type(1,base,1);}
static int array_of(int base,int count) {return derived_type(2,base,count);}
static int is_derived(int type) {return type>=16 && type<16+npointer_types;}
static int is_pointer(int type) {return is_derived(type) && pointer_types[type-16].kind==1;}
static int is_array(int type) {return is_derived(type) && pointer_types[type-16].kind==2;}
static int type_size(int type);
static int expression_type(Node *n);
static int decay_type(int type);
static void binary_typed(int op,int left,int right);
static Node *top, **top_tail=&top;
static uint16_t code[65536];
static int ncode, legacy, serial, return_label;
@@ -25,22 +46,25 @@ enum { ORIGIN=0x300, MAX_SYMBOLS=4096 };
typedef struct { char *name; int address; } Label;
static Label labels[MAX_SYMBOLS];
static int nlabels;
typedef struct { int index; char *name; } Fixup;
typedef struct { int index; char *name; int addend; } Fixup;
static Fixup fixups[65536];
static int nfixups;
typedef struct { int index, length, flags; char *target; } Jump;
static Jump jumps[65536];
static int njumps;
typedef struct { char *name; int type,count,offset; Node *init; } Variable;
typedef struct { char *name; int type,count,offset; Node *init; int base; } Variable;
static Variable globals[MAX_SYMBOLS], locals[MAX_SYMBOLS];
static int nglobals, nlocals;
static int scope_base, function_body;
static const char *current_function;
typedef struct { char *name; Node *node; int nargs; } Function;
static Function functions[MAX_SYMBOLS];
static int nfunctions;
typedef struct { char *name; char *value; } String;
typedef struct { char *name; char *value; int length; } String;
static String strings[4096];
static int nstrings;
static int loop_step[64], loop_end[64], loop_depth;
static int break_targets[64], break_depth;
static int compiling_compare_helper;
static void error(const char *fmt, ...) {
@@ -98,7 +122,7 @@ static void lex(const char *source) {
if(*p!=quote)error("unterminated string");
p++;buffer[count]=0;
if(quote=='\'') { if(count!=1)error("character literal must contain one character");t->type=T_NUM;t->number=(unsigned char)buffer[0]; }
else { t->type=T_STR;t->text=copy(buffer); }
else { t->type=T_STR;t->number=count;t->text=allocate((size_t)count+1);memcpy(t->text,buffer,(size_t)count+1); }
} else {
const char *pairs[]={"==","!=","<=",">=","&&","||","++","--","<<",">>","+=","-=","*=","/=","%=","&=","|=","^="};
int kinds[]={T_EQ,T_NE,T_LE,T_GE,T_AND,T_OR,T_INC,T_DEC,T_SHL,T_SHR,T_ADDEQ,T_SUBEQ,T_MULEQ,T_DIVEQ,T_MODEQ,T_ANDEQ,T_OREQ,T_XOREQ};
@@ -114,30 +138,44 @@ static int take(int t) { if(tok()!=t)return 0;at++;return 1; }
static void expect(int t) { if(!take(t))error("expected token %d, got %d",t,tok()); }
static char *identifier(void) { if(tok()!=T_ID)error("expected identifier");return tokens[at++].text; }
static int type_start(void) { return is("int")||is("char")||is("void")||is("const"); }
static int parse_type(void) {
static int parse_base_type(void) {
if(is("const"))at++;
if(!is("int")&&!is("char")&&!is("void"))error("only int, char, void and pointers supported");
int result=is("void")?3:0;at++;
while(take('*')) { result=1;if(is("const"))at++; }
int result=is("void")?3:is("char")?4:0;at++;
return result;
}
static int parse_declarator(int base,char **name,int abstract);
static int parse_type(void) {
char *name=NULL;int type=parse_declarator(parse_base_type(),&name,1);
if(name && *name)error("identifier in type name");
return type;
}
static Node *expression(int minimum);
static Node *statement(void);
static Node *primary(void) {
Node *n;
if(tok()==T_NUM) { n=node(N_NUM,NULL,NULL);n->value=tokens[at++].number; }
else if(tok()==T_STR) { n=node(N_STR,NULL,NULL);n->name=tokens[at++].text;
while(tok()==T_STR) { size_t a=strlen(n->name),b=strlen(tokens[at].text);char *s=allocate(a+b+1);
memcpy(s,n->name,a);memcpy(s+a,tokens[at++].text,b+1);n->name=s; } }
if(is("sizeof")) {
at++;
if(take('(')) {
if(type_start()) {
int type=parse_type();if(type==3)error("sizeof void is invalid");expect(')');
n=node(N_NUM,NULL,NULL);n->value=type_size(type);
} else {n=node(N_SIZEOF,expression(0),NULL);expect(')');}
} else n=node(N_SIZEOF,expression(13),NULL);
}
else if(tok()==T_NUM) { n=node(N_NUM,NULL,NULL);n->value=tokens[at++].number; }
else if(tok()==T_STR) { n=node(N_STR,NULL,NULL);n->name=tokens[at].text;n->value=tokens[at++].number;
while(tok()==T_STR) { size_t a=(size_t)n->value,b=(size_t)tokens[at].number;char *s=allocate(a+b+1);
memcpy(s,n->name,a);memcpy(s+a,tokens[at++].text,b+1);n->name=s;n->value=(int)(a+b); } }
else if(tok()==T_ID) { n=node(N_ID,NULL,NULL);n->name=identifier(); }
else if(take('(')) {
if(type_start()) { int type=parse_type();expect(')');n=node(N_CAST,expression(13),NULL);n->type=type; }
else { n=expression(1);expect(')'); }
if(type_start()) { int type=parse_type();if(is_array(type))error("cast to array type");expect(')');n=node(N_CAST,expression(13),NULL);n->type=type; }
else { n=expression(0);expect(')'); }
} else if(tok()=='-'||tok()=='+'||tok()=='!'||tok()=='~'||tok()=='&'||tok()=='*'||tok()==T_INC||tok()==T_DEC) {
int op=tokens[at++].type;n=node(N_UNARY,expression(13),NULL);n->op=op;
} else { error("expected expression");return NULL; }
while(1) {
if(take('[')) { n=node(N_INDEX,n,expression(1));expect(']'); }
if(take('[')) { n=node(N_INDEX,n,expression(0));expect(']'); }
else if(take('(')) {
if(n->kind!=N_ID)error("function pointers unsupported");
Node *call=node(N_CALL,NULL,NULL);call->name=n->name;
@@ -151,66 +189,244 @@ static Node *primary(void) {
static int precedence(int op) {
switch(op) {
case '=':case T_ADDEQ:case T_SUBEQ:case T_MULEQ:case T_DIVEQ:case T_MODEQ:case T_ANDEQ:case T_OREQ:case T_XOREQ:return 1;
case T_OR:return 2;case T_AND:return 3;case '|':return 4;case '^':return 5;case '&':return 6;
case T_EQ:case T_NE:return 7;case '<':case '>':case T_LE:case T_GE:return 8;
case T_SHL:case T_SHR:return 9;case '+':case '-':return 10;case '*':case '/':case '%':return 11;
default:return 0;
case ',':return 0;
case T_OR:return 3;case T_AND:return 4;case '|':return 5;case '^':return 6;case '&':return 7;
case T_EQ:case T_NE:return 8;case '<':case '>':case T_LE:case T_GE:return 9;
case T_SHL:case T_SHR:return 10;case '+':case '-':return 11;case '*':case '/':case '%':return 12;
default:return -1;
}
}
static Node *expression(int minimum) {
Node *left=primary();int op,level;
while((level=precedence(op=tok()))>=minimum&&level) {
while(1) {
if(tok()=='?' && minimum<=2) {
at++;Node *middle=expression(0);expect(':');
Node *n=node(N_CONDITIONAL,left,middle);n->c=expression(2);left=n;continue;
}
level=precedence(op=tok());if(level<minimum || level<0)break;
at++;Node *right=expression(level+(level==1?0:1));Node *n=node(level==1?N_ASSIGN:N_BINARY,left,right);n->op=op;left=n;
}
return left;
}
static int constant(Node *n) {
if(n->kind==N_NUM)return n->value;
if(n->kind==N_UNARY&&n->op=='-')return -constant(n->a);
if(n->kind==N_NUM)return (int16_t)n->value;
if(n->kind==N_CAST && n->type!=3)return constant(n->a);
if(n->kind==N_CONDITIONAL)return constant(n->a)?constant(n->b):constant(n->c);
if(n->kind==N_UNARY) {
int a=constant(n->a);
if(n->op=='-')return (int16_t)-a;
if(n->op=='+')return a;
if(n->op=='!')return !a;
if(n->op=='~')return (int16_t)~a;
}
if(n->kind==N_BINARY) {
int a=constant(n->a);
if(n->op==T_AND && !a)return 0;
if(n->op==T_OR && a)return 1;
int b=constant(n->b);
switch(n->op) {
case '+':return (int16_t)(a+b);case '-':return (int16_t)(a-b);
case '*':return (int16_t)(a*b);
case '/':case '%':if(!b)error("division by zero in constant expression");return (int16_t)(n->op=='/'?a/b:a%b);
case '&':return a&b;case '|':return a|b;case '^':return a^b;
case T_EQ:return a==b;case T_NE:return a!=b;
case '<':return a<b;case '>':return a>b;case T_LE:return a<=b;case T_GE:return a>=b;
case T_AND:return !!b;case T_OR:return !!b;
case T_SHL:case T_SHR:
if(b<0 || b>=16)error("invalid constant shift count");
if(n->op==T_SHL)return (int16_t)((uint32_t)(uint16_t)a<<b);
if(!b)return a;
return (int16_t)(((uint16_t)a>>b)|(a<0?(0xffffu<<(16-b)):0));
default:break;
}
}
error("initializer/array size must be constant");return 0;
}
typedef struct {int kind,count;} DeclaratorPart;
static void declarator_parts(DeclaratorPart *parts,int *length,char **name,int abstract,int depth) {
if(depth>32)error("declarator nesting exceeds 32 levels");
int pointers=0;
while(take('*')) {pointers++;if(is("const"))at++;if(pointers>64)error("too many pointer levels");}
if(tok()==T_ID) {*name=identifier();}
else if(take('(')) {declarator_parts(parts,length,name,abstract,depth+1);expect(')');}
else if(!abstract)error("expected declarator name");
while(take('[')) {
int empty=tok()==']',bound=empty?0:constant(expression(1));expect(']');
if(!empty && (bound<1 || bound>4096))error("array length must be 1..4096");
if(*length==64)error("declarator exceeds 64 derived types");
parts[(*length)++]=(DeclaratorPart){2,bound};
}
while(pointers--) {
if(*length==64)error("declarator exceeds 64 derived types");
parts[(*length)++]=(DeclaratorPart){1,1};
}
}
static int parse_declarator(int base,char **name,int abstract) {
DeclaratorPart parts[64];int length=0,dimensions=0;*name=NULL;
declarator_parts(parts,&length,name,abstract,0);
while(length--) {
if(parts[length].kind==1)base=pointer_to(base);
else {
if(++dimensions>16)error("too many array dimensions");
if(base==3)error("array of void");
if(is_array(base) && !pointer_types[base-16].count)error("incomplete array element type");
base=array_of(base,parts[length].count);
}
}
if(!*name)*name=copy("");
return base;
}
static void initializer_append(Node ***tail,Node *value) {
**tail=value;*tail=&value->next;
}
/* Flatten aggregate braces into storage order, preserving omitted subobjects. */
static int initializer_depth;
static int initializer_list(int element,int count,int aggregate,Node ***tail) {
if(++initializer_depth>64)error("initializer nesting exceeds 64 levels");
expect('{');
int stride=type_size(element),position=0,total=count?count*stride:0,extent=0;
if(stride>4096 || total>4096)error("initializer storage exceeds 4096 words");
Node *values[4096]={0};
while(tok()!='}') {
int sub=element;
int designated=tok()=='[';
if(designated) {
if(!aggregate)error("array designator requires an array");
int current=array_of(element,count?count:4096/stride);position=0;
do {
if(!is_array(current))error("too many array designators");
expect('[');int index=constant(expression(1));expect(']');
if(index<0 || index>=pointer_types[current-16].count)error("array designator out of bounds");
current=pointer_types[current-16].base;position+=index*type_size(current);
} while(tok()=='[');
expect('=');sub=current;
}
if(position>=4096 || (total && position>=total))error("too many array initializers");
/* Brace elision can leave us partway through a nested array. */
if(!designated)while(is_array(sub) && position%type_size(sub))sub=pointer_types[sub-16].base;
Node *items=NULL,**items_tail=&items;int length=0;
if(tok()=='{') {
if(is_array(sub)) {
length=initializer_list(pointer_types[sub-16].base,pointer_types[sub-16].count,1,&items_tail);
if(length!=type_size(sub))error("invalid aggregate initializer");
} else length=initializer_list(sub,1,0,&items_tail);
} else {
Node *value=expression(1);
if(value->kind==N_STR && ((is_array(sub) && pointer_types[sub-16].base==4) ||
(!designated && aggregate && element==4 && position==0))) {
length=is_array(sub)?pointer_types[sub-16].count:(count?count:value->value+1);
if(value->value>length)error("character array too small for string");
for(int i=0;i<length;i++) {
Node *item=node(N_NUM,NULL,NULL);
item->value=i<value->value?(unsigned char)value->name[i]:0;
initializer_append(&items_tail,item);
}
} else {initializer_append(&items_tail,value);length=1;}
}
if(position+length>4096 || (total && position+length>total))error("too many array initializers");
while(items) {Node *next=items->next;items->next=NULL;values[position++]=items;items=next;}
if(position>extent)extent=position;
if(!take(','))break;
}
expect('}');
if(total)extent=total;
for(int i=0;i<extent;i++)initializer_append(tail,values[i]?values[i]:node(N_NUM,NULL,NULL));
initializer_depth--;
return extent;
}
static Node *declaration(int type,char *name) {
Node *n=node(N_DECL,NULL,NULL);n->name=name;n->type=type;n->count=1;
if(take('[')) { n->count=constant(expression(1));expect(']');n->type=2;
if(n->count<1||n->count>4096)error("array length must be 1..4096"); }
Node *n=node(N_DECL,NULL,NULL);n->name=name;n->type=type;n->count=1;n->op=type;
int inferred=0,braced=0;
if(is_array(type)){n->type=2;n->count=pointer_types[type-16].count;n->op=pointer_types[type-16].base;inferred=!n->count;}
if(type==3)error("void variable");
if(parsing_parameter) {
if(tok()=='=')error("parameter cannot have an initializer");
if(n->type==2){n->type=pointer_to(n->op);n->count=1;}
return n;
}
if(take('=')) {
if(take('{')) { Node **tail=&n->a;do { *tail=expression(1);tail=&(*tail)->next; }while(take(',')&&tok()!='}');expect('}'); }
if(tok()=='{') { Node **tail=&n->a;braced=1;initializer_list(n->type==2?n->op:n->type,n->type==2?n->count:1,n->type==2,&tail); }
else n->a=expression(1);
}
if(n->type==2 && n->a && n->a->kind==N_STR && !braced) {
Node *string=n->a;
if(n->op!=4)error("string initializer requires a character array");
if(inferred)n->count=string->value+1;
if(n->count<string->value)error("character array too small for string");
Node **tail=&n->a;int length=string->value+1;if(length>n->count)length=n->count;
for(int i=0;i<length;i++){*tail=node(N_NUM,NULL,NULL);(*tail)->value=(unsigned char)string->name[i];tail=&(*tail)->next;}
} else if(inferred) {
int elements=0;for(Node *value=n->a;value;value=value->next)elements++;
int stride=type_size(n->op);n->count=(elements+stride-1)/stride;
}
if(inferred && (!n->a || n->count<1 || n->count>4096))error("inferred array needs 1..4096 initialized elements");
if(n->type==2 && type_size(array_of(n->op,n->count))>4096)error("array storage exceeds 4096 words");
return n;
}
static Node *declaration_group(int base) {
Node *group=node(N_DECL_GROUP,NULL,NULL);Node **tail=&group->a;
do {
char *name;int type=parse_declarator(base,&name,0);
*tail=declaration(type,name);tail=&(*tail)->next;
} while(take(','));
return group;
}
static Node *statement(void) {
if(is("switch")) {at++;expect('(');Node *n=node(N_SWITCH,expression(0),NULL);expect(')');n->b=statement();return n;}
if(is("case") || is("default")) {
Node *n=node(N_CASE,NULL,NULL);n->type=is("default");at++;
if(!n->type)n->count=constant(expression(1));
expect(':');n->b=statement();return n;
}
if(tok()==T_ID && tokens[at+1].type==':') {
Node *n=node(N_LABEL,NULL,NULL);n->name=identifier();expect(':');n->b=statement();return n;
}
if(is("goto")) {at++;Node *n=node(N_GOTO,NULL,NULL);n->name=identifier();expect(';');return n;}
if(take('{')) { Node *n=node(N_BLOCK,NULL,NULL);Node **tail=&n->a;
while(tok()&&tok()!='}') { *tail=statement();tail=&(*tail)->next; }expect('}');return n; }
if(is("if")) { at++;expect('(');Node *n=node(N_IF,expression(1),NULL);expect(')');n->b=statement();if(is("else")){at++;n->c=statement();}return n; }
if(is("while")) { at++;expect('(');Node *n=node(N_WHILE,expression(1),NULL);expect(')');n->b=statement();return n; }
if(is("if")) { at++;expect('(');Node *n=node(N_IF,expression(0),NULL);expect(')');n->b=statement();if(is("else")){at++;n->c=statement();}return n; }
if(is("while")) { at++;expect('(');Node *n=node(N_WHILE,expression(0),NULL);expect(')');n->b=statement();return n; }
if(is("do")) {
at++;Node *n=node(N_DO,NULL,NULL);n->b=statement();
if(!is("while"))error("expected while after do body");
at++;expect('(');n->a=expression(0);expect(')');expect(';');return n;
}
if(is("for")) {
at++;expect('(');Node *n=node(N_FOR,NULL,NULL);
if(type_start()) { int t=parse_type();n->a=declaration(t,identifier()); }
else if(tok()!=';')n->a=expression(1);
if(type_start()) { int base=parse_base_type();n->a=declaration_group(base); }
else if(tok()!=';')n->a=expression(0);
expect(';');
if(tok()!=';')n->b=expression(1);
if(tok()!=';')n->b=expression(0);
expect(';');
if(tok()!=')')n->c=expression(1);
if(tok()!=')')n->c=expression(0);
expect(')');n->d=statement();return n;
}
if(is("return")) { at++;Node *n=node(N_RETURN,NULL,NULL);if(tok()!=';')n->a=expression(1);expect(';');return n; }
if(is("return")) { at++;Node *n=node(N_RETURN,NULL,NULL);if(tok()!=';')n->a=expression(0);expect(';');return n; }
if(is("break")||is("continue")) { int kind=is("break")?N_BREAK:N_CONTINUE;at++;expect(';');return node(kind,NULL,NULL); }
if(type_start()) { int t=parse_type();Node *n=declaration(t,identifier());expect(';');return n; }
if(type_start()) {int base=parse_base_type();Node *n=declaration_group(base);expect(';');return n;}
if(take(';'))return node(N_EMPTY,NULL,NULL);
Node *n=expression(1);expect(';');return n;
Node *n=expression(0);expect(';');return n;
}
static void parse(void) {
while(tok()) {
int type=parse_type();char *name=identifier();Node *n;
int base=parse_base_type();char *name;int type=parse_declarator(base,&name,0);Node *n;
if(take('(')) {
if(is_array(type))error("function cannot return an array");
n=node(N_FUNCTION,NULL,NULL);n->name=name;n->type=type;Node **tail=&n->a;
n->op=tok()==')';
if(is("void")&&tokens[at+1].type==')')at++;
else if(tok()!=')')do { int t=parse_type();char *p=tok()==T_ID?identifier():copy("");
*tail=declaration(t,p);tail=&(*tail)->next; }while(take(','));
expect(')');if(take(';'))continue;n->b=statement();if(n->b->kind!=N_BLOCK)error("expected function body");
} else { n=declaration(type,name);expect(';'); }
else if(tok()!=')')do { char *p;int t=parse_declarator(parse_base_type(),&p,1);
parsing_parameter=1;*tail=declaration(t,p);parsing_parameter=0;tail=&(*tail)->next; }while(take(','));
expect(')');
if(take(';'))n->kind=N_PROTOTYPE;
else {n->b=statement();if(n->b->kind!=N_BLOCK)error("expected function body");}
} else {
n=declaration(type,name);*top_tail=n;top_tail=&n->next;
while(take(',')) {
type=parse_declarator(base,&name,0);n=declaration(type,name);*top_tail=n;top_tail=&n->next;
}
expect(';');continue;
}
*top_tail=n;top_tail=&n->next;
}
}
@@ -228,7 +444,7 @@ static void literal(int reg,int value,const char *name) {
return;
}
emit(0x4001|reg<<9);emit(0xae01);
if(name) { fixups[nfixups++]=(Fixup){ncode,copy(name)};emit(0); }else emit(value);
if(name) { fixups[nfixups++]=(Fixup){ncode,copy(name),0};emit(0); }else emit(value);
}
static void move(int dst,int src) { emit(0x1080|dst<<9|src<<4); }
static void addi(int reg,int value) {
@@ -237,9 +453,14 @@ static void addi(int reg,int value) {
}
static void push(int reg) { addi(6,-1);emit(0x9000|reg<<9|6<<6); }
static void pop(int reg) { emit(0x6000|reg<<9|6<<6);addi(6,1); }
static void jump(int id) {
jumps[njumps++]=(Jump){ncode,4,7,copy(label_name(id))};
literal(3,0,label_name(id));emit(0xb600);
static void jump_name(const char *name) {
jumps[njumps++]=(Jump){ncode,4,7,copy(name)};
literal(3,0,name);emit(0xb600);
}
static void jump(int id) {jump_name(label_name(id));}
static char *user_label(const char *name) {
size_t size=strlen(current_function)+strlen(name)+16;char *label=allocate(size);
snprintf(label,size,"user.%s.%s",current_function,name);return label;
}
static void branch(int flags,int id) {
int start=ncode;
@@ -292,7 +513,7 @@ static void compact_jumps(void) {
static void negate(int reg) { emit(0x3100|reg<<9);addi(reg,1); }
static int fresh(void) { return ++serial; }
static Variable *variable(const char *name,int *global) {
for(int i=0;i<nlocals;i++)if(!strcmp(locals[i].name,name)){*global=0;return &locals[i];}
for(int i=nlocals-1;i>=0;i--)if(!strcmp(locals[i].name,name)){*global=0;return &locals[i];}
for(int i=0;i<nglobals;i++)if(!strcmp(globals[i].name,name)){*global=1;return &globals[i];}
error("unknown variable %s",name);return NULL;
}
@@ -304,7 +525,11 @@ static void expr(Node *n);
static void address(Node *n) {
if(n->kind==N_ID) { int global;Variable *v=variable(n->name,&global);
if(global)literal(0,0,named("g.",n->name));else { move(0,5);addi(0,v->offset); } }
else if(n->kind==N_INDEX) { expr(n->a);push(0);expr(n->b);pop(1);emit(0x1010); }
else if(n->kind==N_INDEX) {
int a=decay_type(expression_type(n->a)),b=decay_type(expression_type(n->b));
if(!is_pointer(a) && !is_pointer(b))error("subscript requires pointer/array");
expr(n->a);push(0);expr(n->b);pop(1);binary_typed('+',a,b);
}
else if(n->kind==N_UNARY&&n->op=='*')expr(n->a);
else error("expected assignable variable or pointer");
}
@@ -336,34 +561,162 @@ static void binary(int op) {
} else compare(op);
}
static void args_reverse(Node *arg) { if(!arg)return;args_reverse(arg->next);expr(arg);push(0); }
static const char *string_label(Node *n) {
for(int i=0;i<nstrings;i++)if(strings[i].length==n->value && !memcmp(strings[i].value,n->name,(size_t)n->value))return strings[i].name;
if(nstrings==4096)error("too many strings");
char *name=label_name(fresh());strings[nstrings++]=(String){name,n->name,n->value};return name;
}
static int global_address(Node *n,const char **name,int *offset);
static int global_object_address(Node *n,const char **name,int *offset) {
if(n->kind==N_ID) {
for(int i=0;i<nglobals;i++)if(!strcmp(globals[i].name,n->name)) {
*name=named("g.",n->name);*offset=0;return 1;
}
} else if(n->kind==N_INDEX) {
Node *base=n->a,*index=n->b;
int type=decay_type(expression_type(base));
if(!is_pointer(type)) {base=n->b;index=n->a;type=decay_type(expression_type(base));}
if(!is_pointer(type))return 0;
if(global_address(base,name,offset)) {
*offset+=constant(index)*type_size(pointer_types[type-16].base);return 1;
}
} else if(n->kind==N_UNARY && n->op=='*')return global_address(n->a,name,offset);
return 0;
}
static int global_address(Node *n,const char **name,int *offset) {
if(n->kind==N_STR){*name=string_label(n);*offset=0;return 1;}
if(n->kind==N_CAST && is_pointer(n->type))return global_address(n->a,name,offset);
if(n->kind==N_BINARY && (n->op=='+' || n->op=='-')) {
if(global_address(n->a,name,offset)){
int t=decay_type(expression_type(n->a));
int delta=constant(n->b)*type_size(pointer_types[t-16].base);*offset+=n->op=='+'?delta:-delta;return 1;
}
if(n->op=='+' && global_address(n->b,name,offset)){
int t=decay_type(expression_type(n->b));*offset+=constant(n->a)*type_size(pointer_types[t-16].base);return 1;
}
return 0;
}
if(n->kind==N_UNARY && n->op=='&')return global_object_address(n->a,name,offset);
if((n->kind==N_ID || n->kind==N_INDEX || (n->kind==N_UNARY && n->op=='*')) &&
is_array(expression_type(n)))return global_object_address(n,name,offset);
return 0;
}
static int decay_type(int type) {
if(is_derived(type) && pointer_types[type-16].kind==2)return pointer_to(pointer_types[type-16].base);
return type;
}
static int expression_type(Node *n) {
switch(n->kind) {
case N_NUM:return 0;
case N_STR:return array_of(4,n->value+1);
case N_ID:{int global;Variable *v=variable(n->name,&global);return v->type==2?array_of(v->base,v->count):v->type;}
case N_CAST:return n->type;
case N_SIZEOF:return 0;
case N_CALL:
for(Node *d=top;d;d=d->next)if((d->kind==N_FUNCTION || d->kind==N_PROTOTYPE) && !strcmp(d->name,n->name))return d->type;
error("unknown function in sizeof: %s",n->name);return 0;
case N_INDEX:{
int t=decay_type(expression_type(n->a)),other=decay_type(expression_type(n->b));
if(is_pointer(t) && is_pointer(other))error("subscript needs one integer operand");
if(!is_pointer(t))t=other;
if(!is_pointer(t))error("subscript requires pointer/array");
return pointer_types[t-16].base;
}
case N_UNARY:{
int t=expression_type(n->a);
if(n->op=='&')return pointer_to(t);
t=decay_type(t);
if(n->op=='*'){if(!is_pointer(t))error("dereference requires pointer");return pointer_types[t-16].base;}
if(n->op==T_INC || n->op==T_DEC)return t;
return 0;
}
case N_ASSIGN:return decay_type(expression_type(n->a));
case N_BINARY:{
if(n->op==',')return decay_type(expression_type(n->b));
int a=decay_type(expression_type(n->a)),b=decay_type(expression_type(n->b));
if(n->op=='+' || n->op=='-') {
if(is_pointer(a) && is_pointer(b) && (n->op=='+' || a!=b))error("invalid pointer arithmetic");
if(n->op=='-' && !is_pointer(a) && is_pointer(b))error("cannot subtract pointer from integer");
if(is_pointer(a))type_size(pointer_types[a-16].base);
if(is_pointer(b))type_size(pointer_types[b-16].base);
}
if(n->op=='+' && is_pointer(b))return b;
if((n->op=='+' || n->op=='-') && is_pointer(a) && !is_pointer(b))return a;
return 0;
}
case N_CONDITIONAL:{
int a=decay_type(expression_type(n->b)),b=decay_type(expression_type(n->c));
if(a==3 || b==3)return 3;
if(is_pointer(a))return a;
if(is_pointer(b))return b;
return 0;
}
default:error("unsupported sizeof operand");return 0;
}
}
static int type_size(int type) {
if(type==3)error("sizeof void expression is invalid");
if(is_array(type)) {
int base=type_size(pointer_types[type-16].base),count=pointer_types[type-16].count;
if(count<1)error("incomplete array has no storage size");
if(count>65535/base)error("array object too large for address space");
return count*base;
}
return 1;
}
static void binary_typed(int op,int left,int right) {
left=decay_type(left);right=decay_type(right);
if((op=='+' || op=='-') && (is_pointer(left) || is_pointer(right))) {
if(is_pointer(left) && is_pointer(right)) {
if(op!='-' || left!=right)error("invalid pointer arithmetic");
int stride=type_size(pointer_types[left-16].base);binary('-');
if(stride!=1){move(1,0);literal(0,stride,NULL);binary('/');}return;
}
int pointer=is_pointer(left)?left:right;
if(op=='-' && !is_pointer(left))error("cannot subtract a pointer from an integer");
int stride=type_size(pointer_types[pointer-16].base);
if(stride!=1) {
if(is_pointer(left)){push(1);move(1,0);literal(0,stride,NULL);binary('*');pop(1);}
else {push(0);move(0,1);literal(1,stride,NULL);binary('*');pop(1);}
}
}
binary(op);
}
static void expr(Node *n) {
if(!n)error("missing expression");
switch(n->kind) {
case N_NUM:literal(0,n->value,NULL);break;
case N_STR: {
int existing=-1;for(int i=0;i<nstrings;i++)if(!strcmp(strings[i].value,n->name)){existing=i;break;}
if(existing>=0){literal(0,0,strings[existing].name);break;}
if(nstrings==4096)error("too many strings");
char *name=label_name(fresh());strings[nstrings++]=(String){name,n->name};literal(0,0,name);break; }
case N_STR:literal(0,0,string_label(n));break;
case N_ID: { int global;Variable *v=variable(n->name,&global);address(n);if(v->type!=2)emit(0x6000);break; }
case N_INDEX:address(n);emit(0x6000);break;
case N_INDEX:address(n);if(!is_array(expression_type(n)))emit(0x6000);break;
case N_CAST:expr(n->a);break;
case N_SIZEOF:{
literal(0,type_size(expression_type(n->a)),NULL);break;
}
case N_UNARY:
if(n->op=='&')address(n->a);
else if(n->op==T_INC||n->op==T_DEC) {address(n->a);push(0);emit(0x6000);if(n->value)move(4,0);
addi(0,n->op==T_INC?1:-1);pop(1);emit(0x9040);if(n->value)move(0,4);}
else {expr(n->a);if(n->op=='*')emit(0x6000);else if(n->op=='-')negate(0);else if(n->op=='~')emit(0x3100);
int type=expression_type(n->a);if(is_array(type))error("array is not modifiable");
int stride=is_pointer(type)?type_size(pointer_types[type-16].base):1;
addi(0,n->op==T_INC?stride:-stride);pop(1);emit(0x9040);if(n->value)move(0,4);}
else {expr(n->a);if(n->op=='*'){int t=expression_type(n);if(t==3)error("cannot load void");if(!is_array(t))emit(0x6000);}else if(n->op=='-')negate(0);else if(n->op=='~')emit(0x3100);
else if(n->op=='!'){literal(1,0,NULL);compare(T_EQ);}else if(n->op!='+')error("unsupported unary operator");}
break;
case N_BINARY:
if(n->op==T_AND||n->op==T_OR) {int shortcut=fresh(),end=fresh();expr(n->a);move(0,0);branch(n->op==T_AND?2:5,shortcut);
if(n->op==','){expr(n->a);expr(n->b);}
else if(n->op==T_AND||n->op==T_OR) {int shortcut=fresh(),end=fresh();expr(n->a);move(0,0);branch(n->op==T_AND?2:5,shortcut);
expr(n->b);literal(1,0,NULL);compare(T_NE);jump(end);mark(shortcut);literal(0,n->op==T_OR,NULL);mark(end);}
else {expr(n->a);push(0);expr(n->b);pop(1);binary(n->op);}break;
else {expr(n->a);push(0);expr(n->b);pop(1);binary_typed(n->op,expression_type(n->a),expression_type(n->b));}break;
case N_CONDITIONAL:{
int other=fresh(),end=fresh();expr(n->a);move(0,0);branch(2,other);
expr(n->b);jump(end);mark(other);expr(n->c);mark(end);break;
}
case N_ASSIGN: {
if(is_array(expression_type(n->a)))error("array is not assignable");
address(n->a);push(0);
if(n->op!='='){emit(0x6000);push(0);}
expr(n->b);
if(n->op!='=') { pop(1);int op=n->op==T_ADDEQ?'+':n->op==T_SUBEQ?'-':n->op==T_MULEQ?'*':n->op==T_DIVEQ?'/':n->op==T_MODEQ?'%':n->op==T_ANDEQ?'&':n->op==T_OREQ?'|':'^';binary(op); }
if(n->op!='=') { pop(1);int op=n->op==T_ADDEQ?'+':n->op==T_SUBEQ?'-':n->op==T_MULEQ?'*':n->op==T_DIVEQ?'/':n->op==T_MODEQ?'%':n->op==T_ANDEQ?'&':n->op==T_OREQ?'|':'^';binary_typed(op,expression_type(n->a),expression_type(n->b)); }
pop(1);emit(0x9040);break; }
case N_CALL: {
int count=0;for(Node *a=n->a;a;a=a->next)count++;
@@ -376,28 +729,103 @@ static void expr(Node *n) {
else if(!strcmp(n->name,"bob_gets")){vector=3;expected=2;}
else if(!strcmp(n->name,"bob_getc"))vector=5;
else if(!strcmp(n->name,"bob_run")){vector=6;expected=1;}
else if(!strcmp(n->name,"bob_snapshot")){vector=7;expected=2;}
else if(!strcmp(n->name,"bob_key"))vector=8;
else if(!strcmp(n->name,"bob_terminal"))vector=9;
else if(!strcmp(n->name,"bob_columns"))vector=10;
else if(!strcmp(n->name,"bob_rows"))vector=11;
if(vector>=0) {if(count!=expected)error("wrong argument count for %s",n->name);
if(vector==3){expr(n->a->next);push(0);expr(n->a);pop(1);}else if(count)expr(n->a);
if(expected==2){expr(n->a->next);push(0);expr(n->a);pop(1);}else if(count)expr(n->a);
emit(0xf000|vector<<8);break;}
Function *f=function(n->name);if(count!=f->nargs)error("wrong argument count for %s",n->name);
args_reverse(n->a);call(named("fn.",n->name));addi(6,count);break; }
default:error("unsupported expression kind %d",n->kind);
}
}
static void switch_cases(Node *n,Node **cases,int *count) {
if(!n)return;
if(n->kind==N_CASE) {
if(*count==256)error("too many switch cases");
for(int i=0;i<*count;i++) {
Node *previous=cases[i];
if(n->type && previous->type)error("duplicate default");
if(!n->type && !previous->type && (uint16_t)n->count==(uint16_t)previous->count)error("duplicate case value");
}
n->value=fresh();cases[(*count)++]=n;
}
if(n->kind!=N_SWITCH) {
switch_cases(n->a,cases,count);switch_cases(n->b,cases,count);
switch_cases(n->c,cases,count);switch_cases(n->d,cases,count);
}
switch_cases(n->next,cases,count);
}
static void stmt(Node *n) {
if(!n)return;
switch(n->kind) {
case N_BLOCK:for(Node *s=n->a;s;s=s->next)stmt(s);break;
case N_DECL:if(n->a){if(n->type==2)error("local array initializers unsupported");Node v={0};v.kind=N_ID;v.name=n->name;address(&v);push(0);expr(n->a);pop(1);emit(0x9040);}break;
case N_DECL_GROUP:for(Node *d=n->a;d;d=d->next)stmt(d);break;
case N_LABEL:define(user_label(n->name));stmt(n->b);break;
case N_GOTO:jump_name(user_label(n->name));break;
case N_CASE:if(!n->value)error("case/default outside switch");mark(n->value);stmt(n->b);break;
case N_SWITCH:{
Node *cases[256];int count=0,end=fresh(),fallback=end;
switch_cases(n->b,cases,&count);
expr(n->a);push(0);
for(int i=0;i<count;i++) {
Node *c=cases[i];if(c->type){fallback=c->value;continue;}
int next=fresh();literal(0,c->count,NULL);emit(0x6380);compare(T_EQ);
move(0,0);branch(2,next);addi(6,1);jump(c->value);mark(next);
}
addi(6,1);jump(fallback);
if(break_depth==64)error("break contexts nested too deeply");
break_targets[break_depth++]=end;stmt(n->b);break_depth--;mark(end);break;
}
case N_BLOCK:{
int saved=nlocals,base=scope_base;
scope_base=function_body?0:nlocals;function_body=0;
for(Node *s=n->a;s;s=s->next)stmt(s);
nlocals=saved;scope_base=base;break;
}
case N_DECL:
for(int i=scope_base;i<nlocals;i++)if(!strcmp(locals[i].name,n->name))error("duplicate local %s",n->name);
if(nlocals==MAX_SYMBOLS)error("too many locals");
locals[nlocals++]=(Variable){n->name,n->type,n->count,n->value,n->a,n->op};
if(n->a){
Node v={0};v.kind=N_ID;v.name=n->name;
if(n->type!=2){address(&v);push(0);expr(n->a);pop(1);emit(0x9040);}
else {
int index=0,total=type_size(array_of(n->op,n->count));
for(Node *value=n->a;value;value=value->next) {
if(index==total)error("too many array initializers");
address(&v);addi(0,index++);push(0);expr(value);pop(1);emit(0x9040);
}
if(index<total) {
address(&v);addi(0,index);move(1,0);literal(2,total-index,NULL);literal(0,0,NULL);
int loop=fresh();mark(loop);emit(0x9040);addi(1,1);addi(2,-1);branch(5,loop);
}
}
}break;
case N_RETURN:if(n->a)expr(n->a);else literal(0,0,NULL);jump(return_label);break;
case N_IF:{int other=fresh(),end=fresh();expr(n->a);move(0,0);branch(2,other);stmt(n->b);jump(end);mark(other);stmt(n->c);mark(end);break;}
case N_DO:{
int start=fresh(),step=fresh(),end=fresh();
if(loop_depth==64)error("loops nested too deeply");
if(break_depth==64)error("break contexts nested too deeply");
mark(start);loop_step[loop_depth]=step;loop_end[loop_depth++]=end;break_targets[break_depth++]=end;
stmt(n->b);loop_depth--;break_depth--;mark(step);expr(n->a);move(0,0);branch(5,start);mark(end);break;
}
case N_WHILE:case N_FOR:{int start=fresh(),step=fresh(),end=fresh();
int saved=nlocals,base=scope_base;
if(n->kind==N_FOR)scope_base=nlocals;
if(n->kind==N_FOR)stmt(n->a);
mark(start);Node *condition=n->kind==N_FOR?n->b:n->a;
if(condition){expr(condition);move(0,0);branch(2,end);}if(loop_depth==64)error("loops nested too deeply");
loop_step[loop_depth]=step;loop_end[loop_depth++]=end;stmt(n->kind==N_FOR?n->d:n->b);loop_depth--;
mark(step);if(n->kind==N_FOR&&n->c)expr(n->c);jump(start);mark(end);break;}
case N_BREAK:case N_CONTINUE:if(!loop_depth)error("break/continue outside loop");jump(n->kind==N_BREAK?loop_end[loop_depth-1]:loop_step[loop_depth-1]);break;
if(break_depth==64)error("break contexts nested too deeply");
loop_step[loop_depth]=step;loop_end[loop_depth++]=end;break_targets[break_depth++]=end;
stmt(n->kind==N_FOR?n->d:n->b);loop_depth--;break_depth--;
mark(step);if(n->kind==N_FOR&&n->c)expr(n->c);jump(start);mark(end);
nlocals=saved;scope_base=base;break;}
case N_BREAK:if(!break_depth)error("break outside loop/switch");jump(break_targets[break_depth-1]);break;
case N_CONTINUE:if(!loop_depth)error("continue outside loop");jump(loop_step[loop_depth-1]);break;
case N_EMPTY:break;
default:expr(n);
}
@@ -405,34 +833,59 @@ static void stmt(Node *n) {
static int frame_slots;
static void collect(Node *n) {
if(!n)return;
if(n->kind==N_DECL){for(int i=0;i<nlocals;i++)if(!strcmp(locals[i].name,n->name))error("shadowing/duplicate local %s",n->name);
if(nlocals==MAX_SYMBOLS)error("too many locals");
frame_slots+=n->count;locals[nlocals++]=(Variable){n->name,n->type,n->count,-frame_slots,n->a};}
if(n->kind==N_DECL){frame_slots+=n->type==2?type_size(array_of(n->op,n->count)):1;n->value=-frame_slots;}
collect(n->a);collect(n->b);collect(n->c);collect(n->d);collect(n->next);
}
static void compatible_function(Node *a,Node *b) {
if(a->type!=b->type)error("conflicting return type for %s",a->name);
if((a->kind==N_PROTOTYPE && a->op) || (b->kind==N_PROTOTYPE && b->op))return;
Node *x=a->a,*y=b->a;
while(x && y){if(x->type!=y->type)error("conflicting parameter type for %s",a->name);x=x->next;y=y->next;}
if(x || y)error("conflicting parameter count for %s",a->name);
}
static void generate(void) {
for(Node *n=top;n;n=n->next) {
if(n->kind==N_FUNCTION){if(nfunctions==MAX_SYMBOLS)error("too many functions");int count=0;for(Node *a=n->a;a;a=a->next)count++;
for(int i=0;i<nfunctions;i++)if(!strcmp(functions[i].name,n->name))error("duplicate function %s",n->name);
functions[nfunctions++]=(Function){n->name,n,count};}
else {if(nglobals==MAX_SYMBOLS)error("too many globals");for(int i=0;i<nglobals;i++)if(!strcmp(globals[i].name,n->name))error("duplicate global %s",n->name);
globals[nglobals++]=(Variable){n->name,n->type,n->count,0,n->a};}
else if(n->kind==N_DECL){if(nglobals==MAX_SYMBOLS)error("too many globals");for(int i=0;i<nglobals;i++)if(!strcmp(globals[i].name,n->name))error("duplicate global %s",n->name);
globals[nglobals++]=(Variable){n->name,n->type,n->count,0,n->a,n->op};}
}
for(Node *n=top;n;n=n->next)if(n->kind==N_PROTOTYPE || n->kind==N_FUNCTION) {
for(Node *other=n->next;other;other=other->next)
if((other->kind==N_PROTOTYPE || other->kind==N_FUNCTION) && !strcmp(n->name,other->name))compatible_function(n,other);
for(int i=0;i<nglobals;i++)if(!strcmp(n->name,globals[i].name))error("object/function name collision %s",n->name);
}
if(function("main")->nargs)error("main must take no arguments");
define("entry");literal(6,0xf000,NULL);literal(5,0,NULL);call("fn.main");emit(0xf000);
for(int i=0;i<nfunctions;i++) {
Function *f=&functions[i];nlocals=0;frame_slots=0;int arg=0;
Function *f=&functions[i];current_function=f->name;nlocals=0;frame_slots=0;int arg=0;
compiling_compare_helper=!strncmp(f->name,"__cmp_",6);
for(Node *a=f->node->a;a;a=a->next){if(!*a->name||a->type==2)error("named scalar/pointer parameters required");locals[nlocals++]=(Variable){a->name,a->type,1,2+arg++,NULL};}
for(Node *a=f->node->a;a;a=a->next){
if(!*a->name||a->type==2)error("named scalar/pointer parameters required");
for(int j=0;j<nlocals;j++)if(!strcmp(locals[j].name,a->name))error("duplicate parameter %s",a->name);
locals[nlocals++]=(Variable){a->name,a->type,1,2+arg++,NULL,a->op};
}
collect(f->node->b);if(frame_slots>4096)error("frame too large");return_label=fresh();define(named("fn.",f->name));
scope_base=0;function_body=1;
push(7);push(5);move(5,6);addi(6,-frame_slots);stmt(f->node->b);literal(0,0,NULL);mark(return_label);move(6,5);pop(5);pop(7);emit(0xe000);
}
nlocals=0;
for(int i=0;i<nglobals;i++){Variable *g=&globals[i];define(named("g.",g->name));Node *init=g->init;
for(int j=0;j<g->count;j++){emit(init?constant(init):0);if(init)init=init->next;}if(init)error("too many initializers for %s",g->name);}
for(int i=0;i<nstrings;i++){define(strings[i].name);for(char *p=strings[i].value;*p;p++)emit((unsigned char)*p);emit(0);}
int total=g->type==2?type_size(array_of(g->base,g->count)):g->count;
int element=g->type==2?g->base:g->type;
while(is_array(element))element=pointer_types[element-16].base;
for(int j=0;j<total;j++){
const char *target=NULL;int offset=0;
if(init && is_pointer(element) && global_address(init,&target,&offset)) {
fixups[nfixups++]=(Fixup){ncode,copy(target),offset};emit(0);
} else emit(init?constant(init):0);
if(init)init=init->next;
}if(init)error("too many initializers for %s",g->name);}
for(int i=0;i<nstrings;i++){define(strings[i].name);for(int j=0;j<strings[i].length;j++)emit((unsigned char)strings[i].value[j]);emit(0);}
compact_jumps();
if(ORIGIN+ncode>0x9000)error("kernel exceeds 0x9000 (code + data is %d words)",ncode);
for(int i=0;i<nfixups;i++){int found=0;for(int j=0;j<nlabels;j++)if(!strcmp(fixups[i].name,labels[j].name)) {code[fixups[i].index]=(uint16_t)labels[j].address;found=1;break;}
for(int i=0;i<nfixups;i++){int found=0;for(int j=0;j<nlabels;j++)if(!strcmp(fixups[i].name,labels[j].name)) {code[fixups[i].index]=(uint16_t)(labels[j].address+fixups[i].addend);found=1;break;}
if(!found)error("unresolved symbol %s",fixups[i].name);}
}
static char *read_file(const char *path) {
+4
View File
@@ -36,6 +36,10 @@ int main(int argc,char **argv) {
if(argc==2&&!strcmp(argv[1],"--test")) {
run("gcc -std=c11 -O2 -Wall -Wextra -Werror tests/test_os.c -o build/test_os" EXE);
run(BUILD_DIR "test_os" EXE);
#ifdef _WIN32
run("gcc -std=c11 -O2 -Wall -Wextra -Werror tests/test_console.c -o build/test_console.exe");
run("build\\test_console.exe");
#endif
} else if(argc==2) run(BOB_COMMAND " --boot build/kernel.b16");
return 0;
}