code_analyzer/cparse.c
2021-12-18 16:12:32 +01:00

101 lines
3.0 KiB
C

#include "vec.h"
#include <errno.h>
#include <regex.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int find_funcs(const char *path)
{
FILE *fp;
regex_t fdre, fcre;
int ret;
char line[1024];
char boum[1024];
regmatch_t rm[2];
const char *re_func_decl = "^(\\w+(\\s+)?\\**){2,}\\([^!@#$+%^]+?\\)\\s+";
const char *re_func_call = "([a-zA-Z_0-9]+)\\(.*\\)";
fp = fopen(path, "r");
if (fp == 0) {
fprintf(stderr, "Failed to open file %s (%d: %s)\n", path, errno, strerror(errno));
return EXIT_FAILURE;
}
ret = regcomp(&fdre, re_func_decl, REG_EXTENDED);
if (ret != 0) {
fprintf(stderr, "Failed to compile regex '%s'\n", re_func_decl);
return EXIT_FAILURE;
}
ret = regcomp(&fcre, re_func_call, REG_EXTENDED);
if (ret != 0) {
fprintf(stderr, "Failed to compile regex '%s'\n", re_func_call);
return EXIT_FAILURE;
}
bool in = false;
graph_vec g = new_graph(10);
int index;
int cur_node;
while ((fgets(line, 1024, fp)) != NULL) {
if (in && line[0] == '}') {
in = false;
}
if (in) {
if (regexec(&fcre, line, 2, rm, 0) == 0) {
// printf("Line: <<%.*s>>\n", (int)(rm[0].rm_eo - rm[0].rm_so), line + rm[0].rm_so);
sprintf(boum, "%.*s", (int)(rm[1].rm_eo - rm[1].rm_so), line + rm[1].rm_so);
// printf("%.*s\n", (int)(rm[1].rm_eo - rm[1].rm_so), line + rm[1].rm_so);
if ((index = is_in(g, boum))) {
if (g.node[cur_node]->nbs == g.node[cur_node]->cap)
g.node[cur_node]->succ = reallocarray(g.node[cur_node]->succ, (g.node[cur_node]->cap += 5), sizeof(nodept));
g.node[cur_node]->succ[g.node[cur_node]->nbs] = g.node[index];
g.node[cur_node]->nbs++;
} else {
insert_node(&g, boum);
if (g.node[cur_node]->nbs == g.node[cur_node]->cap)
g.node[cur_node]->succ = reallocarray(g.node[cur_node]->succ, (g.node[cur_node]->cap += 5), sizeof(nodept));
g.node[cur_node]->succ[g.node[cur_node]->nbs] = g.node[g.n];
g.node[cur_node]->nbs++;
}
}
} else if (regexec(&fdre, line, 2, rm, 0) == 0) { // function definition
sprintf(boum, "%.*s", (int)(rm[1].rm_eo - rm[1].rm_so), line + rm[1].rm_so);
if ((index = is_in(g, boum))) {
cur_node = index;
} else {
insert_node(&g, boum);
cur_node = g.n;
}
// if (strcmp(boum, "ml_new_data") == 0)
// printf("%d\n", cur_node);
in = true;
}
}
// for (int j = 0; j < g.n; j++) {
// printf("NODE %d: %s\n", j, g.node[j]->func);
// }
// print_node(g.node[0]);
dot_graph(g.node[0]);
// int test = is_in(g, "ml_new_data");
// printf("%s\n", g.node[14]->func);
// printf("%d\n", g.node[14]->nbs);
regfree(&fdre);
regfree(&fcre);
fclose(fp);
delete_graph(&g);
return 0;
}
int main(int argc, char *argv[])
{
find_funcs("./memline.c");
// graph_vec g = new_graph(3);
// insert_node(&g, new_node(0), "main");
// insert_node(&g, new_node(1), "main1");
// insert_node(&g, new_node(2), "main2");
// printf("%d %d %d\n", g.node[0]->num,g.node[1]->num,g.node[2]->num);
// printf("%s %s %s\n", g.func[0],g.func[1],g.func[2]);
// delete_graph(&g);
return 0;
}