1
0
mirror of https://github.com/janet-lang/janet synced 2025-01-26 23:24:44 +00:00

Add make format to format code.

A consistent style should help with contributors and
readability. We use astyle as the formatter as can make a pretty
good approximation of the current style and my preferred style.

Astyle can be found at http://astyle.sourceforge.net/astyle.html
This commit is contained in:
Calvin Rose 2019-02-19 20:51:34 -05:00
parent 7c19ed8a48
commit 9d4effc02e
37 changed files with 2472 additions and 2503 deletions

View File

@ -209,6 +209,13 @@ build/doc.html: $(JANET_TARGET) tools/gendoc.janet
##### Other ##### ##### Other #####
################# #################
STYLEOPTS=--style=attach --indent-switches --convert-tabs \
--align-pointer=name --pad-header --pad-oper --unpad-paren --indent-labels
format:
astyle $(STYLEOPTS) */*.c
astyle $(STYLEOPTS) */*/*.c
astyle $(STYLEOPTS) */*/*.h
grammar: build/janet.tmLanguage grammar: build/janet.tmLanguage
build/janet.tmLanguage: tools/tm_lang_gen.janet $(JANET_TARGET) build/janet.tmLanguage: tools/tm_lang_gen.janet $(JANET_TARGET)
$(JANET_TARGET) $< > $@ $(JANET_TARGET) $< > $@
@ -236,5 +243,5 @@ uninstall:
-rm -rf $(INCLUDEDIR) -rm -rf $(INCLUDEDIR)
.PHONY: clean install repl debug valgrind test amalg \ .PHONY: clean install repl debug valgrind test amalg \
valtest emscripten dist uninstall docs grammar \ valtest emscripten dist uninstall docs grammar format \
$(TEST_PROGRAM_PHONIES) $(TEST_PROGRAM_VALPHONIES) $(TEST_PROGRAM_PHONIES) $(TEST_PROGRAM_VALPHONIES)

View File

@ -2,23 +2,23 @@
#include <janet.h> #include <janet.h>
typedef struct { typedef struct {
double * data; double *data;
size_t size; size_t size;
} num_array; } num_array;
static num_array * num_array_init(num_array * array,size_t size) { static num_array *num_array_init(num_array *array, size_t size) {
array->data=(double *)calloc(size,sizeof(double)); array->data = (double *)calloc(size, sizeof(double));
array->size=size; array->size = size;
return array; return array;
} }
static void num_array_deinit(num_array * array) { static void num_array_deinit(num_array *array) {
free(array->data); free(array->data);
} }
static int num_array_gc(void *p, size_t s) { static int num_array_gc(void *p, size_t s) {
(void) s; (void) s;
num_array * array=(num_array *)p; num_array *array = (num_array *)p;
num_array_deinit(array); num_array_deinit(array);
return 0; return 0;
} }
@ -36,42 +36,42 @@ static const JanetAbstractType num_array_type = {
static Janet num_array_new(int32_t argc, Janet *argv) { static Janet num_array_new(int32_t argc, Janet *argv) {
janet_fixarity(argc, 1); janet_fixarity(argc, 1);
int32_t size=janet_getinteger(argv,0); int32_t size = janet_getinteger(argv, 0);
num_array * array = (num_array *)janet_abstract(&num_array_type,sizeof(num_array)); num_array *array = (num_array *)janet_abstract(&num_array_type, sizeof(num_array));
num_array_init(array,size); num_array_init(array, size);
return janet_wrap_abstract(array); return janet_wrap_abstract(array);
} }
static Janet num_array_scale(int32_t argc, Janet *argv) { static Janet num_array_scale(int32_t argc, Janet *argv) {
janet_fixarity(argc, 2); janet_fixarity(argc, 2);
num_array * array = (num_array *)janet_getabstract(argv,0,&num_array_type); num_array *array = (num_array *)janet_getabstract(argv, 0, &num_array_type);
double factor = janet_getnumber(argv,1); double factor = janet_getnumber(argv, 1);
size_t i; size_t i;
for (i=0;i<array->size;i++) { for (i = 0; i < array->size; i++) {
array->data[i]*=factor; array->data[i] *= factor;
} }
return argv[0]; return argv[0];
} }
static Janet num_array_sum(int32_t argc, Janet *argv) { static Janet num_array_sum(int32_t argc, Janet *argv) {
janet_fixarity(argc, 1); janet_fixarity(argc, 1);
num_array * array = (num_array *)janet_getabstract(argv,0,&num_array_type); num_array *array = (num_array *)janet_getabstract(argv, 0, &num_array_type);
double sum = 0; double sum = 0;
for (size_t i=0;i<array->size;i++) sum+=array->data[i]; for (size_t i = 0; i < array->size; i++) sum += array->data[i];
return janet_wrap_number(sum); return janet_wrap_number(sum);
} }
void num_array_put(void *p, Janet key, Janet value) { void num_array_put(void *p, Janet key, Janet value) {
size_t index; size_t index;
num_array * array=(num_array *)p; num_array *array = (num_array *)p;
if (!janet_checkint(key)) if (!janet_checkint(key))
janet_panic("expected integer key"); janet_panic("expected integer key");
if (!janet_checktype(value,JANET_NUMBER)) if (!janet_checktype(value, JANET_NUMBER))
janet_panic("expected number value"); janet_panic("expected number value");
index = (size_t)janet_unwrap_integer(key); index = (size_t)janet_unwrap_integer(key);
if (index < array->size) { if (index < array->size) {
array->data[index]=janet_unwrap_number(value); array->data[index] = janet_unwrap_number(value);
} }
} }
@ -84,7 +84,7 @@ static const JanetMethod methods[] = {
Janet num_array_get(void *p, Janet key) { Janet num_array_get(void *p, Janet key) {
size_t index; size_t index;
Janet value; Janet value;
num_array * array=(num_array *)p; num_array *array = (num_array *)p;
if (janet_checktype(key, JANET_KEYWORD)) if (janet_checktype(key, JANET_KEYWORD))
return janet_getmethod(janet_unwrap_keyword(key), methods); return janet_getmethod(janet_unwrap_keyword(key), methods);
if (!janet_checkint(key)) if (!janet_checkint(key))
@ -99,15 +99,17 @@ Janet num_array_get(void *p, Janet key) {
} }
static const JanetReg cfuns[] = { static const JanetReg cfuns[] = {
{"numarray/new", num_array_new, {
"numarray/new", num_array_new,
"(numarray/new size)\n\n" "(numarray/new size)\n\n"
"Create new numarray" "Create new numarray"
}, },
{"numarray/scale", num_array_scale, {
"numarray/scale", num_array_scale,
"(numarray/scale numarray factor)\n\n" "(numarray/scale numarray factor)\n\n"
"scale numarray by factor" "scale numarray by factor"
}, },
{NULL,NULL,NULL} {NULL, NULL, NULL}
}; };
JANET_MODULE_ENTRY(JanetTable *env) { JANET_MODULE_ENTRY(JanetTable *env) {

View File

@ -180,8 +180,7 @@ static Janet cfun_array_concat(int32_t argc, Janet *argv) {
janet_array_push(array, argv[i]); janet_array_push(array, argv[i]);
break; break;
case JANET_ARRAY: case JANET_ARRAY:
case JANET_TUPLE: case JANET_TUPLE: {
{
int32_t j, len; int32_t j, len;
const Janet *vals; const Janet *vals;
janet_indexed_view(argv[i], &vals, &len); janet_indexed_view(argv[i], &vals, &len);
@ -216,46 +215,54 @@ static Janet cfun_array_insert(int32_t argc, Janet *argv) {
} }
static const JanetReg array_cfuns[] = { static const JanetReg array_cfuns[] = {
{"array/new", cfun_array_new, {
"array/new", cfun_array_new,
JDOC("(array/new capacity)\n\n" JDOC("(array/new capacity)\n\n"
"Creates a new empty array with a pre-allocated capacity. The same as " "Creates a new empty array with a pre-allocated capacity. The same as "
"(array) but can be more efficient if the maximum size of an array is known.") "(array) but can be more efficient if the maximum size of an array is known.")
}, },
{"array/pop", cfun_array_pop, {
"array/pop", cfun_array_pop,
JDOC("(array/pop arr)\n\n" JDOC("(array/pop arr)\n\n"
"Remove the last element of the array and return it. If the array is empty, will return nil. Modifies " "Remove the last element of the array and return it. If the array is empty, will return nil. Modifies "
"the input array.") "the input array.")
}, },
{"array/peek", cfun_array_peek, {
"array/peek", cfun_array_peek,
JDOC("(array/peek arr)\n\n" JDOC("(array/peek arr)\n\n"
"Returns the last element of the array. Does not modify the array.") "Returns the last element of the array. Does not modify the array.")
}, },
{"array/push", cfun_array_push, {
"array/push", cfun_array_push,
JDOC("(array/push arr x)\n\n" JDOC("(array/push arr x)\n\n"
"Insert an element in the end of an array. Modifies the input array and returns it.") "Insert an element in the end of an array. Modifies the input array and returns it.")
}, },
{"array/ensure", cfun_array_ensure, {
"array/ensure", cfun_array_ensure,
JDOC("(array/ensure arr capacity)\n\n" JDOC("(array/ensure arr capacity)\n\n"
"Ensures that the memory backing the array has enough memory for capacity " "Ensures that the memory backing the array has enough memory for capacity "
"items. Capacity must be an integer. If the backing capacity is already enough, " "items. Capacity must be an integer. If the backing capacity is already enough, "
"then this function does nothing. Otherwise, the backing memory will be reallocated " "then this function does nothing. Otherwise, the backing memory will be reallocated "
"so that there is enough space.") "so that there is enough space.")
}, },
{"array/slice", cfun_array_slice, {
"array/slice", cfun_array_slice,
JDOC("(array/slice arrtup [, start=0 [, end=(length arrtup)]])\n\n" JDOC("(array/slice arrtup [, start=0 [, end=(length arrtup)]])\n\n"
"Takes a slice of array or tuple from start to end. The range is half open, " "Takes a slice of array or tuple from start to end. The range is half open, "
"[start, end). Indexes can also be negative, indicating indexing from the end of the " "[start, end). Indexes can also be negative, indicating indexing from the end of the "
"end of the array. By default, start is 0 and end is the length of the array. " "end of the array. By default, start is 0 and end is the length of the array. "
"Returns a new array.") "Returns a new array.")
}, },
{"array/concat", cfun_array_concat, {
"array/concat", cfun_array_concat,
JDOC("(array/concat arr & parts)\n\n" JDOC("(array/concat arr & parts)\n\n"
"Concatenates a variadic number of arrays (and tuples) into the first argument " "Concatenates a variadic number of arrays (and tuples) into the first argument "
"which must an array. If any of the parts are arrays or tuples, their elements will " "which must an array. If any of the parts are arrays or tuples, their elements will "
"be inserted into the array. Otherwise, each part in parts will be appended to arr in order. " "be inserted into the array. Otherwise, each part in parts will be appended to arr in order. "
"Return the modified array arr.") "Return the modified array arr.")
}, },
{"array/insert", cfun_array_insert, {
"array/insert", cfun_array_insert,
JDOC("(array/insert arr at & xs)\n\n" JDOC("(array/insert arr at & xs)\n\n"
"Insert all of xs into array arr at index at. at should be an integer " "Insert all of xs into array arr at index at. at should be an integer "
"0 and the length of the array. A negative value for at will index from " "0 and the length of the array. A negative value for at will index from "

View File

@ -253,8 +253,7 @@ static int32_t doarg_1(
default: default:
goto error; goto error;
break; break;
case JANET_NUMBER: case JANET_NUMBER: {
{
double y = janet_unwrap_number(x); double y = janet_unwrap_number(x);
if (janet_checkintrange(y)) { if (janet_checkintrange(y)) {
ret = (int32_t) y; ret = (int32_t) y;
@ -263,8 +262,7 @@ static int32_t doarg_1(
} }
break; break;
} }
case JANET_TUPLE: case JANET_TUPLE: {
{
const Janet *t = janet_unwrap_tuple(x); const Janet *t = janet_unwrap_tuple(x);
if (argtype == JANET_OAT_TYPE) { if (argtype == JANET_OAT_TYPE) {
int32_t i = 0; int32_t i = 0;
@ -277,8 +275,7 @@ static int32_t doarg_1(
} }
break; break;
} }
case JANET_KEYWORD: case JANET_KEYWORD: {
{
if (NULL != c && argtype == JANET_OAT_LABEL) { if (NULL != c && argtype == JANET_OAT_LABEL) {
Janet result = janet_table_get(c, x); Janet result = janet_table_get(c, x);
if (janet_checktype(result, JANET_NUMBER)) { if (janet_checktype(result, JANET_NUMBER)) {
@ -289,7 +286,7 @@ static int32_t doarg_1(
} else if (argtype == JANET_OAT_TYPE || argtype == JANET_OAT_SIMPLETYPE) { } else if (argtype == JANET_OAT_TYPE || argtype == JANET_OAT_SIMPLETYPE) {
const TypeAlias *alias = janet_strbinsearch( const TypeAlias *alias = janet_strbinsearch(
&type_aliases, &type_aliases,
sizeof(type_aliases)/sizeof(TypeAlias), sizeof(type_aliases) / sizeof(TypeAlias),
sizeof(TypeAlias), sizeof(TypeAlias),
janet_unwrap_keyword(x)); janet_unwrap_keyword(x));
if (alias) { if (alias) {
@ -302,8 +299,7 @@ static int32_t doarg_1(
} }
break; break;
} }
case JANET_SYMBOL: case JANET_SYMBOL: {
{
if (NULL != c) { if (NULL != c) {
Janet result = janet_table_get(c, x); Janet result = janet_table_get(c, x);
if (janet_checktype(result, JANET_NUMBER)) { if (janet_checktype(result, JANET_NUMBER)) {
@ -328,7 +324,7 @@ static int32_t doarg_1(
a->def->slotcount = (int32_t) ret + 1; a->def->slotcount = (int32_t) ret + 1;
return ret; return ret;
error: error:
janet_asm_errorv(a, janet_formatc("error parsing instruction argument %v", x)); janet_asm_errorv(a, janet_formatc("error parsing instruction argument %v", x));
return 0; return 0;
} }
@ -364,44 +360,38 @@ static uint32_t read_instruction(
uint32_t instr = idef->opcode; uint32_t instr = idef->opcode;
enum JanetInstructionType type = janet_instructions[idef->opcode]; enum JanetInstructionType type = janet_instructions[idef->opcode];
switch (type) { switch (type) {
case JINT_0: case JINT_0: {
{
if (janet_tuple_length(argt) != 1) if (janet_tuple_length(argt) != 1)
janet_asm_error(a, "expected 0 arguments: (op)"); janet_asm_error(a, "expected 0 arguments: (op)");
break; break;
} }
case JINT_S: case JINT_S: {
{
if (janet_tuple_length(argt) != 2) if (janet_tuple_length(argt) != 2)
janet_asm_error(a, "expected 1 argument: (op, slot)"); janet_asm_error(a, "expected 1 argument: (op, slot)");
instr |= doarg(a, JANET_OAT_SLOT, 1, 2, 0, argt[1]); instr |= doarg(a, JANET_OAT_SLOT, 1, 2, 0, argt[1]);
break; break;
} }
case JINT_L: case JINT_L: {
{
if (janet_tuple_length(argt) != 2) if (janet_tuple_length(argt) != 2)
janet_asm_error(a, "expected 1 argument: (op, label)"); janet_asm_error(a, "expected 1 argument: (op, label)");
instr |= doarg(a, JANET_OAT_LABEL, 1, 3, 1, argt[1]); instr |= doarg(a, JANET_OAT_LABEL, 1, 3, 1, argt[1]);
break; break;
} }
case JINT_SS: case JINT_SS: {
{
if (janet_tuple_length(argt) != 3) if (janet_tuple_length(argt) != 3)
janet_asm_error(a, "expected 2 arguments: (op, slot, slot)"); janet_asm_error(a, "expected 2 arguments: (op, slot, slot)");
instr |= doarg(a, JANET_OAT_SLOT, 1, 1, 0, argt[1]); instr |= doarg(a, JANET_OAT_SLOT, 1, 1, 0, argt[1]);
instr |= doarg(a, JANET_OAT_SLOT, 2, 2, 0, argt[2]); instr |= doarg(a, JANET_OAT_SLOT, 2, 2, 0, argt[2]);
break; break;
} }
case JINT_SL: case JINT_SL: {
{
if (janet_tuple_length(argt) != 3) if (janet_tuple_length(argt) != 3)
janet_asm_error(a, "expected 2 arguments: (op, slot, label)"); janet_asm_error(a, "expected 2 arguments: (op, slot, label)");
instr |= doarg(a, JANET_OAT_SLOT, 1, 1, 0, argt[1]); instr |= doarg(a, JANET_OAT_SLOT, 1, 1, 0, argt[1]);
instr |= doarg(a, JANET_OAT_LABEL, 2, 2, 1, argt[2]); instr |= doarg(a, JANET_OAT_LABEL, 2, 2, 1, argt[2]);
break; break;
} }
case JINT_ST: case JINT_ST: {
{
if (janet_tuple_length(argt) != 3) if (janet_tuple_length(argt) != 3)
janet_asm_error(a, "expected 2 arguments: (op, slot, type)"); janet_asm_error(a, "expected 2 arguments: (op, slot, type)");
instr |= doarg(a, JANET_OAT_SLOT, 1, 1, 0, argt[1]); instr |= doarg(a, JANET_OAT_SLOT, 1, 1, 0, argt[1]);
@ -409,24 +399,21 @@ static uint32_t read_instruction(
break; break;
} }
case JINT_SI: case JINT_SI:
case JINT_SU: case JINT_SU: {
{
if (janet_tuple_length(argt) != 3) if (janet_tuple_length(argt) != 3)
janet_asm_error(a, "expected 2 arguments: (op, slot, integer)"); janet_asm_error(a, "expected 2 arguments: (op, slot, integer)");
instr |= doarg(a, JANET_OAT_SLOT, 1, 1, 0, argt[1]); instr |= doarg(a, JANET_OAT_SLOT, 1, 1, 0, argt[1]);
instr |= doarg(a, JANET_OAT_INTEGER, 2, 2, type == JINT_SI, argt[2]); instr |= doarg(a, JANET_OAT_INTEGER, 2, 2, type == JINT_SI, argt[2]);
break; break;
} }
case JINT_SD: case JINT_SD: {
{
if (janet_tuple_length(argt) != 3) if (janet_tuple_length(argt) != 3)
janet_asm_error(a, "expected 2 arguments: (op, slot, funcdef)"); janet_asm_error(a, "expected 2 arguments: (op, slot, funcdef)");
instr |= doarg(a, JANET_OAT_SLOT, 1, 1, 0, argt[1]); instr |= doarg(a, JANET_OAT_SLOT, 1, 1, 0, argt[1]);
instr |= doarg(a, JANET_OAT_FUNCDEF, 2, 2, 0, argt[2]); instr |= doarg(a, JANET_OAT_FUNCDEF, 2, 2, 0, argt[2]);
break; break;
} }
case JINT_SSS: case JINT_SSS: {
{
if (janet_tuple_length(argt) != 4) if (janet_tuple_length(argt) != 4)
janet_asm_error(a, "expected 3 arguments: (op, slot, slot, slot)"); janet_asm_error(a, "expected 3 arguments: (op, slot, slot, slot)");
instr |= doarg(a, JANET_OAT_SLOT, 1, 1, 0, argt[1]); instr |= doarg(a, JANET_OAT_SLOT, 1, 1, 0, argt[1]);
@ -435,8 +422,7 @@ static uint32_t read_instruction(
break; break;
} }
case JINT_SSI: case JINT_SSI:
case JINT_SSU: case JINT_SSU: {
{
if (janet_tuple_length(argt) != 4) if (janet_tuple_length(argt) != 4)
janet_asm_error(a, "expected 3 arguments: (op, slot, slot, integer)"); janet_asm_error(a, "expected 3 arguments: (op, slot, slot, integer)");
instr |= doarg(a, JANET_OAT_SLOT, 1, 1, 0, argt[1]); instr |= doarg(a, JANET_OAT_SLOT, 1, 1, 0, argt[1]);
@ -444,8 +430,7 @@ static uint32_t read_instruction(
instr |= doarg(a, JANET_OAT_INTEGER, 3, 1, type == JINT_SSI, argt[3]); instr |= doarg(a, JANET_OAT_INTEGER, 3, 1, type == JINT_SSI, argt[3]);
break; break;
} }
case JINT_SES: case JINT_SES: {
{
JanetAssembler *b = a; JanetAssembler *b = a;
uint32_t env; uint32_t env;
if (janet_tuple_length(argt) != 4) if (janet_tuple_length(argt) != 4)
@ -461,8 +446,7 @@ static uint32_t read_instruction(
instr |= doarg(b, JANET_OAT_SLOT, 3, 1, 0, argt[3]); instr |= doarg(b, JANET_OAT_SLOT, 3, 1, 0, argt[3]);
break; break;
} }
case JINT_SC: case JINT_SC: {
{
if (janet_tuple_length(argt) != 3) if (janet_tuple_length(argt) != 3)
janet_asm_error(a, "expected 2 arguments: (op, slot, constant)"); janet_asm_error(a, "expected 2 arguments: (op, slot, constant)");
instr |= doarg(a, JANET_OAT_SLOT, 1, 1, 0, argt[1]); instr |= doarg(a, JANET_OAT_SLOT, 1, 1, 0, argt[1]);
@ -681,7 +665,7 @@ static JanetAssembleResult janet_asm1(JanetAssembler *parent, Janet source, int
"expected symbol in assembly instruction"); "expected symbol in assembly instruction");
idef = janet_strbinsearch( idef = janet_strbinsearch(
&janet_ops, &janet_ops,
sizeof(janet_ops)/sizeof(JanetInstructionDef), sizeof(janet_ops) / sizeof(JanetInstructionDef),
sizeof(JanetInstructionDef), sizeof(JanetInstructionDef),
janet_unwrap_symbol(t[0])); janet_unwrap_symbol(t[0]));
if (NULL == idef) if (NULL == idef)
@ -750,7 +734,7 @@ JanetAssembleResult janet_asm(Janet source, int flags) {
static const JanetInstructionDef *janet_asm_reverse_lookup(uint32_t instr) { static const JanetInstructionDef *janet_asm_reverse_lookup(uint32_t instr) {
size_t i; size_t i;
uint32_t opcode = instr & 0x7F; uint32_t opcode = instr & 0x7F;
for (i = 0; i < sizeof(janet_ops)/sizeof(JanetInstructionDef); i++) { for (i = 0; i < sizeof(janet_ops) / sizeof(JanetInstructionDef); i++) {
const JanetInstructionDef *def = janet_ops + i; const JanetInstructionDef *def = janet_ops + i;
if (def->opcode == opcode) if (def->opcode == opcode)
return def; return def;
@ -934,13 +918,15 @@ static Janet cfun_disasm(int32_t argc, Janet *argv) {
} }
static const JanetReg asm_cfuns[] = { static const JanetReg asm_cfuns[] = {
{"asm", cfun_asm, {
"asm", cfun_asm,
JDOC("(asm assembly)\n\n" JDOC("(asm assembly)\n\n"
"Returns a new function that is the compiled result of the assembly.\n" "Returns a new function that is the compiled result of the assembly.\n"
"The syntax for the assembly can be found on the janet wiki. Will throw an\n" "The syntax for the assembly can be found on the janet wiki. Will throw an\n"
"error on invalid assembly.") "error on invalid assembly.")
}, },
{"disasm", cfun_disasm, {
"disasm", cfun_disasm,
JDOC("(disasm func)\n\n" JDOC("(disasm func)\n\n"
"Returns assembly that could be used be compile the given function.\n" "Returns assembly that could be used be compile the given function.\n"
"func must be a function, not a c function. Will throw on error on a badly\n" "func must be a function, not a c function. Will throw on error on a badly\n"

View File

@ -182,7 +182,7 @@ static Janet cfun_buffer_u8(int32_t argc, Janet *argv) {
janet_arity(argc, 1, -1); janet_arity(argc, 1, -1);
JanetBuffer *buffer = janet_getbuffer(argv, 0); JanetBuffer *buffer = janet_getbuffer(argv, 0);
for (i = 1; i < argc; i++) { for (i = 1; i < argc; i++) {
janet_buffer_push_u8(buffer, (uint8_t) (janet_getinteger(argv, i) & 0xFF)); janet_buffer_push_u8(buffer, (uint8_t)(janet_getinteger(argv, i) & 0xFF));
} }
return argv[0]; return argv[0];
} }
@ -326,72 +326,86 @@ static Janet cfun_buffer_format(int32_t argc, Janet *argv) {
} }
static const JanetReg buffer_cfuns[] = { static const JanetReg buffer_cfuns[] = {
{"buffer/new", cfun_buffer_new, {
"buffer/new", cfun_buffer_new,
JDOC("(buffer/new capacity)\n\n" JDOC("(buffer/new capacity)\n\n"
"Creates a new, empty buffer with enough memory for capacity bytes. " "Creates a new, empty buffer with enough memory for capacity bytes. "
"Returns a new buffer.") "Returns a new buffer.")
}, },
{"buffer/new-filled", cfun_buffer_new_filled, {
"buffer/new-filled", cfun_buffer_new_filled,
JDOC("(buffer/new-filled count [, byte=0])\n\n" JDOC("(buffer/new-filled count [, byte=0])\n\n"
"Creates a new buffer of length count filled with byte. " "Creates a new buffer of length count filled with byte. "
"Returns the new buffer.") "Returns the new buffer.")
}, },
{"buffer/push-byte", cfun_buffer_u8, {
"buffer/push-byte", cfun_buffer_u8,
JDOC("(buffer/push-byte buffer x)\n\n" JDOC("(buffer/push-byte buffer x)\n\n"
"Append a byte to a buffer. Will expand the buffer as necessary. " "Append a byte to a buffer. Will expand the buffer as necessary. "
"Returns the modified buffer. Will throw an error if the buffer overflows.") "Returns the modified buffer. Will throw an error if the buffer overflows.")
}, },
{"buffer/push-word", cfun_buffer_word, {
"buffer/push-word", cfun_buffer_word,
JDOC("(buffer/push-word buffer x)\n\n" JDOC("(buffer/push-word buffer x)\n\n"
"Append a machine word to a buffer. The 4 bytes of the integer are appended " "Append a machine word to a buffer. The 4 bytes of the integer are appended "
"in twos complement, big endian order, unsigned. Returns the modified buffer. Will " "in twos complement, big endian order, unsigned. Returns the modified buffer. Will "
"throw an error if the buffer overflows.") "throw an error if the buffer overflows.")
}, },
{"buffer/push-string", cfun_buffer_chars, {
"buffer/push-string", cfun_buffer_chars,
JDOC("(buffer/push-string buffer str)\n\n" JDOC("(buffer/push-string buffer str)\n\n"
"Push a string onto the end of a buffer. Non string values will be converted " "Push a string onto the end of a buffer. Non string values will be converted "
"to strings before being pushed. Returns the modified buffer. " "to strings before being pushed. Returns the modified buffer. "
"Will throw an error if the buffer overflows.") "Will throw an error if the buffer overflows.")
}, },
{"buffer/popn", cfun_buffer_popn, {
"buffer/popn", cfun_buffer_popn,
JDOC("(buffer/popn buffer n)\n\n" JDOC("(buffer/popn buffer n)\n\n"
"Removes the last n bytes from the buffer. Returns the modified buffer.") "Removes the last n bytes from the buffer. Returns the modified buffer.")
}, },
{"buffer/clear", cfun_buffer_clear, {
"buffer/clear", cfun_buffer_clear,
JDOC("(buffer/clear buffer)\n\n" JDOC("(buffer/clear buffer)\n\n"
"Sets the size of a buffer to 0 and empties it. The buffer retains " "Sets the size of a buffer to 0 and empties it. The buffer retains "
"its memory so it can be efficiently refilled. Returns the modified buffer.") "its memory so it can be efficiently refilled. Returns the modified buffer.")
}, },
{"buffer/slice", cfun_buffer_slice, {
"buffer/slice", cfun_buffer_slice,
JDOC("(buffer/slice bytes [, start=0 [, end=(length bytes)]])\n\n" JDOC("(buffer/slice bytes [, start=0 [, end=(length bytes)]])\n\n"
"Takes a slice of a byte sequence from start to end. The range is half open, " "Takes a slice of a byte sequence from start to end. The range is half open, "
"[start, end). Indexes can also be negative, indicating indexing from the end of the " "[start, end). Indexes can also be negative, indicating indexing from the end of the "
"end of the array. By default, start is 0 and end is the length of the buffer. " "end of the array. By default, start is 0 and end is the length of the buffer. "
"Returns a new buffer.") "Returns a new buffer.")
}, },
{"buffer/bit-set", cfun_buffer_bitset, {
"buffer/bit-set", cfun_buffer_bitset,
JDOC("(buffer/bit-set buffer index)\n\n" JDOC("(buffer/bit-set buffer index)\n\n"
"Sets the bit at the given bit-index. Returns the buffer.") "Sets the bit at the given bit-index. Returns the buffer.")
}, },
{"buffer/bit-clear", cfun_buffer_bitclear, {
"buffer/bit-clear", cfun_buffer_bitclear,
JDOC("(buffer/bit-clear buffer index)\n\n" JDOC("(buffer/bit-clear buffer index)\n\n"
"Clears the bit at the given bit-index. Returns the buffer.") "Clears the bit at the given bit-index. Returns the buffer.")
}, },
{"buffer/bit", cfun_buffer_bitget, {
"buffer/bit", cfun_buffer_bitget,
JDOC("(buffer/bit buffer index)\n\n" JDOC("(buffer/bit buffer index)\n\n"
"Gets the bit at the given bit-index. Returns true if the bit is set, false if not.") "Gets the bit at the given bit-index. Returns true if the bit is set, false if not.")
}, },
{"buffer/bit-toggle", cfun_buffer_bittoggle, {
"buffer/bit-toggle", cfun_buffer_bittoggle,
JDOC("(buffer/bit-toggle buffer index)\n\n" JDOC("(buffer/bit-toggle buffer index)\n\n"
"Toggles the bit at the given bit index in buffer. Returns the buffer.") "Toggles the bit at the given bit index in buffer. Returns the buffer.")
}, },
{"buffer/blit", cfun_buffer_blit, {
"buffer/blit", cfun_buffer_blit,
JDOC("(buffer/blit dest src [, dest-start=0 [, src-start=0 [, src-end=-1]]])\n\n" JDOC("(buffer/blit dest src [, dest-start=0 [, src-start=0 [, src-end=-1]]])\n\n"
"Insert the contents of src into dest. Can optionally take indices that " "Insert the contents of src into dest. Can optionally take indices that "
"indicate which part of src to copy into which part of dest. Indices can be " "indicate which part of src to copy into which part of dest. Indices can be "
"negative to index from the end of src or dest. Returns dest.") "negative to index from the end of src or dest. Returns dest.")
}, },
{"buffer/format", cfun_buffer_format, {
"buffer/format", cfun_buffer_format,
JDOC("(buffer/format buffer format & args)\n\n" JDOC("(buffer/format buffer format & args)\n\n"
"Snprintf like functionality for printing values into a buffer. Returns " "Snprintf like functionality for printing values into a buffer. Returns "
" the modified buffer.") " the modified buffer.")

View File

@ -118,65 +118,55 @@ int32_t janet_verify(JanetFuncDef *def) {
switch (type) { switch (type) {
case JINT_0: case JINT_0:
continue; continue;
case JINT_S: case JINT_S: {
{
if ((int32_t)(instr >> 8) >= sc) return 4; if ((int32_t)(instr >> 8) >= sc) return 4;
continue; continue;
} }
case JINT_SI: case JINT_SI:
case JINT_SU: case JINT_SU:
case JINT_ST: case JINT_ST: {
{
if ((int32_t)((instr >> 8) & 0xFF) >= sc) return 4; if ((int32_t)((instr >> 8) & 0xFF) >= sc) return 4;
continue; continue;
} }
case JINT_L: case JINT_L: {
{
int32_t jumpdest = i + (((int32_t)instr) >> 8); int32_t jumpdest = i + (((int32_t)instr) >> 8);
if (jumpdest < 0 || jumpdest >= def->bytecode_length) return 5; if (jumpdest < 0 || jumpdest >= def->bytecode_length) return 5;
continue; continue;
} }
case JINT_SS: case JINT_SS: {
{
if ((int32_t)((instr >> 8) & 0xFF) >= sc || if ((int32_t)((instr >> 8) & 0xFF) >= sc ||
(int32_t)(instr >> 16) >= sc) return 4; (int32_t)(instr >> 16) >= sc) return 4;
continue; continue;
} }
case JINT_SSI: case JINT_SSI:
case JINT_SSU: case JINT_SSU: {
{
if ((int32_t)((instr >> 8) & 0xFF) >= sc || if ((int32_t)((instr >> 8) & 0xFF) >= sc ||
(int32_t)((instr >> 16) & 0xFF) >= sc) return 4; (int32_t)((instr >> 16) & 0xFF) >= sc) return 4;
continue; continue;
} }
case JINT_SL: case JINT_SL: {
{
int32_t jumpdest = i + (((int32_t)instr) >> 16); int32_t jumpdest = i + (((int32_t)instr) >> 16);
if ((int32_t)((instr >> 8) & 0xFF) >= sc) return 4; if ((int32_t)((instr >> 8) & 0xFF) >= sc) return 4;
if (jumpdest < 0 || jumpdest >= def->bytecode_length) return 5; if (jumpdest < 0 || jumpdest >= def->bytecode_length) return 5;
continue; continue;
} }
case JINT_SSS: case JINT_SSS: {
{
if (((int32_t)(instr >> 8) & 0xFF) >= sc || if (((int32_t)(instr >> 8) & 0xFF) >= sc ||
((int32_t)(instr >> 16) & 0xFF) >= sc || ((int32_t)(instr >> 16) & 0xFF) >= sc ||
((int32_t)(instr >> 24) & 0xFF) >= sc) return 4; ((int32_t)(instr >> 24) & 0xFF) >= sc) return 4;
continue; continue;
} }
case JINT_SD: case JINT_SD: {
{
if ((int32_t)((instr >> 8) & 0xFF) >= sc) return 4; if ((int32_t)((instr >> 8) & 0xFF) >= sc) return 4;
if ((int32_t)(instr >> 16) >= def->defs_length) return 6; if ((int32_t)(instr >> 16) >= def->defs_length) return 6;
continue; continue;
} }
case JINT_SC: case JINT_SC: {
{
if ((int32_t)((instr >> 8) & 0xFF) >= sc) return 4; if ((int32_t)((instr >> 8) & 0xFF) >= sc) return 4;
if ((int32_t)(instr >> 16) >= def->constants_length) return 7; if ((int32_t)(instr >> 16) >= def->constants_length) return 7;
continue; continue;
} }
case JINT_SES: case JINT_SES: {
{
/* How can we check the last slot index? We need info parent funcdefs. Resort /* How can we check the last slot index? We need info parent funcdefs. Resort
* to runtime checks for now. Maybe invalid upvalue references could be defaulted * to runtime checks for now. Maybe invalid upvalue references could be defaulted
* to nil? (don't commit to this in the long term, though) */ * to nil? (don't commit to this in the long term, though) */

View File

@ -125,9 +125,9 @@ static JanetSlot do_apply(JanetFopts opts, JanetSlot *args) {
JanetCompiler *c = opts.compiler; JanetCompiler *c = opts.compiler;
int32_t i; int32_t i;
for (i = 1; i < janet_v_count(args) - 3; i += 3) for (i = 1; i < janet_v_count(args) - 3; i += 3)
janetc_emit_sss(c, JOP_PUSH_3, args[i], args[i+1], args[i+2], 0); janetc_emit_sss(c, JOP_PUSH_3, args[i], args[i + 1], args[i + 2], 0);
if (i == janet_v_count(args) - 3) if (i == janet_v_count(args) - 3)
janetc_emit_ss(c, JOP_PUSH_2, args[i], args[i+1], 0); janetc_emit_ss(c, JOP_PUSH_2, args[i], args[i + 1], 0);
else if (i == janet_v_count(args) - 2) else if (i == janet_v_count(args) - 2)
janetc_emit_s(c, JOP_PUSH, args[i], 0); janetc_emit_s(c, JOP_PUSH, args[i], 0);
/* Push array phase */ /* Push array phase */
@ -297,7 +297,7 @@ const JanetFunOptimizer *janetc_funopt(uint32_t flags) {
if (tag == 0) if (tag == 0)
return NULL; return NULL;
uint32_t index = tag - 1; uint32_t index = tag - 1;
if (index >= (sizeof(optimizers)/sizeof(optimizers[0]))) if (index >= (sizeof(optimizers) / sizeof(optimizers[0])))
return NULL; return NULL;
return optimizers + index; return optimizers + index;
} }

View File

@ -206,8 +206,7 @@ JanetSlot janetc_resolve(
case JANET_BINDING_DEF: case JANET_BINDING_DEF:
case JANET_BINDING_MACRO: /* Macro should function like defs when not in calling pos */ case JANET_BINDING_MACRO: /* Macro should function like defs when not in calling pos */
return janetc_cslot(check); return janetc_cslot(check);
case JANET_BINDING_VAR: case JANET_BINDING_VAR: {
{
JanetSlot ret = janetc_cslot(check); JanetSlot ret = janetc_cslot(check);
/* TODO save type info */ /* TODO save type info */
ret.flags |= JANET_SLOT_REF | JANET_SLOT_NAMED | JANET_SLOT_MUTABLE | JANET_SLOTTYPE_ANY; ret.flags |= JANET_SLOT_REF | JANET_SLOT_NAMED | JANET_SLOT_MUTABLE | JANET_SLOTTYPE_ANY;
@ -218,7 +217,7 @@ JanetSlot janetc_resolve(
} }
/* Symbol was found */ /* Symbol was found */
found: found:
/* Constants can be returned immediately (they are stateless) */ /* Constants can be returned immediately (they are stateless) */
if (ret.flags & (JANET_SLOT_CONSTANT | JANET_SLOT_REF)) if (ret.flags & (JANET_SLOT_CONSTANT | JANET_SLOT_REF))
@ -334,17 +333,17 @@ void janetc_pushslots(JanetCompiler *c, JanetSlot *slots) {
i++; i++;
} else if (slots[i + 1].flags & JANET_SLOT_SPLICED) { } else if (slots[i + 1].flags & JANET_SLOT_SPLICED) {
janetc_emit_s(c, JOP_PUSH, slots[i], 0); janetc_emit_s(c, JOP_PUSH, slots[i], 0);
janetc_emit_s(c, JOP_PUSH_ARRAY, slots[i+1], 0); janetc_emit_s(c, JOP_PUSH_ARRAY, slots[i + 1], 0);
i += 2; i += 2;
} else if (i + 2 == count) { } else if (i + 2 == count) {
janetc_emit_ss(c, JOP_PUSH_2, slots[i], slots[i+1], 0); janetc_emit_ss(c, JOP_PUSH_2, slots[i], slots[i + 1], 0);
i += 2; i += 2;
} else if (slots[i + 2].flags & JANET_SLOT_SPLICED) { } else if (slots[i + 2].flags & JANET_SLOT_SPLICED) {
janetc_emit_ss(c, JOP_PUSH_2, slots[i], slots[i+1], 0); janetc_emit_ss(c, JOP_PUSH_2, slots[i], slots[i + 1], 0);
janetc_emit_s(c, JOP_PUSH_ARRAY, slots[i+2], 0); janetc_emit_s(c, JOP_PUSH_ARRAY, slots[i + 2], 0);
i += 3; i += 3;
} else { } else {
janetc_emit_sss(c, JOP_PUSH_3, slots[i], slots[i+1], slots[i+2], 0); janetc_emit_sss(c, JOP_PUSH_3, slots[i], slots[i + 1], slots[i + 2], 0);
i += 3; i += 3;
} }
} }
@ -548,8 +547,7 @@ JanetSlot janetc_value(JanetFopts opts, Janet x) {
ret = spec->compile(opts, janet_tuple_length(tup) - 1, tup + 1); ret = spec->compile(opts, janet_tuple_length(tup) - 1, tup + 1);
} else { } else {
switch (janet_type(x)) { switch (janet_type(x)) {
case JANET_TUPLE: case JANET_TUPLE: {
{
JanetFopts subopts = janetc_fopts_default(c); JanetFopts subopts = janetc_fopts_default(c);
const Janet *tup = janet_unwrap_tuple(x); const Janet *tup = janet_unwrap_tuple(x);
/* Empty tuple is tuple literal */ /* Empty tuple is tuple literal */
@ -737,7 +735,8 @@ static Janet cfun(int32_t argc, Janet *argv) {
} }
static const JanetReg compile_cfuns[] = { static const JanetReg compile_cfuns[] = {
{"compile", cfun, {
"compile", cfun,
JDOC("(compile ast env [, source])\n\n" JDOC("(compile ast env [, source])\n\n"
"Compiles an Abstract Syntax Tree (ast) into a janet function. " "Compiles an Abstract Syntax Tree (ast) into a janet function. "
"Pair the compile function with parsing functionality to implement " "Pair the compile function with parsing functionality to implement "

View File

@ -180,13 +180,13 @@ JanetFopts janetc_fopts_default(JanetCompiler *c);
/* For optimizing builtin normal functions. */ /* For optimizing builtin normal functions. */
struct JanetFunOptimizer { struct JanetFunOptimizer {
int (*can_optimize)(JanetFopts opts, JanetSlot *args); int (*can_optimize)(JanetFopts opts, JanetSlot *args);
JanetSlot (*optimize)(JanetFopts opts, JanetSlot *args); JanetSlot(*optimize)(JanetFopts opts, JanetSlot *args);
}; };
/* A grouping of a named special and the corresponding compiler fragment */ /* A grouping of a named special and the corresponding compiler fragment */
struct JanetSpecial { struct JanetSpecial {
const char *name; const char *name;
JanetSlot (*compile)(JanetFopts opts, int32_t argn, const Janet *argv); JanetSlot(*compile)(JanetFopts opts, int32_t argn, const Janet *argv);
}; };
/****************************************************/ /****************************************************/

View File

@ -244,7 +244,8 @@ static Janet janet_core_hash(int32_t argc, Janet *argv) {
} }
static const JanetReg corelib_cfuns[] = { static const JanetReg corelib_cfuns[] = {
{"native", janet_core_native, {
"native", janet_core_native,
JDOC("(native path [,env])\n\n" JDOC("(native path [,env])\n\n"
"Load a native module from the given path. The path " "Load a native module from the given path. The path "
"must be an absolute or relative path on the file system, and is " "must be an absolute or relative path on the file system, and is "
@ -252,95 +253,112 @@ static const JanetReg corelib_cfuns[] = {
"Returns an environment table that contains functions and other values " "Returns an environment table that contains functions and other values "
"from the native module.") "from the native module.")
}, },
{"print", janet_core_print, {
"print", janet_core_print,
JDOC("(print & xs)\n\n" JDOC("(print & xs)\n\n"
"Print values to the console (standard out). Value are converted " "Print values to the console (standard out). Value are converted "
"to strings if they are not already. After printing all values, a " "to strings if they are not already. After printing all values, a "
"newline character is printed. Returns nil.") "newline character is printed. Returns nil.")
}, },
{"describe", janet_core_describe, {
"describe", janet_core_describe,
JDOC("(describe x)\n\n" JDOC("(describe x)\n\n"
"Returns a string that is a human readable description of a value x.") "Returns a string that is a human readable description of a value x.")
}, },
{"string", janet_core_string, {
"string", janet_core_string,
JDOC("(string & parts)\n\n" JDOC("(string & parts)\n\n"
"Creates a string by concatenating values together. Values are " "Creates a string by concatenating values together. Values are "
"converted to bytes via describe if they are not byte sequences. " "converted to bytes via describe if they are not byte sequences. "
"Returns the new string.") "Returns the new string.")
}, },
{"symbol", janet_core_symbol, {
"symbol", janet_core_symbol,
JDOC("(symbol & xs)\n\n" JDOC("(symbol & xs)\n\n"
"Creates a symbol by concatenating values together. Values are " "Creates a symbol by concatenating values together. Values are "
"converted to bytes via describe if they are not byte sequences. Returns " "converted to bytes via describe if they are not byte sequences. Returns "
"the new symbol.") "the new symbol.")
}, },
{"keyword", janet_core_keyword, {
"keyword", janet_core_keyword,
JDOC("(keyword & xs)\n\n" JDOC("(keyword & xs)\n\n"
"Creates a keyword by concatenating values together. Values are " "Creates a keyword by concatenating values together. Values are "
"converted to bytes via describe if they are not byte sequences. Returns " "converted to bytes via describe if they are not byte sequences. Returns "
"the new keyword.") "the new keyword.")
}, },
{"buffer", janet_core_buffer, {
"buffer", janet_core_buffer,
JDOC("(buffer & xs)\n\n" JDOC("(buffer & xs)\n\n"
"Creates a new buffer by concatenating values together. Values are " "Creates a new buffer by concatenating values together. Values are "
"converted to bytes via describe if they are not byte sequences. Returns " "converted to bytes via describe if they are not byte sequences. Returns "
"the new buffer.") "the new buffer.")
}, },
{"abstract?", janet_core_is_abstract, {
"abstract?", janet_core_is_abstract,
JDOC("(abstract? x)\n\n" JDOC("(abstract? x)\n\n"
"Check if x is an abstract type.") "Check if x is an abstract type.")
}, },
{"table", janet_core_table, {
"table", janet_core_table,
JDOC("(table & kvs)\n\n" JDOC("(table & kvs)\n\n"
"Creates a new table from a variadic number of keys and values. " "Creates a new table from a variadic number of keys and values. "
"kvs is a sequence k1, v1, k2, v2, k3, v3, ... If kvs has " "kvs is a sequence k1, v1, k2, v2, k3, v3, ... If kvs has "
"an odd number of elements, an error will be thrown. Returns the " "an odd number of elements, an error will be thrown. Returns the "
"new table.") "new table.")
}, },
{"array", janet_core_array, {
"array", janet_core_array,
JDOC("(array & items)\n\n" JDOC("(array & items)\n\n"
"Create a new array that contains items. Returns the new array.") "Create a new array that contains items. Returns the new array.")
}, },
{"scan-number", janet_core_scannumber, {
"scan-number", janet_core_scannumber,
JDOC("(scan-number str)\n\n" JDOC("(scan-number str)\n\n"
"Parse a number from a byte sequence an return that number, either and integer " "Parse a number from a byte sequence an return that number, either and integer "
"or a real. The number " "or a real. The number "
"must be in the same format as numbers in janet source code. Will return nil " "must be in the same format as numbers in janet source code. Will return nil "
"on an invalid number.") "on an invalid number.")
}, },
{"tuple", janet_core_tuple, {
"tuple", janet_core_tuple,
JDOC("(tuple & items)\n\n" JDOC("(tuple & items)\n\n"
"Creates a new tuple that contains items. Returns the new tuple.") "Creates a new tuple that contains items. Returns the new tuple.")
}, },
{"struct", janet_core_struct, {
"struct", janet_core_struct,
JDOC("(struct & kvs)\n\n" JDOC("(struct & kvs)\n\n"
"Create a new struct from a sequence of key value pairs. " "Create a new struct from a sequence of key value pairs. "
"kvs is a sequence k1, v1, k2, v2, k3, v3, ... If kvs has " "kvs is a sequence k1, v1, k2, v2, k3, v3, ... If kvs has "
"an odd number of elements, an error will be thrown. Returns the " "an odd number of elements, an error will be thrown. Returns the "
"new struct.") "new struct.")
}, },
{"gensym", janet_core_gensym, {
"gensym", janet_core_gensym,
JDOC("(gensym)\n\n" JDOC("(gensym)\n\n"
"Returns a new symbol that is unique across the runtime. This means it " "Returns a new symbol that is unique across the runtime. This means it "
"will not collide with any already created symbols during compilation, so " "will not collide with any already created symbols during compilation, so "
"it can be used in macros to generate automatic bindings.") "it can be used in macros to generate automatic bindings.")
}, },
{"gccollect", janet_core_gccollect, {
"gccollect", janet_core_gccollect,
JDOC("(gccollect)\n\n" JDOC("(gccollect)\n\n"
"Run garbage collection. You should probably not call this manually.") "Run garbage collection. You should probably not call this manually.")
}, },
{"gcsetinterval", janet_core_gcsetinterval, {
"gcsetinterval", janet_core_gcsetinterval,
JDOC("(gcsetinterval interval)\n\n" JDOC("(gcsetinterval interval)\n\n"
"Set an integer number of bytes to allocate before running garbage collection. " "Set an integer number of bytes to allocate before running garbage collection. "
"Low valuesi for interval will be slower but use less memory. " "Low valuesi for interval will be slower but use less memory. "
"High values will be faster but use more memory.") "High values will be faster but use more memory.")
}, },
{"gcinterval", janet_core_gcinterval, {
"gcinterval", janet_core_gcinterval,
JDOC("(gcinterval)\n\n" JDOC("(gcinterval)\n\n"
"Returns the integer number of bytes to allocate before running an iteration " "Returns the integer number of bytes to allocate before running an iteration "
"of garbage collection.") "of garbage collection.")
}, },
{"type", janet_core_type, {
"type", janet_core_type,
JDOC("(type x)\n\n" JDOC("(type x)\n\n"
"Returns the type of x as a keyword symbol. x is one of\n" "Returns the type of x as a keyword symbol. x is one of\n"
"\t:nil\n" "\t:nil\n"
@ -359,7 +377,8 @@ static const JanetReg corelib_cfuns[] = {
"\t:cfunction\n\n" "\t:cfunction\n\n"
"or another symbol for an abstract type.") "or another symbol for an abstract type.")
}, },
{"next", janet_core_next, {
"next", janet_core_next,
JDOC("(next dict key)\n\n" JDOC("(next dict key)\n\n"
"Gets the next key in a struct or table. Can be used to iterate through " "Gets the next key in a struct or table. Can be used to iterate through "
"the keys of a data structure in an unspecified order. Keys are guaranteed " "the keys of a data structure in an unspecified order. Keys are guaranteed "
@ -367,7 +386,8 @@ static const JanetReg corelib_cfuns[] = {
"during iteration. If key is nil, next returns the first key. If next " "during iteration. If key is nil, next returns the first key. If next "
"returns nil, there are no more keys to iterate through. ") "returns nil, there are no more keys to iterate through. ")
}, },
{"hash", janet_core_hash, {
"hash", janet_core_hash,
JDOC("(hash value)\n\n" JDOC("(hash value)\n\n"
"Gets a hash value for any janet value. The hash is an integer can be used " "Gets a hash value for any janet value. The hash is an integer can be used "
"as a cheap hash function for all janet objects. If two values are strictly equal, " "as a cheap hash function for all janet objects. If two values are strictly equal, "

View File

@ -144,7 +144,7 @@ void janet_stacktrace(JanetFiber *fiber, Janet err) {
if (frame->flags & JANET_STACKFRAME_TAILCALL) if (frame->flags & JANET_STACKFRAME_TAILCALL)
fprintf(stderr, " (tailcall)"); fprintf(stderr, " (tailcall)");
if (frame->func && frame->pc) { if (frame->func && frame->pc) {
int32_t off = (int32_t) (frame->pc - def->bytecode); int32_t off = (int32_t)(frame->pc - def->bytecode);
if (def->sourcemap) { if (def->sourcemap) {
JanetSourceMapping mapping = def->sourcemap[off]; JanetSourceMapping mapping = def->sourcemap[off];
fprintf(stderr, " at (%d:%d)", mapping.start, mapping.end); fprintf(stderr, " at (%d:%d)", mapping.start, mapping.end);
@ -252,7 +252,7 @@ static Janet doframe(JanetStackFrame *frame) {
if (frame->func && frame->pc) { if (frame->func && frame->pc) {
Janet *stack = (Janet *)frame + JANET_FRAME_SIZE; Janet *stack = (Janet *)frame + JANET_FRAME_SIZE;
JanetArray *slots; JanetArray *slots;
off = (int32_t) (frame->pc - def->bytecode); off = (int32_t)(frame->pc - def->bytecode);
janet_table_put(t, janet_ckeywordv("pc"), janet_wrap_integer(off)); janet_table_put(t, janet_ckeywordv("pc"), janet_wrap_integer(off));
if (def->sourcemap) { if (def->sourcemap) {
JanetSourceMapping mapping = def->sourcemap[off]; JanetSourceMapping mapping = def->sourcemap[off];

View File

@ -84,8 +84,7 @@ static void janetc_loadconst(JanetCompiler *c, Janet k, int32_t reg) {
case JANET_FALSE: case JANET_FALSE:
janetc_emit(c, (reg << 8) | JOP_LOAD_FALSE); janetc_emit(c, (reg << 8) | JOP_LOAD_FALSE);
break; break;
case JANET_NUMBER: case JANET_NUMBER: {
{
double dval = janet_unwrap_number(k); double dval = janet_unwrap_number(k);
int32_t i = (int32_t) dval; int32_t i = (int32_t) dval;
if (dval != i || !(dval >= INT16_MIN && dval <= INT16_MAX)) if (dval != i || !(dval >= INT16_MIN && dval <= INT16_MAX))
@ -97,8 +96,7 @@ static void janetc_loadconst(JanetCompiler *c, Janet k, int32_t reg) {
break; break;
} }
default: default:
do_constant: do_constant: {
{
int32_t cindex = janetc_const(c, k); int32_t cindex = janetc_const(c, k);
janetc_emit(c, janetc_emit(c,
(cindex << 16) | (cindex << 16) |

View File

@ -60,18 +60,37 @@ void janet_mark(Janet x) {
if (depth) { if (depth) {
depth--; depth--;
switch (janet_type(x)) { switch (janet_type(x)) {
default: break; default:
break;
case JANET_STRING: case JANET_STRING:
case JANET_KEYWORD: case JANET_KEYWORD:
case JANET_SYMBOL: janet_mark_string(janet_unwrap_string(x)); break; case JANET_SYMBOL:
case JANET_FUNCTION: janet_mark_function(janet_unwrap_function(x)); break; janet_mark_string(janet_unwrap_string(x));
case JANET_ARRAY: janet_mark_array(janet_unwrap_array(x)); break; break;
case JANET_TABLE: janet_mark_table(janet_unwrap_table(x)); break; case JANET_FUNCTION:
case JANET_STRUCT: janet_mark_struct(janet_unwrap_struct(x)); break; janet_mark_function(janet_unwrap_function(x));
case JANET_TUPLE: janet_mark_tuple(janet_unwrap_tuple(x)); break; break;
case JANET_BUFFER: janet_mark_buffer(janet_unwrap_buffer(x)); break; case JANET_ARRAY:
case JANET_FIBER: janet_mark_fiber(janet_unwrap_fiber(x)); break; janet_mark_array(janet_unwrap_array(x));
case JANET_ABSTRACT: janet_mark_abstract(janet_unwrap_abstract(x)); break; break;
case JANET_TABLE:
janet_mark_table(janet_unwrap_table(x));
break;
case JANET_STRUCT:
janet_mark_struct(janet_unwrap_struct(x));
break;
case JANET_TUPLE:
janet_mark_tuple(janet_unwrap_tuple(x));
break;
case JANET_BUFFER:
janet_mark_buffer(janet_unwrap_buffer(x));
break;
case JANET_FIBER:
janet_mark_fiber(janet_unwrap_fiber(x));
break;
case JANET_ABSTRACT:
janet_mark_abstract(janet_unwrap_abstract(x));
break;
} }
depth++; depth++;
} else { } else {
@ -123,7 +142,7 @@ static void janet_mark_array(JanetArray *array) {
} }
static void janet_mark_table(JanetTable *table) { static void janet_mark_table(JanetTable *table) {
recur: /* Manual tail recursion */ recur: /* Manual tail recursion */
if (janet_gc_reachable(table)) if (janet_gc_reachable(table))
return; return;
janet_gc_mark(table); janet_gc_mark(table);
@ -236,10 +255,10 @@ static void janet_deinit_block(JanetGCMemoryHeader *block) {
janet_symbol_deinit((const uint8_t *)mem + 2 * sizeof(int32_t)); janet_symbol_deinit((const uint8_t *)mem + 2 * sizeof(int32_t));
break; break;
case JANET_MEMORY_ARRAY: case JANET_MEMORY_ARRAY:
janet_array_deinit((JanetArray*) mem); janet_array_deinit((JanetArray *) mem);
break; break;
case JANET_MEMORY_TABLE: case JANET_MEMORY_TABLE:
janet_table_deinit((JanetTable*) mem); janet_table_deinit((JanetTable *) mem);
break; break;
case JANET_MEMORY_FIBER: case JANET_MEMORY_FIBER:
free(((JanetFiber *)mem)->data); free(((JanetFiber *)mem)->data);
@ -252,15 +271,13 @@ static void janet_deinit_block(JanetGCMemoryHeader *block) {
janet_assert(!h->type->gc((void *)(h + 1), h->size), "finalizer failed"); janet_assert(!h->type->gc((void *)(h + 1), h->size), "finalizer failed");
} }
break; break;
case JANET_MEMORY_FUNCENV: case JANET_MEMORY_FUNCENV: {
{
JanetFuncEnv *env = (JanetFuncEnv *)mem; JanetFuncEnv *env = (JanetFuncEnv *)mem;
if (0 == env->offset) if (0 == env->offset)
free(env->as.values); free(env->as.values);
} }
break; break;
case JANET_MEMORY_FUNCDEF: case JANET_MEMORY_FUNCDEF: {
{
JanetFuncDef *def = (JanetFuncDef *)mem; JanetFuncDef *def = (JanetFuncDef *)mem;
/* TODO - get this all with one alloc and one free */ /* TODO - get this all with one alloc and one free */
free(def->defs); free(def->defs);
@ -417,5 +434,9 @@ void janet_clear_memory(void) {
} }
/* Primitives for suspending GC. */ /* Primitives for suspending GC. */
int janet_gclock(void) { return janet_vm_gc_suspend++; } int janet_gclock(void) {
void janet_gcunlock(int handle) { janet_vm_gc_suspend = handle; } return janet_vm_gc_suspend++;
}
void janet_gcunlock(int handle) {
janet_vm_gc_suspend = handle;
}

View File

@ -306,8 +306,7 @@ static void marshal_one(MarshalState *st, Janet x, int flags) {
case JANET_TRUE: case JANET_TRUE:
pushbyte(st, 200 + type); pushbyte(st, 200 + type);
goto done; goto done;
case JANET_NUMBER: case JANET_NUMBER: {
{
double xval = janet_unwrap_number(x); double xval = janet_unwrap_number(x);
if (janet_checkintrange(xval)) { if (janet_checkintrange(xval)) {
pushint(st, (int32_t) xval); pushint(st, (int32_t) xval);
@ -343,8 +342,7 @@ static void marshal_one(MarshalState *st, Janet x, int flags) {
/* Reference types */ /* Reference types */
switch (type) { switch (type) {
case JANET_NUMBER: case JANET_NUMBER: {
{
union { union {
double d; double d;
uint8_t bytes[8]; uint8_t bytes[8];
@ -353,10 +351,18 @@ static void marshal_one(MarshalState *st, Janet x, int flags) {
#ifdef JANET_BIG_ENDIAN #ifdef JANET_BIG_ENDIAN
/* Swap byte order */ /* Swap byte order */
uint8_t temp; uint8_t temp;
temp = u.bytes[7]; u.bytes[7] = u.bytes[0]; u.bytes[0] = temp; temp = u.bytes[7];
temp = u.bytes[6]; u.bytes[6] = u.bytes[1]; u.bytes[1] = temp; u.bytes[7] = u.bytes[0];
temp = u.bytes[5]; u.bytes[5] = u.bytes[2]; u.bytes[2] = temp; u.bytes[0] = temp;
temp = u.bytes[4]; u.bytes[4] = u.bytes[3]; u.bytes[3] = temp; temp = u.bytes[6];
u.bytes[6] = u.bytes[1];
u.bytes[1] = temp;
temp = u.bytes[5];
u.bytes[5] = u.bytes[2];
u.bytes[2] = temp;
temp = u.bytes[4];
u.bytes[4] = u.bytes[3];
u.bytes[3] = temp;
#endif #endif
pushbyte(st, LB_REAL); pushbyte(st, LB_REAL);
pushbytes(st, u.bytes, 8); pushbytes(st, u.bytes, 8);
@ -365,8 +371,7 @@ static void marshal_one(MarshalState *st, Janet x, int flags) {
goto done; goto done;
case JANET_STRING: case JANET_STRING:
case JANET_SYMBOL: case JANET_SYMBOL:
case JANET_KEYWORD: case JANET_KEYWORD: {
{
const uint8_t *str = janet_unwrap_string(x); const uint8_t *str = janet_unwrap_string(x);
int32_t length = janet_string_length(str); int32_t length = janet_string_length(str);
/* Record reference */ /* Record reference */
@ -379,8 +384,7 @@ static void marshal_one(MarshalState *st, Janet x, int flags) {
pushbytes(st, str, length); pushbytes(st, str, length);
} }
goto done; goto done;
case JANET_BUFFER: case JANET_BUFFER: {
{
JanetBuffer *buffer = janet_unwrap_buffer(x); JanetBuffer *buffer = janet_unwrap_buffer(x);
/* Record reference */ /* Record reference */
MARK_SEEN(); MARK_SEEN();
@ -389,8 +393,7 @@ static void marshal_one(MarshalState *st, Janet x, int flags) {
pushbytes(st, buffer->data, buffer->count); pushbytes(st, buffer->data, buffer->count);
} }
goto done; goto done;
case JANET_ARRAY: case JANET_ARRAY: {
{
int32_t i; int32_t i;
JanetArray *a = janet_unwrap_array(x); JanetArray *a = janet_unwrap_array(x);
MARK_SEEN(); MARK_SEEN();
@ -400,8 +403,7 @@ static void marshal_one(MarshalState *st, Janet x, int flags) {
marshal_one(st, a->data[i], flags + 1); marshal_one(st, a->data[i], flags + 1);
} }
goto done; goto done;
case JANET_TUPLE: case JANET_TUPLE: {
{
int32_t i, count, flag; int32_t i, count, flag;
const Janet *tup = janet_unwrap_tuple(x); const Janet *tup = janet_unwrap_tuple(x);
count = janet_tuple_length(tup); count = janet_tuple_length(tup);
@ -415,8 +417,7 @@ static void marshal_one(MarshalState *st, Janet x, int flags) {
MARK_SEEN(); MARK_SEEN();
} }
goto done; goto done;
case JANET_TABLE: case JANET_TABLE: {
{
JanetTable *t = janet_unwrap_table(x); JanetTable *t = janet_unwrap_table(x);
MARK_SEEN(); MARK_SEEN();
pushbyte(st, t->proto ? LB_TABLE_PROTO : LB_TABLE); pushbyte(st, t->proto ? LB_TABLE_PROTO : LB_TABLE);
@ -431,8 +432,7 @@ static void marshal_one(MarshalState *st, Janet x, int flags) {
} }
} }
goto done; goto done;
case JANET_STRUCT: case JANET_STRUCT: {
{
int32_t count; int32_t count;
const JanetKV *struct_ = janet_unwrap_struct(x); const JanetKV *struct_ = janet_unwrap_struct(x);
count = janet_struct_length(struct_); count = janet_struct_length(struct_);
@ -451,8 +451,7 @@ static void marshal_one(MarshalState *st, Janet x, int flags) {
case JANET_ABSTRACT: case JANET_ABSTRACT:
case JANET_CFUNCTION: case JANET_CFUNCTION:
goto noregval; goto noregval;
case JANET_FUNCTION: case JANET_FUNCTION: {
{
pushbyte(st, LB_FUNCTION); pushbyte(st, LB_FUNCTION);
JanetFunction *func = janet_unwrap_function(x); JanetFunction *func = janet_unwrap_function(x);
marshal_one_def(st, func->def, flags); marshal_one_def(st, func->def, flags);
@ -462,8 +461,7 @@ static void marshal_one(MarshalState *st, Janet x, int flags) {
marshal_one_env(st, func->envs[i], flags + 1); marshal_one_env(st, func->envs[i], flags + 1);
} }
goto done; goto done;
case JANET_FIBER: case JANET_FIBER: {
{
MARK_SEEN(); MARK_SEEN();
pushbyte(st, LB_FIBER); pushbyte(st, LB_FIBER);
marshal_one_fiber(st, janet_unwrap_fiber(x), flags + 1); marshal_one_fiber(st, janet_unwrap_fiber(x), flags + 1);
@ -972,8 +970,7 @@ static const uint8_t *unmarshal_one(
case LB_SYMBOL: case LB_SYMBOL:
case LB_BUFFER: case LB_BUFFER:
case LB_KEYWORD: case LB_KEYWORD:
case LB_REGISTRY: case LB_REGISTRY: {
{
data++; data++;
int32_t len = readint(st, &data); int32_t len = readint(st, &data);
EXTRA(len); EXTRA(len);
@ -1002,15 +999,13 @@ static const uint8_t *unmarshal_one(
janet_array_push(&st->lookup, *out); janet_array_push(&st->lookup, *out);
return data + len; return data + len;
} }
case LB_FIBER: case LB_FIBER: {
{
JanetFiber *fiber; JanetFiber *fiber;
data = unmarshal_one_fiber(st, data + 1, &fiber, flags); data = unmarshal_one_fiber(st, data + 1, &fiber, flags);
*out = janet_wrap_fiber(fiber); *out = janet_wrap_fiber(fiber);
return data; return data;
} }
case LB_FUNCTION: case LB_FUNCTION: {
{
JanetFunction *func; JanetFunction *func;
JanetFuncDef *def; JanetFuncDef *def;
data = unmarshal_one_def(st, data + 1, &def, flags + 1); data = unmarshal_one_def(st, data + 1, &def, flags + 1);

View File

@ -47,15 +47,15 @@
static Janet os_which(int32_t argc, Janet *argv) { static Janet os_which(int32_t argc, Janet *argv) {
janet_fixarity(argc, 0); janet_fixarity(argc, 0);
(void) argv; (void) argv;
#ifdef JANET_WINDOWS #ifdef JANET_WINDOWS
return janet_ckeywordv("windows"); return janet_ckeywordv("windows");
#elif __APPLE__ #elif __APPLE__
return janet_ckeywordv("macos"); return janet_ckeywordv("macos");
#elif defined(__EMSCRIPTEN__) #elif defined(__EMSCRIPTEN__)
return janet_ckeywordv("web"); return janet_ckeywordv("web");
#else #else
return janet_ckeywordv("posix"); return janet_ckeywordv("posix");
#endif #endif
} }
#ifdef JANET_WINDOWS #ifdef JANET_WINDOWS
@ -96,7 +96,7 @@ static Janet os_execute(int32_t argc, Janet *argv) {
ZeroMemory(&pi, sizeof(pi)); ZeroMemory(&pi, sizeof(pi));
// Start the child process. // Start the child process.
if(!CreateProcess(NULL, if (!CreateProcess(NULL,
(LPSTR) sys_str, (LPSTR) sys_str,
NULL, NULL,
NULL, NULL,
@ -212,7 +212,7 @@ static Janet os_time(int32_t argc, Janet *argv) {
#ifdef JANET_WINDOWS #ifdef JANET_WINDOWS
static int gettime(struct timespec *spec) { static int gettime(struct timespec *spec) {
int64_t wintime = 0LL; int64_t wintime = 0LL;
GetSystemTimeAsFileTime((FILETIME*)&wintime); GetSystemTimeAsFileTime((FILETIME *)&wintime);
/* Windows epoch is January 1, 1601 apparently*/ /* Windows epoch is January 1, 1601 apparently*/
wintime -= 116444736000000000LL; wintime -= 116444736000000000LL;
spec->tv_sec = wintime / 10000000LL; spec->tv_sec = wintime / 10000000LL;
@ -249,7 +249,7 @@ static Janet os_sleep(int32_t argc, Janet *argv) {
double delay = janet_getnumber(argv, 0); double delay = janet_getnumber(argv, 0);
if (delay < 0) janet_panic("invalid argument to sleep"); if (delay < 0) janet_panic("invalid argument to sleep");
#ifdef JANET_WINDOWS #ifdef JANET_WINDOWS
Sleep((DWORD) (delay * 1000)); Sleep((DWORD)(delay * 1000));
#else #else
struct timespec ts; struct timespec ts;
ts.tv_sec = (time_t) delay; ts.tv_sec = (time_t) delay;

View File

@ -191,17 +191,28 @@ static void popstate(JanetParser *p, Janet val) {
static int checkescape(uint8_t c) { static int checkescape(uint8_t c) {
switch (c) { switch (c) {
default: return -1; default:
case 'x': return 1; return -1;
case 'n': return '\n'; case 'x':
case 't': return '\t'; return 1;
case 'r': return '\r'; case 'n':
case '0': return '\0'; return '\n';
case 'z': return '\0'; case 't':
case 'f': return '\f'; return '\t';
case 'e': return 27; case 'r':
case '"': return '"'; return '\r';
case '\\': return '\\'; case '0':
return '\0';
case 'z':
return '\0';
case 'f':
return '\f';
case 'e':
return 27;
case '"':
return '"';
case '\\':
return '\\';
} }
} }
@ -475,8 +486,7 @@ static int root(JanetParser *p, JanetParseState *state, uint8_t c) {
return 1; return 1;
case ')': case ')':
case ']': case ']':
case '}': case '}': {
{
Janet ds; Janet ds;
if (p->statecount == 1) { if (p->statecount == 1) {
p->error = "unexpected delimiter"; p->error = "unexpected delimiter";

View File

@ -133,32 +133,28 @@ static const uint8_t *peg_rule(
const uint32_t *rule, const uint32_t *rule,
const uint8_t *text) { const uint8_t *text) {
tail: tail:
switch(*rule & 0x1F) { switch (*rule & 0x1F) {
default: default:
janet_panic("unexpected opcode"); janet_panic("unexpected opcode");
return NULL; return NULL;
case RULE_LITERAL: case RULE_LITERAL: {
{
uint32_t len = rule[1]; uint32_t len = rule[1];
if (text + len > s->text_end) return NULL; if (text + len > s->text_end) return NULL;
return memcmp(text, rule + 2, len) ? NULL : text + len; return memcmp(text, rule + 2, len) ? NULL : text + len;
} }
case RULE_NCHAR: case RULE_NCHAR: {
{
uint32_t n = rule[1]; uint32_t n = rule[1];
return (text + n > s->text_end) ? NULL : text + n; return (text + n > s->text_end) ? NULL : text + n;
} }
case RULE_NOTNCHAR: case RULE_NOTNCHAR: {
{
uint32_t n = rule[1]; uint32_t n = rule[1];
return (text + n > s->text_end) ? text : NULL; return (text + n > s->text_end) ? text : NULL;
} }
case RULE_RANGE: case RULE_RANGE: {
{
uint8_t lo = rule[1] & 0xFF; uint8_t lo = rule[1] & 0xFF;
uint8_t hi = (rule[1] >> 16) & 0xFF; uint8_t hi = (rule[1] >> 16) & 0xFF;
return (text < s->text_end && return (text < s->text_end &&
@ -168,8 +164,7 @@ tail:
: NULL; : NULL;
} }
case RULE_SET: case RULE_SET: {
{
uint32_t word = rule[1 + (text[0] >> 5)]; uint32_t word = rule[1 + (text[0] >> 5)];
uint32_t mask = (uint32_t)1 << (text[0] & 0x1F); uint32_t mask = (uint32_t)1 << (text[0] & 0x1F);
return (text < s->text_end && (word & mask)) return (text < s->text_end && (word & mask))
@ -177,8 +172,7 @@ tail:
: NULL; : NULL;
} }
case RULE_LOOK: case RULE_LOOK: {
{
text += ((int32_t *)rule)[1]; text += ((int32_t *)rule)[1];
if (text < s->text_start || text > s->text_end) return NULL; if (text < s->text_start || text > s->text_end) return NULL;
int oldmode = s->mode; int oldmode = s->mode;
@ -190,8 +184,7 @@ tail:
return result ? text : NULL; return result ? text : NULL;
} }
case RULE_CHOICE: case RULE_CHOICE: {
{
uint32_t len = rule[1]; uint32_t len = rule[1];
const uint32_t *args = rule + 2; const uint32_t *args = rule + 2;
if (len == 0) return NULL; if (len == 0) return NULL;
@ -210,8 +203,7 @@ tail:
goto tail; goto tail;
} }
case RULE_SEQUENCE: case RULE_SEQUENCE: {
{
uint32_t len = rule[1]; uint32_t len = rule[1];
const uint32_t *args = rule + 2; const uint32_t *args = rule + 2;
if (len == 0) return text; if (len == 0) return text;
@ -225,8 +217,7 @@ tail:
} }
case RULE_IF: case RULE_IF:
case RULE_IFNOT: case RULE_IFNOT: {
{
const uint32_t *rule_a = s->bytecode + rule[1]; const uint32_t *rule_a = s->bytecode + rule[1];
const uint32_t *rule_b = s->bytecode + rule[2]; const uint32_t *rule_b = s->bytecode + rule[2];
int oldmode = s->mode; int oldmode = s->mode;
@ -240,8 +231,7 @@ tail:
goto tail; goto tail;
} }
case RULE_NOT: case RULE_NOT: {
{
const uint32_t *rule_a = s->bytecode + rule[1]; const uint32_t *rule_a = s->bytecode + rule[1];
int oldmode = s->mode; int oldmode = s->mode;
s->mode = PEG_MODE_NOCAPTURE; s->mode = PEG_MODE_NOCAPTURE;
@ -252,8 +242,7 @@ tail:
return (result) ? NULL : text; return (result) ? NULL : text;
} }
case RULE_BETWEEN: case RULE_BETWEEN: {
{
uint32_t lo = rule[1]; uint32_t lo = rule[1];
uint32_t hi = rule[2]; uint32_t hi = rule[2];
const uint32_t *rule_a = s->bytecode + rule[3]; const uint32_t *rule_a = s->bytecode + rule[3];
@ -281,8 +270,7 @@ tail:
/* Capturing rules */ /* Capturing rules */
case RULE_GETTAG: case RULE_GETTAG: {
{
uint32_t search = rule[1]; uint32_t search = rule[1];
uint32_t tag = rule[2]; uint32_t tag = rule[2];
for (int32_t i = s->tags->count - 1; i >= 0; i--) { for (int32_t i = s->tags->count - 1; i >= 0; i--) {
@ -294,28 +282,24 @@ tail:
return NULL; return NULL;
} }
case RULE_POSITION: case RULE_POSITION: {
{
pushcap(s, janet_wrap_number((double)(text - s->text_start)), rule[1]); pushcap(s, janet_wrap_number((double)(text - s->text_start)), rule[1]);
return text; return text;
} }
case RULE_ARGUMENT: case RULE_ARGUMENT: {
{
int32_t index = ((int32_t *)rule)[1]; int32_t index = ((int32_t *)rule)[1];
Janet capture = (index >= s->extrac) ? janet_wrap_nil() : s->extrav[index]; Janet capture = (index >= s->extrac) ? janet_wrap_nil() : s->extrav[index];
pushcap(s, capture, rule[2]); pushcap(s, capture, rule[2]);
return text; return text;
} }
case RULE_CONSTANT: case RULE_CONSTANT: {
{
pushcap(s, s->constants[rule[1]], rule[2]); pushcap(s, s->constants[rule[1]], rule[2]);
return text; return text;
} }
case RULE_CAPTURE: case RULE_CAPTURE: {
{
uint32_t tag = rule[2]; uint32_t tag = rule[2];
if (!tag && s->mode == PEG_MODE_NOCAPTURE) { if (!tag && s->mode == PEG_MODE_NOCAPTURE) {
rule = s->bytecode + rule[1]; rule = s->bytecode + rule[1];
@ -334,8 +318,7 @@ tail:
return result; return result;
} }
case RULE_ACCUMULATE: case RULE_ACCUMULATE: {
{
uint32_t tag = rule[2]; uint32_t tag = rule[2];
int oldmode = s->mode; int oldmode = s->mode;
/* No capture mode, skip captures. Accumulate inside accumulate also does nothing. */ /* No capture mode, skip captures. Accumulate inside accumulate also does nothing. */
@ -356,8 +339,7 @@ tail:
return result; return result;
} }
case RULE_DROP: case RULE_DROP: {
{
CapState cs = cap_save(s); CapState cs = cap_save(s);
down1(s); down1(s);
const uint8_t *result = peg_rule(s, s->bytecode + rule[1], text); const uint8_t *result = peg_rule(s, s->bytecode + rule[1], text);
@ -367,8 +349,7 @@ tail:
return result; return result;
} }
case RULE_GROUP: case RULE_GROUP: {
{
uint32_t tag = rule[2]; uint32_t tag = rule[2];
int oldmode = s->mode; int oldmode = s->mode;
if (!tag && oldmode == PEG_MODE_NOCAPTURE) { if (!tag && oldmode == PEG_MODE_NOCAPTURE) {
@ -394,8 +375,7 @@ tail:
} }
case RULE_REPLACE: case RULE_REPLACE:
case RULE_MATCHTIME: case RULE_MATCHTIME: {
{
uint32_t tag = rule[3]; uint32_t tag = rule[3];
int oldmode = s->mode; int oldmode = s->mode;
if (!tag && rule[0] == RULE_REPLACE && oldmode == PEG_MODE_NOCAPTURE) { if (!tag && rule[0] == RULE_REPLACE && oldmode == PEG_MODE_NOCAPTURE) {
@ -440,8 +420,7 @@ tail:
return result; return result;
} }
case RULE_ERROR: case RULE_ERROR: {
{
int oldmode = s->mode; int oldmode = s->mode;
s->mode = PEG_MODE_NORMAL; s->mode = PEG_MODE_NORMAL;
int32_t old_cap = s->captures->count; int32_t old_cap = s->captures->count;
@ -921,8 +900,7 @@ static uint32_t peg_compile1(Builder *b, Janet peg) {
default: default:
peg_panicf(b, "unexpected peg source"); peg_panicf(b, "unexpected peg source");
return 0; return 0;
case JANET_NUMBER: case JANET_NUMBER: {
{
int32_t n = peg_getinteger(b, peg); int32_t n = peg_getinteger(b, peg);
Reserve r = reserve(b, 2); Reserve r = reserve(b, 2);
if (n < 0) { if (n < 0) {
@ -932,23 +910,20 @@ static uint32_t peg_compile1(Builder *b, Janet peg) {
} }
break; break;
} }
case JANET_STRING: case JANET_STRING: {
{
const uint8_t *str = janet_unwrap_string(peg); const uint8_t *str = janet_unwrap_string(peg);
int32_t len = janet_string_length(str); int32_t len = janet_string_length(str);
emit_bytes(b, RULE_LITERAL, len, str); emit_bytes(b, RULE_LITERAL, len, str);
break; break;
} }
case JANET_KEYWORD: case JANET_KEYWORD: {
{
Janet check = janet_table_get(b->grammar, peg); Janet check = janet_table_get(b->grammar, peg);
if (janet_checktype(check, JANET_NIL)) if (janet_checktype(check, JANET_NIL))
peg_panicf(b, "unknown rule"); peg_panicf(b, "unknown rule");
rule = peg_compile1(b, check); rule = peg_compile1(b, check);
break; break;
} }
case JANET_STRUCT: case JANET_STRUCT: {
{
JanetTable *grammar = janet_struct_to_table(janet_unwrap_struct(peg)); JanetTable *grammar = janet_struct_to_table(janet_unwrap_struct(peg));
grammar->proto = b->grammar; grammar->proto = b->grammar;
b->grammar = grammar; b->grammar = grammar;
@ -959,8 +934,7 @@ static uint32_t peg_compile1(Builder *b, Janet peg) {
b->grammar = grammar->proto; b->grammar = grammar->proto;
break; break;
} }
case JANET_TUPLE: case JANET_TUPLE: {
{
const Janet *tup = janet_unwrap_tuple(peg); const Janet *tup = janet_unwrap_tuple(peg);
int32_t len = janet_tuple_length(tup); int32_t len = janet_tuple_length(tup);
if (len == 0) peg_panic(b, "tuple in grammar must have non-zero length"); if (len == 0) peg_panic(b, "tuple in grammar must have non-zero length");
@ -969,7 +943,7 @@ static uint32_t peg_compile1(Builder *b, Janet peg) {
const uint8_t *sym = janet_unwrap_symbol(tup[0]); const uint8_t *sym = janet_unwrap_symbol(tup[0]);
const SpecialPair *sp = janet_strbinsearch( const SpecialPair *sp = janet_strbinsearch(
&peg_specials, &peg_specials,
sizeof(peg_specials)/sizeof(SpecialPair), sizeof(peg_specials) / sizeof(SpecialPair),
sizeof(SpecialPair), sizeof(SpecialPair),
sym); sym);
if (!sp) if (!sp)
@ -1089,12 +1063,14 @@ static Janet cfun_peg_match(int32_t argc, Janet *argv) {
} }
static const JanetReg peg_cfuns[] = { static const JanetReg peg_cfuns[] = {
{"peg/compile", cfun_peg_compile, {
"peg/compile", cfun_peg_compile,
JDOC("(peg/compile peg)\n\n" JDOC("(peg/compile peg)\n\n"
"Compiles a peg source data structure into a <core/peg>. This will speed up matching " "Compiles a peg source data structure into a <core/peg>. This will speed up matching "
"if the same peg will be used multiple times.") "if the same peg will be used multiple times.")
}, },
{"peg/match", cfun_peg_match, {
"peg/match", cfun_peg_match,
JDOC("(peg/match peg text [,start=0])\n\n" JDOC("(peg/match peg text [,start=0])\n\n"
"Match a Parsing Expression Grammar to a byte string and return an array of captured values. " "Match a Parsing Expression Grammar to a byte string and return an array of captured values. "
"Returns nil if text does not match the language defined by peg. The syntax of PEGs are very " "Returns nil if text does not match the language defined by peg. The syntax of PEGs are very "

View File

@ -73,7 +73,7 @@ static void integer_to_string_b(JanetBuffer *buffer, int32_t x) {
len = count_dig10(x); len = count_dig10(x);
buf += len; buf += len;
while (x) { while (x) {
uint8_t digit = (uint8_t) -(x % 10); uint8_t digit = (uint8_t) - (x % 10);
*(--buf) = '0' + digit; *(--buf) = '0' + digit;
x /= 10; x /= 10;
} }
@ -193,14 +193,12 @@ void janet_description_b(JanetBuffer *buffer, Janet x) {
case JANET_BUFFER: case JANET_BUFFER:
janet_escape_buffer_b(buffer, janet_unwrap_buffer(x)); janet_escape_buffer_b(buffer, janet_unwrap_buffer(x));
return; return;
case JANET_ABSTRACT: case JANET_ABSTRACT: {
{
const char *n = janet_abstract_type(janet_unwrap_abstract(x))->name; const char *n = janet_abstract_type(janet_unwrap_abstract(x))->name;
string_description_b(buffer, n, janet_unwrap_abstract(x)); string_description_b(buffer, n, janet_unwrap_abstract(x));
return; return;
} }
case JANET_CFUNCTION: case JANET_CFUNCTION: {
{
Janet check = janet_table_get(janet_vm_registry, x); Janet check = janet_table_get(janet_vm_registry, x);
if (janet_checktype(check, JANET_SYMBOL)) { if (janet_checktype(check, JANET_SYMBOL)) {
janet_buffer_push_cstring(buffer, "<cfunction "); janet_buffer_push_cstring(buffer, "<cfunction ");
@ -212,8 +210,7 @@ void janet_description_b(JanetBuffer *buffer, Janet x) {
} }
goto fallthrough; goto fallthrough;
} }
case JANET_FUNCTION: case JANET_FUNCTION: {
{
JanetFunction *fun = janet_unwrap_function(x); JanetFunction *fun = janet_unwrap_function(x);
JanetFuncDef *def = fun->def; JanetFuncDef *def = fun->def;
if (def->name) { if (def->name) {
@ -265,8 +262,7 @@ const uint8_t *janet_description(Janet x) {
* strings, symbols, and buffers will return their content. */ * strings, symbols, and buffers will return their content. */
const uint8_t *janet_to_string(Janet x) { const uint8_t *janet_to_string(Janet x) {
switch (janet_type(x)) { switch (janet_type(x)) {
default: default: {
{
JanetBuffer b; JanetBuffer b;
janet_buffer_init(&b, 10); janet_buffer_init(&b, 10);
janet_to_string_b(&b, x); janet_to_string_b(&b, x);
@ -313,8 +309,7 @@ static void janet_pretty_one(struct pretty *S, Janet x, int is_dict_value) {
case JANET_TRUE: case JANET_TRUE:
case JANET_FALSE: case JANET_FALSE:
break; break;
default: default: {
{
Janet seenid = janet_table_get(&S->seen, x); Janet seenid = janet_table_get(&S->seen, x);
if (janet_checktype(seenid, JANET_NUMBER)) { if (janet_checktype(seenid, JANET_NUMBER)) {
janet_buffer_push_cstring(S->buffer, "<cycle "); janet_buffer_push_cstring(S->buffer, "<cycle ");
@ -333,8 +328,7 @@ static void janet_pretty_one(struct pretty *S, Janet x, int is_dict_value) {
janet_description_b(S->buffer, x); janet_description_b(S->buffer, x);
break; break;
case JANET_ARRAY: case JANET_ARRAY:
case JANET_TUPLE: case JANET_TUPLE: {
{
int32_t i, len; int32_t i, len;
const Janet *arr; const Janet *arr;
int isarray = janet_checktype(x, JANET_ARRAY); int isarray = janet_checktype(x, JANET_ARRAY);
@ -362,8 +356,7 @@ static void janet_pretty_one(struct pretty *S, Janet x, int is_dict_value) {
break; break;
} }
case JANET_STRUCT: case JANET_STRUCT:
case JANET_TABLE: case JANET_TABLE: {
{
int istable = janet_checktype(x, JANET_TABLE); int istable = janet_checktype(x, JANET_TABLE);
janet_buffer_push_cstring(S->buffer, istable ? "@" : "{"); janet_buffer_push_cstring(S->buffer, istable ? "@" : "{");
@ -483,8 +476,7 @@ const uint8_t *janet_formatc(const char *format, ...) {
default: default:
janet_buffer_push_u8(bufp, c); janet_buffer_push_u8(bufp, c);
break; break;
case '%': case '%': {
{
if (i + 1 >= len) if (i + 1 >= len)
break; break;
switch (format[++i]) { switch (format[++i]) {
@ -497,8 +489,7 @@ const uint8_t *janet_formatc(const char *format, ...) {
case 'd': case 'd':
integer_to_string_b(bufp, va_arg(args, long)); integer_to_string_b(bufp, va_arg(args, long));
break; break;
case 'S': case 'S': {
{
const uint8_t *str = va_arg(args, const uint8_t *); const uint8_t *str = va_arg(args, const uint8_t *);
janet_buffer_push_bytes(bufp, str, janet_string_length(str)); janet_buffer_push_bytes(bufp, str, janet_string_length(str));
break; break;
@ -509,35 +500,29 @@ const uint8_t *janet_formatc(const char *format, ...) {
case 'c': case 'c':
janet_buffer_push_u8(bufp, (uint8_t) va_arg(args, long)); janet_buffer_push_u8(bufp, (uint8_t) va_arg(args, long));
break; break;
case 'q': case 'q': {
{
const uint8_t *str = va_arg(args, const uint8_t *); const uint8_t *str = va_arg(args, const uint8_t *);
janet_escape_string_b(bufp, str); janet_escape_string_b(bufp, str);
break; break;
} }
case 't': case 't': {
{
janet_buffer_push_cstring(bufp, typestr(va_arg(args, Janet))); janet_buffer_push_cstring(bufp, typestr(va_arg(args, Janet)));
break; break;
} }
case 'T': case 'T': {
{
int types = va_arg(args, long); int types = va_arg(args, long);
pushtypes(bufp, types); pushtypes(bufp, types);
break; break;
} }
case 'V': case 'V': {
{
janet_to_string_b(bufp, va_arg(args, Janet)); janet_to_string_b(bufp, va_arg(args, Janet));
break; break;
} }
case 'v': case 'v': {
{
janet_description_b(bufp, va_arg(args, Janet)); janet_description_b(bufp, va_arg(args, Janet));
break; break;
} }
case 'p': case 'p': {
{
janet_pretty(bufp, 4, va_arg(args, Janet)); janet_pretty(bufp, 4, va_arg(args, Janet));
} }
} }
@ -570,20 +555,20 @@ static const char *scanformat(
memset(precision, '\0', 3); memset(precision, '\0', 3);
while (*p != '\0' && strchr(FMT_FLAGS, *p) != NULL) while (*p != '\0' && strchr(FMT_FLAGS, *p) != NULL)
p++; /* skip flags */ p++; /* skip flags */
if ((size_t) (p - strfrmt) >= sizeof(FMT_FLAGS) / sizeof(char)) if ((size_t)(p - strfrmt) >= sizeof(FMT_FLAGS) / sizeof(char))
janet_panic("invalid format (repeated flags)"); janet_panic("invalid format (repeated flags)");
if (isdigit((int) (*p))) if (isdigit((int)(*p)))
width[0] = *p++; /* skip width */ width[0] = *p++; /* skip width */
if (isdigit((int) (*p))) if (isdigit((int)(*p)))
width[1] = *p++; /* (2 digits at most) */ width[1] = *p++; /* (2 digits at most) */
if (*p == '.') { if (*p == '.') {
p++; p++;
if (isdigit((int) (*p))) if (isdigit((int)(*p)))
precision[0] = *p++; /* skip precision */ precision[0] = *p++; /* skip precision */
if (isdigit((int) (*p))) if (isdigit((int)(*p)))
precision[1] = *p++; /* (2 digits at most) */ precision[1] = *p++; /* (2 digits at most) */
} }
if (isdigit((int) (*p))) if (isdigit((int)(*p)))
janet_panic("invalid format (width or precision too long)"); janet_panic("invalid format (width or precision too long)");
*(form++) = '%'; *(form++) = '%';
memcpy(form, strfrmt, ((p - strfrmt) + 1) * sizeof(char)); memcpy(form, strfrmt, ((p - strfrmt) + 1) * sizeof(char));
@ -616,8 +601,7 @@ void janet_buffer_format(
janet_panic("not enough values for format"); janet_panic("not enough values for format");
strfrmt = scanformat(strfrmt, form, width, precision); strfrmt = scanformat(strfrmt, form, width, precision);
switch (*strfrmt++) { switch (*strfrmt++) {
case 'c': case 'c': {
{
nb = snprintf(item, MAX_ITEM, form, (int) nb = snprintf(item, MAX_ITEM, form, (int)
janet_getinteger(argv, arg)); janet_getinteger(argv, arg));
break; break;
@ -627,8 +611,7 @@ void janet_buffer_format(
case 'o': case 'o':
case 'u': case 'u':
case 'x': case 'x':
case 'X': case 'X': {
{
int32_t n = janet_getinteger(argv, arg); int32_t n = janet_getinteger(argv, arg);
nb = snprintf(item, MAX_ITEM, form, n); nb = snprintf(item, MAX_ITEM, form, n);
break; break;
@ -639,14 +622,12 @@ void janet_buffer_format(
case 'E': case 'E':
case 'f': case 'f':
case 'g': case 'g':
case 'G': case 'G': {
{
double d = janet_getnumber(argv, arg); double d = janet_getnumber(argv, arg);
nb = snprintf(item, MAX_ITEM, form, d); nb = snprintf(item, MAX_ITEM, form, d);
break; break;
} }
case 's': case 's': {
{
const uint8_t *s = janet_getstring(argv, arg); const uint8_t *s = janet_getstring(argv, arg);
size_t l = janet_string_length(s); size_t l = janet_string_length(s);
if (form[2] == '\0') if (form[2] == '\0')
@ -663,26 +644,23 @@ void janet_buffer_format(
} }
break; break;
} }
case 'V': case 'V': {
{
janet_to_string_b(b, argv[arg]); janet_to_string_b(b, argv[arg]);
break; break;
} }
case 'v': case 'v': {
{
janet_description_b(b, argv[arg]); janet_description_b(b, argv[arg]);
break; break;
} }
case 'p': /* janet pretty , precision = depth */ case 'p': { /* janet pretty , precision = depth */
{
int depth = atoi(precision); int depth = atoi(precision);
if (depth < 1) if (depth < 1)
depth = 4; depth = 4;
janet_pretty(b, depth, argv[arg]); janet_pretty(b, depth, argv[arg]);
break; break;
} }
default: default: {
{ /* also treat cases 'nLlh' */ /* also treat cases 'nLlh' */
janet_panicf("invalid conversion '%s' to 'format'", janet_panicf("invalid conversion '%s' to 'format'",
form); form);
} }

View File

@ -60,8 +60,7 @@ static JanetSlot quasiquote(JanetFopts opts, Janet x) {
switch (janet_type(x)) { switch (janet_type(x)) {
default: default:
return janetc_cslot(x); return janetc_cslot(x);
case JANET_TUPLE: case JANET_TUPLE: {
{
int32_t i, len; int32_t i, len;
const Janet *tup = janet_unwrap_tuple(x); const Janet *tup = janet_unwrap_tuple(x);
len = janet_tuple_length(tup); len = janet_tuple_length(tup);
@ -74,8 +73,7 @@ static JanetSlot quasiquote(JanetFopts opts, Janet x) {
janet_v_push(slots, quasiquote(opts, tup[i])); janet_v_push(slots, quasiquote(opts, tup[i]));
return qq_slots(opts, slots, JOP_MAKE_TUPLE); return qq_slots(opts, slots, JOP_MAKE_TUPLE);
} }
case JANET_ARRAY: case JANET_ARRAY: {
{
int32_t i; int32_t i;
JanetArray *array = janet_unwrap_array(x); JanetArray *array = janet_unwrap_array(x);
for (i = 0; i < array->count; i++) for (i = 0; i < array->count; i++)
@ -83,8 +81,7 @@ static JanetSlot quasiquote(JanetFopts opts, Janet x) {
return qq_slots(opts, slots, JOP_MAKE_ARRAY); return qq_slots(opts, slots, JOP_MAKE_ARRAY);
} }
case JANET_TABLE: case JANET_TABLE:
case JANET_STRUCT: case JANET_STRUCT: {
{
const JanetKV *kv = NULL, *kvs = NULL; const JanetKV *kv = NULL, *kvs = NULL;
int32_t len, cap; int32_t len, cap;
janet_dictionary_view(x, &kvs, &len, &cap); janet_dictionary_view(x, &kvs, &len, &cap);
@ -136,8 +133,7 @@ static int destructure(JanetCompiler *c,
/* Leaf, assign right to left */ /* Leaf, assign right to left */
return leaf(c, janet_unwrap_symbol(left), right, attr); return leaf(c, janet_unwrap_symbol(left), right, attr);
case JANET_TUPLE: case JANET_TUPLE:
case JANET_ARRAY: case JANET_ARRAY: {
{
int32_t i, len; int32_t i, len;
const Janet *values; const Janet *values;
janet_indexed_view(left, &values, &len); janet_indexed_view(left, &values, &len);
@ -156,8 +152,7 @@ static int destructure(JanetCompiler *c,
} }
return 1; return 1;
case JANET_TABLE: case JANET_TABLE:
case JANET_STRUCT: case JANET_STRUCT: {
{
const JanetKV *kvs = NULL; const JanetKV *kvs = NULL;
int32_t i, cap, len; int32_t i, cap, len;
janet_dictionary_view(left, &kvs, &len, &cap); janet_dictionary_view(left, &kvs, &len, &cap);
@ -708,7 +703,7 @@ static const JanetSpecial janetc_specials[] = {
const JanetSpecial *janetc_special(const uint8_t *name) { const JanetSpecial *janetc_special(const uint8_t *name) {
return janet_strbinsearch( return janet_strbinsearch(
&janetc_specials, &janetc_specials,
sizeof(janetc_specials)/sizeof(JanetSpecial), sizeof(janetc_specials) / sizeof(JanetSpecial),
sizeof(JanetSpecial), sizeof(JanetSpecial),
name); name);
} }

View File

@ -32,7 +32,7 @@
/* Begin building a string */ /* Begin building a string */
uint8_t *janet_string_begin(int32_t length) { uint8_t *janet_string_begin(int32_t length) {
char *data = janet_gcalloc(JANET_MEMORY_STRING, 2 * sizeof(int32_t) + length + 1); char *data = janet_gcalloc(JANET_MEMORY_STRING, 2 * sizeof(int32_t) + length + 1);
uint8_t *str = (uint8_t *) (data + 2 * sizeof(int32_t)); uint8_t *str = (uint8_t *)(data + 2 * sizeof(int32_t));
janet_string_length(str) = length; janet_string_length(str) = length;
str[length] = 0; str[length] = 0;
return str; return str;
@ -48,7 +48,7 @@ const uint8_t *janet_string_end(uint8_t *str) {
const uint8_t *janet_string(const uint8_t *buf, int32_t len) { const uint8_t *janet_string(const uint8_t *buf, int32_t len) {
int32_t hash = janet_string_calchash(buf, len); int32_t hash = janet_string_calchash(buf, len);
char *data = janet_gcalloc(JANET_MEMORY_STRING, 2 * sizeof(int32_t) + len + 1); char *data = janet_gcalloc(JANET_MEMORY_STRING, 2 * sizeof(int32_t) + len + 1);
uint8_t *str = (uint8_t *) (data + 2 * sizeof(int32_t)); uint8_t *str = (uint8_t *)(data + 2 * sizeof(int32_t));
memcpy(str, buf, len); memcpy(str, buf, len);
str[len] = 0; str[len] = 0;
janet_string_length(str) = len; janet_string_length(str) = len;
@ -540,7 +540,8 @@ static const JanetReg string_cfuns[] = {
"Joins an array of strings into one string, optionally separated by " "Joins an array of strings into one string, optionally separated by "
"a separator string sep.") "a separator string sep.")
}, },
{ "string/format", cfun_string_format, {
"string/format", cfun_string_format,
JDOC("(string/format format & values)\n\n" JDOC("(string/format format & values)\n\n"
"Similar to snprintf, but specialized for operating with janet. Returns " "Similar to snprintf, but specialized for operating with janet. Returns "
"a new string.") "a new string.")

View File

@ -50,14 +50,14 @@
/* Lookup table for getting values of characters when parsing numbers. Handles /* Lookup table for getting values of characters when parsing numbers. Handles
* digits 0-9 and a-z (and A-Z). A-Z have values of 10 to 35. */ * digits 0-9 and a-z (and A-Z). A-Z have values of 10 to 35. */
static uint8_t digit_lookup[128] = { static uint8_t digit_lookup[128] = {
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0,1,2,3,4,5,6,7,8,9,0xff,0xff,0xff,0xff,0xff,0xff, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24, 0xff, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25,26,27,28,29,30,31,32,33,34,35,0xff,0xff,0xff,0xff,0xff, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24, 0xff, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25,26,27,28,29,30,31,32,33,34,35,0xff,0xff,0xff,0xff,0xff 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 0xff, 0xff, 0xff, 0xff, 0xff
}; };
#define BIGNAT_NBIT 31 #define BIGNAT_NBIT 31
@ -214,9 +214,9 @@ static double convert(
* Get exponent to zero while holding X constant. */ * Get exponent to zero while holding X constant. */
/* Positive exponents are simple */ /* Positive exponents are simple */
for (;exponent > 3; exponent -= 4) bignat_muladd(mant, base * base * base * base, 0); for (; exponent > 3; exponent -= 4) bignat_muladd(mant, base * base * base * base, 0);
for (;exponent > 1; exponent -= 2) bignat_muladd(mant, base * base, 0); for (; exponent > 1; exponent -= 2) bignat_muladd(mant, base * base, 0);
for (;exponent > 0; exponent -= 1) bignat_muladd(mant, base, 0); for (; exponent > 0; exponent -= 1) bignat_muladd(mant, base, 0);
/* Negative exponents are tricky - we don't want to loose bits /* Negative exponents are tricky - we don't want to loose bits
* from integer division, so we need to premultiply. */ * from integer division, so we need to premultiply. */
@ -224,9 +224,9 @@ static double convert(
int32_t shamt = 5 - exponent / 4; int32_t shamt = 5 - exponent / 4;
bignat_lshift_n(mant, shamt); bignat_lshift_n(mant, shamt);
exponent2 -= shamt * BIGNAT_NBIT; exponent2 -= shamt * BIGNAT_NBIT;
for (;exponent < -3; exponent += 4) bignat_div(mant, base * base * base * base); for (; exponent < -3; exponent += 4) bignat_div(mant, base * base * base * base);
for (;exponent < -1; exponent += 2) bignat_div(mant, base * base); for (; exponent < -1; exponent += 2) bignat_div(mant, base * base);
for (;exponent < 0; exponent += 1) bignat_div(mant, base); for (; exponent < 0; exponent += 1) bignat_div(mant, base);
} }
return negative return negative
@ -346,7 +346,8 @@ int janet_scan_number(
str++; str++;
seenadigit = 1; seenadigit = 1;
} }
if (eneg) ex -= ee; else ex += ee; if (eneg) ex -= ee;
else ex += ee;
} }
if (!seenadigit) if (!seenadigit)
@ -356,7 +357,7 @@ int janet_scan_number(
free(mant.digits); free(mant.digits);
return 0; return 0;
error: error:
free(mant.digits); free(mant.digits);
return 1; return 1;
} }

View File

@ -36,7 +36,7 @@ JanetKV *janet_struct_begin(int32_t count) {
size_t s = sizeof(int32_t) * 4 + (capacity * sizeof(JanetKV)); size_t s = sizeof(int32_t) * 4 + (capacity * sizeof(JanetKV));
char *data = janet_gcalloc(JANET_MEMORY_STRUCT, s); char *data = janet_gcalloc(JANET_MEMORY_STRUCT, s);
JanetKV *st = (JanetKV *) (data + 4 * sizeof(int32_t)); JanetKV *st = (JanetKV *)(data + 4 * sizeof(int32_t));
janet_memempty(st, capacity); janet_memempty(st, capacity);
janet_struct_length(st) = count; janet_struct_length(st) = count;
janet_struct_capacity(st) = capacity; janet_struct_capacity(st) = capacity;

View File

@ -82,7 +82,7 @@ static const uint8_t **janet_symcache_findmem(
bounds[2] = 0; bounds[2] = 0;
bounds[3] = index; bounds[3] = index;
for (j = 0; j < 4; j += 2) for (j = 0; j < 4; j += 2)
for (i = bounds[j]; i < bounds[j+1]; ++i) { for (i = bounds[j]; i < bounds[j + 1]; ++i) {
const uint8_t *test = janet_vm_cache[i]; const uint8_t *test = janet_vm_cache[i];
/* Check empty spots */ /* Check empty spots */
if (NULL == test) { if (NULL == test) {
@ -107,7 +107,7 @@ static const uint8_t **janet_symcache_findmem(
return janet_vm_cache + i; return janet_vm_cache + i;
} }
} }
notfound: notfound:
*success = 0; *success = 0;
return firstEmpty; return firstEmpty;
} }

View File

@ -93,10 +93,10 @@ int32_t janet_hash(Janet x) {
hash = (int32_t)(i & 0xFFFFFFFF); hash = (int32_t)(i & 0xFFFFFFFF);
/* Get a bit more entropy by shifting the low bits out */ /* Get a bit more entropy by shifting the low bits out */
hash >>= 3; hash >>= 3;
hash ^= (int32_t) (i >> 32); hash ^= (int32_t)(i >> 32);
} else { } else {
/* Assuming 4 byte pointer (or smaller) */ /* Assuming 4 byte pointer (or smaller) */
hash = (int32_t) ((char *)janet_unwrap_pointer(x) - (char *)0); hash = (int32_t)((char *)janet_unwrap_pointer(x) - (char *)0);
hash >>= 2; hash >>= 2;
} }
break; break;
@ -161,8 +161,7 @@ Janet janet_get(Janet ds, Janet key) {
case JANET_TABLE: case JANET_TABLE:
value = janet_table_get(janet_unwrap_table(ds), key); value = janet_table_get(janet_unwrap_table(ds), key);
break; break;
case JANET_ARRAY: case JANET_ARRAY: {
{
JanetArray *array = janet_unwrap_array(ds); JanetArray *array = janet_unwrap_array(ds);
int32_t index; int32_t index;
if (!janet_checkint(key)) if (!janet_checkint(key))
@ -175,8 +174,7 @@ Janet janet_get(Janet ds, Janet key) {
} }
break; break;
} }
case JANET_TUPLE: case JANET_TUPLE: {
{
const Janet *tuple = janet_unwrap_tuple(ds); const Janet *tuple = janet_unwrap_tuple(ds);
int32_t index; int32_t index;
if (!janet_checkint(key)) if (!janet_checkint(key))
@ -189,8 +187,7 @@ Janet janet_get(Janet ds, Janet key) {
} }
break; break;
} }
case JANET_BUFFER: case JANET_BUFFER: {
{
JanetBuffer *buffer = janet_unwrap_buffer(ds); JanetBuffer *buffer = janet_unwrap_buffer(ds);
int32_t index; int32_t index;
if (!janet_checkint(key)) if (!janet_checkint(key))
@ -205,8 +202,7 @@ Janet janet_get(Janet ds, Janet key) {
} }
case JANET_STRING: case JANET_STRING:
case JANET_SYMBOL: case JANET_SYMBOL:
case JANET_KEYWORD: case JANET_KEYWORD: {
{
const uint8_t *str = janet_unwrap_string(ds); const uint8_t *str = janet_unwrap_string(ds);
int32_t index; int32_t index;
if (!janet_checkint(key)) if (!janet_checkint(key))
@ -219,11 +215,10 @@ Janet janet_get(Janet ds, Janet key) {
} }
break; break;
} }
case JANET_ABSTRACT: case JANET_ABSTRACT: {
{
JanetAbstractType *type = (JanetAbstractType *)janet_abstract_type(janet_unwrap_abstract(ds)); JanetAbstractType *type = (JanetAbstractType *)janet_abstract_type(janet_unwrap_abstract(ds));
if (type->get) { if (type->get) {
value = (type->get)(janet_unwrap_abstract(ds),key); value = (type->get)(janet_unwrap_abstract(ds), key);
} else { } else {
janet_panicf("no getter for %T ", JANET_TFLAG_LENGTHABLE, ds); janet_panicf("no getter for %T ", JANET_TFLAG_LENGTHABLE, ds);
value = janet_wrap_nil(); value = janet_wrap_nil();
@ -278,11 +273,10 @@ Janet janet_getindex(Janet ds, int32_t index) {
case JANET_STRUCT: case JANET_STRUCT:
value = janet_struct_get(janet_unwrap_struct(ds), janet_wrap_integer(index)); value = janet_struct_get(janet_unwrap_struct(ds), janet_wrap_integer(index));
break; break;
case JANET_ABSTRACT: case JANET_ABSTRACT: {
{
JanetAbstractType *type = (JanetAbstractType *)janet_abstract_type(janet_unwrap_abstract(ds)); JanetAbstractType *type = (JanetAbstractType *)janet_abstract_type(janet_unwrap_abstract(ds));
if (type->get) { if (type->get) {
value = (type->get)(janet_unwrap_abstract(ds),janet_wrap_integer(index)); value = (type->get)(janet_unwrap_abstract(ds), janet_wrap_integer(index));
} else { } else {
janet_panicf("no getter for %T ", JANET_TFLAG_LENGTHABLE, ds); janet_panicf("no getter for %T ", JANET_TFLAG_LENGTHABLE, ds);
value = janet_wrap_nil(); value = janet_wrap_nil();
@ -321,8 +315,7 @@ void janet_putindex(Janet ds, int32_t index, Janet value) {
janet_panicf("expected %T, got %v", janet_panicf("expected %T, got %v",
JANET_TFLAG_ARRAY | JANET_TFLAG_BUFFER | JANET_TFLAG_TABLE, ds); JANET_TFLAG_ARRAY | JANET_TFLAG_BUFFER | JANET_TFLAG_TABLE, ds);
break; break;
case JANET_ARRAY: case JANET_ARRAY: {
{
JanetArray *array = janet_unwrap_array(ds); JanetArray *array = janet_unwrap_array(ds);
if (index >= array->count) { if (index >= array->count) {
janet_array_ensure(array, index + 1, 2); janet_array_ensure(array, index + 1, 2);
@ -331,8 +324,7 @@ void janet_putindex(Janet ds, int32_t index, Janet value) {
array->data[index] = value; array->data[index] = value;
break; break;
} }
case JANET_BUFFER: case JANET_BUFFER: {
{
JanetBuffer *buffer = janet_unwrap_buffer(ds); JanetBuffer *buffer = janet_unwrap_buffer(ds);
if (!janet_checkint(value)) if (!janet_checkint(value))
janet_panicf("can only put integers in buffers, got %v", value); janet_panicf("can only put integers in buffers, got %v", value);
@ -343,17 +335,15 @@ void janet_putindex(Janet ds, int32_t index, Janet value) {
buffer->data[index] = janet_unwrap_integer(value); buffer->data[index] = janet_unwrap_integer(value);
break; break;
} }
case JANET_TABLE: case JANET_TABLE: {
{
JanetTable *table = janet_unwrap_table(ds); JanetTable *table = janet_unwrap_table(ds);
janet_table_put(table, janet_wrap_integer(index), value); janet_table_put(table, janet_wrap_integer(index), value);
break; break;
} }
case JANET_ABSTRACT: case JANET_ABSTRACT: {
{
JanetAbstractType *type = (JanetAbstractType *)janet_abstract_type(janet_unwrap_abstract(ds)); JanetAbstractType *type = (JanetAbstractType *)janet_abstract_type(janet_unwrap_abstract(ds));
if (type->put) { if (type->put) {
(type->put)(janet_unwrap_abstract(ds),janet_wrap_integer(index),value); (type->put)(janet_unwrap_abstract(ds), janet_wrap_integer(index), value);
} else { } else {
janet_panicf("no setter for %T ", JANET_TFLAG_LENGTHABLE, ds); janet_panicf("no setter for %T ", JANET_TFLAG_LENGTHABLE, ds);
} }
@ -368,8 +358,7 @@ void janet_put(Janet ds, Janet key, Janet value) {
janet_panicf("expected %T, got %v", janet_panicf("expected %T, got %v",
JANET_TFLAG_ARRAY | JANET_TFLAG_BUFFER | JANET_TFLAG_TABLE, ds); JANET_TFLAG_ARRAY | JANET_TFLAG_BUFFER | JANET_TFLAG_TABLE, ds);
break; break;
case JANET_ARRAY: case JANET_ARRAY: {
{
int32_t index; int32_t index;
JanetArray *array = janet_unwrap_array(ds); JanetArray *array = janet_unwrap_array(ds);
if (!janet_checkint(key)) janet_panicf("expected integer key, got %v", key); if (!janet_checkint(key)) janet_panicf("expected integer key, got %v", key);
@ -381,8 +370,7 @@ void janet_put(Janet ds, Janet key, Janet value) {
array->data[index] = value; array->data[index] = value;
break; break;
} }
case JANET_BUFFER: case JANET_BUFFER: {
{
int32_t index; int32_t index;
JanetBuffer *buffer = janet_unwrap_buffer(ds); JanetBuffer *buffer = janet_unwrap_buffer(ds);
if (!janet_checkint(key)) janet_panicf("expected integer key, got %v", key); if (!janet_checkint(key)) janet_panicf("expected integer key, got %v", key);
@ -393,17 +381,16 @@ void janet_put(Janet ds, Janet key, Janet value) {
if (index >= buffer->count) { if (index >= buffer->count) {
janet_buffer_setcount(buffer, index + 1); janet_buffer_setcount(buffer, index + 1);
} }
buffer->data[index] = (uint8_t) (janet_unwrap_integer(value) & 0xFF); buffer->data[index] = (uint8_t)(janet_unwrap_integer(value) & 0xFF);
break; break;
} }
case JANET_TABLE: case JANET_TABLE:
janet_table_put(janet_unwrap_table(ds), key, value); janet_table_put(janet_unwrap_table(ds), key, value);
break; break;
case JANET_ABSTRACT: case JANET_ABSTRACT: {
{
JanetAbstractType *type = (JanetAbstractType *)janet_abstract_type(janet_unwrap_abstract(ds)); JanetAbstractType *type = (JanetAbstractType *)janet_abstract_type(janet_unwrap_abstract(ds));
if (type->put) { if (type->put) {
(type->put)(janet_unwrap_abstract(ds),key,value); (type->put)(janet_unwrap_abstract(ds), key, value);
} else { } else {
janet_panicf("no setter for %T ", JANET_TFLAG_LENGTHABLE, ds); janet_panicf("no setter for %T ", JANET_TFLAG_LENGTHABLE, ds);
} }

View File

@ -29,7 +29,7 @@ void *janet_v_grow(void *v, int32_t increment, int32_t itemsize) {
int32_t dbl_cur = (NULL != v) ? 2 * janet_v__cap(v) : 0; int32_t dbl_cur = (NULL != v) ? 2 * janet_v__cap(v) : 0;
int32_t min_needed = janet_v_count(v) + increment; int32_t min_needed = janet_v_count(v) + increment;
int32_t m = dbl_cur > min_needed ? dbl_cur : min_needed; int32_t m = dbl_cur > min_needed ? dbl_cur : min_needed;
int32_t *p = (int32_t *) realloc(v ? janet_v__raw(v) : 0, itemsize * m + sizeof(int32_t)*2); int32_t *p = (int32_t *) realloc(v ? janet_v__raw(v) : 0, itemsize * m + sizeof(int32_t) * 2);
if (NULL != p) { if (NULL != p) {
if (!v) p[1] = 0; if (!v) p[1] = 0;
p[0] = m; p[0] = m;
@ -38,7 +38,7 @@ void *janet_v_grow(void *v, int32_t increment, int32_t itemsize) {
{ {
JANET_OUT_OF_MEMORY; JANET_OUT_OF_MEMORY;
} }
return (void *) (2 * sizeof(int32_t)); return (void *)(2 * sizeof(int32_t));
} }
} }

View File

@ -283,8 +283,7 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
vm_assert_types(stack[A], E); vm_assert_types(stack[A], E);
vm_pcnext(); vm_pcnext();
VM_OP(JOP_RETURN) VM_OP(JOP_RETURN) {
{
Janet retval = stack[D]; Janet retval = stack[D];
int entrance_frame = janet_stack_frame(stack)->flags & JANET_STACKFRAME_ENTRANCE; int entrance_frame = janet_stack_frame(stack)->flags & JANET_STACKFRAME_ENTRANCE;
janet_fiber_popframe(fiber); janet_fiber_popframe(fiber);
@ -294,8 +293,7 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
vm_checkgc_pcnext(); vm_checkgc_pcnext();
} }
VM_OP(JOP_RETURN_NIL) VM_OP(JOP_RETURN_NIL) {
{
Janet retval = janet_wrap_nil(); Janet retval = janet_wrap_nil();
int entrance_frame = janet_stack_frame(stack)->flags & JANET_STACKFRAME_ENTRANCE; int entrance_frame = janet_stack_frame(stack)->flags & JANET_STACKFRAME_ENTRANCE;
janet_fiber_popframe(fiber); janet_fiber_popframe(fiber);
@ -321,37 +319,36 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
vm_binop(*); vm_binop(*);
VM_OP(JOP_NUMERIC_LESS_THAN) VM_OP(JOP_NUMERIC_LESS_THAN)
vm_numcomp(<); vm_numcomp( <);
VM_OP(JOP_NUMERIC_LESS_THAN_EQUAL) VM_OP(JOP_NUMERIC_LESS_THAN_EQUAL)
vm_numcomp(<=); vm_numcomp( <=);
VM_OP(JOP_NUMERIC_GREATER_THAN) VM_OP(JOP_NUMERIC_GREATER_THAN)
vm_numcomp(>); vm_numcomp( >);
VM_OP(JOP_NUMERIC_GREATER_THAN_EQUAL) VM_OP(JOP_NUMERIC_GREATER_THAN_EQUAL)
vm_numcomp(>=); vm_numcomp( >=);
VM_OP(JOP_NUMERIC_EQUAL) VM_OP(JOP_NUMERIC_EQUAL)
vm_numcomp(==); vm_numcomp( ==);
VM_OP(JOP_DIVIDE_IMMEDIATE) VM_OP(JOP_DIVIDE_IMMEDIATE)
vm_binop_immediate(/); vm_binop_immediate( /);
VM_OP(JOP_DIVIDE) VM_OP(JOP_DIVIDE)
vm_binop(/); vm_binop( /);
VM_OP(JOP_BAND) VM_OP(JOP_BAND)
vm_bitop(&); vm_bitop(&);
VM_OP(JOP_BOR) VM_OP(JOP_BOR)
vm_bitop(|); vm_bitop( |);
VM_OP(JOP_BXOR) VM_OP(JOP_BXOR)
vm_bitop(^); vm_bitop(^);
VM_OP(JOP_BNOT) VM_OP(JOP_BNOT) {
{
Janet op = stack[E]; Janet op = stack[E];
vm_assert_type(op, JANET_NUMBER); vm_assert_type(op, JANET_NUMBER);
stack[A] = janet_wrap_integer(~janet_unwrap_integer(op)); stack[A] = janet_wrap_integer(~janet_unwrap_integer(op));
@ -359,22 +356,22 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
} }
VM_OP(JOP_SHIFT_RIGHT_UNSIGNED) VM_OP(JOP_SHIFT_RIGHT_UNSIGNED)
vm_bitopu(>>); vm_bitopu( >>);
VM_OP(JOP_SHIFT_RIGHT_UNSIGNED_IMMEDIATE) VM_OP(JOP_SHIFT_RIGHT_UNSIGNED_IMMEDIATE)
vm_bitopu_immediate(>>); vm_bitopu_immediate( >>);
VM_OP(JOP_SHIFT_RIGHT) VM_OP(JOP_SHIFT_RIGHT)
vm_bitop(>>); vm_bitop( >>);
VM_OP(JOP_SHIFT_RIGHT_IMMEDIATE) VM_OP(JOP_SHIFT_RIGHT_IMMEDIATE)
vm_bitop_immediate(>>); vm_bitop_immediate( >>);
VM_OP(JOP_SHIFT_LEFT) VM_OP(JOP_SHIFT_LEFT)
vm_bitop(<<); vm_bitop( <<);
VM_OP(JOP_SHIFT_LEFT_IMMEDIATE) VM_OP(JOP_SHIFT_LEFT_IMMEDIATE)
vm_bitop_immediate(<<); vm_bitop_immediate( <<);
VM_OP(JOP_MOVE_NEAR) VM_OP(JOP_MOVE_NEAR)
stack[A] = stack[E]; stack[A] = stack[E];
@ -448,8 +445,7 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
stack[A] = janet_wrap_integer(ES); stack[A] = janet_wrap_integer(ES);
vm_pcnext(); vm_pcnext();
VM_OP(JOP_LOAD_CONSTANT) VM_OP(JOP_LOAD_CONSTANT) {
{
int32_t cindex = (int32_t)E; int32_t cindex = (int32_t)E;
vm_assert(cindex < func->def->constants_length, "invalid constant"); vm_assert(cindex < func->def->constants_length, "invalid constant");
stack[A] = func->def->constants[cindex]; stack[A] = func->def->constants[cindex];
@ -460,8 +456,7 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
stack[D] = janet_wrap_function(func); stack[D] = janet_wrap_function(func);
vm_pcnext(); vm_pcnext();
VM_OP(JOP_LOAD_UPVALUE) VM_OP(JOP_LOAD_UPVALUE) {
{
int32_t eindex = B; int32_t eindex = B;
int32_t vindex = C; int32_t vindex = C;
JanetFuncEnv *env; JanetFuncEnv *env;
@ -478,8 +473,7 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
vm_pcnext(); vm_pcnext();
} }
VM_OP(JOP_SET_UPVALUE) VM_OP(JOP_SET_UPVALUE) {
{
int32_t eindex = B; int32_t eindex = B;
int32_t vindex = C; int32_t vindex = C;
JanetFuncEnv *env; JanetFuncEnv *env;
@ -494,8 +488,7 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
vm_pcnext(); vm_pcnext();
} }
VM_OP(JOP_CLOSURE) VM_OP(JOP_CLOSURE) {
{
JanetFuncDef *fd; JanetFuncDef *fd;
JanetFunction *fn; JanetFunction *fn;
int32_t elen; int32_t elen;
@ -544,8 +537,7 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
stack = fiber->data + fiber->frame; stack = fiber->data + fiber->frame;
vm_checkgc_pcnext(); vm_checkgc_pcnext();
VM_OP(JOP_PUSH_ARRAY) VM_OP(JOP_PUSH_ARRAY) {
{
const Janet *vals; const Janet *vals;
int32_t len; int32_t len;
if (janet_indexed_view(stack[D], &vals, &len)) { if (janet_indexed_view(stack[D], &vals, &len)) {
@ -557,8 +549,7 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
stack = fiber->data + fiber->frame; stack = fiber->data + fiber->frame;
vm_checkgc_pcnext(); vm_checkgc_pcnext();
VM_OP(JOP_CALL) VM_OP(JOP_CALL) {
{
Janet callee = stack[E]; Janet callee = stack[E];
if (fiber->stacktop > fiber->maxstack) { if (fiber->stacktop > fiber->maxstack) {
vm_throw("stack overflow"); vm_throw("stack overflow");
@ -597,8 +588,7 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
} }
} }
VM_OP(JOP_TAILCALL) VM_OP(JOP_TAILCALL) {
{
Janet callee = stack[D]; Janet callee = stack[D];
if (janet_checktype(callee, JANET_KEYWORD)) { if (janet_checktype(callee, JANET_KEYWORD)) {
vm_commit(); vm_commit();
@ -638,8 +628,7 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
} }
} }
VM_OP(JOP_RESUME) VM_OP(JOP_RESUME) {
{
Janet retreg; Janet retreg;
vm_assert_type(stack[B], JANET_FIBER); vm_assert_type(stack[B], JANET_FIBER);
JanetFiber *child = janet_unwrap_fiber(stack[B]); JanetFiber *child = janet_unwrap_fiber(stack[B]);
@ -652,8 +641,7 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
vm_checkgc_pcnext(); vm_checkgc_pcnext();
} }
VM_OP(JOP_SIGNAL) VM_OP(JOP_SIGNAL) {
{
int32_t s = C; int32_t s = C;
if (s > JANET_SIGNAL_USER9) s = JANET_SIGNAL_USER9; if (s > JANET_SIGNAL_USER9) s = JANET_SIGNAL_USER9;
if (s < 0) s = 0; if (s < 0) s = 0;
@ -685,8 +673,7 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
stack[A] = janet_wrap_integer(janet_length(stack[E])); stack[A] = janet_wrap_integer(janet_length(stack[E]));
vm_pcnext(); vm_pcnext();
VM_OP(JOP_MAKE_ARRAY) VM_OP(JOP_MAKE_ARRAY) {
{
int32_t count = fiber->stacktop - fiber->stackstart; int32_t count = fiber->stacktop - fiber->stackstart;
Janet *mem = fiber->data + fiber->stackstart; Janet *mem = fiber->data + fiber->stackstart;
stack[D] = janet_wrap_array(janet_array_n(mem, count)); stack[D] = janet_wrap_array(janet_array_n(mem, count));
@ -694,8 +681,7 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
vm_checkgc_pcnext(); vm_checkgc_pcnext();
} }
VM_OP(JOP_MAKE_TUPLE) VM_OP(JOP_MAKE_TUPLE) {
{
int32_t count = fiber->stacktop - fiber->stackstart; int32_t count = fiber->stacktop - fiber->stackstart;
Janet *mem = fiber->data + fiber->stackstart; Janet *mem = fiber->data + fiber->stackstart;
stack[D] = janet_wrap_tuple(janet_tuple_n(mem, count)); stack[D] = janet_wrap_tuple(janet_tuple_n(mem, count));
@ -703,8 +689,7 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
vm_checkgc_pcnext(); vm_checkgc_pcnext();
} }
VM_OP(JOP_MAKE_TABLE) VM_OP(JOP_MAKE_TABLE) {
{
int32_t count = fiber->stacktop - fiber->stackstart; int32_t count = fiber->stacktop - fiber->stackstart;
Janet *mem = fiber->data + fiber->stackstart; Janet *mem = fiber->data + fiber->stackstart;
if (count & 1) if (count & 1)
@ -717,8 +702,7 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
vm_checkgc_pcnext(); vm_checkgc_pcnext();
} }
VM_OP(JOP_MAKE_STRUCT) VM_OP(JOP_MAKE_STRUCT) {
{
int32_t count = fiber->stacktop - fiber->stackstart; int32_t count = fiber->stacktop - fiber->stackstart;
Janet *mem = fiber->data + fiber->stackstart; Janet *mem = fiber->data + fiber->stackstart;
if (count & 1) if (count & 1)
@ -731,8 +715,7 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
vm_checkgc_pcnext(); vm_checkgc_pcnext();
} }
VM_OP(JOP_MAKE_STRING) VM_OP(JOP_MAKE_STRING) {
{
int32_t count = fiber->stacktop - fiber->stackstart; int32_t count = fiber->stacktop - fiber->stackstart;
Janet *mem = fiber->data + fiber->stackstart; Janet *mem = fiber->data + fiber->stackstart;
JanetBuffer buffer; JanetBuffer buffer;
@ -745,8 +728,7 @@ static JanetSignal run_vm(JanetFiber *fiber, Janet in, JanetFiberStatus status)
vm_checkgc_pcnext(); vm_checkgc_pcnext();
} }
VM_OP(JOP_MAKE_BUFFER) VM_OP(JOP_MAKE_BUFFER) {
{
int32_t count = fiber->stacktop - fiber->stackstart; int32_t count = fiber->stacktop - fiber->stackstart;
Janet *mem = fiber->data + fiber->stackstart; Janet *mem = fiber->data + fiber->stackstart;
JanetBuffer *buffer = janet_buffer(10 * count); JanetBuffer *buffer = janet_buffer(10 * count);

View File

@ -277,7 +277,7 @@ typedef struct JanetView JanetView;
typedef struct JanetByteView JanetByteView; typedef struct JanetByteView JanetByteView;
typedef struct JanetDictView JanetDictView; typedef struct JanetDictView JanetDictView;
typedef struct JanetRange JanetRange; typedef struct JanetRange JanetRange;
typedef Janet (*JanetCFunction)(int32_t argc, Janet *argv); typedef Janet(*JanetCFunction)(int32_t argc, Janet *argv);
/* Basic types for all Janet Values */ /* Basic types for all Janet Values */
typedef enum JanetType { typedef enum JanetType {
@ -724,7 +724,7 @@ enum JanetParserStatus {
/* A janet parser */ /* A janet parser */
struct JanetParser { struct JanetParser {
Janet* args; Janet *args;
const char *error; const char *error;
JanetParseState *states; JanetParseState *states;
uint8_t *buf; uint8_t *buf;
@ -744,7 +744,7 @@ struct JanetAbstractType {
const char *name; const char *name;
int (*gc)(void *data, size_t len); int (*gc)(void *data, size_t len);
int (*gcmark)(void *data, size_t len); int (*gcmark)(void *data, size_t len);
Janet (*get)(void *data, Janet key); Janet(*get)(void *data, Janet key);
void (*put)(void *data, Janet key, Janet value); void (*put)(void *data, Janet key, Janet value);
}; };

View File

@ -144,8 +144,8 @@ static int curpos() {
int cols, rows; int cols, rows;
unsigned int i = 0; unsigned int i = 0;
if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4) return -1; if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4) return -1;
while (i < sizeof(buf)-1) { while (i < sizeof(buf) - 1) {
if (read(STDIN_FILENO, buf+i, 1) != 1) break; if (read(STDIN_FILENO, buf + i, 1) != 1) break;
if (buf[i] == 'R') break; if (buf[i] == 'R') break;
i++; i++;
} }
@ -166,7 +166,7 @@ static int getcols() {
if (cols == -1) goto failed; if (cols == -1) goto failed;
if (cols > start) { if (cols > start) {
char seq[32]; char seq[32];
snprintf(seq, 32, "\x1b[%dD", cols-start); snprintf(seq, 32, "\x1b[%dD", cols - start);
if (write(STDOUT_FILENO, seq, strlen(seq)) == -1) {} if (write(STDOUT_FILENO, seq, strlen(seq)) == -1) {}
} }
return cols; return cols;
@ -178,7 +178,7 @@ failed:
} }
static void clear() { static void clear() {
if (write(STDOUT_FILENO,"\x1b[H\x1b[2J",7) <= 0) {} if (write(STDOUT_FILENO, "\x1b[H\x1b[2J", 7) <= 0) {}
} }
static void refresh() { static void refresh() {
@ -206,7 +206,7 @@ static void refresh() {
/* Erase to right */ /* Erase to right */
janet_buffer_push_cstring(&b, "\x1b[0K"); janet_buffer_push_cstring(&b, "\x1b[0K");
/* Move cursor to original position. */ /* Move cursor to original position. */
snprintf(seq, 64,"\r\x1b[%dC", (int)(_pos + plen)); snprintf(seq, 64, "\r\x1b[%dC", (int)(_pos + plen));
janet_buffer_push_cstring(&b, seq); janet_buffer_push_cstring(&b, seq);
if (write(STDOUT_FILENO, b.data, b.count) == -1) {} if (write(STDOUT_FILENO, b.data, b.count) == -1) {}
janet_buffer_deinit(&b); janet_buffer_deinit(&b);
@ -321,7 +321,7 @@ static int line() {
nread = read(STDIN_FILENO, &c, 1); nread = read(STDIN_FILENO, &c, 1);
if (nread <= 0) return -1; if (nread <= 0) return -1;
switch(c) { switch (c) {
default: default:
if (insert(c)) return -1; if (insert(c)) return -1;
break; break;
@ -372,7 +372,7 @@ static int line() {
/* Extended escape, read additional byte. */ /* Extended escape, read additional byte. */
if (read(STDIN_FILENO, seq + 2, 1) == -1) break; if (read(STDIN_FILENO, seq + 2, 1) == -1) break;
if (seq[2] == '~') { if (seq[2] == '~') {
switch(seq[1]) { switch (seq[1]) {
default: default:
break; break;
} }