added input builtin

This commit is contained in:
cozis
2022-03-14 23:10:29 +01:00
parent 64f667127d
commit 90ae41be27
3 changed files with 53 additions and 5 deletions
+1 -1
View File
@@ -36,7 +36,7 @@ print(L, '\n'); # Outputs [1, 2, 3]
I wrote it on a linux machine, but there should be very few places where a linux host is assumed. It should be very easy to port.
## Development state
The interpreter is fully functional, but lots of built-in functions that one would expect still need to be implemented. Unfortunately, I feel like this requires much more work than what it's worth at the moment.
The interpreter is fully functional, but lots of built-in functions that one would expect still need to be implemented. Unfortunately, I feel like this requires much more work than what it's worth at the moment.
## Implementation overview
The architecture is pretty much the same as CPython. The source code is executed by compilig it to bytecode. The bytecode is much more high level than what the CPU understands, it's more like a serialized version of the AST. For example, some bytecode instructions refer to variables by names, which means the compiler does very little static analisys. Memory is managed by a garbage collector that moves and compacts allocations.
+5 -4
View File
@@ -1,9 +1,10 @@
fun fail_at_depth(depth)
{
fun fail(current_depth)
{
fun fail_at_depth(depth) {
fun fail(current_depth) {
assert(current_depth < depth);
fail(current_depth + 1);
}
+47
View File
@@ -63,6 +63,52 @@ static Object *bin_count(Runtime *runtime, Object **argv, unsigned int argc, Err
return Object_FromInt(n, Runtime_GetHeap(runtime), error);
}
static Object *bin_input(Runtime *runtime, Object **argv, unsigned int argc, Error *error)
{
(void) argv;
assert(argc == 0);
char maybe[256];
char *str = maybe;
int size = 0, cap = sizeof(maybe)-1;
while(1)
{
char c = getc(stdin);
if(c == '\n')
break;
if(size == cap)
{
int newcap = cap*2;
char *tmp = realloc(str, newcap + 1);
if(tmp == NULL)
{
if(str != maybe) free(str);
Error_Report(error, 1, "No memory");
return NULL;
}
str = tmp;
cap = newcap;
}
str[size++] = c;
}
str[size] = '\0';
Object *res = Object_FromString(str, size, Runtime_GetHeap(runtime), error);
if(str != maybe)
free(str);
return res;
}
static Object *bin_assert(Runtime *runtime, Object **argv, unsigned int argc, Error *error)
{
for(unsigned int i = 0; i < argc; i += 1)
@@ -186,6 +232,7 @@ const StaticMapSlot bins_basic[] = {
{ "type", SM_FUNCT, .as_funct = bin_type, .argc = 1 },
{ "print", SM_FUNCT, .as_funct = bin_print, .argc = -1 },
{ "input", SM_FUNCT, .as_funct = bin_input, .argc = 0 },
{ "count", SM_FUNCT, .as_funct = bin_count, .argc = 1 },
{ "assert", SM_FUNCT, .as_funct = bin_assert, .argc = -1 },
{ NULL, SM_END, {}, {} },