feat: failed attempt to make emscripten work

This commit is contained in:
Matthieu Bessat 2022-05-21 18:38:26 +02:00
parent bb52b98ae7
commit 110eab7a1a
43 changed files with 700 additions and 148 deletions

29
.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,29 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "gcc build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/bin/test",
"args": [],
"stopAtEntry": true,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "tasks",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}

11
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,11 @@
{
"files.associations": {
"*.ts": "typescript",
"*.asm": "python",
"stdio.h": "c",
"string_view": "c",
"state.h": "c",
"stack.h": "c",
"var_store.h": "c"
}
}

16
.vscode/tasks.json vendored Normal file
View file

@ -0,0 +1,16 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "tasks",
"type": "shell",
"command": "make test-debug",
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

6
Dockerfile Normal file
View file

@ -0,0 +1,6 @@
FROM alpine:3.14
RUN apk add gcc
RUN apk add make
RUN mkdir /app
COPY ./ /app
ENTRYPOINT ["sleep", "infinity"]

View file

@ -6,12 +6,22 @@ TEST_SRCS_ENC := $(foreach DIR,src,$(patsubst $(DIR)/%,%,$(wildcard ./src/*.c)))
TEST_SRCS_ENC := $(filter-out %main.c, $(TEST_SRCS_ENC))
build:
cp src/config_env_main.h src/config_env.h
gcc src/* -o ./bin/main ${CXXFLAGS_WITHOUT_PKGS}
test:
cp src/config_env_main.h src/config_env.h
gcc ${TEST_SRCS_ENC} ./tests/* -o ./bin/test ${CXXFLAGS_WITHOUT_PKGS}
./bin/test
test-no-run:
test-no-run: ./tests/*
cp src/config_env_main.h src/config_env.h
gcc ${TEST_SRCS_ENC} ./tests/* -o ./bin/test ${CXXFLAGS_WITHOUT_PKGS}
test-debug: ./tests/*
cp src/config_env_main.h src/config_env.h
gcc -g ${TEST_SRCS_ENC} ./tests/* -o ./bin/test ${CXXFLAGS_WITHOUT_PKGS}
emscripten:
cp wasm/config_env_wasm.h src/config_env.h
emcc -O3 -s WASM=1 -s EXPORTED_RUNTIME_METHODS=ccall,cwrap,getValue,setValue \
./wasm/emscripten.c ${TEST_SRCS_ENC} -o wasm/langatator_adapter.js
sandbox:
gcc ${TEST_SRCS_ENC} ./sandbox.c -o ./bin/sandbox ${CXXFLAGS_WITHOUT_PKGS}
./bin/sandbox

View file

@ -47,6 +47,7 @@ ToDo List:
- [ ] feat: basic number list support
- [ ] feat: fully features strings support
- [ ] feat: function to access to environment variables
- [ ] feat: hexadecimal and binary constants
- [X] feat: REPL environment
- [ ] feat: add history to REPL
@ -72,6 +73,14 @@ You will need to compile the code from source.
I use GNU Make with GCC, but I'm sure you can use any C compilers though you may need to edit some part of the code to cope with other compilers (eg. binary constants).
## Build to Web assembly
I use emscripten.org
It would be great if I'm not using emscripten.
I have to find implementation for stdlib
## Unit testing
I try to have some sort of code coverage, you can run the unit tests by issuing `make test`
@ -171,3 +180,5 @@ print_string(str)
print_newline()
print_ascii(nb)
```

8
docker-compose.yml Normal file
View file

@ -0,0 +1,8 @@
version: "3.9"
services:
app:
build:
context: ./
volumes:
- ./:/app

3
examples/sandbox2.ltor Normal file
View file

@ -0,0 +1,3 @@
print_number(2)
print_number(3)

View file

@ -1,22 +1,36 @@
// #include <stdio.h>
// #include "./src/types.h"
// #include "./src/list.h"
// #include "./src/number_parsing.h"
// #include "./src/funcs.h"
// #include "./src/utils.h"
// #include "./src/var_store.h"
// #include "./src/line_processing.h"
// #include "./src/state.h"
// #include <stdlib.h>
// #include <sys/time.h>
// #include <stddef.h>
#include <stdio.h>
#include "./src/types.h"
#include "./src/list.h"
#include "./src/number_parsing.h"
#include "./src/funcs.h"
#include "./src/utils.h"
#include "./src/var_store.h"
#include "./src/line_processing.h"
#include "./src/state.h"
#include <stdlib.h>
// #define printf_wrap(f_, ...) \
// { \
// printf_wrap("T=%d \t", (unsigned) time(NULL)); \
// printf_wrap((f_), ##__VA_ARGS__); \
// };
#define eprintf_wrap(template, ...) printf_wrap(template, ##__VA_ARGS__);
int main () {
struct VariableStore* store = var_store_init();
printf("%d", var_store_hash_name(store, "print_number index"));
int i = -1;
if (i < 0) {
printf("lol jpp \n");
}
eprintf_wrap("Hello %d %s \n", 13, "World");
// struct VariableStore* store = var_store_init();
// printf_wrap("%d", var_store_hash_name(store, "print_number index"));
// int i = -1;
// if (i < 0) {
// printf_wrap("lol jpp \n");
// }
return 0;
//struct List l1;
@ -30,32 +44,32 @@ int main () {
// int yes = 1234;
// int dst = 0;
// memcpy(&dst, &yes, 4);
// printf("yes: %d \n", dst);
// printf_wrap("yes: %d \n", dst);
//struct VariableStore* store = var_store_init();
// int hashRes = var_store_hash_name(store, "HelloWorld++");
// printf("hashRes: %d \n", hashRes);
// printf_wrap("hashRes: %d \n", hashRes);
// int val = 1234;
// var_store_set(store, "foo", TYPE_INT, &val);
// var_store_get_key(store, "while i < 10 then");
//printf("Pos of var: %d \n", var_store_get_pos(store, "foo"));
//printf_wrap("Pos of var: %d \n", var_store_get_pos(store, "foo"));
//byte type = var_store_get_type(store, "foo");
//printf("Type of var: %d \n", type);
//printf_wrap("Type of var: %d \n", type);
//int key = var_store_get_pos(store, "foo");
//printf("size of type %d \n", get_size_of_type(store->container[key].type));
//printf("%d \n", *((int*) store->container[key].dataPtr));
//printf_wrap("size of type %d \n", get_size_of_type(store->container[key].type));
//printf_wrap("%d \n", *((int*) store->container[key].dataPtr));
// int val2 = 0;
// var_store_copy(store, "foo", &val2);
// printf("Value of var: %d \n", val2);
// printf_wrap("Value of var: %d \n", val2);
// printf("==== \n");
// printf("==== \n");
// printf_wrap("==== \n");
// printf_wrap("==== \n");
// char* lines = "# hello world\n"
// "set x to 5\n"
@ -65,17 +79,17 @@ int main () {
// "end\n"
// "\n";
char* lines1 = "set x to 5\n"
"set y to 1\n"
"if !(x+y = 6) then\n"
" print_number(x+y)\n"
"end\n"
"\n";
// char* lines1 = "set x to 5\n"
// "set y to 1\n"
// "if !(x+y = 6) then\n"
// " print_number(x+y)\n"
// "end\n"
// "\n";
printf("%s", lines1);
// printf_wrap("%s", lines1);
struct StateContainer* state = state_init();
process_script(state, lines1);
// struct StateContainer* state = state_init();
// process_script(state, lines1);
// struct List l1;
@ -97,20 +111,20 @@ int main () {
// void* ptr = &res;
// printf("%d\n", sizeof(ptr));
// printf_wrap("%d\n", sizeof(ptr));
// int found = identify_func_name("ABS");
// printf("found: %d \n", found);
// printf_wrap("found: %d \n", found);
// unsigned char argsType[1] = { TYPE_FLOAT };
// int argsVals[1] = { get_int_rep_from_float(-3.145) };
// int resVal = 0;
// unsigned char resType = 0;
// execute_func(found, 1, argsType, argsVals, &resVal, &resType);
// printf("func res type: %d \n", resType);
// printf("func res: %f \n", get_float_from_int_rep(resVal));
// printf_wrap("func res type: %d \n", resType);
// printf_wrap("func res: %f \n", get_float_from_int_rep(resVal));
// int stat = parse_float("1052.254", &res);
// printf("float parsing stat: %d \n", stat);
// printf("final float: %f \n", res);
// printf_wrap("float parsing stat: %d \n", stat);
// printf_wrap("final float: %f \n", res);
}

View file

@ -1,12 +1,20 @@
#include "./config_env.h"
//#define printf_wrap(template,...) printf_wrap(template, ##__VA_ARGS__);
#define getline_wrap(...) getline(__VA_ARGS__);
#ifndef G_CONFIG_H_
#define G_CONFIG_H_
#define PRINT_METHOD_CLASSIC 0
#define PRINT_METHOD_WASM 1
// #define CONFIG_PRINT_METHOD
#define PRESET_ENGLISH 0
#define PRESET_FRENCH 1
// 0: no logs; 1: medium debug; 2: full debug
#define G_DEBUG_LEVEL 0
#define G_DEBUG_LEVEL 2
#define SYNTAX_PRESET PRESET_ENGLISH
// Define your own custom syntax here

2
src/config_env.h Normal file
View file

@ -0,0 +1,2 @@
// the config file for main and test
#define PRINT_MODE 0

2
src/config_env_main.h Normal file
View file

@ -0,0 +1,2 @@
// the config file for main and test
#define PRINT_MODE 0

View file

@ -49,7 +49,7 @@ int evaluator_reduce_operator_pattern(struct List* evalList) {
if (operateStatus != 0) {
// the pattern that matched, did not worked as expected
// this is a failure
printf("ERR Evaluator: cannot operate \n");
printf_wrap("ERR Evaluator: cannot operate \n");
return 400;
}
@ -64,7 +64,7 @@ int evaluator_reduce_operator_pattern(struct List* evalList) {
list_delete(evalList, patternPos+1);
list_delete(evalList, patternPos+1);
//printf("END OF THE FIRST OPERATION \n");
//printf_wrap("END OF THE FIRST OPERATION \n");
//list_print(&evalList);
// so we reduced an expression, return 0
@ -105,7 +105,7 @@ int evaluator_reduce_minus_pattern(struct List* evalList) {
unsigned char typeRes = 0;
int operateStatus = operate('*', TYPE_INT, -1, type, val, &typeRes, &res);
if (operateStatus != 0) {
printf("ERR Evaluator: cannot operate \n");
printf_wrap("ERR Evaluator: cannot operate \n");
return 400;
}
@ -148,7 +148,7 @@ int evaluator_reduce_not_pattern(struct List* evalList) {
byte typeRes = 0;
int operateStatus = operate('!', 0, 0, type, val, &typeRes, &res);
if (operateStatus != 0) {
printf("ERR Evaluator: cannot operate \n");
printf_wrap("ERR Evaluator: cannot operate \n");
return 400;
}
@ -208,7 +208,7 @@ int evaluator_reduce_var(struct StateContainer* state, struct List* evalList) {
byte type = var_store_get_type_from_key(state->varStore, varKey);
if (EVALUATOR_DEBUG_LEVEL >= 2) printf("Going to reduce var key %d at pos %d\n", varKey, patternPos);
if (EVALUATOR_DEBUG_LEVEL >= 2) printf_wrap("Going to reduce var key %d at pos %d\n", varKey, patternPos);
byte varVal[get_size_of_type(type)];
var_store_copy_from_key(state->varStore, varKey, &varVal);
@ -268,7 +268,7 @@ int evaluator_reduce_function_call(struct List* evalList, int initialPosition) {
// two case: either we have another arguments or we have a closing parenthesis
while (1) {
if (argsLen > 16) {
printf("ERR Evaluator: too many arguments passed to func (max out the limit) \n");
printf_wrap("ERR Evaluator: too many arguments passed to func (max out the limit) \n");
return 100;
}
if (
@ -335,16 +335,16 @@ int evaluator_reduce_function_call(struct List* evalList, int initialPosition) {
// now we can delete in the list from pos+1 patternPos to pos
// just delete N-1 times where N is the number of components in the func call
//printf("start: %d, end: %d \n", patternPos, pos);
//printf("patternPos: %d, pos: %d \n", patternPos, pos);
//printf_wrap("start: %d, end: %d \n", patternPos, pos);
//printf_wrap("patternPos: %d, pos: %d \n", patternPos, pos);
for (int j = 0; j < (pos-patternPos); j++) {
list_delete(evalList, patternPos);
}
//printf("list report after deleting after applying a func \n");
//printf_wrap("list report after deleting after applying a func \n");
//list_print(evalList);
//printf("patternPos: %d, resType: %d \n", patternPos, resType);
//printf_wrap("patternPos: %d, resType: %d \n", patternPos, resType);
list_set(evalList, patternPos, resType, &resVal);
@ -402,12 +402,12 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
// display the partition
if (EVALUATOR_DEBUG_LEVEL >= 2) {
printf("partitionPtr: %d \n", partitionPtr);
printf_wrap("partitionPtr: %d \n", partitionPtr);
}
for (int j = 0; j < partitionPtr; j++) {
if (EVALUATOR_DEBUG_LEVEL >= 2) {
printf("start %d ", partitionStartPos[j]);
printf("stop %d ", partitionStopPos[j]);
printf_wrap("start %d ", partitionStartPos[j]);
printf_wrap("stop %d ", partitionStopPos[j]);
}
int len = partitionStopPos[j] - partitionStartPos[j];
@ -419,7 +419,7 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
}
buff[len] = 0;
if (EVALUATOR_DEBUG_LEVEL >= 2) {
printf("content %s \n", buff);
printf_wrap("content %s \n", buff);
}
}
@ -441,29 +441,29 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
parenthesisCount--;
}
if (parenthesisCount < 0) {
printf("ERR Evaluator: bad parenthesizing \n");
printf_wrap("ERR Evaluator: bad parenthesizing \n");
return 100;
}
}
if (parenthesisCount > 0) {
// there is an open parenthesis, so it's an error
printf("ERR Evaluator: invalid parenthesis stack \n");
printf_wrap("ERR Evaluator: invalid parenthesis stack \n");
return 100;
}
struct List evalList;
// NOTICE: for some reason the struct don't reset after a usage
list_reset(&evalList);
if (EVALUATOR_DEBUG_LEVEL >= 2) printf("\n - constructing list \n");
if (EVALUATOR_DEBUG_LEVEL >= 2) printf_wrap("\n - constructing list \n");
// initializing the evaluation list
for (int j = 0; j < partitionPtr; j++) {
int startPos = partitionStartPos[j];
int stopPos = partitionStopPos[j];
if (EVALUATOR_DEBUG_LEVEL >= 2) {
printf("=== %d\n", j);
printf("startPos %d, stopPos %d\n", startPos, stopPos);
printf_wrap("=== %d\n", j);
printf_wrap("startPos %d, stopPos %d\n", startPos, stopPos);
}
int len = stopPos - startPos;
@ -492,7 +492,7 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
buff[len] = 0; // terminate the buff
// TODO: SPLIT INTO A FUNCTION "identify_token(char* str)"
if (EVALUATOR_DEBUG_LEVEL >= 2) printf("buff: '%s' \n", buff);
if (EVALUATOR_DEBUG_LEVEL >= 2) printf_wrap("buff: '%s' \n", buff);
char dumbValue = (char) 0;
@ -510,7 +510,7 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
continue;
}
if (len == 1 && is_operator(buff[0])) {
if (EVALUATOR_DEBUG_LEVEL >= 2) printf("found op\n");
if (EVALUATOR_DEBUG_LEVEL >= 2) printf_wrap("found op\n");
char opValue = buff[0];
list_set(&evalList, evalList.num_elements, TYPE_OPERATOR, &opValue);
continue;
@ -520,7 +520,7 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
int st = parse_int(buff, &res);
if (st == 0) {
// parse int success
//printf("Content aftr parsing %d %d \n", st, res);
//printf_wrap("Content aftr parsing %d %d \n", st, res);
list_set(&evalList, evalList.num_elements, TYPE_INT, &res);
}
if (st != 0) {
@ -537,18 +537,18 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
// identify token
// first try a variable then a func name
// not a float, check if this is a common function name
if (EVALUATOR_DEBUG_LEVEL >= 2) printf("now going to identify token '%s' \n", buff);
if (EVALUATOR_DEBUG_LEVEL >= 2) printf_wrap("now going to identify token '%s' \n", buff);
if (EVALUATOR_DEBUG_LEVEL >= 2) var_store_print(state->varStore);
int varKey = (int) var_store_get_key(state->varStore, buff);
if (EVALUATOR_DEBUG_LEVEL >= 2) printf("got var key '%d' \n", varKey);
if (EVALUATOR_DEBUG_LEVEL >= 2) printf_wrap("got var key '%d' \n", varKey);
if (varKey == -1) {
// did not find the var name
short funcID = identify_func_name(buff);
if (funcID == -1) {
// did not find the func name
printf("ERR Evaluator: could not identify token \"%s\" \n", buff);
printf_wrap("ERR Evaluator: could not identify token \"%s\" \n", buff);
return 200;
}
if (funcID >= 0) {
@ -559,13 +559,13 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
list_set(&evalList, evalList.num_elements, TYPE_VAR_NAME, &varKey);
}
}
if (EVALUATOR_DEBUG_LEVEL >= 2) printf("end of a token identification\n");
if (EVALUATOR_DEBUG_LEVEL >= 2) printf_wrap("end of a token identification\n");
}
// check the content of this thing
if (EVALUATOR_DEBUG_LEVEL >= 2) {
list_print(&evalList);
printf("Now going to actually evaluate...\n");
printf_wrap("Now going to actually evaluate...\n");
}
while (evalList.num_elements > 1 || !is_type_literal(list_get_type(&evalList, 0))) {
@ -595,9 +595,9 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
if (m == 4) stat = evaluator_reduce_operator_pattern(&evalList);
if (m == 5) stat = evaluator_reduce_parenthesis_pattern(&evalList);
if (stat > 0) {
printf("ERR Evaluator: mode %d reducing failed \n", m);
printf_wrap("ERR Evaluator: mode %d reducing failed \n", m);
if (EVALUATOR_DEBUG_LEVEL >= 2) {
printf("dumping evalList: \n");
printf_wrap("dumping evalList: \n");
list_print(&evalList);
}
}
@ -607,9 +607,9 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
if (!didReduced) {
// all scans failed to find things to reduce
// this is actually a failure because we can't do anything to get down to 1 element in the eval list
printf("ERR Evaluator: could not reduce more \n");
printf_wrap("ERR Evaluator: could not reduce more \n");
if (EVALUATOR_DEBUG_LEVEL >= 2) {
printf("dumping evalList: \n");
printf_wrap("dumping evalList: \n");
list_print(&evalList);
}
return 400;
@ -620,7 +620,7 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
*typePtr = typeRes;
list_get(&evalList, 0, resultPtr);
if (EVALUATOR_DEBUG_LEVEL >= 2) {
printf("End of evaluation, dumping evalList: \n");
printf_wrap("End of evaluation, dumping evalList: \n");
list_print(&evalList);
}

View file

@ -92,15 +92,15 @@ int print_number_impl(int* res, unsigned char* resType, unsigned char* types, in
return 1;
}
if (G_DEBUG_LEVEL >= 1) {
printf("REAL_PRINT: ");
printf_wrap("REAL_PRINT: ");
}
if (types[0] == TYPE_INT) {
int val = args[0];
printf("%d\n", val);
printf_wrap("%d\n", val);
}
if (types[0] == TYPE_FLOAT) {
float val = get_float_from_int_rep(args[0]);
printf("%f\n", val);
printf_wrap("%f\n", val);
}
*res = 1;
return 0;
@ -122,7 +122,7 @@ int print_ascii_impl(int* res, unsigned char* resType, unsigned char* types, int
charVal = (int) get_float_from_int_rep(args[0]);
}
printf("%c", *((char*) &charVal));
printf_wrap("%c", *((char*) &charVal));
*res = 1;
return 0;
}
@ -134,7 +134,7 @@ int print_newline_impl(int* res, unsigned char* resType, unsigned char* types, i
*resType = TYPE_INT;
*res = 1;
printf("\n");
printf_wrap("\n");
return 0;
}
@ -143,15 +143,15 @@ int input_number_impl(int* res, unsigned char* resType, unsigned char* types, in
{
UNUSED(types);
UNUSED(args);
printf("? ");
printf_wrap("? ");
char* line;
size_t len = 0;
size_t lineSize = 0;
lineSize = getline(&line, &len, stdin);
lineSize = getline_wrap(&line, &len, stdin);
// printf("len=%d, lineSize=%d '%s' \n", len, lineSize, line);
// printf_wrap("len=%d, lineSize=%d '%s' \n", len, lineSize, line);
char toParse[lineSize+1];
str_extract((char*) toParse, line, 0, lineSize-1);
@ -377,22 +377,22 @@ short identify_func_name(char* candidate)
int execute_func(short funcID, short argsLen, unsigned char* argsTypes, int* argsValues, int* resPtr, unsigned char* resTypePtr)
{
if (funcID >= nbOfFuncs) {
printf("ERR: Invalid func with index: %d \n", funcID);
printf_wrap("ERR: Invalid func with index: %d \n", funcID);
return 1;
}
int (*impl)(int*, unsigned char*, unsigned char*, int*) = intros[funcID].implementation;
if (impl == 0) {
printf("ERR: No implementation for func with index: %d \n", funcID);
printf_wrap("ERR: No implementation for func with index: %d \n", funcID);
return 1;
}
char* name = intros[funcID].name;
if (G_DEBUG_LEVEL >= 2) printf("Executing func '%s' \n", name);
if (G_DEBUG_LEVEL >= 2) printf_wrap("Executing func '%s' \n", name);
if (argsLen < intros[funcID].nbArgs) {
printf("ERR: Too few arguments for func call '%s' \n", name);
printf_wrap("ERR: Too few arguments for func call '%s' \n", name);
return 1;
}
if (argsLen > intros[funcID].nbArgs) {
printf("ERR: Too many arguments for func call '%s' \n", name);
printf_wrap("ERR: Too many arguments for func call '%s' \n", name);
return 1;
}
@ -400,7 +400,7 @@ int execute_func(short funcID, short argsLen, unsigned char* argsTypes, int* arg
// first cast the function ptr
impl(resPtr, resTypePtr, argsTypes, argsValues);
if (G_DEBUG_LEVEL >= 2) printf("Got %s \n", get_repr(*resTypePtr, resPtr));
if (G_DEBUG_LEVEL >= 2) printf_wrap("Got %s \n", get_repr(*resTypePtr, resPtr));
return 0;
}

View file

@ -326,8 +326,8 @@ int process_line(struct StateContainer* state, char* str)
}
if (recognize_word(str, SYNTAX_END)) {
byte lastBlockType;
int_stack_pop(state->blockStack, (int*) &lastBlockType); // FIXME: use a stack with size byte instead of int
int lastBlockType;
int_stack_pop(state->blockStack, &lastBlockType); // FIXME: use a stack with size byte instead of int
if (!state->skipping && lastBlockType == BLOCK_WHILE) {
int lastLoopLine;
int_stack_pop(state->loopStack, &lastLoopLine);
@ -441,7 +441,7 @@ int process_line(struct StateContainer* state, char* str)
state->linePtr = lastLoopLine;
// find the last while if the block stack and pop blocks up to that point
byte lastBlockType;
int lastBlockType;
while (lastBlockType != BLOCK_WHILE) {
if (!int_stack_pop(state->blockStack, &lastBlockType)) {
printf("Syntax error: unexpected continue.\n");
@ -588,5 +588,12 @@ int process_script(struct StateContainer* state, char* script)
}
}
if (LINE_PROCESSING_DEBUG_LEVEL >= 1) {
// end of run
printf("End of run dumping var_store \n");
var_store_print(state->varStore);
printf("=== end of dump\n");
}
return 1;
}

View file

@ -185,15 +185,15 @@ int list_append_char(struct List* list, char value)
void list_print(struct List* list)
{
printf("=== LIST REPORT === \n");
printf("num of elements: %d \n", list->num_elements);
printf_wrap("=== LIST REPORT === \n");
printf_wrap("num of elements: %d \n", list->num_elements);
for (int i = 0; i < list->num_elements; i++) {
int type = list_get_type(list, i);
int data = 0;
list_get(list, i, &data);
printf("- i: %d, %s \n", i, get_repr(type, (void*) &data));
printf_wrap("- i: %d, %s \n", i, get_repr(type, (void*) &data));
}
printf("=== END === \n");
printf_wrap("=== END === \n");
}

View file

@ -5,8 +5,8 @@
#include <signal.h>
#include <string.h>
#include "./config.h"
#include "./types.h"
#include "./utils.h"
#include "./types.h"
#include "./stack.h"
#include "./list.h"
#include "./number_parsing.h"
@ -31,13 +31,13 @@ int help_mode(char* cmdName) {
" -v --version print version information and exit\n"
" -i --interactive force interactive mode\n"
" -e --stdin-expression evaluate expression from stdin\n";
printf(helpStr, cmdName);
printf_wrap(helpStr, cmdName);
return 0;
}
int version_mode() {
char* helpStr = "Langatator 0.0.1\n";
printf(helpStr);
printf_wrap(helpStr);
return 0;
}
@ -45,7 +45,7 @@ int interactive_mode() {
struct StateContainer* state = state_init();
while (state->running) {
printf("? ");
printf_wrap("? ");
char* line;
size_t len = 0;
@ -54,7 +54,7 @@ int interactive_mode() {
lineSize = getline(&line, &len, stdin);
if (lineSize == (size_t) -1) {
// we received some kind of interrupt?
printf("\n");
printf_wrap("\n");
return EXIT_SUCCESS;
}
@ -64,10 +64,10 @@ int interactive_mode() {
int stat = process_line(state, toEvaluate);
if (!stat) {
printf("Processing that line failed.\n");
printf_wrap("Processing that line failed.\n");
}
if (state->lastEvaluationType != TYPE_NULL) {
printf("%s\n", get_repr(state->lastEvaluationType, &state->lastEvaluationResult));
printf_wrap("%s\n", get_repr(state->lastEvaluationType, &state->lastEvaluationResult));
}
}
@ -75,7 +75,7 @@ int interactive_mode() {
}
int stdin_expression_mode() {
printf("This mode is not implemented yet ¯\\_(ツ)_/¯ \n");
printf_wrap("This mode is not implemented yet ¯\\_(ツ)_/¯ \n");
return 1;
}
@ -116,7 +116,7 @@ error:
}
int file_mode(char* fileName) {
// printf("Open file mode...\n");
// printf_wrap("Open file mode...\n");
size_t size;
char* buff = slurp_file(fileName, &size);

View file

@ -22,7 +22,7 @@ int parse_clean_positive_integer(int inputStrLen, char* inputStr, int* result) {
);
i++;
}
//printf("parseclean %d \n", value);
//printf_wrap("parseclean %d \n", value);
*result = value;
@ -58,13 +58,13 @@ int parse_int(char* inputStr, int* resultPtr) {
i++;
}
cleanStr[cleanStrLen] = 0;
//printf("clean str: %s/ \n", cleanStr);
//printf_wrap("clean str: %s/ \n", cleanStr);
int inter = 0;
byte stat = parse_clean_positive_integer(cleanStrLen, cleanStr, &inter);
if (NB_PARSING_DEBUG_LEVEL >= 2) {
printf("Parse clean positive integer stat: %d\n", stat);
printf("Got value: %d\n", inter);
printf_wrap("Parse clean positive integer stat: %d\n", stat);
printf_wrap("Got value: %d\n", inter);
}
*resultPtr = inter;
@ -76,7 +76,7 @@ int parse_int(char* inputStr, int* resultPtr) {
}
int parse_float(char* inputStr, float* resultPtr) {
if (NB_PARSING_DEBUG_LEVEL >= 2) printf("Parsing as float: '%s'\n", inputStr);
if (NB_PARSING_DEBUG_LEVEL >= 2) printf_wrap("Parsing as float: '%s'\n", inputStr);
int i = 0;
char cleanStrIntPart[strlen(inputStr)+1];
int cleanStrIntPartLen = 0;
@ -135,8 +135,8 @@ int parse_float(char* inputStr, float* resultPtr) {
}
cleanStrIntPart[cleanStrIntPartLen] = 0;
cleanStrFloatPart[cleanStrFloatPartLen] = 0;
// printf("clean str int part: /%s/ \n", cleanStrIntPart);
// printf("clean str float part: /%s/ \n", cleanStrFloatPart);
// printf_wrap("clean str int part: /%s/ \n", cleanStrIntPart);
// printf_wrap("clean str float part: /%s/ \n", cleanStrFloatPart);
int intPart = 0;
parse_clean_positive_integer(cleanStrIntPartLen, cleanStrIntPart, &intPart);

View file

@ -72,7 +72,7 @@ int operate(
a = convert_to_float(typeA, aRepr);
b = convert_to_float(typeB, bRepr);
if (OPERATE_DEBUG_LEVEL) printf("Appling operation: %f %c %f \n", a, operator, b);
if (OPERATE_DEBUG_LEVEL) printf_wrap("Appling operation: %f %c %f \n", a, operator, b);
if (operator == '+') {
res = a+b;
@ -95,13 +95,13 @@ int operate(
} else {
return 2;
}
if (OPERATE_DEBUG_LEVEL) printf("Got float: %f \n", res);
if (OPERATE_DEBUG_LEVEL) printf_wrap("Got float: %f \n", res);
// get int representation of float
*resPtr = *(int *)(&res);
return 0;
}
if (typeA == TYPE_INT && typeB == TYPE_INT) {
if (OPERATE_DEBUG_LEVEL) printf("Appling operation %d %c %d \n", aRepr, operator, bRepr);
if (OPERATE_DEBUG_LEVEL) printf_wrap("Appling operation %d %c %d \n", aRepr, operator, bRepr);
*typeRes = TYPE_INT;
int res = 0;
if (operator == '+') {

View file

@ -1,3 +1,63 @@
/*
#include "./utils.h"
#include "./stack.h"
#include <stdio.h>
#include <stdlib.h>
struct Stack* int_stack_init(byte unitSize)
{
struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));
stack->unitSize = unitSize;
stack->length = 0;
stack->allocated = 8;
stack->data = (int*) malloc(stack->allocated * stack->unitSize);
return stack;
}
byte stack_push(struct Stack* stack, void* valueToPush)
{
if (stack->length == stack->allocated) {
stack->allocated *= 2;
stack->data = realloc(stack->data, stack->allocated * stack->unitSize);
}
memcpy(stack->data[stack->length], valueToPush, stack->unitSize);
stack->length++;
return 1;
}
byte stack_pop(struct Stack* stack, void* valuePtr)
{
if (stack->length == 0) {
// error, nothing to pop
return 0;
}
memcpy(valuePtr, stack->data[stack->length-1], stack->unitSize);
stack->length--;
return 1;
}
int int_stack_length(struct Stack* stack)
{
return stack->length;
}
void int_stack_print(struct Stack* stack)
{
printf_wrap("= STACK REPORT \n");
for (int i = 0; i < stack->length; i++) {
printf_wrap("%d; ", stack->data[i]);
}
printf_wrap("\n");
}
*/
#include "./utils.h"
#include "./stack.h"
#include <stdio.h>
@ -53,3 +113,4 @@ void int_stack_print(struct IntStack* stack)
}
printf("\n");
}

View file

@ -2,6 +2,24 @@
#ifndef STACK_H_
#define STACK_H_
// struct Stack {
// byte unitSize;
// int length;
// int allocated;
// int* data;
// };
// struct Stack* stack_init();
// byte stack_push(struct Stack* stack, void* valueToPush);
// byte stack_pop(struct Stack* stack, void* valuePtr);
// byte stack_get(struct Stack* stack, int index, void* valuePtr);
// int stack_length(struct Stack* stack);
// void stack_print(struct Stack* stack);
struct IntStack {
int length;
int allocated;
@ -18,4 +36,5 @@ int int_stack_length(struct IntStack* stack);
void int_stack_print(struct IntStack* stack);
#endif

View file

@ -2,6 +2,17 @@
#include <string.h>
#include "./utils.h"
#include <stdarg.h>
#if PRINT_MODE == 0
int printf_wrap(const char* format, ...) {
va_list args;
va_start(args, format);
vprintf(format, args);
va_end( args );
}
#endif
int get_int_rep_from_float(float ft)
{
return *(int *)(&ft);
@ -21,7 +32,7 @@ float get_float_from_int_rep(int representation)
int get_int_rep_from_char(char c)
{
return *(int *)(&c);
return (int) c;
}
int is_char_numeral(char candidate)
@ -217,7 +228,7 @@ int m_newton_method(float (*func)(float, float), float param, float startsAt, fl
return 0;
}
if (runs > 100) {
printf("ERR: newton methods failed, coup dur pour newton \n");
printf_wrap("ERR: newton methods failed, coup dur pour newton \n");
return 100;
}
cursor = newCursor;

View file

@ -3,6 +3,8 @@
#ifndef UTILS_H_
#define UTILS_H_
int printf_wrap(const char* format, ...);
// useful to silent warning of gcc of uunused parameters in functions
#define UNUSED(x) (void)(x)

View file

@ -10,14 +10,14 @@ struct VariableStore* var_store_init()
{
struct VariableStore* store = (struct VariableStore*) malloc(sizeof(struct VariableStore));
if (store == NULL) {
printf("[ERR] VARSTORE: malloc failed for variable store \n");
printf_wrap("[ERR] VARSTORE: malloc failed for variable store \n");
return NULL;
}
store->allocatedLength = VAR_STORE_INITIAL_ALLOC_LENGTH;
store->length = 0;
store->container = (struct VariableContainer*) malloc(sizeof(struct VariableContainer) * store->allocatedLength);
if (store->container == NULL) {
printf("[ERR] VARSTORE: malloc failed for first variable container \n");
printf_wrap("[ERR] VARSTORE: malloc failed for first variable container \n");
return NULL;
}
for (int i = 0; i < store->allocatedLength; i++) {
@ -39,27 +39,29 @@ int var_store_hash_name(struct VariableStore* store, char* varName)
int hash = 0;
int i = 0;
while (varName[i] != '\0') {
int num = get_int_rep_from_char(varName[i])*integer_pow(9, i);
hash = abs(hash + abs(num));
int num = get_int_rep_from_char(varName[i])|integer_pow(9, i);
hash += num;
i++;
}
// FIXME: when reallocating, we should copy all variables to their new key
// because we use modulus operator, the hash will change whenever we reallocated the table
return hash % store->allocatedLength;
hash = (hash < 0 ? -hash : hash) % store->allocatedLength;
//printf_wrap("Compute a hash for '%s' , allocatd: %d; %d\n", varName, store->allocatedLength, hash);
return hash;
}
byte var_store_set(struct VariableStore* store, char* varName, byte type, void* valuePtr)
{
//printf("set variable at var name: '%s' \n", varName);
//printf_wrap("set variable at var name: '%s' \n", varName);
if (!(type == TYPE_FLOAT || type == TYPE_INT || type == TYPE_NULL)) {
printf("[ERR] VARSTORE: unsupported type, cannot store type %d\n", type);
printf_wrap("[ERR] VARSTORE: unsupported type, cannot store type %d\n", type);
return 0;
}
void* dataPtr;
if (type == TYPE_FLOAT || type == TYPE_INT) {
dataPtr = malloc(sizeof(int));
if (dataPtr == NULL) {
printf("[ERR] VARSTORE: malloc failed for data\n");
printf_wrap("[ERR] VARSTORE: malloc failed for data\n");
return 1;
}
@ -70,7 +72,7 @@ byte var_store_set(struct VariableStore* store, char* varName, byte type, void*
char* namePtr = (char*) malloc(strlen(varName));
if (namePtr == NULL) {
printf("[ERR] VARSTORE: malloc failed for var name\n");
printf_wrap("[ERR] VARSTORE: malloc failed for var name\n");
return 1;
}
strcpy(namePtr, varName);
@ -82,7 +84,7 @@ byte var_store_set(struct VariableStore* store, char* varName, byte type, void*
{
if (store->container[key].type == 0) {
// we finally found an empty space, but we didn't found a variable with the same name
// we have a new variable
// so we have a new variable
store->length++;
break;
}
@ -93,24 +95,25 @@ byte var_store_set(struct VariableStore* store, char* varName, byte type, void*
key = (key+1) % store->allocatedLength;
if (key == originalKey) {
// end the search to avoid endless loop
printf("[ERR] VARSTORE: cannot set variable, not enough containers \n");
printf_wrap("[ERR] VARSTORE: cannot set variable, not enough containers \n");
return 1;
}
}
//printf("set variable at key: %d \n", key);
//printf_wrap("set variable at key: %d \n", key);
store->container[key].type = type;
store->container[key].namePtr = namePtr;
store->container[key].dataPtr = dataPtr;
if (2*store->length >= store->allocatedLength) {
printf_wrap("REALLOCATING THE FUCKING VAR STORE\n");
// do smth to double the store->allocatedLength
// e.g reallocate the store->container
// FIXME: copy all variables to their new keys
store->allocatedLength = 2*store->allocatedLength;
store->container = (struct VariableContainer*) realloc(store->container, sizeof(struct VariableContainer) * store->allocatedLength);
if (store->container == NULL) {
printf("[ERR] VARSTORE: relloc failed for container \n");
printf_wrap("[ERR] VARSTORE: relloc failed for container \n");
return 1;
}
}
@ -122,15 +125,15 @@ byte var_store_set(struct VariableStore* store, char* varName, byte type, void*
// return -1 if no pos are found
int var_store_get_key(struct VariableStore* store, char* varName)
{
//printf("get key for %s \n", varName);
//printf_wrap("get key for %s \n", varName);
int originalKey = var_store_hash_name(store, varName);
//printf_wrap("got hash for get key: %d\n", originalKey);
int key = originalKey;
// handle collision, walk along the array
while (1) {
//printf("inter key: %d %d \n", key, store->container[key].type);
//printf_wrap("inter key: %d %d \n", key, store->container[key].type);
if (store->container[key].type == 0) return -1;
// check if we found the position
if (strcmp(store->container[key].namePtr, varName) == 0) return key;
@ -165,13 +168,15 @@ byte var_store_copy_from_key(struct VariableStore* store, int key, void* dst)
if (key < 0) {
return 1;
}
//printf_wrap("Var store: copy from key %d \n", key);
memcpy(dst, store->container[key].dataPtr, (size_t) get_size_of_type(store->container[key].type));
return 0;
}
byte var_store_copy(struct VariableStore* store, char* varName, void* dst)
{
return var_store_copy_from_key(store, var_store_get_key(store, varName), dst);
int key = var_store_get_key(store, varName);
return var_store_copy_from_key(store, key, dst);
}
int var_store_get_int(struct VariableStore* store, char* varName)
@ -196,10 +201,10 @@ float var_store_get_float(struct VariableStore* store, char* varName)
void var_store_print(struct VariableStore* store)
{
printf("== VarStore report (%d items) ==\n", store->length);
printf_wrap("== VarStore report (%d items) ==\n", store->length);
for (int i = 0; i < store->allocatedLength; i++) {
if (store->container[i].type != 0) {
printf(
printf_wrap(
"key: %d, '%s' = %s; ",
i,
store->container[i].namePtr,
@ -207,5 +212,5 @@ void var_store_print(struct VariableStore* store)
);
}
}
printf("== end of report\n");
printf_wrap("== end of report\n");
}

View file

@ -4,7 +4,7 @@
#define VAR_STORE_H_
#define VAR_STORE_DEBUG_LEVEL (G_DEBUG_LEVEL)
#define VAR_STORE_INITIAL_ALLOC_LENGTH 32
#define VAR_STORE_INITIAL_ALLOC_LENGTH 64
/**

View file

@ -1,3 +1,5 @@
#include "../src/config.h"
#include "../src/utils.h"
#include "./test_utils.h"
#include "./test_evaluation.h"
#include "./test_line_processing.h"
@ -7,8 +9,10 @@
int main()
{
printf("== UNIT TESTS == \n");
int var1 = 0x34;
printf_wrap("== UNIT TESTS == \n");
test_utils();
printf_wrap("ça commence à faire chier jpp\n");
test_var_store();
test_stack();
test_evaluation();

View file

@ -9,7 +9,7 @@
void test_evaluation()
{
printf("== test evaluation == \n");
printf_wrap("== test evaluation == \n");
struct StateContainer* state = state_init();
@ -93,7 +93,7 @@ void test_evaluation()
evaluate(state, "random_int(1, 100)", &resVal, &resType);
assert(resType == TYPE_INT);
printf(" - random int: %d \n", resVal);
printf_wrap(" - random int: %d \n", resVal);
evaluate(state, "abs(2)+abs(-2)", &resVal, &resType);
assert(resType == TYPE_INT);
@ -201,7 +201,7 @@ void test_evaluation()
evaluate(state, "abs((var2^2)-((var-41)^2))+2", &resVal, &resType);
assert(resType == TYPE_INT);
printf("actually got: %d \n", resVal);
printf_wrap("actually got: %d \n", resVal);
assert(7 == resVal);
/* TYPE FUNCS */

View file

@ -11,7 +11,7 @@
void test_line_processing()
{
printf("== test line processing == \n");
printf_wrap("== test line processing == \n");
// test string manipulation
assert(!recognize_word("", "hello"));
@ -49,7 +49,7 @@ void test_line_processing()
assert(process_line(state1, "#"));
assert(process_line(state1, "# some random comment"));
assert(process_line(state1, "set VAR_A to 8.5"));
printf("%d \n", var_store_get_int(state1->varStore, "VAR_A"));
printf_wrap("%d \n", var_store_get_int(state1->varStore, "VAR_A"));
assert(float_almost_equal(8.5, var_store_get_float(state1->varStore, "VAR_A")));
assert(process_line(state1, "set VAR_B to 1.5"));
@ -113,7 +113,7 @@ void test_line_processing()
process_script(state2, lines4);
assert(!state2->skipping);
printf("got i: %d \n", var_store_get_int(state2->varStore, "i"));
printf_wrap("got i: %d \n", var_store_get_int(state2->varStore, "i"));
assert(9 == var_store_get_int(state2->varStore, "i"));
// test break keyword
@ -127,7 +127,7 @@ void test_line_processing()
process_script(state2, lines5);
assert(!state2->skipping);
printf("got i: %d \n", var_store_get_int(state2->varStore, "i"));
printf_wrap("got i: %d \n", var_store_get_int(state2->varStore, "i"));
assert(10 == var_store_get_int(state2->varStore, "i"));
// test continue keyword

View file

@ -6,7 +6,7 @@
void test_stack()
{
printf("== test stack == \n");
printf_wrap("== test stack == \n");
int res;
struct IntStack* stack1 = int_stack_init();
@ -28,7 +28,7 @@ void test_stack()
assert(int_stack_push(stack1, 2025));
assert(int_stack_push(stack1, 2026));
assert(16 == stack1->allocated);
printf("%d \n", int_stack_length(stack1));
printf_wrap("%d \n", int_stack_length(stack1));
assert(9 == int_stack_length(stack1));
int_stack_print(stack1);

View file

@ -6,7 +6,7 @@
void test_utils()
{
printf("== test utils == \n");
printf_wrap("== test utils == \n");
// test int parsing
char test1[] = "151087";

View file

@ -5,10 +5,40 @@
void test_var_store()
{
printf("== test var store == \n");
printf_wrap("== test var store == \n");
struct VariableStore* store = var_store_init();
// hash function test
int hash1, hash2, hash3 = 0;
hash1 = var_store_hash_name(store, "a");
hash2 = var_store_hash_name(store, "a");
hash3 = var_store_hash_name(store, "a");
assert(hash1 == hash2);
assert(hash2 == hash3);
assert(hash1 == hash3);
hash1 = var_store_hash_name(store, "i");
hash2 = var_store_hash_name(store, "i");
hash3 = var_store_hash_name(store, "i");
assert(hash1 == hash2);
assert(hash2 == hash3);
assert(hash1 == hash3);
var_store_print(store);
int originalLength = store->length;
int varEx = 42;
int originalHash = var_store_hash_name(store, "i");
var_store_set(store, "i", TYPE_INT, &varEx);
assert(originalHash == var_store_hash_name(store, "i"));
assert(TYPE_INT == var_store_get_type(store, "i"));
assert(originalLength+1 == store->length);
assert(42 == var_store_get_int(store, "i"));
// sequential assignement
int iDest = 0;
for (int i = 0; i < 10; i++) {
var_store_set(store, "i", TYPE_INT, &i);

1
wasm.sh Normal file
View file

@ -0,0 +1 @@
clang -Os -fno-builtin -Wall -Wextra -Wswitch-enum --target=wasm32 --no-standard-libraries -Wl,--export=wasm_info -Wl,--no-entry -Wl,--allow-undefined -o wasm/langatator.wasm ./wasm/wasm.c

2
wasm/config_env_wasm.h Normal file
View file

@ -0,0 +1,2 @@
// the config file for wasm
#define PRINT_MODE 1

81
wasm/emscripten.c Normal file
View file

@ -0,0 +1,81 @@
#include "emscripten.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
EM_JS(void, log_to_js, (char* buff, size_t len), {
log_intake(buff, len);
});
int printf_wrap(const char* format, ...) {
va_list args;
va_start(args, format);
char* out;
vsprintf(out, format, args);
char* sharedPos = (char*) malloc(strlen(out) * sizeof(char));
strcpy(sharedPos, out);
log_to_js((void*) sharedPos, strlen(out));
va_end(args);
return 1;
}
#include "../src/config.h"
#include "../src/utils.h"
#include "../src/types.h"
#include "../src/state.h"
#include "../src/line_processing.h"
struct Result {
byte type;
int data;
};
EMSCRIPTEN_KEEPALIVE
void* wasm_init_state()
{
struct StateContainer* ptr = state_init();
return (void*) ptr;
}
EMSCRIPTEN_KEEPALIVE
void* wasm_process_line(void* state, char* line)
{
struct Result* res = malloc(sizeof(struct Result));
process_line(state, line);
res->type = ((struct StateContainer*) state)->lastEvaluationType;
res->data = ((struct StateContainer*) state)->lastEvaluationResult;
return (void*) res;
}
EMSCRIPTEN_KEEPALIVE
void wasm_process_script(char* scriptLines)
{
printf_wrap("Will process script \"%s\" \n", scriptLines);
struct StateContainer* state = state_init();
process_script(state, scriptLines);
}
// very dangerous indeed
EMSCRIPTEN_KEEPALIVE
int wasm_get_type_from_ref(void* ref) {
return ((struct Result*) ref)->type;
}
EMSCRIPTEN_KEEPALIVE
int wasm_get_int_from_ref(void* ref) {
return ((struct Result*) ref)->data;
}
// EMSCRIPTEN_KEEPALIVE
// int wasm_info(char* lines)
// {
// struct StateContainer* state = state_init();
// process_script(state, lines);
// return state->lastEvaluationResult;
// }

1
wasm/emscripten_raw.html Normal file

File diff suppressed because one or more lines are too long

1
wasm/emscripten_raw.js Normal file

File diff suppressed because one or more lines are too long

BIN
wasm/emscripten_raw.wasm Executable file

Binary file not shown.

69
wasm/index.html Normal file
View file

@ -0,0 +1,69 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Langatator demo</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css">
<style>
* {
box-sizing: border-box;
}
.container {
width: 90%;
margin: 0 auto;
}
.form {
width: 100%;
margin-top: 1em;
}
#script-input {
width: 100%;
min-width: 100%;
max-width: 100%;
display: block;
min-height: 20em;
}
.submit-btn {
margin-top: 1em;
}
</style>
</head>
<body>
<div class="container">
<h1>Langatator demo</h1>
<a href="https://gitlab.com/lefuturiste/langatator">The git repository</a>
<div class="form">
<textarea id="script-input"></textarea>
<button
class="submit-btn"
onclick="submitScript()"
>
Process script!
</button>
</div>
<div class="console">
<pre id="console-output">
</pre>
</div>
</div>
<script>
// const oldLog = console.log;
// console.log = function (message) {
// oldLog.apply(console, ['captured', ...arguments]);
// };
</script>
<script src="./langatator_adapter.js"></script>
<script src="./script.js"></script>
</body>
</html>

File diff suppressed because one or more lines are too long

BIN
wasm/langatator_adapter.wasm Executable file

Binary file not shown.

93
wasm/script.js Normal file
View file

@ -0,0 +1,93 @@
'use strict';
// let app = document.getElementById("app");
// let wasm = null;
// let iota = 0;
// function cstrlen(mem, ptr) {
// let len = 0;
// while (mem[ptr] != 0) {
// len++;
// ptr++;
// }
// return len;
// }
// function cstr_by_ptr(mem_buffer, ptr) {
// const mem = new Uint8Array(mem_buffer);
// const len = cstrlen(mem, ptr);
// const bytes = new Uint8Array(mem_buffer, ptr, len);
// return new TextDecoder().decode(bytes);
// }
// function platform_panic(file_path_ptr, line, message_ptr) {
// const buffer = wasm.instance.exports.memory.buffer;
// const file_path = cstr_by_ptr(buffer, file_path_ptr);
// const message = cstr_by_ptr(buffer, message_ptr);
// console.error(file_path+":"+line+": "+message);
// }
// function platform_log(message_ptr) {
// const buffer = wasm.instance.exports.memory.buffer;
// const message = cstr_by_ptr(buffer, message_ptr);
// console.log(message);
// }
// WebAssembly.instantiateStreaming(fetch('langatator.wasm'), {
// env: {
// platform_panic,
// platform_log
// }
// }).then((w) => {
// wasm = w;
// console.log(wasm.instance.exports.wasm_info());
// //const buffer = wasm.instance.exports.memory.buffer;
// });
const consoleOutput = document.getElementById('console-output')
function log_intake(ptr, len) {
let line = ""
for (var i = 0; i < len; i++) {
let val = Module.getValue(ptr+i, 'i8')
line = line + String.fromCharCode(val)
}
console.log('Got line', line)
// const pre= document.createElement('pre')
// consoleOutput.appendChild(pre)
}
Module.onRuntimeInitialized = async _ => {
const api = {
init: Module.cwrap('wasm_init_state', 'number', []),
processLine: Module.cwrap('wasm_process_line', 'number', ['number', 'string']),
getTypeFromRef: Module.cwrap('wasm_get_type_from_ref', 'number', ['number']),
getIntFromRef: Module.cwrap('wasm_get_int_from_ref', 'number', ['number']),
// standalone (integrated state initialization)
processScript: Module.cwrap('wasm_process_script', 'number', ['string']),
};
console.log(api);
// const ref = api.init();
// console.log(`Got ref: ${ref}`);
window.processLine = (line) => {
const resultRef = api.processLine(ref, line);
console.log(`Got result ref: ${resultRef}`);
console.log(api.getTypeFromRef(resultRef));
console.log(api.getIntFromRef(resultRef));
}
window.submitScript = () => {
const textarea = document.getElementById('script-input')
api.processScript(textarea.value)
}
};

0
wasm/style.css Normal file
View file

44
wasm/wasm.c Normal file
View file

@ -0,0 +1,44 @@
#include <stdlib.h>
#include "../src/config.h"
#define CONFIG_PRINT_METHOD PRINT_METHOD_WASM
#include "../src/utils.h"
#include "../src/types.h"
#include "../src/state.h"
#include "../src/line_processing.h"
void* wasm_init_state()
{
struct StateContainer* ptr = state_init();
return (void*) ptr;
}
void* wasm_process_line(void* state, char* line)
{
struct Result* res = malloc(sizeof(struct Result));
process_line(state, line);
res->type = ((struct StateContainer*) state)->lastEvaluationType;
res->data = ((struct StateContainer*) state)->lastEvaluationResult;
return (void*) res;
}
// very dangerous indeed
int wasm_get_type_from_ref(void* ref) {
return ((struct Result*) ref)->type;
}
int wasm_get_int_from_ref(void* ref) {
return ((struct Result*) ref)->data;
}
// EMSCRIPTEN_KEEPALIVE
// int wasm_info(char* lines)
// {
// struct StateContainer* state = state_init();
// process_script(state, lines);
// return state->lastEvaluationResult;
// }