Skip to content

Commit

Permalink
Merge pull request #53 from cbrune/curt/reduce-imports
Browse files Browse the repository at this point in the history
  • Loading branch information
eqvinox authored Apr 23, 2023
2 parents 0653675 + 1772643 commit 5c4e497
Showing 1 changed file with 37 additions and 1 deletion.
38 changes: 37 additions & 1 deletion compiler/capnpc-c.c
Original file line number Diff line number Diff line change
Expand Up @@ -1308,8 +1308,9 @@ int main() {
struct capn capn;
CodeGeneratorRequest_ptr root;
struct CodeGeneratorRequest req;
struct node *file_node, *n;
struct node *file_node, *n, *f;
struct node *all_files = NULL, *all_structs = NULL;
struct id_bst *used_import_ids = NULL;
int i, j;

if (capn_init_fp(&capn, stdin, 0)) {
Expand Down Expand Up @@ -1392,6 +1393,35 @@ int main() {
str_release(&b);
}

/* find all the used imports */
for (n = all_structs; n != NULL; n = n->next) {
char *display_name = strdup(n->n.displayName.str);
char *file_name = strtok(display_name, ":");

if (!file_name) {
fprintf(stderr, "Unable to determine file name for struct node: %s\n",
n->n.displayName.str);
exit(2);
}

/* find the file node corresponding to the file name */
for (f = all_files; f != NULL; f = f->next) {
if (!strcmp(file_name, f->n.displayName.str))
break;
}

if (!f) {
fprintf(stderr, "Unable to find file node with file name: %s\n", file_name);
exit(2);
}

/* mark this import as used */
if (!contains_id(used_import_ids, f->n.id))
used_import_ids = insert_id(used_import_ids, f->n.id);

free(display_name);
}

for (i = 0; i < capn_len(req.requestedFiles); i++) {
struct CodeGeneratorRequest_RequestedFile file_req;
static struct str b = STR_INIT;
Expand Down Expand Up @@ -1476,12 +1506,18 @@ int main() {
continue;
}

// Check if this import is used at all.
if (!contains_id(used_import_ids, im.id)) {
continue;
}

// Ignore leading slashes when generating C file #include's.
// This signifies an absolute import in a library directory.
const char *base_path = im.name.str[0] == '/' ? &im.name.str[1] : im.name.str;
str_addf(&HDR, "#include \"%s%s.h\"\n", base_path, nameinfix);
}

free_id_bst(used_import_ids);
free_id_bst(donotinclude_ids);

str_addf(&HDR, "\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
Expand Down

0 comments on commit 5c4e497

Please sign in to comment.