| 54 | } why_cache_t; |
| 55 | |
| 56 | static why_file_t *why_file_get(why_cache_t *cache, const char *file_path) { |
| 57 | for (int i = 0; i < cache->count; i++) |
| 58 | if (strcmp(cache->files[i].file_path, file_path) == 0) |
| 59 | return cache->files[i].source ? &cache->files[i] : NULL; |
| 60 | if (cache->count >= WHY_MAX_FILES) |
| 61 | return NULL; |
| 62 | why_file_t *slot = &cache->files[cache->count++]; |
| 63 | slot->file_path = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, file_path); |
| 64 | if (!slot->file_path) |
| 65 | return NULL; |
| 66 | |
| 67 | char full[CBM_SZ_2K]; |
| 68 | snprintf(full, sizeof(full), "%s/%s", cache->root_path, file_path); |
| 69 | FILE *fp = cbm_fopen(full, "rb"); |
| 70 | if (!fp) |
| 71 | return NULL; /* slot stays as a negative cache entry */ |
| 72 | fseek(fp, 0, SEEK_END); |
| 73 | long size = ftell(fp); |
| 74 | fseek(fp, 0, SEEK_SET); |
| 75 | if (size <= 0 || size > WHY_MAX_SOURCE) { |
| 76 | fclose(fp); |
| 77 | return NULL; |
| 78 | } |
| 79 | char *source = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)size + 1); |
| 80 | if (!source) { |
| 81 | fclose(fp); |
| 82 | return NULL; |
| 83 | } |
| 84 | size_t got = fread(source, 1, (size_t)size, fp); |
| 85 | fclose(fp); |
| 86 | source[got] = '\0'; |
| 87 | |
| 88 | const char *dot = strrchr(file_path, '.'); |
| 89 | CBMLanguage lang = cbm_language_for_extension(dot ? dot : ""); |
| 90 | if (lang == CBM_LANG_COUNT) { |
| 91 | cbm_free(CBM_MEM_CLASS_OTHER, source); |
| 92 | return NULL; |
| 93 | } |
| 94 | CBMFileResult *result = cbm_extract_file(source, (int)got, lang, cache->project, file_path, |
| 95 | WHY_PARSE_TIMEOUT_US, NULL, NULL); |
| 96 | if (!result || !result->cached_tree) { |
| 97 | if (result) |
| 98 | cbm_free_result(result); |
| 99 | cbm_free(CBM_MEM_CLASS_OTHER, source); |
| 100 | return NULL; |
| 101 | } |
| 102 | slot->source = source; |
| 103 | slot->source_len = (int)got; |
| 104 | slot->result = result; |
| 105 | return slot; |
| 106 | } |
| 107 | |
| 108 | static void why_cache_free(why_cache_t *cache) { |
| 109 | for (int i = 0; i < cache->count; i++) { |
no test coverage detected