summaryrefslogtreecommitdiffhomepage
path: root/tools/example-indexer/main.c
blob: f912c80050baed3c20e8d963c51c7c8e2c7e4919 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/param.h>
#include <dirent.h>
#include <string.h>
#include <assert.h>

#include "stb_c_lexer.h"
#include "raylib_parser.c"

#define MAX_FUNCS_TO_PARSE    1024 // Maximum number of functions to parse
#define MAX_FUNCS_PER_EXAMPLE 1024 // Maximum number of usages per function per file

typedef struct {
    char filename[256];
    // TODO: Track where function usage was found and display it?
} FunctionUsage;

typedef struct {
    int from, to; // [from, to) - from inclusive, to exclusive
} LineRange;

static bool StartsWith(char *text, int textSize, char *prefix, int prefixSize)
{
    return textSize >= prefixSize && !strncmp(text, prefix, prefixSize);
}

static bool EndsSith(char *text, int textSize, char *suffix, int suffixSize)
{
    return textSize >= suffixSize && !strncmp(text+textSize-suffixSize, suffix, suffixSize);
}

static bool GetNextLine(LineRange *line, char *text, int textSize, int from)
{
    for (int i = from; i < textSize; i++) {
        if (text[i] == '\n') {
            line->from = from;
            line->to = i;
            return true;
        }
    }
    return false;
}

static int GetFunctionFromIdentifier(char *id, FunctionInfo *functions, int functionCount)
{
    int idSize = strlen(id);

    for (int i = 0; i < functionCount; i++) {
        FunctionInfo *function = &functions[i];
        if (idSize > sizeof(function->name)) continue;
        if (!strcmp(id, function->name)) {
            return i;
        }
    }
    return -1;
}

static bool ParseFunctionUsagesFromFile(char *directory, char *filePath, FunctionUsage *usages[], int *usageCounts, FunctionInfo *functions, int functionCount)
{
    char fullPath[PATH_MAX] = { 0 };
    snprintf(fullPath, sizeof(fullPath), "%s/%s", directory, filePath);

    int fileSize = 0;
    char *exampleCode = LoadFileText(fullPath, &fileSize);
    if (exampleCode == NULL) {
        return false;
    }

    stb_lexer lexer;
    char stringStore[512];
    stb_c_lexer_init(&lexer, exampleCode, exampleCode+fileSize, stringStore, sizeof(stringStore));

    while (stb_c_lexer_get_token(&lexer)) {
        if (lexer.token != CLEX_id) continue;

        int functionIndex = GetFunctionFromIdentifier(lexer.string, functions, functionCount);
        if (functionIndex != -1) {
            int *usageCount = &usageCounts[functionIndex];
            assert(*usageCount < MAX_FUNCS_PER_EXAMPLE);
            FunctionUsage *usage = &usages[functionIndex][*usageCount];
            strncpy(usage->filename, filePath, strlen(filePath));
            (*usageCount)++;
        }
    }

    free(exampleCode);

    return true;
}

static void ParseFunctionsUsagesFromFolder(char *cwd, char *dir, FunctionUsage *usages[], int *usageCounts, FunctionInfo *functions, int functionCount)
{
    char dirPath[PATH_MAX];
    snprintf(dirPath, sizeof(dirPath), "%s/%s", cwd, dir);
    DIR *dirp = opendir(dirPath);
    if (dirp == NULL) {
        fprintf(stderr, "Failed to open directory '%s'\n", dirPath);
        return;
    }

    struct dirent *entry;
    while ((entry = readdir(dirp)) != NULL) {
        if (entry->d_type != DT_REG) continue;

        char *extension = strrchr(entry->d_name, '.');
        if (!strcmp(extension, ".c")) {
            char filePath[PATH_MAX];
            snprintf(filePath, sizeof(filePath), "%s/%s", dir, entry->d_name);
            ParseFunctionUsagesFromFile(cwd, filePath, usages, usageCounts, functions, functionCount);
        }
    }

    closedir(dirp);
}

// Checks if the line is in the format "#if defined(*_IMPLEMENTATION)"
static bool IsLineImplementationIfdef(char *line, int line_size) {
    char *prefix = "#if defined(";
    char *suffix = "_IMPLEMENTATION)";
    return StartsWith(line, line_size, prefix, strlen(prefix)) &&
            EndsSith(line, line_size, suffix, strlen(suffix));
}

static int ParseFunctionsDefinitionsFromHeader(char *path, FunctionInfo *functions, int maxFunctions)
{
    int fileSize;
    char *contents = LoadFileText(path, &fileSize);

    int count = 0;

    int nextLineFrom = 0;
    LineRange curr = { 0 };
    while (GetNextLine(&curr, contents, fileSize, nextLineFrom)) {
        int lineSize = curr.to - curr.from;
        char line[512] = { 0 };
        strncpy(line, &contents[curr.from], lineSize); // `raylib_parser.c` expects lines to be null-terminated
        if (IsLineImplementationIfdef(line, lineSize)) break;

        if (IsLineAPIFunction(line, lineSize)) {
            ParseAPIFunctionInfo(line, lineSize, &functions[count]);
            count++;
            if (count == maxFunctions) break;
        }

        nextLineFrom = curr.to+1;
    }

    free(contents);

    return count;
}

static int ParseFunctionsDefinitionsFromFolder(char *dir, FunctionInfo *functions, int maxFunctions)
{
    DIR *dirp = opendir(dir);
    if (dirp == NULL) {
        fprintf(stderr, "Failed to open directory '%s'\n", dir);
        return -1;
    }

    int count = 0;
    struct dirent *entry;
    while ((entry = readdir(dirp)) != NULL) {
        if (entry->d_type != DT_REG) continue;

        char *fileExtension = strrchr(entry->d_name, '.');
        if (fileExtension == NULL) continue;
        if (strcmp(fileExtension, ".h")) continue;

        char path[256];
        snprintf(path, sizeof(path), "%s/%s", dir, entry->d_name);
        count += ParseFunctionsDefinitionsFromHeader(path, functions + count, maxFunctions - count);
    }
    closedir(dirp);

    return count;
}

static int GetUniqueFilenames(FunctionUsage *usages, int usageCount, char *uniqueFilenames[])
{
    int count = 0;

    for (int i = 0; i < usageCount; i++) {
        FunctionUsage *usage = &usages[i];

        bool found = false;
        for (int j = 0; j < count; j++) {
            if (!strcmp(uniqueFilenames[j], usage->filename)) {
                found = true;
                break;
            }
        }

        if (!found) {
            uniqueFilenames[count] = strdup(usage->filename);
            count++;
        }
    }

    return count;
}

static int OutputFunctionUsagesJSON(char *output, FunctionInfo *functions, int functionCount, FunctionUsage **usages, int *usageCounts)
{
    FILE *outputFile = fopen(output, "w");
    if (outputFile == NULL) {
        fprintf(stderr, "Failed to open file '%s\n'", output);
        return -1;
    }

    fwrite("{", sizeof(char), 1, outputFile);
    for (int functionIndex = 0; functionIndex < functionCount; functionIndex++) {
        FunctionInfo *info = &functions[functionIndex];

        fwrite("\"", sizeof(char), 1, outputFile);
        fwrite(info->name, sizeof(char), strlen(info->name), outputFile);
        fwrite("\":[", sizeof(char), 3, outputFile);

        int usageCount = usageCounts[functionIndex];
        if (usageCount > 0) {
            char *uniqueFilenames[usageCount];
            int uniqueCount = GetUniqueFilenames(usages[functionIndex], usageCount, uniqueFilenames);

            for (int i = 0; i < uniqueCount; i++) {
                char *filename = uniqueFilenames[i];
                char *example_name = strchr(filename, '/')+1;
                int example_name_size = strchr(filename, '.') - example_name;

                fwrite("\"", sizeof(char), 1, outputFile);
                fwrite(example_name, sizeof(char), example_name_size, outputFile);
                fwrite("\"", sizeof(char), 1, outputFile);
                if (i < uniqueCount-1) {
                    fwrite(",", sizeof(char), 1, outputFile);
                }
            }

            for (int i = 0; i < uniqueCount; i++) {
                free(uniqueFilenames[i]);
            }
        }

        fwrite("]", sizeof(char), 1, outputFile);
        if (functionIndex < functionCount-1) {
            fwrite(",", sizeof(char), 1, outputFile);
        }
    }

    fwrite("}", sizeof(char), 1, outputFile);
    fclose(outputFile);

    return 0;
}

int main(int argc, char **argv)
{
    if (argc != 4) {
        printf("Usage: %s <raylib-src-dir> <examples-dir> <output-file>\n", argv[0]);
        return -1;
    }

    char *raylibSrc = argv[1];
    char *raylibExamplesPath = argv[2];
    char *outputPath = argv[3];

    FunctionInfo functions[MAX_FUNCS_TO_PARSE];
    int functionCount = ParseFunctionsDefinitionsFromFolder(raylibSrc, functions, MAX_FUNCS_TO_PARSE);
    if (functionCount < 0) {
        return -1;
    }

    FunctionUsage *usages[MAX_FUNCS_TO_PARSE] = { 0 };
    for (int i = 0; i < functionCount; i++) {
        usages[i] = malloc(MAX_FUNCS_PER_EXAMPLE * sizeof(FunctionUsage));
    }
    int usageCounts[MAX_FUNCS_TO_PARSE] = { 0 };

    { // Collect function usages from examples
        DIR *dirp = opendir(raylibExamplesPath);
        if (dirp == NULL) {
            fprintf(stderr, "Failed to open directory '%s'\n", raylibExamplesPath);
            return -1;
        }
        struct dirent *entry;
        while ((entry = readdir(dirp)) != NULL) {
            if (entry->d_type != DT_DIR) continue;
            if (entry->d_name[0] == '.') continue;

            ParseFunctionsUsagesFromFolder(raylibExamplesPath, entry->d_name, usages, usageCounts, functions, functionCount);
        }
        closedir(dirp);
    }

    // Output function usages
    OutputFunctionUsagesJSON(outputPath, functions, functionCount, usages, usageCounts);

    for (int i = 0; i < functionCount; i++) {
        free(usages[i]);
    }

    return 0;
}