From dab8deca423fead72fa6c7385700dda1f65d160d Mon Sep 17 00:00:00 2001 From: Nunuhara Cabbage Date: Fri, 7 Feb 2020 19:49:39 -0800 Subject: [PATCH] Add ainedit utility The ainedit utility is a tool capable of modifying AIN files up to version 12 (Rance X). As far as I know, this is the first publicly released tool that can handle AIN files above version 7. The basic mode of operation is as follows: * dump the CODE section with aindump * edit the disassembled bytecode * assemble & insert the edited bytebode back into the original AIN file using ainedit E.g. aindump -c -o out.jam /path/to/Rance10.ain $EDITOR out.jam ainedit -c out.jam -o out.ain /path/to/Rance10.ain mv /path/to/Rance10.ain /path/to/Rance10.ain.backup mv out.ain /path/to/Rance10.ain ainedit is also capable of editing declarations (structures, functions, etc.) using the JSON (-j) output from aindump. There is currently one major deficiency in this tool: it does not rebuild the AIN file's switch table (SWI0 section). This means that you can't insert or delete instructions, as it would render the addresses stored in the switch table invalid. I hope to fix this soon. A number of changes have also been made to the aindump utility, since these tools need to work together. --- include/cJSON.h | 2 + include/system4/ain.h | 60 +- include/system4/instructions.h | 8 +- src/ain.c | 245 ++++- src/aindump/aindump.c | 46 +- src/aindump/dasm.c | 116 +- src/aindump/json.c | 6 +- src/aindump/meson.build | 10 + src/ainedit/ainedit.c | 116 ++ src/ainedit/ainedit.h | 39 + src/ainedit/asm.c | 411 +++++++ src/ainedit/asm_lexer.l | 75 ++ src/ainedit/asm_lexer.yy.c | 1886 ++++++++++++++++++++++++++++++++ src/ainedit/asm_parser.tab.c | 1604 +++++++++++++++++++++++++++ src/ainedit/asm_parser.tab.h | 106 ++ src/ainedit/asm_parser.y | 141 +++ src/ainedit/json.c | 521 +++++++++ src/ainedit/meson.build | 33 + src/ainedit/repack.c | 439 ++++++++ src/instructions.c | 25 +- src/meson.build | 14 +- 21 files changed, 5834 insertions(+), 69 deletions(-) create mode 100644 src/aindump/meson.build create mode 100644 src/ainedit/ainedit.c create mode 100644 src/ainedit/ainedit.h create mode 100644 src/ainedit/asm.c create mode 100644 src/ainedit/asm_lexer.l create mode 100644 src/ainedit/asm_lexer.yy.c create mode 100644 src/ainedit/asm_parser.tab.c create mode 100644 src/ainedit/asm_parser.tab.h create mode 100644 src/ainedit/asm_parser.y create mode 100644 src/ainedit/json.c create mode 100644 src/ainedit/meson.build create mode 100644 src/ainedit/repack.c diff --git a/include/cJSON.h b/include/cJSON.h index 753b1ad..3e7154e 100644 --- a/include/cJSON.h +++ b/include/cJSON.h @@ -277,6 +277,8 @@ CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); /* Macro for iterating over an array or object */ #define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) +#define cJSON_ArrayForEachIndex(i, element, array) for(element = (array != NULL) ? (array)->child : NULL, i = 0; element != NULL; element = element->next, i++) + /* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ CJSON_PUBLIC(void *) cJSON_malloc(size_t size); CJSON_PUBLIC(void) cJSON_free(void *object); diff --git a/include/system4/ain.h b/include/system4/ain.h index 508b96e..66cb5df 100644 --- a/include/system4/ain.h +++ b/include/system4/ain.h @@ -115,7 +115,8 @@ enum ain_data_type { case AIN_REF_ARRAY_BOOL: \ case AIN_REF_LONG_INT: \ case AIN_REF_ARRAY_LONG_INT: \ - case AIN_REF_ARRAY_DELEGATE + case AIN_REF_ARRAY_DELEGATE: \ + case AIN_REF_ARRAY enum ain_variable_type { AIN_VAR_LOCAL, @@ -224,6 +225,13 @@ struct ain_enum { }; struct kh_func_ht_s; +struct kh_struct_ht_s; + +struct ain_section { + uint32_t addr; + uint32_t size; + bool present; +}; struct ain { char *ain_path; @@ -240,6 +248,7 @@ struct ain { int32_t nr_structures; struct ain_struct *structures; int32_t nr_messages; + int32_t msg1_uk; struct string **messages; int32_t main; int32_t alloc; @@ -254,16 +263,42 @@ struct ain { int32_t nr_filenames; char **filenames; int32_t ojmp; - int nr_function_types; + int32_t nr_function_types; + int32_t fnct_size; struct ain_function_type *function_types; - int nr_delegates; + int32_t nr_delegates; + int32_t delg_size; struct ain_function_type *delegates; int32_t nr_global_groups; char **global_group_names; int32_t nr_enums; struct ain_enum *enums; + // file map + struct ain_section VERS; + struct ain_section KEYC; + struct ain_section CODE; + struct ain_section FUNC; + struct ain_section GLOB; + struct ain_section GSET; + struct ain_section STRT; + struct ain_section MSG0; + struct ain_section MSG1; + struct ain_section MAIN; + struct ain_section MSGF; + struct ain_section HLL0; + struct ain_section SWI0; + struct ain_section GVER; + struct ain_section STR0; + struct ain_section FNAM; + struct ain_section OJMP; + struct ain_section FNCT; + struct ain_section DELG; + struct ain_section OBJG; + struct ain_section ENUM; + struct kh_func_ht_s *_func_ht; + struct kh_struct_ht_s *_struct_ht; }; const char *ain_strerror(int error); @@ -272,6 +307,25 @@ char *ain_strtype_d(struct ain *ain, struct ain_type *v); const char *ain_variable_to_string(struct ain *ain, struct ain_variable *v); uint8_t *ain_read(const char *path, long *len, int *error); struct ain *ain_open(const char *path, int *error); +void ain_decrypt(uint8_t *buf, size_t len); + +struct ain_function *ain_get_function(struct ain *ain, char *name); +int ain_get_function_index(struct ain *ain, struct ain_function *f); +struct ain_struct *ain_get_struct(struct ain *ain, char *name); + void ain_free(struct ain *ain); +void ain_free_functions(struct ain *ain); +void ain_free_globals(struct ain *ain); +void ain_free_initvals(struct ain *ain); +void ain_free_structures(struct ain *ain); +void ain_free_messages(struct ain *ain); +void ain_free_libraries(struct ain *ain); +void ain_free_switches(struct ain *ain); +void ain_free_strings(struct ain *ain); +void ain_free_filenames(struct ain *ain); +void ain_free_function_types(struct ain *ain); +void ain_free_delegates(struct ain *ain); +void ain_free_global_groups(struct ain *ain); +void ain_free_enums(struct ain *ain); #endif /* SYSTEM4_AIN_H */ diff --git a/include/system4/instructions.h b/include/system4/instructions.h index 3c9dca2..7010ff4 100644 --- a/include/system4/instructions.h +++ b/include/system4/instructions.h @@ -328,10 +328,10 @@ enum opcode DG_NEW, DG_STR_TO_METHOD, - OP_0x102 = 0x102, - OP_0x103 = 0x103, - OP_0x104 = 0x104, - OP_0x105 = 0x105, + OP_0X102 = 0x102, + OP_0X103 = 0x103, + OP_0X104 = 0x104, + OP_0X105 = 0x105, NR_OPCODES }; diff --git a/src/ain.c b/src/ain.c index 60c6ca6..043a7f0 100644 --- a/src/ain.c +++ b/src/ain.c @@ -40,10 +40,10 @@ struct func_list { #define func_list_size(nr_slots) (sizeof(struct func_list) + sizeof(struct ain_function*)*(nr_slots)) KHASH_MAP_INIT_STR(func_ht, struct func_list*); +KHASH_MAP_INIT_STR(struct_ht, struct ain_struct*); static void init_func_ht(struct ain *ain) { - ain->_func_ht = kh_init(func_ht); for (int i = 0; i < ain->nr_functions; i++) { int ret; khiter_t k = kh_put(func_ht, ain->_func_ht, ain->functions[i].name, &ret); @@ -66,6 +66,21 @@ static void init_func_ht(struct ain *ain) } } +static void init_struct_ht(struct ain *ain) +{ + for (int i = 0; i < ain->nr_structures; i++) { + int ret; + khiter_t k = kh_put(struct_ht, ain->_struct_ht, ain->structures[i].name, &ret); + if (!ret) { + ERROR("Duplicate structure names: '%s'", ain->structures[i].name); + } else if (ret == 1) { + kh_value(ain->_struct_ht, k) = &ain->structures[i]; + } else { + ERROR("Failed to insert struct into hash table (%d)", ret); + } + } +} + static struct func_list *get_function(struct ain *ain, const char *name) { int ret; @@ -75,6 +90,51 @@ static struct func_list *get_function(struct ain *ain, const char *name) return kh_value(ain->_func_ht, k); } +struct ain_function *ain_get_function(struct ain *ain, char *name) +{ + size_t len; + long n = 0; + + // handle name#index syntax + for (len = 0; name[len]; len++) { + if (name[len] == '#') { + char *endptr; + n = strtol(name+len+1, &endptr, 10); + if (!name[len+1] || *endptr || n < 0) + ERROR("Invalid function name: '%s'", name); + name[len] = '\0'; + break; + } + } + + struct func_list *funs = get_function(ain, name); + if (!funs || n >= funs->nr_slots) + return NULL; + return funs->slots[n]; +} + +int ain_get_function_index(struct ain *ain, struct ain_function *f) +{ + struct func_list *funs = get_function(ain, f->name); + if (!funs) + goto err; + + for (int i = 0; i < funs->nr_slots; i++) { + if (funs->slots[i] == f) + return i; + } +err: + ERROR("Invalid function: '%s'", f->name); +} + +struct ain_struct *ain_get_struct(struct ain *ain, char *name) +{ + khiter_t k = kh_get(struct_ht, ain->_struct_ht, name); + if (k == kh_end(ain->_struct_ht)) + return NULL; + return kh_value(ain->_struct_ht, k); +} + static const char *errtab[AIN_MAX_ERROR] = { [AIN_SUCCESS] = "Success", [AIN_FILE_ERROR] = "Error opening AIN file", @@ -150,8 +210,6 @@ char *ain_strtype_d(struct ain *ain, struct ain_type *v) case AIN_STRUCT: if (v->struc == -1 || !ain) return strdup("struct"); - if (v->struc < 0 || v->struc >= ain->nr_structures) - ERROR("WTF: %d, %d", v->struc, ain->nr_structures); return strdup(ain->structures[v->struc].name); case AIN_ARRAY_INT: return array_type_string("array@int", v->rank); case AIN_ARRAY_FLOAT: return array_type_string("array@float", v->rank); @@ -257,6 +315,7 @@ struct ain_reader { uint8_t *buf; size_t size; size_t index; + struct ain_section *section; }; static int32_t read_int32(struct ain_reader *r) @@ -623,17 +682,31 @@ struct ain_enum *read_enums(struct ain_reader *r, int count, struct ain *ain) return enums; } +static void start_section(struct ain_reader *r, struct ain_section *section) +{ + if (r->section) + r->section->size = r->index - r->section->addr; + r->section = section; + if (section) { + r->section->addr = r->index; + r->section->present = true; + r->index += 4; + } +} + static bool read_tag(struct ain_reader *r, struct ain *ain) { - if (r->index + 4 >= r->size) + if (r->index + 4 >= r->size) { + start_section(r, NULL); return false; + } uint8_t *tag_loc = r->buf + r->index; - r->index += 4; #define TAG_EQ(tag) !strncmp((char*)tag_loc, tag, 4) // FIXME: need to check len or could segfault on currupt AIN file if (TAG_EQ("VERS")) { + start_section(r, &ain->VERS); ain->version = read_int32(r); if (ain->version >= 11) { instructions[CALLHLL].nr_args = 3; @@ -643,65 +716,89 @@ static bool read_tag(struct ain_reader *r, struct ain *ain) instructions[CALLMETHOD].args[0] = T_INT; } } else if (TAG_EQ("KEYC")) { + start_section(r, &ain->KEYC); ain->keycode = read_int32(r); } else if (TAG_EQ("CODE")) { + start_section(r, &ain->CODE); ain->code_size = read_int32(r); ain->code = read_bytes(r, ain->code_size); } else if (TAG_EQ("FUNC")) { + start_section(r, &ain->FUNC); ain->nr_functions = read_int32(r); ain->functions = read_functions(r, ain->nr_functions, ain); init_func_ht(ain); } else if (TAG_EQ("GLOB")) { + start_section(r, &ain->GLOB); ain->nr_globals = read_int32(r); ain->globals = read_globals(r, ain->nr_globals, ain); } else if (TAG_EQ("GSET")) { + start_section(r, &ain->GSET); ain->nr_initvals = read_int32(r); ain->global_initvals = read_initvals(r, ain->nr_initvals); } else if (TAG_EQ("STRT")) { + start_section(r, &ain->STRT); ain->nr_structures = read_int32(r); ain->structures = read_structures(r, ain->nr_structures, ain); + init_struct_ht(ain); } else if (TAG_EQ("MSG0")) { + start_section(r, &ain->MSG0); ain->nr_messages = read_int32(r); ain->messages = read_vm_strings(r, ain->nr_messages); } else if (TAG_EQ("MSG1")) { + start_section(r, &ain->MSG1); ain->nr_messages = read_int32(r); - read_int32(r); // ??? + ain->msg1_uk = read_int32(r); // ??? ain->messages = read_msg1_strings(r, ain->nr_messages); } else if (TAG_EQ("MAIN")) { + start_section(r, &ain->MAIN); ain->main = read_int32(r); } else if (TAG_EQ("MSGF")) { + start_section(r, &ain->MSGF); ain->msgf = read_int32(r); } else if (TAG_EQ("HLL0")) { + start_section(r, &ain->HLL0); ain->nr_libraries = read_int32(r); ain->libraries = read_libraries(r, ain->nr_libraries); } else if (TAG_EQ("SWI0")) { + start_section(r, &ain->SWI0); ain->nr_switches = read_int32(r); ain->switches = read_switches(r, ain->nr_switches); } else if (TAG_EQ("GVER")) { + start_section(r, &ain->GVER); ain->game_version = read_int32(r); } else if (TAG_EQ("STR0")) { + start_section(r, &ain->STR0); ain->nr_strings = read_int32(r); ain->strings = read_vm_strings(r, ain->nr_strings); } else if (TAG_EQ("FNAM")) { + start_section(r, &ain->FNAM); ain->nr_filenames = read_int32(r); ain->filenames = read_strings(r, ain->nr_filenames); } else if (TAG_EQ("OJMP")) { + start_section(r, &ain->OJMP); ain->ojmp = read_int32(r); } else if (TAG_EQ("FNCT")) { - read_int32(r); // ??? + start_section(r, &ain->FNCT); + ain->fnct_size = read_int32(r); ain->nr_function_types = read_int32(r); ain->function_types = read_function_types(r, ain->nr_function_types, ain); } else if (TAG_EQ("DELG")) { - read_int32(r); // ??? + start_section(r, &ain->DELG); + ain->delg_size = read_int32(r); ain->nr_delegates = read_int32(r); ain->delegates = read_function_types(r, ain->nr_delegates, ain); } else if (TAG_EQ("OBJG")) { + start_section(r, &ain->OBJG); ain->nr_global_groups = read_int32(r); ain->global_group_names = read_strings(r, ain->nr_global_groups); } else if (TAG_EQ("ENUM")) { + start_section(r, &ain->ENUM); + ain->ENUM.present = true; ain->nr_enums = read_int32(r); ain->enums = read_enums(r, ain->nr_enums, ain); } else { + start_section(r, NULL); + WARNING("Junk at end of AIN file?"); return false; } #undef TAG_EQ @@ -713,6 +810,7 @@ static void distribute_initvals(struct ain *ain) { for (int i = 0; i < ain->nr_initvals; i++) { struct ain_variable *g = &ain->globals[ain->global_initvals[i].global_index]; + g->has_initval = true; if (ain->global_initvals[i].data_type == AIN_STRING) g->initval.s = ain->global_initvals[i].string_value; else @@ -730,7 +828,14 @@ static uint8_t *decompress_ain(uint8_t *in, long *len) return NULL; out = xmalloc(out_len); - if (Z_OK != uncompress(out, (unsigned long*)&out_len, in+16, in_len)) { + int r = uncompress(out, (unsigned long*)&out_len, in+16, in_len); + if (r != Z_OK) { + if (r == Z_BUF_ERROR) + WARNING("uncompress failed: Z_BUF_ERROR"); + else if (r == Z_MEM_ERROR) + WARNING("uncompress failed: Z_MEM_ERROR"); + else if (r == Z_DATA_ERROR) + WARNING("uncompress failed: Z_DATA_ERROR"); free(out); return NULL; } @@ -773,7 +878,7 @@ static void update(uint32_t *state) } } -static void decrypt_ain(uint8_t *buf, size_t len) +void ain_decrypt(uint8_t *buf, size_t len) { uint32_t state[0x270]; uint32_t key = 0x5D3E3; @@ -800,7 +905,7 @@ static bool ain_is_encrypted(uint8_t *buf) uint8_t magic[8]; memcpy(magic, buf, 8); - decrypt_ain(magic, 8); + ain_decrypt(magic, 8); return !strncmp((char*)magic, "VERS", 4) && !magic[5] && !magic[6] && !magic[7]; } @@ -835,7 +940,7 @@ uint8_t *ain_read(const char *path, long *len, int *error) free(buf); buf = uc; } else if (ain_is_encrypted(buf)) { - decrypt_ain(buf, *len); + ain_decrypt(buf, *len); } else { printf("%.4s\n", buf); *error = AIN_UNRECOGNIZED_FORMAT; @@ -853,6 +958,8 @@ struct ain *ain_open(const char *path, int *error) long len; struct ain *ain = NULL; uint8_t *buf = ain_read(path, &len, error); + if (!buf) + goto err; // read data into ain struct struct ain_reader r = { @@ -861,6 +968,8 @@ struct ain *ain_open(const char *path, int *error) .size = len }; ain = calloc(1, sizeof(struct ain)); + ain->_func_ht = kh_init(func_ht); + ain->_struct_ht = kh_init(struct_ht); while (read_tag(&r, ain)); if (!ain->version) { *error = AIN_INVALID; @@ -889,7 +998,7 @@ static void ain_free_variables(struct ain_variable *vars, int nr_vars) free(vars); } -static void ain_free_function_types(struct ain_function_type *funs, int n) +static void _ain_free_function_types(struct ain_function_type *funs, int n) { for (int i = 0; i < n; i++) { free(funs[i].name); @@ -899,7 +1008,7 @@ static void ain_free_function_types(struct ain_function_type *funs, int n) free(funs); } -static void ain_free_strings(struct string **strings, int n) +static void ain_free_vmstrings(struct string **strings, int n) { for (int i = 0; i < n; i++) { free_string(strings[i]); @@ -915,33 +1024,53 @@ static void ain_free_cstrings(char **strings, int n) free(strings); } -void ain_free(struct ain *ain) +void ain_free_functions(struct ain *ain) { - free(ain->code); - for (int f = 0; f < ain->nr_functions; f++) { free(ain->functions[f].name); free(ain->functions[f].return_type.array_type); ain_free_variables(ain->functions[f].vars, ain->functions[f].nr_vars); } free(ain->functions); + ain->functions = NULL; + ain->nr_functions = 0; +} +void ain_free_globals(struct ain *ain) +{ ain_free_variables(ain->globals, ain->nr_globals); + ain->globals = NULL; + ain->nr_globals = 0; +} - for (int i = 0; i < ain->nr_initvals; i++) { - if (ain->global_initvals[i].data_type != AIN_STRING) - continue; - free(ain->global_initvals[i].string_value); - } +void ain_free_initvals(struct ain *ain) +{ free(ain->global_initvals); + ain->global_initvals = NULL; + ain->nr_initvals = 0; +} +void ain_free_structures(struct ain *ain) +{ for (int s = 0; s < ain->nr_structures; s++) { free(ain->structures[s].name); free(ain->structures[s].interfaces); ain_free_variables(ain->structures[s].members, ain->structures[s].nr_members); } free(ain->structures); + ain->structures = NULL; + ain->nr_structures = 0; +} +void ain_free_messages(struct ain *ain) +{ + ain_free_vmstrings(ain->messages, ain->nr_messages); + ain->messages = NULL; + ain->nr_messages = 0; +} + +void ain_free_libraries(struct ain *ain) +{ for (int lib = 0; lib < ain->nr_libraries; lib++) { free(ain->libraries[lib].name); for (int f = 0; f < ain->libraries[lib].nr_functions; f++) { @@ -954,30 +1083,88 @@ void ain_free(struct ain *ain) free(ain->libraries[lib].functions); } free(ain->libraries); + ain->libraries = NULL; + ain->nr_libraries = 0; +} +void ain_free_switches(struct ain *ain) +{ for (int i = 0; i < ain->nr_switches; i++) { free(ain->switches[i].cases); } free(ain->switches); + ain->switches = NULL; + ain->nr_switches = 0; +} +void ain_free_strings(struct ain *ain) +{ + ain_free_vmstrings(ain->strings, ain->nr_strings); + ain->strings = NULL; + ain->nr_strings = 0; +} + +void ain_free_filenames(struct ain *ain) +{ + ain_free_cstrings(ain->filenames, ain->nr_filenames); + ain->filenames = NULL; + ain->nr_filenames = 0; +} + +void ain_free_function_types(struct ain *ain) +{ + _ain_free_function_types(ain->function_types, ain->nr_function_types); + ain->function_types = NULL; + ain->nr_function_types = 0; +} + +void ain_free_delegates(struct ain *ain) +{ + _ain_free_function_types(ain->delegates, ain->nr_delegates); + ain->delegates = NULL; + ain->nr_delegates = 0; +} + +void ain_free_global_groups(struct ain *ain) +{ + ain_free_cstrings(ain->global_group_names, ain->nr_global_groups); + ain->global_group_names = NULL; + ain->nr_global_groups = 0; +} + +void ain_free_enums(struct ain *ain) +{ for (int i = 0; i < ain->nr_enums; i++) { free(ain->enums[i].name); free(ain->enums[i].symbols); } free(ain->enums); + ain->enums = NULL; + ain->nr_enums = 0; +} - ain_free_function_types(ain->function_types, ain->nr_function_types); - ain_free_function_types(ain->delegates, ain->nr_delegates); +void ain_free(struct ain *ain) +{ + free(ain->code); - ain_free_strings(ain->strings, ain->nr_strings); - ain_free_strings(ain->messages, ain->nr_messages); - - ain_free_cstrings(ain->filenames, ain->nr_filenames); - ain_free_cstrings(ain->global_group_names, ain->nr_global_groups); + ain_free_functions(ain); + ain_free_globals(ain); + ain_free_initvals(ain); + ain_free_structures(ain); + ain_free_messages(ain); + ain_free_libraries(ain); + ain_free_switches(ain); + ain_free_strings(ain); + ain_free_filenames(ain); + ain_free_function_types(ain); + ain_free_delegates(ain); + ain_free_global_groups(ain); + ain_free_enums(ain); struct func_list *list; kh_foreach_value(ain->_func_ht, list, free(list)); kh_destroy(func_ht, ain->_func_ht); + kh_destroy(struct_ht, ain->_struct_ht); free(ain); } diff --git a/src/aindump/aindump.c b/src/aindump/aindump.c index 91da922..e84c7ae 100644 --- a/src/aindump/aindump.c +++ b/src/aindump/aindump.c @@ -50,6 +50,7 @@ static void usage(void) puts(" -A, --audit Audit AIN file for xsystem4 compatibility"); puts(" -d, --decrypt Dump decrypted AIN file"); puts(" -j, --json Dump to JSON format"); + puts(" --map Dump AIN file map"); } static void print_sjis(FILE *f, const char *s) @@ -289,7 +290,41 @@ static void ain_audit(FILE *f, struct ain *ain) fflush(f); } -static void ain_decrypt(FILE *f, const char *path) +static void print_section(FILE *f, const char *name, struct ain_section *section) +{ + if (section->present) + fprintf(f, "%s: %08x -> %08x\n", name, section->addr, section->addr + section->size); +} + +static void ain_dump_map(FILE *f, struct ain *ain) +{ + print_section(f, "VERS", &ain->VERS); + print_section(f, "KEYC", &ain->KEYC); + print_section(f, "CODE", &ain->CODE); + print_section(f, "FUNC", &ain->FUNC); + print_section(f, "GLOB", &ain->GLOB); + print_section(f, "GSET", &ain->GSET); + print_section(f, "STRT", &ain->STRT); + print_section(f, "MSG0", &ain->MSG0); + print_section(f, "MSG1", &ain->MSG1); + print_section(f, "MAIN", &ain->MAIN); + print_section(f, "MSGF", &ain->MSGF); + print_section(f, "HLL0", &ain->HLL0); + print_section(f, "SWI0", &ain->SWI0); + print_section(f, "GVER", &ain->GVER); + print_section(f, "STR0", &ain->STR0); + print_section(f, "FNAM", &ain->FNAM); + print_section(f, "OJMP", &ain->OJMP); + print_section(f, "FNCT", &ain->FNCT); + print_section(f, "DELG", &ain->DELG); + print_section(f, "OBJG", &ain->OBJG); + print_section(f, "ENUM", &ain->ENUM); + + fprintf(f, "FNCT_SIZE = %d\n", ain->delg_size); + fprintf(f, "FNCT.SIZE = %d\n", ain->DELG.size); +} + +static void dump_decrypted(FILE *f, const char *path) { int err; long len; @@ -321,6 +356,7 @@ int main(int argc, char *argv[]) bool dump_global_group_names = false; bool dump_enums = false; bool dump_json = false; + bool dump_map = false; bool audit = false; bool decrypt = false; char *output_file = NULL; @@ -348,6 +384,7 @@ int main(int argc, char *argv[]) { "audit", no_argument, 0, 'A' }, { "decrypt", no_argument, 0, 'd' }, { "json", no_argument, 0, 'j' }, + { "map", no_argument, 0, 'M' }, { "output", required_argument, 0, 'o' }, }; int option_index = 0; @@ -412,6 +449,9 @@ int main(int argc, char *argv[]) case 'j': dump_json = true; break; + case 'M': + dump_map = true; + break; case 'o': output_file = xstrdup(optarg); break; @@ -436,7 +476,7 @@ int main(int argc, char *argv[]) } if (decrypt) { - ain_decrypt(output, argv[0]); + dump_decrypted(output, argv[0]); return 0; } @@ -475,6 +515,8 @@ int main(int argc, char *argv[]) disassemble_ain(output, ain, true); if (dump_json) ain_dump_json(output, ain); + if (dump_map) + ain_dump_map(output, ain); if (audit) ain_audit(output, ain); diff --git a/src/aindump/dasm.c b/src/aindump/dasm.c index fe5d22d..23fe7fb 100644 --- a/src/aindump/dasm.c +++ b/src/aindump/dasm.c @@ -30,6 +30,7 @@ struct dasm_state { struct ain *ain; + uint32_t flags; FILE *out; size_t addr; int func; @@ -90,9 +91,11 @@ static char *prepare_string(const char *str, const char *escape_chars, const cha char *u = sjis2utf(str, strlen(str)); // count number of required escapes - for (int i = 0; str[i]; i++) { + for (int i = 0; u[i]; i++) { + if (u[i] & 0x80) + continue; for (int j = 0; escape_chars[j]; j++) { - if (str[i] == escape_chars[j]) { + if (u[i] == escape_chars[j]) { escapes++; break; } @@ -151,7 +154,64 @@ static void print_identifier(struct dasm_state *dasm, const char *str) print_sjis(dasm, str); } -static void print_argument(struct dasm_state *dasm, int32_t arg, enum instruction_argtype type) +static void print_local_variable(struct dasm_state *dasm, struct ain_function *func, int varno) +{ + int dup_no = 0; // nr of duplicate-named variables preceding varno + for (int i = 0; i < func->nr_vars; i++) { + if (i == varno) + break; + if (!strcmp(func->vars[i].name, func->vars[varno].name)) + dup_no++; + } + + // if variable name is ambiguous, add #n suffix + char *name; + char buf[512]; + if (dup_no) { + snprintf(buf, 512, "%s#%d", func->vars[varno].name, dup_no); + name = buf; + } else { + name = func->vars[varno].name; + } + + print_identifier(dasm, name); +} + +static void print_function_name(struct dasm_state *dasm, struct ain_function *func) +{ + int i = ain_get_function_index(dasm->ain, func); + + char *name = func->name; + char buf[512]; + if (i > 0) { + snprintf(buf, 512, "%s#%d", func->name, i); + name = buf; + } + + print_identifier(dasm, name); +} + +static void print_hll_function_name(struct dasm_state *dasm, struct ain_library *lib, int fno) +{ + int dup_no = 0; + for (int i = 0; i < lib->nr_functions; i++) { + if (i == fno) + break; + if (!strcmp(lib->functions[i].name, lib->functions[fno].name)) + dup_no++; + } + + char *name = lib->functions[fno].name; + char buf[512]; + if (dup_no) { + snprintf(buf, 512, "%s#%d", lib->functions[fno].name, dup_no); + name = buf; + } + + print_identifier(dasm, name); +} + +static void print_argument(struct dasm_state *dasm, int32_t arg, enum instruction_argtype type, possibly_unused const char **comment) { if (dasm->raw) { fprintf(dasm->out, "0x%x", arg); @@ -178,7 +238,7 @@ static void print_argument(struct dasm_state *dasm, int32_t arg, enum instructio case T_FUNC: if (arg < 0 || arg >= ain->nr_functions) DASM_ERROR(dasm, "Invalid function number: %d", arg); - print_identifier(dasm, ain->functions[arg].name); + print_function_name(dasm, &ain->functions[arg]); break; case T_DLG: if (arg < 0 || arg >= ain->nr_delegates) @@ -188,11 +248,15 @@ static void print_argument(struct dasm_state *dasm, int32_t arg, enum instructio case T_STRING: if (arg < 0 || arg >= ain->nr_strings) DASM_ERROR(dasm, "Invalid string number: %d", arg); + //fprintf(dasm->out, "0x%x ", arg); + //*comment = ain->strings[arg]->text; print_string(dasm, ain->strings[arg]->text); break; case T_MSG: if (arg < 0 || arg >= ain->nr_messages) DASM_ERROR(dasm, "Invalid message number: %d", arg); + //fprintf(dasm->out, "0x%x ", arg); + //*comment = ain->messages[arg]->text; print_string(dasm, ain->messages[arg]->text); break; case T_LOCAL: @@ -204,7 +268,8 @@ static void print_argument(struct dasm_state *dasm, int32_t arg, enum instructio } if (arg < 0 || arg >= ain->functions[dasm->func].nr_vars) DASM_ERROR(dasm, "Invalid variable number: %d", arg); - print_identifier(dasm, ain->functions[dasm->func].vars[arg].name); + print_local_variable(dasm, &ain->functions[dasm->func], arg); + //print_identifier(dasm, ain->functions[dasm->func].vars[arg].name); break; case T_GLOBAL: if (arg < 0 || arg >= ain->nr_globals) @@ -249,18 +314,28 @@ static void print_arguments(struct dasm_state *dasm, const struct instruction *i if (instr->opcode == CALLHLL) { int32_t lib = LittleEndian_getDW(dasm->ain->code, dasm->addr + 2); int32_t fun = LittleEndian_getDW(dasm->ain->code, dasm->addr + 6); - fprintf(dasm->out, " %s.%s", dasm->ain->libraries[lib].name, dasm->ain->libraries[lib].functions[fun].name); + fprintf(dasm->out, " %s ", dasm->ain->libraries[lib].name); + print_hll_function_name(dasm, &dasm->ain->libraries[lib], fun); + if (dasm->ain->version >= 11) { + fprintf(dasm->out, " %d", LittleEndian_getDW(dasm->ain->code, dasm->addr + 10)); + } return; } if (instr->opcode == FUNC) { fputc(' ', dasm->out); - ain_dump_function(dasm->out, dasm->ain, &dasm->ain->functions[dasm->func]); + fprintf(dasm->out, "0x%x", dasm->func); + //ain_dump_function(dasm->out, dasm->ain, &dasm->ain->functions[dasm->func]); return; } + const char *comment = NULL; for (int i = 0; i < instr->nr_args; i++) { fputc(' ', dasm->out); - print_argument(dasm, LittleEndian_getDW(dasm->ain->code, dasm->addr + 2 + i*4), instr->args[i]); + print_argument(dasm, LittleEndian_getDW(dasm->ain->code, dasm->addr + 2 + i*4), instr->args[i], &comment); + } + if (comment) { + fprintf(dasm->out, "; "); + print_string(dasm, comment); } } @@ -275,7 +350,10 @@ static void dasm_enter_function(struct dasm_state *dasm, int fno) dasm->func_stack[0] = dasm->func; dasm->func = fno; - fprintf(dasm->out, "; FUNC 0x%x\n", fno); + fprintf(dasm->out, "; "); + ain_dump_function(dasm->out, dasm->ain, &dasm->ain->functions[fno]); + fputc('\n', dasm->out); + //fprintf(dasm->out, "; FUNC 0x%x\n", fno); } static void dasm_leave_function(struct dasm_state *dasm) @@ -328,6 +406,20 @@ static char *genlabel(size_t addr) return strdup(name); } +static char *switch_label(int switch_id, possibly_unused int type, struct ain_switch_case *c) +{ + // TODO: replace with CASE pseudo-op, e.g. + // ... + // STRSWITCH + // CASE "case one" + // ... + // CASE "case two" + // ... + char name[512]; + snprintf(name, 512, "switch%d_case_%d", switch_id, c->value); + return strdup(name); +} + static void generate_labels(struct dasm_state *dasm) { label_table_init(); @@ -341,6 +433,12 @@ static void generate_labels(struct dasm_state *dasm) } dasm->addr += instruction_width(instr->opcode); } + for (int i = 0; i < dasm->ain->nr_switches; i++) { + for (int j = 0; j < dasm->ain->switches[i].nr_cases; j++) { + struct ain_switch_case *c = &dasm->ain->switches[i].cases[j]; + add_label(switch_label(i, dasm->ain->switches[i].case_type, c), c->address); + } + } } void dasm_init(struct dasm_state *dasm, FILE *out, struct ain *ain, bool raw) diff --git a/src/aindump/json.c b/src/aindump/json.c index 45c981d..22604c3 100644 --- a/src/aindump/json.c +++ b/src/aindump/json.c @@ -141,7 +141,7 @@ static cJSON *ain_library_to_json(struct ain_library *lib) for (int i = 0; i < lib->nr_functions; i++) { cJSON *f = cJSON_CreateObject(); cJSON_AddStringToObject(f, "name", lib->functions[i].name); - cJSON_AddNumberToObject(f, "type", lib->functions[i].data_type); + cJSON_AddNumberToObject(f, "return-type", lib->functions[i].data_type); cJSON *args = cJSON_CreateArray(); for (int j = 0; j < lib->functions[i].nr_arguments; j++) { @@ -237,8 +237,6 @@ static cJSON *ain_to_json(struct ain *ain) } cJSON_AddItemToObject(j, "globals", a); - // TODO: use initval in ain_variable structure for global initvals - // STRT: structures a = cJSON_CreateArray(); for (int i = 0; i < ain->nr_structures; i++) { @@ -279,7 +277,7 @@ static cJSON *ain_to_json(struct ain *ain) // OJMP: ??? cJSON_AddNumberToObject(j, "ojmp", ain->ojmp); - // FUNCT: function types + // FNCT: function types if (ain->nr_function_types > 0) { a = cJSON_CreateArray(); for (int i = 0; i < ain->nr_function_types; i++) { diff --git a/src/aindump/meson.build b/src/aindump/meson.build new file mode 100644 index 0000000..a9d17fd --- /dev/null +++ b/src/aindump/meson.build @@ -0,0 +1,10 @@ +aindump = ['../cJSON.c', + 'aindump.c', + 'dasm.c', + 'json.c', +] + +executable('aindump', aindump, + dependencies : [libm, zlib], + include_directories : incdir, + link_with : libsys4) diff --git a/src/ainedit/ainedit.c b/src/ainedit/ainedit.c new file mode 100644 index 0000000..29a0cb0 --- /dev/null +++ b/src/ainedit/ainedit.c @@ -0,0 +1,116 @@ +/* Copyright (C) 2019 Nunuhara Cabbage + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + */ + +#include +#include +#include +#include +#include "ainedit.h" +#include "system4.h" +#include "system4/ain.h" + +static void usage(void) +{ + puts("Usage: ainedit [options...] input-file"); + puts(" Edit AIN files."); + puts(""); + puts(" -h, --help Display this message and exit"); + puts(" -c, --code Update the CODE section (assemble .jam file)"); + puts(" -j, --json Update AIN file from JSON data"); + puts(" -o, --output Set output file path"); + puts(" --raw Read code in raw mode"); + puts(" --no-strings Read code in no-strings mode"); + //puts(" -p,--project Build AIN from project file"); +} + +int main(int argc, char *argv[]) +{ + struct ain *ain; + int err = AIN_SUCCESS; + const char *code_file = NULL; + const char *decl_file = NULL; + const char *output_file = NULL; + uint32_t flags = 0; + while (1) { + static struct option long_options[] = { + { "help", no_argument, 0, 'h' }, + { "code", required_argument, 0, 'c' }, + { "json", required_argument, 0, 'j' }, + { "output", required_argument, 0, 'o' }, + { "raw", no_argument, 0, 'R' }, + { "no-strings", no_argument, 0, 'N' }, + }; + int option_index = 0; + int c; + + c = getopt_long(argc, argv, "hc:j:o:", long_options, &option_index); + if (c == -1) + break; + + switch (c) { + case 'h': + usage(); + return 0; + case 'c': + code_file = optarg; + break; + case 'j': + decl_file = optarg; + break; + case 'o': + output_file = optarg; + break; + case 'R': + flags |= ASM_RAW; + break; + case 'N': + flags |= ASM_NO_STRINGS; + break; + case '?': + ERROR("Unknown command line argument"); + } + } + argc -= optind; + argv += optind; + + if (argc != 1) { + usage(); + ERROR("Wrong number of arguments."); + } + + if (!output_file) { + usage(); + ERROR("No output file given"); + } + + if (!(ain = ain_open(argv[0], &err))) { + ERROR("Failed to open ain file: %s", ain_strerror(err)); + } + + if (code_file) { + asm_assemble_jam(code_file, ain, flags); + } + + if (decl_file) { + read_declarations(decl_file, ain); + } + + NOTICE("Writing AIN file..."); + ain_write(output_file, ain); + + ain_free(ain); + return 0; +} diff --git a/src/ainedit/ainedit.h b/src/ainedit/ainedit.h new file mode 100644 index 0000000..08d038a --- /dev/null +++ b/src/ainedit/ainedit.h @@ -0,0 +1,39 @@ +/* Copyright (C) 2019 Nunuhara Cabbage + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + */ + +#ifndef AINEDIT_AINEDIT_H +#define AINEDIT_AINEDIT_H + +#include +#include "system4/ain.h" +#include "system4/instructions.h" + +enum { + ASM_RAW = 1, + ASM_NO_STRINGS = 2, +}; + +// asm.c +void asm_assemble_jam(const char *filename, struct ain *ain, uint32_t flags); +struct instruction *asm_get_instruction(const char *name); + +// json.c +void read_declarations(const char *filename, struct ain *ain); + +// repack.c +void ain_write(const char *filename, struct ain *ain); + +#endif /* AINEDIT_AINEDIT_H */ diff --git a/src/ainedit/asm.c b/src/ainedit/asm.c new file mode 100644 index 0000000..f97e462 --- /dev/null +++ b/src/ainedit/asm.c @@ -0,0 +1,411 @@ +/* Copyright (C) 2019 Nunuhara Cabbage + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + */ + +#include +#include +#include +#include +#include +#include +#include "ainedit.h" +#include "system4.h" +#include "system4/ain.h" +#include "system4/instructions.h" +#include "system4/string.h" +#include "system4/utfsjis.h" +#include "asm_parser.tab.h" + +extern FILE *yyin; + +KHASH_MAP_INIT_STR(string_ht, size_t); + +// TODO: better error messages +#define ASM_ERROR(state, ...) ERROR(__VA_ARGS__) + +struct string_table { + struct string **strings; + size_t size; + size_t allocated; +}; + +struct asm_state { + struct ain *ain; + uint32_t flags; + uint8_t *buf; + size_t buf_ptr; + size_t buf_len; + int func; + int lib; + struct string_table strings; + struct string_table messages; + khash_t(string_ht) *strings_index; + khash_t(string_ht) *messages_index; +}; + +static int string_table_add(struct string_table *t, const char *s) +{ + if (!t->allocated) { + t->allocated = 4096; + t->strings = xmalloc(t->allocated * sizeof(struct string*)); + } else if (t->allocated <= t->size) { + t->allocated *= 2; + t->strings = xrealloc(t->strings, t->allocated * sizeof(struct string*)); + } + + t->strings[t->size++] = make_string(s, strlen(s)); + return t->size - 1; +} + +static int asm_add_message(struct asm_state *state, const char *s) +{ + char *u = utf2sjis(s, strlen(s)); + int i = string_table_add(&state->messages, u); + free(u); + return i; +} + +static int asm_add_string(struct asm_state *state, const char *s) +{ + int ret; + char *u = utf2sjis(s, strlen(s)); + khiter_t k = kh_put(string_ht, state->strings_index, u, &ret); + if (!ret) { + // nothing + } else if (ret == 1) { + kh_value(state->strings_index, k) = string_table_add(&state->strings, u); + } else { + ERROR("Hash table lookup failed (%d)", ret); + } + return kh_value(state->strings_index, k); +} + +static void init_asm_state(struct asm_state *state, struct ain *ain, uint32_t flags) +{ + memset(state, 0, sizeof(*state)); + state->ain = ain; + state->flags = flags; + state->func = -1; + state->lib = -1; + state->strings_index = kh_init(string_ht); + state->messages_index = kh_init(string_ht); +} + +static void fini_asm_state(struct asm_state *state) +{ + kh_destroy(string_ht, state->strings_index); + kh_destroy(string_ht, state->messages_index); +} + +static void asm_write_opcode(struct asm_state *state, uint16_t opcode) +{ +// if (state->buf_len - state->buf_ptr <= (size_t)instruction_width(opcode)) { + if (state->buf_len - state->buf_ptr <= 18) { + if (!state->buf) { + state->buf_len = 4096; + state->buf = xmalloc(state->buf_len); + } else { + state->buf_len = state->buf_len * 2; + state->buf = xrealloc(state->buf, state->buf_len); + } + } + + state->buf[state->buf_ptr++] = opcode & 0xFF; + state->buf[state->buf_ptr++] = (opcode & 0xFF00) >> 8; +} + +static void asm_write_argument(struct asm_state *state, uint32_t arg) +{ + state->buf[state->buf_ptr++] = (arg & 0x000000FF); + state->buf[state->buf_ptr++] = (arg & 0x0000FF00) >> 8; + state->buf[state->buf_ptr++] = (arg & 0x00FF0000) >> 16; + state->buf[state->buf_ptr++] = (arg & 0xFF000000) >> 24; +} + +struct instruction *asm_get_instruction(const char *name) +{ + for (int i = 0; i < NR_OPCODES; i++) { + if (!strcmp(name, instructions[i].name)) + return &instructions[i]; + } + return NULL; +} + +static char *parse_identifier(possibly_unused struct asm_state *state, char *s, int *n) +{ + char *delim = strchr(s, '#'); + if (!delim) { + *n = 0; + return s; + } + + *delim = '\0'; + delim++; + + char *endptr; + long nn = strtol(delim, &endptr, 10); + if (*delim && !*endptr) { + *n = nn; + return s; + } + + *delim = '#'; + ASM_ERROR(state, "Invalid identifier: '%s' (bad suffix)", s); +} + +static int32_t parse_integer_constant(possibly_unused struct asm_state *state, const char *arg) +{ + char *endptr; + errno = 0; + long i = strtol(arg, &endptr, 0); + if (errno || *endptr != '\0') + ASM_ERROR(state, "Invalid integer constant: '%s'", arg); + //if (i > INT32_MAX || i < INT32_MIN) + // ASM_ERROR(state, "Integer would be truncated: %ld -> %d", i, (int32_t)i); + return i; +} + +static uint32_t asm_resolve_arg(struct asm_state *state, enum instruction_argtype type, const char *arg) +{ + if (state->flags & ASM_RAW) + type = T_INT; + + switch (type) { + case T_INT: + return parse_integer_constant(state, arg); + case T_FLOAT: { + char *endptr; + union { int32_t i; float f; } v; + errno = 0; + v.f = strtof(arg, &endptr); + if (errno || *endptr != '\0') + ASM_ERROR(state, "Invalid float: %s", arg); + return v.i; + } + case T_ADDR: { + khiter_t k; + k = kh_get(label_table, label_table, arg); + if (k == kh_end(label_table)) + ASM_ERROR(state, "Unable to resolve label: '%s'", arg); + return kh_value(label_table, k); + } + case T_FUNC: { + char *u = utf2sjis(arg, strlen(arg)); + struct ain_function *f = ain_get_function(state->ain, u); + free(u); + if (!f) + ASM_ERROR(state, "Unable to resolve function: '%s'", arg); + return f - state->ain->functions; + } + case T_STRING: { + if (state->flags & ASM_NO_STRINGS) { + int32_t i = parse_integer_constant(state, arg); + if (i < 0 || i >= state->ain->nr_strings) + ASM_ERROR(state, "String index out of bounds: '%s'", arg); + return i; + } + return asm_add_string(state, arg); + } + case T_MSG: { + if (state->flags & ASM_NO_STRINGS) { + int32_t i = parse_integer_constant(state, arg); + if (i < 0 || i >= state->ain->nr_messages) + ASM_ERROR(state, "Message index out of bounds: '%s'", arg); + return i; + } + return asm_add_message(state, arg); + } + case T_LOCAL: { + int n, count = 0; + char *u = utf2sjis(arg, strlen(arg)); + u = parse_identifier(state, u, &n); + struct ain_function *f = &state->ain->functions[state->func]; + for (int i = 0; i < f->nr_vars; i++) { + if (!strcmp(u, f->vars[i].name)) { + if (count < n) { + count++; + continue; + } + free(u); + return i; + } + } + ASM_ERROR(state, "Unable to resolve local variable: '%s'", arg); + } + case T_GLOBAL: { + char *u = utf2sjis(arg, strlen(arg)); + for (int i = 0; i < state->ain->nr_globals; i++) { + if (!strcmp(u, state->ain->globals[i].name)) { + free(u); + return i; + } + } + ASM_ERROR(state, "Unable to resolve global variable: '%s'", arg); + } + case T_STRUCT: { + char *u = utf2sjis(arg, strlen(arg)); + struct ain_struct *s = ain_get_struct(state->ain, u); + free(u); + if (!s) + ASM_ERROR(state, "Unable to resolve struct: '%s'", arg); + return s - state->ain->structures; + } + case T_SYSCALL: { + for (int i = 0; i < NR_SYSCALLS; i++) { + if (!strcmp(arg, syscalls[i].name)) + return i; + } + ASM_ERROR(state, "Unable to resolve system call: '%s'", arg); + } + case T_HLL: { + for (int i = 0; i < state->ain->nr_libraries; i++) { + if (!strcmp(arg, state->ain->libraries[i].name)) { + state->lib = i; + return i; + } + } + ASM_ERROR(state, "Unable to resolve library: '%s'", arg); + } + case T_HLLFUNC: { + if (state->lib < 0) + ERROR("Tried to resolve library function without active library?"); + int n, count = 0; + char *u = utf2sjis(arg, strlen(arg)); + u = parse_identifier(state, u, &n); + for (int i = 0; i < state->ain->libraries[state->lib].nr_functions; i++) { + if (strcmp(u, state->ain->libraries[state->lib].functions[i].name)) + continue; + if (count < n) { + count++; + continue; + } + state->lib = -1; + free(u); + return i; + } + ASM_ERROR(state, "Unable to resolve library function: '%s.%s'", + state->ain->libraries[state->lib].name, arg); + } + case T_FILE: { + if (!state->ain->nr_filenames) + return atoi(arg); + char *u = utf2sjis(arg, strlen(arg)); + for (int i = 0; i < state->ain->nr_filenames; i++) { + if (!strcmp(u, state->ain->filenames[i])) { + free(u); + return i; + } + } + ASM_ERROR(state, "Unable to resolve filename: '%s'", arg); + } + case T_DLG: { + char *u = utf2sjis(arg, strlen(arg)); + for (int i = 0; i < state->ain->nr_delegates; i++) { + if (!strcmp(u, state->ain->delegates[i].name)) { + free(u); + return i; + } + } + ASM_ERROR(state, "Unable to resolve delegate: '%s'", arg); + } + default: + ASM_ERROR(state, "Unhandled argument type: %d", type); + } +} + +void asm_assemble_jam(const char *filename, struct ain *ain, uint32_t flags) +{ + struct asm_state state; + init_asm_state(&state, ain, flags); + + if (filename) { + if (!strcmp(filename, "-")) + yyin = stdin; + else + yyin = fopen(filename, "r"); + if (!yyin) + ERROR("Opening input file '%s': %s", filename, strerror(errno)); + } + label_table = kh_init(label_table); + NOTICE("Parsing..."); + yyparse(); + + NOTICE("Encoding..."); + for (size_t i = 0; i < kv_size(*parsed_code); i++) { + struct parse_instruction *instr = kv_A(*parsed_code, i); + struct instruction *idef = &instructions[instr->opcode]; + + // NOTE: special case: we need to record the new function address in the ain structure + if (idef->opcode == FUNC) { + state.func = asm_resolve_arg(&state, T_INT, kv_A(*instr->args, 0)->text); + state.ain->functions[state.func].address = state.buf_ptr + 6; + asm_write_opcode(&state, FUNC); + asm_write_argument(&state, state.func); + continue; + } + + asm_write_opcode(&state, instr->opcode); + for (int a = 0; a < idef->nr_args; a++) { + asm_write_argument(&state, asm_resolve_arg(&state, idef->args[a], kv_A(*instr->args, a)->text)); + } + } + + for (size_t i = 0; i < kv_size(*parsed_code); i++) { + struct parse_instruction *instr = kv_A(*parsed_code, i); + if (!instr->args) + continue; + for (size_t a = 0; a < kv_size(*instr->args); a++) { + free_string(kv_A(*instr->args, a)); + } + } + + for (int i = 0; i < ain->nr_switches; i++) { + if (ain->switches[i].case_type != 4) + continue; + for (int j = 0; j < ain->switches[i].nr_cases; j++) { + if (ain->switches[i].cases[j].value >= ain->nr_strings) + ERROR("Invalid string switch case"); + int c = asm_add_string(&state, ain->strings[ain->switches[i].cases[j].value]->text); + ain->switches[i].cases[j].value = c; + } + } + + /* + if (state.buf_ptr != ain->code_size) + WARNING("CODE SIZE CHANGED"); + if (state.strings.size != (size_t)ain->nr_strings) + WARNING("NR STRINGS CHANGED (%d -> %lu)", ain->nr_strings, state.strings.size); + if (state.messages.size != (size_t)ain->nr_messages) + WARNING("NR MESSAGES CHANGED (%d -> %lu)", ain->nr_messages, state.messages.size); + */ + + // TODO: rebuild switch table (use CASE pseudo-op) + + free(ain->code); + ain->code = state.buf; + ain->code_size = state.buf_ptr; + + ain_free_strings(ain); + ain->strings = state.strings.strings; + ain->nr_strings = state.strings.size; + + ain_free_messages(ain); + ain->messages = state.messages.strings; + ain->nr_messages = state.messages.size; + + // TODO: verify integrity of ain file (e.g. does MAIN still point to a valid function? etc.) + + fini_asm_state(&state); +} diff --git a/src/ainedit/asm_lexer.l b/src/ainedit/asm_lexer.l new file mode 100644 index 0000000..9c58bb0 --- /dev/null +++ b/src/ainedit/asm_lexer.l @@ -0,0 +1,75 @@ +/* Copyright (C) 2019 Nunuhara Cabbage + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + */ + +%{ + +#pragma GCC diagnostic ignored "-Wunused-function" + +#include +#include "asm_parser.tab.h" +#include "system4.h" +#include "system4/string.h" + +#define SAVE_TOKEN yylval.string = makes_string(yytext, yyleng) + +char string_buf[65536]; +char *string_buf_ptr; + +%} + +%option noyywrap + +%x str + +id_char [^ \t\r\n:;\"] + +%% + +[ \t] ; +;[^\n]*\n return NEWLINE; +\n return NEWLINE; +[a-zA-Z0-9_-]+: yylval.string = make_string(yytext, yyleng-1); return LABEL; +({id_char}|:)*{id_char}+ yylval.string = make_string(yytext, yyleng); return IDENTIFIER; + + +\" string_buf_ptr = string_buf; BEGIN(str); + +{ + \" { + BEGIN(INITIAL); + *string_buf_ptr = '\0'; + yylval.string = make_string(string_buf, strlen(string_buf)); + return IDENTIFIER; + } + + \n ERROR("Unterminated string literal"); + + \\n *string_buf_ptr++ = '\n'; + \\t *string_buf_ptr++ = '\t'; + \\r *string_buf_ptr++ = '\r'; + \\b *string_buf_ptr++ = '\b'; + \\f *string_buf_ptr++ = '\f'; + + \\(.|\n) *string_buf_ptr++ = yytext[1]; + + [^\\\n\"]+ { + char *yptr = yytext; + while (*yptr) + *string_buf_ptr++ = *yptr++; + } +} + +%% diff --git a/src/ainedit/asm_lexer.yy.c b/src/ainedit/asm_lexer.yy.c new file mode 100644 index 0000000..c200d84 --- /dev/null +++ b/src/ainedit/asm_lexer.yy.c @@ -0,0 +1,1886 @@ +#line 2 "src/ainedit/48087cf@@ainedit@exe/asm_lexer.yy.c" + +#line 4 "src/ainedit/48087cf@@ainedit@exe/asm_lexer.yy.c" + +#define YY_INT_ALIGNED short int + +/* A lexical scanner generated by flex */ + +#define FLEX_SCANNER +#define YY_FLEX_MAJOR_VERSION 2 +#define YY_FLEX_MINOR_VERSION 6 +#define YY_FLEX_SUBMINOR_VERSION 4 +#if YY_FLEX_SUBMINOR_VERSION > 0 +#define FLEX_BETA +#endif + +/* First, we deal with platform-specific or compiler-specific issues. */ + +/* begin standard C headers. */ +#include +#include +#include +#include + +/* end standard C headers. */ + +/* flex integer type definitions */ + +#ifndef FLEXINT_H +#define FLEXINT_H + +/* C99 systems have . Non-C99 systems may or may not. */ + +#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + +/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, + * if you want the limit (max/min) macros for int types. + */ +#ifndef __STDC_LIMIT_MACROS +#define __STDC_LIMIT_MACROS 1 +#endif + +#include +typedef int8_t flex_int8_t; +typedef uint8_t flex_uint8_t; +typedef int16_t flex_int16_t; +typedef uint16_t flex_uint16_t; +typedef int32_t flex_int32_t; +typedef uint32_t flex_uint32_t; +#else +typedef signed char flex_int8_t; +typedef short int flex_int16_t; +typedef int flex_int32_t; +typedef unsigned char flex_uint8_t; +typedef unsigned short int flex_uint16_t; +typedef unsigned int flex_uint32_t; + +/* Limits of integral types. */ +#ifndef INT8_MIN +#define INT8_MIN (-128) +#endif +#ifndef INT16_MIN +#define INT16_MIN (-32767-1) +#endif +#ifndef INT32_MIN +#define INT32_MIN (-2147483647-1) +#endif +#ifndef INT8_MAX +#define INT8_MAX (127) +#endif +#ifndef INT16_MAX +#define INT16_MAX (32767) +#endif +#ifndef INT32_MAX +#define INT32_MAX (2147483647) +#endif +#ifndef UINT8_MAX +#define UINT8_MAX (255U) +#endif +#ifndef UINT16_MAX +#define UINT16_MAX (65535U) +#endif +#ifndef UINT32_MAX +#define UINT32_MAX (4294967295U) +#endif + +#ifndef SIZE_MAX +#define SIZE_MAX (~(size_t)0) +#endif + +#endif /* ! C99 */ + +#endif /* ! FLEXINT_H */ + +/* begin standard C++ headers. */ + +/* TODO: this is always defined, so inline it */ +#define yyconst const + +#if defined(__GNUC__) && __GNUC__ >= 3 +#define yynoreturn __attribute__((__noreturn__)) +#else +#define yynoreturn +#endif + +/* Returned upon end-of-file. */ +#define YY_NULL 0 + +/* Promotes a possibly negative, possibly signed char to an + * integer in range [0..255] for use as an array index. + */ +#define YY_SC_TO_UI(c) ((YY_CHAR) (c)) + +/* Enter a start condition. This macro really ought to take a parameter, + * but we do it the disgusting crufty way forced on us by the ()-less + * definition of BEGIN. + */ +#define BEGIN (yy_start) = 1 + 2 * +/* Translate the current start state into a value that can be later handed + * to BEGIN to return to the state. The YYSTATE alias is for lex + * compatibility. + */ +#define YY_START (((yy_start) - 1) / 2) +#define YYSTATE YY_START +/* Action number for EOF rule of a given start state. */ +#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) +/* Special action meaning "start processing a new file". */ +#define YY_NEW_FILE yyrestart( yyin ) +#define YY_END_OF_BUFFER_CHAR 0 + +/* Size of default input buffer. */ +#ifndef YY_BUF_SIZE +#ifdef __ia64__ +/* On IA-64, the buffer size is 16k, not 8k. + * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. + * Ditto for the __ia64__ case accordingly. + */ +#define YY_BUF_SIZE 32768 +#else +#define YY_BUF_SIZE 16384 +#endif /* __ia64__ */ +#endif + +/* The state buf must be large enough to hold one state per character in the main buffer. + */ +#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) + +#ifndef YY_TYPEDEF_YY_BUFFER_STATE +#define YY_TYPEDEF_YY_BUFFER_STATE +typedef struct yy_buffer_state *YY_BUFFER_STATE; +#endif + +#ifndef YY_TYPEDEF_YY_SIZE_T +#define YY_TYPEDEF_YY_SIZE_T +typedef size_t yy_size_t; +#endif + +extern int yyleng; + +extern FILE *yyin, *yyout; + +#define EOB_ACT_CONTINUE_SCAN 0 +#define EOB_ACT_END_OF_FILE 1 +#define EOB_ACT_LAST_MATCH 2 + + #define YY_LESS_LINENO(n) + #define YY_LINENO_REWIND_TO(ptr) + +/* Return all but the first "n" matched characters back to the input stream. */ +#define yyless(n) \ + do \ + { \ + /* Undo effects of setting up yytext. */ \ + int yyless_macro_arg = (n); \ + YY_LESS_LINENO(yyless_macro_arg);\ + *yy_cp = (yy_hold_char); \ + YY_RESTORE_YY_MORE_OFFSET \ + (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ + YY_DO_BEFORE_ACTION; /* set up yytext again */ \ + } \ + while ( 0 ) +#define unput(c) yyunput( c, (yytext_ptr) ) + +#ifndef YY_STRUCT_YY_BUFFER_STATE +#define YY_STRUCT_YY_BUFFER_STATE +struct yy_buffer_state + { + FILE *yy_input_file; + + char *yy_ch_buf; /* input buffer */ + char *yy_buf_pos; /* current position in input buffer */ + + /* Size of input buffer in bytes, not including room for EOB + * characters. + */ + int yy_buf_size; + + /* Number of characters read into yy_ch_buf, not including EOB + * characters. + */ + int yy_n_chars; + + /* Whether we "own" the buffer - i.e., we know we created it, + * and can realloc() it to grow it, and should free() it to + * delete it. + */ + int yy_is_our_buffer; + + /* Whether this is an "interactive" input source; if so, and + * if we're using stdio for input, then we want to use getc() + * instead of fread(), to make sure we stop fetching input after + * each newline. + */ + int yy_is_interactive; + + /* Whether we're considered to be at the beginning of a line. + * If so, '^' rules will be active on the next match, otherwise + * not. + */ + int yy_at_bol; + + int yy_bs_lineno; /**< The line count. */ + int yy_bs_column; /**< The column count. */ + + /* Whether to try to fill the input buffer when we reach the + * end of it. + */ + int yy_fill_buffer; + + int yy_buffer_status; + +#define YY_BUFFER_NEW 0 +#define YY_BUFFER_NORMAL 1 + /* When an EOF's been seen but there's still some text to process + * then we mark the buffer as YY_EOF_PENDING, to indicate that we + * shouldn't try reading from the input source any more. We might + * still have a bunch of tokens to match, though, because of + * possible backing-up. + * + * When we actually see the EOF, we change the status to "new" + * (via yyrestart()), so that the user can continue scanning by + * just pointing yyin at a new input file. + */ +#define YY_BUFFER_EOF_PENDING 2 + + }; +#endif /* !YY_STRUCT_YY_BUFFER_STATE */ + +/* Stack of input buffers. */ +static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */ +static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */ +static YY_BUFFER_STATE * yy_buffer_stack = NULL; /**< Stack as an array. */ + +/* We provide macros for accessing buffer states in case in the + * future we want to put the buffer states in a more general + * "scanner state". + * + * Returns the top of the stack, or NULL. + */ +#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ + ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ + : NULL) +/* Same as previous macro, but useful when we know that the buffer stack is not + * NULL or when we need an lvalue. For internal use only. + */ +#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] + +/* yy_hold_char holds the character lost when yytext is formed. */ +static char yy_hold_char; +static int yy_n_chars; /* number of characters read into yy_ch_buf */ +int yyleng; + +/* Points to current character in buffer. */ +static char *yy_c_buf_p = NULL; +static int yy_init = 0; /* whether we need to initialize */ +static int yy_start = 0; /* start state number */ + +/* Flag which is used to allow yywrap()'s to do buffer switches + * instead of setting up a fresh yyin. A bit of a hack ... + */ +static int yy_did_buffer_switch_on_eof; + +void yyrestart ( FILE *input_file ); +void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer ); +YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size ); +void yy_delete_buffer ( YY_BUFFER_STATE b ); +void yy_flush_buffer ( YY_BUFFER_STATE b ); +void yypush_buffer_state ( YY_BUFFER_STATE new_buffer ); +void yypop_buffer_state ( void ); + +static void yyensure_buffer_stack ( void ); +static void yy_load_buffer_state ( void ); +static void yy_init_buffer ( YY_BUFFER_STATE b, FILE *file ); +#define YY_FLUSH_BUFFER yy_flush_buffer( YY_CURRENT_BUFFER ) + +YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size ); +YY_BUFFER_STATE yy_scan_string ( const char *yy_str ); +YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len ); + +void *yyalloc ( yy_size_t ); +void *yyrealloc ( void *, yy_size_t ); +void yyfree ( void * ); + +#define yy_new_buffer yy_create_buffer +#define yy_set_interactive(is_interactive) \ + { \ + if ( ! YY_CURRENT_BUFFER ){ \ + yyensure_buffer_stack (); \ + YY_CURRENT_BUFFER_LVALUE = \ + yy_create_buffer( yyin, YY_BUF_SIZE ); \ + } \ + YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ + } +#define yy_set_bol(at_bol) \ + { \ + if ( ! YY_CURRENT_BUFFER ){\ + yyensure_buffer_stack (); \ + YY_CURRENT_BUFFER_LVALUE = \ + yy_create_buffer( yyin, YY_BUF_SIZE ); \ + } \ + YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ + } +#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) + +/* Begin user sect3 */ + +#define yywrap() (/*CONSTCOND*/1) +#define YY_SKIP_YYWRAP +typedef flex_uint8_t YY_CHAR; + +FILE *yyin = NULL, *yyout = NULL; + +typedef int yy_state_type; + +extern int yylineno; +int yylineno = 1; + +extern char *yytext; +#ifdef yytext_ptr +#undef yytext_ptr +#endif +#define yytext_ptr yytext + +static yy_state_type yy_get_previous_state ( void ); +static yy_state_type yy_try_NUL_trans ( yy_state_type current_state ); +static int yy_get_next_buffer ( void ); +static void yynoreturn yy_fatal_error ( const char* msg ); + +/* Done after the current pattern has been matched and before the + * corresponding action - sets up yytext. + */ +#define YY_DO_BEFORE_ACTION \ + (yytext_ptr) = yy_bp; \ + yyleng = (int) (yy_cp - yy_bp); \ + (yy_hold_char) = *yy_cp; \ + *yy_cp = '\0'; \ + (yy_c_buf_p) = yy_cp; +#define YY_NUM_RULES 16 +#define YY_END_OF_BUFFER 17 +/* This struct is not used in this scanner, + but its presence is necessary. */ +struct yy_trans_info + { + flex_int32_t yy_verify; + flex_int32_t yy_nxt; + }; +static const flex_int16_t yy_accept[32] = + { 0, + 0, 0, 0, 0, 17, 5, 1, 3, 16, 6, + 5, 16, 16, 15, 8, 7, 16, 5, 0, 5, + 4, 0, 2, 15, 14, 12, 13, 9, 11, 10, + 0 + } ; + +static const YY_CHAR yy_ec[256] = + { 0, + 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, + 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 2, 1, 5, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 6, 1, 1, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 7, 8, 1, + 1, 1, 1, 1, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 1, 9, 1, 1, 6, 1, 6, 10, 6, 6, + + 6, 11, 6, 6, 6, 6, 6, 6, 6, 12, + 6, 6, 6, 13, 6, 14, 6, 6, 6, 6, + 6, 6, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1 + } ; + +static const YY_CHAR yy_meta[15] = + { 0, + 1, 2, 3, 2, 3, 1, 1, 2, 4, 1, + 1, 1, 1, 1 + } ; + +static const flex_int16_t yy_base[37] = + { 0, + 0, 0, 12, 19, 27, 19, 79, 79, 79, 79, + 28, 18, 20, 0, 79, 79, 37, 13, 12, 51, + 11, 13, 79, 0, 79, 79, 79, 79, 79, 79, + 79, 60, 64, 68, 72, 76 + } ; + +static const flex_int16_t yy_def[37] = + { 0, + 31, 1, 32, 32, 31, 33, 31, 31, 31, 31, + 34, 33, 35, 36, 31, 31, 31, 33, 33, 34, + 33, 35, 31, 36, 31, 31, 31, 31, 31, 31, + 0, 31, 31, 31, 31, 31 + } ; + +static const flex_int16_t yy_nxt[94] = + { 0, + 6, 7, 8, 9, 10, 11, 12, 13, 6, 11, + 11, 11, 11, 11, 15, 23, 16, 19, 19, 19, + 17, 15, 23, 16, 19, 19, 31, 17, 18, 31, + 31, 31, 31, 31, 21, 31, 18, 25, 25, 25, + 25, 25, 25, 25, 25, 25, 26, 27, 28, 29, + 30, 18, 31, 31, 31, 31, 31, 21, 31, 18, + 14, 14, 14, 14, 18, 31, 31, 18, 20, 31, + 31, 20, 22, 22, 22, 22, 24, 24, 5, 31, + 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, + 31, 31, 31 + + } ; + +static const flex_int16_t yy_chk[94] = + { 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 3, 22, 3, 21, 19, 18, + 3, 4, 13, 4, 12, 6, 5, 4, 11, 0, + 0, 0, 0, 0, 11, 0, 11, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 20, 0, 0, 0, 0, 0, 20, 0, 20, + 32, 32, 32, 32, 33, 0, 0, 33, 34, 0, + 0, 34, 35, 35, 35, 35, 36, 36, 31, 31, + 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, + 31, 31, 31 + + } ; + +static yy_state_type yy_last_accepting_state; +static char *yy_last_accepting_cpos; + +extern int yy_flex_debug; +int yy_flex_debug = 0; + +/* The intent behind this definition is that it'll catch + * any uses of REJECT which flex missed. + */ +#define REJECT reject_used_but_not_detected +#define yymore() yymore_used_but_not_detected +#define YY_MORE_ADJ 0 +#define YY_RESTORE_YY_MORE_OFFSET +char *yytext; +#line 1 "../src/ainedit/asm_lexer.l" +/* Copyright (C) 2019 Nunuhara Cabbage + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + */ +#line 18 "../src/ainedit/asm_lexer.l" + +#pragma GCC diagnostic ignored "-Wunused-function" + +#include +#include "asm_parser.tab.h" +#include "system4.h" +#include "system4/string.h" + +#define SAVE_TOKEN yylval.string = makes_string(yytext, yyleng) + +char string_buf[65536]; +char *string_buf_ptr; + +#line 504 "src/ainedit/48087cf@@ainedit@exe/asm_lexer.yy.c" + +#line 506 "src/ainedit/48087cf@@ainedit@exe/asm_lexer.yy.c" + +#define INITIAL 0 +#define str 1 + +#ifndef YY_NO_UNISTD_H +/* Special case for "unistd.h", since it is non-ANSI. We include it way + * down here because we want the user's section 1 to have been scanned first. + * The user has a chance to override it with an option. + */ +#include +#endif + +#ifndef YY_EXTRA_TYPE +#define YY_EXTRA_TYPE void * +#endif + +static int yy_init_globals ( void ); + +/* Accessor methods to globals. + These are made visible to non-reentrant scanners for convenience. */ + +int yylex_destroy ( void ); + +int yyget_debug ( void ); + +void yyset_debug ( int debug_flag ); + +YY_EXTRA_TYPE yyget_extra ( void ); + +void yyset_extra ( YY_EXTRA_TYPE user_defined ); + +FILE *yyget_in ( void ); + +void yyset_in ( FILE * _in_str ); + +FILE *yyget_out ( void ); + +void yyset_out ( FILE * _out_str ); + + int yyget_leng ( void ); + +char *yyget_text ( void ); + +int yyget_lineno ( void ); + +void yyset_lineno ( int _line_number ); + +/* Macros after this point can all be overridden by user definitions in + * section 1. + */ + +#ifndef YY_SKIP_YYWRAP +#ifdef __cplusplus +extern "C" int yywrap ( void ); +#else +extern int yywrap ( void ); +#endif +#endif + +#ifndef YY_NO_UNPUT + + static void yyunput ( int c, char *buf_ptr ); + +#endif + +#ifndef yytext_ptr +static void yy_flex_strncpy ( char *, const char *, int ); +#endif + +#ifdef YY_NEED_STRLEN +static int yy_flex_strlen ( const char * ); +#endif + +#ifndef YY_NO_INPUT +#ifdef __cplusplus +static int yyinput ( void ); +#else +static int input ( void ); +#endif + +#endif + +/* Amount of stuff to slurp up with each read. */ +#ifndef YY_READ_BUF_SIZE +#ifdef __ia64__ +/* On IA-64, the buffer size is 16k, not 8k */ +#define YY_READ_BUF_SIZE 16384 +#else +#define YY_READ_BUF_SIZE 8192 +#endif /* __ia64__ */ +#endif + +/* Copy whatever the last rule matched to the standard output. */ +#ifndef ECHO +/* This used to be an fputs(), but since the string might contain NUL's, + * we now use fwrite(). + */ +#define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0) +#endif + +/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, + * is returned in "result". + */ +#ifndef YY_INPUT +#define YY_INPUT(buf,result,max_size) \ + if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ + { \ + int c = '*'; \ + int n; \ + for ( n = 0; n < max_size && \ + (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ + buf[n] = (char) c; \ + if ( c == '\n' ) \ + buf[n++] = (char) c; \ + if ( c == EOF && ferror( yyin ) ) \ + YY_FATAL_ERROR( "input in flex scanner failed" ); \ + result = n; \ + } \ + else \ + { \ + errno=0; \ + while ( (result = (int) fread(buf, 1, (yy_size_t) max_size, yyin)) == 0 && ferror(yyin)) \ + { \ + if( errno != EINTR) \ + { \ + YY_FATAL_ERROR( "input in flex scanner failed" ); \ + break; \ + } \ + errno=0; \ + clearerr(yyin); \ + } \ + }\ +\ + +#endif + +/* No semi-colon after return; correct usage is to write "yyterminate();" - + * we don't want an extra ';' after the "return" because that will cause + * some compilers to complain about unreachable statements. + */ +#ifndef yyterminate +#define yyterminate() return YY_NULL +#endif + +/* Number of entries by which start-condition stack grows. */ +#ifndef YY_START_STACK_INCR +#define YY_START_STACK_INCR 25 +#endif + +/* Report a fatal error. */ +#ifndef YY_FATAL_ERROR +#define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) +#endif + +/* end tables serialization structures and prototypes */ + +/* Default declaration of generated scanner - a define so the user can + * easily add parameters. + */ +#ifndef YY_DECL +#define YY_DECL_IS_OURS 1 + +extern int yylex (void); + +#define YY_DECL int yylex (void) +#endif /* !YY_DECL */ + +/* Code executed at the beginning of each rule, after yytext and yyleng + * have been set up. + */ +#ifndef YY_USER_ACTION +#define YY_USER_ACTION +#endif + +/* Code executed at the end of each rule. */ +#ifndef YY_BREAK +#define YY_BREAK /*LINTED*/break; +#endif + +#define YY_RULE_SETUP \ + YY_USER_ACTION + +/** The main scanner function which does all the work. + */ +YY_DECL +{ + yy_state_type yy_current_state; + char *yy_cp, *yy_bp; + int yy_act; + + if ( !(yy_init) ) + { + (yy_init) = 1; + +#ifdef YY_USER_INIT + YY_USER_INIT; +#endif + + if ( ! (yy_start) ) + (yy_start) = 1; /* first start state */ + + if ( ! yyin ) + yyin = stdin; + + if ( ! yyout ) + yyout = stdout; + + if ( ! YY_CURRENT_BUFFER ) { + yyensure_buffer_stack (); + YY_CURRENT_BUFFER_LVALUE = + yy_create_buffer( yyin, YY_BUF_SIZE ); + } + + yy_load_buffer_state( ); + } + + { +#line 39 "../src/ainedit/asm_lexer.l" + + +#line 727 "src/ainedit/48087cf@@ainedit@exe/asm_lexer.yy.c" + + while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ + { + yy_cp = (yy_c_buf_p); + + /* Support of yytext. */ + *yy_cp = (yy_hold_char); + + /* yy_bp points to the position in yy_ch_buf of the start of + * the current run. + */ + yy_bp = yy_cp; + + yy_current_state = (yy_start); +yy_match: + do + { + YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; + if ( yy_accept[yy_current_state] ) + { + (yy_last_accepting_state) = yy_current_state; + (yy_last_accepting_cpos) = yy_cp; + } + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 32 ) + yy_c = yy_meta[yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; + ++yy_cp; + } + while ( yy_base[yy_current_state] != 79 ); + +yy_find_action: + yy_act = yy_accept[yy_current_state]; + if ( yy_act == 0 ) + { /* have to back up */ + yy_cp = (yy_last_accepting_cpos); + yy_current_state = (yy_last_accepting_state); + yy_act = yy_accept[yy_current_state]; + } + + YY_DO_BEFORE_ACTION; + +do_action: /* This label is used only to access EOF actions. */ + + switch ( yy_act ) + { /* beginning of action switch */ + case 0: /* must back up */ + /* undo the effects of YY_DO_BEFORE_ACTION */ + *yy_cp = (yy_hold_char); + yy_cp = (yy_last_accepting_cpos); + yy_current_state = (yy_last_accepting_state); + goto yy_find_action; + +case 1: +YY_RULE_SETUP +#line 41 "../src/ainedit/asm_lexer.l" +; + YY_BREAK +case 2: +/* rule 2 can match eol */ +YY_RULE_SETUP +#line 42 "../src/ainedit/asm_lexer.l" +return NEWLINE; + YY_BREAK +case 3: +/* rule 3 can match eol */ +YY_RULE_SETUP +#line 43 "../src/ainedit/asm_lexer.l" +return NEWLINE; + YY_BREAK +case 4: +YY_RULE_SETUP +#line 44 "../src/ainedit/asm_lexer.l" +yylval.string = make_string(yytext, yyleng-1); return LABEL; + YY_BREAK +case 5: +YY_RULE_SETUP +#line 45 "../src/ainedit/asm_lexer.l" +yylval.string = make_string(yytext, yyleng); return IDENTIFIER; + YY_BREAK +case 6: +YY_RULE_SETUP +#line 48 "../src/ainedit/asm_lexer.l" +string_buf_ptr = string_buf; BEGIN(str); + YY_BREAK + +case 7: +YY_RULE_SETUP +#line 51 "../src/ainedit/asm_lexer.l" +{ + BEGIN(INITIAL); + *string_buf_ptr = '\0'; + yylval.string = make_string(string_buf, strlen(string_buf)); + return IDENTIFIER; + } + YY_BREAK +case 8: +/* rule 8 can match eol */ +YY_RULE_SETUP +#line 58 "../src/ainedit/asm_lexer.l" +ERROR("Unterminated string literal"); + YY_BREAK +case 9: +YY_RULE_SETUP +#line 60 "../src/ainedit/asm_lexer.l" +*string_buf_ptr++ = '\n'; + YY_BREAK +case 10: +YY_RULE_SETUP +#line 61 "../src/ainedit/asm_lexer.l" +*string_buf_ptr++ = '\t'; + YY_BREAK +case 11: +YY_RULE_SETUP +#line 62 "../src/ainedit/asm_lexer.l" +*string_buf_ptr++ = '\r'; + YY_BREAK +case 12: +YY_RULE_SETUP +#line 63 "../src/ainedit/asm_lexer.l" +*string_buf_ptr++ = '\b'; + YY_BREAK +case 13: +YY_RULE_SETUP +#line 64 "../src/ainedit/asm_lexer.l" +*string_buf_ptr++ = '\f'; + YY_BREAK +case 14: +/* rule 14 can match eol */ +YY_RULE_SETUP +#line 66 "../src/ainedit/asm_lexer.l" +*string_buf_ptr++ = yytext[1]; + YY_BREAK +case 15: +YY_RULE_SETUP +#line 68 "../src/ainedit/asm_lexer.l" +{ + char *yptr = yytext; + while (*yptr) + *string_buf_ptr++ = *yptr++; + } + YY_BREAK + +case 16: +YY_RULE_SETUP +#line 75 "../src/ainedit/asm_lexer.l" +ECHO; + YY_BREAK +#line 879 "src/ainedit/48087cf@@ainedit@exe/asm_lexer.yy.c" +case YY_STATE_EOF(INITIAL): +case YY_STATE_EOF(str): + yyterminate(); + + case YY_END_OF_BUFFER: + { + /* Amount of text matched not including the EOB char. */ + int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; + + /* Undo the effects of YY_DO_BEFORE_ACTION. */ + *yy_cp = (yy_hold_char); + YY_RESTORE_YY_MORE_OFFSET + + if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) + { + /* We're scanning a new file or input source. It's + * possible that this happened because the user + * just pointed yyin at a new source and called + * yylex(). If so, then we have to assure + * consistency between YY_CURRENT_BUFFER and our + * globals. Here is the right place to do so, because + * this is the first action (other than possibly a + * back-up) that will match for the new input source. + */ + (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; + YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; + YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; + } + + /* Note that here we test for yy_c_buf_p "<=" to the position + * of the first EOB in the buffer, since yy_c_buf_p will + * already have been incremented past the NUL character + * (since all states make transitions on EOB to the + * end-of-buffer state). Contrast this with the test + * in input(). + */ + if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) + { /* This was really a NUL. */ + yy_state_type yy_next_state; + + (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; + + yy_current_state = yy_get_previous_state( ); + + /* Okay, we're now positioned to make the NUL + * transition. We couldn't have + * yy_get_previous_state() go ahead and do it + * for us because it doesn't know how to deal + * with the possibility of jamming (and we don't + * want to build jamming into it because then it + * will run more slowly). + */ + + yy_next_state = yy_try_NUL_trans( yy_current_state ); + + yy_bp = (yytext_ptr) + YY_MORE_ADJ; + + if ( yy_next_state ) + { + /* Consume the NUL. */ + yy_cp = ++(yy_c_buf_p); + yy_current_state = yy_next_state; + goto yy_match; + } + + else + { + yy_cp = (yy_c_buf_p); + goto yy_find_action; + } + } + + else switch ( yy_get_next_buffer( ) ) + { + case EOB_ACT_END_OF_FILE: + { + (yy_did_buffer_switch_on_eof) = 0; + + if ( yywrap( ) ) + { + /* Note: because we've taken care in + * yy_get_next_buffer() to have set up + * yytext, we can now set up + * yy_c_buf_p so that if some total + * hoser (like flex itself) wants to + * call the scanner after we return the + * YY_NULL, it'll still work - another + * YY_NULL will get returned. + */ + (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; + + yy_act = YY_STATE_EOF(YY_START); + goto do_action; + } + + else + { + if ( ! (yy_did_buffer_switch_on_eof) ) + YY_NEW_FILE; + } + break; + } + + case EOB_ACT_CONTINUE_SCAN: + (yy_c_buf_p) = + (yytext_ptr) + yy_amount_of_matched_text; + + yy_current_state = yy_get_previous_state( ); + + yy_cp = (yy_c_buf_p); + yy_bp = (yytext_ptr) + YY_MORE_ADJ; + goto yy_match; + + case EOB_ACT_LAST_MATCH: + (yy_c_buf_p) = + &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; + + yy_current_state = yy_get_previous_state( ); + + yy_cp = (yy_c_buf_p); + yy_bp = (yytext_ptr) + YY_MORE_ADJ; + goto yy_find_action; + } + break; + } + + default: + YY_FATAL_ERROR( + "fatal flex scanner internal error--no action found" ); + } /* end of action switch */ + } /* end of scanning one token */ + } /* end of user's declarations */ +} /* end of yylex */ + +/* yy_get_next_buffer - try to read in a new buffer + * + * Returns a code representing an action: + * EOB_ACT_LAST_MATCH - + * EOB_ACT_CONTINUE_SCAN - continue scanning from current position + * EOB_ACT_END_OF_FILE - end of file + */ +static int yy_get_next_buffer (void) +{ + char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; + char *source = (yytext_ptr); + int number_to_move, i; + int ret_val; + + if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) + YY_FATAL_ERROR( + "fatal flex scanner internal error--end of buffer missed" ); + + if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) + { /* Don't try to fill the buffer, so this is an EOF. */ + if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) + { + /* We matched a single character, the EOB, so + * treat this as a final EOF. + */ + return EOB_ACT_END_OF_FILE; + } + + else + { + /* We matched some text prior to the EOB, first + * process it. + */ + return EOB_ACT_LAST_MATCH; + } + } + + /* Try to read more data. */ + + /* First move last chars to start of buffer. */ + number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr) - 1); + + for ( i = 0; i < number_to_move; ++i ) + *(dest++) = *(source++); + + if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) + /* don't do the read, it's not guaranteed to return an EOF, + * just force an EOF + */ + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; + + else + { + int num_to_read = + YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; + + while ( num_to_read <= 0 ) + { /* Not enough room in the buffer - grow it. */ + + /* just a shorter name for the current buffer */ + YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; + + int yy_c_buf_p_offset = + (int) ((yy_c_buf_p) - b->yy_ch_buf); + + if ( b->yy_is_our_buffer ) + { + int new_size = b->yy_buf_size * 2; + + if ( new_size <= 0 ) + b->yy_buf_size += b->yy_buf_size / 8; + else + b->yy_buf_size *= 2; + + b->yy_ch_buf = (char *) + /* Include room in for 2 EOB chars. */ + yyrealloc( (void *) b->yy_ch_buf, + (yy_size_t) (b->yy_buf_size + 2) ); + } + else + /* Can't grow it, we don't own it. */ + b->yy_ch_buf = NULL; + + if ( ! b->yy_ch_buf ) + YY_FATAL_ERROR( + "fatal error - scanner input buffer overflow" ); + + (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset]; + + num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - + number_to_move - 1; + + } + + if ( num_to_read > YY_READ_BUF_SIZE ) + num_to_read = YY_READ_BUF_SIZE; + + /* Read in more data. */ + YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), + (yy_n_chars), num_to_read ); + + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); + } + + if ( (yy_n_chars) == 0 ) + { + if ( number_to_move == YY_MORE_ADJ ) + { + ret_val = EOB_ACT_END_OF_FILE; + yyrestart( yyin ); + } + + else + { + ret_val = EOB_ACT_LAST_MATCH; + YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = + YY_BUFFER_EOF_PENDING; + } + } + + else + ret_val = EOB_ACT_CONTINUE_SCAN; + + if (((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { + /* Extend the array by 50%, plus the number we really need. */ + int new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); + YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc( + (void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t) new_size ); + if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) + YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); + /* "- 2" to take care of EOB's */ + YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2); + } + + (yy_n_chars) += number_to_move; + YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; + YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; + + (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; + + return ret_val; +} + +/* yy_get_previous_state - get the state just before the EOB char was reached */ + + static yy_state_type yy_get_previous_state (void) +{ + yy_state_type yy_current_state; + char *yy_cp; + + yy_current_state = (yy_start); + + for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) + { + YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); + if ( yy_accept[yy_current_state] ) + { + (yy_last_accepting_state) = yy_current_state; + (yy_last_accepting_cpos) = yy_cp; + } + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 32 ) + yy_c = yy_meta[yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; + } + + return yy_current_state; +} + +/* yy_try_NUL_trans - try to make a transition on the NUL character + * + * synopsis + * next_state = yy_try_NUL_trans( current_state ); + */ + static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) +{ + int yy_is_jam; + char *yy_cp = (yy_c_buf_p); + + YY_CHAR yy_c = 1; + if ( yy_accept[yy_current_state] ) + { + (yy_last_accepting_state) = yy_current_state; + (yy_last_accepting_cpos) = yy_cp; + } + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 32 ) + yy_c = yy_meta[yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; + yy_is_jam = (yy_current_state == 31); + + return yy_is_jam ? 0 : yy_current_state; +} + +#ifndef YY_NO_UNPUT + + static void yyunput (int c, char * yy_bp ) +{ + char *yy_cp; + + yy_cp = (yy_c_buf_p); + + /* undo effects of setting up yytext */ + *yy_cp = (yy_hold_char); + + if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) + { /* need to shift things up to make room */ + /* +2 for EOB chars. */ + int number_to_move = (yy_n_chars) + 2; + char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ + YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2]; + char *source = + &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]; + + while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) + *--dest = *--source; + + yy_cp += (int) (dest - source); + yy_bp += (int) (dest - source); + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = + (yy_n_chars) = (int) YY_CURRENT_BUFFER_LVALUE->yy_buf_size; + + if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) + YY_FATAL_ERROR( "flex scanner push-back overflow" ); + } + + *--yy_cp = (char) c; + + (yytext_ptr) = yy_bp; + (yy_hold_char) = *yy_cp; + (yy_c_buf_p) = yy_cp; +} + +#endif + +#ifndef YY_NO_INPUT +#ifdef __cplusplus + static int yyinput (void) +#else + static int input (void) +#endif + +{ + int c; + + *(yy_c_buf_p) = (yy_hold_char); + + if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) + { + /* yy_c_buf_p now points to the character we want to return. + * If this occurs *before* the EOB characters, then it's a + * valid NUL; if not, then we've hit the end of the buffer. + */ + if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) + /* This was really a NUL. */ + *(yy_c_buf_p) = '\0'; + + else + { /* need more input */ + int offset = (int) ((yy_c_buf_p) - (yytext_ptr)); + ++(yy_c_buf_p); + + switch ( yy_get_next_buffer( ) ) + { + case EOB_ACT_LAST_MATCH: + /* This happens because yy_g_n_b() + * sees that we've accumulated a + * token and flags that we need to + * try matching the token before + * proceeding. But for input(), + * there's no matching to consider. + * So convert the EOB_ACT_LAST_MATCH + * to EOB_ACT_END_OF_FILE. + */ + + /* Reset buffer status. */ + yyrestart( yyin ); + + /*FALLTHROUGH*/ + + case EOB_ACT_END_OF_FILE: + { + if ( yywrap( ) ) + return 0; + + if ( ! (yy_did_buffer_switch_on_eof) ) + YY_NEW_FILE; +#ifdef __cplusplus + return yyinput(); +#else + return input(); +#endif + } + + case EOB_ACT_CONTINUE_SCAN: + (yy_c_buf_p) = (yytext_ptr) + offset; + break; + } + } + } + + c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ + *(yy_c_buf_p) = '\0'; /* preserve yytext */ + (yy_hold_char) = *++(yy_c_buf_p); + + return c; +} +#endif /* ifndef YY_NO_INPUT */ + +/** Immediately switch to a different input stream. + * @param input_file A readable stream. + * + * @note This function does not reset the start condition to @c INITIAL . + */ + void yyrestart (FILE * input_file ) +{ + + if ( ! YY_CURRENT_BUFFER ){ + yyensure_buffer_stack (); + YY_CURRENT_BUFFER_LVALUE = + yy_create_buffer( yyin, YY_BUF_SIZE ); + } + + yy_init_buffer( YY_CURRENT_BUFFER, input_file ); + yy_load_buffer_state( ); +} + +/** Switch to a different input buffer. + * @param new_buffer The new input buffer. + * + */ + void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ) +{ + + /* TODO. We should be able to replace this entire function body + * with + * yypop_buffer_state(); + * yypush_buffer_state(new_buffer); + */ + yyensure_buffer_stack (); + if ( YY_CURRENT_BUFFER == new_buffer ) + return; + + if ( YY_CURRENT_BUFFER ) + { + /* Flush out information for old buffer. */ + *(yy_c_buf_p) = (yy_hold_char); + YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); + } + + YY_CURRENT_BUFFER_LVALUE = new_buffer; + yy_load_buffer_state( ); + + /* We don't actually know whether we did this switch during + * EOF (yywrap()) processing, but the only time this flag + * is looked at is after yywrap() is called, so it's safe + * to go ahead and always set it. + */ + (yy_did_buffer_switch_on_eof) = 1; +} + +static void yy_load_buffer_state (void) +{ + (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; + (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; + yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; + (yy_hold_char) = *(yy_c_buf_p); +} + +/** Allocate and initialize an input buffer state. + * @param file A readable stream. + * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. + * + * @return the allocated buffer state. + */ + YY_BUFFER_STATE yy_create_buffer (FILE * file, int size ) +{ + YY_BUFFER_STATE b; + + b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) ); + if ( ! b ) + YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); + + b->yy_buf_size = size; + + /* yy_ch_buf has to be 2 characters longer than the size given because + * we need to put in 2 end-of-buffer characters. + */ + b->yy_ch_buf = (char *) yyalloc( (yy_size_t) (b->yy_buf_size + 2) ); + if ( ! b->yy_ch_buf ) + YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); + + b->yy_is_our_buffer = 1; + + yy_init_buffer( b, file ); + + return b; +} + +/** Destroy the buffer. + * @param b a buffer created with yy_create_buffer() + * + */ + void yy_delete_buffer (YY_BUFFER_STATE b ) +{ + + if ( ! b ) + return; + + if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ + YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; + + if ( b->yy_is_our_buffer ) + yyfree( (void *) b->yy_ch_buf ); + + yyfree( (void *) b ); +} + +/* Initializes or reinitializes a buffer. + * This function is sometimes called more than once on the same buffer, + * such as during a yyrestart() or at EOF. + */ + static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file ) + +{ + int oerrno = errno; + + yy_flush_buffer( b ); + + b->yy_input_file = file; + b->yy_fill_buffer = 1; + + /* If b is the current buffer, then yy_init_buffer was _probably_ + * called from yyrestart() or through yy_get_next_buffer. + * In that case, we don't want to reset the lineno or column. + */ + if (b != YY_CURRENT_BUFFER){ + b->yy_bs_lineno = 1; + b->yy_bs_column = 0; + } + + b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; + + errno = oerrno; +} + +/** Discard all buffered characters. On the next scan, YY_INPUT will be called. + * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. + * + */ + void yy_flush_buffer (YY_BUFFER_STATE b ) +{ + if ( ! b ) + return; + + b->yy_n_chars = 0; + + /* We always need two end-of-buffer characters. The first causes + * a transition to the end-of-buffer state. The second causes + * a jam in that state. + */ + b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; + b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; + + b->yy_buf_pos = &b->yy_ch_buf[0]; + + b->yy_at_bol = 1; + b->yy_buffer_status = YY_BUFFER_NEW; + + if ( b == YY_CURRENT_BUFFER ) + yy_load_buffer_state( ); +} + +/** Pushes the new state onto the stack. The new state becomes + * the current state. This function will allocate the stack + * if necessary. + * @param new_buffer The new state. + * + */ +void yypush_buffer_state (YY_BUFFER_STATE new_buffer ) +{ + if (new_buffer == NULL) + return; + + yyensure_buffer_stack(); + + /* This block is copied from yy_switch_to_buffer. */ + if ( YY_CURRENT_BUFFER ) + { + /* Flush out information for old buffer. */ + *(yy_c_buf_p) = (yy_hold_char); + YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); + } + + /* Only push if top exists. Otherwise, replace top. */ + if (YY_CURRENT_BUFFER) + (yy_buffer_stack_top)++; + YY_CURRENT_BUFFER_LVALUE = new_buffer; + + /* copied from yy_switch_to_buffer. */ + yy_load_buffer_state( ); + (yy_did_buffer_switch_on_eof) = 1; +} + +/** Removes and deletes the top of the stack, if present. + * The next element becomes the new top. + * + */ +void yypop_buffer_state (void) +{ + if (!YY_CURRENT_BUFFER) + return; + + yy_delete_buffer(YY_CURRENT_BUFFER ); + YY_CURRENT_BUFFER_LVALUE = NULL; + if ((yy_buffer_stack_top) > 0) + --(yy_buffer_stack_top); + + if (YY_CURRENT_BUFFER) { + yy_load_buffer_state( ); + (yy_did_buffer_switch_on_eof) = 1; + } +} + +/* Allocates the stack if it does not exist. + * Guarantees space for at least one push. + */ +static void yyensure_buffer_stack (void) +{ + yy_size_t num_to_alloc; + + if (!(yy_buffer_stack)) { + + /* First allocation is just for 2 elements, since we don't know if this + * scanner will even need a stack. We use 2 instead of 1 to avoid an + * immediate realloc on the next call. + */ + num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */ + (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc + (num_to_alloc * sizeof(struct yy_buffer_state*) + ); + if ( ! (yy_buffer_stack) ) + YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); + + memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); + + (yy_buffer_stack_max) = num_to_alloc; + (yy_buffer_stack_top) = 0; + return; + } + + if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ + + /* Increase the buffer to prepare for a possible push. */ + yy_size_t grow_size = 8 /* arbitrary grow size */; + + num_to_alloc = (yy_buffer_stack_max) + grow_size; + (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc + ((yy_buffer_stack), + num_to_alloc * sizeof(struct yy_buffer_state*) + ); + if ( ! (yy_buffer_stack) ) + YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); + + /* zero only the new slots.*/ + memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); + (yy_buffer_stack_max) = num_to_alloc; + } +} + +/** Setup the input buffer state to scan directly from a user-specified character buffer. + * @param base the character buffer + * @param size the size in bytes of the character buffer + * + * @return the newly allocated buffer state object. + */ +YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) +{ + YY_BUFFER_STATE b; + + if ( size < 2 || + base[size-2] != YY_END_OF_BUFFER_CHAR || + base[size-1] != YY_END_OF_BUFFER_CHAR ) + /* They forgot to leave room for the EOB's. */ + return NULL; + + b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) ); + if ( ! b ) + YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); + + b->yy_buf_size = (int) (size - 2); /* "- 2" to take care of EOB's */ + b->yy_buf_pos = b->yy_ch_buf = base; + b->yy_is_our_buffer = 0; + b->yy_input_file = NULL; + b->yy_n_chars = b->yy_buf_size; + b->yy_is_interactive = 0; + b->yy_at_bol = 1; + b->yy_fill_buffer = 0; + b->yy_buffer_status = YY_BUFFER_NEW; + + yy_switch_to_buffer( b ); + + return b; +} + +/** Setup the input buffer state to scan a string. The next call to yylex() will + * scan from a @e copy of @a str. + * @param yystr a NUL-terminated string to scan + * + * @return the newly allocated buffer state object. + * @note If you want to scan bytes that may contain NUL values, then use + * yy_scan_bytes() instead. + */ +YY_BUFFER_STATE yy_scan_string (const char * yystr ) +{ + + return yy_scan_bytes( yystr, (int) strlen(yystr) ); +} + +/** Setup the input buffer state to scan the given bytes. The next call to yylex() will + * scan from a @e copy of @a bytes. + * @param yybytes the byte buffer to scan + * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. + * + * @return the newly allocated buffer state object. + */ +YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len ) +{ + YY_BUFFER_STATE b; + char *buf; + yy_size_t n; + int i; + + /* Get memory for full buffer, including space for trailing EOB's. */ + n = (yy_size_t) (_yybytes_len + 2); + buf = (char *) yyalloc( n ); + if ( ! buf ) + YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); + + for ( i = 0; i < _yybytes_len; ++i ) + buf[i] = yybytes[i]; + + buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; + + b = yy_scan_buffer( buf, n ); + if ( ! b ) + YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); + + /* It's okay to grow etc. this buffer, and we should throw it + * away when we're done. + */ + b->yy_is_our_buffer = 1; + + return b; +} + +#ifndef YY_EXIT_FAILURE +#define YY_EXIT_FAILURE 2 +#endif + +static void yynoreturn yy_fatal_error (const char* msg ) +{ + fprintf( stderr, "%s\n", msg ); + exit( YY_EXIT_FAILURE ); +} + +/* Redefine yyless() so it works in section 3 code. */ + +#undef yyless +#define yyless(n) \ + do \ + { \ + /* Undo effects of setting up yytext. */ \ + int yyless_macro_arg = (n); \ + YY_LESS_LINENO(yyless_macro_arg);\ + yytext[yyleng] = (yy_hold_char); \ + (yy_c_buf_p) = yytext + yyless_macro_arg; \ + (yy_hold_char) = *(yy_c_buf_p); \ + *(yy_c_buf_p) = '\0'; \ + yyleng = yyless_macro_arg; \ + } \ + while ( 0 ) + +/* Accessor methods (get/set functions) to struct members. */ + +/** Get the current line number. + * + */ +int yyget_lineno (void) +{ + + return yylineno; +} + +/** Get the input stream. + * + */ +FILE *yyget_in (void) +{ + return yyin; +} + +/** Get the output stream. + * + */ +FILE *yyget_out (void) +{ + return yyout; +} + +/** Get the length of the current token. + * + */ +int yyget_leng (void) +{ + return yyleng; +} + +/** Get the current token. + * + */ + +char *yyget_text (void) +{ + return yytext; +} + +/** Set the current line number. + * @param _line_number line number + * + */ +void yyset_lineno (int _line_number ) +{ + + yylineno = _line_number; +} + +/** Set the input stream. This does not discard the current + * input buffer. + * @param _in_str A readable stream. + * + * @see yy_switch_to_buffer + */ +void yyset_in (FILE * _in_str ) +{ + yyin = _in_str ; +} + +void yyset_out (FILE * _out_str ) +{ + yyout = _out_str ; +} + +int yyget_debug (void) +{ + return yy_flex_debug; +} + +void yyset_debug (int _bdebug ) +{ + yy_flex_debug = _bdebug ; +} + +static int yy_init_globals (void) +{ + /* Initialization is the same as for the non-reentrant scanner. + * This function is called from yylex_destroy(), so don't allocate here. + */ + + (yy_buffer_stack) = NULL; + (yy_buffer_stack_top) = 0; + (yy_buffer_stack_max) = 0; + (yy_c_buf_p) = NULL; + (yy_init) = 0; + (yy_start) = 0; + +/* Defined in main.c */ +#ifdef YY_STDINIT + yyin = stdin; + yyout = stdout; +#else + yyin = NULL; + yyout = NULL; +#endif + + /* For future reference: Set errno on error, since we are called by + * yylex_init() + */ + return 0; +} + +/* yylex_destroy is for both reentrant and non-reentrant scanners. */ +int yylex_destroy (void) +{ + + /* Pop the buffer stack, destroying each element. */ + while(YY_CURRENT_BUFFER){ + yy_delete_buffer( YY_CURRENT_BUFFER ); + YY_CURRENT_BUFFER_LVALUE = NULL; + yypop_buffer_state(); + } + + /* Destroy the stack itself. */ + yyfree((yy_buffer_stack) ); + (yy_buffer_stack) = NULL; + + /* Reset the globals. This is important in a non-reentrant scanner so the next time + * yylex() is called, initialization will occur. */ + yy_init_globals( ); + + return 0; +} + +/* + * Internal utility routines. + */ + +#ifndef yytext_ptr +static void yy_flex_strncpy (char* s1, const char * s2, int n ) +{ + + int i; + for ( i = 0; i < n; ++i ) + s1[i] = s2[i]; +} +#endif + +#ifdef YY_NEED_STRLEN +static int yy_flex_strlen (const char * s ) +{ + int n; + for ( n = 0; s[n]; ++n ) + ; + + return n; +} +#endif + +void *yyalloc (yy_size_t size ) +{ + return malloc(size); +} + +void *yyrealloc (void * ptr, yy_size_t size ) +{ + + /* The cast to (char *) in the following accommodates both + * implementations that use char* generic pointers, and those + * that use void* generic pointers. It works with the latter + * because both ANSI C and C++ allow castless assignment from + * any pointer type to void*, and deal with argument conversions + * as though doing an assignment. + */ + return realloc(ptr, size); +} + +void yyfree (void * ptr ) +{ + free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ +} + +#define YYTABLES_NAME "yytables" + +#line 75 "../src/ainedit/asm_lexer.l" + + diff --git a/src/ainedit/asm_parser.tab.c b/src/ainedit/asm_parser.tab.c new file mode 100644 index 0000000..ef28dca --- /dev/null +++ b/src/ainedit/asm_parser.tab.c @@ -0,0 +1,1604 @@ +/* A Bison parser, made by GNU Bison 3.3.2. */ + +/* Bison implementation for Yacc-like parsers in C + + Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2019 Free Software Foundation, + Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* As a special exception, you may create a larger work that contains + part or all of the Bison parser skeleton and distribute that work + under terms of your choice, so long as that work isn't itself a + parser generator using the skeleton or a modified version thereof + as a parser skeleton. Alternatively, if you modify or redistribute + the parser skeleton itself, you may (at your option) remove this + special exception, which will cause the skeleton and the resulting + Bison output files to be licensed under the GNU General Public + License without this special exception. + + This special exception was added by the Free Software Foundation in + version 2.2 of Bison. */ + +/* C LALR(1) parser skeleton written by Richard Stallman, by + simplifying the original so-called "semantic" parser. */ + +/* All symbols defined below should begin with yy or YY, to avoid + infringing on user name space. This should be done even for local + variables, as they might otherwise be expanded by user macros. + There are some unavoidable exceptions within include files to + define necessary library symbols; they are noted "INFRINGES ON + USER NAME SPACE" below. */ + +/* Undocumented macros, especially those whose name start with YY_, + are private implementation details. Do not rely on them. */ + +/* Identify Bison output. */ +#define YYBISON 1 + +/* Bison version. */ +#define YYBISON_VERSION "3.3.2" + +/* Skeleton name. */ +#define YYSKELETON_NAME "yacc.c" + +/* Pure parsers. */ +#define YYPURE 0 + +/* Push parsers. */ +#define YYPUSH 0 + +/* Pull parsers. */ +#define YYPULL 1 + + + + + +# ifndef YY_NULLPTR +# if defined __cplusplus +# if 201103L <= __cplusplus +# define YY_NULLPTR nullptr +# else +# define YY_NULLPTR 0 +# endif +# else +# define YY_NULLPTR ((void*)0) +# endif +# endif + +/* Enabling verbose error messages. */ +#ifdef YYERROR_VERBOSE +# undef YYERROR_VERBOSE +# define YYERROR_VERBOSE 1 +#else +# define YYERROR_VERBOSE 0 +#endif + +/* In a future release of Bison, this section will be replaced + by #include "asm_parser.tab.h". */ +#ifndef YY_YY_SRC_AINEDIT_48087CF_AINEDIT_EXE_ASM_PARSER_TAB_H_INCLUDED +# define YY_YY_SRC_AINEDIT_48087CF_AINEDIT_EXE_ASM_PARSER_TAB_H_INCLUDED +/* Debug traces. */ +#ifndef YYDEBUG +# define YYDEBUG 0 +#endif +#if YYDEBUG +extern int yydebug; +#endif +/* "%code requires" blocks. */ +#line 9 "../src/ainedit/asm_parser.y" /* yacc.c:352 */ + + #include + #include "khash.h" + #include "kvec.h" + + kv_decl(parse_instruction_list, struct parse_instruction*); + kv_decl(parse_argument_list, struct string*); + kv_decl(pointer_list, uint32_t*); + + struct parse_instruction { + uint16_t opcode; + parse_argument_list *args; + }; + + parse_instruction_list *parsed_code; + + KHASH_MAP_INIT_STR(label_table, uint32_t); + khash_t(label_table) *label_table; + +#line 122 "src/ainedit/48087cf@@ainedit@exe/asm_parser.tab.c" /* yacc.c:352 */ + +/* Token type. */ +#ifndef YYTOKENTYPE +# define YYTOKENTYPE + enum yytokentype + { + IDENTIFIER = 258, + LABEL = 259, + NEWLINE = 260 + }; +#endif + +/* Value type. */ +#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED + +union YYSTYPE +{ +#line 1 "../src/ainedit/asm_parser.y" /* yacc.c:352 */ + + int token; + struct string *string; + parse_argument_list *args; + struct parse_instruction *instr; + parse_instruction_list *program; + +#line 148 "src/ainedit/48087cf@@ainedit@exe/asm_parser.tab.c" /* yacc.c:352 */ +}; + +typedef union YYSTYPE YYSTYPE; +# define YYSTYPE_IS_TRIVIAL 1 +# define YYSTYPE_IS_DECLARED 1 +#endif + + +extern YYSTYPE yylval; + +int yyparse (void); + +#endif /* !YY_YY_SRC_AINEDIT_48087CF_AINEDIT_EXE_ASM_PARSER_TAB_H_INCLUDED */ + +/* Second part of user prologue. */ +#line 29 "../src/ainedit/asm_parser.y" /* yacc.c:354 */ + + +#include +#include +#include "ainedit.h" +#include "kvec.h" +#include "system4.h" +#include "system4/instructions.h" +#include "system4/string.h" + +extern int yylex(); +void yyerror(const char *s) { ERROR("%s", s); } + +static uint32_t instr_ptr; + +static parse_instruction_list *make_program(void) +{ + parse_instruction_list *program = xmalloc(sizeof(parse_instruction_list)); + kv_init(*program); + instr_ptr = 0; + return program; +} + +static void push_instruction(parse_instruction_list *program, struct parse_instruction *instr) +{ + kv_push(struct parse_instruction*, *program, instr); + instr_ptr += instruction_width(instr->opcode); +} + +static struct parse_instruction *make_instruction(struct string *name, parse_argument_list *args) +{ + for (int i = 0; name->text[i]; i++) { + name->text[i] = toupper(name->text[i]); + } + // check opcode + struct instruction *info = asm_get_instruction(name->text); + if (!info) + ERROR("Invalid instruction: %s", name->text); + // check argument count + size_t nr_args = args ? kv_size(*args) : 0; + if (nr_args != (size_t)info->nr_args) { + fprintf(stderr, "In: '%s", info->name); + for (size_t i = 0; i < nr_args; i++) { + fprintf(stderr, " %s", kv_A(*args, i)->text); + } + fprintf(stderr, "'\n"); + ERROR("Wrong number of arguments for instruction '%s' (expected %d; got %lu)", + name->text, info->nr_args, nr_args); + } + // NOTE: argument values checked on second pass + + free_string(name); + + struct parse_instruction *instr = xmalloc(sizeof (struct parse_instruction)); + instr->opcode = info->opcode; + instr->args = args; + return instr; +} + +static parse_argument_list *make_arglist(void) +{ + parse_argument_list *args = xmalloc(sizeof(parse_argument_list)); + kv_init(*args); + return args; +} + +static void push_arg(parse_argument_list *args, struct string *arg) +{ + kv_push(struct string*, *args, arg); +} + +static void push_label(char *name) +{ + int ret; + khiter_t k = kh_put(label_table, label_table, name, &ret); + if (!ret) { + if (kh_value(label_table, k) != instr_ptr) + ERROR("Duplicate label: %s", name); + return; + } + kh_value(label_table, k) = instr_ptr; +} + + +#line 249 "src/ainedit/48087cf@@ainedit@exe/asm_parser.tab.c" /* yacc.c:354 */ + +#ifdef short +# undef short +#endif + +#ifdef YYTYPE_UINT8 +typedef YYTYPE_UINT8 yytype_uint8; +#else +typedef unsigned char yytype_uint8; +#endif + +#ifdef YYTYPE_INT8 +typedef YYTYPE_INT8 yytype_int8; +#else +typedef signed char yytype_int8; +#endif + +#ifdef YYTYPE_UINT16 +typedef YYTYPE_UINT16 yytype_uint16; +#else +typedef unsigned short yytype_uint16; +#endif + +#ifdef YYTYPE_INT16 +typedef YYTYPE_INT16 yytype_int16; +#else +typedef short yytype_int16; +#endif + +#ifndef YYSIZE_T +# ifdef __SIZE_TYPE__ +# define YYSIZE_T __SIZE_TYPE__ +# elif defined size_t +# define YYSIZE_T size_t +# elif ! defined YYSIZE_T +# include /* INFRINGES ON USER NAME SPACE */ +# define YYSIZE_T size_t +# else +# define YYSIZE_T unsigned +# endif +#endif + +#define YYSIZE_MAXIMUM ((YYSIZE_T) -1) + +#ifndef YY_ +# if defined YYENABLE_NLS && YYENABLE_NLS +# if ENABLE_NLS +# include /* INFRINGES ON USER NAME SPACE */ +# define YY_(Msgid) dgettext ("bison-runtime", Msgid) +# endif +# endif +# ifndef YY_ +# define YY_(Msgid) Msgid +# endif +#endif + +#ifndef YY_ATTRIBUTE +# if (defined __GNUC__ \ + && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \ + || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C +# define YY_ATTRIBUTE(Spec) __attribute__(Spec) +# else +# define YY_ATTRIBUTE(Spec) /* empty */ +# endif +#endif + +#ifndef YY_ATTRIBUTE_PURE +# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__)) +#endif + +#ifndef YY_ATTRIBUTE_UNUSED +# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__)) +#endif + +/* Suppress unused-variable warnings by "using" E. */ +#if ! defined lint || defined __GNUC__ +# define YYUSE(E) ((void) (E)) +#else +# define YYUSE(E) /* empty */ +#endif + +#if defined __GNUC__ && ! defined __ICC && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ +/* Suppress an incorrect diagnostic about yylval being uninitialized. */ +# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ + _Pragma ("GCC diagnostic push") \ + _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ + _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") +# define YY_IGNORE_MAYBE_UNINITIALIZED_END \ + _Pragma ("GCC diagnostic pop") +#else +# define YY_INITIAL_VALUE(Value) Value +#endif +#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN +# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN +# define YY_IGNORE_MAYBE_UNINITIALIZED_END +#endif +#ifndef YY_INITIAL_VALUE +# define YY_INITIAL_VALUE(Value) /* Nothing. */ +#endif + + +#if ! defined yyoverflow || YYERROR_VERBOSE + +/* The parser invokes alloca or malloc; define the necessary symbols. */ + +# ifdef YYSTACK_USE_ALLOCA +# if YYSTACK_USE_ALLOCA +# ifdef __GNUC__ +# define YYSTACK_ALLOC __builtin_alloca +# elif defined __BUILTIN_VA_ARG_INCR +# include /* INFRINGES ON USER NAME SPACE */ +# elif defined _AIX +# define YYSTACK_ALLOC __alloca +# elif defined _MSC_VER +# include /* INFRINGES ON USER NAME SPACE */ +# define alloca _alloca +# else +# define YYSTACK_ALLOC alloca +# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS +# include /* INFRINGES ON USER NAME SPACE */ + /* Use EXIT_SUCCESS as a witness for stdlib.h. */ +# ifndef EXIT_SUCCESS +# define EXIT_SUCCESS 0 +# endif +# endif +# endif +# endif +# endif + +# ifdef YYSTACK_ALLOC + /* Pacify GCC's 'empty if-body' warning. */ +# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) +# ifndef YYSTACK_ALLOC_MAXIMUM + /* The OS might guarantee only one guard page at the bottom of the stack, + and a page size can be as small as 4096 bytes. So we cannot safely + invoke alloca (N) if N exceeds 4096. Use a slightly smaller number + to allow for a few compiler-allocated temporary stack slots. */ +# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ +# endif +# else +# define YYSTACK_ALLOC YYMALLOC +# define YYSTACK_FREE YYFREE +# ifndef YYSTACK_ALLOC_MAXIMUM +# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM +# endif +# if (defined __cplusplus && ! defined EXIT_SUCCESS \ + && ! ((defined YYMALLOC || defined malloc) \ + && (defined YYFREE || defined free))) +# include /* INFRINGES ON USER NAME SPACE */ +# ifndef EXIT_SUCCESS +# define EXIT_SUCCESS 0 +# endif +# endif +# ifndef YYMALLOC +# define YYMALLOC malloc +# if ! defined malloc && ! defined EXIT_SUCCESS +void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ +# endif +# endif +# ifndef YYFREE +# define YYFREE free +# if ! defined free && ! defined EXIT_SUCCESS +void free (void *); /* INFRINGES ON USER NAME SPACE */ +# endif +# endif +# endif +#endif /* ! defined yyoverflow || YYERROR_VERBOSE */ + + +#if (! defined yyoverflow \ + && (! defined __cplusplus \ + || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) + +/* A type that is properly aligned for any stack member. */ +union yyalloc +{ + yytype_int16 yyss_alloc; + YYSTYPE yyvs_alloc; +}; + +/* The size of the maximum gap between one aligned stack and the next. */ +# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) + +/* The size of an array large to enough to hold all stacks, each with + N elements. */ +# define YYSTACK_BYTES(N) \ + ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ + + YYSTACK_GAP_MAXIMUM) + +# define YYCOPY_NEEDED 1 + +/* Relocate STACK from its old location to the new one. The + local variables YYSIZE and YYSTACKSIZE give the old and new number of + elements in the stack, and YYPTR gives the new location of the + stack. Advance YYPTR to a properly aligned location for the next + stack. */ +# define YYSTACK_RELOCATE(Stack_alloc, Stack) \ + do \ + { \ + YYSIZE_T yynewbytes; \ + YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ + Stack = &yyptr->Stack_alloc; \ + yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ + yyptr += yynewbytes / sizeof (*yyptr); \ + } \ + while (0) + +#endif + +#if defined YYCOPY_NEEDED && YYCOPY_NEEDED +/* Copy COUNT objects from SRC to DST. The source and destination do + not overlap. */ +# ifndef YYCOPY +# if defined __GNUC__ && 1 < __GNUC__ +# define YYCOPY(Dst, Src, Count) \ + __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) +# else +# define YYCOPY(Dst, Src, Count) \ + do \ + { \ + YYSIZE_T yyi; \ + for (yyi = 0; yyi < (Count); yyi++) \ + (Dst)[yyi] = (Src)[yyi]; \ + } \ + while (0) +# endif +# endif +#endif /* !YYCOPY_NEEDED */ + +/* YYFINAL -- State number of the termination state. */ +#define YYFINAL 10 +/* YYLAST -- Last index in YYTABLE. */ +#define YYLAST 8 + +/* YYNTOKENS -- Number of terminals. */ +#define YYNTOKENS 6 +/* YYNNTS -- Number of nonterminals. */ +#define YYNNTS 5 +/* YYNRULES -- Number of rules. */ +#define YYNRULES 10 +/* YYNSTATES -- Number of states. */ +#define YYNSTATES 14 + +#define YYUNDEFTOK 2 +#define YYMAXUTOK 260 + +/* YYTRANSLATE(TOKEN-NUM) -- Symbol number corresponding to TOKEN-NUM + as returned by yylex, with out-of-bounds checking. */ +#define YYTRANSLATE(YYX) \ + ((unsigned) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) + +/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM + as returned by yylex. */ +static const yytype_uint8 yytranslate[] = +{ + 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, + 5 +}; + +#if YYDEBUG + /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ +static const yytype_uint8 yyrline[] = +{ + 0, 125, 125, 128, 129, 132, 133, 134, 135, 137, + 138 +}; +#endif + +#if YYDEBUG || YYERROR_VERBOSE || 0 +/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. + First, the terminals, then, starting at YYNTOKENS, nonterminals. */ +static const char *const yytname[] = +{ + "$end", "error", "$undefined", "IDENTIFIER", "LABEL", "NEWLINE", + "$accept", "program", "lines", "line", "args", YY_NULLPTR +}; +#endif + +# ifdef YYPRINT +/* YYTOKNUM[NUM] -- (External) token number corresponding to the + (internal) symbol number NUM (which must be that of a token). */ +static const yytype_uint16 yytoknum[] = +{ + 0, 256, 257, 258, 259, 260 +}; +# endif + +#define YYPACT_NINF -4 + +#define yypact_value_is_default(Yystate) \ + (!!((Yystate) == (-4))) + +#define YYTABLE_NINF -1 + +#define yytable_value_is_error(Yytable_value) \ + 0 + + /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing + STATE-NUM. */ +static const yytype_int8 yypact[] = +{ + -3, 0, -4, -4, 7, -3, -4, -4, -4, 1, + -4, -4, -4, -4 +}; + + /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. + Performed when YYTABLE does not specify something else to do. Zero + means the default is an error. */ +static const yytype_uint8 yydefact[] = +{ + 0, 0, 6, 5, 0, 2, 3, 9, 7, 0, + 1, 4, 10, 8 +}; + + /* YYPGOTO[NTERM-NUM]. */ +static const yytype_int8 yypgoto[] = +{ + -4, -4, -4, 3, -4 +}; + + /* YYDEFGOTO[NTERM-NUM]. */ +static const yytype_int8 yydefgoto[] = +{ + -1, 4, 5, 6, 9 +}; + + /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If + positive, shift that token. If negative, reduce the rule whose + number is the opposite. If YYTABLE_NINF, syntax error. */ +static const yytype_uint8 yytable[] = +{ + 1, 2, 3, 7, 12, 8, 13, 10, 11 +}; + +static const yytype_uint8 yycheck[] = +{ + 3, 4, 5, 3, 3, 5, 5, 0, 5 +}; + + /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing + symbol of state STATE-NUM. */ +static const yytype_uint8 yystos[] = +{ + 0, 3, 4, 5, 7, 8, 9, 3, 5, 10, + 0, 9, 3, 5 +}; + + /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ +static const yytype_uint8 yyr1[] = +{ + 0, 6, 7, 8, 8, 9, 9, 9, 9, 10, + 10 +}; + + /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ +static const yytype_uint8 yyr2[] = +{ + 0, 2, 1, 1, 2, 1, 1, 2, 3, 1, + 2 +}; + + +#define yyerrok (yyerrstatus = 0) +#define yyclearin (yychar = YYEMPTY) +#define YYEMPTY (-2) +#define YYEOF 0 + +#define YYACCEPT goto yyacceptlab +#define YYABORT goto yyabortlab +#define YYERROR goto yyerrorlab + + +#define YYRECOVERING() (!!yyerrstatus) + +#define YYBACKUP(Token, Value) \ + do \ + if (yychar == YYEMPTY) \ + { \ + yychar = (Token); \ + yylval = (Value); \ + YYPOPSTACK (yylen); \ + yystate = *yyssp; \ + goto yybackup; \ + } \ + else \ + { \ + yyerror (YY_("syntax error: cannot back up")); \ + YYERROR; \ + } \ + while (0) + +/* Error token number */ +#define YYTERROR 1 +#define YYERRCODE 256 + + + +/* Enable debugging if requested. */ +#if YYDEBUG + +# ifndef YYFPRINTF +# include /* INFRINGES ON USER NAME SPACE */ +# define YYFPRINTF fprintf +# endif + +# define YYDPRINTF(Args) \ +do { \ + if (yydebug) \ + YYFPRINTF Args; \ +} while (0) + +/* This macro is provided for backward compatibility. */ +#ifndef YY_LOCATION_PRINT +# define YY_LOCATION_PRINT(File, Loc) ((void) 0) +#endif + + +# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ +do { \ + if (yydebug) \ + { \ + YYFPRINTF (stderr, "%s ", Title); \ + yy_symbol_print (stderr, \ + Type, Value); \ + YYFPRINTF (stderr, "\n"); \ + } \ +} while (0) + + +/*-----------------------------------. +| Print this symbol's value on YYO. | +`-----------------------------------*/ + +static void +yy_symbol_value_print (FILE *yyo, int yytype, YYSTYPE const * const yyvaluep) +{ + FILE *yyoutput = yyo; + YYUSE (yyoutput); + if (!yyvaluep) + return; +# ifdef YYPRINT + if (yytype < YYNTOKENS) + YYPRINT (yyo, yytoknum[yytype], *yyvaluep); +# endif + YYUSE (yytype); +} + + +/*---------------------------. +| Print this symbol on YYO. | +`---------------------------*/ + +static void +yy_symbol_print (FILE *yyo, int yytype, YYSTYPE const * const yyvaluep) +{ + YYFPRINTF (yyo, "%s %s (", + yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]); + + yy_symbol_value_print (yyo, yytype, yyvaluep); + YYFPRINTF (yyo, ")"); +} + +/*------------------------------------------------------------------. +| yy_stack_print -- Print the state stack from its BOTTOM up to its | +| TOP (included). | +`------------------------------------------------------------------*/ + +static void +yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) +{ + YYFPRINTF (stderr, "Stack now"); + for (; yybottom <= yytop; yybottom++) + { + int yybot = *yybottom; + YYFPRINTF (stderr, " %d", yybot); + } + YYFPRINTF (stderr, "\n"); +} + +# define YY_STACK_PRINT(Bottom, Top) \ +do { \ + if (yydebug) \ + yy_stack_print ((Bottom), (Top)); \ +} while (0) + + +/*------------------------------------------------. +| Report that the YYRULE is going to be reduced. | +`------------------------------------------------*/ + +static void +yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule) +{ + unsigned long yylno = yyrline[yyrule]; + int yynrhs = yyr2[yyrule]; + int yyi; + YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", + yyrule - 1, yylno); + /* The symbols being reduced. */ + for (yyi = 0; yyi < yynrhs; yyi++) + { + YYFPRINTF (stderr, " $%d = ", yyi + 1); + yy_symbol_print (stderr, + yystos[yyssp[yyi + 1 - yynrhs]], + &yyvsp[(yyi + 1) - (yynrhs)] + ); + YYFPRINTF (stderr, "\n"); + } +} + +# define YY_REDUCE_PRINT(Rule) \ +do { \ + if (yydebug) \ + yy_reduce_print (yyssp, yyvsp, Rule); \ +} while (0) + +/* Nonzero means print parse trace. It is left uninitialized so that + multiple parsers can coexist. */ +int yydebug; +#else /* !YYDEBUG */ +# define YYDPRINTF(Args) +# define YY_SYMBOL_PRINT(Title, Type, Value, Location) +# define YY_STACK_PRINT(Bottom, Top) +# define YY_REDUCE_PRINT(Rule) +#endif /* !YYDEBUG */ + + +/* YYINITDEPTH -- initial size of the parser's stacks. */ +#ifndef YYINITDEPTH +# define YYINITDEPTH 200 +#endif + +/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only + if the built-in stack extension method is used). + + Do not make this value too large; the results are undefined if + YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) + evaluated with infinite-precision integer arithmetic. */ + +#ifndef YYMAXDEPTH +# define YYMAXDEPTH 10000 +#endif + + +#if YYERROR_VERBOSE + +# ifndef yystrlen +# if defined __GLIBC__ && defined _STRING_H +# define yystrlen strlen +# else +/* Return the length of YYSTR. */ +static YYSIZE_T +yystrlen (const char *yystr) +{ + YYSIZE_T yylen; + for (yylen = 0; yystr[yylen]; yylen++) + continue; + return yylen; +} +# endif +# endif + +# ifndef yystpcpy +# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE +# define yystpcpy stpcpy +# else +/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in + YYDEST. */ +static char * +yystpcpy (char *yydest, const char *yysrc) +{ + char *yyd = yydest; + const char *yys = yysrc; + + while ((*yyd++ = *yys++) != '\0') + continue; + + return yyd - 1; +} +# endif +# endif + +# ifndef yytnamerr +/* Copy to YYRES the contents of YYSTR after stripping away unnecessary + quotes and backslashes, so that it's suitable for yyerror. The + heuristic is that double-quoting is unnecessary unless the string + contains an apostrophe, a comma, or backslash (other than + backslash-backslash). YYSTR is taken from yytname. If YYRES is + null, do not copy; instead, return the length of what the result + would have been. */ +static YYSIZE_T +yytnamerr (char *yyres, const char *yystr) +{ + if (*yystr == '"') + { + YYSIZE_T yyn = 0; + char const *yyp = yystr; + + for (;;) + switch (*++yyp) + { + case '\'': + case ',': + goto do_not_strip_quotes; + + case '\\': + if (*++yyp != '\\') + goto do_not_strip_quotes; + else + goto append; + + append: + default: + if (yyres) + yyres[yyn] = *yyp; + yyn++; + break; + + case '"': + if (yyres) + yyres[yyn] = '\0'; + return yyn; + } + do_not_strip_quotes: ; + } + + if (! yyres) + return yystrlen (yystr); + + return (YYSIZE_T) (yystpcpy (yyres, yystr) - yyres); +} +# endif + +/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message + about the unexpected token YYTOKEN for the state stack whose top is + YYSSP. + + Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is + not large enough to hold the message. In that case, also set + *YYMSG_ALLOC to the required number of bytes. Return 2 if the + required number of bytes is too large to store. */ +static int +yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, + yytype_int16 *yyssp, int yytoken) +{ + YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]); + YYSIZE_T yysize = yysize0; + enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; + /* Internationalized format string. */ + const char *yyformat = YY_NULLPTR; + /* Arguments of yyformat. */ + char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; + /* Number of reported tokens (one for the "unexpected", one per + "expected"). */ + int yycount = 0; + + /* There are many possibilities here to consider: + - If this state is a consistent state with a default action, then + the only way this function was invoked is if the default action + is an error action. In that case, don't check for expected + tokens because there are none. + - The only way there can be no lookahead present (in yychar) is if + this state is a consistent state with a default action. Thus, + detecting the absence of a lookahead is sufficient to determine + that there is no unexpected or expected token to report. In that + case, just report a simple "syntax error". + - Don't assume there isn't a lookahead just because this state is a + consistent state with a default action. There might have been a + previous inconsistent state, consistent state with a non-default + action, or user semantic action that manipulated yychar. + - Of course, the expected token list depends on states to have + correct lookahead information, and it depends on the parser not + to perform extra reductions after fetching a lookahead from the + scanner and before detecting a syntax error. Thus, state merging + (from LALR or IELR) and default reductions corrupt the expected + token list. However, the list is correct for canonical LR with + one exception: it will still contain any token that will not be + accepted due to an error action in a later state. + */ + if (yytoken != YYEMPTY) + { + int yyn = yypact[*yyssp]; + yyarg[yycount++] = yytname[yytoken]; + if (!yypact_value_is_default (yyn)) + { + /* Start YYX at -YYN if negative to avoid negative indexes in + YYCHECK. In other words, skip the first -YYN actions for + this state because they are default actions. */ + int yyxbegin = yyn < 0 ? -yyn : 0; + /* Stay within bounds of both yycheck and yytname. */ + int yychecklim = YYLAST - yyn + 1; + int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; + int yyx; + + for (yyx = yyxbegin; yyx < yyxend; ++yyx) + if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR + && !yytable_value_is_error (yytable[yyx + yyn])) + { + if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) + { + yycount = 1; + yysize = yysize0; + break; + } + yyarg[yycount++] = yytname[yyx]; + { + YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]); + if (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM) + yysize = yysize1; + else + return 2; + } + } + } + } + + switch (yycount) + { +# define YYCASE_(N, S) \ + case N: \ + yyformat = S; \ + break + default: /* Avoid compiler warnings. */ + YYCASE_(0, YY_("syntax error")); + YYCASE_(1, YY_("syntax error, unexpected %s")); + YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); + YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); + YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); + YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); +# undef YYCASE_ + } + + { + YYSIZE_T yysize1 = yysize + yystrlen (yyformat); + if (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM) + yysize = yysize1; + else + return 2; + } + + if (*yymsg_alloc < yysize) + { + *yymsg_alloc = 2 * yysize; + if (! (yysize <= *yymsg_alloc + && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) + *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; + return 1; + } + + /* Avoid sprintf, as that infringes on the user's name space. + Don't have undefined behavior even if the translation + produced a string with the wrong number of "%s"s. */ + { + char *yyp = *yymsg; + int yyi = 0; + while ((*yyp = *yyformat) != '\0') + if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) + { + yyp += yytnamerr (yyp, yyarg[yyi++]); + yyformat += 2; + } + else + { + yyp++; + yyformat++; + } + } + return 0; +} +#endif /* YYERROR_VERBOSE */ + +/*-----------------------------------------------. +| Release the memory associated to this symbol. | +`-----------------------------------------------*/ + +static void +yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep) +{ + YYUSE (yyvaluep); + if (!yymsg) + yymsg = "Deleting"; + YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); + + YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN + YYUSE (yytype); + YY_IGNORE_MAYBE_UNINITIALIZED_END +} + + + + +/* The lookahead symbol. */ +int yychar; + +/* The semantic value of the lookahead symbol. */ +YYSTYPE yylval; +/* Number of syntax errors so far. */ +int yynerrs; + + +/*----------. +| yyparse. | +`----------*/ + +int +yyparse (void) +{ + int yystate; + /* Number of tokens to shift before error messages enabled. */ + int yyerrstatus; + + /* The stacks and their tools: + 'yyss': related to states. + 'yyvs': related to semantic values. + + Refer to the stacks through separate pointers, to allow yyoverflow + to reallocate them elsewhere. */ + + /* The state stack. */ + yytype_int16 yyssa[YYINITDEPTH]; + yytype_int16 *yyss; + yytype_int16 *yyssp; + + /* The semantic value stack. */ + YYSTYPE yyvsa[YYINITDEPTH]; + YYSTYPE *yyvs; + YYSTYPE *yyvsp; + + YYSIZE_T yystacksize; + + int yyn; + int yyresult; + /* Lookahead token as an internal (translated) token number. */ + int yytoken = 0; + /* The variables used to return semantic value and location from the + action routines. */ + YYSTYPE yyval; + +#if YYERROR_VERBOSE + /* Buffer for error messages, and its allocated size. */ + char yymsgbuf[128]; + char *yymsg = yymsgbuf; + YYSIZE_T yymsg_alloc = sizeof yymsgbuf; +#endif + +#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) + + /* The number of symbols on the RHS of the reduced rule. + Keep to zero when no symbol should be popped. */ + int yylen = 0; + + yyssp = yyss = yyssa; + yyvsp = yyvs = yyvsa; + yystacksize = YYINITDEPTH; + + YYDPRINTF ((stderr, "Starting parse\n")); + + yystate = 0; + yyerrstatus = 0; + yynerrs = 0; + yychar = YYEMPTY; /* Cause a token to be read. */ + goto yysetstate; + + +/*------------------------------------------------------------. +| yynewstate -- push a new state, which is found in yystate. | +`------------------------------------------------------------*/ +yynewstate: + /* In all cases, when you get here, the value and location stacks + have just been pushed. So pushing a state here evens the stacks. */ + yyssp++; + + +/*--------------------------------------------------------------------. +| yynewstate -- set current state (the top of the stack) to yystate. | +`--------------------------------------------------------------------*/ +yysetstate: + *yyssp = (yytype_int16) yystate; + + if (yyss + yystacksize - 1 <= yyssp) +#if !defined yyoverflow && !defined YYSTACK_RELOCATE + goto yyexhaustedlab; +#else + { + /* Get the current used size of the three stacks, in elements. */ + YYSIZE_T yysize = (YYSIZE_T) (yyssp - yyss + 1); + +# if defined yyoverflow + { + /* Give user a chance to reallocate the stack. Use copies of + these so that the &'s don't force the real ones into + memory. */ + YYSTYPE *yyvs1 = yyvs; + yytype_int16 *yyss1 = yyss; + + /* Each stack pointer address is followed by the size of the + data in use in that stack, in bytes. This used to be a + conditional around just the two extra args, but that might + be undefined if yyoverflow is a macro. */ + yyoverflow (YY_("memory exhausted"), + &yyss1, yysize * sizeof (*yyssp), + &yyvs1, yysize * sizeof (*yyvsp), + &yystacksize); + yyss = yyss1; + yyvs = yyvs1; + } +# else /* defined YYSTACK_RELOCATE */ + /* Extend the stack our own way. */ + if (YYMAXDEPTH <= yystacksize) + goto yyexhaustedlab; + yystacksize *= 2; + if (YYMAXDEPTH < yystacksize) + yystacksize = YYMAXDEPTH; + + { + yytype_int16 *yyss1 = yyss; + union yyalloc *yyptr = + (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); + if (! yyptr) + goto yyexhaustedlab; + YYSTACK_RELOCATE (yyss_alloc, yyss); + YYSTACK_RELOCATE (yyvs_alloc, yyvs); +# undef YYSTACK_RELOCATE + if (yyss1 != yyssa) + YYSTACK_FREE (yyss1); + } +# endif + + yyssp = yyss + yysize - 1; + yyvsp = yyvs + yysize - 1; + + YYDPRINTF ((stderr, "Stack size increased to %lu\n", + (unsigned long) yystacksize)); + + if (yyss + yystacksize - 1 <= yyssp) + YYABORT; + } +#endif /* !defined yyoverflow && !defined YYSTACK_RELOCATE */ + + YYDPRINTF ((stderr, "Entering state %d\n", yystate)); + + if (yystate == YYFINAL) + YYACCEPT; + + goto yybackup; + + +/*-----------. +| yybackup. | +`-----------*/ +yybackup: + /* Do appropriate processing given the current state. Read a + lookahead token if we need one and don't already have one. */ + + /* First try to decide what to do without reference to lookahead token. */ + yyn = yypact[yystate]; + if (yypact_value_is_default (yyn)) + goto yydefault; + + /* Not known => get a lookahead token if don't already have one. */ + + /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ + if (yychar == YYEMPTY) + { + YYDPRINTF ((stderr, "Reading a token: ")); + yychar = yylex (); + } + + if (yychar <= YYEOF) + { + yychar = yytoken = YYEOF; + YYDPRINTF ((stderr, "Now at end of input.\n")); + } + else + { + yytoken = YYTRANSLATE (yychar); + YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); + } + + /* If the proper action on seeing token YYTOKEN is to reduce or to + detect an error, take that action. */ + yyn += yytoken; + if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) + goto yydefault; + yyn = yytable[yyn]; + if (yyn <= 0) + { + if (yytable_value_is_error (yyn)) + goto yyerrlab; + yyn = -yyn; + goto yyreduce; + } + + /* Count tokens shifted since error; after three, turn off error + status. */ + if (yyerrstatus) + yyerrstatus--; + + /* Shift the lookahead token. */ + YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); + + /* Discard the shifted token. */ + yychar = YYEMPTY; + + yystate = yyn; + YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN + *++yyvsp = yylval; + YY_IGNORE_MAYBE_UNINITIALIZED_END + + goto yynewstate; + + +/*-----------------------------------------------------------. +| yydefault -- do the default action for the current state. | +`-----------------------------------------------------------*/ +yydefault: + yyn = yydefact[yystate]; + if (yyn == 0) + goto yyerrlab; + goto yyreduce; + + +/*-----------------------------. +| yyreduce -- do a reduction. | +`-----------------------------*/ +yyreduce: + /* yyn is the number of a rule to reduce with. */ + yylen = yyr2[yyn]; + + /* If YYLEN is nonzero, implement the default value of the action: + '$$ = $1'. + + Otherwise, the following line sets YYVAL to garbage. + This behavior is undocumented and Bison + users should not rely upon it. Assigning to YYVAL + unconditionally makes the parser a bit smaller, and it avoids a + GCC warning that YYVAL may be used uninitialized. */ + yyval = yyvsp[1-yylen]; + + + YY_REDUCE_PRINT (yyn); + switch (yyn) + { + case 2: +#line 125 "../src/ainedit/asm_parser.y" /* yacc.c:1652 */ + { parsed_code = (yyvsp[0].program); } +#line 1321 "src/ainedit/48087cf@@ainedit@exe/asm_parser.tab.c" /* yacc.c:1652 */ + break; + + case 3: +#line 128 "../src/ainedit/asm_parser.y" /* yacc.c:1652 */ + { (yyval.program) = make_program(); if ((yyvsp[0].instr)) { push_instruction((yyval.program), (yyvsp[0].instr)); } } +#line 1327 "src/ainedit/48087cf@@ainedit@exe/asm_parser.tab.c" /* yacc.c:1652 */ + break; + + case 4: +#line 129 "../src/ainedit/asm_parser.y" /* yacc.c:1652 */ + { if ((yyvsp[0].instr)) { push_instruction((yyvsp[-1].program), (yyvsp[0].instr)); } } +#line 1333 "src/ainedit/48087cf@@ainedit@exe/asm_parser.tab.c" /* yacc.c:1652 */ + break; + + case 5: +#line 132 "../src/ainedit/asm_parser.y" /* yacc.c:1652 */ + { (yyval.instr) = NULL; } +#line 1339 "src/ainedit/48087cf@@ainedit@exe/asm_parser.tab.c" /* yacc.c:1652 */ + break; + + case 6: +#line 133 "../src/ainedit/asm_parser.y" /* yacc.c:1652 */ + { push_label((yyvsp[0].string)->text); (yyval.instr) = NULL; } +#line 1345 "src/ainedit/48087cf@@ainedit@exe/asm_parser.tab.c" /* yacc.c:1652 */ + break; + + case 7: +#line 134 "../src/ainedit/asm_parser.y" /* yacc.c:1652 */ + { (yyval.instr) = make_instruction((yyvsp[-1].string), NULL); } +#line 1351 "src/ainedit/48087cf@@ainedit@exe/asm_parser.tab.c" /* yacc.c:1652 */ + break; + + case 8: +#line 135 "../src/ainedit/asm_parser.y" /* yacc.c:1652 */ + { (yyval.instr) = make_instruction((yyvsp[-2].string), (yyvsp[-1].args)); } +#line 1357 "src/ainedit/48087cf@@ainedit@exe/asm_parser.tab.c" /* yacc.c:1652 */ + break; + + case 9: +#line 137 "../src/ainedit/asm_parser.y" /* yacc.c:1652 */ + { (yyval.args) = make_arglist(); push_arg((yyval.args), (yyvsp[0].string)); } +#line 1363 "src/ainedit/48087cf@@ainedit@exe/asm_parser.tab.c" /* yacc.c:1652 */ + break; + + case 10: +#line 138 "../src/ainedit/asm_parser.y" /* yacc.c:1652 */ + { push_arg((yyvsp[-1].args), (yyvsp[0].string)); } +#line 1369 "src/ainedit/48087cf@@ainedit@exe/asm_parser.tab.c" /* yacc.c:1652 */ + break; + + +#line 1373 "src/ainedit/48087cf@@ainedit@exe/asm_parser.tab.c" /* yacc.c:1652 */ + default: break; + } + /* User semantic actions sometimes alter yychar, and that requires + that yytoken be updated with the new translation. We take the + approach of translating immediately before every use of yytoken. + One alternative is translating here after every semantic action, + but that translation would be missed if the semantic action invokes + YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or + if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an + incorrect destructor might then be invoked immediately. In the + case of YYERROR or YYBACKUP, subsequent parser actions might lead + to an incorrect destructor call or verbose syntax error message + before the lookahead is translated. */ + YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); + + YYPOPSTACK (yylen); + yylen = 0; + YY_STACK_PRINT (yyss, yyssp); + + *++yyvsp = yyval; + + /* Now 'shift' the result of the reduction. Determine what state + that goes to, based on the state we popped back to and the rule + number reduced by. */ + { + const int yylhs = yyr1[yyn] - YYNTOKENS; + const int yyi = yypgoto[yylhs] + *yyssp; + yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp + ? yytable[yyi] + : yydefgoto[yylhs]); + } + + goto yynewstate; + + +/*--------------------------------------. +| yyerrlab -- here on detecting error. | +`--------------------------------------*/ +yyerrlab: + /* Make sure we have latest lookahead translation. See comments at + user semantic actions for why this is necessary. */ + yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); + + /* If not already recovering from an error, report this error. */ + if (!yyerrstatus) + { + ++yynerrs; +#if ! YYERROR_VERBOSE + yyerror (YY_("syntax error")); +#else +# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ + yyssp, yytoken) + { + char const *yymsgp = YY_("syntax error"); + int yysyntax_error_status; + yysyntax_error_status = YYSYNTAX_ERROR; + if (yysyntax_error_status == 0) + yymsgp = yymsg; + else if (yysyntax_error_status == 1) + { + if (yymsg != yymsgbuf) + YYSTACK_FREE (yymsg); + yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); + if (!yymsg) + { + yymsg = yymsgbuf; + yymsg_alloc = sizeof yymsgbuf; + yysyntax_error_status = 2; + } + else + { + yysyntax_error_status = YYSYNTAX_ERROR; + yymsgp = yymsg; + } + } + yyerror (yymsgp); + if (yysyntax_error_status == 2) + goto yyexhaustedlab; + } +# undef YYSYNTAX_ERROR +#endif + } + + + + if (yyerrstatus == 3) + { + /* If just tried and failed to reuse lookahead token after an + error, discard it. */ + + if (yychar <= YYEOF) + { + /* Return failure if at end of input. */ + if (yychar == YYEOF) + YYABORT; + } + else + { + yydestruct ("Error: discarding", + yytoken, &yylval); + yychar = YYEMPTY; + } + } + + /* Else will try to reuse lookahead token after shifting the error + token. */ + goto yyerrlab1; + + +/*---------------------------------------------------. +| yyerrorlab -- error raised explicitly by YYERROR. | +`---------------------------------------------------*/ +yyerrorlab: + /* Pacify compilers when the user code never invokes YYERROR and the + label yyerrorlab therefore never appears in user code. */ + if (0) + YYERROR; + + /* Do not reclaim the symbols of the rule whose action triggered + this YYERROR. */ + YYPOPSTACK (yylen); + yylen = 0; + YY_STACK_PRINT (yyss, yyssp); + yystate = *yyssp; + goto yyerrlab1; + + +/*-------------------------------------------------------------. +| yyerrlab1 -- common code for both syntax error and YYERROR. | +`-------------------------------------------------------------*/ +yyerrlab1: + yyerrstatus = 3; /* Each real token shifted decrements this. */ + + for (;;) + { + yyn = yypact[yystate]; + if (!yypact_value_is_default (yyn)) + { + yyn += YYTERROR; + if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) + { + yyn = yytable[yyn]; + if (0 < yyn) + break; + } + } + + /* Pop the current state because it cannot handle the error token. */ + if (yyssp == yyss) + YYABORT; + + + yydestruct ("Error: popping", + yystos[yystate], yyvsp); + YYPOPSTACK (1); + yystate = *yyssp; + YY_STACK_PRINT (yyss, yyssp); + } + + YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN + *++yyvsp = yylval; + YY_IGNORE_MAYBE_UNINITIALIZED_END + + + /* Shift the error token. */ + YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); + + yystate = yyn; + goto yynewstate; + + +/*-------------------------------------. +| yyacceptlab -- YYACCEPT comes here. | +`-------------------------------------*/ +yyacceptlab: + yyresult = 0; + goto yyreturn; + + +/*-----------------------------------. +| yyabortlab -- YYABORT comes here. | +`-----------------------------------*/ +yyabortlab: + yyresult = 1; + goto yyreturn; + + +#if !defined yyoverflow || YYERROR_VERBOSE +/*-------------------------------------------------. +| yyexhaustedlab -- memory exhaustion comes here. | +`-------------------------------------------------*/ +yyexhaustedlab: + yyerror (YY_("memory exhausted")); + yyresult = 2; + /* Fall through. */ +#endif + + +/*-----------------------------------------------------. +| yyreturn -- parsing is finished, return the result. | +`-----------------------------------------------------*/ +yyreturn: + if (yychar != YYEMPTY) + { + /* Make sure we have latest lookahead translation. See comments at + user semantic actions for why this is necessary. */ + yytoken = YYTRANSLATE (yychar); + yydestruct ("Cleanup: discarding lookahead", + yytoken, &yylval); + } + /* Do not reclaim the symbols of the rule whose action triggered + this YYABORT or YYACCEPT. */ + YYPOPSTACK (yylen); + YY_STACK_PRINT (yyss, yyssp); + while (yyssp != yyss) + { + yydestruct ("Cleanup: popping", + yystos[*yyssp], yyvsp); + YYPOPSTACK (1); + } +#ifndef yyoverflow + if (yyss != yyssa) + YYSTACK_FREE (yyss); +#endif +#if YYERROR_VERBOSE + if (yymsg != yymsgbuf) + YYSTACK_FREE (yymsg); +#endif + return yyresult; +} +#line 141 "../src/ainedit/asm_parser.y" /* yacc.c:1918 */ + diff --git a/src/ainedit/asm_parser.tab.h b/src/ainedit/asm_parser.tab.h new file mode 100644 index 0000000..1de4021 --- /dev/null +++ b/src/ainedit/asm_parser.tab.h @@ -0,0 +1,106 @@ +/* A Bison parser, made by GNU Bison 3.3.2. */ + +/* Bison interface for Yacc-like parsers in C + + Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2019 Free Software Foundation, + Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* As a special exception, you may create a larger work that contains + part or all of the Bison parser skeleton and distribute that work + under terms of your choice, so long as that work isn't itself a + parser generator using the skeleton or a modified version thereof + as a parser skeleton. Alternatively, if you modify or redistribute + the parser skeleton itself, you may (at your option) remove this + special exception, which will cause the skeleton and the resulting + Bison output files to be licensed under the GNU General Public + License without this special exception. + + This special exception was added by the Free Software Foundation in + version 2.2 of Bison. */ + +/* Undocumented macros, especially those whose name start with YY_, + are private implementation details. Do not rely on them. */ + +#ifndef YY_YY_SRC_AINEDIT_48087CF_AINEDIT_EXE_ASM_PARSER_TAB_H_INCLUDED +# define YY_YY_SRC_AINEDIT_48087CF_AINEDIT_EXE_ASM_PARSER_TAB_H_INCLUDED +/* Debug traces. */ +#ifndef YYDEBUG +# define YYDEBUG 0 +#endif +#if YYDEBUG +extern int yydebug; +#endif +/* "%code requires" blocks. */ +#line 9 "../src/ainedit/asm_parser.y" /* yacc.c:1921 */ + + #include + #include "khash.h" + #include "kvec.h" + + kv_decl(parse_instruction_list, struct parse_instruction*); + kv_decl(parse_argument_list, struct string*); + kv_decl(pointer_list, uint32_t*); + + struct parse_instruction { + uint16_t opcode; + parse_argument_list *args; + }; + + parse_instruction_list *parsed_code; + + KHASH_MAP_INIT_STR(label_table, uint32_t); + khash_t(label_table) *label_table; + +#line 68 "src/ainedit/48087cf@@ainedit@exe/asm_parser.tab.h" /* yacc.c:1921 */ + +/* Token type. */ +#ifndef YYTOKENTYPE +# define YYTOKENTYPE + enum yytokentype + { + IDENTIFIER = 258, + LABEL = 259, + NEWLINE = 260 + }; +#endif + +/* Value type. */ +#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED + +union YYSTYPE +{ +#line 1 "../src/ainedit/asm_parser.y" /* yacc.c:1921 */ + + int token; + struct string *string; + parse_argument_list *args; + struct parse_instruction *instr; + parse_instruction_list *program; + +#line 94 "src/ainedit/48087cf@@ainedit@exe/asm_parser.tab.h" /* yacc.c:1921 */ +}; + +typedef union YYSTYPE YYSTYPE; +# define YYSTYPE_IS_TRIVIAL 1 +# define YYSTYPE_IS_DECLARED 1 +#endif + + +extern YYSTYPE yylval; + +int yyparse (void); + +#endif /* !YY_YY_SRC_AINEDIT_48087CF_AINEDIT_EXE_ASM_PARSER_TAB_H_INCLUDED */ diff --git a/src/ainedit/asm_parser.y b/src/ainedit/asm_parser.y new file mode 100644 index 0000000..38496c4 --- /dev/null +++ b/src/ainedit/asm_parser.y @@ -0,0 +1,141 @@ +%union { + int token; + struct string *string; + parse_argument_list *args; + struct parse_instruction *instr; + parse_instruction_list *program; +} + +%code requires { + #include + #include "khash.h" + #include "kvec.h" + + kv_decl(parse_instruction_list, struct parse_instruction*); + kv_decl(parse_argument_list, struct string*); + kv_decl(pointer_list, uint32_t*); + + struct parse_instruction { + uint16_t opcode; + parse_argument_list *args; + }; + + parse_instruction_list *parsed_code; + + KHASH_MAP_INIT_STR(label_table, uint32_t); + khash_t(label_table) *label_table; +} + +%{ + +#include +#include +#include "ainedit.h" +#include "kvec.h" +#include "system4.h" +#include "system4/instructions.h" +#include "system4/string.h" + +extern int yylex(); +void yyerror(const char *s) { ERROR("%s", s); } + +static uint32_t instr_ptr; + +static parse_instruction_list *make_program(void) +{ + parse_instruction_list *program = xmalloc(sizeof(parse_instruction_list)); + kv_init(*program); + instr_ptr = 0; + return program; +} + +static void push_instruction(parse_instruction_list *program, struct parse_instruction *instr) +{ + kv_push(struct parse_instruction*, *program, instr); + instr_ptr += instruction_width(instr->opcode); +} + +static struct parse_instruction *make_instruction(struct string *name, parse_argument_list *args) +{ + for (int i = 0; name->text[i]; i++) { + name->text[i] = toupper(name->text[i]); + } + // check opcode + struct instruction *info = asm_get_instruction(name->text); + if (!info) + ERROR("Invalid instruction: %s", name->text); + // check argument count + size_t nr_args = args ? kv_size(*args) : 0; + if (nr_args != (size_t)info->nr_args) { + fprintf(stderr, "In: '%s", info->name); + for (size_t i = 0; i < nr_args; i++) { + fprintf(stderr, " %s", kv_A(*args, i)->text); + } + fprintf(stderr, "'\n"); + ERROR("Wrong number of arguments for instruction '%s' (expected %d; got %lu)", + name->text, info->nr_args, nr_args); + } + // NOTE: argument values checked on second pass + + free_string(name); + + struct parse_instruction *instr = xmalloc(sizeof (struct parse_instruction)); + instr->opcode = info->opcode; + instr->args = args; + return instr; +} + +static parse_argument_list *make_arglist(void) +{ + parse_argument_list *args = xmalloc(sizeof(parse_argument_list)); + kv_init(*args); + return args; +} + +static void push_arg(parse_argument_list *args, struct string *arg) +{ + kv_push(struct string*, *args, arg); +} + +static void push_label(char *name) +{ + int ret; + khiter_t k = kh_put(label_table, label_table, name, &ret); + if (!ret) { + if (kh_value(label_table, k) != instr_ptr) + ERROR("Duplicate label: %s", name); + return; + } + kh_value(label_table, k) = instr_ptr; +} + +%} + +%token IDENTIFIER LABEL +%token NEWLINE + +%type lines +%type line +%type args + +%start program + +%% + +program : lines { parsed_code = $1; } + ; + +lines : line { $$ = make_program(); if ($1) { push_instruction($$, $1); } } + | lines line { if ($2) { push_instruction($1, $2); } } + ; + +line : NEWLINE { $$ = NULL; } + | LABEL { push_label($1->text); $$ = NULL; } + | IDENTIFIER NEWLINE { $$ = make_instruction($1, NULL); } + | IDENTIFIER args NEWLINE { $$ = make_instruction($1, $2); } + +args : IDENTIFIER { $$ = make_arglist(); push_arg($$, $1); } + | args IDENTIFIER { push_arg($1, $2); } + ; + +%% diff --git a/src/ainedit/json.c b/src/ainedit/json.c new file mode 100644 index 0000000..299feaf --- /dev/null +++ b/src/ainedit/json.c @@ -0,0 +1,521 @@ +/* Copyright (C) 2019 Nunuhara Cabbage + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + */ + +#include +#include +#include +#include +#include +#include "cJSON.h" +#include "system4.h" +#include "system4/ain.h" + +static bool cJSON_GetObjectBool(const cJSON * const o, const char * const name, bool def) +{ + cJSON *v = cJSON_GetObjectItem(o, name); + if (v && !cJSON_IsBool(v)) + ERROR("Expected a boolean for '%s'", name); + return v ? v->valueint : def; +} + +static int cJSON_GetObjectInteger(const cJSON * const o, const char * const name, int def) +{ + cJSON *v = cJSON_GetObjectItem(o, name); + if (v && !cJSON_IsNumber(v)) + ERROR("Expected a number for '%s'", name); + return v ? v->valueint : def; +} + +static int cJSON_GetObjectInteger_NonNull(const cJSON * const o, const char * const name) +{ + cJSON *v = cJSON_GetObjectItem(o, name); + if (!v || !cJSON_IsNumber(v)) + ERROR("Expected a number for '%s'", name); + return v->valueint; +} + +static char *cJSON_GetObjectString(const cJSON * const o, const char * const name) +{ + cJSON *v = cJSON_GetObjectItem(o, name); + if (v && !cJSON_IsString(v)) + ERROR("Expected string for '%s'", name); + return v ? strdup(v->valuestring) : NULL; +} + +static char *cJSON_GetObjectString_NonNull(const cJSON * const o, const char * const name) +{ + cJSON *v = cJSON_GetObjectItem(o, name); + if (!v || !cJSON_IsString(v)) + ERROR("Expected string for '%s'", name); + return strdup(v->valuestring); +} + +static cJSON *cJSON_GetObjectArray(const cJSON * const o, const char * const name) +{ + cJSON *v = cJSON_GetObjectItem(o, name); + if (v && !cJSON_IsArray(v)) + ERROR("Expected an array for '%s'", name); + return v; +} + +static cJSON *cJSON_GetObjectArray_NonNull(const cJSON * const o, const char * const name) +{ + cJSON *v = cJSON_GetObjectItem(o, name); + if (!v || !cJSON_IsArray(v)) + ERROR("Expected an array for '%s'", name); + return v; +} + +static void _read_type_declaration(cJSON *decl, struct ain_type *dst) +{ + dst->data = cJSON_GetArrayItem(decl, 0)->valueint; + dst->struc = cJSON_GetArrayItem(decl, 1)->valueint; + dst->rank = cJSON_GetArrayItem(decl, 2)->valueint; +} + +static void read_type_declaration(cJSON *decl, struct ain_type *dst) +{ + int size = cJSON_GetArraySize(decl); + if (size < 3 || size > 4) + ERROR("Invalid type declaration (array size = %d)", size); + + _read_type_declaration(decl, dst); + if (size == 4) { + int i; + cJSON *v, *a = cJSON_GetArrayItem(decl, 4); + if (!cJSON_IsArray(a)) + ERROR("Non-array in array-type slot"); + if (cJSON_GetArraySize(a) == 0) + return; + + dst->array_type = xcalloc(cJSON_GetArraySize(a), sizeof(struct ain_variable)); + cJSON_ArrayForEachIndex(i, v, a) { + if (!cJSON_IsArray(v)) + ERROR("Non-array in array-type list"); + if (cJSON_GetArraySize(v) != 3) + ERROR("Invalid type declaration (array size = %d)", cJSON_GetArraySize(v)); + _read_type_declaration(v, &dst->array_type[i]); + dst->array_type[i].array_type = &dst->array_type[i+1]; + } + dst->array_type[i-1].array_type = NULL; + } +} + +static void read_variable_declaration(cJSON *decl, struct ain_variable *dst) +{ + dst->name = cJSON_GetObjectString_NonNull(decl, "name"); + dst->name2 = cJSON_GetObjectString(decl, "name2"); + read_type_declaration(cJSON_GetObjectArray_NonNull(decl, "type"), &dst->type); + + cJSON *v = cJSON_GetObjectItem(decl, "initval"); + if (v) { + switch (dst->type.data) { + case AIN_STRING: + if (!cJSON_IsString(v)) + ERROR("Non-string initval for string variable"); + dst->initval.s = strdup(v->valuestring); + break; + case AIN_FLOAT: + if (!cJSON_IsNumber(v)) + ERROR("Non-number initval for float variable"); + dst->initval.f = v->valuedouble; + break; + default: + if (!cJSON_IsNumber(v)) + ERROR("Non-number initval for variable"); + dst->initval.i = v->valueint; + break; + } + } + + dst->group_index = cJSON_GetObjectInteger(decl, "group-index", -1); +} + +static void read_function_declaration(cJSON *decl, struct ain_function *dst) +{ + int i; + cJSON *args, *vars, *v; + + dst->address = cJSON_GetObjectInteger(decl, "address", 0); + dst->name = cJSON_GetObjectString_NonNull(decl, "name"); + dst->is_label = cJSON_GetObjectBool(decl, "is-label", 0); + read_type_declaration(cJSON_GetObjectArray_NonNull(decl, "return-type"), &dst->return_type); + dst->is_lambda = cJSON_GetObjectInteger(decl, "unknown-bool", 0); + dst->crc = cJSON_GetObjectInteger(decl, "crc", 0); + + args = cJSON_GetObjectArray_NonNull(decl, "arguments"); + vars = cJSON_GetObjectArray_NonNull(decl, "variables"); + dst->nr_args = cJSON_GetArraySize(args); + dst->nr_vars = dst->nr_args + cJSON_GetArraySize(vars); + + i = 0; + dst->vars = xcalloc(dst->nr_vars, sizeof(struct ain_variable)); + cJSON_ArrayForEach(v, args) { + if (!cJSON_IsObject(v)) + ERROR("Non-object in argument list"); + read_variable_declaration(v, &dst->vars[i]); + i++; + } + cJSON_ArrayForEach(v, vars) { + if (!cJSON_IsObject(v)) + ERROR("Non-object in variable list"); + read_variable_declaration(v, &dst->vars[i]); + i++; + } +} + +static void read_function_declarations(cJSON *decl, struct ain *ain) +{ + int i; + cJSON *f; + struct ain_function *functions = xcalloc(cJSON_GetArraySize(decl), sizeof(struct ain_function)); + cJSON_ArrayForEachIndex(i, f, decl) { + if (!cJSON_IsObject(f)) + ERROR("Non-object in function list"); + read_function_declaration(f, &functions[i]); + } + + ain_free_functions(ain); + ain->functions = functions; + ain->nr_functions = i; +} + +static struct ain_variable *read_variable_declarations(cJSON *decl, int *n) +{ + cJSON *v; + int i; + struct ain_variable *vars = xcalloc(cJSON_GetArraySize(decl), sizeof(struct ain_variable)); + cJSON_ArrayForEachIndex(i, v, decl) { + if (!cJSON_IsObject(v)) + ERROR("Non-object in variable list"); + read_variable_declaration(v, &vars[i]); + } + *n = i; + return vars; +} + +static void read_global_declarations(cJSON *decl, struct ain *ain) +{ + ain_free_globals(ain); + ain->globals = read_variable_declarations(decl, &ain->nr_globals); +} + +static struct ain_interface *read_interface_list(cJSON *decl, int32_t *n) +{ + *n = cJSON_GetArraySize(decl); + struct ain_interface *iface = xcalloc(*n, sizeof(struct ain_interface)); + + cJSON *v; + int i; + cJSON_ArrayForEachIndex(i, v, decl) { + if (!cJSON_IsArray(v)) + ERROR("Non-array in interface list"); + if (cJSON_GetArraySize(v) != 2) + ERROR("Wrong size array in interface list"); + iface[i].struct_type = cJSON_GetArrayItem(v, 0)->valueint; + iface[i].uk = cJSON_GetArrayItem(v, 1)->valueint; + } + + *n = i; + return iface; +} + +static void read_structure_declaration(cJSON *decl, struct ain_struct *dst) +{ + cJSON *a; + dst->name = cJSON_GetObjectString_NonNull(decl, "name"); + if ((a = cJSON_GetObjectArray(decl, "interfaces"))) { + dst->interfaces = read_interface_list(a, &dst->nr_interfaces); + } + dst->constructor = cJSON_GetObjectInteger(decl, "constructor", -1); + dst->destructor = cJSON_GetObjectInteger(decl, "destructor", -1); + if ((a = cJSON_GetObjectArray(decl, "members"))) { + dst->members = read_variable_declarations(a, &dst->nr_members); + } +} + +static void read_structure_declarations(cJSON *decl, struct ain *ain) +{ + int i; + cJSON *s; + struct ain_struct *structs = xcalloc(cJSON_GetArraySize(decl), sizeof(struct ain_struct)); + cJSON_ArrayForEachIndex(i, s, decl) { + if (!cJSON_IsObject(s)) + ERROR("Non-object in structure list"); + read_structure_declaration(s, &structs[i]); + } + + ain_free_structures(ain); + ain->structures = structs; + ain->nr_structures = i; +} + +static void read_library_declaration(cJSON *decl, struct ain_library *dst) +{ + dst->name = cJSON_GetObjectString_NonNull(decl, "name"); + + int i; + cJSON *f, *jfuns = cJSON_GetObjectArray_NonNull(decl, "functions"); + struct ain_hll_function *funs = xcalloc(cJSON_GetArraySize(jfuns), sizeof(struct ain_hll_function)); + cJSON_ArrayForEachIndex(i, f, jfuns) { + funs[i].name = cJSON_GetObjectString_NonNull(f, "name"); + funs[i].data_type = cJSON_GetObjectInteger_NonNull(f, "return-type"); + + int j; + cJSON *arg, *jargs = cJSON_GetObjectArray_NonNull(f, "arguments"); + struct ain_hll_argument *args = xcalloc(cJSON_GetArraySize(jargs), sizeof(struct ain_hll_argument)); + cJSON_ArrayForEachIndex(j, arg, jargs) { + args[j].name = cJSON_GetObjectString_NonNull(arg, "name"); + args[j].data_type = cJSON_GetObjectInteger_NonNull(arg, "type"); + } + funs[i].nr_arguments = j; + funs[i].arguments = args; + } + + dst->nr_functions = i; + dst->functions = funs; +} + +static void read_library_declarations(cJSON *decl, struct ain *ain) +{ + int i; + cJSON *lib; + struct ain_library *libs = xcalloc(cJSON_GetArraySize(decl), sizeof(struct ain_library)); + cJSON_ArrayForEachIndex(i, lib, decl) { + if (!cJSON_IsObject(lib)) + ERROR("Non-object in library list"); + read_library_declaration(lib, &libs[i]); + } + + ain_free_libraries(ain); + ain->libraries = libs; + ain->nr_libraries = i; +} + +static void read_switch_declaration(cJSON *decl, struct ain_switch *dst) +{ + dst->case_type = cJSON_GetObjectInteger_NonNull(decl, "case-type"); + dst->default_address = cJSON_GetObjectInteger_NonNull(decl, "default-address"); + + int i; + cJSON *v, *a = cJSON_GetObjectArray_NonNull(decl, "cases"); + struct ain_switch_case *cases = xcalloc(cJSON_GetArraySize(a), sizeof(struct ain_switch_case)); + cJSON_ArrayForEachIndex(i, v, a) { + if (!cJSON_IsObject(v)) + ERROR("Non-object in switch case list"); + cases[i].value = cJSON_GetObjectInteger_NonNull(v, "value"); + cases[i].address = cJSON_GetObjectInteger_NonNull(v, "address"); + } + dst->cases = cases; + dst->nr_cases = i; +} + +static void read_switch_declarations(cJSON *decl, struct ain *ain) +{ + int i; + cJSON *s; + struct ain_switch *switches = xcalloc(cJSON_GetArraySize(decl), sizeof(struct ain_switch)); + cJSON_ArrayForEachIndex(i, s, decl) { + if (!cJSON_IsObject(s)) + ERROR("Non-object in switch list"); + read_switch_declaration(s, &switches[i]); + } + + ain_free_switches(ain); + ain->switches = switches; + ain->nr_switches = i; +} + +static char **read_string_array(cJSON *decl, int *n) +{ + int i; + cJSON *str; + char **strings = xcalloc(cJSON_GetArraySize(decl), sizeof(char*)); + cJSON_ArrayForEachIndex(i, str, decl) { + if (!cJSON_IsString(str)) + ERROR("Non-string in string list"); + strings[i] = strdup(str->valuestring); + } + *n = i; + return strings; +} + +static void read_filename_declarations(cJSON *decl, struct ain *ain) +{ + ain_free_filenames(ain); + ain->filenames = read_string_array(decl, &ain->nr_filenames); +} + +static void read_function_type_declaration(cJSON *decl, struct ain_function_type *dst) +{ + dst->name = cJSON_GetObjectString_NonNull(decl, "name"); + read_type_declaration(cJSON_GetObjectArray_NonNull(decl, "return-type"), &dst->return_type); + + int i = 0; + cJSON *v; + cJSON *args = cJSON_GetObjectArray_NonNull(decl, "arguments"); + cJSON *vars = cJSON_GetObjectArray_NonNull(decl, "variables"); + dst->nr_arguments = cJSON_GetArraySize(args); + dst->nr_variables = cJSON_GetArraySize(vars) + dst->nr_arguments; + struct ain_variable *variables = xcalloc(dst->nr_variables, sizeof(struct ain_variable)); + cJSON_ArrayForEach(v, args) { + if (!cJSON_IsObject(v)) + ERROR("Non-object in argument list"); + read_variable_declaration(v, &variables[i]); + i++; + } + cJSON_ArrayForEach(v, vars) { + if (!cJSON_IsObject(v)) + ERROR("Non-object in variable list"); + read_variable_declaration(v, &variables[i]); + i++; + } + dst->variables = variables; +} + +static struct ain_function_type *_read_function_type_declarations(cJSON *decl, int *n) +{ + int i; + cJSON *f; + struct ain_function_type *types = xcalloc(cJSON_GetArraySize(decl), sizeof(struct ain_function_type)); + cJSON_ArrayForEachIndex(i, f, decl) { + if (!cJSON_IsObject(f)) + ERROR("Non-object in function type list"); + read_function_type_declaration(f, &types[i]); + } + *n = i; + return types; +} + +static void read_function_type_declarations(cJSON *decl, struct ain *ain) +{ + ain_free_function_types(ain); + ain->function_types = _read_function_type_declarations(decl, &ain->nr_function_types); +} + +static void read_delegate_declarations(cJSON *decl, struct ain *ain) +{ + ain_free_delegates(ain); + ain->delegates = _read_function_type_declarations(decl, &ain->nr_delegates); +} + +static void read_global_group_declarations(cJSON *decl, struct ain *ain) +{ + ain_free_global_groups(ain); + ain->global_group_names = read_string_array(decl, &ain->nr_global_groups); +} + +static void read_enum_declarations(cJSON *decl, struct ain *ain) +{ + int i; + cJSON *e; + struct ain_enum *enums = xcalloc(cJSON_GetArraySize(decl), sizeof(struct ain_enum)); + cJSON_ArrayForEachIndex(i, e, decl) { + if (!cJSON_IsObject(e)) + ERROR("Non-object in enum list"); + enums[i].name = cJSON_GetObjectString_NonNull(e, "name"); + + int j; + cJSON *s, *syms = cJSON_GetObjectArray_NonNull(e, "values"); + char **symbols = xcalloc(cJSON_GetArraySize(syms), sizeof(char*)); + cJSON_ArrayForEachIndex(j, s, syms) { + if (!cJSON_IsString(s)) + ERROR("Non-string in enum symbol list"); + symbols[i] = strdup(s->valuestring); + } + enums[i].nr_symbols = j; + enums[i].symbols = symbols; + } + + ain_free_enums(ain); + ain->enums = enums; + ain->nr_enums = i; +} + +static void read_json_declarations(cJSON *decl, struct ain *ain) +{ + cJSON *v; + + // VERS + ain->version = cJSON_GetObjectInteger(decl, "version", 0); + // KEYC + ain->keycode = cJSON_GetObjectInteger(decl, "keycode", 0); + // FUNC + if ((v = cJSON_GetObjectArray(decl, "functions"))) + read_function_declarations(v, ain); + // GLOB + if ((v = cJSON_GetObjectArray(decl, "globals"))) + read_global_declarations(v, ain); + // STRT + if ((v = cJSON_GetObjectArray(decl, "structures"))) + read_structure_declarations(v, ain); + // MAIN + ain->main = cJSON_GetObjectInteger(decl, "main", 0); + // MSGF + ain->msgf = cJSON_GetObjectInteger(decl, "msgf", 0); + // HLL0 + if ((v = cJSON_GetObjectArray(decl, "libraries"))) + read_library_declarations(v, ain); + // SWI0 + if ((v = cJSON_GetObjectArray(decl, "switches"))) + read_switch_declarations(v, ain); + // GVER + ain->game_version = cJSON_GetObjectInteger(decl, "game-version", 0); + // FNAM + if ((v = cJSON_GetObjectArray(decl, "filenames"))) + read_filename_declarations(v, ain); + // OJMP + ain->ojmp = cJSON_GetObjectInteger(decl, "ojmp", 0); + // FNCT + if ((v = cJSON_GetObjectArray(decl, "function-types"))) + read_function_type_declarations(v, ain); + // DELG + if ((v = cJSON_GetObjectArray(decl, "delegates"))) + read_delegate_declarations(v, ain); + // OBJG + if ((v = cJSON_GetObjectArray(decl, "global-groups"))) + read_global_group_declarations(v, ain); + // ENUM + if ((v = cJSON_GetObjectArray(decl, "enums"))) + read_enum_declarations(v, ain); +} + +void read_declarations(const char *filename, struct ain *ain) +{ + FILE *f; + long len; + char *buf; + + if (!(f = fopen(filename, "r"))) + ERROR("Failed to open '%s': %s", filename, strerror(errno)); + + fseek(f, 0, SEEK_END); + len = ftell(f); + fseek(f, 0, SEEK_SET); + + buf = xmalloc(len + 1); + if (fread(buf, len, 1, f) != 1) + ERROR("Failed to read '%s': %s", filename, strerror(errno)); + + if (fclose(f)) + ERROR("Failed to close '%s': %s", filename, strerror(errno)); + + cJSON *j = cJSON_Parse(buf); + if (!j) + ERROR("Failed to parse JSON file '%s'", filename); + + read_json_declarations(j, ain); +} diff --git a/src/ainedit/meson.build b/src/ainedit/meson.build new file mode 100644 index 0000000..93cbf57 --- /dev/null +++ b/src/ainedit/meson.build @@ -0,0 +1,33 @@ +# sources for ainedit +ainedit = ['../cJSON.c', + 'ainedit.c', + 'asm.c', + 'json.c', + 'repack.c', + #'ainedit/parser.c', + #'ainedit/tokens.c', +] + +if flex.found() + lgen = generator(flex, + output : '@BASENAME@.yy.c', + arguments : ['-o', '@OUTPUT@', '@INPUT@']) + lfiles = lgen.process('asm_lexer.l') +else + lfiles = 'asm_lexer.yy.c' +endif + +if bison.found() + pgen = generator(bison, + output: ['@BASENAME@.tab.c', '@BASENAME@.tab.h'], + arguments : ['@INPUT@', '--defines=@OUTPUT1@', '--output=@OUTPUT0@']) + pfiles = pgen.process('asm_parser.y') +else + pfiles = ['asm_parser.tab.c', 'asm_parser.tab.h'] +endif + +executable('ainedit', ainedit, lfiles, pfiles, + dependencies : [libm, zlib], + c_args : ['-Wno-unused-parameter'], + include_directories : incdir, + link_with : libsys4) diff --git a/src/ainedit/repack.c b/src/ainedit/repack.c new file mode 100644 index 0000000..dc43aea --- /dev/null +++ b/src/ainedit/repack.c @@ -0,0 +1,439 @@ +/* Copyright (C) 2019 Nunuhara Cabbage + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + */ + +#include +#include +#include +#include +#include +#include +#include "system4.h" +#include "system4/ain.h" +#include "system4/string.h" + +struct ain_buffer { + uint8_t *buf; + size_t size; + size_t ptr; +}; + +static void alloc_ainbuf(struct ain_buffer *out, size_t size) +{ + if (out->ptr + size < out->size) + return; + + size_t new_size = out->ptr + size; + while (out->size <= new_size) + out->size *= 2; + out->buf = xrealloc(out->buf, out->size); +} + +static void _write_int32(uint8_t *buf, uint32_t v) +{ + buf[0] = (v & 0x000000FF); + buf[1] = (v & 0x0000FF00) >> 8; + buf[2] = (v & 0x00FF0000) >> 16; + buf[3] = (v & 0xFF000000) >> 24; +} + +static void write_int32(struct ain_buffer *out, uint32_t v) +{ + alloc_ainbuf(out, 4); + out->buf[out->ptr++] = (v & 0x000000FF); + out->buf[out->ptr++] = (v & 0x0000FF00) >> 8; + out->buf[out->ptr++] = (v & 0x00FF0000) >> 16; + out->buf[out->ptr++] = (v & 0xFF000000) >> 24; +} + +static void write_bytes(struct ain_buffer *out, const uint8_t *bytes, size_t len) +{ + alloc_ainbuf(out, len); + memcpy(out->buf + out->ptr, bytes, len); + out->ptr += len; +} + +static void write_string(struct ain_buffer *out, const char *s) +{ + size_t len = strlen(s); + write_bytes(out, (const uint8_t*)s, len+1); +} + +static void write_header(struct ain_buffer *out, const char *s) +{ + write_bytes(out, (const uint8_t*)s, 4); +} + +static void write_array_type(struct ain_buffer *out, possibly_unused struct ain *ain, struct ain_type *t) +{ + for (int i = 0; i < t[0].rank+1; i++) { + write_int32(out, t[i].data); + write_int32(out, t[i].struc); + write_int32(out, t[i].rank); + } +} + +static void write_variable_type(struct ain_buffer *out, struct ain *ain, struct ain_type *t) +{ + write_int32(out, t->data); + write_int32(out, t->struc); + write_int32(out, t->rank); + + if (t->data == AIN_ARRAY || t->data == AIN_REF_ARRAY || t->data == AIN_ITERATOR || t->data == AIN_ENUM1) + write_array_type(out, ain, t->array_type); +} + +static void write_return_type(struct ain_buffer *out, struct ain *ain, struct ain_type *t) +{ + if (ain->version >= 11) { + write_variable_type(out, ain, t); + return; + } + + write_int32(out, t->data); + write_int32(out, t->struc); +} + +static void write_variable(struct ain_buffer *out, struct ain *ain, struct ain_variable *v) +{ + write_string(out, v->name); + if (ain->version >= 12) + write_string(out, v->name2); + write_variable_type(out, ain, &v->type); + if (ain->version >= 8) { + write_int32(out, v->has_initval); + if (v->has_initval) { + switch (v->type.data) { + case AIN_STRING: + write_string(out, v->initval.s); + case AIN_DELEGATE: + case AIN_REF_TYPE: + break; + default: + write_int32(out, v->initval.i); + } + } + } +} + +static void write_function(struct ain_buffer *out, struct ain *ain, struct ain_function *f) +{ + write_int32(out, f->address); + write_string(out, f->name); + if (ain->version > 0 && ain->version < 7) + write_int32(out, f->is_label); + write_return_type(out, ain, &f->return_type); + write_int32(out, f->nr_args); + write_int32(out, f->nr_vars); + if (ain->version >= 11) + write_int32(out, f->is_lambda); + if (ain->version > 0) + write_int32(out, f->crc); + for (int i = 0; i < f->nr_vars; i++) { + write_variable(out, ain, &f->vars[i]); + } +} + +static void write_global(struct ain_buffer *out, struct ain *ain, struct ain_variable *g) +{ + write_string(out, g->name); + if (ain->version >= 12) + write_string(out, g->name2); + write_variable_type(out, ain, &g->type); + if (ain->version >= 5) + write_int32(out, g->group_index); +} + +static void write_initval(struct ain_buffer *out, possibly_unused struct ain *ain, struct ain_initval *v) +{ + write_int32(out, v->global_index); + write_int32(out, v->data_type); + if (v->data_type == AIN_STRING) + write_string(out, v->string_value); + else + write_int32(out, v->int_value); +} + +static void write_structure(struct ain_buffer *out, struct ain *ain, struct ain_struct *s) +{ + write_string(out, s->name); + if (ain->version >= 11) { + write_int32(out, s->nr_interfaces); + for (int i = 0; i < s->nr_interfaces; i++) { + write_int32(out, s->interfaces[i].struct_type); + write_int32(out, s->interfaces[i].uk); + } + } + write_int32(out, s->constructor); + write_int32(out, s->destructor); + write_int32(out, s->nr_members); + for (int i = 0; i < s->nr_members; i++) { + write_variable(out, ain, &s->members[i]); + } +} + +static void write_library(struct ain_buffer *out, possibly_unused struct ain *ain, struct ain_library *lib) +{ + write_string(out, lib->name); + write_int32(out, lib->nr_functions); + for (int i = 0; i < lib->nr_functions; i++) { + write_string(out, lib->functions[i].name); + write_int32(out, lib->functions[i].data_type); + write_int32(out, lib->functions[i].nr_arguments); + for (int j = 0; j < lib->functions[i].nr_arguments; j++) { + write_string(out, lib->functions[i].arguments[j].name); + write_int32(out, lib->functions[i].arguments[j].data_type); + } + } +} + +static void write_switch(struct ain_buffer *out, possibly_unused struct ain *ain, struct ain_switch *s) +{ + write_int32(out, s->case_type); + write_int32(out, s->default_address); + write_int32(out, s->nr_cases); + for (int i = 0; i < s->nr_cases; i++) { + write_int32(out, s->cases[i].value); + write_int32(out, s->cases[i].address); + } +} + +static void write_function_type(struct ain_buffer *out, struct ain *ain, struct ain_function_type *f) +{ + write_string(out, f->name); + write_return_type(out, ain, &f->return_type); + write_int32(out, f->nr_arguments); + write_int32(out, f->nr_variables); + for (int i = 0; i < f->nr_variables; i++) { + write_variable(out, ain, &f->variables[i]); + } +} + +static void write_msg1_string(struct ain_buffer *out, possibly_unused struct ain *ain, struct string *msg) +{ + write_int32(out, msg->size); + + uint8_t *buf = xmalloc(msg->size); + for (int i = 0; i < msg->size; i++) { + buf[i] = msg->text[i]; + buf[i] += 0x60; + buf[i] += (uint8_t)i; + } + + write_bytes(out, buf, msg->size); + free(buf); +} + +static uint8_t *ain_flatten(struct ain *ain, size_t *len) +{ + struct ain_buffer out = { + .buf = xmalloc(256), + .size = 256, + .ptr = 0 + }; + + // VERS + write_header(&out, "VERS"); + write_int32(&out, ain->version); + // KEYC + if (ain->KEYC.present) { + write_header(&out, "KEYC"); + write_int32(&out, ain->keycode); + } + // CODE + if (ain->CODE.present) { + write_header(&out, "CODE"); + write_int32(&out, ain->code_size); + write_bytes(&out, ain->code, ain->code_size); + } + // FUNC + if (ain->FUNC.present) { + write_header(&out, "FUNC"); + write_int32(&out, ain->nr_functions); + for (int i = 0; i < ain->nr_functions; i++) { + write_function(&out, ain, &ain->functions[i]); + } + } + // GLOB + if (ain->GLOB.present) { + write_header(&out, "GLOB"); + write_int32(&out, ain->nr_globals); + for (int i = 0; i < ain->nr_globals; i++) { + write_global(&out, ain, &ain->globals[i]); + } + } + // GSET + if (ain->GSET.present) { + write_header(&out, "GSET"); + write_int32(&out, ain->nr_initvals); + for (int i = 0; i < ain->nr_initvals; i++) { + write_initval(&out, ain, &ain->global_initvals[i]); + } + } + // STRT + if (ain->STRT.present) { + write_header(&out, "STRT"); + write_int32(&out, ain->nr_structures); + for (int i = 0; i < ain->nr_structures; i++) { + write_structure(&out, ain, &ain->structures[i]); + } + } + // MSG0 + if (ain->MSG0.present) { + write_header(&out, "MSG0"); + write_int32(&out, ain->nr_messages); + for (int i = 0; i < ain->nr_messages; i++) { + write_bytes(&out, (uint8_t*)ain->messages[i]->text, ain->messages[i]->size+1); + } + } + // MSG1 + if (ain->MSG1.present) { + write_header(&out, "MSG1"); + write_int32(&out, ain->nr_messages); + write_int32(&out, ain->msg1_uk); + for (int i = 0; i < ain->nr_messages; i++) { + write_msg1_string(&out, ain, ain->messages[i]); + } + } + // MAIN + if (ain->MAIN.present) { + write_header(&out, "MAIN"); + write_int32(&out, ain->main); + } + // MSGF + if (ain->MSGF.present) { + write_header(&out, "MSGF"); + write_int32(&out, ain->msgf); + } + // HLL0 + if (ain->HLL0.present) { + write_header(&out, "HLL0"); + write_int32(&out, ain->nr_libraries); + for (int i = 0; i < ain->nr_libraries; i++) { + write_library(&out, ain, &ain->libraries[i]); + } + } + // SWI0 + if (ain->SWI0.present) { + write_header(&out, "SWI0"); + write_int32(&out, ain->nr_switches); + for (int i = 0; i < ain->nr_switches; i++) { + write_switch(&out, ain, &ain->switches[i]); + } + } + // GVER + if (ain->GVER.present) { + write_header(&out, "GVER"); + write_int32(&out, ain->game_version); + } + // STR0 + if (ain->STR0.present) { + write_header(&out, "STR0"); + write_int32(&out, ain->nr_strings); + for (int i = 0; i < ain->nr_strings; i++) { + write_bytes(&out, (uint8_t*)ain->strings[i]->text, ain->strings[i]->size+1); + } + } + // FNAM + if (ain->FNAM.present) { + write_header(&out, "FNAM"); + write_int32(&out, ain->nr_filenames); + for (int i = 0; i < ain->nr_filenames; i++) { + write_string(&out, ain->filenames[i]); + } + } + // OJMP + if (ain->OJMP.present) { + write_header(&out, "OJMP"); + write_int32(&out, ain->ojmp); + } + // FNCT + if (ain->FNCT.present) { + write_header(&out, "FNCT"); + write_int32(&out, ain->fnct_size); + write_int32(&out, ain->nr_function_types); + for (int i = 0; i < ain->nr_function_types; i++) { + write_function_type(&out, ain, &ain->function_types[i]); + } + } + // DELG + if (ain->DELG.present) { + write_header(&out, "DELG"); + write_int32(&out, ain->delg_size); + write_int32(&out, ain->nr_delegates); + for (int i = 0; i < ain->nr_delegates; i++) { + write_function_type(&out, ain, &ain->delegates[i]); + } + } + // OBJG + if (ain->OBJG.present) { + write_header(&out, "OBJG"); + write_int32(&out, ain->nr_global_groups); + for (int i = 0; i < ain->nr_global_groups; i++) { + write_string(&out, ain->global_group_names[i]); + } + } + // ENUM + if (ain->ENUM.present) { + write_header(&out, "ENUM"); + write_int32(&out, ain->nr_enums); + for (int i = 0; i < ain->nr_enums; i++) { + write_string(&out, ain->enums[i].name); + } + } + + *len = out.ptr; + return out.buf; +} + +static uint8_t *ain_compress(uint8_t *buf, size_t *len) +{ + unsigned long dst_len = *len * 1.001 + 12; + uint8_t *dst = xmalloc(dst_len + 16); + + memcpy(dst, "AI2\0\0\0\0", 8); + _write_int32(dst+8, *len); + + int r = compress2(dst+16, &dst_len, buf, *len, 1); + if (r != Z_OK) { + ERROR("compress failed"); + } + free(buf); + + _write_int32(dst+12, dst_len); + *len = dst_len + 16; + return dst; +} + +void ain_write(const char *filename, struct ain *ain) +{ + size_t len; + uint8_t *buf = ain_flatten(ain, &len); + + if (ain->version <= 5) + ain_decrypt(buf, len); // NOTE: this actually encrypts the buffer + else + buf = ain_compress(buf, &len); + + FILE *out = fopen(filename, "w"); + if (!out) + ERROR("Failed to open '%s': %s", filename, strerror(errno)); + if (fwrite(buf, len, 1, out) != 1) + ERROR("Failed to write to '%s': %s", filename, strerror(errno)); + if (fclose(out)) + ERROR("Failed to close '%s': %s", filename, strerror(errno)); + + free(buf); +} diff --git a/src/instructions.c b/src/instructions.c index b98c5f4..41b9307 100644 --- a/src/instructions.c +++ b/src/instructions.c @@ -69,6 +69,16 @@ const struct syscall syscalls[NR_SYSCALLS] = { // JMP = instruction that modifies the instruction pointer // OP = everything else +#define _OP(code, opname, nargs, ...) \ + [code] = { \ + .opcode = code, \ + .name = opname, \ + .nr_args = nargs, \ + .ip_inc = 2 + nargs * 4, \ + .implemented = true, \ + .args = { __VA_ARGS__ } \ + } + #define OP(code, nargs, ...) \ [code] = { \ .opcode = code, \ @@ -200,12 +210,12 @@ struct instruction instructions[NR_OPCODES] = { JMP ( SWITCH, 1, T_INT ), JMP ( STRSWITCH, 1, T_INT ), OP ( FUNC, 1, T_FUNC ), - OP ( _EOF, 1, T_FILE ), + _OP ( _EOF, "EOF", 1, T_FILE ), OP ( CALLSYS, 1, T_SYSCALL ), JMP ( SJUMP, 0 ), OP ( CALLONJUMP, 0 ), OP ( SWAP, 0 ), - OP ( SH_STRUCTREF, 1, T_INT ), + OP ( SH_STRUCTREF, 1, T_MEMB ), OP ( S_LENGTH, 0 ), OP ( S_LENGTHBYTE, 0 ), OP ( I_STRING, 0 ), @@ -220,7 +230,7 @@ struct instruction instructions[NR_OPCODES] = { OP ( S_GTE, 0 ), OP ( S_LENGTH2, 0 ), TODO ( S_LENGTHBYTE2, 0 ), - TODO ( NEW, 2, T_INT, T_INT ), + TODO ( NEW, 2, T_STRUCT, T_INT ), // FIXME: 2nd arg is T_FUNC *OR* -1 OP ( DELETE, 0 ), TODO ( CHECKUDO, 0 ), OP ( A_REF, 0 ), @@ -280,7 +290,6 @@ struct instruction instructions[NR_OPCODES] = { OP ( A_FIND, 0 ), OP ( A_REVERSE, 0 ), - // FIXME: all types are guesses TODO ( SH_SR_ASSIGN, 0 ), TODO ( SH_MEM_ASSIGN_LOCAL, 2, T_MEMB, T_LOCAL ), TODO ( A_NUMOF_GLOB_1, 1, T_GLOBAL ), @@ -364,8 +373,8 @@ struct instruction instructions[NR_OPCODES] = { TODO ( DG_NEW, 0 ), TODO ( DG_STR_TO_METHOD, 0, T_DLG ), // XXX: changed in ain version > 8 - TODO ( OP_0x102, 0 ), - TODO ( OP_0x103, 0 ), - TODO ( OP_0x104, 0 ), - TODO ( OP_0x105, 1, T_STRUCT ), + TODO ( OP_0X102, 0 ), + TODO ( OP_0X103, 0 ), + TODO ( OP_0X104, 0 ), + TODO ( OP_0X105, 1, T_STRUCT ), }; diff --git a/src/meson.build b/src/meson.build index f208283..18b6b25 100644 --- a/src/meson.build +++ b/src/meson.build @@ -46,12 +46,8 @@ xsystem4 = ['audio.c', 'hll/SystemServiceEx.c', ] -# sources for aindump -aindump = ['cJSON.c', - 'aindump/aindump.c', - 'aindump/dasm.c', - 'aindump/json.c', -] +flex = find_program('flex', required: false) +bison = find_program('bison', required: false) xsystem4_deps = [libm, zlib, sdl2, sdl2ttf, sdl2mixer, ffi, gl, glew] if chibi.found() @@ -70,7 +66,5 @@ executable('xsystem4', xsystem4, include_directories : incdir, link_with : libsys4) -executable('aindump', aindump, - dependencies : [libm, zlib], - include_directories : incdir, - link_with : libsys4) +subdir('aindump') +subdir('ainedit')