Repository navigation
Expand file tree
/
Copy pathaether_module.c
More file actions
5851 lines (5437 loc) · 268 KB
/
Copy pathaether_module.c
File metadata and controls
5851 lines (5437 loc) · 268 KB
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "aether_module.h"
#include "codegen/optimizer.h" // resolve_when_statements (#2275)
#include "aether_error.h"
#include "aether_strmap.h"
#include "aether_aea.h"
#include "aether_defines.h"
#include "parser/lexer.h"
#include "parser/parser.h"
#include "analysis/typechecker.h"
#include "analysis/sandbox_trust.h" // module_sweep_unreachable (#2613)
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#ifdef _WIN32
#include <io.h>
#include <windows.h>
#include <direct.h> // _getcwd, for the unresolved-import message (#3181)
#define access _access
#define F_OK 0
#else
#include <unistd.h>
#include <sys/stat.h>
#endif
#include <dirent.h>
#ifdef __FreeBSD__
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
ModuleRegistry* global_module_registry = NULL;
/* --- Dependency recording (#1882) -------------------------------------------
* A build launched with --emit-deps records, in first-seen order, every path
* the resolver probed (found or absent) and every file it parsed. Deduped by
* exact path. Kept deliberately simple — a build resolves a few dozen paths,
* not thousands, so a linear-scan dedupe over a growable array is ample. */
typedef struct { char* path; int found; int is_read; } DepEntry;
static DepEntry* g_deps = NULL;
static int g_dep_count = 0, g_dep_cap = 0;
static int g_dep_recording = 0;
/* Set when a path could not be recorded (out of memory). The manifest is
* then incomplete, and a key built from it would not change when the
* missing file does, so module_dep_write writes none (#2537). */
static int g_dep_incomplete = 0;
void module_dep_recording_enable(void) { g_dep_recording = 1; }
static DepEntry* dep_find(const char* path) {
for (int i = 0; i < g_dep_count; i++)
if (strcmp(g_deps[i].path, path) == 0) return &g_deps[i];
return NULL;
}
/* Record one path. `found` = the probe saw it on disk; `is_read` = its CONTENTS
* were read (a parsed module file), which the manifest content-hashes. A path
* can be upgraded absent->found and probe->read as more is learned about it. */
static void dep_record(const char* path, int found, int is_read) {
if (!g_dep_recording || !path || !path[0]) return;
DepEntry* e = dep_find(path);
if (e) {
if (found) e->found = 1;
if (is_read) e->is_read = 1;
return;
}
/* A dropped entry under-invalidates: an edit to a file the manifest does
* not name leaves the key as it was. So a failure here poisons the whole
* manifest rather than losing one line of it. */
if (g_dep_count == g_dep_cap) {
int ncap = g_dep_cap ? g_dep_cap * 2 : 32;
DepEntry* nd = realloc(g_deps, (size_t)ncap * sizeof(DepEntry));
if (!nd) { g_dep_incomplete = 1; return; }
g_deps = nd; g_dep_cap = ncap;
}
char* copy = strdup(path);
if (!copy) { g_dep_incomplete = 1; return; }
g_deps[g_dep_count].path = copy;
g_deps[g_dep_count].found = found;
g_deps[g_dep_count].is_read = is_read;
g_dep_count++;
}
int module_probe(const char* path) {
int found = (access(path, F_OK) == 0);
dep_record(path, found, 0);
return found;
}
void module_dep_record_read(const char* path) { dep_record(path, 1, 1); }
/* On any failure (an incomplete recording, a file that cannot be opened or
* written in full) there is no manifest at `out_path` afterwards, not even
* the previous build's: ae then keys on the source tree. A partial or stale
* manifest would name fewer files than the build read, and an edit to one
* it leaves out would be served from the cache (#2537). */
int module_dep_write(const char* out_path) {
if (g_dep_incomplete) {
remove(out_path);
return 1;
}
FILE* f = fopen(out_path, "w");
if (!f) {
remove(out_path);
return 1;
}
/* v1 header lets the reader reject a format it doesn't understand and fall
* back to the tree hash rather than trust a stale/foreign layout. */
fprintf(f, "# aether-deps v1\n");
for (int i = 0; i < g_dep_count; i++) {
if (g_deps[i].is_read) fprintf(f, "read %s\n", g_deps[i].path);
else if (!g_deps[i].found) fprintf(f, "absent %s\n", g_deps[i].path);
/* a probed-and-found path that was never parsed (e.g. a directory
* existence check) is neither read nor absent — its presence is
* captured by the sibling `absent` lines it would flip, so it needs
* no line of its own. */
}
int failed = ferror(f) != 0;
if (fclose(f) != 0) failed = 1;
if (failed) {
remove(out_path);
return 1;
}
return 0;
}
char* module_resolve_source_directive(ASTNode* c) {
const char* rel = c->value;
int absolute = rel[0] == '/' || rel[0] == '\\' ||
(((rel[0] >= 'A' && rel[0] <= 'Z') || (rel[0] >= 'a' && rel[0] <= 'z')) &&
rel[1] == ':');
const char* file = c->source_file;
if (absolute || !file) return strdup(rel);
const char* cut = NULL;
for (const char* p = file; *p; p++)
if (*p == '/' || *p == '\\') cut = p;
if (!cut) return strdup(rel);
size_t dlen = (size_t)(cut - file);
char* out = (char*)malloc(dlen + 1 + strlen(rel) + 1);
if (!out) return NULL;
memcpy(out, file, dlen);
out[dlen] = '/';
strcpy(out + dlen + 1, rel);
return out;
}
int module_check_source_directives(ASTNode* ast) {
int ok = 1;
for (int i = 0; ast && i < ast->child_count; i++) {
ASTNode* c = ast->children[i];
if (c && c->type == AST_C_INCLUDE_DIRECTIVE && c->value) {
/* #2560: a header the generated C includes is read by the C
* compiler, not by aetherc, so the dependency manifest has to
* name it or an edit to it leaves ae's build key unchanged and
* the cache serves the old object. The copy beside the module,
* the directory first on the include path (emit_c_include_dirs),
* is recorded as read; its absence is recorded too, so a header
* put there later changes the key. One found elsewhere on the
* include path (a system or SDK header) is not followed. */
char* path = module_resolve_source_directive(c);
if (path && module_probe(path)) module_dep_record_read(path);
free(path);
continue;
}
if (!c || c->type != AST_SOURCE_DIRECTIVE || !c->value) continue;
char* path = module_resolve_source_directive(c);
if (!path) continue;
if (access(path, F_OK) != 0) {
char msg[1200];
snprintf(msg, sizeof(msg),
"@source(\"%s\"): no such file (looked for %s, relative to the "
"directory of the file that names it)", c->value, path);
AetherError e = { c->source_file, NULL, c->line, c->column, msg,
"the path is relative to the module's own directory; "
"put the C file beside module.ae or fix the name",
NULL, AETHER_ERR_SYNTAX };
aether_error_report(&e);
ok = 0;
} else {
module_dep_record_read(path);
}
free(path);
}
return ok;
}
void module_set_source_dir(const char* source_path) {
module_registry_init();
/* The directory part of the path, whole (#2543): a 2048-byte copy cut
* a longer one, and the modules beside the file were not found. Strip
* the filename, keeping the trailing slash; "" when there is no
* directory component. */
size_t len = 0;
if (source_path) {
for (size_t i = 0; source_path[i]; i++) {
if (source_path[i] == '/' || source_path[i] == '\\') len = i + 1;
}
}
char* dir = (char*)malloc(len + 1);
if (!dir) {
fprintf(stderr, "aetherc: out of memory recording the source directory\n");
exit(1);
}
if (len) memcpy(dir, source_path, len);
dir[len] = '\0';
free(global_module_registry->source_dir);
global_module_registry->source_dir = dir;
}
void module_add_lib_dir(const char* dir) {
module_registry_init();
if (!dir || !dir[0]) return;
/* Normalise: strip trailing slash so `--lib ./lib/` and
* `--lib ./lib` resolve to the same entry (dedup catches them)
* AND the joined lookup path stays clean (`<entry>/<mod>.ae`
* rather than `./lib//<mod>.ae`). Root paths ("/" on POSIX,
* "C:\" on Windows) are preserved — stripping their slash
* would change semantics. ALSO translate MSYS2 POSIX-form
* (`/d/foo`) to native Windows (`D:/foo`) so a `;`-joined
* path-list reaches us in the same shape as a sequence of
* separate `--lib` flags. Both are aether_lib_path_normalize's,
* which keeps the whole path (#2539). */
char* norm = aether_lib_path_normalize(dir);
if (!norm) {
fprintf(stderr, "aetherc: out of memory adding the --lib directory '%s'\n", dir);
exit(1);
}
/* Skip duplicates so repeated `--lib /same/dir` doesn't waste
* search slots. O(N) check over a fixed cap-of-8 list — trivial. */
for (int i = 0; i < global_module_registry->lib_dir_count; i++) {
if (strcmp(global_module_registry->lib_dirs[i], norm) == 0) { free(norm); return; }
}
if (global_module_registry->lib_dir_count >= AETHER_LIB_DIRS_MAX) {
fprintf(stderr,
"warning: --lib search path is full (max %d entries); "
"ignoring '%s'\n", AETHER_LIB_DIRS_MAX, norm);
free(norm);
return;
}
global_module_registry->lib_dirs[global_module_registry->lib_dir_count++] = norm;
}
void module_add_lib_dirs(const char* spec) {
if (!spec || !spec[0]) return;
module_registry_init();
/* Split on the platform path separator. Each segment is
* appended via module_add_lib_dir, which normalises, dedupes,
* and enforces the cap. Empty segments (e.g. trailing `:`,
* double `::`) are silently skipped — matches Java -cp and
* PATH semantics. Single source of truth for separator
* parsing — both `module_set_lib_dir` and aetherc's repeated
* `--lib` handler route through here. */
const char* cur = spec;
while (*cur) {
const char* next = strchr(cur, AETHER_LIB_PATH_SEP_CHAR);
size_t len = next ? (size_t)(next - cur) : strlen(cur);
if (len > 0) {
char* seg = (char*)malloc(len + 1);
if (!seg) {
fprintf(stderr, "aetherc: out of memory reading the --lib path\n");
exit(1);
}
memcpy(seg, cur, len);
seg[len] = '\0';
module_add_lib_dir(seg);
free(seg);
}
if (!next) break;
cur = next + 1;
}
}
static void module_clear_lib_dirs(void) {
for (int i = 0; i < global_module_registry->lib_dir_count; i++)
free(global_module_registry->lib_dirs[i]);
global_module_registry->lib_dir_count = 0;
}
void module_set_lib_dir(const char* lib_dir) {
module_registry_init();
if (!lib_dir || !lib_dir[0]) return;
/* RESET — a fresh `--lib <path>` (or `AETHER_LIB_DIR=<path>`)
* replaces, doesn't append. The append-form is
* `module_add_lib_dirs`. */
module_clear_lib_dirs();
module_add_lib_dirs(lib_dir);
/* Defensive: an entirely-empty path (all separators, no
* segments) should fall back to the default so the toolchain
* still finds stdlib modules. */
if (global_module_registry->lib_dir_count == 0) {
module_add_lib_dir(AETHER_DEFAULT_LIB_DIR);
}
}
// Module management
void module_registry_init(void) {
if (!global_module_registry) {
global_module_registry = (ModuleRegistry*)malloc(sizeof(ModuleRegistry));
global_module_registry->modules = NULL;
global_module_registry->module_count = 0;
global_module_registry->module_capacity = 0;
global_module_registry->source_dir = NULL;
/* #3181: the entry program's imports are resolved first, so this
* starts at 0. It was left as malloc gave it: where that was not
* zero, the entry program's imports looked beside it before the
* project's lib/ (the order #3103 keeps for a module's own), and a
* missing one was reported as "beside this module". */
global_module_registry->source_is_module = 0;
global_module_registry->lib_dir_count = 0;
const char* env_lib = getenv("AETHER_LIB_DIR");
if (env_lib && env_lib[0]) {
/* Reuse module_set_lib_dir's parser so the env var
* accepts the same separator-string form as --lib.
* Issue #413. */
module_set_lib_dir(env_lib);
} else {
module_add_lib_dir(AETHER_DEFAULT_LIB_DIR);
}
}
}
static void module_sees_reset(void);
static void module_unreachable_reset(void);
void module_registry_shutdown(void) {
module_sees_reset();
module_unreachable_reset();
if (global_module_registry) {
for (int i = 0; i < global_module_registry->module_count; i++) {
module_free(global_module_registry->modules[i]);
}
free(global_module_registry->modules);
module_clear_lib_dirs();
free(global_module_registry->source_dir);
free(global_module_registry);
global_module_registry = NULL;
}
}
AetherModule* module_create(const char* name, const char* file_path) {
AetherModule* module = (AetherModule*)malloc(sizeof(AetherModule));
module->name = strdup(name);
module->file_path = strdup(file_path);
module->ast = NULL;
module->exports = NULL;
module->export_count = 0;
module->imports = NULL;
module->import_count = 0;
module->ns = NULL;
module->lane_target = NULL;
return module;
}
void module_free(AetherModule* module) {
if (!module) return;
free(module->name);
free(module->file_path);
free(module->ns);
free(module->lane_target);
if (module->ast) {
free_ast_node(module->ast);
}
for (int i = 0; i < module->export_count; i++) {
free(module->exports[i]);
}
free(module->exports);
for (int i = 0; i < module->import_count; i++) {
free(module->imports[i]);
}
free(module->imports);
free(module);
}
// Module registration
void module_register(AetherModule* module) {
if (!global_module_registry) {
module_registry_init();
}
// Check if module already exists
for (int i = 0; i < global_module_registry->module_count; i++) {
if (strcmp(global_module_registry->modules[i]->name, module->name) == 0) {
fprintf(stderr, "Warning: Module '%s' already registered, replacing\n", module->name);
module_free(global_module_registry->modules[i]);
global_module_registry->modules[i] = module;
return;
}
}
// Grow array if needed
if (global_module_registry->module_count >= global_module_registry->module_capacity) {
int new_capacity = global_module_registry->module_capacity == 0 ? 8 : global_module_registry->module_capacity * 2;
AetherModule** new_modules = (AetherModule**)aether_xrealloc(
global_module_registry->modules,
new_capacity * sizeof(AetherModule*)
);
if (!new_modules) return;
global_module_registry->modules = new_modules;
global_module_registry->module_capacity = new_capacity;
}
global_module_registry->modules[global_module_registry->module_count++] = module;
}
AetherModule* module_find(const char* name) {
if (!global_module_registry) return NULL;
for (int i = 0; i < global_module_registry->module_count; i++) {
if (strcmp(global_module_registry->modules[i]->name, name) == 0) {
return global_module_registry->modules[i];
}
}
return NULL;
}
static const char* module_last_segment(const char* path); /* defined below */
static ASTNode* unwrap_export(ASTNode* node); /* defined below */
static int module_is_shipped(const char* name) {
return name && (strncmp(name, "std.", 4) == 0 || strncmp(name, "contrib.", 8) == 0);
}
/* #2190 / #2255: does this module need its last segment as its namespace?
* A module whose externs carry that segment as a prefix does: std.math
* declares `extern math_floor`, and `math.floor` reaches it as
* `<ns>_floor`, so under a namespace of `std_math` the call would look
* for `std_math_floor` and find nothing. A module without such externs
* (all its functions are Aether, renamed along with the namespace) can
* take its full path like any other. Without an AST to inspect, a shipped
* module is assumed to need its leaf and a local one not to. */
static int module_pins_leaf(AetherModule* m) {
if (!m || !m->name) return 0;
if (!m->ast) return module_is_shipped(m->name);
const char* leaf = module_last_segment(m->name);
size_t n = strlen(leaf);
for (int i = 0; i < m->ast->child_count; i++) {
ASTNode* decl = unwrap_export(m->ast->children[i]);
if (decl && decl->type == AST_EXTERN_FUNCTION && decl->value &&
strncmp(decl->value, leaf, n) == 0 && decl->value[n] == '_') {
return 1;
}
}
return 0;
}
/* #2209: two modules whose paths end in the same segment (`mine.vk` and
* `contrib.vulkan.vk`) used to share the namespace `vk`, so their merged
* symbols were both `vk_<name>`, `module_find_by_name_or_leaf("vk")` returned
* whichever loaded first, and the other's exports were reported as missing.
* A module keeps the short last-segment namespace unless another loaded
* module ends the same way; then it gets its full path, dots as underscores
* (`mine_vk`). Written `vk.` / alias prefixes are rewritten to these
* namespaces by the merger, in the scope that wrote them, so nothing
* downstream sees the collision.
*
* #2190: a module whose externs need its leaf (module_pins_leaf) keeps it
* whatever collides with it, so when a program's own `pkg.math` collides
* with std.math, pkg.math is the one that moves. #2255: two pure-Aether
* modules that happen to share a leaf, such as std.jsonpath.parser and
* contrib.jq.parser, both move, shipped or not. */
void module_assign_namespaces(void) {
if (!global_module_registry) return;
ModuleRegistry* reg = global_module_registry;
for (int i = 0; i < reg->module_count; i++) {
AetherModule* m = reg->modules[i];
if (!m || !m->name) continue;
const char* leaf = module_last_segment(m->name);
int shared = 0;
for (int j = 0; j < reg->module_count && !shared; j++) {
AetherModule* o = reg->modules[j];
if (j == i || !o || !o->name) continue;
shared = strcmp(module_last_segment(o->name), leaf) == 0;
}
int renamed = shared && !module_pins_leaf(m);
free(m->ns);
m->ns = strdup(renamed ? m->name : leaf);
if (renamed) {
for (char* p = m->ns; *p; p++) if (*p == '.') *p = '_';
}
}
}
const char* module_namespace_of(const char* module_path) {
if (!module_path) return "";
AetherModule* m = module_find(module_path);
if (m && m->ns) return m->ns;
return module_last_segment(module_path);
}
AetherModule* module_find_by_namespace(const char* ns) {
if (!global_module_registry || !ns) return NULL;
AetherModule* m = module_find(ns);
if (m) return m;
ModuleRegistry* reg = global_module_registry;
for (int i = 0; i < reg->module_count; i++) {
AetherModule* cand = reg->modules[i];
if (cand && cand->ns && strcmp(cand->ns, ns) == 0) return cand;
}
for (int i = 0; i < reg->module_count; i++) {
AetherModule* cand = reg->modules[i];
if (cand && cand->name && strcmp(module_last_segment(cand->name), ns) == 0)
return cand;
}
return NULL;
}
// Import/export handling
void module_add_export(AetherModule* module, const char* symbol) {
if (!module) return;
// Check if already exported
for (int i = 0; i < module->export_count; i++) {
if (strcmp(module->exports[i], symbol) == 0) {
return;
}
}
char** new_exports = (char**)realloc(module->exports, (module->export_count + 1) * sizeof(char*));
if (!new_exports) return;
module->exports = new_exports;
module->exports[module->export_count++] = strdup(symbol);
}
void module_add_import(AetherModule* module, const char* module_name) {
if (!module) return;
// Check if already imported
for (int i = 0; i < module->import_count; i++) {
if (strcmp(module->imports[i], module_name) == 0) {
return;
}
}
char** new_imports = (char**)realloc(module->imports, (module->import_count + 1) * sizeof(char*));
if (!new_imports) return;
module->imports = new_imports;
module->imports[module->import_count++] = strdup(module_name);
}
/* #2614: the namespaces code written in one module may qualify a name with.
* Asked once per qualified name the checker resolves inside a merged body,
* and consecutive asks come from the same function, so the last module's
* list is kept; module_registry_shutdown drops it with the modules. */
static AetherModule* g_sees_module = NULL;
static const char** g_sees_ns = NULL;
static int g_sees_count = 0;
static void module_sees_reset(void) {
free(g_sees_ns);
g_sees_ns = NULL;
g_sees_count = 0;
g_sees_module = NULL;
}
int module_sees_namespace(const char* module_name, const char* ns) {
if (!module_name || !ns) return 0;
if (!g_sees_module || strcmp(g_sees_module->name, module_name) != 0) {
AetherModule* m = module_find(module_name);
if (!m) return 0;
const char** list = malloc(sizeof(const char*) * (size_t)(m->import_count + 1));
if (!list) return 0;
int n = 0;
/* A module names itself (#1780: `audio.x` inside module `audio`). */
list[n++] = module_namespace_of(m->name);
for (int i = 0; i < m->import_count; i++) {
if (m->imports[i]) list[n++] = module_namespace_of(m->imports[i]);
}
free(g_sees_ns);
g_sees_ns = list;
g_sees_count = n;
g_sees_module = m;
}
for (int i = 0; i < g_sees_count; i++) {
if (strcmp(g_sees_ns[i], ns) == 0) return 1;
}
return 0;
}
/* #2631: the last segment a module file is imported under, which is the
* namespace a build gives it: `<dir>/module.ae` is `<dir>`, any other
* `<name>.ae` (a package's own file, `contrib/jq/parser.ae`) is `<name>`. */
const char* module_leaf_of_file(const char* path, char* buf, size_t cap) {
if (!buf || cap == 0) return "";
buf[0] = '\0';
if (!path) return buf;
const char* base = path;
for (const char* p = path; *p; p++) {
if (*p == '/' || *p == '\\') base = p + 1;
}
size_t blen = strlen(base);
if (blen < 4 || strcmp(base + blen - 3, ".ae") != 0) return buf;
if (strcmp(base, "module.ae") == 0) {
if (base == path) {
/* `ae check module.ae` inside the module's directory: the
* directory is named by the full path. */
char full[4096];
#ifdef _WIN32
if (!_fullpath(full, path, sizeof(full))) return buf;
#else
if (!realpath(path, full)) return buf;
#endif
if (strcmp(full, path) == 0) return buf;
return module_leaf_of_file(full, buf, cap);
}
const char* end = base - 1; /* the separator before module.ae */
const char* start = end;
while (start > path && start[-1] != '/' && start[-1] != '\\') start--;
size_t n = (size_t)(end - start);
if (n == 0 || n >= cap || (n == 1 && start[0] == '.') ||
(n == 2 && start[0] == '.' && start[1] == '.')) return buf;
memcpy(buf, start, n);
buf[n] = '\0';
return buf;
}
size_t n = blen - 3;
if (n >= cap) return buf;
memcpy(buf, base, n);
buf[n] = '\0';
return buf;
}
int module_is_exported(AetherModule* module, const char* symbol) {
if (!module) return 0;
for (int i = 0; i < module->export_count; i++) {
if (strcmp(module->exports[i], symbol) == 0) {
return 1;
}
}
return 0;
}
/* #2172: does `module` make `name` reachable as `<leaf>.name`? Either it
* exports `name` itself, or it exports the prefixed C-style spelling
* `<leaf>_name` that a qualified call resolves to: std.math lists
* `math_sqrt`, and `math.sqrt` / `import std.math (sqrt)` reach it through
* that convention. Export enforcement asks this, not module_is_exported. */
int module_exports_symbol(AetherModule* module, const char* name) {
if (!module || !name) return 0;
if (module_is_exported(module, name)) return 1;
if (!module->name) return 0;
char prefixed[512];
int n = snprintf(prefixed, sizeof(prefixed), "%s_%s",
module_last_segment(module->name), name);
if (n < 0 || (size_t)n >= sizeof(prefixed)) return 0;
return module_is_exported(module, prefixed);
}
/* #924 re-export resolution. A module may list, in its `exports`, a symbol
* it brought in via `import` — `module_resolve_reexport` finds the module
* that actually DEFINES such a symbol so qualified resolution can redirect
* `hub.X` to `<origin>_X`.
*
* `module` exports `symbol`; if one of its imported modules also exports
* `symbol`, that import is the origin (re-export). Resolution is transitive
* (the origin may itself re-export) and cycle-guarded via `depth`. Returns
* the origin module, or NULL when `module` is itself the definer (no
* importer exports the name) — the caller then resolves locally as before.
*
* Precision: a module that DEFINES `symbol` itself is never treated as
* re-exporting it (a local definition wins over a same-named import), so a
* name collision resolves to the local def — the redirect simply doesn't
* fire. Re-export is also opt-in: `module` must list `symbol` in `exports`. */
static ASTNode* unwrap_export(ASTNode* node); /* defined below */
static int module_defines_symbol(AetherModule* module, const char* symbol) {
if (!module || !module->ast) return 0;
for (int j = 0; j < module->ast->child_count; j++) {
ASTNode* d = unwrap_export(module->ast->children[j]);
if (!d || !d->value) continue;
if ((d->type == AST_FUNCTION_DEFINITION ||
d->type == AST_BUILDER_FUNCTION ||
d->type == AST_CONST_DECLARATION) &&
strcmp(d->value, symbol) == 0) {
return 1;
}
}
return 0;
}
static AetherModule* resolve_reexport_rec(AetherModule* module,
const char* symbol, int depth) {
if (!module || depth > 64) return NULL;
if (!module_is_exported(module, symbol)) return NULL;
/* A locally-defined export is not a re-export — resolve it in place. */
if (module_defines_symbol(module, symbol)) return NULL;
for (int i = 0; i < module->import_count; i++) {
AetherModule* imp = module_find(module->imports[i]);
if (!imp || imp == module) continue;
if (module_is_exported(imp, symbol)) {
/* Follow transitively: imp might itself be re-exporting. */
AetherModule* deeper = resolve_reexport_rec(imp, symbol, depth + 1);
return deeper ? deeper : imp;
}
}
return NULL;
}
AetherModule* module_resolve_reexport(AetherModule* module, const char* symbol) {
return resolve_reexport_rec(module, symbol, 0);
}
// Package manifest (aether.toml)
PackageManifest* package_manifest_load(const char* path) {
FILE* file = fopen(path, "r");
if (!file) {
fprintf(stderr, "Warning: Could not open package manifest: %s\n", path);
return NULL;
}
PackageManifest* manifest = (PackageManifest*)malloc(sizeof(PackageManifest));
manifest->package_name = NULL;
manifest->version = NULL;
manifest->author = NULL;
manifest->dependencies = NULL;
manifest->dependency_count = 0;
// Simple TOML parser (basic implementation)
char line[1024];
while (fgets(line, sizeof(line), file)) {
// Remove newline
line[strcspn(line, "\n")] = 0;
// Skip comments and empty lines
if (line[0] == '#' || line[0] == '\0') continue;
// Parse key = "value"
char* equals = strchr(line, '=');
if (equals) {
*equals = '\0';
char* key = line;
char* value = equals + 1;
// Trim whitespace
while (*key == ' ') key++;
while (*value == ' ') value++;
// Remove quotes
if (*value == '"') {
value++;
char* end = strchr(value, '"');
if (end) *end = '\0';
}
if (strcmp(key, "name") == 0) {
manifest->package_name = strdup(value);
} else if (strcmp(key, "version") == 0) {
manifest->version = strdup(value);
} else if (strcmp(key, "author") == 0) {
manifest->author = strdup(value);
}
}
}
fclose(file);
return manifest;
}
void package_manifest_free(PackageManifest* manifest) {
if (!manifest) return;
free(manifest->package_name);
free(manifest->version);
free(manifest->author);
for (int i = 0; i < manifest->dependency_count; i++) {
free(manifest->dependencies[i]);
}
free(manifest->dependencies);
free(manifest);
}
// Dependency Graph Implementation
DependencyGraph* dependency_graph_create(void) {
DependencyGraph* graph = malloc(sizeof(DependencyGraph));
graph->nodes = NULL;
graph->node_count = 0;
return graph;
}
void dependency_graph_free(DependencyGraph* graph) {
if (!graph) return;
for (int i = 0; i < graph->node_count; i++) {
DependencyNode* node = graph->nodes[i];
free(node->module_name);
free(node->dependencies);
free(node);
}
free(graph->nodes);
free(graph);
}
DependencyNode* dependency_graph_find_node(DependencyGraph* graph, const char* module_name) {
if (!graph) return NULL;
for (int i = 0; i < graph->node_count; i++) {
if (strcmp(graph->nodes[i]->module_name, module_name) == 0) {
return graph->nodes[i];
}
}
return NULL;
}
DependencyNode* dependency_graph_add_node(DependencyGraph* graph, const char* module_name) {
if (!graph) return NULL;
// Check if node already exists
DependencyNode* existing = dependency_graph_find_node(graph, module_name);
if (existing) return existing;
// Create new node
DependencyNode* node = malloc(sizeof(DependencyNode));
node->module_name = strdup(module_name);
node->dependencies = NULL;
node->dependency_count = 0;
node->visited = 0;
node->in_stack = 0;
// Add to graph
DependencyNode** new_nodes = realloc(graph->nodes, (graph->node_count + 1) * sizeof(DependencyNode*));
if (!new_nodes) { free(node); return NULL; }
graph->nodes = new_nodes;
graph->nodes[graph->node_count++] = node;
return node;
}
void dependency_graph_add_edge(DependencyGraph* graph, const char* from, const char* to) {
if (!graph) return;
DependencyNode* from_node = dependency_graph_add_node(graph, from);
DependencyNode* to_node = dependency_graph_add_node(graph, to);
// Check if edge already exists
for (int i = 0; i < from_node->dependency_count; i++) {
if (from_node->dependencies[i] == to_node) {
return;
}
}
// Add edge
DependencyNode** new_deps = realloc(from_node->dependencies,
(from_node->dependency_count + 1) * sizeof(DependencyNode*));
if (!new_deps) return;
from_node->dependencies = new_deps;
from_node->dependencies[from_node->dependency_count++] = to_node;
}
// DFS helper for cycle detection.
//
// #925: on finding a back edge we capture the ACTUAL cycle — the chain of
// modules from the back-edge target down to the current node — rather than
// reporting the DFS root (which is `__main__`, not a cycle member). `path`
// is the in-stack ancestor list; `path_len` its depth. On a hit we record
// the slice of `path` starting at the back-edge target into `out_cycle`
// (caller-owned, capacity `out_cap`) and return its length via `out_len`.
static int dfs_find_cycle(DependencyNode* node,
DependencyNode** path, int path_len,
DependencyNode** out_cycle, int out_cap,
int* out_len) {
if (node->in_stack) {
// Back edge: the cycle is path[start..path_len) + node, where
// path[start] == node (the module the back edge re-enters).
int start = 0;
for (int i = 0; i < path_len; i++) {
if (path[i] == node) { start = i; break; }
}
int n = 0;
for (int i = start; i < path_len && n < out_cap; i++) {
out_cycle[n++] = path[i];
}
// Close the loop by repeating the entry node (a → b → a).
if (n < out_cap) out_cycle[n++] = node;
*out_len = n;
return 1;
}
if (node->visited) {
// Already checked this node
return 0;
}
node->visited = 1;
node->in_stack = 1;
if (path_len < out_cap) path[path_len] = node;
// Visit all dependencies
for (int i = 0; i < node->dependency_count; i++) {
if (dfs_find_cycle(node->dependencies[i], path, path_len + 1,
out_cycle, out_cap, out_len)) {
return 1;
}
}
node->in_stack = 0;
return 0;
}
int dependency_graph_has_cycle(DependencyGraph* graph) {
if (!graph || graph->node_count == 0) return 0;
// Reset visited flags
for (int i = 0; i < graph->node_count; i++) {
graph->nodes[i]->visited = 0;
graph->nodes[i]->in_stack = 0;
}
int cap = graph->node_count + 1;
DependencyNode** path = malloc(sizeof(DependencyNode*) * cap);
DependencyNode** cycle = malloc(sizeof(DependencyNode*) * cap);
if (!path || !cycle) { free(path); free(cycle); return 0; }
// Run DFS from each unvisited node
int found = 0;
for (int i = 0; i < graph->node_count && !found; i++) {
if (!graph->nodes[i]->visited) {
int cycle_len = 0;
if (dfs_find_cycle(graph->nodes[i], path, 0, cycle, cap, &cycle_len)) {
found = 1;
/* #925: name the modules in the cycle, in order, instead of
* the bogus `involving module '__main__'`. Skip a leading
* `__main__` if present (it's the synthetic entry root, not
* a user module — it can't be part of a real import cycle,
* but a defensive slice keeps the message clean). */
char msg[512];
int off = snprintf(msg, sizeof(msg),
"circular import dependency: ");
for (int c = 0; c < cycle_len && off < (int)sizeof(msg) - 8; c++) {
const char* nm = cycle[c]->module_name
? cycle[c]->module_name : "?";
off += snprintf(msg + off, sizeof(msg) - off,
"%s%s", (c ? " -> " : ""), nm);
}
aether_error_simple(msg, 0, 0);
}
}
}
free(path);
free(cycle);
return found;
}
// --- Module Orchestration ---
static const char* get_user_home_dir(void) {
const char* h = getenv("HOME");
if (h && h[0]) return h;
#ifdef _WIN32
h = getenv("USERPROFILE");
if (h && h[0]) return h;
h = getenv("LOCALAPPDATA");
if (h && h[0]) return h;
#endif
return NULL;
}
static int get_exe_directory(char* buf, size_t bufsz) {
#ifdef _WIN32
DWORD n = GetModuleFileNameA(NULL, buf, (DWORD)bufsz);
if (n == 0 || n >= bufsz) return 0;
#elif defined(__APPLE__)
uint32_t sz = (uint32_t)bufsz;
if (_NSGetExecutablePath(buf, &sz) != 0) return 0;
#elif defined(__FreeBSD__)
/* #1586: /proc/self/exe is Linux-only; KERN_PROC_PATHNAME is the
* mount-nothing FreeBSD primitive (pid -1 = current process). */
int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
size_t fb_len = bufsz;
if (sysctl(mib, 4, buf, &fb_len, NULL, 0) != 0 || fb_len <= 1) {
ssize_t pn = readlink("/proc/curproc/file", buf, bufsz - 1);
if (pn <= 0) return 0;
buf[pn] = '\0';
}
#elif defined(__linux__)
ssize_t n = readlink("/proc/self/exe", buf, bufsz - 1);
if (n <= 0) return 0;
buf[n] = '\0';
#else
return 0;
#endif
char* last_sep = strrchr(buf, '/');
#ifdef _WIN32
char* last_bsep = strrchr(buf, '\\');
if (!last_sep || (last_bsep && last_bsep > last_sep)) last_sep = last_bsep;
#endif
if (last_sep) *last_sep = '\0';