Minimizes memory footprint of id-tree search

pull/1/head
venko 2021-05-07 14:07:57 -07:00
parent 565d815deb
commit 71ba1f9454
2 changed files with 16 additions and 23 deletions

View File

@ -163,26 +163,31 @@ IdNode* FindId(IdNode *root, NodeType targetType, char *targetName) {
IdNode **frontier = (IdNode**)malloc(sizeof(IdNode*)); IdNode **frontier = (IdNode**)malloc(sizeof(IdNode*));
frontier[0] = root; frontier[0] = root;
uint32_t frontierCount = 1; uint32_t frontierCount = 1;
uint32_t cursor = 0;
while (frontierCount > 0 && cursor < frontierCount) { while (frontierCount > 0) {
IdNode *current = frontier[cursor]; IdNode *current = frontier[0];
if (current->type == targetType && strcmp(current->name, targetName) == 0) { if (current->type == targetType && strcmp(current->name, targetName) == 0) {
result = current; result = current;
break; break;
} }
int newSize = frontierCount + current->childCount;
frontier = realloc(frontier, sizeof(IdNode*) * newSize);
uint32_t i; uint32_t i;
for (i = 0; i < current->childCount; i++) { for(i = 1; i < frontierCount; i++) {
frontier[frontierCount + i] = current->children[i]; frontier[i-1] = frontier[i];
} }
frontierCount += current->childCount;
cursor += 1; size_t newSize = frontierCount + current->childCount - 1;
if (frontierCount != newSize) {
frontier = realloc(frontier, sizeof(IdNode*) * newSize);
}
for (i = 0; i < current->childCount; i++) {
frontier[frontierCount + i - 1] = current->children[i];
}
frontierCount = newSize;
} }
free(frontier); free(frontier);
return result; return result;
} }

View File

@ -65,21 +65,9 @@ int main(int argc, char *argv[])
} }
else else
{ {
{ if (parseVerbose) {
IdNode *idTree = MakeIdTree(rootNode, NULL); IdNode *idTree = MakeIdTree(rootNode, NULL);
PrintIdTree(idTree, /*tabCount=*/0); PrintIdTree(idTree, /*tabCount=*/0);
printf("\n");
printf("Searching for a variable named 'lol' and printing its ancestors\n");
IdNode *deepest = FindId(idTree, Variable, "lol");
PrintAncestors(deepest);
printf("\n");
printf("Now searching for the same variable but with the caveat that it"
" must be inside an if-block, and printing its ancestors\n");
deepest = FindId(idTree, LexicalScope, "if");
deepest = FindId(deepest, Variable, "lol");
PrintAncestors(deepest);
} }
exitCode = Codegen(rootNode, optimizationLevel); exitCode = Codegen(rootNode, optimizationLevel);
} }