Compare commits

..

No commits in common. "main" and "1.0.0" have entirely different histories.
main ... 1.0.0

53 changed files with 1149 additions and 1051 deletions

3
.gitmodules vendored
View File

@ -1,3 +0,0 @@
[submodule "dependencies/tlibc"]
path = dependencies/tlibc
url = https://timerix.ddns.net/git/Timerix/tlibc.git

View File

@ -1,15 +0,0 @@
{
"configurations": [
{
"name": "all",
"defines": [],
"includePath": [
"dependencies/tlibc/include",
"src",
"${default}"
],
"cStandard": "c11"
}
],
"version": 4
}

10
.vscode/launch.json vendored
View File

@ -2,20 +2,16 @@
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{ {
"name": "gdb_debug", "name": "(gdb) Debug",
"type": "cppdbg", "type": "cppdbg",
"request": "launch", "request": "launch",
"program": "${workspaceFolder}/bin/tcpu", "program": "${workspaceFolder}/bin/tcpu",
"windows": { "program": "${workspaceFolder}/bin/tcpu.exe" }, "windows": { "program": "${workspaceFolder}/bin/tcpu.exe" },
"args": [ "args": [ "-c", "../examples/s.tasm", "o.bin", "--debug" ],
"-c", "../examples/video.tasm", "o.bin",
"-i", "o.bin", "--debug", "--video"
],
"cwd": "${workspaceFolder}/bin", "cwd": "${workspaceFolder}/bin",
"preLaunchTask": "build_exec_dbg", "preLaunchTask": "build_exec_dbg",
"stopAtEntry": false, "stopAtEntry": false,
"externalConsole": false, "externalConsole": false,
"internalConsoleOptions": "neverOpen",
"MIMode": "gdb", "MIMode": "gdb",
"miDebuggerPath": "gdb", "miDebuggerPath": "gdb",
"setupCommands": [ "setupCommands": [
@ -30,4 +26,4 @@
] ]
} }
] ]
} }

View File

@ -2,80 +2,37 @@
Machine code interpreter written in pure C. Can execute programs up to 1 MEGABYTE (1048576 bytes) in size!!! Machine code interpreter written in pure C. Can execute programs up to 1 MEGABYTE (1048576 bytes) in size!!!
## Building ## Building
1. Clone repo 1. Install [cbuild](https://timerix.ddns.net:3322/Timerix/cbuild.git)
``` 2. ```sh
git clone --recurse-submodules https://timerix.ddns.net/git/Timerix/tcpu.git
```
2. Install [cbuild](https://timerix.ddns.net/git/Timerix/cbuild.git)
3. Install [SDL3](https://github.com/libsdl-org/SDL) and [SDL3_image](https://github.com/libsdl-org/SDL_image) from package manager or source.
3. ```sh
cbuild build_exec_dbg cbuild build_exec_dbg
``` ```
## Assembly language ## Assembly language
### Registers
| name | code | size (bits) |
|-----|------|----|
| rax | 0x01 | 64 |
| eax | 0x02 | 32 |
| ax | 0x04 | 16 |
| al | 0x07 | 8 |
| ah | 0x08 | 8 |
| |
| rbx | 0x11 | 64 |
| ebx | 0x12 | 32 |
| bx | 0x14 | 16 |
| bl | 0x17 | 8 |
| bh | 0x18 | 8 |
| |
| rcx | 0x21 | 64 |
| ecx | 0x22 | 32 |
| cx | 0x24 | 16 |
| cl | 0x27 | 8 |
| ch | 0x28 | 8 |
| |
| rdx | 0x31 | 64 |
| edx | 0x32 | 32 |
| dx | 0x34 | 16 |
| dl | 0x37 | 8 |
| dh | 0x38 | 8 |
### Instructions ### Instructions
| name | arguments | details | | code | name | arguments | details |
|------|-----------|---------| |------|------|-----------|---------|
| NOP | | ignored instruction | | 00 | NOP | | ignored instruction |
| EXIT | | stop the program with exit code in `eax` | | 01 | PUSH | `dst_register`, `value_size(bytes)`, `value` | push constant value into `dst_register` |
| SYS | | call system function | | 02 | MOV | `dst_register`, `src_register` | copy value from `src_register` to `dst_register`
| | | 03 | ADD | `dst_register`, `src_register` | `dst` += `src` |
| MOVC | `dst_register`, `const_value` | push constant value into `dst_register` | | 04 | SUB | `dst_register`, `src_register` | `dst` -= `src` |
| MOVR | `dst_register`, `src_register` | copy value from `src_register` to `dst_register` | | 05 | MUL | `dst_register`, `src_register` | `dst` *= `src` |
| | | 06 | DIV | `dst_register`, `src_register` | `dst` /= `src` |
| ADD | `dst_register`, `src_register` | `dst += src` | | 07 | MOD | `dst_register`, `src_register` | `dst` %= `src` |
| SUB | `dst_register`, `src_register` | `dst -= src` | | 08 | SYS | | call system function |
| MUL | `dst_register`, `src_register` | `dst *= src` | | 09 | EXIT | | stop the program with exit code in `ax` |
| DIV | `dst_register`, `src_register` | `dst /= src` |
| MOD | `dst_register`, `src_register` | `dst %= src` | ### Registers
| | | code | name | size (bits) |
| EQ | `dst_register`, `src_register` | `cmp_flag = dst == src` | |------|------|-------------|
| NE | `dst_register`, `src_register` | `cmp_flag = dst != src` | | 00 | ax | 32 |
| LT | `dst_register`, `src_register` | `cmp_flag = dst < src` | | 01 | bx | 32 |
| LE | `dst_register`, `src_register` | `cmp_flag = dst <= src` | | 02 | cx | 32 |
| GT | `dst_register`, `src_register` | `cmp_flag = dst > src` | | 03 | dx | 32 |
| GE | `dst_register`, `src_register` | `cmp_flag = dst >= src` |
| |
| NOT | `dst_register` | `dst = !dst` |
| INV | `dst_register` | `dst = ~dst` |
| OR | `dst_register`, `src_register` | `dst = dst \| src` |
| XOR | `dst_register`, `src_register` | `dst = dst ^ src` |
| AND | `dst_register`, `src_register` | `dst = dst & src` |
| |
| JMP | `dst_address_const` | goto `dst` |
| JNZ | `dst_address_const` | if (`cmp_flag` != 0) goto `dst` |
| JZ | `dst_address_const` | if (`cmp_flag` == 0) goto `dst` |
### System functions ### System functions
To call a system function you need to push values to registers and write `SYS` opcode. The return value of a function will will be avaliable in `ax` after call. To call a system function you need to push values to registers and write `SYS` opcode. The return value of a function will will be avaliable in `ax` after call.
| name | `al` | `ah` | `rbx` | `ecx` | details | | `ax` | name | `bx` | `cx` | `dx` | details |
|------|------|------|-------|-------|---------| |-----------|------|----|----|----|---------|
| read | 0 | file number | buffer pointer | buffer size | read data from file | | 0 | read | file number | buffer pointer | buffer size | read data from file |
| write | 1 | file number | buffer pointer | buffer size | write data to file | | 1 | write | file number | buffer pointer | buffer size | write data to file |

11
TODO.md
View File

@ -1,11 +0,0 @@
# TODO List
- add negative number arguments support
- add movc char support
- add padding to compilation
- VM debug log
- add display syscalls
- change section binary format:
1. code
2. exit instruction with code ERR_U_FORGOT_TO_CALL_EXIT
3. data
- arguments validation for each instruction

1
dependencies/tlibc vendored

@ -1 +0,0 @@
Subproject commit c415e2ca8ff51f41984ace8fe796187e6ad0fa27

View File

@ -1,19 +0,0 @@
#!/usr/bin/env bash
###########################################################
# Copy this file to your cbuild DEPENDENCY_CONFIGS_DIR #
# and enable it (ENABLED_DEPENDENCIES=tlibc). #
###########################################################
DEP_WORKING_DIR="dependencies/tlibc"
DEP_PRE_BUILD_COMMAND=""
DEP_POST_BUILD_COMMAND=""
if [[ "$TASK" = *_dbg ]]; then
dep_build_target="build_static_lib_dbg"
else
dep_build_target="build_static_lib"
fi
DEP_BUILD_COMMAND="cbuild $dep_build_target"
DEP_CLEAN_COMMAND="cbuild clean"
DEP_DYNAMIC_OUT_FILES=""
DEP_STATIC_OUT_FILES="bin/tlibc.a"
DEP_OTHER_OUT_FILES=""
PRESERVE_OUT_DIRECTORY_STRUCTURE=false

View File

@ -1,32 +0,0 @@
/*
Example of behavior change depending on some condition
*/
.main:
movc ax 1
movc bx 2
gt ax bx
jnz @true
jz @false
.true:
const8 true.msg "true\n"
movc rbx @true.msg
movc ecx #true.msg
jmp @print
.false
const8 false.msg "false\n"
movc rbx @false.msg
movc ecx #false.msg
jmp @print
.print:
movc al 1
movc ah 1
sys
jmp @end
.end:
movc ax 0
exit

View File

@ -1,22 +0,0 @@
/*
Example of self-repeating code section
*/
.main:
movc dx 0; // loop counter
.loop
const8 datum "ITERATION!!! "
movc al 1
movc ah 1
movc rbx @datum
movc ecx #datum
sys
movc cx 1
add dx cx
movc cx 8
lt dx cx
jnz @loop
movc rax 0
exit

16
examples/s.tasm Normal file
View File

@ -0,0 +1,16 @@
/*
"hello world" program in my assembly language
*/
.data:
// named array of 8-bit values
const8 msg "Hello, World :3\0"
.main:
push ax 1; // sys_write
push bx 1; // stdout
push cx @msg; // address of msg data
push dx #msg; // size of msg data
sys
push ax 0
exit

View File

@ -1,16 +0,0 @@
/*
"hello world" program in my assembly language
*/
.data:
// named array of 8-bit values
const8 msg "Hello, World!\n"
.main:
movc al 1; // sys_write
movc ah 1; // stdout
movc rbx @msg; // address of msg data
movc ecx #msg; // size of msg data
sys
movc ax 0
exit

View File

@ -1,7 +0,0 @@
/*
Example of graphical application
*/
.main:
//TODO: add a way to access Event struct's fields
exit

View File

@ -1,21 +1,22 @@
#!/usr/bin/env bash #!/usr/bin/env bash
CBUILD_VERSION=2.2.3 CBUILD_VERSION=2.1.4
CONFIG_VERSION=1
PROJECT="tcpu" PROJECT="tcpu"
CMP_C="gcc" CMP_C="gcc"
CMP_CPP="g++" CMP_CPP="g++"
STD_C="c11" STD_C="c11"
STD_CPP="c++11" STD_CPP="c++11"
WARN_C="-Wall -Wextra -Werror=return-type -Werror=pointer-arith -Wno-unused-parameter" WARN_C="-Wall -Wextra -Wno-unused-parameter"
WARN_CPP="-Wall -Wextra -Werror=return-type -Werror=pointer-arith -Wno-unused-parameter" WARN_CPP="-Wall -Wextra -Wno-unused-parameter"
SRC_C="$(find src -name '*.c')" SRC_C="$(find src -name '*.c')"
SRC_CPP="$(find src -name '*.cpp')" SRC_CPP="$(find src -name '*.cpp')"
# Directory with dependency configs. # Directory with dependency configs.
# See cbuild/example_dependency_configs # See cbuild/example_dependency_configs
DEPENDENCY_CONFIGS_DIR='dependencies' DEPENDENCY_CONFIGS_DIR='.'
# List of dependency config files in DEPENDENCY_CONFIGS_DIR separated by space. # List of dependency config files in DEPENDENCY_CONFIGS_DIR separated by space.
ENABLED_DEPENDENCIES='tlibc' ENABLED_DEPENDENCIES=''
# OBJDIR structure: # OBJDIR structure:
# ├── objects/ - Compiled object files. Cleans on each call of build task # ├── objects/ - Compiled object files. Cleans on each call of build task
@ -26,19 +27,18 @@ OBJDIR="obj"
OUTDIR="bin" OUTDIR="bin"
STATIC_LIB_FILE="lib$PROJECT.a" STATIC_LIB_FILE="lib$PROJECT.a"
INCLUDE="-Isrc -Idependencies/tlibc/include"
# OS-specific options # OS-specific options
case "$OS" in case "$OS" in
WINDOWS) WINDOWS)
EXEC_FILE="$PROJECT.exe" EXEC_FILE="$PROJECT.exe"
SHARED_LIB_FILE="$PROJECT.dll" SHARED_LIB_FILE="$PROJECT.dll"
LINKER_LIBS="-lSDL3_image -lSDL3" # example: "-I./"
INCLUDE=""
;; ;;
LINUX) LINUX)
EXEC_FILE="$PROJECT" EXEC_FILE="$PROJECT"
SHARED_LIB_FILE="$PROJECT.so" SHARED_LIB_FILE="$PROJECT.so"
LINKER_LIBS="-lSDL3_image -lSDL3" INCLUDE=""
;; ;;
*) *)
error "operating system $OS has no configuration variants" error "operating system $OS has no configuration variants"
@ -57,7 +57,7 @@ case "$TASK" in
# -fdata-sections -ffunction-sections -Wl,--gc-sections removes unused code # -fdata-sections -ffunction-sections -Wl,--gc-sections removes unused code
C_ARGS="-O2 -flto=auto -fuse-linker-plugin -fprofile-use -fprofile-prefix-path=$(realpath $OBJDIR)/objects -fdata-sections -ffunction-sections -Wl,--gc-sections" C_ARGS="-O2 -flto=auto -fuse-linker-plugin -fprofile-use -fprofile-prefix-path=$(realpath $OBJDIR)/objects -fdata-sections -ffunction-sections -Wl,--gc-sections"
CPP_ARGS="$C_ARGS" CPP_ARGS="$C_ARGS"
LINKER_ARGS="$CPP_ARGS $LINKER_LIBS" LINKER_ARGS="$CPP_ARGS"
PRE_TASK_SCRIPT= PRE_TASK_SCRIPT=
TASK_SCRIPT=cbuild/default_tasks/build_exec.sh TASK_SCRIPT=cbuild/default_tasks/build_exec.sh
POST_TASK_SCRIPT= POST_TASK_SCRIPT=
@ -66,7 +66,7 @@ case "$TASK" in
build_exec_dbg) build_exec_dbg)
C_ARGS="-O0 -g3" C_ARGS="-O0 -g3"
CPP_ARGS="$C_ARGS" CPP_ARGS="$C_ARGS"
LINKER_ARGS="$CPP_ARGS $LINKER_LIBS" LINKER_ARGS="$CPP_ARGS"
PRE_TASK_SCRIPT= PRE_TASK_SCRIPT=
TASK_SCRIPT=cbuild/default_tasks/build_exec.sh TASK_SCRIPT=cbuild/default_tasks/build_exec.sh
POST_TASK_SCRIPT= POST_TASK_SCRIPT=
@ -75,7 +75,7 @@ case "$TASK" in
build_shared_lib) build_shared_lib)
C_ARGS="-O2 -fpic -flto -shared" C_ARGS="-O2 -fpic -flto -shared"
CPP_ARGS="$C_ARGS" CPP_ARGS="$C_ARGS"
LINKER_ARGS="$CPP_ARGS $LINKER_LIBS -Wl,-soname,$SHARED_LIB_FILE" LINKER_ARGS="$CPP_ARGS -Wl,-soname,$SHARED_LIB_FILE"
PRE_TASK_SCRIPT= PRE_TASK_SCRIPT=
TASK_SCRIPT=cbuild/default_tasks/build_shared_lib.sh TASK_SCRIPT=cbuild/default_tasks/build_shared_lib.sh
POST_TASK_SCRIPT= POST_TASK_SCRIPT=
@ -84,7 +84,7 @@ case "$TASK" in
build_shared_lib_dbg) build_shared_lib_dbg)
C_ARGS="-O0 -g3 -fpic -shared" C_ARGS="-O0 -g3 -fpic -shared"
CPP_ARGS="$C_ARGS" CPP_ARGS="$C_ARGS"
LINKER_ARGS="$CPP_ARGS $LINKER_LIBS -Wl,-soname,$SHARED_LIB_FILE" LINKER_ARGS="$CPP_ARGS -Wl,-soname,$SHARED_LIB_FILE"
PRE_TASK_SCRIPT= PRE_TASK_SCRIPT=
TASK_SCRIPT=cbuild/default_tasks/build_shared_lib.sh TASK_SCRIPT=cbuild/default_tasks/build_shared_lib.sh
POST_TASK_SCRIPT= POST_TASK_SCRIPT=
@ -125,7 +125,7 @@ case "$TASK" in
# -fprofile-prefix-path sets path where profiling info about objects will be saved # -fprofile-prefix-path sets path where profiling info about objects will be saved
C_ARGS="-O2 -flto=auto -fuse-linker-plugin -fprofile-generate -fprofile-prefix-path=$(realpath $OBJDIR)/objects" C_ARGS="-O2 -flto=auto -fuse-linker-plugin -fprofile-generate -fprofile-prefix-path=$(realpath $OBJDIR)/objects"
CPP_ARGS="$C_ARGS" CPP_ARGS="$C_ARGS"
LINKER_ARGS="$CPP_ARGS $LINKER_LIBS" LINKER_ARGS="$CPP_ARGS"
PRE_TASK_SCRIPT=cbuild/default_tasks/build_exec.sh PRE_TASK_SCRIPT=cbuild/default_tasks/build_exec.sh
TASK_SCRIPT=cbuild/default_tasks/profile.sh TASK_SCRIPT=cbuild/default_tasks/profile.sh
POST_TASK_SCRIPT= POST_TASK_SCRIPT=
@ -138,7 +138,7 @@ case "$TASK" in
# -pg adds code to executable, that generates file containing function call info (gmon.out) # -pg adds code to executable, that generates file containing function call info (gmon.out)
C_ARGS="-O2 -flto=auto -fuse-linker-plugin -pg" C_ARGS="-O2 -flto=auto -fuse-linker-plugin -pg"
CPP_ARGS="$C_ARGS" CPP_ARGS="$C_ARGS"
LINKER_ARGS="$CPP_ARGS $LINKER_LIBS" LINKER_ARGS="$CPP_ARGS"
PRE_TASK_SCRIPT=cbuild/default_tasks/build_exec.sh PRE_TASK_SCRIPT=cbuild/default_tasks/build_exec.sh
TASK_SCRIPT=cbuild/default_tasks/gprof.sh TASK_SCRIPT=cbuild/default_tasks/gprof.sh
POST_TASK_SCRIPT= POST_TASK_SCRIPT=
@ -152,7 +152,7 @@ case "$TASK" in
# -pg adds code to executable, that generates file containing function call info (gmon.out) # -pg adds code to executable, that generates file containing function call info (gmon.out)
C_ARGS="-O2 -flto=auto -fuse-linker-plugin" C_ARGS="-O2 -flto=auto -fuse-linker-plugin"
CPP_ARGS="$C_ARGS" CPP_ARGS="$C_ARGS"
LINKER_ARGS="$CPP_ARGS $LINKER_LIBS" LINKER_ARGS="$CPP_ARGS"
PRE_TASK_SCRIPT=cbuild/default_tasks/build_exec.sh PRE_TASK_SCRIPT=cbuild/default_tasks/build_exec.sh
TASK_SCRIPT=cbuild/default_tasks/callgrind.sh TASK_SCRIPT=cbuild/default_tasks/callgrind.sh
POST_TASK_SCRIPT= POST_TASK_SCRIPT=
@ -162,7 +162,7 @@ case "$TASK" in
OUTDIR="$OUTDIR/sanitize" OUTDIR="$OUTDIR/sanitize"
C_ARGS="-O0 -g3 -fsanitize=undefined,address" C_ARGS="-O0 -g3 -fsanitize=undefined,address"
CPP_ARGS="$C_ARGS" CPP_ARGS="$C_ARGS"
LINKER_ARGS="$CPP_ARGS $LINKER_LIBS" LINKER_ARGS="$CPP_ARGS"
PRE_TASK_SCRIPT=cbuild/default_tasks/build_exec.sh PRE_TASK_SCRIPT=cbuild/default_tasks/build_exec.sh
TASK_SCRIPT=cbuild/default_tasks/exec.sh TASK_SCRIPT=cbuild/default_tasks/exec.sh
POST_TASK_SCRIPT= POST_TASK_SCRIPT=

View File

@ -1,85 +0,0 @@
#include <SDL3/SDL.h>
#include <SDL3_image/SDL_image.h>
#include "Display.h"
#include "tcpu_version.h"
typedef struct Display {
i32 width;
i32 height;
SDL_Window* window;
SDL_Renderer* renderer;
} Display;
static SDL_InitState _sdl_init_state = {0};
static Display _d = {0};
static cstr _title = "TCPU v" TCPU_VERSION_CSTR;
bool Display_init(i32 w, i32 h, DisplayFlags flags){
_d.width = w;
_d.height = h;
_d.window = NULL;
_d.renderer = NULL;
if (SDL_ShouldInit(&_sdl_init_state)) {
bool sdl_initialized = SDL_Init(SDL_INIT_VIDEO);
SDL_SetInitialized(&_sdl_init_state, sdl_initialized);
if(!sdl_initialized)
return false;
}
SDL_WindowFlags window_flags = SDL_WINDOW_ALWAYS_ON_TOP;
if(!SDL_CreateWindowAndRenderer(_title, _d.width, _d.height, window_flags, &_d.window, &_d.renderer)){
return false;
}
return true;
}
void Display_destroy(){
SDL_DestroyRenderer(_d.renderer);
SDL_DestroyWindow(_d.window);
// if (SDL_ShouldQuit(&_sdl_init_state)) {
// SDL_Quit();
// SDL_SetInitialized(&_sdl_init_state, false);
// }
}
NULLABLE(cstr) Display_getError(){
return SDL_GetError();
}
bool Display_setSize(u32 w, u32 h){
_d.width = w;
_d.height = h;
return SDL_SetWindowSize(_d.window, w, h);
}
bool Display_setFullScreenMode(bool value){
return SDL_SetWindowFullscreen(_d.window, value);
}
bool Display_setDrawingColor(ColorRGBA color){
return SDL_SetRenderDrawColor(_d.renderer, color.r, color.g, color.b, color.a);
}
bool Display_clear(){
return SDL_RenderClear(_d.renderer);
}
#define Rect_copy(DST, SRC) {\
DST.x = SRC.x;\
DST.y = SRC.y;\
DST.w = SRC.w;\
DST.h = SRC.h;\
}
bool Display_fillRect(Rect rect) {
SDL_FRect sdl_rect;
Rect_copy(sdl_rect, rect);
return SDL_RenderFillRect(_d.renderer, &sdl_rect);
}
bool Display_swapBuffers(){
return SDL_RenderPresent(_d.renderer);
}

View File

@ -1,30 +0,0 @@
#pragma once
#include "tlibc/std.h"
#include "tlibc/string/str.h"
typedef struct Rect {
i32 x, y;
i32 w, h;
} Rect;
#define Rect_create(X, Y, W, H) ((Rect){ .x = X, .y = Y, .w = W, .h = H})
typedef struct ColorRGBA {
u8 r, g, b, a;
} ColorRGBA;
#define ColorRGBA_create(R, G, B, A) ((ColorRGBA){ .r = R, .g = G, .b = B, .a = A })
typedef enum DisplayFlags {
DisplayFlags_Default = 0
} DisplayFlags;
bool Display_init(i32 w, i32 h, DisplayFlags flags);
void Display_destroy();
NULLABLE(cstr) Display_getError();
bool Display_setSize(u32 w, u32 h);
bool Display_setFullScreenMode(bool value);
bool Display_setDrawingColor(ColorRGBA color);
bool Display_clear();
bool Display_fillRect(Rect rect);
bool Display_swapBuffers();

View File

@ -1,7 +1,7 @@
#include "VM.h" #include "VM.h"
#include "instructions/instructions.h" #include "../instructions/instructions.h"
void VM_construct(VM* vm){ void VM_init(VM* vm){
memset(vm, 0, sizeof(VM)); memset(vm, 0, sizeof(VM));
vm->state = VMState_Initialized; vm->state = VMState_Initialized;
} }
@ -50,7 +50,7 @@ i32 VM_boot(VM* vm){
u8 opcode = vm->data[vm->current_pos]; u8 opcode = vm->data[vm->current_pos];
const Instruction* instr = Instruction_getByOpcode(opcode); const Instruction* instr = Instruction_getByOpcode(opcode);
// printfe("[at 0x%x] %02X %s\n", (u32)vm->current_pos, opcode, instr->name.data); // printfe("[at 0x%x] %02X %s\n", (u32)vm->current_pos, opcode, instr->name);
if(instr == NULL){ if(instr == NULL){
VM_setError(vm, "unknown opcode %02X", opcode); VM_setError(vm, "unknown opcode %02X", opcode);
return -1; return -1;
@ -60,7 +60,7 @@ i32 VM_boot(VM* vm){
i32 bytes_read = instr->implementation(vm); i32 bytes_read = instr->implementation(vm);
// internal error occured // internal error occured
if(bytes_read < 0) if(bytes_read < 0)
return bytes_read; return -1;
if(vm->state == VMState_Exited) if(vm->state == VMState_Exited)
break; break;
@ -72,7 +72,7 @@ i32 VM_boot(VM* vm){
} }
// exit code of the program should be in ax register // exit code of the program should be in ax register
return vm->registers.a.ex; return vm->ax.i32v;
} }
bool VM_dataRead(VM* vm, void* dst, size_t pos, size_t size){ bool VM_dataRead(VM* vm, void* dst, size_t pos, size_t size){
@ -84,25 +84,6 @@ bool VM_dataRead(VM* vm, void* dst, size_t pos, size_t size){
return false; return false;
} }
void* addr = vm->data + pos; memcpy(dst, vm->data + pos, size);
memcpy(dst, addr, size);
return true; return true;
} }
void VM_registerRead(VM* vm, void* dst, RegisterCode code) {
u8 index = code / 0x10;
u8 part = code & 0xf;
u8 offset = part / 8;
u8 size = 8 / part;
void* addr = (u8*)(&vm->registers.array[index]) + offset;
memcpy(dst, addr, size);
}
void VM_registerWrite(VM* vm, void* src, RegisterCode code){
u8 index = code / 0x10;
u8 part = code & 0xf;
u8 offset = part / 8;
u8 size = 8 / part;
void* addr = (u8*)(&vm->registers.array[index]) + offset;
memcpy(addr, src, size);
}

View File

@ -1,15 +1,30 @@
#pragma once #pragma once
#include "tlibc/std.h" #include "../std.h"
#include "tlibc/string/str.h" #include "../string/str.h"
#include "instructions/registers.h"
typedef union Register { typedef union Register {
u64 rx; u32 u32v;
u32 ex; i32 i32v;
u16 x; f32 f32v;
struct { struct {
u8 l; u16 u16v0;
u8 h; u16 u16v1;
};
struct {
i16 i16v0;
i16 i16v1;
};
struct {
u8 u8v0;
u8 u8v1;
u8 u8v2;
u8 u8v3;
};
struct {
i8 i8v0;
i8 i8v1;
i8 i8v2;
i8 i8v3;
}; };
} Register; } Register;
@ -23,17 +38,13 @@ typedef enum VMState {
typedef struct VM { typedef struct VM {
union { union {
struct { struct {
Register a; Register ax;
Register b; Register bx;
Register c; Register cx;
Register d; Register dx;
}; };
Register array[4]; Register registers[4];
} registers; };
struct {
bool cmp; // result of comparison operation
} flags;
VMState state; VMState state;
char* NULLABLE(error_message); // not null on if state == VMState_InternalError char* NULLABLE(error_message); // not null on if state == VMState_InternalError
@ -43,7 +54,7 @@ typedef struct VM {
size_t current_pos; size_t current_pos;
} VM; } VM;
void VM_construct(VM* vm); void VM_init(VM* vm);
/// @brief Loads a program from the buffer. /// @brief Loads a program from the buffer.
/// @param data buffer starting with machine code /// @param data buffer starting with machine code
@ -55,8 +66,6 @@ bool VM_setMemory(VM* vm, u8* data, size_t size);
i32 VM_boot(VM* vm); i32 VM_boot(VM* vm);
bool VM_dataRead(VM* vm, void* dst, size_t pos, size_t size); bool VM_dataRead(VM* vm, void* dst, size_t pos, size_t size);
void VM_registerRead(VM* vm, void* dst, RegisterCode code);
void VM_registerWrite(VM* vm, void* src, RegisterCode code);
#define VM_setError(vm, format, ...) _VM_setError(vm, __func__, format ,##__VA_ARGS__) #define VM_setError(vm, format, ...) _VM_setError(vm, __func__, format ,##__VA_ARGS__)
void _VM_setError(VM* vm, cstr context, cstr format, ...) __attribute__((__format__(__printf__, 3, 4))); void _VM_setError(VM* vm, cstr context, cstr format, ...) __attribute__((__format__(__printf__, 3, 4)));

24
src/collections/Array.h Normal file
View File

@ -0,0 +1,24 @@
#pragma once
#include "../std.h"
#define Array_construct(T, DATA, LEN) ((Array_##T){ .data = DATA, .len = LEN })
/// creates Array_##T from a const array
#define ARRAY(T, A...) Array_construct(T, ((T[])A), ARRAY_SIZE(((T[])A)))
#define Array_declare(T)\
typedef struct Array_##T {\
T* data;\
u32 len;\
} Array_##T;\
\
static inline Array_##T Array_##T##_alloc(u32 len){\
return Array_construct(T, (T*)malloc(len * sizeof(T)), len);\
}\
static inline void Array_##T##_realloc(Array_##T* ptr, u32 new_len){\
ptr->data = (T*)realloc(ptr->data, new_len * sizeof(T));\
ptr->len = new_len;\
}
Array_declare(u8)
Array_declare(u32)

140
src/collections/HashMap.h Normal file
View File

@ -0,0 +1,140 @@
#pragma once
#include "../std.h"
#include "../string/str.h"
#include "Array.h"
#include "List.h"
//TODO: sorting of bucket and binary search
//TODO: delayed deletion
#define __HashMap_HASH_FUNC str_hash32
#define __HashMapBucket_MAX_LEN 16
#define HashMap_DESTROY_VALUE_FUNC_NULL ((void (*)(void*))NULL)
/// call this in a header file
///@param T Value type
#define HashMap_declare(T)\
typedef struct KeyValue_##T {\
str key;\
T value;\
u32 hash;\
} KeyValue_##T;\
\
List_declare(KeyValue_##T);\
\
typedef struct HashMapBucket_##T {\
List_KeyValue_##T kvs;\
} HashMapBucket_##T;\
\
typedef struct HashMap_##T {\
HashMapBucket_##T* table;\
u32 height;\
u16 height_n;\
} HashMap_##T;\
\
void HashMap_##T##_alloc(HashMap_##T* ptr);\
void HashMap_##T##_free(HashMap_##T* ptr);\
T* NULLABLE(HashMap_##T##_tryGetPtr)(HashMap_##T* ptr, str key);\
bool HashMap_##T##_tryPush(HashMap_##T* ptr, str key, T value);\
bool HashMap_##T##_tryDelete(HashMap_##T* ptr, str key);\
/// call this in a source code file
///@param T Value type
///@param DESTROY_VALUE_FUNC `void foo (T*)` or HashMap_DESTROY_VALUE_FUNC_NULL
#define HashMap_define(T, DESTROY_VALUE_FUNC)\
List_define(KeyValue_##T);\
\
static const Array_u32 __HashMap_##T##_heights = ARRAY(u32, {\
17, 31, 61, 127, 257, 521, 1021, 2053, 4099, 8191, 16381, 32771,\
65521, 131071, 262147, 524287, 1048583, 2097169, 4194319,\
8388617, 16777213, 33554467, 67108859, 134217757, 268435493\
});\
\
void HashMap_##T##_alloc(HashMap_##T* ptr){\
ptr->height_n = 0;\
ptr->height = __HashMap_##T##_heights.data[0];\
ptr->table = (HashMapBucket_##T*)malloc(ptr->height * sizeof(HashMapBucket_##T));\
memset(ptr->table, 0, ptr->height * sizeof(HashMapBucket_##T));\
}\
\
void HashMap_##T##_free(HashMap_##T* ptr){\
for(u32 i = 0; i < ptr->height; i++){\
for(u32 j = 0; j < ptr->table[i].kvs.len; j++){\
KeyValue_##T* kv_ptr = &ptr->table[i].kvs.data[j];\
if(DESTROY_VALUE_FUNC){\
DESTROY_VALUE_FUNC(&kv_ptr->value);\
}\
free(kv_ptr->key.data);\
}\
\
free(ptr->table[i].kvs.data);\
}\
\
free(ptr->table);\
}\
\
T* NULLABLE(HashMap_##T##_tryGetPtr)(HashMap_##T* ptr, str key){\
u32 hash = __HashMap_HASH_FUNC(key);\
HashMapBucket_##T* bu = &ptr->table[hash % ptr->height];\
for(u32 i = 0; i < bu->kvs.len; i++){\
if(bu->kvs.data[i].hash == hash && str_equals(bu->kvs.data[i].key, key)){\
return &bu->kvs.data[i].value;\
}\
}\
\
return NULL;\
}\
\
bool HashMap_##T##_tryPush(HashMap_##T* ptr, str key, T value){\
u32 hash = __HashMap_HASH_FUNC(key);\
HashMapBucket_##T* bu = &ptr->table[hash % ptr->height];\
for(u32 i = 0; i < bu->kvs.len; i++){\
if(bu->kvs.data[i].hash == hash && str_equals(bu->kvs.data[i].key, key)){\
return false;\
}\
}\
\
if(bu->kvs.len >= __HashMapBucket_MAX_LEN){\
u32 height_expanded_n = ptr->height_n + 1;\
if(height_expanded_n >= __HashMap_##T##_heights.len){\
printf("ERROR: HashMap_" #T " IS FULL\n");\
return false;\
}\
\
u32 height_expanded = __HashMap_##T##_heights.data[height_expanded_n];\
HashMapBucket_##T* table_expanded = (HashMapBucket_##T*)malloc(height_expanded * sizeof(HashMapBucket_##T));\
memset(table_expanded, 0, height_expanded * sizeof(HashMapBucket_##T));\
for(u32 i = 0; i < height_expanded; i++){\
for(u32 j = 0; j < ptr->table[i].kvs.len; j++){\
KeyValue_##T kv = ptr->table[i].kvs.data[j];\
List_KeyValue_##T##_push(&table_expanded[kv.hash % height_expanded].kvs, kv);\
}\
\
free(ptr->table[i].kvs.data);\
}\
free(ptr->table);\
ptr->table = table_expanded;\
ptr->height = height_expanded;\
ptr->height_n = height_expanded_n;\
bu = &ptr->table[hash % ptr->height];\
}\
\
KeyValue_##T kv = { .key = str_copy(key), .value = value, .hash = hash };\
List_KeyValue_##T##_push(&bu->kvs, kv);\
return true;\
}\
\
bool HashMap_##T##_tryDelete(HashMap_##T* ptr, str key){\
u32 hash = __HashMap_HASH_FUNC(key);\
HashMapBucket_##T* bu = &ptr->table[hash % ptr->height];\
for(u32 i = 0; i < bu->kvs.len; i++){\
if(bu->kvs.data[i].hash == hash && str_equals(bu->kvs.data[i].key, key)){\
return List_KeyValue_##T##_tryRemoveAt(&bu->kvs, i);\
}\
}\
\
return false;\
}

4
src/collections/List.c Normal file
View File

@ -0,0 +1,4 @@
#include "List.h"
List_define(u32);
List_define(u8);

75
src/collections/List.h Normal file
View File

@ -0,0 +1,75 @@
#pragma once
#include "../std.h"
// minimal max_len after initial (0)
#define __List_min_size 16
#define List_declare(T)\
typedef struct List_##T {\
T* data;\
u32 len;\
u32 max_len;\
} List_##T;\
\
static inline List_##T List_##T##_construct(T* data_ptr, u32 len, u32 max_len) {\
return (List_##T){ .data = data_ptr, .len = len, .max_len = max_len };\
}\
\
List_##T List_##T##_alloc(u32 initial_len);\
\
T* List_##T##_expand(List_##T* ptr, u32 count);\
void List_##T##_push(List_##T* ptr, T value);\
void List_##T##_pushMany(List_##T* ptr, T* values, u32 count);\
bool List_##T##_tryRemoveAt(List_##T* ptr, u32 i);\
#define List_define(T)\
List_##T List_##T##_alloc(u32 initial_len){\
if(initial_len == 0)\
return List_##T##_construct((T*)NULL, 0, 0);\
u32 max_len = ALIGN_TO(initial_len, sizeof(void*)/sizeof(T));\
/* branchless version of max(max_len, __List_min_size) */\
max_len += (max_len < __List_min_size) * (__List_min_size - max_len);\
return List_##T##_construct((T*)malloc(max_len * sizeof(T)), 0, max_len);\
}\
\
T* List_##T##_expand(List_##T* ptr, u32 count){\
u32 occupied_len = ptr->len;\
u32 expanded_max_len = ptr->max_len;\
expanded_max_len += (expanded_max_len < __List_min_size) * (__List_min_size - expanded_max_len);\
ptr->len += count;\
while(ptr->len > expanded_max_len){\
expanded_max_len *= 2;\
}\
u32 alloc_size = expanded_max_len * sizeof(T);\
if(ptr->data == NULL)\
ptr->data = (T*)malloc(alloc_size);\
else ptr->data = (T*)realloc(ptr->data, alloc_size);\
ptr->max_len = expanded_max_len;\
return ptr->data + occupied_len;\
}\
\
void List_##T##_push(List_##T* ptr, T value){\
T* empty_cell_ptr = List_##T##_expand(ptr, 1);\
*empty_cell_ptr = value;\
}\
\
void List_##T##_pushMany(List_##T* ptr, T* values, u32 count){\
T* empty_cell_ptr = List_##T##_expand(ptr, count);\
memcpy(empty_cell_ptr, values, count * sizeof(T));\
}\
\
bool List_##T##_tryRemoveAt(List_##T* ptr, u32 i){\
if(ptr->len == 0 || i >= ptr->len)\
return false;\
\
ptr->len--;\
for(; i < ptr->len; i++){\
ptr->data[i] = ptr->data[i + 1];\
}\
return true;\
}\
List_declare(u32);
List_declare(u8);

View File

@ -1,49 +1,52 @@
#include "AST.h" #include "AST.h"
static Array(str) _ArgumentType_str_array = ARRAY(str, { List_define(Argument);
List_define(Operation);
List_define(DataDefinition);
List_define(Section);
static str _ArgumentType_str[] = {
STR("Unset"), STR("Unset"),
STR("Register"), STR("Register"),
STR("ConstValue"), STR("ConstValue"),
STR("VarDataName"), STR("VarDataName"),
STR("ConstDataPointer"), STR("ConstDataPointer"),
STR("ConstDataSize"), STR("ConstDataSize"),
}); };
str ArgumentType_toString(ArgumentType t){ str ArgumentType_toString(ArgumentType t){
if(t >= Array_len(&_ArgumentType_str_array, str)) if(t >= ARRAY_SIZE(_ArgumentType_str))
return STR("!!ArgumentType INDEX_ERROR!!"); return STR("!!ArgumentType INDEX_ERROR!!");
return ((str*)_ArgumentType_str_array.data)[t]; return _ArgumentType_str[t];
} }
void Section_construct(Section* sec, str name){ void Section_init(Section* sec, str name){
sec->name = name; sec->name = name;
sec->data_definitions_list = List_alloc(DataDefinition, 256); sec->data = List_DataDefinition_alloc(256);
sec->operations_list = List_alloc(Operation, 1024); sec->code = List_Operation_alloc(1024);
} }
void Section_destroy(Section* sec){ void Section_free(Section* sec){
for(u32 i = 0; i < Array_len(&sec->data_definitions_list, DataDefinition); i++){ for(u32 i = 0; i < sec->data.len; i++){
DataDefinition* dd = (DataDefinition*)sec->data_definitions_list.data + i; free(sec->data.data[i].data.data);
free(dd->data_bytes.data);
} }
free(sec->data_definitions_list.data); free(sec->data.data);
for(u32 i = 0; i < Array_len(&sec->operations_list, Operation); i++){ for(u32 i = 0; i < sec->code.len; i++){
Operation* op = (Operation*)sec->operations_list.data + i; free(sec->code.data[i].args.data);
free(op->args.data);
} }
free(sec->operations_list.data); free(sec->code.data);
} }
void AST_construct(AST* ast){ void AST_init(AST* ast){
ast->sections = List_alloc(Section, 32); ast->sections = List_Section_alloc(32);
} }
void AST_destroy(AST* ast){ void AST_free(AST* ast){
for(u32 i = 0; i != Array_len(&ast->sections, Section); i++){ for(u32 i = 0; i != ast->sections.len; i++){
Section_destroy((Section*)ast->sections.data + i); Section_free(&ast->sections.data[i]);
} }
free(ast->sections.data); free(ast->sections.data);
} }

View File

@ -1,9 +1,9 @@
#pragma once #pragma once
#include "tlibc/std.h" #include "../std.h"
#include "tlibc/string/str.h" #include "../string/str.h"
#include "instructions/instructions.h" #include "../instructions/instructions.h"
#include "instructions/registers.h" #include "../instructions/registers.h"
#include "tlibc/collections/List.h" #include "../collections/List.h"
typedef enum ArgumentType { typedef enum ArgumentType {
ArgumentType_Unset, ArgumentType_Unset,
@ -26,32 +26,40 @@ typedef struct Argument {
} value; } value;
} Argument; } Argument;
List_declare(Argument);
typedef struct Operation { typedef struct Operation {
List(Argument) args; List_Argument args;
Opcode opcode; Opcode opcode;
} Operation; } Operation;
List_declare(Operation);
typedef struct DataDefinition { typedef struct DataDefinition {
str name; str name;
List(u8) data_bytes; List_u8 data;
u32 element_size; u32 element_size;
} DataDefinition; } DataDefinition;
List_declare(DataDefinition);
typedef struct Section { typedef struct Section {
str name; str name;
List(DataDefinition) data_definitions_list; List_DataDefinition data;
List(Operation) operations_list; List_Operation code;
} Section; } Section;
void Section_construct(Section* Section, str name); List_declare(Section);
void Section_destroy(Section* Section);
void Section_init(Section* Section, str name);
void Section_free(Section* Section);
typedef struct AST { typedef struct AST {
List(Section) sections; List_Section sections;
} AST; } AST;
void AST_construct(AST* ast); void AST_init(AST* ast);
void AST_destroy(AST* ast); void AST_free(AST* ast);

View File

@ -1,15 +1,22 @@
#include "Binary.h" #include "Binary.h"
List_define(ConstDataProps);
HashMap_define(ConstDataProps, HashMap_DESTROY_VALUE_FUNC_NULL);
List_define(NamedRef);
List_define(CompiledSection);
HashMap_define(CompiledSectionPtr, HashMap_DESTROY_VALUE_FUNC_NULL);
void CompiledSection_construct(CompiledSection* ptr, str name){ void CompiledSection_construct(CompiledSection* ptr, str name){
ptr->name = name; ptr->name = name;
ptr->next = NULL; ptr->next = NULL;
ptr->offset = 0; ptr->offset = 0;
ptr->const_data_props_list = List_construct(ConstDataProps, NULL, 0, 0); ptr->const_data_props_list = List_ConstDataProps_construct(NULL, 0, 0);
ptr->named_refs = List_construct(NamedRef, NULL, 0, 0); ptr->named_refs = List_NamedRef_construct(NULL, 0, 0);
ptr->bytes = List_alloc(u8, 64); ptr->bytes = List_u8_alloc(64);
} }
void CompiledSection_destroy(CompiledSection* ptr){ void CompiledSection_free(CompiledSection* ptr){
free(ptr->const_data_props_list.data); free(ptr->const_data_props_list.data);
free(ptr->named_refs.data); free(ptr->named_refs.data);
free(ptr->bytes.data); free(ptr->bytes.data);
@ -17,20 +24,17 @@ void CompiledSection_destroy(CompiledSection* ptr){
void BinaryObject_construct(BinaryObject* ptr){ void BinaryObject_construct(BinaryObject* ptr){
ptr->comp_sec_list = List_alloc(CompiledSection, 64); ptr->section_list = List_CompiledSection_alloc(64);
HashMap_construct(&ptr->comp_sec_i_map, u32, NULL); HashMap_CompiledSectionPtr_alloc(&ptr->section_map);
HashMap_construct(&ptr->const_data_props_map, ConstDataProps, NULL); HashMap_ConstDataProps_alloc(&ptr->const_data_map);
ptr->main_sec = NULL;
ptr->total_size = 0;
} }
void BinaryObject_destroy(BinaryObject* ptr){ void BinaryObject_free(BinaryObject* ptr){
for(u32 i = 0; i < List_len(&ptr->comp_sec_list, CompiledSection); i++){ for(u32 i = 0; i < ptr->section_list.len; i++){
CompiledSection* sec_ptr = (CompiledSection*)ptr->comp_sec_list.data + i; CompiledSection_free(&ptr->section_list.data[i]);
CompiledSection_destroy(sec_ptr);
} }
free(ptr->comp_sec_list.data); free(ptr->section_list.data);
HashMap_destroy(&ptr->comp_sec_i_map); HashMap_CompiledSectionPtr_free(&ptr->section_map);
HashMap_destroy(&ptr->const_data_props_map); HashMap_ConstDataProps_free(&ptr->const_data_map);
} }

View File

@ -1,10 +1,10 @@
#pragma once #pragma once
#include "tlibc/std.h" #include "../std.h"
#include "tlibc/string/str.h" #include "../string/str.h"
#include "instructions/instructions.h" #include "../instructions/instructions.h"
#include "instructions/registers.h" #include "../instructions/registers.h"
#include "tlibc/collections/List.h" #include "../collections/List.h"
#include "tlibc/collections/HashMap.h" #include "../collections/HashMap.h"
#include "AST.h" #include "AST.h"
typedef struct CompiledSection CompiledSection; typedef struct CompiledSection CompiledSection;
@ -16,6 +16,9 @@ typedef struct ConstDataProps {
#define ConstDataProps_construct(NAME, SIZE, OFFSET) ((ConstDataProps){ .name = NAME, .size = SIZE, .offset = OFFSET}) #define ConstDataProps_construct(NAME, SIZE, OFFSET) ((ConstDataProps){ .name = NAME, .size = SIZE, .offset = OFFSET})
List_declare(ConstDataProps);
HashMap_declare(ConstDataProps);
typedef enum NamedRefType { typedef enum NamedRefType {
NamedRefType_Unset, NamedRefType_Unset,
@ -31,27 +34,32 @@ typedef struct NamedRef {
#define NamedRef_construct(NAME, TYPE, OFFSET) ((NamedRef){ .name = NAME, .type = TYPE, .offset = OFFSET}) #define NamedRef_construct(NAME, TYPE, OFFSET) ((NamedRef){ .name = NAME, .type = TYPE, .offset = OFFSET})
List_declare(NamedRef);
typedef struct CompiledSection { typedef struct CompiledSection {
str name; str name;
CompiledSection* next; CompiledSection* next;
u32 offset; u32 offset;
List(ConstDataProps) const_data_props_list; List_ConstDataProps const_data_props_list;
List(NamedRef) named_refs; List_NamedRef named_refs;
List(u8) bytes; List_u8 bytes;
} CompiledSection; } CompiledSection;
void CompiledSection_construct(CompiledSection* ptr, str name); void CompiledSection_construct(CompiledSection* ptr, str name);
void CompiledSection_destroy(CompiledSection* ptr); void CompiledSection_free(CompiledSection* ptr);
List_declare(CompiledSection);
typedef CompiledSection* CompiledSectionPtr;
HashMap_declare(CompiledSectionPtr);
typedef struct BinaryObject { typedef struct BinaryObject {
List(CompiledSection) comp_sec_list; List_CompiledSection section_list;
HashMap(u32) comp_sec_i_map; HashMap_CompiledSectionPtr section_map;
NULLABLE(CompiledSection*) main_sec; HashMap_ConstDataProps const_data_map;
HashMap(ConstDataProps) const_data_props_map;
u32 total_size; u32 total_size;
} BinaryObject; } BinaryObject;
void BinaryObject_construct(BinaryObject* ptr); void BinaryObject_construct(BinaryObject* ptr);
void BinaryObject_destroy(BinaryObject* ptr); void BinaryObject_free(BinaryObject* ptr);

View File

@ -1,29 +1,31 @@
#include "Compiler_internal.h" #include "Compiler_internal.h"
void Compiler_construct(Compiler* cmp){ HashMap_define(SectionPtr, HashMap_DESTROY_VALUE_FUNC_NULL);
void Compiler_init(Compiler* cmp){
memset(cmp, 0, sizeof(Compiler)); memset(cmp, 0, sizeof(Compiler));
cmp->state = CompilerState_Initial; cmp->state = CompilerState_Initial;
cmp->tokens = List_alloc(Token, 4096); cmp->tokens = List_Token_alloc(4096);
cmp->line_lengths = List_alloc(u32, 1024); cmp->line_lengths = List_u32_alloc(1024);
AST_construct(&cmp->ast); AST_init(&cmp->ast);
BinaryObject_construct(&cmp->binary); BinaryObject_construct(&cmp->binary);
} }
void Compiler_destroy(Compiler* cmp){ void Compiler_free(Compiler* cmp){
free(cmp->code.data); free(cmp->code.data);
free(cmp->tokens.data); free(cmp->tokens.data);
free(cmp->line_lengths.data); free(cmp->line_lengths.data);
AST_destroy(&cmp->ast); AST_free(&cmp->ast);
BinaryObject_destroy(&cmp->binary); BinaryObject_free(&cmp->binary);
} }
CodePos Compiler_getLineAndColumn(Compiler* cmp, u32 pos){ CodePos Compiler_getLineAndColumn(Compiler* cmp, u32 pos){
u32 prev_lines_len = 0; u32 prev_lines_len = 0;
if(pos >= cmp->code.size) if(pos >= cmp->code.len)
return CodePos_create(0, 0); return CodePos_create(0, 0);
for(u32 i = 0; i < List_len(&cmp->line_lengths, u32); i++){ for(u32 i = 0; i < cmp->line_lengths.len; i++){
u32 line_len = ((u32*)cmp->line_lengths.data)[i]; u32 line_len = cmp->line_lengths.data[i];
if(prev_lines_len + line_len > pos) if(prev_lines_len + line_len > pos)
return CodePos_create(i + 1, pos + 1 - prev_lines_len); return CodePos_create(i + 1, pos + 1 - prev_lines_len);
prev_lines_len += line_len; prev_lines_len += line_len;
@ -34,8 +36,8 @@ CodePos Compiler_getLineAndColumn(Compiler* cmp, u32 pos){
void _Compiler_setError(Compiler* cmp, cstr context, cstr format, ...){ void _Compiler_setError(Compiler* cmp, cstr context, cstr format, ...){
// happens at the end of file // happens at the end of file
if(cmp->pos >= cmp->code.size) if(cmp->pos >= cmp->code.len)
cmp->pos = cmp->code.size - 1; cmp->pos = cmp->code.len - 1;
char position_str[32]; char position_str[32];
CodePos code_pos = Compiler_getLineAndColumn(cmp, cmp->pos); CodePos code_pos = Compiler_getLineAndColumn(cmp, cmp->pos);
sprintf(position_str, "[at %u:%u][", code_pos.line, code_pos.column); sprintf(position_str, "[at %u:%u][", code_pos.line, code_pos.column);
@ -63,20 +65,19 @@ str Compiler_constructTokenStr(Compiler* cmp, Token t){
} }
static bool compileSection(Compiler* cmp, Section* sec){ static bool compileSection(Compiler* cmp, Section* sec){
u32 cs_index = List_len(&cmp->binary.comp_sec_list, CompiledSection); CompiledSection* cs = List_CompiledSection_expand(&cmp->binary.section_list, 1);
CompiledSection* cs = List_expand_size(&cmp->binary.comp_sec_list, sizeof(CompiledSection));
CompiledSection_construct(cs, sec->name); CompiledSection_construct(cs, sec->name);
if(!HashMap_tryPush(&cmp->binary.comp_sec_i_map, cs->name, &cs_index)){ if(!HashMap_CompiledSectionPtr_tryPush(&cmp->binary.section_map, cs->name, cs)){
returnError("duplicate section '%s'", str_copy(sec->name).data); returnError("duplicate section '%s'", str_copy(sec->name));
} }
// compile code // compile code
u8 zeroes[8] = {0, 0, 0, 0, 0, 0, 0, 0}; u8 zeroes[8] = {0, 0, 0, 0, 0, 0, 0, 0};
for(u32 i = 0; i < List_len(&sec->operations_list, Operation); i++){ for(u32 i = 0; i < sec->code.len; i++){
Operation* op = (Operation*)sec->operations_list.data + i; Operation* op = &sec->code.data[i];
List_pushMany(&cs->bytes, u8, &op->opcode, sizeof(op->opcode)); List_u8_pushMany(&cs->bytes, (void*)&op->opcode, sizeof(op->opcode));
for(u32 j = 0; j < List_len(&op->args, Argument); j++){ for(u32 j = 0; j < op->args.len; j++){
Argument* arg = (Argument*)op->args.data + j; Argument* arg = &op->args.data[j];
switch(arg->type){ switch(arg->type){
case ArgumentType_VarDataName: case ArgumentType_VarDataName:
returnError("argument type 'VarDataName' is not supported yet"); returnError("argument type 'VarDataName' is not supported yet");
@ -86,35 +87,35 @@ static bool compileSection(Compiler* cmp, Section* sec){
returnError("invalid ArgumentType %i", arg->type); returnError("invalid ArgumentType %i", arg->type);
case ArgumentType_Register: case ArgumentType_Register:
List_push(&cs->bytes, u8, arg->value.register_code); List_u8_push(&cs->bytes, arg->value.register_code);
break; break;
case ArgumentType_ConstValue: case ArgumentType_ConstValue:
List_pushMany(&cs->bytes, u8, &arg->value.i, 8); //TODO: add const value size parsing
List_u8_pushMany(&cs->bytes, (void*)&arg->value.i, 4);
break; break;
case ArgumentType_ConstDataPointer: case ArgumentType_ConstDataPointer:
List_push(&cs->named_refs, NamedRef, NamedRef_construct( List_NamedRef_push(&cs->named_refs, NamedRef_construct(
arg->value.data_name, arg->value.data_name,
NamedRefType_Ptr, NamedRefType_Ptr,
cs->bytes.size)); cs->bytes.len));
List_pushMany(&cs->bytes, u8, zeroes, 8); List_u8_pushMany(&cs->bytes, zeroes, 4);
break; break;
case ArgumentType_ConstDataSize: case ArgumentType_ConstDataSize:
List_push(&cs->named_refs, NamedRef, NamedRef_construct( List_NamedRef_push(&cs->named_refs, NamedRef_construct(
arg->value.data_name, arg->value.data_name,
NamedRefType_Size, NamedRefType_Size,
cs->bytes.size)); cs->bytes.len));
List_pushMany(&cs->bytes, u8, zeroes, 8); List_u8_pushMany(&cs->bytes, zeroes, 4);
break; break;
} }
} }
} }
// compile data // compile data
for(u32 i = 0; i < List_len(&sec->data_definitions_list, DataDefinition); i++){ for(u32 i = 0; i < sec->data.len; i++){
DataDefinition* dd = (DataDefinition*)sec->data_definitions_list.data + i; DataDefinition* dd = &sec->data.data[i];
List_push(&cs->const_data_props_list, ConstDataProps, List_ConstDataProps_push(&cs->const_data_props_list, ConstDataProps_construct(dd->name, dd->data.len, cs->bytes.len));
ConstDataProps_construct(dd->name, dd->data_bytes.size, cs->bytes.size)); List_u8_pushMany(&cs->bytes, dd->data.data, dd->data.len);
List_pushMany(&cs->bytes, u8, dd->data_bytes.data, dd->data_bytes.size);
} }
// TODO: push padding // TODO: push padding
@ -123,11 +124,8 @@ static bool compileSection(Compiler* cmp, Section* sec){
} }
static bool compileBinary(Compiler* cmp){ static bool compileBinary(Compiler* cmp){
returnErrorIf_auto(cmp->state != CompilerState_Parsing); for(u32 i = 0; i < cmp->ast.sections.len; i++){
cmp->state = CompilerState_Compiling; SectionPtr sec = &cmp->ast.sections.data[i];
for(u32 i = 0; i < List_len(&cmp->ast.sections, Section); i++){
Section* sec = (Section*)cmp->ast.sections.data + i;
if(!compileSection(cmp, sec)){ if(!compileSection(cmp, sec)){
return false; return false;
} }
@ -135,63 +133,57 @@ static bool compileBinary(Compiler* cmp){
// find main section // find main section
str main_sec_name = STR("main"); str main_sec_name = STR("main");
u32* main_sec_i_ptr = HashMap_tryGetPtr(&cmp->binary.comp_sec_i_map, main_sec_name); CompiledSection** main_sec_ptrptr = HashMap_CompiledSectionPtr_tryGetPtr(&cmp->binary.section_map, main_sec_name);
if(main_sec_i_ptr == NULL){ if(main_sec_ptrptr == NULL){
returnError("no 'main' section was defined"); returnError("no 'main' section was defined");
} }
u32 main_sec_i = *main_sec_i_ptr;
cmp->binary.main_sec = (CompiledSection*)cmp->binary.comp_sec_list.data + main_sec_i;
// create linked list of CompiledSection where main is the first // create linked list of CompiledSection where main is the first
CompiledSection* prev_sec = cmp->binary.main_sec; CompiledSection* prev_sec = *main_sec_ptrptr;
u32 total_size = 0; u32 total_size = 0;
for(u32 i = 0; i < List_len(&cmp->binary.comp_sec_list, CompiledSection); i++){ for(u32 i = 0; i < cmp->binary.section_list.len; i++){
CompiledSection* sec = (CompiledSection*)cmp->binary.comp_sec_list.data + i; CompiledSection* sec = &cmp->binary.section_list.data[i];
total_size += sec->bytes.size; total_size += sec->bytes.len;
bool is_main_sec = str_equals(sec->name, main_sec_name); if(str_equals(sec->name, main_sec_name))
if(!is_main_sec){ continue;
sec->offset = prev_sec->offset + prev_sec->bytes.size; prev_sec->next = sec;
} sec->offset = prev_sec->offset + prev_sec->bytes.len;
ConstDataProps cd = ConstDataProps_construct(sec->name, sec->bytes.size, sec->offset); ConstDataProps cd = ConstDataProps_construct(sec->name, sec->bytes.len, sec->offset);
if(!HashMap_tryPush(&cmp->binary.const_data_props_map, cd.name, &cd)){ if(!HashMap_ConstDataProps_tryPush(&cmp->binary.const_data_map, cd.name, cd)){
returnError("duplicate named data '%s'", str_copy(cd.name).data); returnError("duplicate named data '%s'", str_copy(cd.name).data);
} }
for(u32 j = 0; j < List_len(&sec->const_data_props_list, ConstDataProps); j++){ for(u32 j = 0; j < sec->const_data_props_list.len; j++){
cd = ((ConstDataProps*)sec->const_data_props_list.data)[j]; cd = sec->const_data_props_list.data[j];
cd.offset += sec->offset; cd.offset += sec->offset;
if(!HashMap_tryPush(&cmp->binary.const_data_props_map, cd.name, &cd)){ if(!HashMap_ConstDataProps_tryPush(&cmp->binary.const_data_map, cd.name, cd)){
returnError("duplicate named data '%s'", str_copy(cd.name).data); returnError("duplicate named data '%s'", str_copy(cd.name).data);
} }
} }
if(is_main_sec)
continue;
prev_sec->next = sec;
prev_sec = sec;
} }
// insert calculated offsets into sections // insert calculated offsets into sections
for(u32 i = 0; i < List_len(&cmp->binary.comp_sec_list, CompiledSection); i++){ for(u32 i = 0; i < cmp->binary.section_list.len; i++){
CompiledSection* sec = (CompiledSection*)cmp->binary.comp_sec_list.data + i; CompiledSection* sec = &cmp->binary.section_list.data[i];
for(u32 j = 0; j < List_len(&sec->named_refs, NamedRef); j++){ for(u32 j = 0; j < sec->named_refs.len; j++){
NamedRef* ref = (NamedRef*)sec->named_refs.data +j; NamedRef* ref = &sec->named_refs.data[j];
ConstDataProps* target_data = HashMap_tryGetPtr( ConstDataProps* target_data = HashMap_ConstDataProps_tryGetPtr(
&cmp->binary.const_data_props_map, ref->name); &cmp->binary.const_data_map, ref->name);
if(target_data == NULL){ if(target_data == NULL){
returnError("can't find named data '%s'", str_copy(ref->name).data); returnError("can't find named data '%s'", str_copy(ref->name).data);
} }
u64* ref_value_ptr = (void*)((u8*)sec->bytes.data + ref->offset); void* ref_value_ptr = sec->bytes.data + ref->offset;
switch(ref->type){ switch(ref->type){
default: default:
returnError("invalid NamedRefType %i", ref->type); returnError("invalid NamedRefType %i", ref->type);
case NamedRefType_Size: case NamedRefType_Size:
*ref_value_ptr = target_data->size; *((u32*)ref_value_ptr) = target_data->size;
break; break;
case NamedRefType_Ptr: case NamedRefType_Ptr:
*ref_value_ptr = target_data->offset; *((u32*)ref_value_ptr) = target_data->offset;
break; break;
} }
} }
@ -202,16 +194,26 @@ static bool compileBinary(Compiler* cmp){
} }
static bool writeBinaryFile(Compiler* cmp, FILE* f){ static bool writeBinaryFile(Compiler* cmp, FILE* f){
returnErrorIf_auto(cmp->state != CompilerState_Compiling); returnErrorIf_auto(cmp->state != CompilerState_Parsing);
cmp->state = CompilerState_Compiling;
CompiledSection* sec = cmp->binary.main_sec; if(!compileBinary(cmp)){
return false;
}
CompiledSection** main_sec_ptrptr = HashMap_CompiledSectionPtr_tryGetPtr(&cmp->binary.section_map, STR("main"));
if(main_sec_ptrptr == NULL){
returnError("no 'main' section was defined");
}
CompiledSection* sec = *main_sec_ptrptr;
while(sec){ while(sec){
fwrite(sec->bytes.data, 1, sec->bytes.size, f); fwrite(sec->bytes.data, 1, sec->bytes.len, f);
fflush(f);
sec = sec->next; sec = sec->next;
} }
//TODO: print warnings for unused sections //TODO: print warnings for unused sections
return true; return true;
} }
@ -226,19 +228,19 @@ bool Compiler_compile(Compiler* cmp, cstr source_file_name, cstr out_file_name,
StringBuilder_append_char(&sb, ret); StringBuilder_append_char(&sb, ret);
} }
if(ferror(f)){ if(ferror(f)){
StringBuilder_destroy(&sb); StringBuilder_free(&sb);
fclose(f); fclose(f);
returnError("can't read file '%s'", source_file_name); returnError("can't read file '%s'", source_file_name);
} }
fclose(f); fclose(f);
if(sb.buffer.size == 0){ if(sb.buffer.len == 0){
StringBuilder_destroy(&sb); StringBuilder_free(&sb);
returnError("soucre file is empty"); returnError("soucre file is empty");
} }
cmp->code = str_copy(StringBuilder_getStr(&sb)); cmp->code = str_copy(StringBuilder_getStr(&sb));
StringBuilder_destroy(&sb); StringBuilder_free(&sb);
f = fopen(out_file_name, "wb"); f = fopen(out_file_name, "wb");
if(f == NULL){ if(f == NULL){
@ -257,13 +259,13 @@ bool Compiler_compile(Compiler* cmp, cstr source_file_name, cstr out_file_name,
if(debug_log){ if(debug_log){
printf("------------------------------------[lines]------------------------------------\n"); printf("------------------------------------[lines]------------------------------------\n");
for(u32 i = 0; i < List_len(&cmp->line_lengths, u32); i++){ for(u32 i = 0; i < cmp->line_lengths.len; i++){
printf("[%u] length: %u\n", i+1, ((u32*)cmp->line_lengths.data)[i]); printf("[%u] length: %u\n", i+1, cmp->line_lengths.data[i]);
} }
printf("------------------------------------[tokens]-----------------------------------\n"); printf("------------------------------------[tokens]-----------------------------------\n");
for(u32 i = 0; i < List_len(&cmp->tokens, Token); i++){ for(u32 i = 0; i < cmp->tokens.len; i++){
Token t = ((Token*)cmp->tokens.data)[i]; Token t = cmp->tokens.data[i];
CodePos pos = Compiler_getLineAndColumn(cmp, t.begin); CodePos pos = Compiler_getLineAndColumn(cmp, t.begin);
char* tokstr = malloc(4096); char* tokstr = malloc(4096);
strncpy(tokstr, cmp->code.data + t.begin, t.length); strncpy(tokstr, cmp->code.data + t.begin, t.length);
@ -287,45 +289,37 @@ bool Compiler_compile(Compiler* cmp, cstr source_file_name, cstr out_file_name,
if(debug_log) if(debug_log)
printf("===================================[parsing]===================================\n"); printf("===================================[parsing]===================================\n");
success = Compiler_parse(cmp); success = Compiler_parse(cmp);
if (debug_log){ if (debug_log){
printf("-------------------------------------[AST]-------------------------------------\n"); printf("-------------------------------------[AST]-------------------------------------\n");
for(u32 i = 0; i < List_len(&cmp->ast.sections, Section); i++){ for(u32 i = 0; i < cmp->ast.sections.len; i++){
Section* sec = (Section*)cmp->ast.sections.data + i; Section* sec = &cmp->ast.sections.data[i];
str tmpstr = str_copy(sec->name); str tmpstr = str_copy(sec->name);
printf("section '%s'\n", tmpstr.data); printf("section '%s'\n", tmpstr.data);
free(tmpstr.data); free(tmpstr.data);
for(u32 j = 0; j < List_len(&sec->data_definitions_list, DataDefinition); j++){ for(u32 j = 0; j < sec->data.len; j++){
DataDefinition* dd = (DataDefinition*)sec->data_definitions_list.data + j; DataDefinition* dd = &sec->data.data[j];
tmpstr = str_copy(dd->name); tmpstr = str_copy(dd->name);
printf(" const%u %s (len %u)\n", dd->element_size * 8, tmpstr.data, printf(" const%u %s (len %u)\n", dd->element_size * 8, tmpstr.data, dd->data.len/dd->element_size);
dd->data_bytes.size/dd->element_size);
free(tmpstr.data); free(tmpstr.data);
} }
for(u32 j = 0; j < List_len(&sec->operations_list, Operation); j++){ for(u32 j = 0; j < sec->code.len; j++){
Operation* op = (Operation*)sec->operations_list.data + j; Operation* op = &sec->code.data[j];
const Instruction* instr = Instruction_getByOpcode(op->opcode); const Instruction* instr = Instruction_getByOpcode(op->opcode);
if(instr == NULL){
fclose(f);
returnError("unknown opcode: %i", op->opcode)
}
printf(" %s", instr->name.data); printf(" %s", instr->name.data);
for(u32 k = 0; k < List_len(&op->args, Argument); k++){ for(u32 k = 0; k < op->args.len; k++){
Argument* arg = (Argument*)op->args.data + k; Argument* arg = &op->args.data[k];
printf(" %s(", ArgumentType_toString(arg->type).data); printf(" %s(", ArgumentType_toString(arg->type).data);
switch(arg->type){ switch(arg->type){
default: default:
fclose(f); fclose(f);
returnError("invalid argument type %i", arg->type); returnError("invalid argument type %i", arg->type);
case ArgumentType_Register:; case ArgumentType_Register:
str register_name = RegisterCode_toString(arg->value.register_code); const char* register_names[] = {"null", "ax", "bx", "cx", "dx"};
printf("%s 0x%x", register_name.data, arg->value.register_code); printf("%s", register_names[arg->value.register_code]);
free(register_name.data);
break; break;
case ArgumentType_ConstValue: case ArgumentType_ConstValue:
printf(IFWIN("%lli", "%li"), arg->value.i); printf(IFWIN("%lli", "%li"), arg->value.i);
@ -354,7 +348,6 @@ bool Compiler_compile(Compiler* cmp, cstr source_file_name, cstr out_file_name,
} }
} }
} }
if(!success){ if(!success){
fclose(f); fclose(f);
return false; return false;
@ -362,25 +355,6 @@ bool Compiler_compile(Compiler* cmp, cstr source_file_name, cstr out_file_name,
if(debug_log) if(debug_log)
printf("==================================[compiling]==================================\n"); printf("==================================[compiling]==================================\n");
success = compileBinary(cmp);
if(debug_log){
for(u32 i = 0; i < List_len(&cmp->binary.comp_sec_list, CompiledSection); i++){
CompiledSection* sec = (CompiledSection*)cmp->binary.comp_sec_list.data + i;
str tmpstr = str_copy(sec->name);
printf("compiled section '%s' to %u bytes with offset 0x%x\n", tmpstr.data, sec->bytes.size, sec->offset);
free(tmpstr.data);
}
}
if(!success){
fclose(f);
return false;
}
if(debug_log)
printf("----------------------------[writing output to file]---------------------------\n");
success = writeBinaryFile(cmp, f); success = writeBinaryFile(cmp, f);
fclose(f); fclose(f);
if(success){ if(success){

View File

@ -1,8 +1,8 @@
#pragma once #pragma once
#include "tlibc/std.h" #include "../std.h"
#include "tlibc/string/str.h" #include "../string/str.h"
#include "tlibc/collections/List.h" #include "../collections/List.h"
#include "tlibc/collections/HashMap.h" #include "../collections/HashMap.h"
#include "Token.h" #include "Token.h"
#include "Binary.h" #include "Binary.h"
@ -15,6 +15,8 @@ typedef enum CompilerState {
CompilerState_Success CompilerState_Success
} CompilerState; } CompilerState;
typedef Section* SectionPtr;
HashMap_declare(SectionPtr);
typedef struct Compiler { typedef struct Compiler {
/* general fields */ /* general fields */
@ -24,8 +26,8 @@ typedef struct Compiler {
CompilerState state; CompilerState state;
NULLABLE(char* error_message); NULLABLE(char* error_message);
/* lexer fields */ /* lexer fields */
List(Token) tokens; List_Token tokens;
List(u32) line_lengths; List_u32 line_lengths;
/* parser fields */ /* parser fields */
AST ast; AST ast;
u32 tok_i; u32 tok_i;
@ -33,8 +35,8 @@ typedef struct Compiler {
BinaryObject binary; BinaryObject binary;
} Compiler; } Compiler;
void Compiler_construct(Compiler* cmp); void Compiler_init(Compiler* cmp);
void Compiler_destroy(Compiler* cmp); void Compiler_free(Compiler* cmp);
/// @brief compile assembly language code to machine code /// @brief compile assembly language code to machine code
/// @return true if no errors, false if any error occured (check cmp->error_message) /// @return true if no errors, false if any error occured (check cmp->error_message)

View File

@ -1,5 +1,5 @@
#include "Compiler.h" #include "Compiler.h"
#include "tlibc/string/StringBuilder.h" #include "../string/StringBuilder.h"
void _Compiler_setError(Compiler* cmp, cstr context, cstr format, ...) __attribute__((__format__(__printf__, 3, 4))); void _Compiler_setError(Compiler* cmp, cstr context, cstr format, ...) __attribute__((__format__(__printf__, 3, 4)));

View File

@ -9,7 +9,7 @@
#define Error_endOfFile "unexpected end of file" #define Error_endOfFile "unexpected end of file"
static void completeLine(Compiler* cmp){ static void completeLine(Compiler* cmp){
List_push(&cmp->line_lengths, u32, cmp->column); List_u32_push(&cmp->line_lengths, cmp->column);
cmp->column = 0; cmp->column = 0;
} }
@ -19,12 +19,12 @@ static void readCommentSingleLine(Compiler* cmp){
cmp->column++; cmp->column++;
cmp->pos++; cmp->pos++;
while(cmp->pos < cmp->code.size){ while(cmp->pos < cmp->code.len){
c = cmp->code.data[cmp->pos]; c = cmp->code.data[cmp->pos];
// end of line // end of line
if(c == '\r' || c == '\n'){ if(c == '\r' || c == '\n'){
tok.length = cmp->pos - tok.begin; tok.length = cmp->pos - tok.begin;
List_push(&cmp->tokens, Token, tok); List_Token_push(&cmp->tokens, tok);
// cmp->line will be increased in lex() // cmp->line will be increased in lex()
return; return;
} }
@ -35,7 +35,7 @@ static void readCommentSingleLine(Compiler* cmp){
// end of file // end of file
tok.length = cmp->pos - tok.begin; tok.length = cmp->pos - tok.begin;
List_push(&cmp->tokens, Token, tok); List_Token_push(&cmp->tokens, tok);
} }
static void readCommentMultiLine(Compiler* cmp){ static void readCommentMultiLine(Compiler* cmp){
@ -44,12 +44,12 @@ static void readCommentMultiLine(Compiler* cmp){
cmp->column++; cmp->column++;
cmp->pos++; cmp->pos++;
while(cmp->pos < cmp->code.size){ while(cmp->pos < cmp->code.len){
c = cmp->code.data[cmp->pos]; c = cmp->code.data[cmp->pos];
// closing comment // closing comment
if(cmp->pos > tok.begin + 3 && c == '/' && cmp->code.data[cmp->pos - 1] == '*') { if(cmp->pos > tok.begin + 3 && c == '/' && cmp->code.data[cmp->pos - 1] == '*') {
tok.length = cmp->pos - tok.begin + 1; tok.length = cmp->pos - tok.begin + 1;
List_push(&cmp->tokens, Token, tok); List_Token_push(&cmp->tokens, tok);
return; return;
} }
@ -65,7 +65,7 @@ static void readCommentMultiLine(Compiler* cmp){
static void readComment(Compiler* cmp){ static void readComment(Compiler* cmp){
char c; // '/' char c; // '/'
if(cmp->pos + 1 == cmp->code.size){ if(cmp->pos + 1 == cmp->code.len){
setError(Error_endOfFile); setError(Error_endOfFile);
return; return;
} }
@ -91,13 +91,13 @@ static void readLabel(Compiler* cmp){
cmp->column++; cmp->column++;
Token tok = Token_construct(TokenType_Label, cmp->pos, 0); Token tok = Token_construct(TokenType_Label, cmp->pos, 0);
while(cmp->pos < cmp->code.size){ while(cmp->pos < cmp->code.len){
c = cmp->code.data[cmp->pos]; c = cmp->code.data[cmp->pos];
// end of line // end of line
if(c == ':' || c == '\r' || c == '\n'){ if(c == ':' || c == '\r' || c == '\n'){
tok.length = cmp->pos - tok.begin; tok.length = cmp->pos - tok.begin;
if(tok.length > 0) if(tok.length > 0)
List_push(&cmp->tokens, Token, tok); List_Token_push(&cmp->tokens, tok);
else setError(Error_unexpectedCharacter(cmp->code.data[--cmp->pos])); else setError(Error_unexpectedCharacter(cmp->code.data[--cmp->pos]));
// cmp->line will be increased in lex() // cmp->line will be increased in lex()
return; return;
@ -116,7 +116,7 @@ static void readLabel(Compiler* cmp){
// end of file // end of file
tok.length = cmp->pos - tok.begin; tok.length = cmp->pos - tok.begin;
if(tok.length > 0) if(tok.length > 0)
List_push(&cmp->tokens, Token, tok); List_Token_push(&cmp->tokens, tok);
else setError(Error_endOfFile); else setError(Error_endOfFile);
} }
@ -125,12 +125,12 @@ static void readArguments(Compiler* cmp){
Token tok = Token_construct(TokenType_Unset, cmp->pos, 0); Token tok = Token_construct(TokenType_Unset, cmp->pos, 0);
char quot = '\0'; // quotation character of a string value char quot = '\0'; // quotation character of a string value
while(cmp->pos < cmp->code.size){ while(cmp->pos < cmp->code.len){
c = cmp->code.data[cmp->pos]; c = cmp->code.data[cmp->pos];
// string argument reading // string argument reading
if(quot != '\0'){ if(quot != '\0'){
if(c == quot && (cmp->code.data[cmp->pos - 1] != '\\' || cmp->code.data[cmp->pos - 2] == '\\')){ if(c == quot && cmp->code.data[cmp->pos - 1] != '\\'){
quot = '\0'; quot = '\0';
} }
else if(c == '\r' || c == '\n'){ else if(c == '\r' || c == '\n'){
@ -143,7 +143,7 @@ static void readArguments(Compiler* cmp){
else if(c == '\r' || c == '\n' || c == ';'){ else if(c == '\r' || c == '\n' || c == ';'){
tok.length = cmp->pos - tok.begin; tok.length = cmp->pos - tok.begin;
if(tok.length > 0) if(tok.length > 0)
List_push(&cmp->tokens, Token, tok); List_Token_push(&cmp->tokens, tok);
// cmp->line will be increased in lex() // cmp->line will be increased in lex()
return; return;
} }
@ -152,7 +152,7 @@ static void readArguments(Compiler* cmp){
else if(c == ' ' || c == '\t'){ else if(c == ' ' || c == '\t'){
tok.length = cmp->pos - tok.begin; tok.length = cmp->pos - tok.begin;
if(tok.length > 0) if(tok.length > 0)
List_push(&cmp->tokens, Token, tok); List_Token_push(&cmp->tokens, tok);
tok = Token_construct(TokenType_Unset, cmp->pos + 1, 0); tok = Token_construct(TokenType_Unset, cmp->pos + 1, 0);
} }
@ -181,7 +181,7 @@ static void readArguments(Compiler* cmp){
// end of file // end of file
tok.length = cmp->pos - tok.begin; tok.length = cmp->pos - tok.begin;
if(tok.length > 0) if(tok.length > 0)
List_push(&cmp->tokens, Token, tok); List_Token_push(&cmp->tokens, tok);
} }
static void readInstruction(Compiler* cmp){ static void readInstruction(Compiler* cmp){
@ -189,14 +189,14 @@ static void readInstruction(Compiler* cmp){
cmp->pos++; cmp->pos++;
cmp->column++; cmp->column++;
while(cmp->pos < cmp->code.size){ while(cmp->pos < cmp->code.len){
char c = cmp->code.data[cmp->pos]; char c = cmp->code.data[cmp->pos];
// end of line // end of line
if(c == '\r' || c == '\n' || c == ';'){ if(c == '\r' || c == '\n' || c == ';'){
tok.length = cmp->pos - tok.begin; tok.length = cmp->pos - tok.begin;
List_push(&cmp->tokens, Token, tok); List_Token_push(&cmp->tokens, tok);
tok = Token_construct(TokenType_OperationEnd, cmp->pos, 1); tok = Token_construct(TokenType_OperationEnd, cmp->pos, 1);
List_push(&cmp->tokens, Token, tok); List_Token_push(&cmp->tokens, tok);
// cmp->line will be increased in lex() // cmp->line will be increased in lex()
return; return;
} }
@ -204,10 +204,10 @@ static void readInstruction(Compiler* cmp){
// arguments begin // arguments begin
if(c == ' ' || c == '\t'){ if(c == ' ' || c == '\t'){
tok.length = cmp->pos - tok.begin; tok.length = cmp->pos - tok.begin;
List_push(&cmp->tokens, Token, tok); List_Token_push(&cmp->tokens, tok);
readArguments(cmp); readArguments(cmp);
tok = Token_construct(TokenType_OperationEnd, cmp->pos, 1); tok = Token_construct(TokenType_OperationEnd, cmp->pos, 1);
List_push(&cmp->tokens, Token, tok); List_Token_push(&cmp->tokens, tok);
return; return;
} }
@ -222,9 +222,9 @@ static void readInstruction(Compiler* cmp){
// end of file // end of file
tok.length = cmp->pos - tok.begin; tok.length = cmp->pos - tok.begin;
List_push(&cmp->tokens, Token, tok); List_Token_push(&cmp->tokens, tok);
tok = Token_construct(TokenType_OperationEnd, cmp->pos, 1); tok = Token_construct(TokenType_OperationEnd, cmp->pos, 1);
List_push(&cmp->tokens, Token, tok); List_Token_push(&cmp->tokens, tok);
} }
bool Compiler_lex(Compiler* cmp){ bool Compiler_lex(Compiler* cmp){
@ -232,7 +232,7 @@ bool Compiler_lex(Compiler* cmp){
cmp->state = CompilerState_Lexing; cmp->state = CompilerState_Lexing;
cmp->column = 1; cmp->column = 1;
while(cmp->pos < cmp->code.size){ while(cmp->pos < cmp->code.len){
char c = cmp->code.data[cmp->pos]; char c = cmp->code.data[cmp->pos];
switch(c){ switch(c){
// skip blank characters // skip blank characters

View File

@ -1,7 +1,7 @@
#include "Compiler_internal.h" #include "Compiler_internal.h"
#define setError(FORMAT, ...) {\ #define setError(FORMAT, ...) {\
cmp->pos = ((Token*)cmp->tokens.data)[cmp->tok_i].begin;\ cmp->pos = cmp->tokens.data[cmp->tok_i].begin;\
Compiler_setError(cmp, FORMAT, ##__VA_ARGS__);\ Compiler_setError(cmp, FORMAT, ##__VA_ARGS__);\
} }
@ -27,21 +27,24 @@
#define Error_TokenUnset "token of undefined type" #define Error_TokenUnset "token of undefined type"
#define Error_BitSize "invalid size in bits" #define Error_BitSize "invalid size in bits"
#define List_pushAsBytes(L, VAL_PTR, START_INDEX, COUNT)\ static void List_u8_pushBytes(List_u8* l, void* value, u32 startIndex, u32 count){
List_push_size(L, (u8*)(VAL_PTR) + START_INDEX, COUNT) u8* v = value;
for(u32 byte_i = startIndex; byte_i < startIndex + count; byte_i++){
List_u8_push(l, v[byte_i]);
}
}
static inline bool isVarSizeBits(u32 B) { return (B == 8 || B == 16 || B == 32 || B == 64); } static inline bool isVarSizeBits(u32 B) { return (B == 8 || B == 16 || B == 32 || B == 64); }
static NULLABLE(str) resolveEscapeSequences(Compiler* cmp, str src){ static NULLABLE(str) resolveEscapeSequences(Compiler* cmp, str src){
StringBuilder sb = StringBuilder_alloc(src.size); StringBuilder sb = StringBuilder_alloc(src.len);
char c; char c;
bool escaped = false; bool escaped = false;
for(u32 i = 0; i < src.size; i++){ for(u32 i = 0; i < src.len; i++){
c = src.data[i]; c = src.data[i];
if(c == '\\'){ if(c == '\\'){
escaped = !escaped; escaped = !escaped;
if(escaped) continue;
continue;
} }
if(!escaped){ if(!escaped){
@ -66,17 +69,11 @@ static NULLABLE(str) resolveEscapeSequences(Compiler* cmp, str src){
case 'e': case 'e':
StringBuilder_append_char(&sb, '\e'); StringBuilder_append_char(&sb, '\e');
break; break;
case '"':
case '\'':
StringBuilder_append_char(&sb, c);
break;
default: default:
setError_unexpectedTokenChar(((Token*)cmp->tokens.data)[cmp->tok_i], i); setError_unexpectedTokenChar(cmp->tokens.data[cmp->tok_i], i);
StringBuilder_destroy(&sb); StringBuilder_free(&sb);
return str_null; return str_null;
} }
escaped = false;
} }
return StringBuilder_getStr(&sb); return StringBuilder_getStr(&sb);
@ -92,9 +89,9 @@ static void parseDataDefinition(Compiler* cmp, str instr_name, DataDefinition* d
} }
free(_instr_name_zero_terminated.data); free(_instr_name_zero_terminated.data);
ddf->element_size = _element_size_bits / 8; ddf->element_size = _element_size_bits / 8;
ddf->data_bytes = List_alloc(u8, 32); ddf->data = List_u8_alloc(32);
Token tok = ((Token*)cmp->tokens.data)[++cmp->tok_i]; Token tok = cmp->tokens.data[++cmp->tok_i];
if(tok.type != TokenType_Name){ if(tok.type != TokenType_Name){
setError_unexpectedToken(tok); setError_unexpectedToken(tok);
return; return;
@ -104,8 +101,8 @@ static void parseDataDefinition(Compiler* cmp, str instr_name, DataDefinition* d
str processed_str = str_null; str processed_str = str_null;
ddf->name = tok_str; ddf->name = tok_str;
while(++cmp->tok_i < List_len(&cmp->tokens, Token)){ while(++cmp->tok_i < cmp->tokens.len){
tok = ((Token*)cmp->tokens.data)[cmp->tok_i]; tok = cmp->tokens.data[cmp->tok_i];
switch(tok.type){ switch(tok.type){
case TokenType_SingleLineComment: case TokenType_SingleLineComment:
case TokenType_MultiLineComment: case TokenType_MultiLineComment:
@ -126,11 +123,11 @@ static void parseDataDefinition(Compiler* cmp, str instr_name, DataDefinition* d
processed_str = str_copy(tok_str); processed_str = str_copy(tok_str);
if(str_seekChar(tok_str, '.', 0) != -1){ if(str_seekChar(tok_str, '.', 0) != -1){
f64 f = atof(processed_str.data); f64 f = atof(processed_str.data);
List_pushAsBytes(&ddf->data_bytes, &f, 8 - ddf->element_size, ddf->element_size); List_u8_pushBytes(&ddf->data, &f, 8 - ddf->element_size, ddf->element_size);
} }
else { else {
i64 i = atoll(processed_str.data); i64 i = atoll(processed_str.data);
List_pushAsBytes(&ddf->data_bytes, &i, 8 - ddf->element_size, ddf->element_size); List_u8_pushBytes(&ddf->data, &i, 8 - ddf->element_size, ddf->element_size);
} }
free(processed_str.data); free(processed_str.data);
break; break;
@ -140,11 +137,11 @@ static void parseDataDefinition(Compiler* cmp, str instr_name, DataDefinition* d
tok_str = Compiler_constructTokenStr(cmp, tok); tok_str = Compiler_constructTokenStr(cmp, tok);
processed_str = resolveEscapeSequences(cmp, tok_str); processed_str = resolveEscapeSequences(cmp, tok_str);
if(processed_str.size != ddf->element_size){ if(processed_str.len != ddf->element_size){
setError("can't fit char of size %i in %u bit variable", processed_str.size, _element_size_bits); setError("can't fit char of size %i in %u bit variable", processed_str.len, _element_size_bits);
return; return;
} }
List_pushAsBytes(&ddf->data_bytes, processed_str.data, 0, processed_str.size); List_u8_pushBytes(&ddf->data, processed_str.data, 0, processed_str.len);
free(processed_str.data); free(processed_str.data);
break; break;
case TokenType_String: case TokenType_String:
@ -152,7 +149,7 @@ static void parseDataDefinition(Compiler* cmp, str instr_name, DataDefinition* d
tok.length -= 2; tok.length -= 2;
tok_str = Compiler_constructTokenStr(cmp, tok); tok_str = Compiler_constructTokenStr(cmp, tok);
processed_str = resolveEscapeSequences(cmp, tok_str); processed_str = resolveEscapeSequences(cmp, tok_str);
List_pushAsBytes(&ddf->data_bytes, processed_str.data, 0, processed_str.size); List_u8_pushBytes(&ddf->data, processed_str.data, 0, processed_str.len);
free(processed_str.data); free(processed_str.data);
break; break;
} }
@ -161,7 +158,7 @@ static void parseDataDefinition(Compiler* cmp, str instr_name, DataDefinition* d
static void parseOperation(Compiler* cmp, str instr_name, Operation* operPtr){ static void parseOperation(Compiler* cmp, str instr_name, Operation* operPtr){
Token tok = ((Token*)cmp->tokens.data)[cmp->tok_i]; Token tok = cmp->tokens.data[cmp->tok_i];
const Instruction* instr = Instruction_getByName(instr_name); const Instruction* instr = Instruction_getByName(instr_name);
if(instr == NULL){ if(instr == NULL){
setError_unexpectedInstruction(tok); setError_unexpectedInstruction(tok);
@ -169,12 +166,12 @@ static void parseOperation(Compiler* cmp, str instr_name, Operation* operPtr){
} }
operPtr->opcode = instr->opcode; operPtr->opcode = instr->opcode;
operPtr->args = List_alloc(Argument, 8); operPtr->args = List_Argument_alloc(8);
Argument arg = (Argument){ .type = ArgumentType_Unset, .value.i = 0 }; Argument arg = (Argument){ .type = ArgumentType_Unset, .value.i = 0 };
str tok_str = str_null; str tok_str = str_null;
str processed_str = str_null; str processed_str = str_null;
while(++cmp->tok_i < List_len(&cmp->tokens, Token)){ while(++cmp->tok_i < cmp->tokens.len){
tok = ((Token*)cmp->tokens.data)[cmp->tok_i]; tok = cmp->tokens.data[cmp->tok_i];
switch(tok.type){ switch(tok.type){
case TokenType_SingleLineComment: case TokenType_SingleLineComment:
case TokenType_MultiLineComment: case TokenType_MultiLineComment:
@ -201,7 +198,7 @@ static void parseOperation(Compiler* cmp, str instr_name, Operation* operPtr){
arg.value.i = atoll(processed_str.data); arg.value.i = atoll(processed_str.data);
} }
free(processed_str.data); free(processed_str.data);
List_push(&operPtr->args, Argument, arg); List_Argument_push(&operPtr->args, arg);
break; break;
case TokenType_Name: case TokenType_Name:
tok_str = Compiler_constructTokenStr(cmp, tok); tok_str = Compiler_constructTokenStr(cmp, tok);
@ -213,23 +210,23 @@ static void parseOperation(Compiler* cmp, str instr_name, Operation* operPtr){
arg.type = ArgumentType_VarDataName; arg.type = ArgumentType_VarDataName;
arg.value.data_name = tok_str; arg.value.data_name = tok_str;
} }
List_push(&operPtr->args, Argument, arg); List_Argument_push(&operPtr->args, arg);
break; break;
case TokenType_NamedDataPointer: case TokenType_NamedDataPointer:
tok_str = Compiler_constructTokenStr(cmp, tok); tok_str = Compiler_constructTokenStr(cmp, tok);
tok_str.data++; tok_str.data++;
tok_str.size--; tok_str.len--;
arg.type = ArgumentType_ConstDataPointer; arg.type = ArgumentType_ConstDataPointer;
arg.value.data_name = tok_str; arg.value.data_name = tok_str;
List_push(&operPtr->args, Argument, arg); List_Argument_push(&operPtr->args, arg);
break; break;
case TokenType_NamedDataSize: case TokenType_NamedDataSize:
tok_str = Compiler_constructTokenStr(cmp, tok); tok_str = Compiler_constructTokenStr(cmp, tok);
tok_str.data++; tok_str.data++;
tok_str.size--; tok_str.len--;
arg.type = ArgumentType_ConstDataSize; arg.type = ArgumentType_ConstDataSize;
arg.value.data_name = tok_str; arg.value.data_name = tok_str;
List_push(&operPtr->args, Argument, arg); List_Argument_push(&operPtr->args, arg);
break; break;
} }
} }
@ -241,8 +238,8 @@ bool Compiler_parse(Compiler* cmp){
Token tok; Token tok;
Section* sec = NULL; Section* sec = NULL;
while(cmp->tok_i < List_len(&cmp->tokens, Token)){ while(cmp->tok_i < cmp->tokens.len){
tok = ((Token*)cmp->tokens.data)[cmp->tok_i]; tok = cmp->tokens.data[cmp->tok_i];
switch(tok.type){ switch(tok.type){
case TokenType_Unset: case TokenType_Unset:
returnError(Error_TokenUnset); returnError(Error_TokenUnset);
@ -252,8 +249,8 @@ bool Compiler_parse(Compiler* cmp){
break; break;
case TokenType_Label: case TokenType_Label:
// create new section // create new section
sec = List_expand_size(&cmp->ast.sections, sizeof(Section)); sec = List_Section_expand(&cmp->ast.sections, 1);
Section_construct(sec, Compiler_constructTokenStr(cmp, tok)); Section_init(sec, Compiler_constructTokenStr(cmp, tok));
break; break;
case TokenType_Instruction: case TokenType_Instruction:
if(sec == NULL) if(sec == NULL)
@ -261,15 +258,11 @@ bool Compiler_parse(Compiler* cmp){
str instr_name = Compiler_constructTokenStr(cmp, tok); str instr_name = Compiler_constructTokenStr(cmp, tok);
// data definition starts with const // data definition starts with const
if(str_startsWith(instr_name, STR("const"))){ if(str_startsWith(instr_name, STR("const"))){
DataDefinition* dataDefPtr = List_expand_size( DataDefinition* dataDefPtr = List_DataDefinition_expand(&sec->data, 1);
&sec->data_definitions_list, sizeof(DataDefinition));
memset(dataDefPtr, 0, sizeof(DataDefinition));
parseDataDefinition(cmp, instr_name, dataDefPtr); parseDataDefinition(cmp, instr_name, dataDefPtr);
} }
else { else {
Operation* operPtr = List_expand_size( Operation* operPtr = List_Operation_expand(&sec->code, 1);
&sec->operations_list, sizeof(Operation));
memset(operPtr, 0, sizeof(Operation));
parseOperation(cmp, instr_name, operPtr); parseOperation(cmp, instr_name, operPtr);
} }
break; break;

View File

@ -1,6 +1,8 @@
#include "Token.h" #include "Token.h"
static Array(str) _TokenType_str_array = ARRAY(str, { List_define(Token);
static str _TokenType_str[] = {
STR("Unset"), STR("Unset"),
STR("SingleLineComment"), STR("SingleLineComment"),
STR("MultiLineComment"), STR("MultiLineComment"),
@ -13,10 +15,10 @@ static Array(str) _TokenType_str_array = ARRAY(str, {
STR("NamedDataPointer"), STR("NamedDataPointer"),
STR("NamedDataSize"), STR("NamedDataSize"),
STR("OperationEnd"), STR("OperationEnd"),
}); };
str TokenType_toString(TokenType t){ str TokenType_toString(TokenType t){
if(t >= Array_len(&_TokenType_str_array, str)) if(t >= ARRAY_SIZE(_TokenType_str))
return STR("!!TokenType INDEX_ERROR!!"); return STR("!!TokenType INDEX_ERROR!!");
return ((str*)_TokenType_str_array.data)[t]; return _TokenType_str[t];
} }

View File

@ -1,7 +1,7 @@
#pragma once #pragma once
#include "tlibc/std.h" #include "../std.h"
#include "tlibc/string/str.h" #include "../string/str.h"
#include "tlibc/collections/List.h" #include "../collections/List.h"
typedef enum TokenType { typedef enum TokenType {
TokenType_Unset, // initial value TokenType_Unset, // initial value
@ -26,4 +26,6 @@ typedef struct Token {
TokenType type : 8; // type of token (8 bits) TokenType type : 8; // type of token (8 bits)
} Token; } Token;
List_declare(Token);
#define Token_construct(TYPE, BEGIN, LEN) ((Token){ .type = TYPE, .begin = BEGIN, .length = LEN }) #define Token_construct(TYPE, BEGIN, LEN) ((Token){ .type = TYPE, .begin = BEGIN, .length = LEN })

52
src/cstr.c Normal file
View File

@ -0,0 +1,52 @@
#include "std.h"
char* _strcat_malloc(size_t n, cstr str0, ...){
va_list argv;
va_start(argv, str0);
char* heap_ptr = _vstrcat_malloc(n, str0, argv);
va_end(argv);
return heap_ptr;
}
char* _vstrcat_malloc(size_t n, cstr str0, va_list argv){
size_t str0_len = strlen(str0);
size_t total_len = str0_len;
cstr* const parts = malloc(sizeof(cstr) * n);
size_t* const part_lengths = malloc(sizeof(size_t) * n);
for(size_t i = 0; i < n; i++){
cstr part = va_arg(argv, cstr);
size_t length = strlen(part);
parts[i] = part;
part_lengths[i] = length;
total_len += length;
}
char* const buf = malloc(total_len + 1);
memcpy(buf, str0, str0_len);
char* walking_ptr = buf + str0_len;
for(size_t i = 0; i < n; i++){
memcpy(walking_ptr, parts[i], part_lengths[i]);
walking_ptr += part_lengths[i];
}
buf[total_len] = '\0';
free(parts);
free(part_lengths);
return buf;
}
char* NULLABLE(sprintf_malloc)(size_t buffer_size, cstr format, ...){
va_list argv;
va_start(argv, format);
char* NULLABLE(heap_ptr) = vsprintf_malloc(buffer_size, format, argv);
va_end(argv);
return heap_ptr;
}
char* NULLABLE(vsprintf_malloc)(size_t buffer_size, cstr format, va_list argv){
char* buf = malloc(buffer_size);
int r = vsprintf(buf, format, argv);
if(r < 0){
free(buf);
return NULL;
}
return buf;
}

View File

@ -1,36 +0,0 @@
#include "impl_macros.h"
// JUMP [destination address]
i32 JMP_impl(VM* vm){
u64 dst_addr = 0;
readVar(dst_addr);
vm->current_pos = dst_addr;
return sizeof(dst_addr);
}
// JNZ [destination address]
i32 JNZ_impl(VM* vm){
u64 dst_addr = 0;
readVar(dst_addr);
if(vm->flags.cmp != 0){
vm->current_pos = dst_addr;
}
return sizeof(dst_addr);
}
// JZ [destination address]
i32 JZ_impl(VM* vm){
u64 dst_addr = 0;
readVar(dst_addr);
if(vm->flags.cmp == 0){
vm->current_pos = dst_addr;
}
return sizeof(dst_addr);
}

View File

@ -0,0 +1,16 @@
#include "impl_macros.h"
/// MOV [dst_register] [src_register]
i32 MOV_impl(VM* vm){
u8 dst_register_i = 0;
readRegisterVar(dst_register_i);
u8 src_register_i = 0;
readRegisterVar(src_register_i);
if(dst_register_i == src_register_i){
VM_setError(vm, "dst_register_i == src_register_i (%x) ", src_register_i);
return -1;
}
vm->registers[dst_register_i].u32v = vm->registers[src_register_i].u32v;
return sizeof(dst_register_i) + sizeof(src_register_i);
}

View File

@ -1,12 +0,0 @@
#include "impl_macros.h"
/// MOVC [dst_register] [value_size] [value]
i32 MOVC_impl(VM* vm){
RegisterCode dst_reg_code = 0;
readRegisterCode(dst_reg_code);
u64 const_value = 0;
readVar(const_value);
VM_registerWrite(vm, &const_value, dst_reg_code);
return sizeof(dst_reg_code) + sizeof(const_value);
}

View File

@ -1,17 +0,0 @@
#include "impl_macros.h"
/// MOVR [dst_register] [src_register]
i32 MOVR_impl(VM* vm){
RegisterCode dst_reg_code = 0, src_reg_code = 0;
readRegisterCode(dst_reg_code);
readRegisterCode(src_reg_code);
if(dst_reg_code == src_reg_code){
VM_setError(vm, "dst_reg_code == src_reg_code (%x) ", src_reg_code);
return -1;
}
u64 src_reg_value = 0;
VM_registerRead(vm, &src_reg_value, src_reg_code);
VM_registerWrite(vm, &src_reg_value, dst_reg_code);
return sizeof(dst_reg_code) + sizeof(src_reg_code);
}

View File

@ -0,0 +1,17 @@
#include "impl_macros.h"
/// PUSH [dst_register] [value_size] [value]
i32 PUSH_impl(VM* vm){
u8 dst_register_i = 0;
readRegisterVar(dst_register_i);
/*u8 value_size = 0;
readValueSizeVar(value_size);*/
u8 value_size = 4;\
vm->registers[dst_register_i].u32v = 0;
if(!VM_dataRead(vm, &vm->registers[dst_register_i].u32v, vm->current_pos, value_size))
return -1;
vm->current_pos += value_size;
return sizeof(dst_register_i) + sizeof(value_size) + value_size;
}

View File

@ -1,6 +1,6 @@
#include "impl_macros.h" #include "impl_macros.h"
FILE* NULLABLE(fileFromN)(VM* vm, u8 file_n){ FILE* NULLABLE(fileFromN)(VM* vm, u32 file_n){
FILE* f = NULL; FILE* f = NULL;
switch(file_n){ switch(file_n){
case 0: f = stdin; break; case 0: f = stdin; break;
@ -15,13 +15,13 @@ FILE* NULLABLE(fileFromN)(VM* vm, u8 file_n){
} }
// sys_read // sys_read
// ah - file n // bx - file n
// rbx - buffer ptr // cx - buffer ptr
// ecx - buffer size // dx - buffer size
i32 SYS_read(VM* vm){ i32 SYS_read(VM* vm){
const u8 file_n = vm->registers.a.h; const u32 file_n = vm->bx.u32v;
u8* const buf = vm->data + vm->registers.b.rx; u8* const buf = vm->data + vm->cx.u32v;
const u32 size = vm->registers.c.ex; const u32 size = vm->dx.u32v;
if(buf + size > vm->data + vm->data_size) if(buf + size > vm->data + vm->data_size)
return 40; return 40;
@ -31,13 +31,13 @@ i32 SYS_read(VM* vm){
} }
// sys_write // sys_write
// ah - file n // bx - file n
// rbx - buffer ptr // cx - buffer ptr
// ecx - buffer size // dx - buffer size
i32 SYS_write(VM* vm){ i32 SYS_write(VM* vm){
const u8 file_n = vm->registers.a.h; const u32 file_n = vm->bx.u32v;
u8* const buf = vm->data + vm->registers.b.rx; u8* const buf = vm->data + vm->cx.u32v;
const u32 size = vm->registers.c.ex; const u32 size = vm->dx.u32v;
if(buf + size > vm->data + vm->data_size) if(buf + size > vm->data + vm->data_size)
return 41; return 41;
@ -47,16 +47,16 @@ i32 SYS_write(VM* vm){
} }
/// SYS /// SYS
/// before call: al - func code /// before call: ax - func code
/// after call: eax - result code /// after call: ax - result code
i32 SYS_impl(VM* vm){ i32 SYS_impl(VM* vm){
u8 func_code = vm->registers.a.l; u8 func_code = vm->ax.u8v0;
i32 result_code = 0; u32 result_code = 0;
switch(func_code){ switch(func_code){
case 0: case 0:
result_code = SYS_read(vm); result_code = SYS_read(vm);
break; break;
case 1: case 1:;
result_code = SYS_write(vm); result_code = SYS_write(vm);
break; break;
default: default:
@ -64,6 +64,6 @@ i32 SYS_impl(VM* vm){
return -1; return -1;
} }
vm->registers.a.ex = result_code; vm->ax.u32v = result_code;
return 0; return 0;
} }

View File

@ -1,6 +1,6 @@
#pragma once #pragma once
#include "instructions/instructions.h" #include "../instructions.h"
#include "instructions/registers.h" #include "../registers.h"
#define readVar(VAR) {\ #define readVar(VAR) {\
if(!VM_dataRead(vm, &VAR, vm->current_pos, sizeof(VAR))) \ if(!VM_dataRead(vm, &VAR, vm->current_pos, sizeof(VAR))) \
@ -8,52 +8,29 @@
vm->current_pos += sizeof(VAR);\ vm->current_pos += sizeof(VAR);\
} }
#define validateRegisterCode(VAR) \ #define validateRegisterIndex(VAR) {\
if(VAR == RegisterCode_Unset || VAR > RegisterCode_dh){\ if(VAR> sizeof(vm->registers)){\
VM_setError(vm, "invalid register index (%x)", VAR);\ VM_setError(vm, "invalid register index (%x)", VAR);\
return -1;\ return -1;\
} }\
}
#define readRegisterCode(VAR) {\ #define readRegisterVar(VAR) {\
readVar(VAR);\ readVar(VAR);\
validateRegisterCode(VAR);\ VAR -= 1;\
validateRegisterIndex(VAR);\
} }
#define OPERATOR_IMPL_1(NAME, OPERATOR)\ /*
i32 NAME##_impl (VM* vm) {\ #define validateValueSize(VAR) {\
RegisterCode dst_reg_code = 0;\ if(VAR < 1 || VAR > 4){\
readRegisterCode(dst_reg_code);\ VM_setError(vm, "invalid value_size (%x)", VAR);\
u64 dst_reg_value = 0;\ return -1;\
VM_registerRead(vm, &dst_reg_value, dst_reg_code);\ }\
\
dst_reg_value = OPERATOR dst_reg_value;\
VM_registerWrite(vm, &dst_reg_value, dst_reg_code);\
return sizeof(dst_reg_code);\
} }
#define OPERATOR_IMPL_2(NAME, OPERATOR)\ #define readValueSizeVar(VAR) {\
i32 NAME##_impl (VM* vm) {\ readVar(VAR);\
RegisterCode dst_reg_code = 0, src_reg_code = 0;\ validateValueSize(VAR);\
readRegisterCode(dst_reg_code);\
readRegisterCode(src_reg_code);\
u64 dst_reg_value = 0, src_reg_value = 0;\
VM_registerRead(vm, &dst_reg_value, dst_reg_code);\
VM_registerRead(vm, &src_reg_value, src_reg_code);\
\
dst_reg_value = dst_reg_value OPERATOR src_reg_value;\
VM_registerWrite(vm, &dst_reg_value, dst_reg_code);\
return sizeof(dst_reg_code) + sizeof(src_reg_code);\
}
#define OPERATOR_IMPL_CMP_FLAG(NAME, OPERATOR)\
i32 NAME##_impl (VM* vm) {\
RegisterCode src0_reg_code = 0, src1_reg_code = 0;\
readRegisterCode(src0_reg_code);\
readRegisterCode(src1_reg_code);\
u64 src0_reg_value = 0, src1_reg_value = 0;\
VM_registerRead(vm, &src0_reg_value, src0_reg_code);\
VM_registerRead(vm, &src1_reg_value, src1_reg_code);\
\
vm->flags.cmp = src0_reg_value OPERATOR src1_reg_value;\
return sizeof(src0_reg_code) + sizeof(src1_reg_code);\
} }
*/

View File

@ -1,36 +0,0 @@
#include "impl_macros.h"
/// NOT [dst_register]
OPERATOR_IMPL_1(NOT, !)
/// INV [dst_register]
OPERATOR_IMPL_1(INV, ~)
/// OR [dst_register] [src_register]
OPERATOR_IMPL_2(OR, |)
/// XOR [dst_register] [src_register]
OPERATOR_IMPL_2(XOR, ^)
/// AND [dst_register] [src_register]
OPERATOR_IMPL_2(AND, &)
/// EQ [src0_register] [src1_register]
OPERATOR_IMPL_CMP_FLAG(EQ, ==)
/// NE [src0_register] [src1_register]
OPERATOR_IMPL_CMP_FLAG(NE, !=)
/// LT [src0_register] [src1_register]
OPERATOR_IMPL_CMP_FLAG(LT, <)
/// LE [src0_register] [src1_register]
OPERATOR_IMPL_CMP_FLAG(LE, <=)
/// GT [src0_register] [src1_register]
OPERATOR_IMPL_CMP_FLAG(GT, >)
/// GE [src0_register] [src1_register]
OPERATOR_IMPL_CMP_FLAG(GE, >=)

View File

@ -1,16 +1,48 @@
#include "impl_macros.h" #include "impl_macros.h"
#define mathOperatorImpl(OPERATOR){\
u8 dst_register_i = 0, src_register_i = 0;\
readRegisterVar(dst_register_i);\
readRegisterVar(src_register_i);\
/*u8 value_size = 0;\
readValueSizeVar(value_size);*/\
u8 value_size = 4;\
\
switch(value_size){\
case 1: \
vm->registers[dst_register_i].u8v0 OPERATOR##= vm->registers[src_register_i].u8v0;\
break;\
case 2: \
vm->registers[dst_register_i].u16v0 OPERATOR##= vm->registers[src_register_i].u16v0;\
break;\
case 4: \
vm->registers[dst_register_i].u32v OPERATOR##= vm->registers[src_register_i].u32v;\
break;\
}\
return sizeof(dst_register_i) + sizeof(src_register_i) + sizeof(value_size);\
}
/// ADD [dst_register] [src_register] /// ADD [dst_register] [src_register]
OPERATOR_IMPL_2(ADD, +) i32 ADD_impl(VM* vm){
mathOperatorImpl(+);
}
/// SUB [dst_register] [src_register] /// SUB [dst_register] [src_register]
OPERATOR_IMPL_2(SUB, -) i32 SUB_impl(VM* vm){
mathOperatorImpl(-);
}
/// MUL [dst_register] [src_register] /// MUL [dst_register] [src_register]
OPERATOR_IMPL_2(MUL, *) i32 MUL_impl(VM* vm){
mathOperatorImpl(*)
}
/// DIV [dst_register] [src_register] /// DIV [dst_register] [src_register]
OPERATOR_IMPL_2(DIV, /) i32 DIV_impl(VM* vm){
mathOperatorImpl(/)
}
/// MOD [dst_register] [src_register] /// MOD [dst_register] [src_register]
OPERATOR_IMPL_2(MOD, %) i32 MOD_impl(VM* vm){
mathOperatorImpl(%)
}

View File

@ -1,101 +1,65 @@
#include "instructions.h" #include "instructions.h"
#include "tlibc/collections/HashMap.h" #include "../collections/HashMap.h"
i32 NOP_impl(VM* vm); i32 NOP_impl(VM* vm);
i32 EXIT_impl(VM* vm); i32 PUSH_impl(VM* vm);
i32 SYS_impl(VM* vm); i32 MOV_impl(VM* vm);
i32 MOVC_impl(VM* vm);
i32 MOVR_impl(VM* vm);
i32 ADD_impl(VM* vm); i32 ADD_impl(VM* vm);
i32 SUB_impl(VM* vm); i32 SUB_impl(VM* vm);
i32 MUL_impl(VM* vm); i32 MUL_impl(VM* vm);
i32 DIV_impl(VM* vm); i32 DIV_impl(VM* vm);
i32 MOD_impl(VM* vm); i32 MOD_impl(VM* vm);
i32 SYS_impl(VM* vm);
i32 EQ_impl(VM* vm); i32 EXIT_impl(VM* vm);
i32 NE_impl(VM* vm);
i32 LT_impl(VM* vm);
i32 LE_impl(VM* vm);
i32 GT_impl(VM* vm);
i32 GE_impl(VM* vm);
i32 NOT_impl(VM* vm);
i32 INV_impl(VM* vm);
i32 OR_impl(VM* vm);
i32 XOR_impl(VM* vm);
i32 AND_impl(VM* vm);
i32 JMP_impl(VM* vm); i32 JMP_impl(VM* vm);
i32 JNZ_impl(VM* vm); i32 CALL_impl(VM* vm);
i32 JZ_impl(VM* vm);
Array_declare(Instruction);
static const Array(Instruction) instructions_array = ARRAY(Instruction, { static const Array_Instruction instructions_array = ARRAY(Instruction, {
Instruction_construct(NOP), Instruction_construct(NOP),
Instruction_construct(EXIT), Instruction_construct(PUSH),
Instruction_construct(SYS), Instruction_construct(MOV),
Instruction_construct(MOVC),
Instruction_construct(MOVR),
Instruction_construct(ADD), Instruction_construct(ADD),
Instruction_construct(SUB), Instruction_construct(SUB),
Instruction_construct(MUL), Instruction_construct(MUL),
Instruction_construct(DIV), Instruction_construct(DIV),
Instruction_construct(MOD), Instruction_construct(MOD),
Instruction_construct(SYS),
Instruction_construct(EQ), Instruction_construct(EXIT),
Instruction_construct(NE), // Instruction_construct(JMP),
Instruction_construct(LT), // Instruction_construct(CALL),
Instruction_construct(LE),
Instruction_construct(GT),
Instruction_construct(GE),
Instruction_construct(NOT),
Instruction_construct(INV),
Instruction_construct(OR),
Instruction_construct(XOR),
Instruction_construct(AND),
Instruction_construct(JMP),
Instruction_construct(JNZ),
Instruction_construct(JZ),
}); });
const Instruction* Instruction_getByOpcode(Opcode opcode){ const Instruction* Instruction_getByOpcode(Opcode opcode){
if(opcode >= Array_len(&instructions_array, Instruction)) if(opcode >= instructions_array.len)
return NULL; return NULL;
return (Instruction*)instructions_array.data + opcode; return instructions_array.data + opcode;
} }
HashMap_declare(Instruction);
HashMap_define(Instruction, HashMap_DESTROY_VALUE_FUNC_NULL);
static HashMap(Opcode)* opcode_map = NULL; static HashMap_Instruction* instructions_map = NULL;
static void _opcode_map_construct(){
opcode_map = malloc(sizeof(*opcode_map));
HashMap_construct(opcode_map, Opcode, NULL);
for(u32 i = 0; i < Array_len(&instructions_array, Instruction); i++){
Instruction* instr_ptr = (Instruction*)instructions_array.data + i;
HashMap_tryPush(opcode_map, instr_ptr->name, &instr_ptr->opcode);
}
}
const Instruction* Instruction_getByName(str name){ const Instruction* Instruction_getByName(str name){
if(opcode_map == NULL) if(instructions_map == NULL){
_opcode_map_construct(); instructions_map = malloc(sizeof(HashMap_Instruction));
HashMap_Instruction_alloc(instructions_map);
for(u32 i = 0; i < instructions_array.len; i++){
HashMap_Instruction_tryPush(instructions_map, instructions_array.data[i].name, instructions_array.data[i]);
}
}
str name_upper = str_toUpper(name); str name_upper = str_toUpper(name);
Opcode* op_ptr = HashMap_tryGetPtr(opcode_map, name_upper); Instruction* iptr = HashMap_Instruction_tryGetPtr(instructions_map, name_upper);
free(name_upper.data); free(name_upper.data);
if(op_ptr == NULL) return iptr;
return NULL;
return Instruction_getByOpcode(*op_ptr);
} }
void Instruction_destroySearchStructs(){ void Instruction_freeSearchStructs(){
if(opcode_map != NULL){ if(instructions_map != NULL){
HashMap_destroy(opcode_map); HashMap_Instruction_free(instructions_map);
free(opcode_map); free(instructions_map);
} }
} }

View File

@ -1,5 +1,5 @@
#pragma once #pragma once
#include "VM/VM.h" #include "../VM/VM.h"
///@param program_pos position in vm->program next afrer opcode ///@param program_pos position in vm->program next afrer opcode
///@returns number of bytes read ///@returns number of bytes read
@ -7,33 +7,15 @@ typedef i32 (*InstructionImplFunc_t)(VM* vm);
typedef enum __attribute__((__packed__)) Opcode { typedef enum __attribute__((__packed__)) Opcode {
Opcode_NOP, Opcode_NOP,
Opcode_EXIT, Opcode_PUSH,
Opcode_SYS, Opcode_MOV,
Opcode_MOVC,
Opcode_MOVR,
Opcode_ADD, Opcode_ADD,
Opcode_SUB, Opcode_SUB,
Opcode_MUL, Opcode_MUL,
Opcode_DIV, Opcode_DIV,
Opcode_MOD, Opcode_MOD,
Opcode_SYS,
Opcode_EQ, Opcode_EXIT,
Opcode_NE,
Opcode_LT,
Opcode_LE,
Opcode_GT,
Opcode_GE,
Opcode_NOT,
Opcode_INV,
Opcode_OR,
Opcode_XOR,
Opcode_AND,
Opcode_JMP,
Opcode_JNZ,
Opcode_JZ,
} Opcode; } Opcode;
typedef struct Instruction { typedef struct Instruction {
@ -53,4 +35,4 @@ typedef struct Instruction {
/// @return ptr to struct or NULL /// @return ptr to struct or NULL
const Instruction* NULLABLE(Instruction_getByOpcode)(Opcode opcode); const Instruction* NULLABLE(Instruction_getByOpcode)(Opcode opcode);
const Instruction* NULLABLE(Instruction_getByName)(str name); const Instruction* NULLABLE(Instruction_getByName)(str name);
void Instruction_destroySearchStructs(); void Instruction_freeSearchStructs();

View File

@ -1,76 +1,13 @@
#include "registers.h" #include "registers.h"
#define check_code(R) if(str_equals(lower, STR(#R))) code = RegisterCode_##R;
RegisterCode RegisterCode_parse(str r){ RegisterCode RegisterCode_parse(str r){
str lower = str_toLower(r); if(str_equals(r, STR("ax")))
RegisterCode code = RegisterCode_Unset; return RegisterCode_ax;
// a if(str_equals(r, STR("bx")))
check_code(rax) return RegisterCode_bx;
else check_code(eax) if(str_equals(r, STR("cx")))
else check_code(ax) return RegisterCode_cx;
else check_code(al) if(str_equals(r, STR("dx")))
else check_code(ah) return RegisterCode_dx;
// b return RegisterCode_Unset;
else check_code(rbx)
else check_code(ebx)
else check_code(bx)
else check_code(bl)
else check_code(bh)
// c
else check_code(rcx)
else check_code(ecx)
else check_code(cx)
else check_code(cl)
else check_code(ch)
//d
else check_code(rdx)
else check_code(edx)
else check_code(dx)
else check_code(dl)
else check_code(dh)
free(lower.data);
return code;
} }
str RegisterCode_toString(RegisterCode code){
char buf[3] = { '?', 'a', 'x' };
u8 index = code / 0x10;
switch(index){
default:
return str_copy(STR("!!! ERROR: invalid RegisterCode !!!"));
case 0:
case 1:
case 2:
case 3:
buf[1] += index;
break;
}
str buf_str = str_construct(buf, 3, false);
switch(code & 0xf){
default:
return str_copy(STR("!!! ERROR: invalid RegisterCode !!!"));
case 1:
buf_str.data[0] = 'r';
break;
case 2:
buf_str.data[0] = 'e';
break;
case 4:
buf_str.data += 1;
buf_str.size -= 1;
break;
case 7:
buf_str.data[0] = 'l';
buf_str.size -= 1;
break;
case 8:
buf_str.data[0] = 'h';
buf_str.size -= 1;
break;
}
return str_copy(buf_str);
}

View File

@ -1,35 +1,13 @@
#pragma once #pragma once
#include "tlibc/std.h" #include "../std.h"
#include "tlibc/string/str.h" #include "../string/str.h"
typedef enum RegisterCode { typedef enum RegisterCode {
RegisterCode_Unset = 0, RegisterCode_Unset,
RegisterCode_ax,
RegisterCode_rax = 0x01, RegisterCode_bx,
RegisterCode_eax = 0x02, RegisterCode_cx,
RegisterCode_ax = 0x04, RegisterCode_dx
RegisterCode_al = 0x07, } RegisterCode;
RegisterCode_ah = 0x08,
RegisterCode_rbx = 0x11,
RegisterCode_ebx = 0x12,
RegisterCode_bx = 0x14,
RegisterCode_bl = 0x17,
RegisterCode_bh = 0x18,
RegisterCode_rcx = 0x21,
RegisterCode_ecx = 0x22,
RegisterCode_cx = 0x24,
RegisterCode_cl = 0x27,
RegisterCode_ch = 0x28,
RegisterCode_rdx = 0x31,
RegisterCode_edx = 0x32,
RegisterCode_dx = 0x34,
RegisterCode_dl = 0x37,
RegisterCode_dh = 0x38,
} __attribute__((__packed__)) RegisterCode;
RegisterCode RegisterCode_parse(str register_name); RegisterCode RegisterCode_parse(str register_name);
/// @return allocated string
str RegisterCode_toString(RegisterCode code);

View File

@ -1,11 +1,9 @@
#include "VM/VM.h" #include "VM/VM.h"
#include "instructions/instructions.h" #include "instructions/instructions.h"
#include "collections/List.h"
#include "compiler/Compiler.h" #include "compiler/Compiler.h"
#include "VM/Display/Display.h"
#include "tcpu_version.h"
#include "tlibc/time.h"
#define arg_is(LITERAL) str_equals(arg_str, STR(LITERAL)) #define arg_is(STR) (strcmp(argv[argi], STR) == 0)
i32 compileSources(cstr source_file, cstr out_file, bool debug_log); i32 compileSources(cstr source_file, cstr out_file, bool debug_log);
i32 bootFromImage(cstr image_file); i32 bootFromImage(cstr image_file);
@ -24,18 +22,15 @@ i32 main(const i32 argc, cstr* argv){
cstr NULLABLE(source_file) = NULL; cstr NULLABLE(source_file) = NULL;
bool debug_log = false; bool debug_log = false;
bool video_enabled = false;
for(i32 argi = 1; argi < argc; argi++){ for(i32 argi = 1; argi < argc; argi++){
str arg_str = str_from_cstr(argv[argi]);
if(arg_is("-h") || arg_is("--help")){ if(arg_is("-h") || arg_is("--help")){
printf( printf(
"-h, --help Show this message.\n" "-h, --help Show this message.\n"
"-d, --debug Enable debug log.\n"
"-op, --opcodes Show list of all instructions.\n" "-op, --opcodes Show list of all instructions.\n"
"-c, --compile [SOURCE_FILE] [OUT_FILE] Compile assembly source files to machine code.\n"
"-i, --image [FILE] Boot VM using image file.\n" "-i, --image [FILE] Boot VM using image file.\n"
"--video Enable VM display.\n" "-c, --compile [SOURCE_FILE] [OUT_FILE] Compile assembly source files to machine code.\n"
"-d, --debug Enable debug log.\n"
); );
return 0; return 0;
} }
@ -83,10 +78,6 @@ i32 main(const i32 argc, cstr* argv){
else if(arg_is("-d") || arg_is("--debug")){ else if(arg_is("-d") || arg_is("--debug")){
debug_log = true; debug_log = true;
} }
else if(arg_is("--video")){
video_enabled = true;
}
else { else {
printfe("ERROR: unknown argument '%s'\n", argv[argi]); printfe("ERROR: unknown argument '%s'\n", argv[argi]);
return 1; return 1;
@ -96,25 +87,13 @@ i32 main(const i32 argc, cstr* argv){
i32 exit_code = 0; i32 exit_code = 0;
if(compile){ if(compile){
exit_code = compileSources(source_file, out_file, debug_log); exit_code = compileSources(source_file, out_file, debug_log);
if(exit_code != 0)
goto main_exit;
} }
if(exit_code == 0 && boot){
if(boot){
printfe("TCPU version: " TCPU_VERSION_CSTR "\n");
if(video_enabled){
printfe("video enabled\n");
if(!Display_init(1600, 900, DisplayFlags_Default)){
printfe("DISPLAY ERROR: %s\n", Display_getError());
return 1;
}
}
exit_code = bootFromImage(image_file); exit_code = bootFromImage(image_file);
} }
// frees global variables to supress valgrind memory leak errors // frees global variables to supress valgrind memory leak errors
main_exit: Instruction_freeSearchStructs();
Instruction_destroySearchStructs();
return exit_code; return exit_code;
} }
@ -138,14 +117,11 @@ i32 bootFromImage(cstr image_file){
} }
VM vm; VM vm;
VM_construct(&vm); VM_init(&vm);
i32 exit_code = 1; i32 exit_code = 1;
if(VM_setMemory(&vm, vm_memory, bytes_read)){ if(VM_setMemory(&vm, vm_memory, bytes_read)){
printf("===============================================================================\n");
exit_code = VM_boot(&vm); exit_code = VM_boot(&vm);
printf("===============================================================================\n");
printfe("VM stopped with code %i\n", exit_code);
} }
if(vm.state == VMState_InternalError){ if(vm.state == VMState_InternalError){
if(vm.error_message){ if(vm.error_message){
@ -155,13 +131,17 @@ i32 bootFromImage(cstr image_file){
else printfe("VM ERROR: unknown (error_message is null)\n"); else printfe("VM ERROR: unknown (error_message is null)\n");
} }
if(exit_code != 0){
printfe("program exited with code %i\n", exit_code);
}
free(vm_memory); free(vm_memory);
return exit_code; return exit_code;
} }
i32 compileSources(cstr source_file, cstr out_file, bool debug_log){ i32 compileSources(cstr source_file, cstr out_file, bool debug_log){
Compiler cmp; Compiler cmp;
Compiler_construct(&cmp); Compiler_init(&cmp);
bool success = Compiler_compile(&cmp, source_file, out_file, debug_log); bool success = Compiler_compile(&cmp, source_file, out_file, debug_log);
if(!success){ if(!success){
if(cmp.error_message){ if(cmp.error_message){
@ -169,10 +149,10 @@ i32 compileSources(cstr source_file, cstr out_file, bool debug_log){
free(cmp.error_message); free(cmp.error_message);
} }
else printfe("COMPILER ERROR: unknown (error_message is null)\n"); else printfe("COMPILER ERROR: unknown (error_message is null)\n");
Compiler_destroy(&cmp); Compiler_free(&cmp);
return 111; return 111;
} }
Compiler_destroy(&cmp); Compiler_free(&cmp);
return 0; return 0;
} }

66
src/std.h Normal file
View File

@ -0,0 +1,66 @@
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <stddef.h>
#include <time.h>
#include <math.h>
#include <string.h>
typedef int8_t i8;
typedef uint8_t u8;
typedef int16_t i16;
typedef uint16_t u16;
typedef int32_t i32;
typedef uint32_t u32;
typedef int64_t i64;
typedef uint64_t u64;
typedef float f32;
typedef double f64;
typedef u8 bool;
#define true 1
#define false 0
typedef const char* cstr;
#if defined(_WIN64) || defined(_WIN32)
#define IFWIN(YES, NO) YES
#else
#define IFWIN(YES, NO) NO
#endif
#define ARRAY_SIZE(A) (sizeof(A)/sizeof(A[0]))
#define ALIGN_TO(_SIZE,_ALIGN) (((_SIZE) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1))
#define __count_args( \
a0, a1, a2, a3, a4, a5, a6, a7 , a8, a9, a10,a11,a12,a13,a14,a15, \
a16,a17,a18,a19,a20,a21,a22,a23, a24,a25,a26,a27,a28,a29,a30,a31, \
a32,a33,a34,a35,a36,a37,a38,a39, a40,a41,a42,a43,a44,a45,a46,a47, \
a48,a49,a50,a51,a52,a53,a54,a55, a56,a57,a58,a59,a60,a61,a62,a63, \
a64,...) a64
// Macro for counting variadic arguments (max 64)
// (see usage in kprint.h)
#define count_args(ARGS...) __count_args(ARGS, \
64,63,62,61,60,59,58,57, 56,55,54,53,52,51,50,49, \
48,47,46,45,44,43,42,41, 40,39,38,37,36,35,34,33, \
32,31,30,29,28,27,26,25, 24,23,22,21,20,19,18,17, \
16,15,14,13,12,11,10,9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define printfe(FORMAT, ...) fprintf(stderr, FORMAT ,##__VA_ARGS__)
/// @warning pointer can be null
#define NULLABLE(NAME) NAME
#define strcat_malloc(STR0, ...) _strcat_malloc(count_args(__VA_ARGS__), STR0, __VA_ARGS__)
char* _strcat_malloc(size_t n, cstr str0, ...);
char* _vstrcat_malloc(size_t n, cstr str0, va_list argv);
char* NULLABLE(sprintf_malloc)(size_t buffer_size, cstr format, ...) __attribute__((__format__(__printf__, 2, 3)));
char* NULLABLE(vsprintf_malloc)(size_t buffer_size, cstr format, va_list argv);
static inline bool isAlphabeticalLower(char c) { return 'a' <= c && c <= 'z'; }
static inline bool isAlphabeticalUpper(char c) { return 'A' <= c && c <= 'Z'; }
static inline bool isDigit(char c) { return '0' <= c && c <= '9'; }

View File

@ -0,0 +1,53 @@
#include "StringBuilder.h"
void StringBuilder_free(StringBuilder* b){
free(b->buffer.data);
b->buffer = List_u8_construct(NULL, 0, 0);
}
str StringBuilder_getStr(StringBuilder* b){
List_u8_push(&b->buffer, '\0');
str result = str_construct((char*)b->buffer.data, b->buffer.len - 1, true);
return result;
}
void StringBuilder_removeFromEnd(StringBuilder* b, u32 count){
if(count < b->buffer.len){
b->buffer.len -= count;
}
else{
b->buffer.len = 0;
}
}
void StringBuilder_append_char(StringBuilder* b, char c){
List_u8_push(&b->buffer, c);
}
void StringBuilder_append_string(StringBuilder* b, str s){
List_u8_pushMany(&b->buffer, (u8*)s.data, s.len);
}
void StringBuilder_append_cstr(StringBuilder* b, char* s){
StringBuilder_append_string(b, str_construct(s, strlen(s), true));
}
void StringBuilder_append_i64(StringBuilder* b, i64 n){
char buf[32];
sprintf(buf, IFWIN("%lli", "%li"), n);
StringBuilder_append_cstr(b, buf);
}
void StringBuilder_append_u64(StringBuilder* b, u64 n){
char buf[32];
sprintf(buf, IFWIN("%llu", "%lu"), n);
StringBuilder_append_cstr(b, buf);
}
void StringBuilder_append_f64(StringBuilder* b, f64 n){
char buf[32];
sprintf(buf, "%lf", n);
StringBuilder_append_cstr(b, buf);
}

View File

@ -0,0 +1,25 @@
#pragma once
#include "../collections/List.h"
#include "str.h"
typedef struct StringBuilder {
List_u8 buffer;
} StringBuilder;
static inline StringBuilder StringBuilder_alloc(u32 initial_size) {
return (StringBuilder){ .buffer = List_u8_alloc(initial_size) };
}
void StringBuilder_free(StringBuilder* b);
/// @param count set to -1 to clear StringBuilder
void StringBuilder_removeFromEnd(StringBuilder* b, u32 count);
void StringBuilder_append_char(StringBuilder* b, char c);
void StringBuilder_append_cstr(StringBuilder* b, char* s);
void StringBuilder_append_string(StringBuilder* b, str s);
void StringBuilder_append_i64(StringBuilder* b, i64 a);
void StringBuilder_append_u64(StringBuilder* b, u64 a);
void StringBuilder_append_f64(StringBuilder* b, f64 a);
// adds '\0' to the buffer and returns pointer to buffer content
str StringBuilder_getStr(StringBuilder* b);

125
src/string/str.c Normal file
View File

@ -0,0 +1,125 @@
#include "str.h"
str str_copy(str src){
if(src.data == NULL || src.len == 0)
return src;
str nstr = str_construct((char*)malloc(src.len + 1), src.len, true);
memcpy(nstr.data, src.data, src.len);
nstr.data[nstr.len] = '\0';
return nstr;
}
bool str_equals(str s0, str s1){
if(s0.len != s1.len)
return false;
for(u32 i = 0; i < s0.len; i++)
if(s0.data[i] != s1.data[i])
return false;
return true;
}
str str_reverse(str s){
if(s.data == NULL || s.len == 0)
return s;
str r = str_construct(malloc(s.len), s.len, s.isZeroTerminated);
for(u32 i = 0; i < s.len; i++ )
r.data[i] = s.data[s.len - i - 1];
return r;
}
i32 str_seek(str src, str fragment, u32 startIndex){
if(src.len == 0 || fragment.len == 0)
return -1;
for(u32 i = startIndex; i < src.len - fragment.len + 1; i++){
for(u32 j = 0;; j++){
if(j == fragment.len)
return i;
if(src.data[i + j] != fragment.data[j])
break;
}
}
return -1;
}
i32 str_seekReverse(str src, str fragment, u32 startIndex){
if(src.len == 0 || fragment.len == 0)
return -1;
if(startIndex > src.len - 1)
startIndex = src.len - 1;
for(u32 i = startIndex; i >= fragment.len - 1; i--){
for(u32 j = 0;; j++){
if(j == fragment.len)
return i - j + 1;
if(src.data[i - j] != fragment.data[fragment.len - 1 - j])
break;
}
}
return -1;
}
i32 str_seekChar(str src, char c, u32 startIndex){
for(u32 i = startIndex; i < src.len; i++){
if(src.data[i] == c)
return i;
}
return -1;
}
i32 str_seekCharReverse(str src, char c, u32 startIndex){
if(startIndex > src.len - 1)
startIndex = src.len - 1;
for(u32 i = startIndex; i != (u32)-1; i--){
if(src.data[i] == c)
return i;
}
return -1;
}
bool str_startsWith(str src, str fragment){
if(src.len < fragment.len)
return false;
src.len = fragment.len;
return str_equals(src, fragment);
}
bool str_endsWith(str src, str fragment){
if(src.len < fragment.len)
return false;
src.data = (char*)(src.data + src.len - fragment.len);
src.len = fragment.len;
return str_equals(src, fragment);
}
u32 str_hash32(str s){
u8* ubuf = (u8*)s.data;
u32 hash=0;
for (u32 i = 0; i < s.len; i++)
hash = (hash<<6) + (hash<<16) - hash + ubuf[i];
return hash;
}
str str_toUpper(str src){
str r = str_copy(src);
for (u32 i = 0; i < r.len; i++){
if(isAlphabeticalLower(r.data[i]))
r.data[i] = r.data[i] - 'a' + 'A';
}
return r;
}
str str_toLower(str src){
str r = str_copy(src);
for (u32 i = 0; i < r.len; i++){
if(isAlphabeticalUpper(r.data[i]))
r.data[i] = r.data[i] - 'A' + 'a';
}
return r;
}

41
src/string/str.h Normal file
View File

@ -0,0 +1,41 @@
#pragma once
#include "../std.h"
typedef struct str {
char* data;
u32 len;
bool isZeroTerminated;
} str;
/// creates str from a string literal
#define STR(LITERAL) str_construct(LITERAL, ARRAY_SIZE(LITERAL) - 1, true)
#define str_construct(DATA, LEN, ZERO_TERMINATED) ((str){ .data = DATA, .len = LEN, .isZeroTerminated = ZERO_TERMINATED })
static const str str_null = str_construct(NULL, 0, 0);
/// copies src content to new string and adds \0 at the end
str str_copy(str src);
/// compares two strings, NullPtr-friendly
bool str_equals(str str0, str str1);
/// allocates new string which is reversed variant of <s>
str str_reverse(str s);
i32 str_seek(str src, str fragment, u32 startIndex);
i32 str_seekReverse(str src, str fragment, u32 startIndex);
i32 str_seekChar(str src, char c, u32 startIndex);
i32 str_seekCharReverse(str src, char c, u32 startIndex);
bool str_startsWith(str src, str fragment);
bool str_endsWith(str src, str fragment);
/// @brief calculates string hash using sdbm32 algorythm (something like lightweight crc32)
/// @return non-cryptografic hash of the string
u32 str_hash32(str s);
str str_toUpper(str src);
str str_toLower(str src);

View File

@ -1,3 +0,0 @@
#pragma once
#define TCPU_VERSION_CSTR "1.0.0"