From: Dale Weiler Date: Sun, 3 Jan 2016 03:30:35 +0000 (-0500) Subject: Merge branch 'master' into cleanup X-Git-Tag: xonotic-v0.8.2~6 X-Git-Url: https://git.rm.cloudns.org/?a=commitdiff_plain;h=1a18ff529420930cb4116484991c2dabe3a70654;p=xonotic%2Fgmqcc.git Merge branch 'master' into cleanup --- 1a18ff529420930cb4116484991c2dabe3a70654 diff --cc exec.cpp index bfb090c,0000000..e76004e mode 100644,000000..100644 --- a/exec.cpp +++ b/exec.cpp @@@ -1,1622 -1,0 +1,1622 @@@ +#ifndef QCVM_LOOP +#include +#include +#include +#include + +#include "gmqcc.h" + +static void loaderror(const char *fmt, ...) +{ + int err = errno; + va_list ap; + va_start(ap, fmt); + vprintf(fmt, ap); + va_end(ap); + printf(": %s\n", util_strerror(err)); +} + +static void qcvmerror(qc_program_t *prog, const char *fmt, ...) +{ + va_list ap; + + prog->vmerror++; + + va_start(ap, fmt); + vprintf(fmt, ap); + va_end(ap); + putchar('\n'); +} + +qc_program_t* prog_load(const char *filename, bool skipversion) +{ + prog_header_t header; + qc_program_t *prog; + FILE *file = fopen(filename, "rb"); + + /* we need all those in order to support INSTR_STATE: */ + bool has_self = false, + has_time = false, + has_think = false, + has_nextthink = false, + has_frame = false; + + if (!file) + return nullptr; + + if (fread(&header, sizeof(header), 1, file) != 1) { + loaderror("failed to read header from '%s'", filename); + fclose(file); + return nullptr; + } + + util_swap_header(header); + + if (!skipversion && header.version != 6) { + loaderror("header says this is a version %i progs, we need version 6\n", header.version); + fclose(file); + return nullptr; + } + + prog = (qc_program_t*)mem_a(sizeof(qc_program_t)); + if (!prog) { + fclose(file); + fprintf(stderr, "failed to allocate program data\n"); + return nullptr; + } + memset(prog, 0, sizeof(*prog)); + + prog->entityfields = header.entfield; + prog->crc16 = header.crc16; + + prog->filename = util_strdup(filename); + if (!prog->filename) { + loaderror("failed to store program name"); + goto error; + } + +#define read_data(hdrvar, progvar, reserved) \ + if (fseek(file, header.hdrvar.offset, SEEK_SET) != 0) { \ + loaderror("seek failed"); \ + goto error; \ + } \ + prog->progvar.resize(header.hdrvar.length + reserved); \ + if (fread( \ + &prog->progvar[0], \ + sizeof(prog->progvar[0]), \ + header.hdrvar.length, \ + file \ + )!= header.hdrvar.length \ + ) { \ + loaderror("read failed"); \ + goto error; \ + } +#define read_data1(x) read_data(x, x, 0) +#define read_data2(x, y) read_data(x, x, y) + + read_data (statements, code, 0); + read_data1(defs); + read_data1(fields); + read_data1(functions); + read_data1(strings); + read_data2(globals, 2); /* reserve more in case a RETURN using with the global at "the end" exists */ + + util_swap_statements(prog->code); + util_swap_defs_fields(prog->defs); + util_swap_defs_fields(prog->fields); + util_swap_functions(prog->functions); + util_swap_globals(prog->globals); + + fclose(file); + + /* profile counters */ + memset(vec_add(prog->profile, prog->code.size()), 0, sizeof(prog->profile[0]) * prog->code.size()); + + /* Add tempstring area */ + prog->tempstring_start = prog->strings.size(); + prog->tempstring_at = prog->strings.size(); + + prog->strings.resize(prog->strings.size() + 16*1024, '\0'); + + /* spawn the world entity */ + vec_push(prog->entitypool, true); + memset(vec_add(prog->entitydata, prog->entityfields), 0, prog->entityfields * sizeof(prog->entitydata[0])); + prog->entities = 1; + + /* cache some globals and fields from names */ + for (auto &it : prog->defs) { + const char *name = prog_getstring(prog, it.name); + if (!strcmp(name, "self")) { + prog->cached_globals.self = it.offset; + has_self = true; + } + else if (!strcmp(name, "time")) { + prog->cached_globals.time = it.offset; + has_time = true; + } + } + for (auto &it : prog->fields) { + const char *name = prog_getstring(prog, it.name); + if (!strcmp(name, "think")) { + prog->cached_fields.think = it.offset; + has_think = true; + } + else if (!strcmp(name, "nextthink")) { + prog->cached_fields.nextthink = it.offset; + has_nextthink = true; + } + else if (!strcmp(name, "frame")) { + prog->cached_fields.frame = it.offset; + has_frame = true; + } + } + if (has_self && has_time && has_think && has_nextthink && has_frame) + prog->supports_state = true; + + return prog; + +error: + if (prog->filename) + mem_d(prog->filename); + vec_free(prog->entitydata); + vec_free(prog->entitypool); + mem_d(prog); + + fclose(file); + return nullptr; +} + +void prog_delete(qc_program_t *prog) +{ + if (prog->filename) mem_d(prog->filename); + vec_free(prog->entitydata); + vec_free(prog->entitypool); + vec_free(prog->localstack); + vec_free(prog->stack); + vec_free(prog->profile); + mem_d(prog); +} + +/*********************************************************************** + * VM code + */ + +const char* prog_getstring(qc_program_t *prog, qcint_t str) { + /* cast for return required for C++ */ + if (str < 0 || str >= (qcint_t)prog->strings.size()) + return "<<>>"; + + return &prog->strings[0] + str; +} + +prog_section_def_t* prog_entfield(qc_program_t *prog, qcint_t off) { + for (auto &it : prog->fields) + if (it.offset == off) + return ⁢ + return nullptr; +} + +prog_section_def_t* prog_getdef(qc_program_t *prog, qcint_t off) +{ + for (auto &it : prog->defs) + if (it.offset == off) + return ⁢ + return nullptr; +} + +qcany_t* prog_getedict(qc_program_t *prog, qcint_t e) { + if (e >= (qcint_t)vec_size(prog->entitypool)) { + prog->vmerror++; + fprintf(stderr, "Accessing out of bounds edict %i\n", (int)e); + e = 0; + } + return (qcany_t*)(prog->entitydata + (prog->entityfields * e)); +} + +static qcint_t prog_spawn_entity(qc_program_t *prog) { + char *data; + qcint_t e; + for (e = 0; e < (qcint_t)vec_size(prog->entitypool); ++e) { + if (!prog->entitypool[e]) { + data = (char*)(prog->entitydata + (prog->entityfields * e)); + memset(data, 0, prog->entityfields * sizeof(qcint_t)); + return e; + } + } + vec_push(prog->entitypool, true); + prog->entities++; + data = (char*)vec_add(prog->entitydata, prog->entityfields); + memset(data, 0, prog->entityfields * sizeof(qcint_t)); + return e; +} + +static void prog_free_entity(qc_program_t *prog, qcint_t e) { + if (!e) { + prog->vmerror++; + fprintf(stderr, "Trying to free world entity\n"); + return; + } + if (e >= (qcint_t)vec_size(prog->entitypool)) { + prog->vmerror++; + fprintf(stderr, "Trying to free out of bounds entity\n"); + return; + } + if (!prog->entitypool[e]) { + prog->vmerror++; + fprintf(stderr, "Double free on entity\n"); + return; + } + prog->entitypool[e] = false; +} + +qcint_t prog_tempstring(qc_program_t *prog, const char *str) { + size_t len = strlen(str); + size_t at = prog->tempstring_at; + + /* when we reach the end we start over */ + if (at + len >= prog->strings.size()) + at = prog->tempstring_start; + + /* when it doesn't fit, reallocate */ + if (at + len >= prog->strings.size()) + { + prog->strings.resize(prog->strings.size() + len+1); + memcpy(&prog->strings[0] + at, str, len+1); + return at; + } + + /* when it fits, just copy */ + memcpy(&prog->strings[0] + at, str, len+1); + prog->tempstring_at += len+1; + return at; +} + +static size_t print_escaped_string(const char *str, size_t maxlen) { + size_t len = 2; + putchar('"'); + --maxlen; /* because we're lazy and have escape sequences */ + while (*str) { + if (len >= maxlen) { + putchar('.'); + putchar('.'); + putchar('.'); + len += 3; + break; + } + switch (*str) { + case '\a': len += 2; putchar('\\'); putchar('a'); break; + case '\b': len += 2; putchar('\\'); putchar('b'); break; + case '\r': len += 2; putchar('\\'); putchar('r'); break; + case '\n': len += 2; putchar('\\'); putchar('n'); break; + case '\t': len += 2; putchar('\\'); putchar('t'); break; + case '\f': len += 2; putchar('\\'); putchar('f'); break; + case '\v': len += 2; putchar('\\'); putchar('v'); break; + case '\\': len += 2; putchar('\\'); putchar('\\'); break; + case '"': len += 2; putchar('\\'); putchar('"'); break; + default: + ++len; + putchar(*str); + break; + } + ++str; + } + putchar('"'); + return len; +} + +static void trace_print_global(qc_program_t *prog, unsigned int glob, int vtype) { + static char spaces[28+1] = " "; + prog_section_def_t *def; + qcany_t *value; + int len; + + if (!glob) { + if ((len = printf(",")) == -1) + len = 0; + + goto done; + } + + def = prog_getdef(prog, glob); + value = (qcany_t*)(&prog->globals[glob]); + + len = printf("[@%u] ", glob); + if (def) { + const char *name = prog_getstring(prog, def->name); + if (name[0] == '#') + len += printf("$"); + else + len += printf("%s ", name); + vtype = def->type & DEF_TYPEMASK; + } + + switch (vtype) { + case TYPE_VOID: + case TYPE_ENTITY: + case TYPE_FIELD: + case TYPE_FUNCTION: + case TYPE_POINTER: + len += printf("(%i),", value->_int); + break; + case TYPE_VECTOR: + len += printf("'%g %g %g',", value->vector[0], + value->vector[1], + value->vector[2]); + break; + case TYPE_STRING: + if (value->string) + len += print_escaped_string(prog_getstring(prog, value->string), sizeof(spaces)-len-5); + else + len += printf("(null)"); + len += printf(","); + /* len += printf("\"%s\",", prog_getstring(prog, value->string)); */ + break; + case TYPE_FLOAT: + default: + len += printf("%g,", value->_float); + break; + } +done: + if (len < (int)sizeof(spaces)-1) { + spaces[sizeof(spaces)-1-len] = 0; + fputs(spaces, stdout); + spaces[sizeof(spaces)-1-len] = ' '; + } +} + +static void prog_print_statement(qc_program_t *prog, prog_section_statement_t *st) { + if (st->opcode >= VINSTR_END) { + printf("\n", st->opcode); + return; + } + if ((prog->xflags & VMXF_TRACE) && vec_size(prog->function_stack)) { + size_t i; + for (i = 0; i < vec_size(prog->function_stack); ++i) + printf("->"); + printf("%s:", vec_last(prog->function_stack)); + } + printf(" <> %-12s", util_instr_str[st->opcode]); + if (st->opcode >= INSTR_IF && + st->opcode <= INSTR_IFNOT) + { + trace_print_global(prog, st->o1.u1, TYPE_FLOAT); + printf("%d\n", st->o2.s1); + } + else if (st->opcode >= INSTR_CALL0 && + st->opcode <= INSTR_CALL8) + { + trace_print_global(prog, st->o1.u1, TYPE_FUNCTION); + printf("\n"); + } + else if (st->opcode == INSTR_GOTO) + { + printf("%i\n", st->o1.s1); + } + else + { + int t[3] = { TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT }; + switch (st->opcode) + { + case INSTR_MUL_FV: + t[1] = t[2] = TYPE_VECTOR; + break; + case INSTR_MUL_VF: + t[0] = t[2] = TYPE_VECTOR; + break; + case INSTR_MUL_V: + t[0] = t[1] = TYPE_VECTOR; + break; + case INSTR_ADD_V: + case INSTR_SUB_V: + case INSTR_EQ_V: + case INSTR_NE_V: + t[0] = t[1] = t[2] = TYPE_VECTOR; + break; + case INSTR_EQ_S: + case INSTR_NE_S: + t[0] = t[1] = TYPE_STRING; + break; + case INSTR_STORE_F: + case INSTR_STOREP_F: + t[2] = -1; + break; + case INSTR_STORE_V: + t[0] = t[1] = TYPE_VECTOR; t[2] = -1; + break; + case INSTR_STORE_S: + t[0] = t[1] = TYPE_STRING; t[2] = -1; + break; + case INSTR_STORE_ENT: + t[0] = t[1] = TYPE_ENTITY; t[2] = -1; + break; + case INSTR_STORE_FLD: + t[0] = t[1] = TYPE_FIELD; t[2] = -1; + break; + case INSTR_STORE_FNC: + t[0] = t[1] = TYPE_FUNCTION; t[2] = -1; + break; + case INSTR_STOREP_V: + t[0] = TYPE_VECTOR; t[1] = TYPE_ENTITY; t[2] = -1; + break; + case INSTR_STOREP_S: + t[0] = TYPE_STRING; t[1] = TYPE_ENTITY; t[2] = -1; + break; + case INSTR_STOREP_ENT: + t[0] = TYPE_ENTITY; t[1] = TYPE_ENTITY; t[2] = -1; + break; + case INSTR_STOREP_FLD: + t[0] = TYPE_FIELD; t[1] = TYPE_ENTITY; t[2] = -1; + break; + case INSTR_STOREP_FNC: + t[0] = TYPE_FUNCTION; t[1] = TYPE_ENTITY; t[2] = -1; + break; + } + if (t[0] >= 0) trace_print_global(prog, st->o1.u1, t[0]); + else printf("(none), "); + if (t[1] >= 0) trace_print_global(prog, st->o2.u1, t[1]); + else printf("(none), "); + if (t[2] >= 0) trace_print_global(prog, st->o3.u1, t[2]); + else printf("(none)"); + printf("\n"); + } +} + +static qcint_t prog_enterfunction(qc_program_t *prog, prog_section_function_t *func) { + qc_exec_stack_t st; + size_t parampos; + int32_t p; + + /* back up locals */ + st.localsp = vec_size(prog->localstack); + st.stmt = prog->statement; + st.function = func; + + if (prog->xflags & VMXF_TRACE) { + const char *str = prog_getstring(prog, func->name); + vec_push(prog->function_stack, str); + } + +#ifdef QCVM_BACKUP_STRATEGY_CALLER_VARS + if (vec_size(prog->stack)) + { + prog_section_function_t *cur; + cur = prog->stack[vec_size(prog->stack)-1].function; + if (cur) + { + qcint_t *globals = &prog->globals[0] + cur->firstlocal; + vec_append(prog->localstack, cur->locals, globals); + } + } +#else + { + qcint_t *globals = &prog->globals[0] + func->firstlocal; + vec_append(prog->localstack, func->locals, globals); + } +#endif + + /* copy parameters */ + parampos = func->firstlocal; + for (p = 0; p < func->nargs; ++p) + { + size_t s; + for (s = 0; s < func->argsize[p]; ++s) { + prog->globals[parampos] = prog->globals[OFS_PARM0 + 3*p + s]; + ++parampos; + } + } + + vec_push(prog->stack, st); + + return func->entry; +} + +static qcint_t prog_leavefunction(qc_program_t *prog) { + prog_section_function_t *prev = nullptr; + size_t oldsp; + + qc_exec_stack_t st = vec_last(prog->stack); + + if (prog->xflags & VMXF_TRACE) { + if (vec_size(prog->function_stack)) + vec_pop(prog->function_stack); + } + +#ifdef QCVM_BACKUP_STRATEGY_CALLER_VARS + if (vec_size(prog->stack) > 1) { + prev = prog->stack[vec_size(prog->stack)-2].function; + oldsp = prog->stack[vec_size(prog->stack)-2].localsp; + } +#else + prev = prog->stack[vec_size(prog->stack)-1].function; + oldsp = prog->stack[vec_size(prog->stack)-1].localsp; +#endif + if (prev) { + qcint_t *globals = &prog->globals[0] + prev->firstlocal; + memcpy(globals, prog->localstack + oldsp, prev->locals * sizeof(prog->localstack[0])); + /* vec_remove(prog->localstack, oldsp, vec_size(prog->localstack)-oldsp); */ + vec_shrinkto(prog->localstack, oldsp); + } + + vec_pop(prog->stack); + + return st.stmt - 1; /* offset the ++st */ +} + +bool prog_exec(qc_program_t *prog, prog_section_function_t *func, size_t flags, long maxjumps) { + long jumpcount = 0; + size_t oldxflags = prog->xflags; + prog_section_statement_t *st; + + prog->vmerror = 0; + prog->xflags = flags; + + st = &prog->code[0] + prog_enterfunction(prog, func); + --st; + switch (flags) + { + default: + case 0: + { +#define QCVM_LOOP 1 +#define QCVM_PROFILE 0 +#define QCVM_TRACE 0 +# include __FILE__ + } + case (VMXF_TRACE): + { +#define QCVM_PROFILE 0 +#define QCVM_TRACE 1 +# include __FILE__ + } + case (VMXF_PROFILE): + { +#define QCVM_PROFILE 1 +#define QCVM_TRACE 0 +# include __FILE__ + } + case (VMXF_TRACE|VMXF_PROFILE): + { +#define QCVM_PROFILE 1 +#define QCVM_TRACE 1 +# include __FILE__ + } + }; + +cleanup: + prog->xflags = oldxflags; + vec_free(prog->localstack); + vec_free(prog->stack); + if (prog->vmerror) + return false; + return true; +} + +/*********************************************************************** + * main for when building the standalone executor + */ + +#include + +const char *type_name[TYPE_COUNT] = { + "void", + "string", + "float", + "vector", + "entity", + "field", + "function", + "pointer", + "integer", + + "variant", + + "struct", + "union", + "array", + + "nil", + "noexpr" +}; + +struct qcvm_parameter { + int vtype; + const char *value; +}; + +static qcvm_parameter *main_params = nullptr; + +#define CheckArgs(num) do { \ + if (prog->argc != (num)) { \ + prog->vmerror++; \ + fprintf(stderr, "ERROR: invalid number of arguments for %s: %i, expected %i\n", \ - __FUNCTION__, prog->argc, (num)); \ ++ __func__, prog->argc, (num)); \ + return -1; \ + } \ +} while (0) + +#define GetGlobal(idx) ((qcany_t*)(&prog->globals[0] + (idx))) +#define GetArg(num) GetGlobal(OFS_PARM0 + 3*(num)) +#define Return(any) *(GetGlobal(OFS_RETURN)) = (any) + +static int qc_print(qc_program_t *prog) { + size_t i; + const char *laststr = nullptr; + for (i = 0; i < (size_t)prog->argc; ++i) { + qcany_t *str = (qcany_t*)(&prog->globals[0] + OFS_PARM0 + 3*i); + laststr = prog_getstring(prog, str->string); + printf("%s", laststr); + } + if (laststr && (prog->xflags & VMXF_TRACE)) { + size_t len = strlen(laststr); + if (!len || laststr[len-1] != '\n') + printf("\n"); + } + return 0; +} + +static int qc_error(qc_program_t *prog) { + fprintf(stderr, "*** VM raised an error:\n"); + qc_print(prog); + prog->vmerror++; + return -1; +} + +static int qc_ftos(qc_program_t *prog) { + char buffer[512]; + qcany_t *num; + qcany_t str; + CheckArgs(1); + num = GetArg(0); + util_snprintf(buffer, sizeof(buffer), "%g", num->_float); + str.string = prog_tempstring(prog, buffer); + Return(str); + return 0; +} + +static int qc_stof(qc_program_t *prog) { + qcany_t *str; + qcany_t num; + CheckArgs(1); + str = GetArg(0); + num._float = (float)strtod(prog_getstring(prog, str->string), nullptr); + Return(num); + return 0; +} + +static int qc_vtos(qc_program_t *prog) { + char buffer[512]; + qcany_t *num; + qcany_t str; + CheckArgs(1); + num = GetArg(0); + util_snprintf(buffer, sizeof(buffer), "'%g %g %g'", num->vector[0], num->vector[1], num->vector[2]); + str.string = prog_tempstring(prog, buffer); + Return(str); + return 0; +} + +static int qc_etos(qc_program_t *prog) { + char buffer[512]; + qcany_t *num; + qcany_t str; + CheckArgs(1); + num = GetArg(0); + util_snprintf(buffer, sizeof(buffer), "%i", num->_int); + str.string = prog_tempstring(prog, buffer); + Return(str); + return 0; +} + +static int qc_spawn(qc_program_t *prog) { + qcany_t ent; + CheckArgs(0); + ent.edict = prog_spawn_entity(prog); + Return(ent); + return (ent.edict ? 0 : -1); +} + +static int qc_kill(qc_program_t *prog) { + qcany_t *ent; + CheckArgs(1); + ent = GetArg(0); + prog_free_entity(prog, ent->edict); + return 0; +} + +static int qc_sqrt(qc_program_t *prog) { + qcany_t *num, out; + CheckArgs(1); + num = GetArg(0); + out._float = sqrt(num->_float); + Return(out); + return 0; +} + +static int qc_vlen(qc_program_t *prog) { + qcany_t *vec, len; + CheckArgs(1); + vec = GetArg(0); + len._float = sqrt(vec->vector[0] * vec->vector[0] + + vec->vector[1] * vec->vector[1] + + vec->vector[2] * vec->vector[2]); + Return(len); + return 0; +} + +static int qc_normalize(qc_program_t *prog) { + double len; + qcany_t *vec; + qcany_t out; + CheckArgs(1); + vec = GetArg(0); + len = sqrt(vec->vector[0] * vec->vector[0] + + vec->vector[1] * vec->vector[1] + + vec->vector[2] * vec->vector[2]); + if (len) + len = 1.0 / len; + else + len = 0; + out.vector[0] = len * vec->vector[0]; + out.vector[1] = len * vec->vector[1]; + out.vector[2] = len * vec->vector[2]; + Return(out); + return 0; +} + +static int qc_strcat(qc_program_t *prog) { + char *buffer; + size_t len1, len2; + qcany_t *str1, *str2; + qcany_t out; + + const char *cstr1; + const char *cstr2; + + CheckArgs(2); + str1 = GetArg(0); + str2 = GetArg(1); + cstr1 = prog_getstring(prog, str1->string); + cstr2 = prog_getstring(prog, str2->string); + len1 = strlen(cstr1); + len2 = strlen(cstr2); + buffer = (char*)mem_a(len1 + len2 + 1); + memcpy(buffer, cstr1, len1); + memcpy(buffer+len1, cstr2, len2+1); + out.string = prog_tempstring(prog, buffer); + mem_d(buffer); + Return(out); + return 0; +} + +static int qc_strcmp(qc_program_t *prog) { + qcany_t *str1, *str2; + qcany_t out; + + const char *cstr1; + const char *cstr2; + + if (prog->argc != 2 && prog->argc != 3) { + fprintf(stderr, "ERROR: invalid number of arguments for strcmp/strncmp: %i, expected 2 or 3\n", + prog->argc); + return -1; + } + + str1 = GetArg(0); + str2 = GetArg(1); + cstr1 = prog_getstring(prog, str1->string); + cstr2 = prog_getstring(prog, str2->string); + if (prog->argc == 3) + out._float = strncmp(cstr1, cstr2, GetArg(2)->_float); + else + out._float = strcmp(cstr1, cstr2); + Return(out); + return 0; +} + +static int qc_floor(qc_program_t *prog) { + qcany_t *num, out; + CheckArgs(1); + num = GetArg(0); + out._float = floor(num->_float); + Return(out); + return 0; +} + +static int qc_pow(qc_program_t *prog) { + qcany_t *base, *exp, out; + CheckArgs(2); + base = GetArg(0); + exp = GetArg(1); + out._float = powf(base->_float, exp->_float); + Return(out); + return 0; +} + +static prog_builtin_t qc_builtins[] = { + nullptr, + &qc_print, /* 1 */ + &qc_ftos, /* 2 */ + &qc_spawn, /* 3 */ + &qc_kill, /* 4 */ + &qc_vtos, /* 5 */ + &qc_error, /* 6 */ + &qc_vlen, /* 7 */ + &qc_etos, /* 8 */ + &qc_stof, /* 9 */ + &qc_strcat, /* 10 */ + &qc_strcmp, /* 11 */ + &qc_normalize, /* 12 */ + &qc_sqrt, /* 13 */ + &qc_floor, /* 14 */ + &qc_pow /* 15 */ +}; + +static const char *arg0 = nullptr; + +static void version(void) { + printf("GMQCC-QCVM %d.%d.%d Built %s %s\n", + GMQCC_VERSION_MAJOR, + GMQCC_VERSION_MINOR, + GMQCC_VERSION_PATCH, + __DATE__, + __TIME__ + ); +} + +static void usage(void) { + printf("usage: %s [options] [parameters] file\n", arg0); + printf("options:\n"); + printf(" -h, --help print this message\n" + " -trace trace the execution\n" + " -profile perform profiling during execution\n" + " -info print information from the prog's header\n" + " -disasm disassemble and exit\n" + " -disasm-func func disassemble and exit\n" + " -printdefs list the defs section\n" + " -printfields list the field section\n" + " -printfuns list functions information\n" + " -v be verbose\n" + " -vv be even more verbose\n"); + printf("parameters:\n"); + printf(" -vector pass a vector parameter to main()\n" + " -float pass a float parameter to main()\n" + " -string pass a string parameter to main() \n"); +} + +static void prog_main_setparams(qc_program_t *prog) { + size_t i; + qcany_t *arg; + + for (i = 0; i < vec_size(main_params); ++i) { + arg = GetGlobal(OFS_PARM0 + 3*i); + arg->vector[0] = 0; + arg->vector[1] = 0; + arg->vector[2] = 0; + switch (main_params[i].vtype) { + case TYPE_VECTOR: + (void)util_sscanf(main_params[i].value, " %f %f %f ", + &arg->vector[0], + &arg->vector[1], + &arg->vector[2]); + break; + case TYPE_FLOAT: + arg->_float = atof(main_params[i].value); + break; + case TYPE_STRING: + arg->string = prog_tempstring(prog, main_params[i].value); + break; + default: + fprintf(stderr, "error: unhandled parameter type: %i\n", main_params[i].vtype); + break; + } + } +} + +static void prog_disasm_function(qc_program_t *prog, size_t id); + +int main(int argc, char **argv) { + size_t i; + qcint_t fnmain = -1; + qc_program_t *prog; + size_t xflags = VMXF_DEFAULT; + bool opts_printfields = false; + bool opts_printdefs = false; + bool opts_printfuns = false; + bool opts_disasm = false; + bool opts_info = false; + bool noexec = false; + const char *progsfile = nullptr; + const char **dis_list = nullptr; + int opts_v = 0; + + arg0 = argv[0]; + + if (argc < 2) { + usage(); + exit(EXIT_FAILURE); + } + + while (argc > 1) { + if (!strcmp(argv[1], "-h") || + !strcmp(argv[1], "-help") || + !strcmp(argv[1], "--help")) + { + usage(); + exit(EXIT_SUCCESS); + } + else if (!strcmp(argv[1], "-v")) { + ++opts_v; + --argc; + ++argv; + } + else if (!strncmp(argv[1], "-vv", 3)) { + const char *av = argv[1]+1; + for (; *av; ++av) { + if (*av == 'v') + ++opts_v; + else { + usage(); + exit(EXIT_FAILURE); + } + } + --argc; + ++argv; + } + else if (!strcmp(argv[1], "-version") || + !strcmp(argv[1], "--version")) + { + version(); + exit(EXIT_SUCCESS); + } + else if (!strcmp(argv[1], "-trace")) { + --argc; + ++argv; + xflags |= VMXF_TRACE; + } + else if (!strcmp(argv[1], "-profile")) { + --argc; + ++argv; + xflags |= VMXF_PROFILE; + } + else if (!strcmp(argv[1], "-info")) { + --argc; + ++argv; + opts_info = true; + noexec = true; + } + else if (!strcmp(argv[1], "-disasm")) { + --argc; + ++argv; + opts_disasm = true; + noexec = true; + } + else if (!strcmp(argv[1], "-disasm-func")) { + --argc; + ++argv; + if (argc <= 1) { + usage(); + exit(EXIT_FAILURE); + } + vec_push(dis_list, argv[1]); + --argc; + ++argv; + noexec = true; + } + else if (!strcmp(argv[1], "-printdefs")) { + --argc; + ++argv; + opts_printdefs = true; + noexec = true; + } + else if (!strcmp(argv[1], "-printfuns")) { + --argc; + ++argv; + opts_printfuns = true; + noexec = true; + } + else if (!strcmp(argv[1], "-printfields")) { + --argc; + ++argv; + opts_printfields = true; + noexec = true; + } + else if (!strcmp(argv[1], "-vector") || + !strcmp(argv[1], "-string") || + !strcmp(argv[1], "-float") ) + { + qcvm_parameter p; + if (argv[1][1] == 'f') + p.vtype = TYPE_FLOAT; + else if (argv[1][1] == 's') + p.vtype = TYPE_STRING; + else if (argv[1][1] == 'v') + p.vtype = TYPE_VECTOR; + else + p.vtype = TYPE_VOID; + + --argc; + ++argv; + if (argc < 2) { + usage(); + exit(EXIT_FAILURE); + } + p.value = argv[1]; + + vec_push(main_params, p); + --argc; + ++argv; + } + else if (!strcmp(argv[1], "--")) { + --argc; + ++argv; + break; + } + else if (argv[1][0] != '-') { + if (progsfile) { + fprintf(stderr, "only 1 program file may be specified\n"); + usage(); + exit(EXIT_FAILURE); + } + progsfile = argv[1]; + --argc; + ++argv; + } + else + { + fprintf(stderr, "unknown parameter: %s\n", argv[1]); + usage(); + exit(EXIT_FAILURE); + } + } + + if (argc == 2 && !progsfile) { + progsfile = argv[1]; + --argc; + ++argv; + } + + if (!progsfile) { + fprintf(stderr, "must specify a program to execute\n"); + usage(); + exit(EXIT_FAILURE); + } + + prog = prog_load(progsfile, noexec); + if (!prog) { + fprintf(stderr, "failed to load program '%s'\n", progsfile); + exit(EXIT_FAILURE); + } + + prog->builtins = qc_builtins; + prog->builtins_count = GMQCC_ARRAY_COUNT(qc_builtins); + + if (opts_info) { + printf("Program's system-checksum = 0x%04x\n", (unsigned int)prog->crc16); + printf("Entity field space: %u\n", (unsigned int)prog->entityfields); + printf("Globals: %zu\n", prog->globals.size()); + printf("Counts:\n" + " code: %zu\n" + " defs: %zu\n" + " fields: %zu\n" + " functions: %zu\n" + " strings: %zu\n", + prog->code.size(), + prog->defs.size(), + prog->fields.size(), + prog->functions.size(), + prog->strings.size()); + } + + if (opts_info) { + prog_delete(prog); + return 0; + } + for (i = 0; i < vec_size(dis_list); ++i) { + size_t k; + printf("Looking for `%s`\n", dis_list[i]); + for (k = 1; k < prog->functions.size(); ++k) { + const char *name = prog_getstring(prog, prog->functions[k].name); + if (!strcmp(name, dis_list[i])) { + prog_disasm_function(prog, k); + break; + } + } + } + if (opts_disasm) { + for (i = 1; i < prog->functions.size(); ++i) + prog_disasm_function(prog, i); + return 0; + } + if (opts_printdefs) { + const char *getstring = nullptr; + for (auto &it : prog->defs) { + printf("Global: %8s %-16s at %u%s", + type_name[it.type & DEF_TYPEMASK], + prog_getstring(prog, it.name), + (unsigned int)it.offset, + ((it.type & DEF_SAVEGLOBAL) ? " [SAVE]" : "")); + if (opts_v) { + switch (it.type & DEF_TYPEMASK) { + case TYPE_FLOAT: + printf(" [init: %g]", ((qcany_t*)(&prog->globals[0] + it.offset))->_float); + break; + case TYPE_INTEGER: + printf(" [init: %i]", (int)( ((qcany_t*)(&prog->globals[0] + it.offset))->_int )); + break; + case TYPE_ENTITY: + case TYPE_FUNCTION: + case TYPE_FIELD: + case TYPE_POINTER: + printf(" [init: %u]", (unsigned)( ((qcany_t*)(&prog->globals[0] + it.offset))->_int )); + break; + case TYPE_STRING: + getstring = prog_getstring(prog, ((qcany_t*)(&prog->globals[0] + it.offset))->string); + printf(" [init: `"); + print_escaped_string(getstring, strlen(getstring)); + printf("`]\n"); + break; + default: + break; + } + } + printf("\n"); + } + } + if (opts_printfields) { + for (auto &it : prog->fields) { + printf("Field: %8s %-16s at %d%s\n", + type_name[it.type], + prog_getstring(prog, it.name), + it.offset, + ((it.type & DEF_SAVEGLOBAL) ? " [SAVE]" : "")); + } + } + if (opts_printfuns) { + for (auto &it : prog->functions) { + int32_t a; + printf("Function: %-16s taking %u parameters:(", + prog_getstring(prog, it.name), + (unsigned int)it.nargs); + for (a = 0; a < it.nargs; ++a) { + printf(" %i", it.argsize[a]); + } + if (opts_v > 1) { + int32_t start = it.entry; + if (start < 0) + printf(") builtin %i\n", (int)-start); + else { + size_t funsize = 0; + prog_section_statement_t *st = &prog->code[0] + start; + for (;st->opcode != INSTR_DONE; ++st) + ++funsize; + printf(") - %zu instructions", funsize); + if (opts_v > 2) { + printf(" - locals: %i + %i\n", + it.firstlocal, + it.locals); + } + else + printf("\n"); + } + } + else if (opts_v) { + printf(") locals: %i + %i\n", + it.firstlocal, + it.locals); + } + else + printf(")\n"); + } + } + if (!noexec) { + for (i = 1; i < prog->functions.size(); ++i) { + const char *name = prog_getstring(prog, prog->functions[i].name); + if (!strcmp(name, "main")) + fnmain = (qcint_t)i; + } + if (fnmain > 0) + { + prog_main_setparams(prog); + prog_exec(prog, &prog->functions[fnmain], xflags, VM_JUMPS_DEFAULT); + } + else + fprintf(stderr, "No main function found\n"); + } + + prog_delete(prog); + return 0; +} + +static void prog_disasm_function(qc_program_t *prog, size_t id) { + prog_section_function_t *fdef = &prog->functions[0] + id; + prog_section_statement_t *st; + + if (fdef->entry < 0) { + printf("FUNCTION \"%s\" = builtin #%i\n", prog_getstring(prog, fdef->name), (int)-fdef->entry); + return; + } + else + printf("FUNCTION \"%s\"\n", prog_getstring(prog, fdef->name)); + + st = &prog->code[0] + fdef->entry; + while (st->opcode != INSTR_DONE) { + prog_print_statement(prog, st); + ++st; + } +} +#else /* !QCVM_LOOP */ +/* + * Everything from here on is not including into the compilation of the + * executor. This is simply code that is #included via #include __FILE__ + * see when QCVM_LOOP is defined, the rest of the code above do not get + * re-included. So this really just acts like one large macro, but it + * sort of isn't, which makes it nicer looking. + */ + +#define OPA ( (qcany_t*) (&prog->globals[0] + st->o1.u1) ) +#define OPB ( (qcany_t*) (&prog->globals[0] + st->o2.u1) ) +#define OPC ( (qcany_t*) (&prog->globals[0] + st->o3.u1) ) + +#define GLOBAL(x) ( (qcany_t*) (&prog->globals[0] + (x)) ) + +/* to be consistent with current darkplaces behaviour */ +#if !defined(FLOAT_IS_TRUE_FOR_INT) +# define FLOAT_IS_TRUE_FOR_INT(x) ( (x) & 0x7FFFFFFF ) +#endif + +while (prog->vmerror == 0) { + prog_section_function_t *newf; + qcany_t *ed; + qcany_t *ptr; + + ++st; + +#if QCVM_PROFILE + prog->profile[st - &prog->code[0]]++; +#endif + +#if QCVM_TRACE + prog_print_statement(prog, st); +#endif + + switch (st->opcode) + { + default: + qcvmerror(prog, "Illegal instruction in %s\n", prog->filename); + goto cleanup; + + case INSTR_DONE: + case INSTR_RETURN: + /* TODO: add instruction count to function profile count */ + GLOBAL(OFS_RETURN)->ivector[0] = OPA->ivector[0]; + GLOBAL(OFS_RETURN)->ivector[1] = OPA->ivector[1]; + GLOBAL(OFS_RETURN)->ivector[2] = OPA->ivector[2]; + + st = &prog->code[0] + prog_leavefunction(prog); + if (!vec_size(prog->stack)) + goto cleanup; + + break; + + case INSTR_MUL_F: + OPC->_float = OPA->_float * OPB->_float; + break; + case INSTR_MUL_V: + OPC->_float = OPA->vector[0]*OPB->vector[0] + + OPA->vector[1]*OPB->vector[1] + + OPA->vector[2]*OPB->vector[2]; + break; + case INSTR_MUL_FV: + { + qcfloat_t f = OPA->_float; + OPC->vector[0] = f * OPB->vector[0]; + OPC->vector[1] = f * OPB->vector[1]; + OPC->vector[2] = f * OPB->vector[2]; + break; + } + case INSTR_MUL_VF: + { + qcfloat_t f = OPB->_float; + OPC->vector[0] = f * OPA->vector[0]; + OPC->vector[1] = f * OPA->vector[1]; + OPC->vector[2] = f * OPA->vector[2]; + break; + } + case INSTR_DIV_F: + if (OPB->_float != 0.0f) + OPC->_float = OPA->_float / OPB->_float; + else + OPC->_float = 0; + break; + + case INSTR_ADD_F: + OPC->_float = OPA->_float + OPB->_float; + break; + case INSTR_ADD_V: + OPC->vector[0] = OPA->vector[0] + OPB->vector[0]; + OPC->vector[1] = OPA->vector[1] + OPB->vector[1]; + OPC->vector[2] = OPA->vector[2] + OPB->vector[2]; + break; + case INSTR_SUB_F: + OPC->_float = OPA->_float - OPB->_float; + break; + case INSTR_SUB_V: + OPC->vector[0] = OPA->vector[0] - OPB->vector[0]; + OPC->vector[1] = OPA->vector[1] - OPB->vector[1]; + OPC->vector[2] = OPA->vector[2] - OPB->vector[2]; + break; + + case INSTR_EQ_F: + OPC->_float = (OPA->_float == OPB->_float); + break; + case INSTR_EQ_V: + OPC->_float = ((OPA->vector[0] == OPB->vector[0]) && + (OPA->vector[1] == OPB->vector[1]) && + (OPA->vector[2] == OPB->vector[2]) ); + break; + case INSTR_EQ_S: + OPC->_float = !strcmp(prog_getstring(prog, OPA->string), + prog_getstring(prog, OPB->string)); + break; + case INSTR_EQ_E: + OPC->_float = (OPA->_int == OPB->_int); + break; + case INSTR_EQ_FNC: + OPC->_float = (OPA->function == OPB->function); + break; + case INSTR_NE_F: + OPC->_float = (OPA->_float != OPB->_float); + break; + case INSTR_NE_V: + OPC->_float = ((OPA->vector[0] != OPB->vector[0]) || + (OPA->vector[1] != OPB->vector[1]) || + (OPA->vector[2] != OPB->vector[2]) ); + break; + case INSTR_NE_S: + OPC->_float = !!strcmp(prog_getstring(prog, OPA->string), + prog_getstring(prog, OPB->string)); + break; + case INSTR_NE_E: + OPC->_float = (OPA->_int != OPB->_int); + break; + case INSTR_NE_FNC: + OPC->_float = (OPA->function != OPB->function); + break; + + case INSTR_LE: + OPC->_float = (OPA->_float <= OPB->_float); + break; + case INSTR_GE: + OPC->_float = (OPA->_float >= OPB->_float); + break; + case INSTR_LT: + OPC->_float = (OPA->_float < OPB->_float); + break; + case INSTR_GT: + OPC->_float = (OPA->_float > OPB->_float); + break; + + case INSTR_LOAD_F: + case INSTR_LOAD_S: + case INSTR_LOAD_FLD: + case INSTR_LOAD_ENT: + case INSTR_LOAD_FNC: + if (OPA->edict < 0 || OPA->edict >= prog->entities) { + qcvmerror(prog, "progs `%s` attempted to read an out of bounds entity", prog->filename); + goto cleanup; + } + if ((unsigned int)(OPB->_int) >= (unsigned int)(prog->entityfields)) { + qcvmerror(prog, "prog `%s` attempted to read an invalid field from entity (%i)", + prog->filename, + OPB->_int); + goto cleanup; + } + ed = prog_getedict(prog, OPA->edict); + OPC->_int = ((qcany_t*)( ((qcint_t*)ed) + OPB->_int ))->_int; + break; + case INSTR_LOAD_V: + if (OPA->edict < 0 || OPA->edict >= prog->entities) { + qcvmerror(prog, "progs `%s` attempted to read an out of bounds entity", prog->filename); + goto cleanup; + } + if (OPB->_int < 0 || OPB->_int + 3 > (qcint_t)prog->entityfields) + { + qcvmerror(prog, "prog `%s` attempted to read an invalid field from entity (%i)", + prog->filename, + OPB->_int + 2); + goto cleanup; + } + ed = prog_getedict(prog, OPA->edict); + ptr = (qcany_t*)( ((qcint_t*)ed) + OPB->_int ); + OPC->ivector[0] = ptr->ivector[0]; + OPC->ivector[1] = ptr->ivector[1]; + OPC->ivector[2] = ptr->ivector[2]; + break; + + case INSTR_ADDRESS: + if (OPA->edict < 0 || OPA->edict >= prog->entities) { + qcvmerror(prog, "prog `%s` attempted to address an out of bounds entity %i", prog->filename, OPA->edict); + goto cleanup; + } + if ((unsigned int)(OPB->_int) >= (unsigned int)(prog->entityfields)) + { + qcvmerror(prog, "prog `%s` attempted to read an invalid field from entity (%i)", + prog->filename, + OPB->_int); + goto cleanup; + } + + ed = prog_getedict(prog, OPA->edict); + OPC->_int = ((qcint_t*)ed) - prog->entitydata + OPB->_int; + break; + + case INSTR_STORE_F: + case INSTR_STORE_S: + case INSTR_STORE_ENT: + case INSTR_STORE_FLD: + case INSTR_STORE_FNC: + OPB->_int = OPA->_int; + break; + case INSTR_STORE_V: + OPB->ivector[0] = OPA->ivector[0]; + OPB->ivector[1] = OPA->ivector[1]; + OPB->ivector[2] = OPA->ivector[2]; + break; + + case INSTR_STOREP_F: + case INSTR_STOREP_S: + case INSTR_STOREP_ENT: + case INSTR_STOREP_FLD: + case INSTR_STOREP_FNC: + if (OPB->_int < 0 || OPB->_int >= (qcint_t)vec_size(prog->entitydata)) { + qcvmerror(prog, "`%s` attempted to write to an out of bounds edict (%i)", prog->filename, OPB->_int); + goto cleanup; + } + if (OPB->_int < (qcint_t)prog->entityfields && !prog->allowworldwrites) + qcvmerror(prog, "`%s` tried to assign to world.%s (field %i)\n", + prog->filename, + prog_getstring(prog, prog_entfield(prog, OPB->_int)->name), + OPB->_int); + ptr = (qcany_t*)(prog->entitydata + OPB->_int); + ptr->_int = OPA->_int; + break; + case INSTR_STOREP_V: + if (OPB->_int < 0 || OPB->_int + 2 >= (qcint_t)vec_size(prog->entitydata)) { + qcvmerror(prog, "`%s` attempted to write to an out of bounds edict (%i)", prog->filename, OPB->_int); + goto cleanup; + } + if (OPB->_int < (qcint_t)prog->entityfields && !prog->allowworldwrites) + qcvmerror(prog, "`%s` tried to assign to world.%s (field %i)\n", + prog->filename, + prog_getstring(prog, prog_entfield(prog, OPB->_int)->name), + OPB->_int); + ptr = (qcany_t*)(prog->entitydata + OPB->_int); + ptr->ivector[0] = OPA->ivector[0]; + ptr->ivector[1] = OPA->ivector[1]; + ptr->ivector[2] = OPA->ivector[2]; + break; + + case INSTR_NOT_F: + OPC->_float = !FLOAT_IS_TRUE_FOR_INT(OPA->_int); + break; + case INSTR_NOT_V: + OPC->_float = !OPA->vector[0] && + !OPA->vector[1] && + !OPA->vector[2]; + break; + case INSTR_NOT_S: + OPC->_float = !OPA->string || + !*prog_getstring(prog, OPA->string); + break; + case INSTR_NOT_ENT: + OPC->_float = (OPA->edict == 0); + break; + case INSTR_NOT_FNC: + OPC->_float = !OPA->function; + break; + + case INSTR_IF: + /* this is consistent with darkplaces' behaviour */ + if(FLOAT_IS_TRUE_FOR_INT(OPA->_int)) + { + st += st->o2.s1 - 1; /* offset the s++ */ + if (++jumpcount >= maxjumps) + qcvmerror(prog, "`%s` hit the runaway loop counter limit of %li jumps", prog->filename, jumpcount); + } + break; + case INSTR_IFNOT: + if(!FLOAT_IS_TRUE_FOR_INT(OPA->_int)) + { + st += st->o2.s1 - 1; /* offset the s++ */ + if (++jumpcount >= maxjumps) + qcvmerror(prog, "`%s` hit the runaway loop counter limit of %li jumps", prog->filename, jumpcount); + } + break; + + case INSTR_CALL0: + case INSTR_CALL1: + case INSTR_CALL2: + case INSTR_CALL3: + case INSTR_CALL4: + case INSTR_CALL5: + case INSTR_CALL6: + case INSTR_CALL7: + case INSTR_CALL8: + prog->argc = st->opcode - INSTR_CALL0; + if (!OPA->function) + qcvmerror(prog, "nullptr function in `%s`", prog->filename); + + if(!OPA->function || OPA->function >= (qcint_t)prog->functions.size()) + { + qcvmerror(prog, "CALL outside the program in `%s`", prog->filename); + goto cleanup; + } + + newf = &prog->functions[OPA->function]; + newf->profile++; + + prog->statement = (st - &prog->code[0]) + 1; + + if (newf->entry < 0) + { + /* negative statements are built in functions */ + qcint_t builtinnumber = -newf->entry; + if (builtinnumber < (qcint_t)prog->builtins_count && prog->builtins[builtinnumber]) + prog->builtins[builtinnumber](prog); + else + qcvmerror(prog, "No such builtin #%i in %s! Try updating your gmqcc sources", + builtinnumber, prog->filename); + } + else + st = &prog->code[0] + prog_enterfunction(prog, newf) - 1; /* offset st++ */ + if (prog->vmerror) + goto cleanup; + break; + + case INSTR_STATE: + { + qcfloat_t *nextthink; + qcfloat_t *time; + qcfloat_t *frame; + if (!prog->supports_state) { + qcvmerror(prog, "`%s` tried to execute a STATE operation but misses its defs!", prog->filename); + goto cleanup; + } + ed = prog_getedict(prog, prog->globals[prog->cached_globals.self]); + ((qcint_t*)ed)[prog->cached_fields.think] = OPB->function; + + frame = (qcfloat_t*)&((qcint_t*)ed)[prog->cached_fields.frame]; + *frame = OPA->_float; + nextthink = (qcfloat_t*)&((qcint_t*)ed)[prog->cached_fields.nextthink]; + time = (qcfloat_t*)(&prog->globals[0] + prog->cached_globals.time); + *nextthink = *time + 0.1; + break; + } + + case INSTR_GOTO: + st += st->o1.s1 - 1; /* offset the s++ */ + if (++jumpcount == 10000000) + qcvmerror(prog, "`%s` hit the runaway loop counter limit of %li jumps", prog->filename, jumpcount); + break; + + case INSTR_AND: + OPC->_float = FLOAT_IS_TRUE_FOR_INT(OPA->_int) && + FLOAT_IS_TRUE_FOR_INT(OPB->_int); + break; + case INSTR_OR: + OPC->_float = FLOAT_IS_TRUE_FOR_INT(OPA->_int) || + FLOAT_IS_TRUE_FOR_INT(OPB->_int); + break; + + case INSTR_BITAND: + OPC->_float = ((int)OPA->_float) & ((int)OPB->_float); + break; + case INSTR_BITOR: + OPC->_float = ((int)OPA->_float) | ((int)OPB->_float); + break; + } +} + +#undef QCVM_PROFILE +#undef QCVM_TRACE +#endif /* !QCVM_LOOP */ diff --cc parser.cpp index df1715c,0000000..51f7e1e mode 100644,000000..100644 --- a/parser.cpp +++ b/parser.cpp @@@ -1,6347 -1,0 +1,6345 @@@ +#include +#include + +#include "intrin.h" +#include "fold.h" +#include "ast.h" +#include "parser.h" + +#define PARSER_HT_LOCALS 2 +#define PARSER_HT_SIZE 512 +#define TYPEDEF_HT_SIZE 512 + +static void parser_enterblock(parser_t *parser); +static bool parser_leaveblock(parser_t *parser); +static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e); +static void parser_addlocal(parser_t *parser, const std::string &name, ast_expression *e); +static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e); +static void parser_addglobal(parser_t *parser, const std::string &name, ast_expression *e); +static bool parse_typedef(parser_t *parser); +static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool is_static, uint32_t qflags, char *vstring); +static ast_block* parse_block(parser_t *parser); +static bool parse_block_into(parser_t *parser, ast_block *block); +static bool parse_statement_or_block(parser_t *parser, ast_expression **out); +static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases); +static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels); +static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels); +static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname); +static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname); +static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg); + +static void parseerror_(parser_t *parser, const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + vcompile_error(parser->lex->tok.ctx, fmt, ap); + va_end(ap); +} + +template +static inline void parseerror(parser_t *parser, const char *fmt, const Ts&... ts) { + return parseerror_(parser, fmt, formatNormalize(ts)...); +} + +// returns true if it counts as an error +static bool GMQCC_WARN parsewarning_(parser_t *parser, int warntype, const char *fmt, ...) +{ + bool r; + va_list ap; + va_start(ap, fmt); + r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap); + va_end(ap); + return r; +} + +template +static inline bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, const Ts&... ts) { + return parsewarning_(parser, warntype, fmt, formatNormalize(ts)...); +} + +/********************************************************************** + * parsing + */ + +static bool parser_next(parser_t *parser) +{ + /* lex_do kills the previous token */ + parser->tok = lex_do(parser->lex); + if (parser->tok == TOKEN_EOF) + return true; + if (parser->tok >= TOKEN_ERROR) { + parseerror(parser, "lex error"); + return false; + } + return true; +} + +#define parser_tokval(p) ((p)->lex->tok.value) +#define parser_token(p) (&((p)->lex->tok)) + +char *parser_strdup(const char *str) +{ + if (str && !*str) { + /* actually dup empty strings */ + char *out = (char*)mem_a(1); + *out = 0; + return out; + } + return util_strdup(str); +} + +static ast_expression* parser_find_field(parser_t *parser, const char *name) { + return (ast_expression*)util_htget(parser->htfields, name); +} +static ast_expression* parser_find_field(parser_t *parser, const std::string &name) { + return parser_find_field(parser, name.c_str()); +} + +static ast_expression* parser_find_label(parser_t *parser, const char *name) +{ + for (auto &it : parser->labels) + if (it->m_name == name) + return it; + return nullptr; +} +static inline ast_expression* parser_find_label(parser_t *parser, const std::string &name) { + return parser_find_label(parser, name.c_str()); +} + +ast_expression* parser_find_global(parser_t *parser, const char *name) +{ + ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser)); + if (var) + return var; + return (ast_expression*)util_htget(parser->htglobals, name); +} + +ast_expression* parser_find_global(parser_t *parser, const std::string &name) { + return parser_find_global(parser, name.c_str()); +} + +static ast_expression* parser_find_param(parser_t *parser, const char *name) +{ + ast_value *fun; + if (!parser->function) + return nullptr; + fun = parser->function->m_function_type; + for (auto &it : fun->m_type_params) { + if (it->m_name == name) + return it.get(); + } + return nullptr; +} + +static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam) +{ + size_t i, hash; + ast_expression *e; + + hash = util_hthash(parser->htglobals, name); + + *isparam = false; + for (i = vec_size(parser->variables); i > upto;) { + --i; + if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) ) + return e; + } + *isparam = true; + return parser_find_param(parser, name); +} + +static ast_expression* parser_find_local(parser_t *parser, const std::string &name, size_t upto, bool *isparam) { + return parser_find_local(parser, name.c_str(), upto, isparam); +} + +static ast_expression* parser_find_var(parser_t *parser, const char *name) +{ + bool dummy; + ast_expression *v; + v = parser_find_local(parser, name, 0, &dummy); + if (!v) v = parser_find_global(parser, name); + return v; +} + +static inline ast_expression* parser_find_var(parser_t *parser, const std::string &name) { + return parser_find_var(parser, name.c_str()); +} + +static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto) +{ + size_t i, hash; + ast_value *e; + hash = util_hthash(parser->typedefs[0], name); + + for (i = vec_size(parser->typedefs); i > upto;) { + --i; + if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) ) + return e; + } + return nullptr; +} + +static ast_value* parser_find_typedef(parser_t *parser, const std::string &name, size_t upto) { + return parser_find_typedef(parser, name.c_str(), upto); +} + +struct sy_elem { + size_t etype; /* 0 = expression, others are operators */ + bool isparen; + size_t off; + ast_expression *out; + ast_block *block; /* for commas and function calls */ + lex_ctx_t ctx; +}; + +enum { + PAREN_EXPR, + PAREN_FUNC, + PAREN_INDEX, + PAREN_TERNARY1, + PAREN_TERNARY2 +}; + +struct shunt { + std::vector out; + std::vector ops; + std::vector argc; + std::vector paren; +}; + +static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) { + sy_elem e; + e.etype = 0; + e.off = 0; + e.out = v; + e.block = nullptr; + e.ctx = ctx; + e.isparen = false; + return e; +} + +static sy_elem syblock(lex_ctx_t ctx, ast_block *v) { + sy_elem e; + e.etype = 0; + e.off = 0; + e.out = v; + e.block = v; + e.ctx = ctx; + e.isparen = false; + return e; +} + +static sy_elem syop(lex_ctx_t ctx, const oper_info *op) { + sy_elem e; + e.etype = 1 + (op - operators); + e.off = 0; + e.out = nullptr; + e.block = nullptr; + e.ctx = ctx; + e.isparen = false; + return e; +} + +static sy_elem syparen(lex_ctx_t ctx, size_t off) { + sy_elem e; + e.etype = 0; + e.off = off; + e.out = nullptr; + e.block = nullptr; + e.ctx = ctx; + e.isparen = true; + return e; +} + +/* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n], + * so we need to rotate it to become ent.(foo[n]). + */ +static bool rotate_entfield_array_index_nodes(ast_expression **out) +{ + ast_array_index *index, *oldindex; + ast_entfield *entfield; + + ast_value *field; + ast_expression *sub; + ast_expression *entity; + + lex_ctx_t ctx = (*out)->m_context; + + if (!ast_istype(*out, ast_array_index)) + return false; + index = (ast_array_index*)*out; + + if (!ast_istype(index->m_array, ast_entfield)) + return false; + entfield = (ast_entfield*)index->m_array; + + if (!ast_istype(entfield->m_field, ast_value)) + return false; + field = (ast_value*)entfield->m_field; + + sub = index->m_index; + entity = entfield->m_entity; + + oldindex = index; + + index = ast_array_index::make(ctx, field, sub); + entfield = new ast_entfield(ctx, entity, index); + *out = entfield; + + oldindex->m_array = nullptr; + oldindex->m_index = nullptr; + delete oldindex; + + return true; +} + +static bool check_write_to(lex_ctx_t ctx, ast_expression *expr) +{ + if (ast_istype(expr, ast_value)) { + ast_value *val = (ast_value*)expr; + if (val->m_cvq == CV_CONST) { + if (val->m_name[0] == '#') { + compile_error(ctx, "invalid assignment to a literal constant"); + return false; + } + /* + * To work around quakeworld we must elide the error and make it + * a warning instead. + */ + if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC) + compile_error(ctx, "assignment to constant `%s`", val->m_name); + else + (void)!compile_warning(ctx, WARN_CONST_OVERWRITE, "assignment to constant `%s`", val->m_name); + return false; + } + } + return true; +} + +static bool parser_sy_apply_operator(parser_t *parser, shunt *sy) +{ + const oper_info *op; + lex_ctx_t ctx; + ast_expression *out = nullptr; + ast_expression *exprs[3]; + ast_block *blocks[3]; + ast_binstore *asbinstore; + size_t i, assignop, addop, subop; + qcint_t generated_op = 0; + + char ty1[1024]; + char ty2[1024]; + + if (sy->ops.empty()) { + parseerror(parser, "internal error: missing operator"); + return false; + } + + if (sy->ops.back().isparen) { + parseerror(parser, "unmatched parenthesis"); + return false; + } + + op = &operators[sy->ops.back().etype - 1]; + ctx = sy->ops.back().ctx; + + if (sy->out.size() < op->operands) { + if (op->flags & OP_PREFIX) + compile_error(ctx, "expected expression after unary operator `%s`", op->op, (int)op->id); + else /* this should have errored previously already */ + compile_error(ctx, "expected expression after operator `%s`", op->op, (int)op->id); + return false; + } + + sy->ops.pop_back(); + + /* op(:?) has no input and no output */ + if (!op->operands) + return true; + + sy->out.erase(sy->out.end() - op->operands, sy->out.end()); + for (i = 0; i < op->operands; ++i) { + exprs[i] = sy->out[sy->out.size()+i].out; + blocks[i] = sy->out[sy->out.size()+i].block; + + if (exprs[i]->m_vtype == TYPE_NOEXPR && + !(i != 0 && op->id == opid2('?',':')) && + !(i == 1 && op->id == opid1('.'))) + { + if (ast_istype(exprs[i], ast_label)) + compile_error(exprs[i]->m_context, "expected expression, got an unknown identifier"); + else + compile_error(exprs[i]->m_context, "not an expression"); + (void)!compile_warning(exprs[i]->m_context, WARN_DEBUG, "expression %u\n", (unsigned int)i); + } + } + + if (blocks[0] && blocks[0]->m_exprs.empty() && op->id != opid1(',')) { + compile_error(ctx, "internal error: operator cannot be applied on empty blocks"); + return false; + } + +#define NotSameType(T) \ + (exprs[0]->m_vtype != exprs[1]->m_vtype || \ + exprs[0]->m_vtype != T) + + switch (op->id) + { + default: + compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id); + return false; + + case opid1('.'): + if (exprs[0]->m_vtype == TYPE_VECTOR && + exprs[1]->m_vtype == TYPE_NOEXPR) + { + if (exprs[1] == parser->const_vec[0]) + out = ast_member::make(ctx, exprs[0], 0, ""); + else if (exprs[1] == parser->const_vec[1]) + out = ast_member::make(ctx, exprs[0], 1, ""); + else if (exprs[1] == parser->const_vec[2]) + out = ast_member::make(ctx, exprs[0], 2, ""); + else { + compile_error(ctx, "access to invalid vector component"); + return false; + } + } + else if (exprs[0]->m_vtype == TYPE_ENTITY) { + if (exprs[1]->m_vtype != TYPE_FIELD) { + compile_error(exprs[1]->m_context, "type error: right hand of member-operand should be an entity-field"); + return false; + } + out = new ast_entfield(ctx, exprs[0], exprs[1]); + } + else if (exprs[0]->m_vtype == TYPE_VECTOR) { + compile_error(exprs[1]->m_context, "vectors cannot be accessed this way"); + return false; + } + else { + compile_error(exprs[1]->m_context, "type error: member-of operator on something that is not an entity or vector"); + return false; + } + break; + + case opid1('['): + if (exprs[0]->m_vtype != TYPE_ARRAY && + !(exprs[0]->m_vtype == TYPE_FIELD && + exprs[0]->m_next->m_vtype == TYPE_ARRAY)) + { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + compile_error(exprs[0]->m_context, "cannot index value of type %s", ty1); + return false; + } + if (exprs[1]->m_vtype != TYPE_FLOAT) { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + compile_error(exprs[1]->m_context, "index must be of type float, not %s", ty1); + return false; + } + out = ast_array_index::make(ctx, exprs[0], exprs[1]); + rotate_entfield_array_index_nodes(&out); + break; + + case opid1(','): + if (sy->paren.size() && sy->paren.back() == PAREN_FUNC) { + sy->out.push_back(syexp(ctx, exprs[0])); + sy->out.push_back(syexp(ctx, exprs[1])); + sy->argc.back()++; + return true; + } + if (blocks[0]) { + if (!blocks[0]->addExpr(exprs[1])) + return false; + } else { + blocks[0] = new ast_block(ctx); + if (!blocks[0]->addExpr(exprs[0]) || + !blocks[0]->addExpr(exprs[1])) + { + return false; + } + } + blocks[0]->setType(*exprs[1]); + + sy->out.push_back(syblock(ctx, blocks[0])); + return true; + + case opid2('+','P'): + out = exprs[0]; + break; + case opid2('-','P'): + if ((out = parser->m_fold.op(op, exprs))) + break; + + if (exprs[0]->m_vtype != TYPE_FLOAT && + exprs[0]->m_vtype != TYPE_VECTOR) { + compile_error(ctx, "invalid types used in unary expression: cannot negate type %s", + type_name[exprs[0]->m_vtype]); + return false; + } + if (exprs[0]->m_vtype == TYPE_FLOAT) + out = ast_unary::make(ctx, VINSTR_NEG_F, exprs[0]); + else + out = ast_unary::make(ctx, VINSTR_NEG_V, exprs[0]); + break; + + case opid2('!','P'): + if (!(out = parser->m_fold.op(op, exprs))) { + switch (exprs[0]->m_vtype) { + case TYPE_FLOAT: + out = ast_unary::make(ctx, INSTR_NOT_F, exprs[0]); + break; + case TYPE_VECTOR: + out = ast_unary::make(ctx, INSTR_NOT_V, exprs[0]); + break; + case TYPE_STRING: + if (OPTS_FLAG(TRUE_EMPTY_STRINGS)) + out = ast_unary::make(ctx, INSTR_NOT_F, exprs[0]); + else + out = ast_unary::make(ctx, INSTR_NOT_S, exprs[0]); + break; + /* we don't constant-fold NOT for these types */ + case TYPE_ENTITY: + out = ast_unary::make(ctx, INSTR_NOT_ENT, exprs[0]); + break; + case TYPE_FUNCTION: + out = ast_unary::make(ctx, INSTR_NOT_FNC, exprs[0]); + break; + default: + compile_error(ctx, "invalid types used in expression: cannot logically negate type %s", + type_name[exprs[0]->m_vtype]); + return false; + } + } + break; + + case opid1('+'): + if (exprs[0]->m_vtype != exprs[1]->m_vtype || + (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT) ) + { + compile_error(ctx, "invalid types used in expression: cannot add type %s and %s", + type_name[exprs[0]->m_vtype], + type_name[exprs[1]->m_vtype]); + return false; + } + if (!(out = parser->m_fold.op(op, exprs))) { + switch (exprs[0]->m_vtype) { + case TYPE_FLOAT: + out = fold::binary(ctx, INSTR_ADD_F, exprs[0], exprs[1]); + break; + case TYPE_VECTOR: + out = fold::binary(ctx, INSTR_ADD_V, exprs[0], exprs[1]); + break; + default: + compile_error(ctx, "invalid types used in expression: cannot add type %s and %s", + type_name[exprs[0]->m_vtype], + type_name[exprs[1]->m_vtype]); + return false; + } + } + break; + case opid1('-'): + if (exprs[0]->m_vtype != exprs[1]->m_vtype || + (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT)) + { + compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s", + type_name[exprs[1]->m_vtype], + type_name[exprs[0]->m_vtype]); + return false; + } + if (!(out = parser->m_fold.op(op, exprs))) { + switch (exprs[0]->m_vtype) { + case TYPE_FLOAT: + out = fold::binary(ctx, INSTR_SUB_F, exprs[0], exprs[1]); + break; + case TYPE_VECTOR: + out = fold::binary(ctx, INSTR_SUB_V, exprs[0], exprs[1]); + break; + default: + compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s", + type_name[exprs[1]->m_vtype], + type_name[exprs[0]->m_vtype]); + return false; + } + } + break; + case opid1('*'): + if (exprs[0]->m_vtype != exprs[1]->m_vtype && + !(exprs[0]->m_vtype == TYPE_VECTOR && + exprs[1]->m_vtype == TYPE_FLOAT) && + !(exprs[1]->m_vtype == TYPE_VECTOR && + exprs[0]->m_vtype == TYPE_FLOAT) + ) + { + compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s", + type_name[exprs[1]->m_vtype], + type_name[exprs[0]->m_vtype]); + return false; + } + if (!(out = parser->m_fold.op(op, exprs))) { + switch (exprs[0]->m_vtype) { + case TYPE_FLOAT: + if (exprs[1]->m_vtype == TYPE_VECTOR) + out = fold::binary(ctx, INSTR_MUL_FV, exprs[0], exprs[1]); + else + out = fold::binary(ctx, INSTR_MUL_F, exprs[0], exprs[1]); + break; + case TYPE_VECTOR: + if (exprs[1]->m_vtype == TYPE_FLOAT) + out = fold::binary(ctx, INSTR_MUL_VF, exprs[0], exprs[1]); + else + out = fold::binary(ctx, INSTR_MUL_V, exprs[0], exprs[1]); + break; + default: + compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s", + type_name[exprs[1]->m_vtype], + type_name[exprs[0]->m_vtype]); + return false; + } + } + break; + + case opid1('/'): + if (exprs[1]->m_vtype != TYPE_FLOAT) { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + ast_type_to_string(exprs[1], ty2, sizeof(ty2)); + compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2); + return false; + } + if (!(out = parser->m_fold.op(op, exprs))) { + if (exprs[0]->m_vtype == TYPE_FLOAT) + out = fold::binary(ctx, INSTR_DIV_F, exprs[0], exprs[1]); + else { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + ast_type_to_string(exprs[1], ty2, sizeof(ty2)); + compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2); + return false; + } + } + break; + + case opid1('%'): + if (NotSameType(TYPE_FLOAT)) { + compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s", + type_name[exprs[0]->m_vtype], + type_name[exprs[1]->m_vtype]); + return false; + } else if (!(out = parser->m_fold.op(op, exprs))) { + /* generate a call to __builtin_mod */ + ast_expression *mod = parser->m_intrin.func("mod"); + ast_call *call = nullptr; + if (!mod) return false; /* can return null for missing floor */ + + call = ast_call::make(parser_ctx(parser), mod); + call->m_params.push_back(exprs[0]); + call->m_params.push_back(exprs[1]); + + out = call; + } + break; + + case opid2('%','='): + compile_error(ctx, "%= is unimplemented"); + return false; + + case opid1('|'): + case opid1('&'): + case opid1('^'): + if ( !(exprs[0]->m_vtype == TYPE_FLOAT && exprs[1]->m_vtype == TYPE_FLOAT) && + !(exprs[0]->m_vtype == TYPE_VECTOR && exprs[1]->m_vtype == TYPE_FLOAT) && + !(exprs[0]->m_vtype == TYPE_VECTOR && exprs[1]->m_vtype == TYPE_VECTOR)) + { + compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s", + type_name[exprs[0]->m_vtype], + type_name[exprs[1]->m_vtype]); + return false; + } + + if (!(out = parser->m_fold.op(op, exprs))) { + /* + * IF the first expression is float, the following will be too + * since scalar ^ vector is not allowed. + */ + if (exprs[0]->m_vtype == TYPE_FLOAT) { + out = fold::binary(ctx, + (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND), + exprs[0], exprs[1]); + } else { + /* + * The first is a vector: vector is allowed to bitop with vector and + * with scalar, branch here for the second operand. + */ + if (exprs[1]->m_vtype == TYPE_VECTOR) { + /* + * Bitop all the values of the vector components against the + * vectors components in question. + */ + out = fold::binary(ctx, + (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V), + exprs[0], exprs[1]); + } else { + out = fold::binary(ctx, + (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF), + exprs[0], exprs[1]); + } + } + } + break; + + case opid2('<','<'): + case opid2('>','>'): + if (NotSameType(TYPE_FLOAT)) { + compile_error(ctx, "invalid types used in expression: cannot perform shift between types %s and %s", + type_name[exprs[0]->m_vtype], + type_name[exprs[1]->m_vtype]); + return false; + } + + if (!(out = parser->m_fold.op(op, exprs))) { + ast_expression *shift = parser->m_intrin.func((op->id == opid2('<','<')) ? "__builtin_lshift" : "__builtin_rshift"); + ast_call *call = ast_call::make(parser_ctx(parser), shift); + call->m_params.push_back(exprs[0]); + call->m_params.push_back(exprs[1]); + out = call; + } + break; + + case opid3('<','<','='): + case opid3('>','>','='): + if (NotSameType(TYPE_FLOAT)) { + compile_error(ctx, "invalid types used in expression: cannot perform shift operation between types %s and %s", + type_name[exprs[0]->m_vtype], + type_name[exprs[1]->m_vtype]); + return false; + } + + if(!(out = parser->m_fold.op(op, exprs))) { + ast_expression *shift = parser->m_intrin.func((op->id == opid3('<','<','=')) ? "__builtin_lshift" : "__builtin_rshift"); + ast_call *call = ast_call::make(parser_ctx(parser), shift); + call->m_params.push_back(exprs[0]); + call->m_params.push_back(exprs[1]); + out = new ast_store( + parser_ctx(parser), + INSTR_STORE_F, + exprs[0], + call + ); + } + + break; + + case opid2('|','|'): + generated_op += 1; /* INSTR_OR */ + case opid2('&','&'): + generated_op += INSTR_AND; + if (!(out = parser->m_fold.op(op, exprs))) { + if (OPTS_FLAG(PERL_LOGIC) && !exprs[0]->compareType(*exprs[1])) { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + ast_type_to_string(exprs[1], ty2, sizeof(ty2)); + compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2); + return false; + } + for (i = 0; i < 2; ++i) { + if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->m_vtype == TYPE_VECTOR) { + out = ast_unary::make(ctx, INSTR_NOT_V, exprs[i]); + if (!out) break; + out = ast_unary::make(ctx, INSTR_NOT_F, out); + if (!out) break; + exprs[i] = out; out = nullptr; + if (OPTS_FLAG(PERL_LOGIC)) { + /* here we want to keep the right expressions' type */ + break; + } + } + else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->m_vtype == TYPE_STRING) { + out = ast_unary::make(ctx, INSTR_NOT_S, exprs[i]); + if (!out) break; + out = ast_unary::make(ctx, INSTR_NOT_F, out); + if (!out) break; + exprs[i] = out; out = nullptr; + if (OPTS_FLAG(PERL_LOGIC)) { + /* here we want to keep the right expressions' type */ + break; + } + } + } + out = fold::binary(ctx, generated_op, exprs[0], exprs[1]); + } + break; + + case opid2('?',':'): + if (sy->paren.back() != PAREN_TERNARY2) { + compile_error(ctx, "mismatched parenthesis/ternary"); + return false; + } + sy->paren.pop_back(); + if (!exprs[1]->compareType(*exprs[2])) { + ast_type_to_string(exprs[1], ty1, sizeof(ty1)); + ast_type_to_string(exprs[2], ty2, sizeof(ty2)); + compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2); + return false; + } + if (!(out = parser->m_fold.op(op, exprs))) + out = new ast_ternary(ctx, exprs[0], exprs[1], exprs[2]); + break; + + case opid2('*', '*'): + if (NotSameType(TYPE_FLOAT)) { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + ast_type_to_string(exprs[1], ty2, sizeof(ty2)); + compile_error(ctx, "invalid types used in exponentiation: %s and %s", + ty1, ty2); + return false; + } + + if (!(out = parser->m_fold.op(op, exprs))) { + ast_call *gencall = ast_call::make(parser_ctx(parser), parser->m_intrin.func("pow")); + gencall->m_params.push_back(exprs[0]); + gencall->m_params.push_back(exprs[1]); + out = gencall; + } + break; + + case opid2('>', '<'): + if (NotSameType(TYPE_VECTOR)) { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + ast_type_to_string(exprs[1], ty2, sizeof(ty2)); + compile_error(ctx, "invalid types used in cross product: %s and %s", + ty1, ty2); + return false; + } + + if (!(out = parser->m_fold.op(op, exprs))) { + out = fold::binary( + parser_ctx(parser), + VINSTR_CROSS, + exprs[0], + exprs[1] + ); + } + + break; + + case opid3('<','=','>'): /* -1, 0, or 1 */ + if (NotSameType(TYPE_FLOAT)) { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + ast_type_to_string(exprs[1], ty2, sizeof(ty2)); + compile_error(ctx, "invalid types used in comparision: %s and %s", + ty1, ty2); + + return false; + } + + if (!(out = parser->m_fold.op(op, exprs))) { + /* This whole block is NOT fold_binary safe */ + ast_binary *eq = new ast_binary(ctx, INSTR_EQ_F, exprs[0], exprs[1]); + + eq->m_refs = AST_REF_NONE; + + /* if (lt) { */ + out = new ast_ternary(ctx, + new ast_binary(ctx, INSTR_LT, exprs[0], exprs[1]), + /* out = -1 */ + parser->m_fold.imm_float(2), + /* } else { */ + /* if (eq) { */ + new ast_ternary(ctx, eq, + /* out = 0 */ + parser->m_fold.imm_float(0), + /* } else { */ + /* out = 1 */ + parser->m_fold.imm_float(1) + /* } */ + ) + /* } */ + ); + + } + break; + + case opid1('>'): + generated_op += 1; /* INSTR_GT */ + case opid1('<'): + generated_op += 1; /* INSTR_LT */ + case opid2('>', '='): + generated_op += 1; /* INSTR_GE */ + case opid2('<', '='): + generated_op += INSTR_LE; + if (NotSameType(TYPE_FLOAT)) { + compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s", + type_name[exprs[0]->m_vtype], + type_name[exprs[1]->m_vtype]); + return false; + } + if (!(out = parser->m_fold.op(op, exprs))) + out = fold::binary(ctx, generated_op, exprs[0], exprs[1]); + break; + case opid2('!', '='): + if (exprs[0]->m_vtype != exprs[1]->m_vtype) { + compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s", + type_name[exprs[0]->m_vtype], + type_name[exprs[1]->m_vtype]); + return false; + } + if (!(out = parser->m_fold.op(op, exprs))) + out = fold::binary(ctx, type_ne_instr[exprs[0]->m_vtype], exprs[0], exprs[1]); + break; + case opid2('=', '='): + if (exprs[0]->m_vtype != exprs[1]->m_vtype) { + compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s", + type_name[exprs[0]->m_vtype], + type_name[exprs[1]->m_vtype]); + return false; + } + if (!(out = parser->m_fold.op(op, exprs))) + out = fold::binary(ctx, type_eq_instr[exprs[0]->m_vtype], exprs[0], exprs[1]); + break; + + case opid1('='): + if (ast_istype(exprs[0], ast_entfield)) { + ast_expression *field = ((ast_entfield*)exprs[0])->m_field; + if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) && + exprs[0]->m_vtype == TYPE_FIELD && + exprs[0]->m_next->m_vtype == TYPE_VECTOR) + { + assignop = type_storep_instr[TYPE_VECTOR]; + } + else + assignop = type_storep_instr[exprs[0]->m_vtype]; + if (assignop == VINSTR_END || !field->m_next->compareType(*exprs[1])) + { + ast_type_to_string(field->m_next, ty1, sizeof(ty1)); + ast_type_to_string(exprs[1], ty2, sizeof(ty2)); + if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) && + field->m_next->m_vtype == TYPE_FUNCTION && + exprs[1]->m_vtype == TYPE_FUNCTION) + { + (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES, + "invalid types in assignment: cannot assign %s to %s", ty2, ty1); + } + else + compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1); + } + } + else + { + if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) && + exprs[0]->m_vtype == TYPE_FIELD && + exprs[0]->m_next->m_vtype == TYPE_VECTOR) + { + assignop = type_store_instr[TYPE_VECTOR]; + } + else { + assignop = type_store_instr[exprs[0]->m_vtype]; + } + + if (assignop == VINSTR_END) { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + ast_type_to_string(exprs[1], ty2, sizeof(ty2)); + compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1); + } + else if (!exprs[0]->compareType(*exprs[1])) + { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + ast_type_to_string(exprs[1], ty2, sizeof(ty2)); + if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) && + exprs[0]->m_vtype == TYPE_FUNCTION && + exprs[1]->m_vtype == TYPE_FUNCTION) + { + (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES, + "invalid types in assignment: cannot assign %s to %s", ty2, ty1); + } + else + compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1); + } + } + (void)check_write_to(ctx, exprs[0]); + /* When we're a vector of part of an entity field we use STOREP */ + if (ast_istype(exprs[0], ast_member) && ast_istype(((ast_member*)exprs[0])->m_owner, ast_entfield)) + assignop = INSTR_STOREP_F; + out = new ast_store(ctx, assignop, exprs[0], exprs[1]); + break; + case opid3('+','+','P'): + case opid3('-','-','P'): + /* prefix ++ */ + if (exprs[0]->m_vtype != TYPE_FLOAT) { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + compile_error(exprs[0]->m_context, "invalid type for prefix increment: %s", ty1); + return false; + } + if (op->id == opid3('+','+','P')) + addop = INSTR_ADD_F; + else + addop = INSTR_SUB_F; + (void)check_write_to(exprs[0]->m_context, exprs[0]); + if (ast_istype(exprs[0], ast_entfield)) { + out = new ast_binstore(ctx, INSTR_STOREP_F, addop, + exprs[0], + parser->m_fold.imm_float(1)); + } else { + out = new ast_binstore(ctx, INSTR_STORE_F, addop, + exprs[0], + parser->m_fold.imm_float(1)); + } + break; + case opid3('S','+','+'): + case opid3('S','-','-'): + /* prefix ++ */ + if (exprs[0]->m_vtype != TYPE_FLOAT) { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + compile_error(exprs[0]->m_context, "invalid type for suffix increment: %s", ty1); + return false; + } + if (op->id == opid3('S','+','+')) { + addop = INSTR_ADD_F; + subop = INSTR_SUB_F; + } else { + addop = INSTR_SUB_F; + subop = INSTR_ADD_F; + } + (void)check_write_to(exprs[0]->m_context, exprs[0]); + if (ast_istype(exprs[0], ast_entfield)) { + out = new ast_binstore(ctx, INSTR_STOREP_F, addop, + exprs[0], + parser->m_fold.imm_float(1)); + } else { + out = new ast_binstore(ctx, INSTR_STORE_F, addop, + exprs[0], + parser->m_fold.imm_float(1)); + } + if (!out) + return false; + out = fold::binary(ctx, subop, + out, + parser->m_fold.imm_float(1)); + + break; + case opid2('+','='): + case opid2('-','='): + if (exprs[0]->m_vtype != exprs[1]->m_vtype || + (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT) ) + { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + ast_type_to_string(exprs[1], ty2, sizeof(ty2)); + compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s", + ty1, ty2); + return false; + } + (void)check_write_to(ctx, exprs[0]); + if (ast_istype(exprs[0], ast_entfield)) + assignop = type_storep_instr[exprs[0]->m_vtype]; + else + assignop = type_store_instr[exprs[0]->m_vtype]; + switch (exprs[0]->m_vtype) { + case TYPE_FLOAT: + out = new ast_binstore(ctx, assignop, + (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F), + exprs[0], exprs[1]); + break; + case TYPE_VECTOR: + out = new ast_binstore(ctx, assignop, + (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V), + exprs[0], exprs[1]); + break; + default: + compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s", + type_name[exprs[0]->m_vtype], + type_name[exprs[1]->m_vtype]); + return false; + }; + break; + case opid2('*','='): + case opid2('/','='): + if (exprs[1]->m_vtype != TYPE_FLOAT || + !(exprs[0]->m_vtype == TYPE_FLOAT || + exprs[0]->m_vtype == TYPE_VECTOR)) + { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + ast_type_to_string(exprs[1], ty2, sizeof(ty2)); + compile_error(ctx, "invalid types used in expression: %s and %s", + ty1, ty2); + return false; + } + (void)check_write_to(ctx, exprs[0]); + if (ast_istype(exprs[0], ast_entfield)) + assignop = type_storep_instr[exprs[0]->m_vtype]; + else + assignop = type_store_instr[exprs[0]->m_vtype]; + switch (exprs[0]->m_vtype) { + case TYPE_FLOAT: + out = new ast_binstore(ctx, assignop, + (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F), + exprs[0], exprs[1]); + break; + case TYPE_VECTOR: + if (op->id == opid2('*','=')) { + out = new ast_binstore(ctx, assignop, INSTR_MUL_VF, + exprs[0], exprs[1]); + } else { + out = fold::binary(ctx, INSTR_DIV_F, + parser->m_fold.imm_float(1), + exprs[1]); + if (!out) { + compile_error(ctx, "internal error: failed to generate division"); + return false; + } + out = new ast_binstore(ctx, assignop, INSTR_MUL_VF, + exprs[0], out); + } + break; + default: + compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s", + type_name[exprs[0]->m_vtype], + type_name[exprs[1]->m_vtype]); + return false; + }; + break; + case opid2('&','='): + case opid2('|','='): + case opid2('^','='): + if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + ast_type_to_string(exprs[1], ty2, sizeof(ty2)); + compile_error(ctx, "invalid types used in expression: %s and %s", + ty1, ty2); + return false; + } + (void)check_write_to(ctx, exprs[0]); + if (ast_istype(exprs[0], ast_entfield)) + assignop = type_storep_instr[exprs[0]->m_vtype]; + else + assignop = type_store_instr[exprs[0]->m_vtype]; + if (exprs[0]->m_vtype == TYPE_FLOAT) + out = new ast_binstore(ctx, assignop, + (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR), + exprs[0], exprs[1]); + else + out = new ast_binstore(ctx, assignop, + (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V), + exprs[0], exprs[1]); + break; + case opid3('&','~','='): + /* This is like: a &= ~(b); + * But QC has no bitwise-not, so we implement it as + * a -= a & (b); + */ + if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + ast_type_to_string(exprs[1], ty2, sizeof(ty2)); + compile_error(ctx, "invalid types used in expression: %s and %s", + ty1, ty2); + return false; + } + if (ast_istype(exprs[0], ast_entfield)) + assignop = type_storep_instr[exprs[0]->m_vtype]; + else + assignop = type_store_instr[exprs[0]->m_vtype]; + if (exprs[0]->m_vtype == TYPE_FLOAT) + out = fold::binary(ctx, INSTR_BITAND, exprs[0], exprs[1]); + else + out = fold::binary(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]); + if (!out) + return false; + (void)check_write_to(ctx, exprs[0]); + if (exprs[0]->m_vtype == TYPE_FLOAT) + asbinstore = new ast_binstore(ctx, assignop, INSTR_SUB_F, exprs[0], out); + else + asbinstore = new ast_binstore(ctx, assignop, INSTR_SUB_V, exprs[0], out); + asbinstore->m_keep_dest = true; + out = asbinstore; + break; + + case opid3('l', 'e', 'n'): + if (exprs[0]->m_vtype != TYPE_STRING && exprs[0]->m_vtype != TYPE_ARRAY) { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + compile_error(exprs[0]->m_context, "invalid type for length operator: %s", ty1); + return false; + } + /* strings must be const, arrays are statically sized */ + if (exprs[0]->m_vtype == TYPE_STRING && + !(((ast_value*)exprs[0])->m_hasvalue && ((ast_value*)exprs[0])->m_cvq == CV_CONST)) + { + compile_error(exprs[0]->m_context, "operand of length operator not a valid constant expression"); + return false; + } + out = parser->m_fold.op(op, exprs); + break; + + case opid2('~', 'P'): + if (exprs[0]->m_vtype != TYPE_FLOAT && exprs[0]->m_vtype != TYPE_VECTOR) { + ast_type_to_string(exprs[0], ty1, sizeof(ty1)); + compile_error(exprs[0]->m_context, "invalid type for bit not: %s", ty1); + return false; + } + if (!(out = parser->m_fold.op(op, exprs))) { + if (exprs[0]->m_vtype == TYPE_FLOAT) { + out = fold::binary(ctx, INSTR_SUB_F, parser->m_fold.imm_float(2), exprs[0]); + } else { + out = fold::binary(ctx, INSTR_SUB_V, parser->m_fold.imm_vector(1), exprs[0]); + } + } + break; + } +#undef NotSameType + if (!out) { + compile_error(ctx, "failed to apply operator %s", op->op); + return false; + } + + sy->out.push_back(syexp(ctx, out)); + return true; +} + +static bool parser_close_call(parser_t *parser, shunt *sy) +{ + /* was a function call */ + ast_expression *fun; + ast_value *funval = nullptr; + ast_call *call; + + size_t fid; + size_t paramcount, i; + bool fold = true; + + fid = sy->ops.back().off; + sy->ops.pop_back(); + + /* out[fid] is the function + * everything above is parameters... + */ + if (sy->argc.empty()) { + parseerror(parser, "internal error: no argument counter available"); + return false; + } + + paramcount = sy->argc.back(); + sy->argc.pop_back(); + + if (sy->out.size() < fid) { + parseerror(parser, "internal error: broken function call %zu < %zu+%zu\n", + sy->out.size(), + fid, + paramcount); + return false; + } + + /* + * TODO handle this at the intrinsic level with an ast_intrinsic + * node and codegen. + */ + if ((fun = sy->out[fid].out) == parser->m_intrin.debug_typestring()) { + char ty[1024]; + if (fid+2 != sy->out.size() || sy->out.back().block) { + parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter"); + return false; + } + ast_type_to_string(sy->out.back().out, ty, sizeof(ty)); + ast_unref(sy->out.back().out); + sy->out[fid] = syexp(sy->out.back().out->m_context, + parser->m_fold.constgen_string(ty, false)); + sy->out.pop_back(); + return true; + } + + /* + * Now we need to determine if the function that is being called is + * an intrinsic so we can evaluate if the arguments to it are constant + * and than fruitfully fold them. + */ +#define fold_can_1(X) \ + (ast_istype(((X)), ast_value) && (X)->m_hasvalue && ((X)->m_cvq == CV_CONST) && \ + ((X))->m_vtype != TYPE_FUNCTION) + + if (fid + 1 < sy->out.size()) + ++paramcount; + + for (i = 0; i < paramcount; ++i) { + if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) { + fold = false; + break; + } + } + + /* + * All is well which ends well, if we make it into here we can ignore the + * intrinsic call and just evaluate it i.e constant fold it. + */ + if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->m_intrinsic) { + ast_expression **exprs = nullptr; + ast_expression *foldval = nullptr; + + for (i = 0; i < paramcount; i++) + vec_push(exprs, sy->out[fid+1 + i].out); + + if (!(foldval = parser->m_intrin.do_fold((ast_value*)fun, exprs))) { + vec_free(exprs); + goto fold_leave; + } + + /* + * Blub: what sorts of unreffing and resizing of + * sy->out should I be doing here? + */ + sy->out[fid] = syexp(foldval->m_context, foldval); + sy->out.erase(sy->out.end() - paramcount, sy->out.end()); + vec_free(exprs); + + return true; + } + + fold_leave: + call = ast_call::make(sy->ops[sy->ops.size()].ctx, fun); + + if (!call) + return false; + + if (fid+1 + paramcount != sy->out.size()) { + parseerror(parser, "internal error: parameter count mismatch: (%zu+1+%zu), %zu", + fid, + paramcount, + sy->out.size()); + return false; + } + + for (i = 0; i < paramcount; ++i) + call->m_params.push_back(sy->out[fid+1 + i].out); + sy->out.erase(sy->out.end() - paramcount, sy->out.end()); + (void)!call->checkTypes(parser->function->m_function_type->m_varparam); + if (parser->max_param_count < paramcount) + parser->max_param_count = paramcount; + + if (ast_istype(fun, ast_value)) { + funval = (ast_value*)fun; + if ((fun->m_flags & AST_FLAG_VARIADIC) && + !(/*funval->m_cvq == CV_CONST && */ funval->m_hasvalue && funval->m_constval.vfunc->m_builtin)) + { + call->m_va_count = parser->m_fold.constgen_float((qcfloat_t)paramcount, false); + } + } + + /* overwrite fid, the function, with a call */ + sy->out[fid] = syexp(call->m_context, call); + + if (fun->m_vtype != TYPE_FUNCTION) { + parseerror(parser, "not a function (%s)", type_name[fun->m_vtype]); + return false; + } + + if (!fun->m_next) { + parseerror(parser, "could not determine function return type"); + return false; + } else { + ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : nullptr); + + if (fun->m_flags & AST_FLAG_DEPRECATED) { + if (!fval) { + return !parsewarning(parser, WARN_DEPRECATED, + "call to function (which is marked deprecated)\n", + "-> it has been declared here: %s:%i", + fun->m_context.file, fun->m_context.line); + } + if (!fval->m_desc.length()) { + return !parsewarning(parser, WARN_DEPRECATED, + "call to `%s` (which is marked deprecated)\n" + "-> `%s` declared here: %s:%i", + fval->m_name, fval->m_name, fun->m_context.file, fun->m_context.line); + } + return !parsewarning(parser, WARN_DEPRECATED, + "call to `%s` (deprecated: %s)\n" + "-> `%s` declared here: %s:%i", + fval->m_name, fval->m_desc, fval->m_name, fun->m_context.file, + fun->m_context.line); + } + + if (fun->m_type_params.size() != paramcount && + !((fun->m_flags & AST_FLAG_VARIADIC) && + fun->m_type_params.size() < paramcount)) + { + const char *fewmany = (fun->m_type_params.size() > paramcount) ? "few" : "many"; + if (fval) + return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT, + "too %s parameters for call to %s: expected %i, got %i\n" + " -> `%s` has been declared here: %s:%i", + fewmany, fval->m_name, (int)fun->m_type_params.size(), (int)paramcount, + fval->m_name, fun->m_context.file, (int)fun->m_context.line); + else + return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT, + "too %s parameters for function call: expected %i, got %i\n" + " -> it has been declared here: %s:%i", + fewmany, (int)fun->m_type_params.size(), (int)paramcount, + fun->m_context.file, (int)fun->m_context.line); + } + } + + return true; +} + +static bool parser_close_paren(parser_t *parser, shunt *sy) +{ + if (sy->ops.empty()) { + parseerror(parser, "unmatched closing paren"); + return false; + } + + while (sy->ops.size()) { + if (sy->ops.back().isparen) { + if (sy->paren.back() == PAREN_FUNC) { + sy->paren.pop_back(); + if (!parser_close_call(parser, sy)) + return false; + break; + } + if (sy->paren.back() == PAREN_EXPR) { + sy->paren.pop_back(); + if (sy->out.empty()) { + compile_error(sy->ops.back().ctx, "empty paren expression"); + sy->ops.pop_back(); + return false; + } + sy->ops.pop_back(); + break; + } + if (sy->paren.back() == PAREN_INDEX) { + sy->paren.pop_back(); + // pop off the parenthesis + sy->ops.pop_back(); + /* then apply the index operator */ + if (!parser_sy_apply_operator(parser, sy)) + return false; + break; + } + if (sy->paren.back() == PAREN_TERNARY1) { + sy->paren.back() = PAREN_TERNARY2; + // pop off the parenthesis + sy->ops.pop_back(); + break; + } + compile_error(sy->ops.back().ctx, "invalid parenthesis"); + return false; + } + if (!parser_sy_apply_operator(parser, sy)) + return false; + } + return true; +} + +static void parser_reclassify_token(parser_t *parser) +{ + size_t i; + if (parser->tok >= TOKEN_START) + return; + for (i = 0; i < operator_count; ++i) { + if (!strcmp(parser_tokval(parser), operators[i].op)) { + parser->tok = TOKEN_OPERATOR; + return; + } + } +} + +static ast_expression* parse_vararg_do(parser_t *parser) +{ + ast_expression *idx, *out; + ast_value *typevar; + ast_value *funtype = parser->function->m_function_type; + lex_ctx_t ctx = parser_ctx(parser); + + if (!parser->function->m_varargs) { + parseerror(parser, "function has no variable argument list"); + return nullptr; + } + + if (!parser_next(parser) || parser->tok != '(') { + parseerror(parser, "expected parameter index and type in parenthesis"); + return nullptr; + } + if (!parser_next(parser)) { + parseerror(parser, "error parsing parameter index"); + return nullptr; + } + + idx = parse_expression_leave(parser, true, false, false); + if (!idx) + return nullptr; + + if (parser->tok != ',') { + if (parser->tok != ')') { + ast_unref(idx); + parseerror(parser, "expected comma after parameter index"); + return nullptr; + } + // vararg piping: ...(start) + out = new ast_argpipe(ctx, idx); + return out; + } + + if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) { + ast_unref(idx); + parseerror(parser, "expected typename for vararg"); + return nullptr; + } + + typevar = parse_typename(parser, nullptr, nullptr, nullptr); + if (!typevar) { + ast_unref(idx); + return nullptr; + } + + if (parser->tok != ')') { + ast_unref(idx); + delete typevar; + parseerror(parser, "expected closing paren"); + return nullptr; + } + + if (funtype->m_varparam && + !typevar->compareType(*funtype->m_varparam)) + { + char ty1[1024]; + char ty2[1024]; + ast_type_to_string(typevar, ty1, sizeof(ty1)); + ast_type_to_string(funtype->m_varparam, ty2, sizeof(ty2)); + compile_error(typevar->m_context, + "function was declared to take varargs of type `%s`, requested type is: %s", + ty2, ty1); + } + + out = ast_array_index::make(ctx, parser->function->m_varargs.get(), idx); + out->adoptType(*typevar); + delete typevar; + return out; +} + +static ast_expression* parse_vararg(parser_t *parser) +{ + bool old_noops = parser->lex->flags.noops; + + ast_expression *out; + + parser->lex->flags.noops = true; + out = parse_vararg_do(parser); + + parser->lex->flags.noops = old_noops; + return out; +} + +/* not to be exposed */ +bool ftepp_predef_exists(const char *name); +static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels) +{ + if (OPTS_FLAG(TRANSLATABLE_STRINGS) && + parser->tok == TOKEN_IDENT && + !strcmp(parser_tokval(parser), "_")) + { + /* a translatable string */ + ast_value *val; + + parser->lex->flags.noops = true; + if (!parser_next(parser) || parser->tok != '(') { + parseerror(parser, "use _(\"string\") to create a translatable string constant"); + return false; + } + parser->lex->flags.noops = false; + if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) { + parseerror(parser, "expected a constant string in translatable-string extension"); + return false; + } + val = (ast_value*)parser->m_fold.constgen_string(parser_tokval(parser), true); + if (!val) + return false; + sy->out.push_back(syexp(parser_ctx(parser), val)); + + if (!parser_next(parser) || parser->tok != ')') { + parseerror(parser, "expected closing paren after translatable string"); + return false; + } + return true; + } + else if (parser->tok == TOKEN_DOTS) + { + ast_expression *va; + if (!OPTS_FLAG(VARIADIC_ARGS)) { + parseerror(parser, "cannot access varargs (try -fvariadic-args)"); + return false; + } + va = parse_vararg(parser); + if (!va) + return false; + sy->out.push_back(syexp(parser_ctx(parser), va)); + return true; + } + else if (parser->tok == TOKEN_FLOATCONST) { + ast_expression *val = parser->m_fold.constgen_float((parser_token(parser)->constval.f), false); + if (!val) + return false; + sy->out.push_back(syexp(parser_ctx(parser), val)); + return true; + } + else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) { + ast_expression *val = parser->m_fold.constgen_float((qcfloat_t)(parser_token(parser)->constval.i), false); + if (!val) + return false; + sy->out.push_back(syexp(parser_ctx(parser), val)); + return true; + } + else if (parser->tok == TOKEN_STRINGCONST) { + ast_expression *val = parser->m_fold.constgen_string(parser_tokval(parser), false); + if (!val) + return false; + sy->out.push_back(syexp(parser_ctx(parser), val)); + return true; + } + else if (parser->tok == TOKEN_VECTORCONST) { + ast_expression *val = parser->m_fold.constgen_vector(parser_token(parser)->constval.v); + if (!val) + return false; + sy->out.push_back(syexp(parser_ctx(parser), val)); + return true; + } + else if (parser->tok == TOKEN_IDENT) + { + const char *ctoken = parser_tokval(parser); + ast_expression *prev = sy->out.size() ? sy->out.back().out : nullptr; + ast_expression *var; + /* a_vector.{x,y,z} */ + if (sy->ops.empty() || + !sy->ops.back().etype || + operators[sy->ops.back().etype-1].id != opid1('.')) + { + /* When adding more intrinsics, fix the above condition */ + prev = nullptr; + } + if (prev && prev->m_vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1]) + { + var = parser->const_vec[ctoken[0]-'x']; + } else { + var = parser_find_var(parser, parser_tokval(parser)); + if (!var) + var = parser_find_field(parser, parser_tokval(parser)); + } + if (!var && with_labels) { + var = parser_find_label(parser, parser_tokval(parser)); + if (!with_labels) { + ast_label *lbl = new ast_label(parser_ctx(parser), parser_tokval(parser), true); + var = lbl; + parser->labels.push_back(lbl); + } + } + if (!var && !strcmp(parser_tokval(parser), "__FUNC__")) + var = parser->m_fold.constgen_string(parser->function->m_name, false); + if (!var) { + /* + * now we try for the real intrinsic hashtable. If the string + * begins with __builtin, we simply skip past it, otherwise we + * use the identifier as is. + */ + if (!strncmp(parser_tokval(parser), "__builtin_", 10)) { + var = parser->m_intrin.func(parser_tokval(parser)); + } + + /* + * Try it again, intrin_func deals with the alias method as well + * the first one masks for __builtin though, we emit warning here. + */ + if (!var) { + if ((var = parser->m_intrin.func(parser_tokval(parser)))) { + (void)!compile_warning( + parser_ctx(parser), + WARN_BUILTINS, + "using implicitly defined builtin `__builtin_%s' for `%s'", + parser_tokval(parser), + parser_tokval(parser) + ); + } + } + + + if (!var) { + /* + * sometimes people use preprocessing predefs without enabling them + * i've done this thousands of times already myself. Lets check for + * it in the predef table. And diagnose it better :) + */ + if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) { + parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser)); + return false; + } + + parseerror(parser, "unexpected identifier: %s", parser_tokval(parser)); + return false; + } + } + else + { + if (ast_istype(var, ast_value)) { + ((ast_value*)var)->m_uses++; + } + else if (ast_istype(var, ast_member)) { + ast_member *mem = (ast_member*)var; + if (ast_istype(mem->m_owner, ast_value)) + ((ast_value*)(mem->m_owner))->m_uses++; + } + } + sy->out.push_back(syexp(parser_ctx(parser), var)); + return true; + } + parseerror(parser, "unexpected token `%s`", parser_tokval(parser)); + return false; +} + +static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels) +{ + ast_expression *expr = nullptr; + shunt sy; + bool wantop = false; + /* only warn once about an assignment in a truth value because the current code + * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part + */ + bool warn_parenthesis = true; + + /* count the parens because an if starts with one, so the + * end of a condition is an unmatched closing paren + */ + int ternaries = 0; + + memset(&sy, 0, sizeof(sy)); + + parser->lex->flags.noops = false; + + parser_reclassify_token(parser); + + while (true) + { + if (parser->tok == TOKEN_TYPENAME) { + parseerror(parser, "unexpected typename `%s`", parser_tokval(parser)); + goto onerr; + } + + if (parser->tok == TOKEN_OPERATOR) + { + /* classify the operator */ + const oper_info *op; + const oper_info *olast = nullptr; + size_t o; + for (o = 0; o < operator_count; ++o) { + if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) && + /* !(operators[o].flags & OP_SUFFIX) && / * remove this */ + !strcmp(parser_tokval(parser), operators[o].op)) + { + break; + } + } + if (o == operator_count) { + compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser)); + goto onerr; + } + /* found an operator */ + op = &operators[o]; + + /* when declaring variables, a comma starts a new variable */ + if (op->id == opid1(',') && sy.paren.empty() && stopatcomma) { + /* fixup the token */ + parser->tok = ','; + break; + } + + /* a colon without a pervious question mark cannot be a ternary */ + if (!ternaries && op->id == opid2(':','?')) { + parser->tok = ':'; + break; + } + + if (op->id == opid1(',')) { + if (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) { + (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression"); + } + } + + if (sy.ops.size() && !sy.ops.back().isparen) + olast = &operators[sy.ops.back().etype-1]; + + /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */ + while (olast && op->prec < olast->prec) + { + if (!parser_sy_apply_operator(parser, &sy)) + goto onerr; + if (sy.ops.size() && !sy.ops.back().isparen) + olast = &operators[sy.ops.back().etype-1]; + else + olast = nullptr; + } + +#define IsAssignOp(x) (\ + (x) == opid1('=') || \ + (x) == opid2('+','=') || \ + (x) == opid2('-','=') || \ + (x) == opid2('*','=') || \ + (x) == opid2('/','=') || \ + (x) == opid2('%','=') || \ + (x) == opid2('&','=') || \ + (x) == opid2('|','=') || \ + (x) == opid3('&','~','=') \ + ) + if (warn_parenthesis) { + if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) || + (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) || + (truthvalue && sy.paren.empty() && IsAssignOp(op->id)) + ) + { + (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value"); + warn_parenthesis = false; + } + + if (olast && olast->id != op->id) { + if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) && + (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^'))) + { + (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations"); + warn_parenthesis = false; + } + else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) && + (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) + { + (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations"); + warn_parenthesis = false; + } + } + } + + while (olast && ( + (op->prec < olast->prec) || + (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) ) + { + if (!parser_sy_apply_operator(parser, &sy)) + goto onerr; + if (sy.ops.size() && !sy.ops.back().isparen) + olast = &operators[sy.ops.back().etype-1]; + else + olast = nullptr; + } + + if (op->id == opid1('(')) { + if (wantop) { + size_t sycount = sy.out.size(); + /* we expected an operator, this is the function-call operator */ + sy.paren.push_back(PAREN_FUNC); + sy.ops.push_back(syparen(parser_ctx(parser), sycount-1)); + sy.argc.push_back(0); + } else { + sy.paren.push_back(PAREN_EXPR); + sy.ops.push_back(syparen(parser_ctx(parser), 0)); + } + wantop = false; + } else if (op->id == opid1('[')) { + if (!wantop) { + parseerror(parser, "unexpected array subscript"); + goto onerr; + } + sy.paren.push_back(PAREN_INDEX); + /* push both the operator and the paren, this makes life easier */ + sy.ops.push_back(syop(parser_ctx(parser), op)); + sy.ops.push_back(syparen(parser_ctx(parser), 0)); + wantop = false; + } else if (op->id == opid2('?',':')) { + sy.ops.push_back(syop(parser_ctx(parser), op)); + sy.ops.push_back(syparen(parser_ctx(parser), 0)); + wantop = false; + ++ternaries; + sy.paren.push_back(PAREN_TERNARY1); + } else if (op->id == opid2(':','?')) { + if (sy.paren.empty()) { + parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)"); + goto onerr; + } + if (sy.paren.back() != PAREN_TERNARY1) { + parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)"); + goto onerr; + } + if (!parser_close_paren(parser, &sy)) + goto onerr; + sy.ops.push_back(syop(parser_ctx(parser), op)); + wantop = false; + --ternaries; + } else { + sy.ops.push_back(syop(parser_ctx(parser), op)); + wantop = !!(op->flags & OP_SUFFIX); + } + } + else if (parser->tok == ')') { + while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) { + if (!parser_sy_apply_operator(parser, &sy)) + goto onerr; + } + if (sy.paren.empty()) + break; + if (wantop) { + if (sy.paren.back() == PAREN_TERNARY1) { + parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)"); + goto onerr; + } + if (!parser_close_paren(parser, &sy)) + goto onerr; + } else { + /* must be a function call without parameters */ + if (sy.paren.back() != PAREN_FUNC) { + parseerror(parser, "closing paren in invalid position"); + goto onerr; + } + if (!parser_close_paren(parser, &sy)) + goto onerr; + } + wantop = true; + } + else if (parser->tok == '(') { + parseerror(parser, "internal error: '(' should be classified as operator"); + goto onerr; + } + else if (parser->tok == '[') { + parseerror(parser, "internal error: '[' should be classified as operator"); + goto onerr; + } + else if (parser->tok == ']') { + while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) { + if (!parser_sy_apply_operator(parser, &sy)) + goto onerr; + } + if (sy.paren.empty()) + break; + if (sy.paren.back() != PAREN_INDEX) { + parseerror(parser, "mismatched parentheses, unexpected ']'"); + goto onerr; + } + if (!parser_close_paren(parser, &sy)) + goto onerr; + wantop = true; + } + else if (!wantop) { + if (!parse_sya_operand(parser, &sy, with_labels)) + goto onerr; + wantop = true; + } + else { + /* in this case we might want to allow constant string concatenation */ + bool concatenated = false; + if (parser->tok == TOKEN_STRINGCONST && sy.out.size()) { + ast_expression *lexpr = sy.out.back().out; + if (ast_istype(lexpr, ast_value)) { + ast_value *last = (ast_value*)lexpr; + if (last->m_isimm == true && last->m_cvq == CV_CONST && + last->m_hasvalue && last->m_vtype == TYPE_STRING) + { + char *newstr = nullptr; + util_asprintf(&newstr, "%s%s", last->m_constval.vstring, parser_tokval(parser)); + sy.out.back().out = parser->m_fold.constgen_string(newstr, false); + mem_d(newstr); + concatenated = true; + } + } + } + if (!concatenated) { + parseerror(parser, "expected operator or end of statement"); + goto onerr; + } + } + + if (!parser_next(parser)) { + goto onerr; + } + if (parser->tok == ';' || + ((sy.paren.empty() || (sy.paren.size() == 1 && sy.paren.back() == PAREN_TERNARY2)) && + (parser->tok == ']' || parser->tok == ')' || parser->tok == '}'))) + { + break; + } + } + + while (sy.ops.size()) { + if (!parser_sy_apply_operator(parser, &sy)) + goto onerr; + } + + parser->lex->flags.noops = true; + if (sy.out.size() != 1) { + parseerror(parser, "expression expected"); + expr = nullptr; + } else + expr = sy.out[0].out; + if (sy.paren.size()) { + parseerror(parser, "internal error: sy.paren.size() = %zu", sy.paren.size()); + return nullptr; + } + return expr; + +onerr: + parser->lex->flags.noops = true; + for (auto &it : sy.out) + if (it.out) ast_unref(it.out); + return nullptr; +} + +static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels) +{ + ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels); + if (!e) + return nullptr; + if (parser->tok != ';') { + parseerror(parser, "semicolon expected after expression"); + ast_unref(e); + return nullptr; + } + if (!parser_next(parser)) { + ast_unref(e); + return nullptr; + } + return e; +} + +static void parser_enterblock(parser_t *parser) +{ + vec_push(parser->variables, util_htnew(PARSER_HT_SIZE)); + vec_push(parser->_blocklocals, vec_size(parser->_locals)); + vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE)); + vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs)); + vec_push(parser->_block_ctx, parser_ctx(parser)); +} + +static bool parser_leaveblock(parser_t *parser) +{ + bool rv = true; + size_t locals, typedefs; + + if (vec_size(parser->variables) <= PARSER_HT_LOCALS) { + parseerror(parser, "internal error: parser_leaveblock with no block"); + return false; + } + + util_htdel(vec_last(parser->variables)); + + vec_pop(parser->variables); + if (!vec_size(parser->_blocklocals)) { + parseerror(parser, "internal error: parser_leaveblock with no block (2)"); + return false; + } + + locals = vec_last(parser->_blocklocals); + vec_pop(parser->_blocklocals); + while (vec_size(parser->_locals) != locals) { + ast_expression *e = vec_last(parser->_locals); + ast_value *v = (ast_value*)e; + vec_pop(parser->_locals); + if (ast_istype(e, ast_value) && !v->m_uses) { + if (compile_warning(v->m_context, WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->m_name)) + rv = false; + } + } + + typedefs = vec_last(parser->_blocktypedefs); + while (vec_size(parser->_typedefs) != typedefs) { + delete vec_last(parser->_typedefs); + vec_pop(parser->_typedefs); + } + util_htdel(vec_last(parser->typedefs)); + vec_pop(parser->typedefs); + + vec_pop(parser->_block_ctx); + + return rv; +} + +static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e) +{ + vec_push(parser->_locals, e); + util_htset(vec_last(parser->variables), name, (void*)e); +} +static void parser_addlocal(parser_t *parser, const std::string &name, ast_expression *e) { + return parser_addlocal(parser, name.c_str(), e); +} + +static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e) +{ + parser->globals.push_back(e); + util_htset(parser->htglobals, name, e); +} +static void parser_addglobal(parser_t *parser, const std::string &name, ast_expression *e) { + return parser_addglobal(parser, name.c_str(), e); +} + +static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot) +{ + bool ifnot = false; + ast_unary *unary; + ast_expression *prev; + + if (cond->m_vtype == TYPE_VOID || cond->m_vtype >= TYPE_VARIANT) { + char ty[1024]; + ast_type_to_string(cond, ty, sizeof(ty)); + compile_error(cond->m_context, "invalid type for if() condition: %s", ty); + } + + if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->m_vtype == TYPE_STRING) + { + prev = cond; + cond = ast_unary::make(cond->m_context, INSTR_NOT_S, cond); + if (!cond) { + ast_unref(prev); + parseerror(parser, "internal error: failed to process condition"); + return nullptr; + } + ifnot = !ifnot; + } + else if (OPTS_FLAG(CORRECT_LOGIC) && cond->m_vtype == TYPE_VECTOR) + { + /* vector types need to be cast to true booleans */ + ast_binary *bin = (ast_binary*)cond; + if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->m_op == INSTR_AND || bin->m_op == INSTR_OR)) + { + /* in perl-logic, AND and OR take care of the -fcorrect-logic */ + prev = cond; + cond = ast_unary::make(cond->m_context, INSTR_NOT_V, cond); + if (!cond) { + ast_unref(prev); + parseerror(parser, "internal error: failed to process condition"); + return nullptr; + } + ifnot = !ifnot; + } + } + + unary = (ast_unary*)cond; + /* ast_istype dereferences cond, should test here for safety */ + while (cond && ast_istype(cond, ast_unary) && unary->m_op == INSTR_NOT_F) + { + cond = unary->m_operand; + unary->m_operand = nullptr; + delete unary; + ifnot = !ifnot; + unary = (ast_unary*)cond; + } + + if (!cond) + parseerror(parser, "internal error: failed to process condition"); + + if (ifnot) *_ifnot = !*_ifnot; + return cond; +} + +static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out) +{ + ast_ifthen *ifthen; + ast_expression *cond, *ontrue = nullptr, *onfalse = nullptr; + bool ifnot = false; + + lex_ctx_t ctx = parser_ctx(parser); + + (void)block; /* not touching */ + + /* skip the 'if', parse an optional 'not' and check for an opening paren */ + if (!parser_next(parser)) { + parseerror(parser, "expected condition or 'not'"); + return false; + } + if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) { + ifnot = true; + if (!parser_next(parser)) { + parseerror(parser, "expected condition in parenthesis"); + return false; + } + } + if (parser->tok != '(') { + parseerror(parser, "expected 'if' condition in parenthesis"); + return false; + } + /* parse into the expression */ + if (!parser_next(parser)) { + parseerror(parser, "expected 'if' condition after opening paren"); + return false; + } + /* parse the condition */ + cond = parse_expression_leave(parser, false, true, false); + if (!cond) + return false; + /* closing paren */ + if (parser->tok != ')') { + parseerror(parser, "expected closing paren after 'if' condition"); + ast_unref(cond); + return false; + } + /* parse into the 'then' branch */ + if (!parser_next(parser)) { + parseerror(parser, "expected statement for on-true branch of 'if'"); + ast_unref(cond); + return false; + } + if (!parse_statement_or_block(parser, &ontrue)) { + ast_unref(cond); + return false; + } + if (!ontrue) + ontrue = new ast_block(parser_ctx(parser)); + /* check for an else */ + if (!strcmp(parser_tokval(parser), "else")) { + /* parse into the 'else' branch */ + if (!parser_next(parser)) { + parseerror(parser, "expected on-false branch after 'else'"); + delete ontrue; + ast_unref(cond); + return false; + } + if (!parse_statement_or_block(parser, &onfalse)) { + delete ontrue; + ast_unref(cond); + return false; + } + } + + cond = process_condition(parser, cond, &ifnot); + if (!cond) { + if (ontrue) delete ontrue; + if (onfalse) delete onfalse; + return false; + } + + if (ifnot) + ifthen = new ast_ifthen(ctx, cond, onfalse, ontrue); + else + ifthen = new ast_ifthen(ctx, cond, ontrue, onfalse); + *out = ifthen; + return true; +} + +static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out); +static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out) +{ + bool rv; + char *label = nullptr; + + /* skip the 'while' and get the body */ + if (!parser_next(parser)) { + if (OPTS_FLAG(LOOP_LABELS)) + parseerror(parser, "expected loop label or 'while' condition in parenthesis"); + else + parseerror(parser, "expected 'while' condition in parenthesis"); + return false; + } + + if (parser->tok == ':') { + if (!OPTS_FLAG(LOOP_LABELS)) + parseerror(parser, "labeled loops not activated, try using -floop-labels"); + if (!parser_next(parser) || parser->tok != TOKEN_IDENT) { + parseerror(parser, "expected loop label"); + return false; + } + label = util_strdup(parser_tokval(parser)); + if (!parser_next(parser)) { + mem_d(label); + parseerror(parser, "expected 'while' condition in parenthesis"); + return false; + } + } + + if (parser->tok != '(') { + parseerror(parser, "expected 'while' condition in parenthesis"); + return false; + } + + parser->breaks.push_back(label); + parser->continues.push_back(label); + + rv = parse_while_go(parser, block, out); + if (label) + mem_d(label); + if (parser->breaks.back() != label || parser->continues.back() != label) { + parseerror(parser, "internal error: label stack corrupted"); + rv = false; + delete *out; + *out = nullptr; + } + else { + parser->breaks.pop_back(); + parser->continues.pop_back(); + } + return rv; +} + +static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out) +{ + ast_loop *aloop; + ast_expression *cond, *ontrue; + + bool ifnot = false; + + lex_ctx_t ctx = parser_ctx(parser); + + (void)block; /* not touching */ + + /* parse into the expression */ + if (!parser_next(parser)) { + parseerror(parser, "expected 'while' condition after opening paren"); + return false; + } + /* parse the condition */ + cond = parse_expression_leave(parser, false, true, false); + if (!cond) + return false; + /* closing paren */ + if (parser->tok != ')') { + parseerror(parser, "expected closing paren after 'while' condition"); + ast_unref(cond); + return false; + } + /* parse into the 'then' branch */ + if (!parser_next(parser)) { + parseerror(parser, "expected while-loop body"); + ast_unref(cond); + return false; + } + if (!parse_statement_or_block(parser, &ontrue)) { + ast_unref(cond); + return false; + } + + cond = process_condition(parser, cond, &ifnot); + if (!cond) { + ast_unref(ontrue); + return false; + } + aloop = new ast_loop(ctx, nullptr, cond, ifnot, nullptr, false, nullptr, ontrue); + *out = aloop; + return true; +} + +static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out); +static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out) +{ + bool rv; + char *label = nullptr; + + /* skip the 'do' and get the body */ + if (!parser_next(parser)) { + if (OPTS_FLAG(LOOP_LABELS)) + parseerror(parser, "expected loop label or body"); + else + parseerror(parser, "expected loop body"); + return false; + } + + if (parser->tok == ':') { + if (!OPTS_FLAG(LOOP_LABELS)) + parseerror(parser, "labeled loops not activated, try using -floop-labels"); + if (!parser_next(parser) || parser->tok != TOKEN_IDENT) { + parseerror(parser, "expected loop label"); + return false; + } + label = util_strdup(parser_tokval(parser)); + if (!parser_next(parser)) { + mem_d(label); + parseerror(parser, "expected loop body"); + return false; + } + } + + parser->breaks.push_back(label); + parser->continues.push_back(label); + + rv = parse_dowhile_go(parser, block, out); + if (label) + mem_d(label); + if (parser->breaks.back() != label || parser->continues.back() != label) { + parseerror(parser, "internal error: label stack corrupted"); + rv = false; + delete *out; + *out = nullptr; + } + else { + parser->breaks.pop_back(); + parser->continues.pop_back(); + } + return rv; +} + +static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out) +{ + ast_loop *aloop; + ast_expression *cond, *ontrue; + + bool ifnot = false; + + lex_ctx_t ctx = parser_ctx(parser); + + (void)block; /* not touching */ + + if (!parse_statement_or_block(parser, &ontrue)) + return false; + + /* expect the "while" */ + if (parser->tok != TOKEN_KEYWORD || + strcmp(parser_tokval(parser), "while")) + { + parseerror(parser, "expected 'while' and condition"); + delete ontrue; + return false; + } + + /* skip the 'while' and check for opening paren */ + if (!parser_next(parser) || parser->tok != '(') { + parseerror(parser, "expected 'while' condition in parenthesis"); + delete ontrue; + return false; + } + /* parse into the expression */ + if (!parser_next(parser)) { + parseerror(parser, "expected 'while' condition after opening paren"); + delete ontrue; + return false; + } + /* parse the condition */ + cond = parse_expression_leave(parser, false, true, false); + if (!cond) + return false; + /* closing paren */ + if (parser->tok != ')') { + parseerror(parser, "expected closing paren after 'while' condition"); + delete ontrue; + ast_unref(cond); + return false; + } + /* parse on */ + if (!parser_next(parser) || parser->tok != ';') { + parseerror(parser, "expected semicolon after condition"); + delete ontrue; + ast_unref(cond); + return false; + } + + if (!parser_next(parser)) { + parseerror(parser, "parse error"); + delete ontrue; + ast_unref(cond); + return false; + } + + cond = process_condition(parser, cond, &ifnot); + if (!cond) { + delete ontrue; + return false; + } + aloop = new ast_loop(ctx, nullptr, nullptr, false, cond, ifnot, nullptr, ontrue); + *out = aloop; + return true; +} + +static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out); +static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out) +{ + bool rv; + char *label = nullptr; + + /* skip the 'for' and check for opening paren */ + if (!parser_next(parser)) { + if (OPTS_FLAG(LOOP_LABELS)) + parseerror(parser, "expected loop label or 'for' expressions in parenthesis"); + else + parseerror(parser, "expected 'for' expressions in parenthesis"); + return false; + } + + if (parser->tok == ':') { + if (!OPTS_FLAG(LOOP_LABELS)) + parseerror(parser, "labeled loops not activated, try using -floop-labels"); + if (!parser_next(parser) || parser->tok != TOKEN_IDENT) { + parseerror(parser, "expected loop label"); + return false; + } + label = util_strdup(parser_tokval(parser)); + if (!parser_next(parser)) { + mem_d(label); + parseerror(parser, "expected 'for' expressions in parenthesis"); + return false; + } + } + + if (parser->tok != '(') { + parseerror(parser, "expected 'for' expressions in parenthesis"); + return false; + } + + parser->breaks.push_back(label); + parser->continues.push_back(label); + + rv = parse_for_go(parser, block, out); + if (label) + mem_d(label); + if (parser->breaks.back() != label || parser->continues.back() != label) { + parseerror(parser, "internal error: label stack corrupted"); + rv = false; + delete *out; + *out = nullptr; + } + else { + parser->breaks.pop_back(); + parser->continues.pop_back(); + } + return rv; +} +static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out) +{ + ast_loop *aloop; + ast_expression *initexpr, *cond, *increment, *ontrue; + ast_value *typevar; + + bool ifnot = false; + + lex_ctx_t ctx = parser_ctx(parser); + + parser_enterblock(parser); + + initexpr = nullptr; + cond = nullptr; + increment = nullptr; + ontrue = nullptr; + + /* parse into the expression */ + if (!parser_next(parser)) { + parseerror(parser, "expected 'for' initializer after opening paren"); + goto onerr; + } + + typevar = nullptr; + if (parser->tok == TOKEN_IDENT) + typevar = parser_find_typedef(parser, parser_tokval(parser), 0); + + if (typevar || parser->tok == TOKEN_TYPENAME) { + if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, nullptr)) + goto onerr; + } + else if (parser->tok != ';') + { + initexpr = parse_expression_leave(parser, false, false, false); + if (!initexpr) + goto onerr; + /* move on to condition */ + if (parser->tok != ';') { + parseerror(parser, "expected semicolon after for-loop initializer"); + goto onerr; + } + if (!parser_next(parser)) { + parseerror(parser, "expected for-loop condition"); + goto onerr; + } - } - else if (!parser_next(parser)) { ++ } else if (!parser_next(parser)) { + parseerror(parser, "expected for-loop condition"); + goto onerr; + } + + /* parse the condition */ + if (parser->tok != ';') { + cond = parse_expression_leave(parser, false, true, false); + if (!cond) + goto onerr; + } - + /* move on to incrementor */ + if (parser->tok != ';') { + parseerror(parser, "expected semicolon after for-loop initializer"); + goto onerr; + } + if (!parser_next(parser)) { + parseerror(parser, "expected for-loop condition"); + goto onerr; + } + + /* parse the incrementor */ + if (parser->tok != ')') { + lex_ctx_t condctx = parser_ctx(parser); + increment = parse_expression_leave(parser, false, false, false); + if (!increment) + goto onerr; + if (!increment->m_side_effects) { + if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect")) + goto onerr; + } + } + + /* closing paren */ + if (parser->tok != ')') { + parseerror(parser, "expected closing paren after 'for-loop' incrementor"); + goto onerr; + } + /* parse into the 'then' branch */ + if (!parser_next(parser)) { + parseerror(parser, "expected for-loop body"); + goto onerr; + } + if (!parse_statement_or_block(parser, &ontrue)) + goto onerr; + + if (cond) { + cond = process_condition(parser, cond, &ifnot); + if (!cond) + goto onerr; + } + aloop = new ast_loop(ctx, initexpr, cond, ifnot, nullptr, false, increment, ontrue); + *out = aloop; + + if (!parser_leaveblock(parser)) { + delete aloop; + return false; + } + return true; +onerr: + if (initexpr) ast_unref(initexpr); + if (cond) ast_unref(cond); + if (increment) ast_unref(increment); + (void)!parser_leaveblock(parser); + return false; +} + +static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out) +{ + ast_expression *exp = nullptr; + ast_expression *var = nullptr; + ast_return *ret = nullptr; + ast_value *retval = parser->function->m_return_value; + ast_value *expected = parser->function->m_function_type; + + lex_ctx_t ctx = parser_ctx(parser); + + (void)block; /* not touching */ + + if (!parser_next(parser)) { + parseerror(parser, "expected return expression"); + return false; + } + + /* return assignments */ + if (parser->tok == '=') { + if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) { + parseerror(parser, "return assignments not activated, try using -freturn-assigments"); + return false; + } + + if (type_store_instr[expected->m_next->m_vtype] == VINSTR_END) { + char ty1[1024]; + ast_type_to_string(expected->m_next, ty1, sizeof(ty1)); + parseerror(parser, "invalid return type: `%s'", ty1); + return false; + } + + if (!parser_next(parser)) { + parseerror(parser, "expected return assignment expression"); + return false; + } + + if (!(exp = parse_expression_leave(parser, false, false, false))) + return false; + + /* prepare the return value */ + if (!retval) { + retval = new ast_value(ctx, "#LOCAL_RETURN", TYPE_VOID); + retval->adoptType(*expected->m_next); + parser->function->m_return_value = retval; + } + + if (!exp->compareType(*retval)) { + char ty1[1024], ty2[1024]; + ast_type_to_string(exp, ty1, sizeof(ty1)); + ast_type_to_string(retval, ty2, sizeof(ty2)); + parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2); + } + + /* store to 'return' local variable */ + var = new ast_store( + ctx, + type_store_instr[expected->m_next->m_vtype], + retval, exp); + + if (!var) { + ast_unref(exp); + return false; + } + + if (parser->tok != ';') + parseerror(parser, "missing semicolon after return assignment"); + else if (!parser_next(parser)) + parseerror(parser, "parse error after return assignment"); + + *out = var; + return true; + } + + if (parser->tok != ';') { + exp = parse_expression(parser, false, false); + if (!exp) + return false; + + if (exp->m_vtype != TYPE_NIL && + exp->m_vtype != (expected)->m_next->m_vtype) + { + parseerror(parser, "return with invalid expression"); + } + + ret = new ast_return(ctx, exp); + if (!ret) { + ast_unref(exp); + return false; + } + } else { + if (!parser_next(parser)) + parseerror(parser, "parse error"); + + if (!retval && expected->m_next->m_vtype != TYPE_VOID) + { + (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value"); + } + ret = new ast_return(ctx, retval); + } + *out = ret; + return true; +} + +static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue) +{ + size_t i; + unsigned int levels = 0; + lex_ctx_t ctx = parser_ctx(parser); + auto &loops = (is_continue ? parser->continues : parser->breaks); + + (void)block; /* not touching */ + if (!parser_next(parser)) { + parseerror(parser, "expected semicolon or loop label"); + return false; + } + + if (loops.empty()) { + if (is_continue) + parseerror(parser, "`continue` can only be used inside loops"); + else + parseerror(parser, "`break` can only be used inside loops or switches"); + } + + if (parser->tok == TOKEN_IDENT) { + if (!OPTS_FLAG(LOOP_LABELS)) + parseerror(parser, "labeled loops not activated, try using -floop-labels"); + i = loops.size(); + while (i--) { + if (loops[i] && !strcmp(loops[i], parser_tokval(parser))) + break; + if (!i) { + parseerror(parser, "no such loop to %s: `%s`", + (is_continue ? "continue" : "break out of"), + parser_tokval(parser)); + return false; + } + ++levels; + } + if (!parser_next(parser)) { + parseerror(parser, "expected semicolon"); + return false; + } + } + + if (parser->tok != ';') { + parseerror(parser, "expected semicolon"); + return false; + } + + if (!parser_next(parser)) + parseerror(parser, "parse error"); + + *out = new ast_breakcont(ctx, is_continue, levels); + return true; +} + +/* returns true when it was a variable qualifier, false otherwise! + * on error, cvq is set to CV_WRONG + */ +struct attribute_t { + const char *name; + size_t flag; +}; + +static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message) +{ + bool had_const = false; + bool had_var = false; + bool had_noref = false; + bool had_attrib = false; + bool had_static = false; + uint32_t flags = 0; + + static attribute_t attributes[] = { + { "noreturn", AST_FLAG_NORETURN }, + { "inline", AST_FLAG_INLINE }, + { "eraseable", AST_FLAG_ERASEABLE }, + { "accumulate", AST_FLAG_ACCUMULATE }, + { "last", AST_FLAG_FINAL_DECL } + }; + + *cvq = CV_NONE; + + for (;;) { + size_t i; + if (parser->tok == TOKEN_ATTRIBUTE_OPEN) { + had_attrib = true; + /* parse an attribute */ + if (!parser_next(parser)) { + parseerror(parser, "expected attribute after `[[`"); + *cvq = CV_WRONG; + return false; + } + + for (i = 0; i < GMQCC_ARRAY_COUNT(attributes); i++) { + if (!strcmp(parser_tokval(parser), attributes[i].name)) { + flags |= attributes[i].flag; + if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) { + parseerror(parser, "`%s` attribute has no parameters, expected `]]`", + attributes[i].name); + *cvq = CV_WRONG; + return false; + } + break; + } + } + + if (i != GMQCC_ARRAY_COUNT(attributes)) + goto leave; + + + if (!strcmp(parser_tokval(parser), "noref")) { + had_noref = true; + if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) { + parseerror(parser, "`noref` attribute has no parameters, expected `]]`"); + *cvq = CV_WRONG; + return false; + } + } + else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) { + flags |= AST_FLAG_ALIAS; + *message = nullptr; + + if (!parser_next(parser)) { + parseerror(parser, "parse error in attribute"); + goto argerr; + } + + if (parser->tok == '(') { + if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) { + parseerror(parser, "`alias` attribute missing parameter"); + goto argerr; + } + + *message = util_strdup(parser_tokval(parser)); + + if (!parser_next(parser)) { + parseerror(parser, "parse error in attribute"); + goto argerr; + } + + if (parser->tok != ')') { + parseerror(parser, "`alias` attribute expected `)` after parameter"); + goto argerr; + } + + if (!parser_next(parser)) { + parseerror(parser, "parse error in attribute"); + goto argerr; + } + } + + if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) { + parseerror(parser, "`alias` attribute expected `]]`"); + goto argerr; + } + } + else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) { + flags |= AST_FLAG_DEPRECATED; + *message = nullptr; + + if (!parser_next(parser)) { + parseerror(parser, "parse error in attribute"); + goto argerr; + } + + if (parser->tok == '(') { + if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) { + parseerror(parser, "`deprecated` attribute missing parameter"); + goto argerr; + } + + *message = util_strdup(parser_tokval(parser)); + + if (!parser_next(parser)) { + parseerror(parser, "parse error in attribute"); + goto argerr; + } + + if(parser->tok != ')') { + parseerror(parser, "`deprecated` attribute expected `)` after parameter"); + goto argerr; + } + + if (!parser_next(parser)) { + parseerror(parser, "parse error in attribute"); + goto argerr; + } + } + /* no message */ + if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) { + parseerror(parser, "`deprecated` attribute expected `]]`"); + + argerr: /* ugly */ + if (*message) mem_d(*message); + *message = nullptr; + *cvq = CV_WRONG; + return false; + } + } + else if (!strcmp(parser_tokval(parser), "coverage") && !(flags & AST_FLAG_COVERAGE)) { + flags |= AST_FLAG_COVERAGE; + if (!parser_next(parser)) { + error_in_coverage: + parseerror(parser, "parse error in coverage attribute"); + *cvq = CV_WRONG; + return false; + } + if (parser->tok == '(') { + if (!parser_next(parser)) { + bad_coverage_arg: + parseerror(parser, "invalid parameter for coverage() attribute\n" + "valid are: block"); + *cvq = CV_WRONG; + return false; + } + if (parser->tok != ')') { + do { + if (parser->tok != TOKEN_IDENT) + goto bad_coverage_arg; + if (!strcmp(parser_tokval(parser), "block")) + flags |= AST_FLAG_BLOCK_COVERAGE; + else if (!strcmp(parser_tokval(parser), "none")) + flags &= ~(AST_FLAG_COVERAGE_MASK); + else + goto bad_coverage_arg; + if (!parser_next(parser)) + goto error_in_coverage; + if (parser->tok == ',') { + if (!parser_next(parser)) + goto error_in_coverage; + } + } while (parser->tok != ')'); + } + if (parser->tok != ')' || !parser_next(parser)) + goto error_in_coverage; + } else { + /* without parameter [[coverage]] equals [[coverage(block)]] */ + flags |= AST_FLAG_BLOCK_COVERAGE; + } + } + else + { + /* Skip tokens until we hit a ]] */ + (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser)); + while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) { + if (!parser_next(parser)) { + parseerror(parser, "error inside attribute"); + *cvq = CV_WRONG; + return false; + } + } + } + } + else if (with_local && !strcmp(parser_tokval(parser), "static")) + had_static = true; + else if (!strcmp(parser_tokval(parser), "const")) + had_const = true; + else if (!strcmp(parser_tokval(parser), "var")) + had_var = true; + else if (with_local && !strcmp(parser_tokval(parser), "local")) + had_var = true; + else if (!strcmp(parser_tokval(parser), "noref")) + had_noref = true; + else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) { + return false; + } + else + break; + + leave: + if (!parser_next(parser)) + goto onerr; + } + if (had_const) + *cvq = CV_CONST; + else if (had_var) + *cvq = CV_VAR; + else + *cvq = CV_NONE; + *noref = had_noref; + *is_static = had_static; + *_flags = flags; + return true; +onerr: + parseerror(parser, "parse error after variable qualifier"); + *cvq = CV_WRONG; + return true; +} + +static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out); +static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out) +{ + bool rv; + char *label = nullptr; + + /* skip the 'while' and get the body */ + if (!parser_next(parser)) { + if (OPTS_FLAG(LOOP_LABELS)) + parseerror(parser, "expected loop label or 'switch' operand in parenthesis"); + else + parseerror(parser, "expected 'switch' operand in parenthesis"); + return false; + } + + if (parser->tok == ':') { + if (!OPTS_FLAG(LOOP_LABELS)) + parseerror(parser, "labeled loops not activated, try using -floop-labels"); + if (!parser_next(parser) || parser->tok != TOKEN_IDENT) { + parseerror(parser, "expected loop label"); + return false; + } + label = util_strdup(parser_tokval(parser)); + if (!parser_next(parser)) { + mem_d(label); + parseerror(parser, "expected 'switch' operand in parenthesis"); + return false; + } + } + + if (parser->tok != '(') { + parseerror(parser, "expected 'switch' operand in parenthesis"); + return false; + } + + parser->breaks.push_back(label); + + rv = parse_switch_go(parser, block, out); + if (label) + mem_d(label); + if (parser->breaks.back() != label) { + parseerror(parser, "internal error: label stack corrupted"); + rv = false; + delete *out; + *out = nullptr; + } + else { + parser->breaks.pop_back(); + } + return rv; +} + +static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out) +{ + ast_expression *operand; + ast_value *opval; + ast_value *typevar; + ast_switch *switchnode; + ast_switch_case swcase; + + int cvq; + bool noref, is_static; + uint32_t qflags = 0; + + lex_ctx_t ctx = parser_ctx(parser); + + (void)block; /* not touching */ + (void)opval; + + /* parse into the expression */ + if (!parser_next(parser)) { + parseerror(parser, "expected switch operand"); + return false; + } + /* parse the operand */ + operand = parse_expression_leave(parser, false, false, false); + if (!operand) + return false; + + switchnode = new ast_switch(ctx, operand); + + /* closing paren */ + if (parser->tok != ')') { + delete switchnode; + parseerror(parser, "expected closing paren after 'switch' operand"); + return false; + } + + /* parse over the opening paren */ + if (!parser_next(parser) || parser->tok != '{') { + delete switchnode; + parseerror(parser, "expected list of cases"); + return false; + } + + if (!parser_next(parser)) { + delete switchnode; + parseerror(parser, "expected 'case' or 'default'"); + return false; + } + + /* new block; allow some variables to be declared here */ + parser_enterblock(parser); + while (true) { + typevar = nullptr; + if (parser->tok == TOKEN_IDENT) + typevar = parser_find_typedef(parser, parser_tokval(parser), 0); + if (typevar || parser->tok == TOKEN_TYPENAME) { + if (!parse_variable(parser, block, true, CV_NONE, typevar, false, false, 0, nullptr)) { + delete switchnode; + return false; + } + continue; + } + if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, nullptr)) + { + if (cvq == CV_WRONG) { + delete switchnode; + return false; + } + if (!parse_variable(parser, block, true, cvq, nullptr, noref, is_static, qflags, nullptr)) { + delete switchnode; + return false; + } + continue; + } + break; + } + + /* case list! */ + while (parser->tok != '}') { + ast_block *caseblock; + + if (!strcmp(parser_tokval(parser), "case")) { + if (!parser_next(parser)) { + delete switchnode; + parseerror(parser, "expected expression for case"); + return false; + } + swcase.m_value = parse_expression_leave(parser, false, false, false); + if (!swcase.m_value) { + delete switchnode; + parseerror(parser, "expected expression for case"); + return false; + } + if (!OPTS_FLAG(RELAXED_SWITCH)) { + if (!ast_istype(swcase.m_value, ast_value)) { /* || ((ast_value*)swcase.m_value)->m_cvq != CV_CONST) { */ + parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch"); + ast_unref(operand); + return false; + } + } + } + else if (!strcmp(parser_tokval(parser), "default")) { + swcase.m_value = nullptr; + if (!parser_next(parser)) { + delete switchnode; + parseerror(parser, "expected colon"); + return false; + } + } + else { + delete switchnode; + parseerror(parser, "expected 'case' or 'default'"); + return false; + } + + /* Now the colon and body */ + if (parser->tok != ':') { + if (swcase.m_value) ast_unref(swcase.m_value); + delete switchnode; + parseerror(parser, "expected colon"); + return false; + } + + if (!parser_next(parser)) { + if (swcase.m_value) ast_unref(swcase.m_value); + delete switchnode; + parseerror(parser, "expected statements or case"); + return false; + } + caseblock = new ast_block(parser_ctx(parser)); + if (!caseblock) { + if (swcase.m_value) ast_unref(swcase.m_value); + delete switchnode; + return false; + } + swcase.m_code = caseblock; + switchnode->m_cases.push_back(swcase); + while (true) { + ast_expression *expr; + if (parser->tok == '}') + break; + if (parser->tok == TOKEN_KEYWORD) { + if (!strcmp(parser_tokval(parser), "case") || + !strcmp(parser_tokval(parser), "default")) + { + break; + } + } + if (!parse_statement(parser, caseblock, &expr, true)) { + delete switchnode; + return false; + } + if (!expr) + continue; + if (!caseblock->addExpr(expr)) { + delete switchnode; + return false; + } + } + } + + parser_leaveblock(parser); + + /* closing paren */ + if (parser->tok != '}') { + delete switchnode; + parseerror(parser, "expected closing paren of case list"); + return false; + } + if (!parser_next(parser)) { + delete switchnode; + parseerror(parser, "parse error after switch"); + return false; + } + *out = switchnode; + return true; +} + +/* parse computed goto sides */ +static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) { + ast_expression *on_true; + ast_expression *on_false; + ast_expression *cond; + + if (!*side) + return nullptr; + + if (ast_istype(*side, ast_ternary)) { + ast_ternary *tern = (ast_ternary*)*side; + on_true = parse_goto_computed(parser, &tern->m_on_true); + on_false = parse_goto_computed(parser, &tern->m_on_false); + + if (!on_true || !on_false) { + parseerror(parser, "expected label or expression in ternary"); + if (on_true) ast_unref(on_true); + if (on_false) ast_unref(on_false); + return nullptr; + } + + cond = tern->m_cond; + tern->m_cond = nullptr; + delete tern; + *side = nullptr; + return new ast_ifthen(parser_ctx(parser), cond, on_true, on_false); + } else if (ast_istype(*side, ast_label)) { + ast_goto *gt = new ast_goto(parser_ctx(parser), ((ast_label*)*side)->m_name); + gt->setLabel(reinterpret_cast(*side)); + *side = nullptr; + return gt; + } + return nullptr; +} + +static bool parse_goto(parser_t *parser, ast_expression **out) +{ + ast_goto *gt = nullptr; + ast_expression *lbl; + + if (!parser_next(parser)) + return false; + + if (parser->tok != TOKEN_IDENT) { + ast_expression *expression; + + /* could be an expression i.e computed goto :-) */ + if (parser->tok != '(') { + parseerror(parser, "expected label name after `goto`"); + return false; + } + + /* failed to parse expression for goto */ + if (!(expression = parse_expression(parser, false, true)) || + !(*out = parse_goto_computed(parser, &expression))) { + parseerror(parser, "invalid goto expression"); + if(expression) + ast_unref(expression); + return false; + } + + return true; + } + + /* not computed goto */ + gt = new ast_goto(parser_ctx(parser), parser_tokval(parser)); + lbl = parser_find_label(parser, gt->m_name); + if (lbl) { + if (!ast_istype(lbl, ast_label)) { + parseerror(parser, "internal error: label is not an ast_label"); + delete gt; + return false; + } + gt->setLabel(reinterpret_cast(lbl)); + } + else + parser->gotos.push_back(gt); + + if (!parser_next(parser) || parser->tok != ';') { + parseerror(parser, "semicolon expected after goto label"); + return false; + } + if (!parser_next(parser)) { + parseerror(parser, "parse error after goto"); + return false; + } + + *out = gt; + return true; +} + +static bool parse_skipwhite(parser_t *parser) +{ + do { + if (!parser_next(parser)) + return false; + } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR); + return parser->tok < TOKEN_ERROR; +} + +static bool parse_eol(parser_t *parser) +{ + if (!parse_skipwhite(parser)) + return false; + return parser->tok == TOKEN_EOL; +} + +static bool parse_pragma_do(parser_t *parser) +{ + if (!parser_next(parser) || + parser->tok != TOKEN_IDENT || + strcmp(parser_tokval(parser), "pragma")) + { + parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser)); + return false; + } + if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) { + parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser)); + return false; + } + + if (!strcmp(parser_tokval(parser), "noref")) { + if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) { + parseerror(parser, "`noref` pragma requires an argument: 0 or 1"); + return false; + } + parser->noref = !!parser_token(parser)->constval.i; + if (!parse_eol(parser)) { + parseerror(parser, "parse error after `noref` pragma"); + return false; + } + } + else + { + (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser)); + + /* skip to eol */ + while (!parse_eol(parser)) { + parser_next(parser); + } + + return true; + } + + return true; +} + +static bool parse_pragma(parser_t *parser) +{ + bool rv; + parser->lex->flags.preprocessing = true; + parser->lex->flags.mergelines = true; + rv = parse_pragma_do(parser); + if (parser->tok != TOKEN_EOL) { + parseerror(parser, "junk after pragma"); + rv = false; + } + parser->lex->flags.preprocessing = false; + parser->lex->flags.mergelines = false; + if (!parser_next(parser)) { + parseerror(parser, "parse error after pragma"); + rv = false; + } + return rv; +} + +static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases) +{ + bool noref, is_static; + int cvq = CV_NONE; + uint32_t qflags = 0; + ast_value *typevar = nullptr; + char *vstring = nullptr; + + *out = nullptr; + + if (parser->tok == TOKEN_IDENT) + typevar = parser_find_typedef(parser, parser_tokval(parser), 0); + + if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS) + { + /* local variable */ + if (!block) { + parseerror(parser, "cannot declare a variable from here"); + return false; + } + if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) { + if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable")) + return false; + } + if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, nullptr)) + return false; + return true; + } + else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring)) + { + if (cvq == CV_WRONG) + return false; + return parse_variable(parser, block, false, cvq, nullptr, noref, is_static, qflags, vstring); + } + else if (parser->tok == TOKEN_KEYWORD) + { + if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype")) + { + char ty[1024]; + ast_value *tdef; + + if (!parser_next(parser)) { + parseerror(parser, "parse error after __builtin_debug_printtype"); + return false; + } + + if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0))) + { + ast_type_to_string(tdef, ty, sizeof(ty)); + con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->m_name.c_str(), ty); + if (!parser_next(parser)) { + parseerror(parser, "parse error after __builtin_debug_printtype typename argument"); + return false; + } + } + else + { + if (!parse_statement(parser, block, out, allow_cases)) + return false; + if (!*out) + con_out("__builtin_debug_printtype: got no output node\n"); + else + { + ast_type_to_string(*out, ty, sizeof(ty)); + con_out("__builtin_debug_printtype: `%s`\n", ty); + } + } + return true; + } + else if (!strcmp(parser_tokval(parser), "return")) + { + return parse_return(parser, block, out); + } + else if (!strcmp(parser_tokval(parser), "if")) + { + return parse_if(parser, block, out); + } + else if (!strcmp(parser_tokval(parser), "while")) + { + return parse_while(parser, block, out); + } + else if (!strcmp(parser_tokval(parser), "do")) + { + return parse_dowhile(parser, block, out); + } + else if (!strcmp(parser_tokval(parser), "for")) + { + if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) { + if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?")) + return false; + } + return parse_for(parser, block, out); + } + else if (!strcmp(parser_tokval(parser), "break")) + { + return parse_break_continue(parser, block, out, false); + } + else if (!strcmp(parser_tokval(parser), "continue")) + { + return parse_break_continue(parser, block, out, true); + } + else if (!strcmp(parser_tokval(parser), "switch")) + { + return parse_switch(parser, block, out); + } + else if (!strcmp(parser_tokval(parser), "case") || + !strcmp(parser_tokval(parser), "default")) + { + if (!allow_cases) { + parseerror(parser, "unexpected 'case' label"); + return false; + } + return true; + } + else if (!strcmp(parser_tokval(parser), "goto")) + { + return parse_goto(parser, out); + } + else if (!strcmp(parser_tokval(parser), "typedef")) + { + if (!parser_next(parser)) { + parseerror(parser, "expected type definition after 'typedef'"); + return false; + } + return parse_typedef(parser); + } + parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser)); + return false; + } + else if (parser->tok == '{') + { + ast_block *inner; + inner = parse_block(parser); + if (!inner) + return false; + *out = inner; + return true; + } + else if (parser->tok == ':') + { + size_t i; + ast_label *label; + if (!parser_next(parser)) { + parseerror(parser, "expected label name"); + return false; + } + if (parser->tok != TOKEN_IDENT) { + parseerror(parser, "label must be an identifier"); + return false; + } + label = (ast_label*)parser_find_label(parser, parser_tokval(parser)); + if (label) { + if (!label->m_undefined) { + parseerror(parser, "label `%s` already defined", label->m_name); + return false; + } + label->m_undefined = false; + } + else { + label = new ast_label(parser_ctx(parser), parser_tokval(parser), false); + parser->labels.push_back(label); + } + *out = label; + if (!parser_next(parser)) { + parseerror(parser, "parse error after label"); + return false; + } + for (i = 0; i < parser->gotos.size(); ++i) { + if (parser->gotos[i]->m_name == label->m_name) { + parser->gotos[i]->setLabel(label); + parser->gotos.erase(parser->gotos.begin() + i); + --i; + } + } + return true; + } + else if (parser->tok == ';') + { + if (!parser_next(parser)) { + parseerror(parser, "parse error after empty statement"); + return false; + } + return true; + } + else + { + lex_ctx_t ctx = parser_ctx(parser); + ast_expression *exp = parse_expression(parser, false, false); + if (!exp) + return false; + *out = exp; + if (!exp->m_side_effects) { + if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect")) + return false; + } + return true; + } +} + +static bool parse_enum(parser_t *parser) +{ + bool flag = false; + bool reverse = false; + qcfloat_t num = 0; + ast_value **values = nullptr; + ast_value *var = nullptr; + ast_value *asvalue; + + ast_expression *old; + + if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) { + parseerror(parser, "expected `{` or `:` after `enum` keyword"); + return false; + } + + /* enumeration attributes (can add more later) */ + if (parser->tok == ':') { + if (!parser_next(parser) || parser->tok != TOKEN_IDENT){ + parseerror(parser, "expected `flag` or `reverse` for enumeration attribute"); + return false; + } + + /* attributes? */ + if (!strcmp(parser_tokval(parser), "flag")) { + num = 1; + flag = true; + } + else if (!strcmp(parser_tokval(parser), "reverse")) { + reverse = true; + } + else { + parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser)); + return false; + } + + if (!parser_next(parser) || parser->tok != '{') { + parseerror(parser, "expected `{` after enum attribute "); + return false; + } + } + + while (true) { + if (!parser_next(parser) || parser->tok != TOKEN_IDENT) { + if (parser->tok == '}') { + /* allow an empty enum */ + break; + } + parseerror(parser, "expected identifier or `}`"); + goto onerror; + } + + old = parser_find_field(parser, parser_tokval(parser)); + if (!old) + old = parser_find_global(parser, parser_tokval(parser)); + if (old) { + parseerror(parser, "value `%s` has already been declared here: %s:%i", + parser_tokval(parser), old->m_context.file, old->m_context.line); + goto onerror; + } + + var = new ast_value(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT); + vec_push(values, var); + var->m_cvq = CV_CONST; + var->m_hasvalue = true; + + /* for flagged enumerations increment in POTs of TWO */ + var->m_constval.vfloat = (flag) ? (num *= 2) : (num ++); + parser_addglobal(parser, var->m_name, var); + + if (!parser_next(parser)) { + parseerror(parser, "expected `=`, `}` or comma after identifier"); + goto onerror; + } + + if (parser->tok == ',') + continue; + if (parser->tok == '}') + break; + if (parser->tok != '=') { + parseerror(parser, "expected `=`, `}` or comma after identifier"); + goto onerror; + } + + if (!parser_next(parser)) { + parseerror(parser, "expected expression after `=`"); + goto onerror; + } + + /* We got a value! */ + old = parse_expression_leave(parser, true, false, false); + asvalue = (ast_value*)old; + if (!ast_istype(old, ast_value) || asvalue->m_cvq != CV_CONST || !asvalue->m_hasvalue) { + compile_error(var->m_context, "constant value or expression expected"); + goto onerror; + } + num = (var->m_constval.vfloat = asvalue->m_constval.vfloat) + 1; + + if (parser->tok == '}') + break; + if (parser->tok != ',') { + parseerror(parser, "expected `}` or comma after expression"); + goto onerror; + } + } + + /* patch them all (for reversed attribute) */ + if (reverse) { + size_t i; + for (i = 0; i < vec_size(values); i++) + values[i]->m_constval.vfloat = vec_size(values) - i - 1; + } + + if (parser->tok != '}') { + parseerror(parser, "internal error: breaking without `}`"); + goto onerror; + } + + if (!parser_next(parser) || parser->tok != ';') { + parseerror(parser, "expected semicolon after enumeration"); + goto onerror; + } + + if (!parser_next(parser)) { + parseerror(parser, "parse error after enumeration"); + goto onerror; + } + + vec_free(values); + return true; + +onerror: + vec_free(values); + return false; +} + +static bool parse_block_into(parser_t *parser, ast_block *block) +{ + bool retval = true; + + parser_enterblock(parser); + + if (!parser_next(parser)) { /* skip the '{' */ + parseerror(parser, "expected function body"); + goto cleanup; + } + + while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR) + { + ast_expression *expr = nullptr; + if (parser->tok == '}') + break; + + if (!parse_statement(parser, block, &expr, false)) { + /* parseerror(parser, "parse error"); */ + block = nullptr; + goto cleanup; + } + if (!expr) + continue; + if (!block->addExpr(expr)) { + delete block; + block = nullptr; + goto cleanup; + } + } + + if (parser->tok != '}') { + block = nullptr; + } else { + (void)parser_next(parser); + } + +cleanup: + if (!parser_leaveblock(parser)) + retval = false; + return retval && !!block; +} + +static ast_block* parse_block(parser_t *parser) +{ + ast_block *block; + block = new ast_block(parser_ctx(parser)); + if (!block) + return nullptr; + if (!parse_block_into(parser, block)) { + delete block; + return nullptr; + } + return block; +} + +static bool parse_statement_or_block(parser_t *parser, ast_expression **out) +{ + if (parser->tok == '{') { + *out = parse_block(parser); + return !!*out; + } + return parse_statement(parser, nullptr, out, false); +} + +static bool create_vector_members(ast_value *var, ast_member **me) +{ + size_t i; + size_t len = var->m_name.length(); + + for (i = 0; i < 3; ++i) { + char *name = (char*)mem_a(len+3); + memcpy(name, var->m_name.c_str(), len); + name[len+0] = '_'; + name[len+1] = 'x'+i; + name[len+2] = 0; + me[i] = ast_member::make(var->m_context, var, i, name); + mem_d(name); + if (!me[i]) + break; + } + if (i == 3) + return true; + + /* unroll */ + do { delete me[--i]; } while(i); + return false; +} + +static bool parse_function_body(parser_t *parser, ast_value *var) +{ + ast_block *block = nullptr; + ast_function *func; + ast_function *old; + + ast_expression *framenum = nullptr; + ast_expression *nextthink = nullptr; + /* None of the following have to be deleted */ + ast_expression *fld_think = nullptr, *fld_nextthink = nullptr, *fld_frame = nullptr; + ast_expression *gbl_time = nullptr, *gbl_self = nullptr; + bool has_frame_think; + + bool retval = true; + + has_frame_think = false; + old = parser->function; + + if (var->m_flags & AST_FLAG_ALIAS) { + parseerror(parser, "function aliases cannot have bodies"); + return false; + } + + if (parser->gotos.size() || parser->labels.size()) { + parseerror(parser, "gotos/labels leaking"); + return false; + } + + if (!OPTS_FLAG(VARIADIC_ARGS) && var->m_flags & AST_FLAG_VARIADIC) { + if (parsewarning(parser, WARN_VARIADIC_FUNCTION, + "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)")) + { + return false; + } + } + + if (parser->tok == '[') { + /* got a frame definition: [ framenum, nextthink ] + * this translates to: + * self.frame = framenum; + * self.nextthink = time + 0.1; + * self.think = nextthink; + */ + nextthink = nullptr; + + fld_think = parser_find_field(parser, "think"); + fld_nextthink = parser_find_field(parser, "nextthink"); + fld_frame = parser_find_field(parser, "frame"); + if (!fld_think || !fld_nextthink || !fld_frame) { + parseerror(parser, "cannot use [frame,think] notation without the required fields"); + parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`"); + return false; + } + gbl_time = parser_find_global(parser, "time"); + gbl_self = parser_find_global(parser, "self"); + if (!gbl_time || !gbl_self) { + parseerror(parser, "cannot use [frame,think] notation without the required globals"); + parseerror(parser, "please declare the following globals: `time`, `self`"); + return false; + } + + if (!parser_next(parser)) + return false; + + framenum = parse_expression_leave(parser, true, false, false); + if (!framenum) { + parseerror(parser, "expected a framenumber constant in[frame,think] notation"); + return false; + } + if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->m_hasvalue) { + ast_unref(framenum); + parseerror(parser, "framenumber in [frame,think] notation must be a constant"); + return false; + } + + if (parser->tok != ',') { + ast_unref(framenum); + parseerror(parser, "expected comma after frame number in [frame,think] notation"); + parseerror(parser, "Got a %i\n", parser->tok); + return false; + } + + if (!parser_next(parser)) { + ast_unref(framenum); + return false; + } + + if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser))) + { + /* qc allows the use of not-yet-declared functions here + * - this automatically creates a prototype */ + ast_value *thinkfunc; + ast_expression *functype = fld_think->m_next; + + thinkfunc = new ast_value(parser_ctx(parser), parser_tokval(parser), functype->m_vtype); + if (!thinkfunc) { /* || !thinkfunc->adoptType(*functype)*/ + ast_unref(framenum); + parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser)); + return false; + } + thinkfunc->adoptType(*functype); + + if (!parser_next(parser)) { + ast_unref(framenum); + delete thinkfunc; + return false; + } + + parser_addglobal(parser, thinkfunc->m_name, thinkfunc); + + nextthink = thinkfunc; + + } else { + nextthink = parse_expression_leave(parser, true, false, false); + if (!nextthink) { + ast_unref(framenum); + parseerror(parser, "expected a think-function in [frame,think] notation"); + return false; + } + } + + if (!ast_istype(nextthink, ast_value)) { + parseerror(parser, "think-function in [frame,think] notation must be a constant"); + retval = false; + } + + if (retval && parser->tok != ']') { + parseerror(parser, "expected closing `]` for [frame,think] notation"); + retval = false; + } + + if (retval && !parser_next(parser)) { + retval = false; + } + + if (retval && parser->tok != '{') { + parseerror(parser, "a function body has to be declared after a [frame,think] declaration"); + retval = false; + } + + if (!retval) { + ast_unref(nextthink); + ast_unref(framenum); + return false; + } + + has_frame_think = true; + } + + block = new ast_block(parser_ctx(parser)); + if (!block) { + parseerror(parser, "failed to allocate block"); + if (has_frame_think) { + ast_unref(nextthink); + ast_unref(framenum); + } + return false; + } + + if (has_frame_think) { + if (!OPTS_FLAG(EMULATE_STATE)) { + ast_state *state_op = new ast_state(parser_ctx(parser), framenum, nextthink); + if (!block->addExpr(state_op)) { + parseerror(parser, "failed to generate state op for [frame,think]"); + ast_unref(nextthink); + ast_unref(framenum); + delete block; + return false; + } + } else { + /* emulate OP_STATE in code: */ + lex_ctx_t ctx; + ast_expression *self_frame; + ast_expression *self_nextthink; + ast_expression *self_think; + ast_expression *time_plus_1; + ast_store *store_frame; + ast_store *store_nextthink; + ast_store *store_think; + + float frame_delta = 1.0f / (float)OPTS_OPTION_U32(OPTION_STATE_FPS); + + ctx = parser_ctx(parser); + self_frame = new ast_entfield(ctx, gbl_self, fld_frame); + self_nextthink = new ast_entfield(ctx, gbl_self, fld_nextthink); + self_think = new ast_entfield(ctx, gbl_self, fld_think); + + time_plus_1 = new ast_binary(ctx, INSTR_ADD_F, + gbl_time, parser->m_fold.constgen_float(frame_delta, false)); + + if (!self_frame || !self_nextthink || !self_think || !time_plus_1) { + if (self_frame) delete self_frame; + if (self_nextthink) delete self_nextthink; + if (self_think) delete self_think; + if (time_plus_1) delete time_plus_1; + retval = false; + } + + if (retval) + { + store_frame = new ast_store(ctx, INSTR_STOREP_F, self_frame, framenum); + store_nextthink = new ast_store(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1); + store_think = new ast_store(ctx, INSTR_STOREP_FNC, self_think, nextthink); + + if (!store_frame) { + delete self_frame; + retval = false; + } + if (!store_nextthink) { + delete self_nextthink; + retval = false; + } + if (!store_think) { + delete self_think; + retval = false; + } + if (!retval) { + if (store_frame) delete store_frame; + if (store_nextthink) delete store_nextthink; + if (store_think) delete store_think; + retval = false; + } + if (!block->addExpr(store_frame) || + !block->addExpr(store_nextthink) || + !block->addExpr(store_think)) + { + retval = false; + } + } + + if (!retval) { + parseerror(parser, "failed to generate code for [frame,think]"); + ast_unref(nextthink); + ast_unref(framenum); + delete block; + return false; + } + } + } + + if (var->m_hasvalue) { + if (!(var->m_flags & AST_FLAG_ACCUMULATE)) { + parseerror(parser, "function `%s` declared with multiple bodies", var->m_name); + delete block; + goto enderr; + } + func = var->m_constval.vfunc; + + if (!func) { + parseerror(parser, "internal error: nullptr function: `%s`", var->m_name); + delete block; + goto enderr; + } + } else { + func = ast_function::make(var->m_context, var->m_name, var); + + if (!func) { + parseerror(parser, "failed to allocate function for `%s`", var->m_name); + delete block; + goto enderr; + } + parser->functions.push_back(func); + } + + parser_enterblock(parser); + + for (auto &it : var->m_type_params) { + size_t e; + ast_member *me[3]; + + if (it->m_vtype != TYPE_VECTOR && + (it->m_vtype != TYPE_FIELD || + it->m_next->m_vtype != TYPE_VECTOR)) + { + continue; + } + + if (!create_vector_members(it.get(), me)) { + delete block; + goto enderrfn; + } + + for (e = 0; e < 3; ++e) { + parser_addlocal(parser, me[e]->m_name, me[e]); + block->collect(me[e]); + } + } + + if (var->m_argcounter && !func->m_argc) { + ast_value *argc = new ast_value(var->m_context, var->m_argcounter, TYPE_FLOAT); + parser_addlocal(parser, argc->m_name, argc); + func->m_argc.reset(argc); + } + + if (OPTS_FLAG(VARIADIC_ARGS) && var->m_flags & AST_FLAG_VARIADIC && !func->m_varargs) { + char name[1024]; + ast_value *varargs = new ast_value(var->m_context, "reserved:va_args", TYPE_ARRAY); + varargs->m_flags |= AST_FLAG_IS_VARARG; + varargs->m_next = new ast_value(var->m_context, "", TYPE_VECTOR); + varargs->m_count = 0; + util_snprintf(name, sizeof(name), "%s##va##SET", var->m_name.c_str()); + if (!parser_create_array_setter_proto(parser, varargs, name)) { + delete varargs; + delete block; + goto enderrfn; + } + util_snprintf(name, sizeof(name), "%s##va##GET", var->m_name.c_str()); + if (!parser_create_array_getter_proto(parser, varargs, varargs->m_next, name)) { + delete varargs; + delete block; + goto enderrfn; + } + func->m_varargs.reset(varargs); + func->m_fixedparams = (ast_value*)parser->m_fold.constgen_float(var->m_type_params.size(), false); + } + + parser->function = func; + if (!parse_block_into(parser, block)) { + delete block; + goto enderrfn; + } + + func->m_blocks.emplace_back(block); + + parser->function = old; + if (!parser_leaveblock(parser)) + retval = false; + if (vec_size(parser->variables) != PARSER_HT_LOCALS) { + parseerror(parser, "internal error: local scopes left"); + retval = false; + } + + if (parser->tok == ';') + return parser_next(parser); + else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) + parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)"); + return retval; + +enderrfn: + (void)!parser_leaveblock(parser); + parser->functions.pop_back(); + delete func; + var->m_constval.vfunc = nullptr; + +enderr: + parser->function = old; + return false; +} + +static ast_expression *array_accessor_split( + parser_t *parser, + ast_value *array, + ast_value *index, + size_t middle, + ast_expression *left, + ast_expression *right + ) +{ + ast_ifthen *ifthen; + ast_binary *cmp; + + lex_ctx_t ctx = array->m_context; + + if (!left || !right) { + if (left) delete left; + if (right) delete right; + return nullptr; + } + + cmp = new ast_binary(ctx, INSTR_LT, + index, + parser->m_fold.constgen_float(middle, false)); + if (!cmp) { + delete left; + delete right; + parseerror(parser, "internal error: failed to create comparison for array setter"); + return nullptr; + } + + ifthen = new ast_ifthen(ctx, cmp, left, right); + if (!ifthen) { + delete cmp; /* will delete left and right */ + parseerror(parser, "internal error: failed to create conditional jump for array setter"); + return nullptr; + } + + return ifthen; +} + +static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend) +{ + lex_ctx_t ctx = array->m_context; + + if (from+1 == afterend) { + /* set this value */ + ast_block *block; + ast_return *ret; + ast_array_index *subscript; + ast_store *st; + int assignop = type_store_instr[value->m_vtype]; + + if (value->m_vtype == TYPE_FIELD && value->m_next->m_vtype == TYPE_VECTOR) + assignop = INSTR_STORE_V; + + subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false)); + if (!subscript) + return nullptr; + + st = new ast_store(ctx, assignop, subscript, value); + if (!st) { + delete subscript; + return nullptr; + } + + block = new ast_block(ctx); + if (!block) { + delete st; + return nullptr; + } + + if (!block->addExpr(st)) { + delete block; + return nullptr; + } + + ret = new ast_return(ctx, nullptr); + if (!ret) { + delete block; + return nullptr; + } + + if (!block->addExpr(ret)) { + delete block; + return nullptr; + } + + return block; + } else { + ast_expression *left, *right; + size_t diff = afterend - from; + size_t middle = from + diff/2; + left = array_setter_node(parser, array, index, value, from, middle); + right = array_setter_node(parser, array, index, value, middle, afterend); + return array_accessor_split(parser, array, index, middle, left, right); + } +} + +static ast_expression *array_field_setter_node( + parser_t *parser, + ast_value *array, + ast_value *entity, + ast_value *index, + ast_value *value, + size_t from, + size_t afterend) +{ + lex_ctx_t ctx = array->m_context; + + if (from+1 == afterend) { + /* set this value */ + ast_block *block; + ast_return *ret; + ast_entfield *entfield; + ast_array_index *subscript; + ast_store *st; + int assignop = type_storep_instr[value->m_vtype]; + + if (value->m_vtype == TYPE_FIELD && value->m_next->m_vtype == TYPE_VECTOR) + assignop = INSTR_STOREP_V; + + subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false)); + if (!subscript) + return nullptr; + + subscript->m_next = new ast_expression(ast_copy_type, subscript->m_context, *subscript); + subscript->m_vtype = TYPE_FIELD; + + entfield = new ast_entfield(ctx, entity, subscript, subscript); + if (!entfield) { + delete subscript; + return nullptr; + } + + st = new ast_store(ctx, assignop, entfield, value); + if (!st) { + delete entfield; + return nullptr; + } + + block = new ast_block(ctx); + if (!block) { + delete st; + return nullptr; + } + + if (!block->addExpr(st)) { + delete block; + return nullptr; + } + + ret = new ast_return(ctx, nullptr); + if (!ret) { + delete block; + return nullptr; + } + + if (!block->addExpr(ret)) { + delete block; + return nullptr; + } + + return block; + } else { + ast_expression *left, *right; + size_t diff = afterend - from; + size_t middle = from + diff/2; + left = array_field_setter_node(parser, array, entity, index, value, from, middle); + right = array_field_setter_node(parser, array, entity, index, value, middle, afterend); + return array_accessor_split(parser, array, index, middle, left, right); + } +} + +static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend) +{ + lex_ctx_t ctx = array->m_context; + + if (from+1 == afterend) { + ast_return *ret; + ast_array_index *subscript; + + subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false)); + if (!subscript) + return nullptr; + + ret = new ast_return(ctx, subscript); + if (!ret) { + delete subscript; + return nullptr; + } + + return ret; + } else { + ast_expression *left, *right; + size_t diff = afterend - from; + size_t middle = from + diff/2; + left = array_getter_node(parser, array, index, from, middle); + right = array_getter_node(parser, array, index, middle, afterend); + return array_accessor_split(parser, array, index, middle, left, right); + } +} + +static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out) +{ + ast_function *func = nullptr; + ast_value *fval = nullptr; + ast_block *body = nullptr; + + fval = new ast_value(array->m_context, funcname, TYPE_FUNCTION); + if (!fval) { + parseerror(parser, "failed to create accessor function value"); + return false; + } + fval->m_flags &= ~(AST_FLAG_COVERAGE_MASK); + + func = ast_function::make(array->m_context, funcname, fval); + if (!func) { + delete fval; + parseerror(parser, "failed to create accessor function node"); + return false; + } + + body = new ast_block(array->m_context); + if (!body) { + parseerror(parser, "failed to create block for array accessor"); + delete fval; + delete func; + return false; + } + + func->m_blocks.emplace_back(body); + *out = fval; + + parser->accessors.push_back(fval); + + return true; +} + +static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname) +{ + ast_value *index = nullptr; + ast_value *value = nullptr; + ast_function *func; + ast_value *fval; + + if (!ast_istype(array->m_next, ast_value)) { + parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type"); + return nullptr; + } + + if (!parser_create_array_accessor(parser, array, funcname, &fval)) + return nullptr; + func = fval->m_constval.vfunc; + fval->m_next = new ast_value(array->m_context, "", TYPE_VOID); + + index = new ast_value(array->m_context, "index", TYPE_FLOAT); + value = new ast_value(ast_copy_type, *(ast_value*)array->m_next); + + if (!index || !value) { + parseerror(parser, "failed to create locals for array accessor"); + goto cleanup; + } + value->m_name = "value"; // not important + fval->m_type_params.emplace_back(index); + fval->m_type_params.emplace_back(value); + + array->m_setter = fval; + return fval; +cleanup: + if (index) delete index; + if (value) delete value; + delete func; + delete fval; + return nullptr; +} + +static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array) +{ + ast_expression *root = nullptr; + root = array_setter_node(parser, array, + array->m_setter->m_type_params[0].get(), + array->m_setter->m_type_params[1].get(), + 0, array->m_count); + if (!root) { + parseerror(parser, "failed to build accessor search tree"); + return false; + } + if (!array->m_setter->m_constval.vfunc->m_blocks[0].get()->addExpr(root)) { + delete root; + return false; + } + return true; +} + +static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname) +{ + if (!parser_create_array_setter_proto(parser, array, funcname)) + return false; + return parser_create_array_setter_impl(parser, array); +} + +static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname) +{ + ast_expression *root = nullptr; + ast_value *entity = nullptr; + ast_value *index = nullptr; + ast_value *value = nullptr; + ast_function *func; + ast_value *fval; + + if (!ast_istype(array->m_next, ast_value)) { + parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type"); + return false; + } + + if (!parser_create_array_accessor(parser, array, funcname, &fval)) + return false; + func = fval->m_constval.vfunc; + fval->m_next = new ast_value(array->m_context, "", TYPE_VOID); + + entity = new ast_value(array->m_context, "entity", TYPE_ENTITY); + index = new ast_value(array->m_context, "index", TYPE_FLOAT); + value = new ast_value(ast_copy_type, *(ast_value*)array->m_next); + if (!entity || !index || !value) { + parseerror(parser, "failed to create locals for array accessor"); + goto cleanup; + } + value->m_name = "value"; // not important + fval->m_type_params.emplace_back(entity); + fval->m_type_params.emplace_back(index); + fval->m_type_params.emplace_back(value); + + root = array_field_setter_node(parser, array, entity, index, value, 0, array->m_count); + if (!root) { + parseerror(parser, "failed to build accessor search tree"); + goto cleanup; + } + + array->m_setter = fval; + return func->m_blocks[0].get()->addExpr(root); +cleanup: + if (entity) delete entity; + if (index) delete index; + if (value) delete value; + if (root) delete root; + delete func; + delete fval; + return false; +} + +static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname) +{ + ast_value *index = nullptr; + ast_value *fval; + ast_function *func; + + /* NOTE: checking array->m_next rather than elemtype since + * for fields elemtype is a temporary fieldtype. + */ + if (!ast_istype(array->m_next, ast_value)) { + parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type"); + return nullptr; + } + + if (!parser_create_array_accessor(parser, array, funcname, &fval)) + return nullptr; + func = fval->m_constval.vfunc; + fval->m_next = new ast_expression(ast_copy_type, array->m_context, *elemtype); + + index = new ast_value(array->m_context, "index", TYPE_FLOAT); + + if (!index) { + parseerror(parser, "failed to create locals for array accessor"); + goto cleanup; + } + fval->m_type_params.emplace_back(index); + + array->m_getter = fval; + return fval; +cleanup: + if (index) delete index; + delete func; + delete fval; + return nullptr; +} + +static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array) +{ + ast_expression *root = nullptr; + + root = array_getter_node(parser, array, array->m_getter->m_type_params[0].get(), 0, array->m_count); + if (!root) { + parseerror(parser, "failed to build accessor search tree"); + return false; + } + if (!array->m_getter->m_constval.vfunc->m_blocks[0].get()->addExpr(root)) { + delete root; + return false; + } + return true; +} + +static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname) +{ + if (!parser_create_array_getter_proto(parser, array, elemtype, funcname)) + return false; + return parser_create_array_getter_impl(parser, array); +} + +static ast_value *parse_parameter_list(parser_t *parser, ast_value *var) +{ + lex_ctx_t ctx = parser_ctx(parser); + std::vector> params; + ast_value *fval; + bool first = true; + bool variadic = false; + ast_value *varparam = nullptr; + char *argcounter = nullptr; + + /* for the sake of less code we parse-in in this function */ + if (!parser_next(parser)) { + delete var; + parseerror(parser, "expected parameter list"); + return nullptr; + } + + /* parse variables until we hit a closing paren */ + while (parser->tok != ')') { + bool is_varargs = false; + + if (!first) { + /* there must be commas between them */ + if (parser->tok != ',') { + parseerror(parser, "expected comma or end of parameter list"); + goto on_error; + } + if (!parser_next(parser)) { + parseerror(parser, "expected parameter"); + goto on_error; + } + } + first = false; + + ast_value *param = parse_typename(parser, nullptr, nullptr, &is_varargs); + if (!param && !is_varargs) + goto on_error; + if (is_varargs) { + /* '...' indicates a varargs function */ + variadic = true; + if (parser->tok != ')' && parser->tok != TOKEN_IDENT) { + parseerror(parser, "`...` must be the last parameter of a variadic function declaration"); + goto on_error; + } + if (parser->tok == TOKEN_IDENT) { + argcounter = util_strdup(parser_tokval(parser)); + if (!parser_next(parser) || parser->tok != ')') { + parseerror(parser, "`...` must be the last parameter of a variadic function declaration"); + goto on_error; + } + } + } else { + params.emplace_back(param); + if (param->m_vtype >= TYPE_VARIANT) { + char tname[1024]; /* typename is reserved in C++ */ + ast_type_to_string(param, tname, sizeof(tname)); + parseerror(parser, "type not supported as part of a parameter list: %s", tname); + goto on_error; + } + /* type-restricted varargs */ + if (parser->tok == TOKEN_DOTS) { + variadic = true; + varparam = params.back().release(); + params.pop_back(); + if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) { + parseerror(parser, "`...` must be the last parameter of a variadic function declaration"); + goto on_error; + } + if (parser->tok == TOKEN_IDENT) { + argcounter = util_strdup(parser_tokval(parser)); + param->m_name = argcounter; + if (!parser_next(parser) || parser->tok != ')') { + parseerror(parser, "`...` must be the last parameter of a variadic function declaration"); + goto on_error; + } + } + } + if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC && param->m_name[0] == '<') { + parseerror(parser, "parameter name omitted"); + goto on_error; + } + } + } + + if (params.size() == 1 && params[0]->m_vtype == TYPE_VOID) + params.clear(); + + /* sanity check */ + if (params.size() > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) + (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard"); + + /* parse-out */ + if (!parser_next(parser)) { + parseerror(parser, "parse error after typename"); + goto on_error; + } + + /* now turn 'var' into a function type */ + fval = new ast_value(ctx, "", TYPE_FUNCTION); + fval->m_next = var; + if (variadic) + fval->m_flags |= AST_FLAG_VARIADIC; + var = fval; + + var->m_type_params = move(params); + var->m_varparam = varparam; + var->m_argcounter = argcounter; + + return var; + +on_error: + if (argcounter) + mem_d(argcounter); + if (varparam) + delete varparam; + delete var; + return nullptr; +} + +static ast_value *parse_arraysize(parser_t *parser, ast_value *var) +{ + ast_expression *cexp; + ast_value *cval, *tmp; + lex_ctx_t ctx; + + ctx = parser_ctx(parser); + + if (!parser_next(parser)) { + delete var; + parseerror(parser, "expected array-size"); + return nullptr; + } + + if (parser->tok != ']') { + cexp = parse_expression_leave(parser, true, false, false); + + if (!cexp || !ast_istype(cexp, ast_value)) { + if (cexp) + ast_unref(cexp); + delete var; + parseerror(parser, "expected array-size as constant positive integer"); + return nullptr; + } + cval = (ast_value*)cexp; + } + else { + cexp = nullptr; + cval = nullptr; + } + + tmp = new ast_value(ctx, "", TYPE_ARRAY); + tmp->m_next = var; + var = tmp; + + if (cval) { + if (cval->m_vtype == TYPE_INTEGER) + tmp->m_count = cval->m_constval.vint; + else if (cval->m_vtype == TYPE_FLOAT) + tmp->m_count = cval->m_constval.vfloat; + else { + ast_unref(cexp); + delete var; + parseerror(parser, "array-size must be a positive integer constant"); + return nullptr; + } + + ast_unref(cexp); + } else { + var->m_count = -1; + var->m_flags |= AST_FLAG_ARRAY_INIT; + } + + if (parser->tok != ']') { + delete var; + parseerror(parser, "expected ']' after array-size"); + return nullptr; + } + if (!parser_next(parser)) { + delete var; + parseerror(parser, "error after parsing array size"); + return nullptr; + } + return var; +} + +/* Parse a complete typename. + * for single-variables (ie. function parameters or typedefs) storebase should be nullptr + * but when parsing variables separated by comma + * 'storebase' should point to where the base-type should be kept. + * The base type makes up every bit of type information which comes *before* the + * variable name. + * + * NOTE: The value must either be named, have a nullptr name, or a name starting + * with '<'. In the first case, this will be the actual variable or type + * name, in the other cases it is assumed that the name will appear + * later, and an error is generated otherwise. + * + * The following will be parsed in its entirety: + * void() foo() + * The 'basetype' in this case is 'void()' + * and if there's a comma after it, say: + * void() foo(), bar + * then the type-information 'void()' can be stored in 'storebase' + */ +static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg) +{ + ast_value *var, *tmp; + lex_ctx_t ctx; + + const char *name = nullptr; + bool isfield = false; + bool wasarray = false; + size_t morefields = 0; + + bool vararg = (parser->tok == TOKEN_DOTS); + + ctx = parser_ctx(parser); + + /* types may start with a dot */ + if (parser->tok == '.' || parser->tok == TOKEN_DOTS) { + isfield = true; + if (parser->tok == TOKEN_DOTS) + morefields += 2; + /* if we parsed a dot we need a typename now */ + if (!parser_next(parser)) { + parseerror(parser, "expected typename for field definition"); + return nullptr; + } + + /* Further dots are handled seperately because they won't be part of the + * basetype + */ + while (true) { + if (parser->tok == '.') + ++morefields; + else if (parser->tok == TOKEN_DOTS) + morefields += 3; + else + break; + vararg = false; + if (!parser_next(parser)) { + parseerror(parser, "expected typename for field definition"); + return nullptr; + } + } + } + if (parser->tok == TOKEN_IDENT) + cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0); + if (!cached_typedef && parser->tok != TOKEN_TYPENAME) { + if (vararg && is_vararg) { + *is_vararg = true; + return nullptr; + } + parseerror(parser, "expected typename"); + return nullptr; + } + + /* generate the basic type value */ + if (cached_typedef) { + var = new ast_value(ast_copy_type, *cached_typedef); + var->m_name = ""; + } else + var = new ast_value(ctx, "", parser_token(parser)->constval.t); + + for (; morefields; --morefields) { + tmp = new ast_value(ctx, "<.type>", TYPE_FIELD); + tmp->m_next = var; + var = tmp; + } + + /* do not yet turn into a field - remember: + * .void() foo; is a field too + * .void()() foo; is a function + */ + + /* parse on */ + if (!parser_next(parser)) { + delete var; + parseerror(parser, "parse error after typename"); + return nullptr; + } + + /* an opening paren now starts the parameter-list of a function + * this is where original-QC has parameter lists. + * We allow a single parameter list here. + * Much like fteqcc we don't allow `float()() x` + */ + if (parser->tok == '(') { + var = parse_parameter_list(parser, var); + if (!var) + return nullptr; + } + + /* store the base if requested */ + if (storebase) { + *storebase = new ast_value(ast_copy_type, *var); + if (isfield) { + tmp = new ast_value(ctx, "", TYPE_FIELD); + tmp->m_next = *storebase; + *storebase = tmp; + } + } + + /* there may be a name now */ + if (parser->tok == TOKEN_IDENT || parser->tok == TOKEN_KEYWORD) { + if (!strcmp(parser_tokval(parser), "break")) + (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)"); + else if (parser->tok == TOKEN_KEYWORD) + goto leave; + + name = util_strdup(parser_tokval(parser)); + + /* parse on */ + if (!parser_next(parser)) { + delete var; + mem_d(name); + parseerror(parser, "error after variable or field declaration"); + return nullptr; + } + } + + leave: + /* now this may be an array */ + if (parser->tok == '[') { + wasarray = true; + var = parse_arraysize(parser, var); + if (!var) { + if (name) mem_d(name); + return nullptr; + } + } + + /* This is the point where we can turn it into a field */ + if (isfield) { + /* turn it into a field if desired */ + tmp = new ast_value(ctx, "", TYPE_FIELD); + tmp->m_next = var; + var = tmp; + } + + /* now there may be function parens again */ + if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) + parseerror(parser, "C-style function syntax is not allowed in -std=qcc"); + if (parser->tok == '(' && wasarray) + parseerror(parser, "arrays as part of a return type is not supported"); + while (parser->tok == '(') { + var = parse_parameter_list(parser, var); + if (!var) { + if (name) mem_d(name); + return nullptr; + } + } + + /* finally name it */ + if (name) { + var->m_name = name; + // free the name, ast_value_set_name duplicates + mem_d(name); + } + + return var; +} + +static bool parse_typedef(parser_t *parser) +{ + ast_value *typevar, *oldtype; + ast_expression *old; + + typevar = parse_typename(parser, nullptr, nullptr, nullptr); + + if (!typevar) + return false; + + // while parsing types, the ast_value's get named '' + if (!typevar->m_name.length() || typevar->m_name[0] == '<') { + parseerror(parser, "missing name in typedef"); + delete typevar; + return false; + } + + if ( (old = parser_find_var(parser, typevar->m_name)) ) { + parseerror(parser, "cannot define a type with the same name as a variable: %s\n" + " -> `%s` has been declared here: %s:%i", + typevar->m_name, old->m_context.file, old->m_context.line); + delete typevar; + return false; + } + + if ( (oldtype = parser_find_typedef(parser, typevar->m_name, vec_last(parser->_blocktypedefs))) ) { + parseerror(parser, "type `%s` has already been declared here: %s:%i", + typevar->m_name, oldtype->m_context.file, oldtype->m_context.line); + delete typevar; + return false; + } + + vec_push(parser->_typedefs, typevar); + util_htset(vec_last(parser->typedefs), typevar->m_name.c_str(), typevar); + + if (parser->tok != ';') { + parseerror(parser, "expected semicolon after typedef"); + return false; + } + if (!parser_next(parser)) { + parseerror(parser, "parse error after typedef"); + return false; + } + + return true; +} + +static const char *cvq_to_str(int cvq) { + switch (cvq) { + case CV_NONE: return "none"; + case CV_VAR: return "`var`"; + case CV_CONST: return "`const`"; + default: return ""; + } +} + +static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto) +{ + bool av, ao; + if (proto->m_cvq != var->m_cvq) { + if (!(proto->m_cvq == CV_CONST && var->m_cvq == CV_NONE && + !OPTS_FLAG(INITIALIZED_NONCONSTANTS) && + parser->tok == '=')) + { + return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS, + "`%s` declared with different qualifiers: %s\n" + " -> previous declaration here: %s:%i uses %s", + var->m_name, cvq_to_str(var->m_cvq), + proto->m_context.file, proto->m_context.line, + cvq_to_str(proto->m_cvq)); + } + } + av = (var ->m_flags & AST_FLAG_NORETURN); + ao = (proto->m_flags & AST_FLAG_NORETURN); + if (!av != !ao) { + return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES, + "`%s` declared with different attributes%s\n" + " -> previous declaration here: %s:%i", + var->m_name, (av ? ": noreturn" : ""), + proto->m_context.file, proto->m_context.line, + (ao ? ": noreturn" : "")); + } + return true; +} + +static bool create_array_accessors(parser_t *parser, ast_value *var) +{ + char name[1024]; + util_snprintf(name, sizeof(name), "%s##SET", var->m_name.c_str()); + if (!parser_create_array_setter(parser, var, name)) + return false; + util_snprintf(name, sizeof(name), "%s##GET", var->m_name.c_str()); + if (!parser_create_array_getter(parser, var, var->m_next, name)) + return false; + return true; +} + +static bool parse_array(parser_t *parser, ast_value *array) +{ + size_t i; + if (array->m_initlist.size()) { + parseerror(parser, "array already initialized elsewhere"); + return false; + } + if (!parser_next(parser)) { + parseerror(parser, "parse error in array initializer"); + return false; + } + i = 0; + while (parser->tok != '}') { + ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false); + if (!v) + return false; + if (!ast_istype(v, ast_value) || !v->m_hasvalue || v->m_cvq != CV_CONST) { + ast_unref(v); + parseerror(parser, "initializing element must be a compile time constant"); + return false; + } + array->m_initlist.push_back(v->m_constval); + if (v->m_vtype == TYPE_STRING) { + array->m_initlist[i].vstring = util_strdupe(array->m_initlist[i].vstring); + ++i; + } + ast_unref(v); + if (parser->tok == '}') + break; + if (parser->tok != ',' || !parser_next(parser)) { + parseerror(parser, "expected comma or '}' in element list"); + return false; + } + } + if (!parser_next(parser) || parser->tok != ';') { + parseerror(parser, "expected semicolon after initializer, got %s"); + return false; + } + /* + if (!parser_next(parser)) { + parseerror(parser, "parse error after initializer"); + return false; + } + */ + + if (array->m_flags & AST_FLAG_ARRAY_INIT) { + if (array->m_count != (size_t)-1) { + parseerror(parser, "array `%s' has already been initialized with %u elements", + array->m_name, (unsigned)array->m_count); + } + array->m_count = array->m_initlist.size(); + if (!create_array_accessors(parser, array)) + return false; + } + return true; +} + +static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool is_static, uint32_t qflags, char *vstring) +{ + ast_value *var; + ast_value *proto; + ast_expression *old; + bool was_end; + size_t i; + + ast_value *basetype = nullptr; + bool retval = true; + bool isparam = false; + bool isvector = false; + bool cleanvar = true; + bool wasarray = false; + + ast_member *me[3] = { nullptr, nullptr, nullptr }; + ast_member *last_me[3] = { nullptr, nullptr, nullptr }; + + if (!localblock && is_static) + parseerror(parser, "`static` qualifier is not supported in global scope"); + + /* get the first complete variable */ + var = parse_typename(parser, &basetype, cached_typedef, nullptr); + if (!var) { + if (basetype) + delete basetype; + return false; + } + + /* while parsing types, the ast_value's get named '' */ + if (!var->m_name.length() || var->m_name[0] == '<') { + parseerror(parser, "declaration does not declare anything"); + if (basetype) + delete basetype; + return false; + } + + while (true) { + proto = nullptr; + wasarray = false; + + /* Part 0: finish the type */ + if (parser->tok == '(') { + if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) + parseerror(parser, "C-style function syntax is not allowed in -std=qcc"); + var = parse_parameter_list(parser, var); + if (!var) { + retval = false; + goto cleanup; + } + } + /* we only allow 1-dimensional arrays */ + if (parser->tok == '[') { + wasarray = true; + var = parse_arraysize(parser, var); + if (!var) { + retval = false; + goto cleanup; + } + } + if (parser->tok == '(' && wasarray) { + parseerror(parser, "arrays as part of a return type is not supported"); + /* we'll still parse the type completely for now */ + } + /* for functions returning functions */ + while (parser->tok == '(') { + if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) + parseerror(parser, "C-style function syntax is not allowed in -std=qcc"); + var = parse_parameter_list(parser, var); + if (!var) { + retval = false; + goto cleanup; + } + } + + var->m_cvq = qualifier; + if (qflags & AST_FLAG_COVERAGE) /* specified in QC, drop our default */ + var->m_flags &= ~(AST_FLAG_COVERAGE_MASK); + var->m_flags |= qflags; + + /* + * store the vstring back to var for alias and + * deprecation messages. + */ + if (var->m_flags & AST_FLAG_DEPRECATED || + var->m_flags & AST_FLAG_ALIAS) + var->m_desc = vstring; + + if (parser_find_global(parser, var->m_name) && var->m_flags & AST_FLAG_ALIAS) { + parseerror(parser, "function aliases cannot be forward declared"); + retval = false; + goto cleanup; + } + + + /* Part 1: + * check for validity: (end_sys_..., multiple-definitions, prototypes, ...) + * Also: if there was a prototype, `var` will be deleted and set to `proto` which + * is then filled with the previous definition and the parameter-names replaced. + */ + if (var->m_name == "nil") { + if (OPTS_FLAG(UNTYPED_NIL)) { + if (!localblock || !OPTS_FLAG(PERMISSIVE)) + parseerror(parser, "name `nil` not allowed (try -fpermissive)"); + } else + (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved"); + } + if (!localblock) { + /* Deal with end_sys_ vars */ + was_end = false; + if (var->m_name == "end_sys_globals") { + var->m_uses++; + parser->crc_globals = parser->globals.size(); + was_end = true; + } + else if (var->m_name == "end_sys_fields") { + var->m_uses++; + parser->crc_fields = parser->fields.size(); + was_end = true; + } + if (was_end && var->m_vtype == TYPE_FIELD) { + if (parsewarning(parser, WARN_END_SYS_FIELDS, + "global '%s' hint should not be a field", + parser_tokval(parser))) + { + retval = false; + goto cleanup; + } + } + + if (!nofields && var->m_vtype == TYPE_FIELD) + { + /* deal with field declarations */ + old = parser_find_field(parser, var->m_name); + if (old) { + if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i", + var->m_name, old->m_context.file, (int)old->m_context.line)) + { + retval = false; + goto cleanup; + } + delete var; + var = nullptr; + goto skipvar; + /* + parseerror(parser, "field `%s` already declared here: %s:%i", + var->m_name, old->m_context.file, old->m_context.line); + retval = false; + goto cleanup; + */ + } + if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) && + (old = parser_find_global(parser, var->m_name))) + { + parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc"); + parseerror(parser, "field `%s` already declared here: %s:%i", + var->m_name, old->m_context.file, old->m_context.line); + retval = false; + goto cleanup; + } + } + else + { + /* deal with other globals */ + old = parser_find_global(parser, var->m_name); + if (old && var->m_vtype == TYPE_FUNCTION && old->m_vtype == TYPE_FUNCTION) + { + /* This is a function which had a prototype */ + if (!ast_istype(old, ast_value)) { + parseerror(parser, "internal error: prototype is not an ast_value"); + retval = false; + goto cleanup; + } + proto = (ast_value*)old; + proto->m_desc = var->m_desc; + if (!proto->compareType(*var)) { + parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i", + proto->m_name, + proto->m_context.file, proto->m_context.line); + retval = false; + goto cleanup; + } + /* we need the new parameter-names */ + for (i = 0; i < proto->m_type_params.size(); ++i) + proto->m_type_params[i]->m_name = var->m_type_params[i]->m_name; + if (!parser_check_qualifiers(parser, var, proto)) { + retval = false; + proto = nullptr; + goto cleanup; + } + proto->m_flags |= var->m_flags; + delete var; + var = proto; + } + else + { + /* other globals */ + if (old) { + if (parsewarning(parser, WARN_DOUBLE_DECLARATION, + "global `%s` already declared here: %s:%i", + var->m_name, old->m_context.file, old->m_context.line)) + { + retval = false; + goto cleanup; + } + if (old->m_flags & AST_FLAG_FINAL_DECL) { + parseerror(parser, "cannot redeclare variable `%s`, declared final here: %s:%i", + var->m_name, old->m_context.file, old->m_context.line); + retval = false; + goto cleanup; + } + proto = (ast_value*)old; + if (!ast_istype(old, ast_value)) { + parseerror(parser, "internal error: not an ast_value"); + retval = false; + proto = nullptr; + goto cleanup; + } + if (!parser_check_qualifiers(parser, var, proto)) { + retval = false; + proto = nullptr; + goto cleanup; + } + proto->m_flags |= var->m_flags; + /* copy the context for finals, + * so the error can show where it was actually made 'final' + */ + if (proto->m_flags & AST_FLAG_FINAL_DECL) + old->m_context = var->m_context; + delete var; + var = proto; + } + if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC && + (old = parser_find_field(parser, var->m_name))) + { + parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc"); + parseerror(parser, "global `%s` already declared here: %s:%i", + var->m_name, old->m_context.file, old->m_context.line); + retval = false; + goto cleanup; + } + } + } + } + else /* it's not a global */ + { + old = parser_find_local(parser, var->m_name, vec_size(parser->variables)-1, &isparam); + if (old && !isparam) { + parseerror(parser, "local `%s` already declared here: %s:%i", + var->m_name, old->m_context.file, (int)old->m_context.line); + retval = false; + goto cleanup; + } + /* doing this here as the above is just for a single scope */ + old = parser_find_local(parser, var->m_name, 0, &isparam); + if (old && isparam) { + if (parsewarning(parser, WARN_LOCAL_SHADOWS, + "local `%s` is shadowing a parameter", var->m_name)) + { + parseerror(parser, "local `%s` already declared here: %s:%i", + var->m_name, old->m_context.file, (int)old->m_context.line); + retval = false; + goto cleanup; + } + if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) { + delete var; + if (ast_istype(old, ast_value)) + var = proto = (ast_value*)old; + else { + var = nullptr; + goto skipvar; + } + } + } + } + + /* in a noref section we simply bump the usecount */ + if (noref || parser->noref) + var->m_uses++; + + /* Part 2: + * Create the global/local, and deal with vector types. + */ + if (!proto) { + if (var->m_vtype == TYPE_VECTOR) + isvector = true; + else if (var->m_vtype == TYPE_FIELD && + var->m_next->m_vtype == TYPE_VECTOR) + isvector = true; + + if (isvector) { + if (!create_vector_members(var, me)) { + retval = false; + goto cleanup; + } + } + + if (!localblock) { + /* deal with global variables, fields, functions */ + if (!nofields && var->m_vtype == TYPE_FIELD && parser->tok != '=') { + var->m_isfield = true; + parser->fields.push_back(var); + util_htset(parser->htfields, var->m_name.c_str(), var); + if (isvector) { + for (i = 0; i < 3; ++i) { + parser->fields.push_back(me[i]); + util_htset(parser->htfields, me[i]->m_name.c_str(), me[i]); + } + } + } + else { + if (!(var->m_flags & AST_FLAG_ALIAS)) { + parser_addglobal(parser, var->m_name, var); + if (isvector) { + for (i = 0; i < 3; ++i) { + parser_addglobal(parser, me[i]->m_name.c_str(), me[i]); + } + } + } else { + ast_expression *find = parser_find_global(parser, var->m_desc); + + if (!find) { + compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->m_desc, var->m_name); + return false; + } + + if (!var->compareType(*find)) { + char ty1[1024]; + char ty2[1024]; + + ast_type_to_string(find, ty1, sizeof(ty1)); + ast_type_to_string(var, ty2, sizeof(ty2)); + + compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`", + ty1, ty2, var->m_name + ); + return false; + } + + util_htset(parser->aliases, var->m_name.c_str(), find); + + /* generate aliases for vector components */ + if (isvector) { + char *buffer[3]; + + util_asprintf(&buffer[0], "%s_x", var->m_desc.c_str()); + util_asprintf(&buffer[1], "%s_y", var->m_desc.c_str()); + util_asprintf(&buffer[2], "%s_z", var->m_desc.c_str()); + + util_htset(parser->aliases, me[0]->m_name.c_str(), parser_find_global(parser, buffer[0])); + util_htset(parser->aliases, me[1]->m_name.c_str(), parser_find_global(parser, buffer[1])); + util_htset(parser->aliases, me[2]->m_name.c_str(), parser_find_global(parser, buffer[2])); + + mem_d(buffer[0]); + mem_d(buffer[1]); + mem_d(buffer[2]); + } + } + } + } else { + if (is_static) { + // a static adds itself to be generated like any other global + // but is added to the local namespace instead + std::string defname; + size_t prefix_len; + size_t sn, sn_size; + + defname = parser->function->m_name; + defname.append(2, ':'); + + // remember the length up to here + prefix_len = defname.length(); + + // Add it to the local scope + util_htset(vec_last(parser->variables), var->m_name.c_str(), (void*)var); + + // now rename the global + defname.append(var->m_name); + // if a variable of that name already existed, add the + // counter value. + // The counter is incremented either way. + sn_size = parser->function->m_static_names.size(); + for (sn = 0; sn != sn_size; ++sn) { + if (parser->function->m_static_names[sn] == var->m_name.c_str()) + break; + } + if (sn != sn_size) { + char *num = nullptr; + int len = util_asprintf(&num, "#%u", parser->function->m_static_count); + defname.append(num, 0, len); + mem_d(num); + } + else + parser->function->m_static_names.emplace_back(var->m_name); + parser->function->m_static_count++; + var->m_name = defname; + + // push it to the to-be-generated globals + parser->globals.push_back(var); + + // same game for the vector members + if (isvector) { + defname.erase(prefix_len); + for (i = 0; i < 3; ++i) { + util_htset(vec_last(parser->variables), me[i]->m_name.c_str(), (void*)(me[i])); + me[i]->m_name = move(defname + me[i]->m_name); + parser->globals.push_back(me[i]); + } + } + } else { + localblock->m_locals.push_back(var); + parser_addlocal(parser, var->m_name, var); + if (isvector) { + for (i = 0; i < 3; ++i) { + parser_addlocal(parser, me[i]->m_name, me[i]); + localblock->collect(me[i]); + } + } + } + } + } + memcpy(last_me, me, sizeof(me)); + me[0] = me[1] = me[2] = nullptr; + cleanvar = false; + /* Part 2.2 + * deal with arrays + */ + if (var->m_vtype == TYPE_ARRAY) { + if (var->m_count != (size_t)-1) { + if (!create_array_accessors(parser, var)) + goto cleanup; + } + } + else if (!localblock && !nofields && + var->m_vtype == TYPE_FIELD && + var->m_next->m_vtype == TYPE_ARRAY) + { + char name[1024]; + ast_expression *telem; + ast_value *tfield; + ast_value *array = (ast_value*)var->m_next; + + if (!ast_istype(var->m_next, ast_value)) { + parseerror(parser, "internal error: field element type must be an ast_value"); + goto cleanup; + } + + util_snprintf(name, sizeof(name), "%s##SETF", var->m_name.c_str()); + if (!parser_create_array_field_setter(parser, array, name)) + goto cleanup; + + telem = new ast_expression(ast_copy_type, var->m_context, *array->m_next); + tfield = new ast_value(var->m_context, "<.type>", TYPE_FIELD); + tfield->m_next = telem; + util_snprintf(name, sizeof(name), "%s##GETFP", var->m_name.c_str()); + if (!parser_create_array_getter(parser, array, tfield, name)) { + delete tfield; + goto cleanup; + } + delete tfield; + } + +skipvar: + if (parser->tok == ';') { + delete basetype; + if (!parser_next(parser)) { + parseerror(parser, "error after variable declaration"); + return false; + } + return true; + } + + if (parser->tok == ',') + goto another; + + /* + if (!var || (!localblock && !nofields && basetype->m_vtype == TYPE_FIELD)) { + */ + if (!var) { + parseerror(parser, "missing comma or semicolon while parsing variables"); + break; + } + + if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) { + if (parsewarning(parser, WARN_LOCAL_CONSTANTS, + "initializing expression turns variable `%s` into a constant in this standard", + var->m_name) ) + { + break; + } + } + + if (parser->tok != '{' || var->m_vtype != TYPE_FUNCTION) { + if (parser->tok != '=') { + parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser)); + break; + } + + if (!parser_next(parser)) { + parseerror(parser, "error parsing initializer"); + break; + } + } + else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) { + parseerror(parser, "expected '=' before function body in this standard"); + } + + if (parser->tok == '#') { + ast_function *func = nullptr; + ast_value *number = nullptr; + float fractional; + float integral; + int builtin_num; + + if (localblock) { + parseerror(parser, "cannot declare builtins within functions"); + break; + } + if (var->m_vtype != TYPE_FUNCTION) { + parseerror(parser, "unexpected builtin number, '%s' is not a function", var->m_name); + break; + } + if (!parser_next(parser)) { + parseerror(parser, "expected builtin number"); + break; + } + + if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) { + number = (ast_value*)parse_expression_leave(parser, true, false, false); + if (!number) { + parseerror(parser, "builtin number expected"); + break; + } + if (!ast_istype(number, ast_value) || !number->m_hasvalue || number->m_cvq != CV_CONST) + { + ast_unref(number); + parseerror(parser, "builtin number must be a compile time constant"); + break; + } + if (number->m_vtype == TYPE_INTEGER) + builtin_num = number->m_constval.vint; + else if (number->m_vtype == TYPE_FLOAT) + builtin_num = number->m_constval.vfloat; + else { + ast_unref(number); + parseerror(parser, "builtin number must be an integer constant"); + break; + } + ast_unref(number); + + fractional = modff(builtin_num, &integral); + if (builtin_num < 0 || fractional != 0) { + parseerror(parser, "builtin number must be an integer greater than zero"); + break; + } + + /* we only want the integral part anyways */ + builtin_num = integral; + } else if (parser->tok == TOKEN_INTCONST) { + builtin_num = parser_token(parser)->constval.i; + } else { + parseerror(parser, "builtin number must be a compile time constant"); + break; + } + + if (var->m_hasvalue) { + (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION, + "builtin `%s` has already been defined\n" + " -> previous declaration here: %s:%i", + var->m_name, var->m_context.file, (int)var->m_context.line); + } + else + { + func = ast_function::make(var->m_context, var->m_name, var); + if (!func) { + parseerror(parser, "failed to allocate function for `%s`", var->m_name); + break; + } + parser->functions.push_back(func); + + func->m_builtin = -builtin_num-1; + } + + if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS) + ? (parser->tok != ',' && parser->tok != ';') + : (!parser_next(parser))) + { + parseerror(parser, "expected comma or semicolon"); + delete func; + var->m_constval.vfunc = nullptr; + break; + } + } + else if (var->m_vtype == TYPE_ARRAY && parser->tok == '{') + { + if (localblock) { + /* Note that fteqcc and most others don't even *have* + * local arrays, so this is not a high priority. + */ + parseerror(parser, "TODO: initializers for local arrays"); + break; + } + + var->m_hasvalue = true; + if (!parse_array(parser, var)) + break; + } + else if (var->m_vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '[')) + { + if (localblock) { + parseerror(parser, "cannot declare functions within functions"); + break; + } + + if (proto) + proto->m_context = parser_ctx(parser); + + if (!parse_function_body(parser, var)) + break; + delete basetype; + for (auto &it : parser->gotos) + parseerror(parser, "undefined label: `%s`", it->m_name); + parser->gotos.clear(); + parser->labels.clear(); + return true; + } else { + ast_expression *cexp; + ast_value *cval; + bool folded_const = false; + + cexp = parse_expression_leave(parser, true, false, false); + if (!cexp) + break; + cval = ast_istype(cexp, ast_value) ? (ast_value*)cexp : nullptr; + + /* deal with foldable constants: */ + if (localblock && + var->m_cvq == CV_CONST && cval && cval->m_hasvalue && cval->m_cvq == CV_CONST && !cval->m_isfield) + { + /* remove it from the current locals */ + if (isvector) { + for (i = 0; i < 3; ++i) { + vec_pop(parser->_locals); + localblock->m_collect.pop_back(); + } + } + /* do sanity checking, this function really needs refactoring */ + if (vec_last(parser->_locals) != var) + parseerror(parser, "internal error: unexpected change in local variable handling"); + else + vec_pop(parser->_locals); + if (localblock->m_locals.back() != var) + parseerror(parser, "internal error: unexpected change in local variable handling (2)"); + else + localblock->m_locals.pop_back(); + /* push it to the to-be-generated globals */ + parser->globals.push_back(var); + if (isvector) + for (i = 0; i < 3; ++i) + parser->globals.push_back(last_me[i]); + folded_const = true; + } + + if (folded_const || !localblock || is_static) { + if (cval != parser->nil && + (!cval || ((!cval->m_hasvalue || cval->m_cvq != CV_CONST) && !cval->m_isfield)) + ) + { + parseerror(parser, "initializer is non constant"); + } + else + { + if (!is_static && + !OPTS_FLAG(INITIALIZED_NONCONSTANTS) && + qualifier != CV_VAR) + { + var->m_cvq = CV_CONST; + } + if (cval == parser->nil) + var->m_flags |= AST_FLAG_INITIALIZED; + else + { + var->m_hasvalue = true; + if (cval->m_vtype == TYPE_STRING) + var->m_constval.vstring = parser_strdup(cval->m_constval.vstring); + else if (cval->m_vtype == TYPE_FIELD) + var->m_constval.vfield = cval; + else + memcpy(&var->m_constval, &cval->m_constval, sizeof(var->m_constval)); + ast_unref(cval); + } + } + } else { + int cvq; + shunt sy; + cvq = var->m_cvq; + var->m_cvq = CV_NONE; + sy.out.push_back(syexp(var->m_context, var)); + sy.out.push_back(syexp(cexp->m_context, cexp)); + sy.ops.push_back(syop(var->m_context, parser->assign_op)); + if (!parser_sy_apply_operator(parser, &sy)) + ast_unref(cexp); + else { + if (sy.out.size() != 1 && sy.ops.size() != 0) + parseerror(parser, "internal error: leaked operands"); + if (!localblock->addExpr(sy.out[0].out)) + break; + } + var->m_cvq = cvq; + } + /* a constant initialized to an inexact value should be marked inexact: + * const float x = ; should propagate the inexact flag + */ + if (var->m_cvq == CV_CONST && var->m_vtype == TYPE_FLOAT) { + if (cval && cval->m_hasvalue && cval->m_cvq == CV_CONST) + var->m_inexact = cval->m_inexact; + } + } + +another: + if (parser->tok == ',') { + if (!parser_next(parser)) { + parseerror(parser, "expected another variable"); + break; + } + + if (parser->tok != TOKEN_IDENT) { + parseerror(parser, "expected another variable"); + break; + } + var = new ast_value(ast_copy_type, *basetype); + cleanvar = true; + var->m_name = parser_tokval(parser); + if (!parser_next(parser)) { + parseerror(parser, "error parsing variable declaration"); + break; + } + continue; + } + + if (parser->tok != ';') { + parseerror(parser, "missing semicolon after variables"); + break; + } + + if (!parser_next(parser)) { + parseerror(parser, "parse error after variable declaration"); + break; + } + + delete basetype; + return true; + } + + if (cleanvar && var) + delete var; + delete basetype; + return false; + +cleanup: + delete basetype; + if (cleanvar && var) + delete var; + delete me[0]; + delete me[1]; + delete me[2]; + return retval; +} + +static bool parser_global_statement(parser_t *parser) +{ + int cvq = CV_WRONG; + bool noref = false; + bool is_static = false; + uint32_t qflags = 0; + ast_value *istype = nullptr; + char *vstring = nullptr; + + if (parser->tok == TOKEN_IDENT) + istype = parser_find_typedef(parser, parser_tokval(parser), 0); + + if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS) + { + return parse_variable(parser, nullptr, false, CV_NONE, istype, false, false, 0, nullptr); + } + else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring)) + { + if (cvq == CV_WRONG) + return false; + return parse_variable(parser, nullptr, false, cvq, nullptr, noref, is_static, qflags, vstring); + } + else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum")) + { + return parse_enum(parser); + } + else if (parser->tok == TOKEN_KEYWORD) + { + if (!strcmp(parser_tokval(parser), "typedef")) { + if (!parser_next(parser)) { + parseerror(parser, "expected type definition after 'typedef'"); + return false; + } + return parse_typedef(parser); + } + parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser)); + return false; + } + else if (parser->tok == '#') + { + return parse_pragma(parser); + } + else if (parser->tok == '$') + { + if (!parser_next(parser)) { + parseerror(parser, "parse error"); + return false; + } + } + else + { + parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value); + return false; + } + return true; +} + +static uint16_t progdefs_crc_sum(uint16_t old, const char *str) +{ + return util_crc16(old, str, strlen(str)); +} + +static void progdefs_crc_file(const char *str) +{ + /* write to progdefs.h here */ + (void)str; +} + +static uint16_t progdefs_crc_both(uint16_t old, const char *str) +{ + old = progdefs_crc_sum(old, str); + progdefs_crc_file(str); + return old; +} + +static void generate_checksum(parser_t *parser, ir_builder *ir) +{ + uint16_t crc = 0xFFFF; + size_t i; + ast_value *value; + + crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{"); + crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n"); + /* + progdefs_crc_file("\tint\tpad;\n"); + progdefs_crc_file("\tint\tofs_return[3];\n"); + progdefs_crc_file("\tint\tofs_parm0[3];\n"); + progdefs_crc_file("\tint\tofs_parm1[3];\n"); + progdefs_crc_file("\tint\tofs_parm2[3];\n"); + progdefs_crc_file("\tint\tofs_parm3[3];\n"); + progdefs_crc_file("\tint\tofs_parm4[3];\n"); + progdefs_crc_file("\tint\tofs_parm5[3];\n"); + progdefs_crc_file("\tint\tofs_parm6[3];\n"); + progdefs_crc_file("\tint\tofs_parm7[3];\n"); + */ + for (i = 0; i < parser->crc_globals; ++i) { + if (!ast_istype(parser->globals[i], ast_value)) + continue; + value = (ast_value*)(parser->globals[i]); + switch (value->m_vtype) { + case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break; + case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break; + case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break; + case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break; + default: + crc = progdefs_crc_both(crc, "\tint\t"); + break; + } + crc = progdefs_crc_both(crc, value->m_name.c_str()); + crc = progdefs_crc_both(crc, ";\n"); + } + crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n"); + for (i = 0; i < parser->crc_fields; ++i) { + if (!ast_istype(parser->fields[i], ast_value)) + continue; + value = (ast_value*)(parser->fields[i]); + switch (value->m_next->m_vtype) { + case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break; + case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break; + case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break; + case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break; + default: + crc = progdefs_crc_both(crc, "\tint\t"); + break; + } + crc = progdefs_crc_both(crc, value->m_name.c_str()); + crc = progdefs_crc_both(crc, ";\n"); + } + crc = progdefs_crc_both(crc, "} entvars_t;\n\n"); + ir->m_code->crc = crc; +} + +parser_t *parser_create() +{ + parser_t *parser; + lex_ctx_t empty_ctx; + size_t i; + + parser = (parser_t*)mem_a(sizeof(parser_t)); + if (!parser) + return nullptr; + + memset(parser, 0, sizeof(*parser)); + + // TODO: remove + new (parser) parser_t(); + + for (i = 0; i < operator_count; ++i) { + if (operators[i].id == opid1('=')) { + parser->assign_op = operators+i; + break; + } + } + if (!parser->assign_op) { + con_err("internal error: initializing parser: failed to find assign operator\n"); + mem_d(parser); + return nullptr; + } + + vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE)); + vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE)); + vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE)); + vec_push(parser->_blocktypedefs, 0); + + parser->aliases = util_htnew(PARSER_HT_SIZE); + + empty_ctx.file = ""; + empty_ctx.line = 0; + empty_ctx.column = 0; + parser->nil = new ast_value(empty_ctx, "nil", TYPE_NIL); + parser->nil->m_cvq = CV_CONST; + if (OPTS_FLAG(UNTYPED_NIL)) + util_htset(parser->htglobals, "nil", (void*)parser->nil); + + parser->max_param_count = 1; + + parser->const_vec[0] = new ast_value(empty_ctx, "", TYPE_NOEXPR); + parser->const_vec[1] = new ast_value(empty_ctx, "", TYPE_NOEXPR); + parser->const_vec[2] = new ast_value(empty_ctx, "", TYPE_NOEXPR); + + if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) { + parser->reserved_version = new ast_value(empty_ctx, "reserved:version", TYPE_STRING); + parser->reserved_version->m_cvq = CV_CONST; + parser->reserved_version->m_hasvalue = true; + parser->reserved_version->m_flags |= AST_FLAG_INCLUDE_DEF; + parser->reserved_version->m_constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING); + } else { + parser->reserved_version = nullptr; + } + + parser->m_fold = fold(parser); + parser->m_intrin = intrin(parser); + return parser; +} + +static bool parser_compile(parser_t *parser) +{ + /* initial lexer/parser state */ + parser->lex->flags.noops = true; + + if (parser_next(parser)) + { + while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR) + { + if (!parser_global_statement(parser)) { + if (parser->tok == TOKEN_EOF) + parseerror(parser, "unexpected end of file"); + else if (compile_errors) + parseerror(parser, "there have been errors, bailing out"); + lex_close(parser->lex); + parser->lex = nullptr; + return false; + } + } + } else { + parseerror(parser, "parse error"); + lex_close(parser->lex); + parser->lex = nullptr; + return false; + } + + lex_close(parser->lex); + parser->lex = nullptr; + + return !compile_errors; +} + +bool parser_compile_file(parser_t *parser, const char *filename) +{ + parser->lex = lex_open(filename); + if (!parser->lex) { + con_err("failed to open file \"%s\"\n", filename); + return false; + } + return parser_compile(parser); +} + +bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len) +{ + parser->lex = lex_open_string(str, len, name); + if (!parser->lex) { + con_err("failed to create lexer for string \"%s\"\n", name); + return false; + } + return parser_compile(parser); +} + +static void parser_remove_ast(parser_t *parser) +{ + size_t i; + if (parser->ast_cleaned) + return; + parser->ast_cleaned = true; + for (auto &it : parser->accessors) { + delete it->m_constval.vfunc; + it->m_constval.vfunc = nullptr; + delete it; + } + for (auto &it : parser->functions) delete it; + for (auto &it : parser->globals) delete it; + for (auto &it : parser->fields) delete it; + + for (i = 0; i < vec_size(parser->variables); ++i) + util_htdel(parser->variables[i]); + vec_free(parser->variables); + vec_free(parser->_blocklocals); + vec_free(parser->_locals); + + for (i = 0; i < vec_size(parser->_typedefs); ++i) + delete parser->_typedefs[i]; + vec_free(parser->_typedefs); + for (i = 0; i < vec_size(parser->typedefs); ++i) + util_htdel(parser->typedefs[i]); + vec_free(parser->typedefs); + vec_free(parser->_blocktypedefs); + + vec_free(parser->_block_ctx); + + delete parser->nil; + + delete parser->const_vec[0]; + delete parser->const_vec[1]; + delete parser->const_vec[2]; + + if (parser->reserved_version) + delete parser->reserved_version; + + util_htdel(parser->aliases); +} + +void parser_cleanup(parser_t *parser) +{ + parser_remove_ast(parser); + parser->~parser_t(); + mem_d(parser); +} + +static bool parser_set_coverage_func(parser_t *parser, ir_builder *ir) { + ast_expression *expr; + ast_value *cov; + ast_function *func; + + if (!OPTS_OPTION_BOOL(OPTION_COVERAGE)) + return true; + + func = nullptr; + for (auto &it : parser->functions) { + if (it->m_name == "coverage") { + func = it; + break; + } + } + if (!func) { + if (OPTS_OPTION_BOOL(OPTION_COVERAGE)) { + con_out("coverage support requested but no coverage() builtin declared\n"); + delete ir; + return false; + } + return true; + } + + cov = func->m_function_type; + expr = cov; + + if (expr->m_vtype != TYPE_FUNCTION || expr->m_type_params.size()) { + char ty[1024]; + ast_type_to_string(expr, ty, sizeof(ty)); + con_out("invalid type for coverage(): %s\n", ty); + delete ir; + return false; + } + + ir->m_coverage_func = func->m_ir_func->m_value; + return true; +} + +bool parser_finish(parser_t *parser, const char *output) +{ + ir_builder *ir; + bool retval = true; + + if (compile_errors) { + con_out("*** there were compile errors\n"); + return false; + } + + ir = new ir_builder("gmqcc_out"); + if (!ir) { + con_out("failed to allocate builder\n"); + return false; + } + + for (auto &it : parser->fields) { + bool hasvalue; + if (!ast_istype(it, ast_value)) + continue; + ast_value *field = (ast_value*)it; + hasvalue = field->m_hasvalue; + field->m_hasvalue = false; + if (!reinterpret_cast(field)->generateGlobal(ir, true)) { + con_out("failed to generate field %s\n", field->m_name.c_str()); + delete ir; + return false; + } + if (hasvalue) { + ir_value *ifld; + ast_expression *subtype; + field->m_hasvalue = true; + subtype = field->m_next; + ifld = ir->createField(field->m_name, subtype->m_vtype); + if (subtype->m_vtype == TYPE_FIELD) + ifld->m_fieldtype = subtype->m_next->m_vtype; + else if (subtype->m_vtype == TYPE_FUNCTION) + ifld->m_outtype = subtype->m_next->m_vtype; + (void)!field->m_ir_v->setField(ifld); + } + } + for (auto &it : parser->globals) { + ast_value *asvalue; + if (!ast_istype(it, ast_value)) + continue; + asvalue = (ast_value*)it; + if (!asvalue->m_uses && !asvalue->m_hasvalue && asvalue->m_vtype != TYPE_FUNCTION) { + retval = retval && !compile_warning(asvalue->m_context, WARN_UNUSED_VARIABLE, + "unused global: `%s`", asvalue->m_name); + } + if (!asvalue->generateGlobal(ir, false)) { + con_out("failed to generate global %s\n", asvalue->m_name.c_str()); + delete ir; + return false; + } + } + /* Build function vararg accessor ast tree now before generating + * immediates, because the accessors may add new immediates + */ + for (auto &f : parser->functions) { + if (f->m_varargs) { + if (parser->max_param_count > f->m_function_type->m_type_params.size()) { + f->m_varargs->m_count = parser->max_param_count - f->m_function_type->m_type_params.size(); + if (!parser_create_array_setter_impl(parser, f->m_varargs.get())) { + con_out("failed to generate vararg setter for %s\n", f->m_name.c_str()); + delete ir; + return false; + } + if (!parser_create_array_getter_impl(parser, f->m_varargs.get())) { + con_out("failed to generate vararg getter for %s\n", f->m_name.c_str()); + delete ir; + return false; + } + } else { + f->m_varargs = nullptr; + } + } + } + /* Now we can generate immediates */ + if (!parser->m_fold.generate(ir)) + return false; + + /* before generating any functions we need to set the coverage_func */ + if (!parser_set_coverage_func(parser, ir)) + return false; + for (auto &it : parser->globals) { + if (!ast_istype(it, ast_value)) + continue; + ast_value *asvalue = (ast_value*)it; + if (!(asvalue->m_flags & AST_FLAG_INITIALIZED)) + { + if (asvalue->m_cvq == CV_CONST && !asvalue->m_hasvalue) + (void)!compile_warning(asvalue->m_context, WARN_UNINITIALIZED_CONSTANT, + "uninitialized constant: `%s`", + asvalue->m_name); + else if ((asvalue->m_cvq == CV_NONE || asvalue->m_cvq == CV_CONST) && !asvalue->m_hasvalue) + (void)!compile_warning(asvalue->m_context, WARN_UNINITIALIZED_GLOBAL, + "uninitialized global: `%s`", + asvalue->m_name); + } + if (!asvalue->generateAccessors(ir)) { + delete ir; + return false; + } + } + for (auto &it : parser->fields) { + ast_value *asvalue = (ast_value*)it->m_next; + if (!ast_istype(asvalue, ast_value)) + continue; + if (asvalue->m_vtype != TYPE_ARRAY) + continue; + if (!asvalue->generateAccessors(ir)) { + delete ir; + return false; + } + } + if (parser->reserved_version && + !parser->reserved_version->generateGlobal(ir, false)) + { + con_out("failed to generate reserved::version"); + delete ir; + return false; + } + for (auto &f : parser->functions) { + if (!f->generateFunction(ir)) { + con_out("failed to generate function %s\n", f->m_name.c_str()); + delete ir; + return false; + } + } + + generate_checksum(parser, ir); + + if (OPTS_OPTION_BOOL(OPTION_DUMP)) + ir->dump(con_out); + for (auto &it : parser->functions) { + if (!ir_function_finalize(it->m_ir_func)) { + con_out("failed to finalize function %s\n", it->m_name.c_str()); + delete ir; + return false; + } + } + parser_remove_ast(parser); + + if (compile_Werrors) { + con_out("*** there were warnings treated as errors\n"); + compile_show_werrors(); + retval = false; + } + + if (retval) { + if (OPTS_OPTION_BOOL(OPTION_DUMPFIN)) + ir->dump(con_out); + + if (!ir->generate(output)) { + con_out("*** failed to generate output file\n"); + delete ir; + return false; + } + } + delete ir; + return retval; +} diff --cc test.cpp index 6d783f7,0000000..2614c7f mode 100644,000000..100644 --- a/test.cpp +++ b/test.cpp @@@ -1,1303 -1,0 +1,1305 @@@ +#include + +#include +#include +#include + +#include +#include +#include + +#include +#include + +#include "gmqcc.h" + +static const char *task_bins[] = { + "./gmqcc", + "./qcvm" +}; + +struct popen_t { + FILE *handles[3]; + int pipes[3]; + int stderr_fd; + int stdout_fd; + int pid; +}; + +static FILE **task_popen(const char *command, const char *mode) { + int inhandle [2]; + int outhandle [2]; + int errhandle [2]; + int trypipe; + + popen_t *data = (popen_t*)mem_a(sizeof(popen_t)); + + char *line = (char*)command; + std::vector argv; + { + + while (*line != '\0') { + while (*line == ' ' || *line == '\t' || *line == '\n') + *line++ = '\0'; + argv.push_back(line); + while (*line != '\0' && *line != ' ' && + *line != '\t' && *line != '\n') line++; + } + argv.push_back((char *)0); + } + + if ((trypipe = pipe(inhandle)) < 0) goto task_popen_error_0; + if ((trypipe = pipe(outhandle)) < 0) goto task_popen_error_1; + if ((trypipe = pipe(errhandle)) < 0) goto task_popen_error_2; + + if ((data->pid = fork()) > 0) { + /* parent */ + close(inhandle [0]); + close(outhandle [1]); + close(errhandle [1]); + data->pipes[0] = inhandle [1]; + data->pipes[1] = outhandle[0]; + data->pipes[2] = errhandle[0]; + data->handles[0] = fdopen(inhandle [1], "w"); + data->handles[1] = fdopen(outhandle[0], mode); + data->handles[2] = fdopen(errhandle[0], mode); + return data->handles; + } else if (data->pid == 0) { + /* child */ + close(inhandle [1]); + close(outhandle[0]); + close(errhandle[0]); + + /* see piping documentation for this sillyness :P */ + dup2(inhandle [0], 0); + dup2(outhandle[1], 1); + dup2(errhandle[1], 2); + + execvp(argv[0], &argv[0]); + exit(95); + } else { + /* fork failed */ + goto task_popen_error_3; + } + +task_popen_error_3: close(errhandle[0]), close(errhandle[1]); +task_popen_error_2: close(outhandle[0]), close(outhandle[1]); +task_popen_error_1: close(inhandle [0]), close(inhandle [1]); +task_popen_error_0: + + return nullptr; +} + +static int task_pclose(FILE **handles) { + popen_t *data = (popen_t*)handles; + int status = 0; + + close(data->pipes[0]); /* stdin */ + close(data->pipes[1]); /* stdout */ + close(data->pipes[2]); /* stderr */ + + if (data->pid != waitpid(data->pid, &status, 0)) { + abort(); + } + if (!WIFEXITED(status)) + return -1; + if (WIFSIGNALED(status)) + con_out("got signaled!\n"); + + mem_d(data); + + return status ? 1 : 0; +} + +#define TASK_COMPILE 0 +#define TASK_EXECUTE 1 +/* + * Task template system: + * templates are rules for a specific test, used to create a "task" that + * is executed with those set of rules (arguments, and what not). Tests + * that don't have a template with them cannot become tasks, since without + * the information for that test there is no way to properly "test" them. + * Rules for these templates are described in a template file, using a + * task template language. + * + * The language is a basic finite statemachine, top-down single-line + * description language. + * + * The languge is composed entierly of "tags" which describe a string of + * text for a task. Think of it much like a configuration file. Except + * it's been designed to allow flexibility and future support for prodecual + * semantics. + * + * The following "tags" are suported by the language + * + * D: + * Used to set a description of the current test, this must be + * provided, this tag is NOT optional. + * + * T: + * Used to set the procedure for the given task, there are two + * options for this: + * -compile + * This simply performs compilation only + * -execute + * This will perform compilation and execution + * -fail + * This will perform compilation, but requires + * the compilation to fail in order to succeed. + * + * This must be provided, this tag is NOT optional. + * + * C: + * Used to set the compilation flags for the given task, this + * must be provided, this tag is NOT optional. + * + * F: Used to set some test suite flags, currently the only option + * is -no-defs (to including of defs.qh) + * + * E: + * Used to set the execution flags for the given task. This tag + * must be provided if T == -execute, otherwise it's erroneous + * as compilation only takes place. + * + * M: + * Used to describe a string of text that should be matched from + * the output of executing the task. If this doesn't match the + * task fails. This tag must be provided if T == -execute, otherwise + * it's erroneous as compilation only takes place. + * + * I: + * Used to specify the INPUT source file to operate on, this must be + * provided, this tag is NOT optional + * + * + * Notes: + * These tags have one-time use, using them more than once will result + * in template compilation errors. + * + * Lines beginning with # or // in the template file are comments and + * are ignored by the template parser. + * + * Whitespace is optional, with exception to the colon ':' between the + * tag and it's assignment value/ + * + * The template compiler will detect erronrous tags (optional tags + * that need not be set), as well as missing tags, and error accordingly + * this will result in the task failing. + */ +struct task_template_t { + char *description; + char *compileflags; + char *executeflags; + char *proceduretype; + char *sourcefile; + char *tempfilename; + std::vector comparematch; + char *rulesfile; + char *testflags; +}; + +/* + * This is very much like a compiler code generator :-). This generates + * a value from some data observed from the compiler. + */ +static bool task_template_generate(task_template_t *tmpl, char tag, const char *file, size_t line, char *value, size_t *pad) { + size_t desclen = 0; + size_t filelen = 0; + char **destval = nullptr; + + if (!tmpl) + return false; + + switch(tag) { + case 'D': destval = &tmpl->description; break; + case 'T': destval = &tmpl->proceduretype; break; + case 'C': destval = &tmpl->compileflags; break; + case 'E': destval = &tmpl->executeflags; break; + case 'I': destval = &tmpl->sourcefile; break; + case 'F': destval = &tmpl->testflags; break; + default: + con_printmsg(LVL_ERROR, __FILE__, __LINE__, 0, "internal error", + "invalid tag `%c:` during code generation\n", + tag + ); + return false; + } + + /* + * Ensure if for the given tag, there already exists a + * assigned value. + */ + if (*destval) { + con_printmsg(LVL_ERROR, file, line, 0, /*TODO: column for match*/ "compile error", + "tag `%c:` already assigned value: %s\n", + tag, *destval + ); + return false; + } + + /* + * Strip any whitespace that might exist in the value for assignments + * like "D: foo" + */ + if (value && *value && (*value == ' ' || *value == '\t')) + value++; + else if (!value) + exit(EXIT_FAILURE); + + /* + * Value will contain a newline character at the end, we need to strip + * this otherwise kaboom, seriously, kaboom :P + */ + if (strchr(value, '\n')) + *strrchr(value, '\n')='\0'; + + /* + * Now allocate and set the actual value for the specific tag. Which + * was properly selected and can be accessed with *destval. + */ + *destval = util_strdup(value); + + + if (*destval == tmpl->description) { + /* + * Create some padding for the description to align the + * printing of the rules file. + */ + if ((desclen = strlen(tmpl->description)) > pad[0]) + pad[0] = desclen; + } + + if ((filelen = strlen(file)) > pad[2]) + pad[2] = filelen; + + return true; +} + +static bool task_template_parse(const char *file, task_template_t *tmpl, FILE *fp, size_t *pad) { + char *data = nullptr; + char *back = nullptr; + size_t size = 0; + size_t line = 1; + + if (!tmpl) + return false; + + /* top down parsing */ + while (util_getline(&back, &size, fp) != EOF) { + /* skip whitespace */ + data = back; + if (*data && (*data == ' ' || *data == '\t')) + data++; + + switch (*data) { + /* + * Handle comments inside task tmpl files. We're strict + * about the language for fun :-) + */ + case '/': + if (data[1] != '/') { + con_printmsg(LVL_ERROR, file, line, 0, /*TODO: column for match*/ "tmpl parse error", + "invalid character `/`, perhaps you meant `//` ?"); + + mem_d(back); + return false; + } + case '#': + break; + + /* + * Empty newlines are acceptable as well, so we handle that here + * despite being just odd since there should't be that many + * empty lines to begin with. + */ + case '\r': + case '\n': + break; + + + /* + * Now begin the actual "tag" stuff. This works as you expect + * it to. + */ + case 'D': + case 'T': + case 'C': + case 'E': + case 'I': + case 'F': + if (data[1] != ':') { + con_printmsg(LVL_ERROR, file, line, 0, /*TODO: column for match*/ "tmpl parse error", + "expected `:` after `%c`", + *data + ); + goto failure; + } + if (!task_template_generate(tmpl, *data, file, line, &data[3], pad)) { + con_printmsg(LVL_ERROR, file, line, 0, /*TODO: column for match*/ "tmpl compile error", + "failed to generate for given task\n" + ); + goto failure; + } + break; + + /* + * Match requires it's own system since we allow multiple M's + * for multi-line matching. + */ + case 'M': + { + char *value = &data[3]; + if (data[1] != ':') { + con_printmsg(LVL_ERROR, file, line, 0, /*TODO: column for match*/ "tmpl parse error", + "expected `:` after `%c`", + *data + ); + goto failure; + } + + /* + * Value will contain a newline character at the end, we need to strip + * this otherwise kaboom, seriously, kaboom :P + */ + if (strrchr(value, '\n')) + *strrchr(value, '\n')='\0'; + else /* cppcheck: possible null pointer dereference */ + exit(EXIT_FAILURE); + + tmpl->comparematch.push_back(util_strdup(value)); + + break; + } + + default: + con_printmsg(LVL_ERROR, file, line, 0, /*TODO: column for match*/ "tmpl parse error", + "invalid tag `%c`", *data + ); + goto failure; + /* no break required */ + } + + /* update line and free old sata */ + line++; + mem_d(back); + back = nullptr; + } + if (back) + mem_d(back); + return true; + +failure: + mem_d (back); + return false; +} + +/* + * Nullifies the template data: used during initialization of a new + * template and free. + */ +static void task_template_nullify(task_template_t *tmpl) { + if (!tmpl) + return; + + tmpl->description = nullptr; + tmpl->proceduretype = nullptr; + tmpl->compileflags = nullptr; + tmpl->executeflags = nullptr; + tmpl->sourcefile = nullptr; + tmpl->tempfilename = nullptr; + tmpl->rulesfile = nullptr; + tmpl->testflags = nullptr; +} + +static task_template_t *task_template_compile(const char *file, const char *dir, size_t *pad) { + /* a page should be enough */ + char fullfile[4096]; + size_t filepadd = 0; + FILE *tempfile = nullptr; + task_template_t *tmpl = nullptr; + + util_snprintf(fullfile, sizeof(fullfile), "%s/%s", dir, file); + + tempfile = fopen(fullfile, "r"); + tmpl = (task_template_t*)mem_a(sizeof(task_template_t)); + new (tmpl) task_template_t(); + task_template_nullify(tmpl); + + /* + * Create some padding for the printing to align the + * printing of the rules file to the console. + */ + if ((filepadd = strlen(fullfile)) > pad[1]) + pad[1] = filepadd; + + tmpl->rulesfile = util_strdup(fullfile); + + /* + * Esnure the file even exists for the task, this is pretty useless + * to even do. + */ + if (!tempfile) { + con_err("template file: %s does not exist or invalid permissions\n", + file + ); + goto failure; + } + + if (!task_template_parse(file, tmpl, tempfile, pad)) { + con_err("template parse error: error during parsing\n"); + goto failure; + } + + /* + * Regardless procedure type, the following tags must exist: + * D + * T + * C + * I + */ + if (!tmpl->description) { + con_err("template compile error: %s missing `D:` tag\n", file); + goto failure; + } + if (!tmpl->proceduretype) { + con_err("template compile error: %s missing `T:` tag\n", file); + goto failure; + } + if (!tmpl->compileflags) { + con_err("template compile error: %s missing `C:` tag\n", file); + goto failure; + } + if (!tmpl->sourcefile) { + con_err("template compile error: %s missing `I:` tag\n", file); + goto failure; + } + + /* + * Now lets compile the template, compilation is really just + * the process of validating the input. + */ + if (!strcmp(tmpl->proceduretype, "-compile")) { + if (tmpl->executeflags) + con_err("template compile warning: %s erroneous tag `E:` when only compiling\n", file); + if (tmpl->comparematch.size()) + con_err("template compile warning: %s erroneous tag `M:` when only compiling\n", file); + goto success; + } else if (!strcmp(tmpl->proceduretype, "-execute")) { + if (!tmpl->executeflags) { + /* default to $null */ + tmpl->executeflags = util_strdup("$null"); + } + if (tmpl->comparematch.empty()) { + con_err("template compile error: %s missing `M:` tag (use `$null` for exclude)\n", file); + goto failure; + } + } else if (!strcmp(tmpl->proceduretype, "-fail")) { + if (tmpl->executeflags) + con_err("template compile warning: %s erroneous tag `E:` when only failing\n", file); + if (tmpl->comparematch.size()) + con_err("template compile warning: %s erroneous tag `M:` when only failing\n", file); + } else if (!strcmp(tmpl->proceduretype, "-diagnostic")) { + if (tmpl->executeflags) + con_err("template compile warning: %s erroneous tag `E:` when only diagnostic\n", file); + if (tmpl->comparematch.empty()) { + con_err("template compile error: %s missing `M:` tag (use `$null` for exclude)\n", file); + goto failure; + } + } else if (!strcmp(tmpl->proceduretype, "-pp")) { + if (tmpl->executeflags) + con_err("template compile warning: %s erroneous tag `E:` when only preprocessing\n", file); + if (tmpl->comparematch.empty()) { + con_err("template compile error: %s missing `M:` tag (use `$null` for exclude)\n", file); + goto failure; + } + } else { + con_err("template compile error: %s invalid procedure type: %s\n", file, tmpl->proceduretype); + goto failure; + } + +success: + fclose(tempfile); + return tmpl; + +failure: + /* + * The file might not exist and we jump here when that doesn't happen + * so the check to see if it's not null here is required. + */ + if (tempfile) + fclose(tempfile); + mem_d(tmpl); + + return nullptr; +} + +static void task_template_destroy(task_template_t *tmpl) { + if (!tmpl) + return; + + if (tmpl->description) mem_d(tmpl->description); + if (tmpl->proceduretype) mem_d(tmpl->proceduretype); + if (tmpl->compileflags) mem_d(tmpl->compileflags); + if (tmpl->executeflags) mem_d(tmpl->executeflags); + if (tmpl->sourcefile) mem_d(tmpl->sourcefile); + if (tmpl->rulesfile) mem_d(tmpl->rulesfile); + if (tmpl->testflags) mem_d(tmpl->testflags); + + + for (auto &it : tmpl->comparematch) + mem_d(it); + + /* + * Nullify all the template members otherwise nullptr comparision + * checks will fail if tmpl pointer is reused. + */ + mem_d(tmpl->tempfilename); + mem_d(tmpl); +} + +/* + * Now comes the task manager, this system allows adding tasks in and out + * of a task list. This is the executor of the tasks essentially as well. + */ +struct task_t { + task_template_t *tmpl; + FILE **runhandles; + FILE *stderrlog; + FILE *stdoutlog; + char *stdoutlogfile; + char *stderrlogfile; + bool compiled; +}; + +static std::vector task_tasks; + +/* + * Read a directory and searches for all template files in it + * which is later used to run all tests. + */ +static bool task_propagate(const char *curdir, size_t *pad, const char *defs) { + bool success = true; + DIR *dir; + struct dirent *files; + struct stat directory; + char buffer[4096]; + size_t found = 0; + std::vector directories; + char *claim = util_strdup(curdir); + + directories.push_back(claim); + dir = opendir(claim); + + /* + * Generate a list of subdirectories since we'll be checking them too + * for tmpl files. + */ + while ((files = readdir(dir))) { + util_asprintf(&claim, "%s/%s", curdir, files->d_name); + if (stat(claim, &directory) == -1) { + closedir(dir); + mem_d(claim); + return false; + } + + if (S_ISDIR(directory.st_mode) && files->d_name[0] != '.') { + directories.push_back(claim); + } else { + mem_d(claim); + claim = nullptr; + } + } + closedir(dir); + + /* + * Now do all the work, by touching all the directories inside + * test as well and compile the task templates into data we can + * use to run the tests. + */ + for (auto &it : directories) { + dir = opendir(it); + while ((files = readdir(dir))) { + util_snprintf(buffer, sizeof(buffer), "%s/%s", it, files->d_name); + if (stat(buffer, &directory) == -1) { + con_err("internal error: stat failed, aborting\n"); + abort(); + } + + if (S_ISDIR(directory.st_mode)) + continue; + + /* + * We made it here, which concludes the file/directory is not + * actually a directory, so it must be a file :) + */ + if (strcmp(files->d_name + strlen(files->d_name) - 5, ".tmpl") == 0) { + task_template_t *tmpl = task_template_compile(files->d_name, it, pad); + char buf[4096]; /* one page should be enough */ + const char *qcflags = nullptr; + task_t task; + ++ memset(&task, 0, sizeof(task)); ++ + found ++; + if (!tmpl) { + con_err("error compiling task template: %s\n", files->d_name); + success = false; + continue; + } + /* + * Generate a temportary file name for the output binary + * so we don't trample over an existing one. + */ + tmpl->tempfilename = nullptr; + util_asprintf(&tmpl->tempfilename, "%s/TMPDAT.%s.dat", it, files->d_name); + + /* + * Additional QCFLAGS enviroment variable may be used + * to test compile flags for all tests. This needs to be + * BEFORE other flags (so that the .tmpl can override them) + */ + qcflags = getenv("QCFLAGS"); + + /* + * Generate the command required to open a pipe to a process + * which will be refered to with a handle in the task for + * reading the data from the pipe. + */ + if (strcmp(tmpl->proceduretype, "-pp")) { + if (qcflags) { + if (tmpl->testflags && !strcmp(tmpl->testflags, "-no-defs")) { + util_snprintf(buf, sizeof(buf), "%s %s/%s %s %s -o %s", + task_bins[TASK_COMPILE], + it, + tmpl->sourcefile, + qcflags, + tmpl->compileflags, + tmpl->tempfilename + ); + } else { + util_snprintf(buf, sizeof(buf), "%s %s/%s %s/%s %s %s -o %s", + task_bins[TASK_COMPILE], + curdir, + defs, + it, + tmpl->sourcefile, + qcflags, + tmpl->compileflags, + tmpl->tempfilename + ); + } + } else { + if (tmpl->testflags && !strcmp(tmpl->testflags, "-no-defs")) { + util_snprintf(buf, sizeof(buf), "%s %s/%s %s -o %s", + task_bins[TASK_COMPILE], + it, + tmpl->sourcefile, + tmpl->compileflags, + tmpl->tempfilename + ); + } else { + util_snprintf(buf, sizeof(buf), "%s %s/%s %s/%s %s -o %s", + task_bins[TASK_COMPILE], + curdir, + defs, + it, + tmpl->sourcefile, + tmpl->compileflags, + tmpl->tempfilename + ); + } + } + } else { + /* Preprocessing (qcflags mean shit all here we don't allow them) */ + if (tmpl->testflags && !strcmp(tmpl->testflags, "-no-defs")) { + util_snprintf(buf, sizeof(buf), "%s -E %s/%s %s -o %s", + task_bins[TASK_COMPILE], + it, + tmpl->sourcefile, + tmpl->compileflags, + tmpl->tempfilename + ); + } else { + util_snprintf(buf, sizeof(buf), "%s -E %s/%s %s/%s %s -o %s", + task_bins[TASK_COMPILE], + curdir, + defs, + it, + tmpl->sourcefile, + tmpl->compileflags, + tmpl->tempfilename + ); + } + } + + /* + * The task template was compiled, now lets create a task from + * the template data which has now been propagated. + */ + task.tmpl = tmpl; + if (!(task.runhandles = task_popen(buf, "r"))) { + con_err("error opening pipe to process for test: %s\n", tmpl->description); + success = false; + continue; + } + + /* + * Open up some file desciptors for logging the stdout/stderr + * to our own. + */ + util_snprintf(buf, sizeof(buf), "%s.stdout", tmpl->tempfilename); + task.stdoutlogfile = util_strdup(buf); + if (!(task.stdoutlog = fopen(buf, "w"))) { + con_err("error opening %s for stdout\n", buf); + continue; + } + + util_snprintf(buf, sizeof(buf), "%s.stderr", tmpl->tempfilename); + task.stderrlogfile = util_strdup(buf); + if (!(task.stderrlog = fopen(buf, "w"))) { + con_err("error opening %s for stderr\n", buf); + continue; + } + task_tasks.push_back(task); + } + } + closedir(dir); + mem_d(it); /* free claimed memory */ + } + return success; +} + +/* + * Task precleanup removes any existing temporary files or log files + * left behind from a previous invoke of the test-suite. + */ +static void task_precleanup(const char *curdir) { + DIR *dir; + struct dirent *files; + char buffer[4096]; + + dir = opendir(curdir); + + while ((files = readdir(dir))) { + if (strstr(files->d_name, "TMP") || + strstr(files->d_name, ".stdout") || + strstr(files->d_name, ".stderr") || + strstr(files->d_name, ".dat")) + { + util_snprintf(buffer, sizeof(buffer), "%s/%s", curdir, files->d_name); + if (remove(buffer)) + con_err("error removing temporary file: %s\n", buffer); + } + } + + closedir(dir); +} + +static void task_destroy(void) { + /* + * Free all the data in the task list and finally the list itself + * then proceed to cleanup anything else outside the program like + * temporary files. + */ + for (auto &it : task_tasks) { + /* + * Close any open handles to files or processes here. It's mighty + * annoying to have to do all this cleanup work. + */ + if (it.stdoutlog) fclose(it.stdoutlog); + if (it.stderrlog) fclose(it.stderrlog); + + /* + * Only remove the log files if the test actually compiled otherwise + * forget about it (or if it didn't compile, and the procedure type + * was set to -fail (meaning it shouldn't compile) .. stil remove) + */ + if (it.compiled || !strcmp(it.tmpl->proceduretype, "-fail")) { + if (remove(it.stdoutlogfile)) + con_err("error removing stdout log file: %s\n", it.stdoutlogfile); + if (remove(it.stderrlogfile)) + con_err("error removing stderr log file: %s\n", it.stderrlogfile); + + (void)!remove(it.tmpl->tempfilename); + } + + /* free util_strdup data for log files */ + mem_d(it.stdoutlogfile); + mem_d(it.stderrlogfile); + + task_template_destroy(it.tmpl); + } +} + +/* + * This executes the QCVM task for a specificly compiled progs.dat + * using the template passed into it for call-flags and user defined + * messages IF the procedure type is -execute, otherwise it matches + * the preprocessor output. + */ +static bool task_trymatch(task_t &task, std::vector &line) { + bool success = true; + bool process = true; + int retval = EXIT_SUCCESS; + FILE *execute; + char buffer[4096]; + task_template_t *tmpl = task.tmpl; + + memset(buffer,0,sizeof(buffer)); + + if (!strcmp(tmpl->proceduretype, "-execute")) { + /* + * Drop the execution flags for the QCVM if none where + * actually specified. + */ + if (!strcmp(tmpl->executeflags, "$null")) { + util_snprintf(buffer, sizeof(buffer), "%s %s", + task_bins[TASK_EXECUTE], + tmpl->tempfilename + ); + } else { + util_snprintf(buffer, sizeof(buffer), "%s %s %s", + task_bins[TASK_EXECUTE], + tmpl->executeflags, + tmpl->tempfilename + ); + } + + execute = popen(buffer, "r"); + if (!execute) + return false; + } else if (!strcmp(tmpl->proceduretype, "-pp")) { + /* + * we're preprocessing, which means we need to read int + * the produced file and do some really weird shit. + */ + if (!(execute = fopen(tmpl->tempfilename, "r"))) + return false; + process = false; + } else { + /* + * we're testing diagnostic output, which means it will be + * in runhandles[2] (stderr) since that is where the compiler + * puts it's errors. + */ + if (!(execute = fopen(task.stderrlogfile, "r"))) + return false; + process = false; + } + + /* + * Now lets read the lines and compare them to the matches we expect + * and handle accordingly. + */ + { + char *data = nullptr; + size_t size = 0; + size_t compare = 0; + + while (util_getline(&data, &size, execute) != EOF) { + if (!strcmp(data, "No main function found\n")) { + con_err("test failure: `%s` (No main function found) [%s]\n", + tmpl->description, + tmpl->rulesfile + ); + if (!process) + fclose(execute); + else + pclose((FILE*)execute); + return false; + } + + /* + * Trim newlines from data since they will just break our + * ability to properly validate matches. + */ + if (strrchr(data, '\n')) + *strrchr(data, '\n') = '\0'; + + /* + * We remove the file/directory and stuff from the error + * match messages when testing diagnostics. + */ + if(!strcmp(tmpl->proceduretype, "-diagnostic")) { + if (strstr(data, "there have been errors, bailing out")) + continue; /* ignore it */ + if (strstr(data, ": error: ")) { + char *claim = util_strdup(data + (strstr(data, ": error: ") - data) + 9); + mem_d(data); + data = claim; + } + } + + /* + * We need to ignore null lines for when -pp is used (preprocessor), since + * the preprocessor is likely to create empty newlines in certain macro + * instantations, otherwise it's in the wrong nature to ignore empty newlines. + */ + if (!strcmp(tmpl->proceduretype, "-pp") && !*data) + continue; + + if (tmpl->comparematch.size() > compare) { + if (strcmp(data, tmpl->comparematch[compare++])) { + success = false; + } + } else { + success = false; + } + + line.push_back(data); + + /* reset */ + data = nullptr; + size = 0; + } + + if (compare != tmpl->comparematch.size()) + success = false; + + mem_d(data); + data = nullptr; + } + + if (process) + retval = pclose((FILE*)execute); + else + fclose(execute); + + return success && retval == EXIT_SUCCESS; +} + +static const char *task_type(task_template_t *tmpl) { + if (!strcmp(tmpl->proceduretype, "-pp")) + return "type: preprocessor"; + if (!strcmp(tmpl->proceduretype, "-execute")) + return "type: execution"; + if (!strcmp(tmpl->proceduretype, "-compile")) + return "type: compile"; + if (!strcmp(tmpl->proceduretype, "-diagnostic")) + return "type: diagnostic"; + return "type: fail"; +} + +/* + * This schedualizes all tasks and actually runs them individually + * this is generally easy for just -compile variants. For compile and + * execution this takes more work since a task needs to be generated + * from thin air and executed INLINE. + */ +#include +static size_t task_schedualize(size_t *pad) { + char space[2][64]; + bool execute = false; + char *data = nullptr; + std::vector match; + size_t size = 0; + size_t i = 0; + size_t failed = 0; + int status = 0; + + util_snprintf(space[0], sizeof(space[0]), "%d", (int)task_tasks.size()); + + for (auto &it : task_tasks) { + i++; + memset(space[1], 0, sizeof(space[1])); + util_snprintf(space[1], sizeof(space[1]), "%d", (int)(i)); + + con_out("test #%u %*s", i, strlen(space[0]) - strlen(space[1]), ""); + //con_out("[[%*s]]", + // (pad[0] + pad[1] - strlen(it.tmpl->description)) + (strlen(it.tmpl->rulesfile) - pad[1]), + // it.tmpl->rulesfile); + //fflush(stdout); + + /* + * Generate a task from thin air if it requires execution in + * the QCVM. + */ + + /* diagnostic is not executed, but compare tested instead, like preproessor */ + execute = !! (!strcmp(it.tmpl->proceduretype, "-execute")) || + (!strcmp(it.tmpl->proceduretype, "-pp")) || + (!strcmp(it.tmpl->proceduretype, "-diagnostic")); + + /* + * We assume it compiled before we actually compiled :). On error + * we change the value + */ + it.compiled = true; + + /* + * Read data from stdout first and pipe that stuff into a log file + * then we do the same for stderr. + */ + while (util_getline(&data, &size, it.runhandles[1]) != EOF) { + fputs(data, it.stdoutlog); + + if (strstr(data, "failed to open file")) { + it.compiled = false; + execute = false; + } + } + while (util_getline(&data, &size, it.runhandles[2]) != EOF) { + /* + * If a string contains an error we just dissalow execution + * of it in the vm. + * + * TODO: make this more percise, e.g if we print a warning + * that refers to a variable named error, or something like + * that .. then this will blowup :P + */ + if (strstr(data, "error") && strcmp(it.tmpl->proceduretype, "-diagnostic")) { + execute = false; + it.compiled = false; + } + + fputs(data, it.stderrlog); + fflush(it.stderrlog); /* fast flush for read */ + } + + if (!it.compiled && strcmp(it.tmpl->proceduretype, "-fail")) { + con_out("failure: `%s` %*s %*s\n", + it.tmpl->description, + (pad[0] + pad[1] - strlen(it.tmpl->description)) + (strlen(it.tmpl->rulesfile) - pad[1]), + it.tmpl->rulesfile, + (pad[1] + pad[2] - strlen(it.tmpl->rulesfile)) + (strlen("(failed to compile)") - pad[2]), + "(failed to compile)" + ); + failed++; + continue; + } + + status = task_pclose(it.runhandles); + if (status != 0 && status != 1) { + con_out("compiler failure (returned: %i): `%s` %*s\n", + status, + it.tmpl->description, + (pad[0] + pad[1] - strlen(it.tmpl->description)) + (strlen(it.tmpl->rulesfile) - pad[1]), + it.tmpl->rulesfile + ); + failed++; + continue; + } + if ((!strcmp(it.tmpl->proceduretype, "-fail") && status == EXIT_SUCCESS) + || ( strcmp(it.tmpl->proceduretype, "-fail") && status == EXIT_FAILURE)) { + con_out("failure: `%s` %*s %*s\n", + it.tmpl->description, + (pad[0] + pad[1] - strlen(it.tmpl->description)) + (strlen(it.tmpl->rulesfile) - pad[1]), + it.tmpl->rulesfile, + (pad[1] + pad[2] - strlen(it.tmpl->rulesfile)) + (strlen("(compiler didn't return exit success)") - pad[2]), + "(compiler didn't return exit success)" + ); + failed++; + continue; + } + + if (!execute) { + con_out("succeeded: `%s` %*s %*s\n", + it.tmpl->description, + (pad[0] + pad[1] - strlen(it.tmpl->description)) + (strlen(it.tmpl->rulesfile) - pad[1]), + it.tmpl->rulesfile, + (pad[1] + pad[2] - strlen(it.tmpl->rulesfile)) + (strlen(task_type(it.tmpl)) - pad[2]), + task_type(it.tmpl) + + ); + continue; + } + + /* + * If we made it here that concludes the task is to be executed + * in the virtual machine (or the preprocessor output needs to + * be matched). + */ + if (!task_trymatch(it, match)) { + size_t d = 0; + + con_out("failure: `%s` %*s %*s\n", + it.tmpl->description, + (pad[0] + pad[1] - strlen(it.tmpl->description)) + (strlen(it.tmpl->rulesfile) - pad[1]), + it.tmpl->rulesfile, + (pad[1] + pad[2] - strlen(it.tmpl->rulesfile)) + (strlen( + (strcmp(it.tmpl->proceduretype, "-pp")) + ? "(invalid results from execution)" + : (strcmp(it.tmpl->proceduretype, "-diagnostic")) + ? "(invalid results from preprocessing)" + : "(invalid results from compiler diagnsotics)" + ) - pad[2]), + (strcmp(it.tmpl->proceduretype, "-pp")) + ? "(invalid results from execution)" + : (strcmp(it.tmpl->proceduretype, "-diagnostic")) + ? "(invalid results from preprocessing)" + : "(invalid results from compiler diagnsotics)" + ); + + /* + * Print nicely formatted expected match lists to console error + * handler for the all the given matches in the template file and + * what was actually returned from executing. + */ + con_out(" Expected From %u Matches: (got %u Matches)\n", + it.tmpl->comparematch.size(), + match.size() + ); + for (; d < it.tmpl->comparematch.size(); d++) { + char *select = it.tmpl->comparematch[d]; + size_t length = 60 - strlen(select); + con_out(" Expected: \"%s\"", select); + while (length --) + con_out(" "); + con_out("| Got: \"%s\"\n", (d >= match.size()) ? "<>" : match[d]); + } + + /* + * Print the non-expected out (since we are simply not expecting it) + * This will help track down bugs in template files that fail to match + * something. + */ + if (match.size() > it.tmpl->comparematch.size()) { + for (d = 0; d < match.size() - it.tmpl->comparematch.size(); d++) { + con_out(" Expected: Nothing | Got: \"%s\"\n", + match[d + it.tmpl->comparematch.size()] + ); + } + } + + for (auto &it : match) + mem_d(it); + match.clear(); + failed++; + continue; + } + + for (auto &it : match) + mem_d(it); + match.clear(); + + con_out("succeeded: `%s` %*s %*s\n", + it.tmpl->description, + (pad[0] + pad[1] - strlen(it.tmpl->description)) + (strlen(it.tmpl->rulesfile) - pad[1]), + it.tmpl->rulesfile, + (pad[1] + pad[2] - strlen(it.tmpl->rulesfile)) + (strlen(task_type(it.tmpl))- pad[2]), + task_type(it.tmpl) + + ); + } + mem_d(data); + return failed; +} + +/* + * This is the heart of the whole test-suite process. This cleans up + * any existing temporary files left behind as well as log files left + * behind. Then it propagates a list of tests from `curdir` by scaning + * it for template files and compiling them into tasks, in which it + * schedualizes them (executes them) and actually reports errors and + * what not. It then proceeds to destroy the tasks and return memory + * it's the engine :) + * + * It returns true of tests could be propagated, otherwise it returns + * false. + * + * It expects con_init() was called before hand. + */ +static GMQCC_WARN bool test_perform(const char *curdir, const char *defs) { + size_t failed = false; + static const char *default_defs = "defs.qh"; + + size_t pad[] = { + /* test ### [succeed/fail]: `description` [tests/template.tmpl] [type] */ + 0, 0, 0 + }; + + /* + * If the default definition file isn't set to anything. We will + * use the default_defs here, which is "defs.qc" + */ + if (!defs) { + defs = default_defs; + } + + + task_precleanup(curdir); + if (!task_propagate(curdir, pad, defs)) { + con_err("error: failed to propagate tasks\n"); + task_destroy(); + return false; + } + /* + * If we made it here all tasks where propagated from their resultant + * template file. So we can start the FILO scheduler, this has been + * designed in the most thread-safe way possible for future threading + * it's designed to prevent lock contention, and possible syncronization + * issues. + */ + failed = task_schedualize(pad); + if (failed) + con_out("%u out of %u tests failed\n", failed, task_tasks.size()); + task_destroy(); + + return (failed) ? false : true; +} + +/* + * Fancy GCC-like LONG parsing allows things like --opt=param with + * assignment operator. This is used for redirecting stdout/stderr + * console to specific files of your choice. + */ +static bool parsecmd(const char *optname, int *argc_, char ***argv_, char **out, int ds, bool split) { + int argc = *argc_; + char **argv = *argv_; + + size_t len = strlen(optname); + + if (strncmp(argv[0]+ds, optname, len)) + return false; + + /* it's --optname, check how the parameter is supplied */ + if (argv[0][ds+len] == '=') { + *out = argv[0]+ds+len+1; + return true; + } + + if (!split || argc < ds) /* no parameter was provided, or only single-arg form accepted */ + return false; + + /* using --opt param */ + *out = argv[1]; + --*argc_; + ++*argv_; + return true; +} + +int main(int argc, char **argv) { + bool succeed = false; + char *defs = nullptr; + + con_init(); + + /* + * Command line option parsing commences now We only need to support + * a few things in the test suite. + */ + while (argc > 1) { + ++argv; + --argc; + + if (argv[0][0] == '-') { + if (parsecmd("defs", &argc, &argv, &defs, 1, false)) + continue; + + if (!strcmp(argv[0]+1, "debug")) { + OPTS_OPTION_BOOL(OPTION_DEBUG) = true; + continue; + } + if (!strcmp(argv[0]+1, "nocolor")) { + con_color(0); + continue; + } + + con_err("invalid argument %s\n", argv[0]+1); + return -1; + } + } + succeed = test_perform("tests", defs); + + return (succeed) ? EXIT_SUCCESS : EXIT_FAILURE; +}